├── .changes
├── config.json
└── readme.md
├── .github
└── workflows
│ ├── audit.yml
│ ├── clippy-fmt.yml
│ ├── covector-status.yml
│ ├── covector-version-or-publish.yml
│ └── test.yml
├── .gitignore
├── CHANGELOG.md
├── Cargo.lock
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── LICENSE.spdx
├── README.md
├── examples
├── egui.rs
├── iced.rs
├── tao.rs
└── winit.rs
├── renovate.json
└── src
├── error.rs
├── hotkey.rs
├── lib.rs
└── platform_impl
├── macos
├── ffi.rs
└── mod.rs
├── mod.rs
├── no-op.rs
├── windows
└── mod.rs
└── x11
└── mod.rs
/.changes/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "gitSiteUrl": "https://www.github.com/tauri-apps/global-hotkey/",
3 | "timeout": 3600000,
4 | "pkgManagers": {
5 | "rust": {
6 | "version": true,
7 | "getPublishedVersion": "cargo search ${ pkg.pkg } --limit 1 | sed -nE 's/^[^\"]*\"//; s/\".*//1p' -",
8 | "publish": [
9 | {
10 | "command": "cargo package --no-verify",
11 | "dryRunCommand": true
12 | },
13 | {
14 | "command": "echo '\nCargo Publish
\n\n```'",
15 | "dryRunCommand": true,
16 | "pipe": true
17 | },
18 | {
19 | "command": "cargo publish",
20 | "dryRunCommand": "cargo publish --dry-run",
21 | "pipe": true
22 | },
23 | {
24 | "command": "echo '```\n\n \n'",
25 | "dryRunCommand": true,
26 | "pipe": true
27 | }
28 | ],
29 | "postpublish": [
30 | "git tag ${ pkg.pkg }-v${ pkgFile.versionMajor } -f",
31 | "git tag ${ pkg.pkg }-v${ pkgFile.versionMajor }.${ pkgFile.versionMinor } -f",
32 | "git push --tags -f"
33 | ]
34 | }
35 | },
36 | "packages": {
37 | "global-hotkey": {
38 | "path": ".",
39 | "manager": "rust",
40 | "assets": [
41 | {
42 | "path": "${ pkg.path }/target/package/global-hotkey-${ pkgFile.version }.crate",
43 | "name": "${ pkg.pkg }-${ pkgFile.version }.crate"
44 | }
45 | ]
46 | }
47 | }
48 | }
--------------------------------------------------------------------------------
/.changes/readme.md:
--------------------------------------------------------------------------------
1 | # Changes
2 |
3 | ##### via https://github.com/jbolda/covector
4 |
5 | As you create PRs and make changes that require a version bump, please add a new markdown file in this folder. You do not note the version _number_, but rather the type of bump that you expect: major, minor, or patch. The filename is not important, as long as it is a `.md`, but we recommend it represents the overall change for our sanity.
6 |
7 | When you select the version bump required, you do _not_ need to consider dependencies. Only note the package with the actual change, and any packages that depend on that package will be bumped automatically in the process.
8 |
9 | Use the following format:
10 |
11 | ```md
12 | ---
13 | "global-hotkey": patch
14 | ---
15 |
16 | Change summary goes here
17 | ```
18 |
19 | Summaries do not have a specific character limit, but are text only. These summaries are used within the (future implementation of) changelogs. They will give context to the change and also point back to the original PR if more details and context are needed.
20 |
21 | Changes will be designated as a `major`, `minor` or `patch` as further described in [semver](https://semver.org/).
22 |
23 | Given a version number MAJOR.MINOR.PATCH, increment the:
24 |
25 | - MAJOR version when you make incompatible API changes,
26 | - MINOR version when you add functionality in a backwards compatible manner, and
27 | - PATCH version when you make backwards compatible bug fixes.
28 |
29 | Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format, but will be discussed prior to usage (as extra steps will be necessary in consideration of merging and publishing).
30 |
--------------------------------------------------------------------------------
/.github/workflows/audit.yml:
--------------------------------------------------------------------------------
1 | # Copyright 2022-2022 Tauri Programme within The Commons Conservancy
2 | # SPDX-License-Identifier: Apache-2.0
3 | # SPDX-License-Identifier: MIT
4 |
5 | name: audit
6 |
7 | on:
8 | workflow_dispatch:
9 | schedule:
10 | - cron: '0 0 * * *'
11 | push:
12 | branches:
13 | - dev
14 | paths:
15 | - 'Cargo.lock'
16 | - 'Cargo.toml'
17 | pull_request:
18 | paths:
19 | - 'Cargo.lock'
20 | - 'Cargo.toml'
21 |
22 | concurrency:
23 | group: ${{ github.workflow }}-${{ github.ref }}
24 | cancel-in-progress: true
25 |
26 | jobs:
27 | audit:
28 | runs-on: ubuntu-latest
29 | steps:
30 | - uses: actions/checkout@v4
31 | - uses: rustsec/audit-check@v2
32 | with:
33 | token: ${{ secrets.GITHUB_TOKEN }}
34 |
--------------------------------------------------------------------------------
/.github/workflows/clippy-fmt.yml:
--------------------------------------------------------------------------------
1 | # Copyright 2022-2022 Tauri Programme within The Commons Conservancy
2 | # SPDX-License-Identifier: Apache-2.0
3 | # SPDX-License-Identifier: MIT
4 |
5 | name: clippy & fmt
6 |
7 | on:
8 | push:
9 | branches:
10 | - dev
11 | pull_request:
12 |
13 | concurrency:
14 | group: ${{ github.workflow }}-${{ github.ref }}
15 | cancel-in-progress: true
16 |
17 | jobs:
18 | clippy:
19 | strategy:
20 | fail-fast: false
21 | matrix:
22 | platform: [ubuntu-latest, macos-latest, windows-latest]
23 |
24 | runs-on: ${{ matrix.platform }}
25 |
26 | steps:
27 | - uses: actions/checkout@v4
28 | - name: install system deps
29 | if: matrix.platform == 'ubuntu-latest'
30 | run: |
31 | sudo apt-get update
32 | sudo apt-get install -y libgtk-3-dev libxdo-dev
33 |
34 | - uses: dtolnay/rust-toolchain@stable
35 | with:
36 | components: clippy
37 |
38 | - run: cargo clippy --all-targets --all-features -- -D warnings
39 |
40 | fmt:
41 | runs-on: ubuntu-latest
42 | steps:
43 | - uses: actions/checkout@v4
44 | - uses: dtolnay/rust-toolchain@stable
45 | with:
46 | components: rustfmt
47 |
48 | - run: cargo fmt --all -- --check
49 |
--------------------------------------------------------------------------------
/.github/workflows/covector-status.yml:
--------------------------------------------------------------------------------
1 | # Copyright 2022-2022 Tauri Programme within The Commons Conservancy
2 | # SPDX-License-Identifier: Apache-2.0
3 | # SPDX-License-Identifier: MIT
4 |
5 | name: covector status
6 | on: [pull_request]
7 |
8 | jobs:
9 | covector:
10 | runs-on: ubuntu-latest
11 |
12 | steps:
13 | - uses: actions/checkout@v4
14 | - name: covector status
15 | uses: jbolda/covector/packages/action@covector-v0
16 | id: covector
17 | with:
18 | command: "status"
19 | token: ${{ secrets.GITHUB_TOKEN }}
20 | comment: true
--------------------------------------------------------------------------------
/.github/workflows/covector-version-or-publish.yml:
--------------------------------------------------------------------------------
1 | # Copyright 2022-2022 Tauri Programme within The Commons Conservancy
2 | # SPDX-License-Identifier: Apache-2.0
3 | # SPDX-License-Identifier: MIT
4 |
5 | name: covector version or publish
6 |
7 | on:
8 | push:
9 | branches:
10 | - dev
11 |
12 | jobs:
13 | version-or-publish:
14 | runs-on: ubuntu-latest
15 | timeout-minutes: 65
16 | outputs:
17 | change: ${{ steps.covector.outputs.change }}
18 | commandRan: ${{ steps.covector.outputs.commandRan }}
19 | successfulPublish: ${{ steps.covector.outputs.successfulPublish }}
20 |
21 | steps:
22 | - uses: actions/checkout@v4
23 | with:
24 | fetch-depth: 0
25 |
26 | - name: cargo login
27 | run: cargo login ${{ secrets.ORG_CRATES_IO_TOKEN }}
28 |
29 | - name: git config
30 | run: |
31 | git config --global user.name "${{ github.event.pusher.name }}"
32 | git config --global user.email "${{ github.event.pusher.email }}"
33 |
34 | - name: covector version or publish (publish when no change files present)
35 | uses: jbolda/covector/packages/action@covector-v0
36 | id: covector
37 | env:
38 | NODE_AUTH_TOKEN: ${{ secrets.ORG_NPM_TOKEN }}
39 | with:
40 | token: ${{ secrets.GITHUB_TOKEN }}
41 | command: 'version-or-publish'
42 | createRelease: true
43 | recognizeContributors: true
44 |
45 | - name: Sync Cargo.lock
46 | if: steps.covector.outputs.commandRan == 'version'
47 | run: cargo tree --depth 0
48 |
49 | - name: Create Pull Request With Versions Bumped
50 | if: steps.covector.outputs.commandRan == 'version'
51 | uses: tauri-apps/create-pull-request@v3
52 | with:
53 | token: ${{ secrets.GITHUB_TOKEN }}
54 | title: Apply Version Updates From Current Changes
55 | commit-message: 'apply version updates'
56 | labels: 'version updates'
57 | branch: 'release'
58 | body: ${{ steps.covector.outputs.change }}
59 |
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | # Copyright 2022-2022 Tauri Programme within The Commons Conservancy
2 | # SPDX-License-Identifier: Apache-2.0
3 | # SPDX-License-Identifier: MIT
4 |
5 | name: test
6 |
7 | on:
8 | push:
9 | branches:
10 | - dev
11 | pull_request:
12 |
13 | env:
14 | RUST_BACKTRACE: 1
15 |
16 | concurrency:
17 | group: ${{ github.workflow }}-${{ github.ref }}
18 | cancel-in-progress: true
19 |
20 | jobs:
21 | test:
22 | strategy:
23 | fail-fast: false
24 | matrix:
25 | platform: ["windows-latest", "macos-latest", "ubuntu-latest"]
26 |
27 | runs-on: ${{ matrix.platform }}
28 |
29 | steps:
30 | - uses: actions/checkout@v4
31 |
32 | - name: install system deps
33 | if: matrix.platform == 'ubuntu-latest'
34 | run: |
35 | sudo apt-get update
36 | sudo apt-get install -y libgtk-3-dev libxdo-dev
37 |
38 | - uses: dtolnay/rust-toolchain@1.71
39 | - run: cargo build
40 |
41 | - uses: dtolnay/rust-toolchain@stable
42 | - run: cargo test --all-features
43 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 | /.vscode
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | ## \[0.7.0]
4 |
5 | - [`77dbe4e`](https://www.github.com/tauri-apps/global-hotkey/commit/77dbe4ebe5911f9ee41f3264ecb11295d7e6abe7) ([#150](https://www.github.com/tauri-apps/global-hotkey/pull/150) by [@Exidex](https://www.github.com/tauri-apps/global-hotkey/../../Exidex)) Use `x11rb` crate instead of `x11-dl` for linux (x11) backend.
6 |
7 | ## \[0.6.4]
8 |
9 | - [`a25c485`](https://www.github.com/tauri-apps/global-hotkey/commit/a25c485b6fce488799510c7f70563db3ebcdb72f) ([#120](https://www.github.com/tauri-apps/global-hotkey/pull/120) by [@FabianLars](https://www.github.com/tauri-apps/global-hotkey/../../FabianLars)) Update `objc2` to `0.6`. This raises the MSRV to 1.71 which is now also set in `rust-version`.
10 |
11 | ## \[0.6.3]
12 |
13 | - [`ddf5515`](https://www.github.com/tauri-apps/global-hotkey/commit/ddf5515712f85e887e715bda7da40becc9159ac9) ([#112](https://www.github.com/tauri-apps/global-hotkey/pull/112) by [@amrbashir](https://www.github.com/tauri-apps/global-hotkey/../../amrbashir)) Support using `Pause` or `PauseBreak` key on Windows and Linux.
14 |
15 | ## \[0.6.2]
16 |
17 | - [`2c7397b`](https://www.github.com/tauri-apps/global-hotkey/commit/2c7397b27ccb2efd4589bb364e611a80635413c8) ([#106](https://www.github.com/tauri-apps/global-hotkey/pull/106) by [@FabianLars](https://www.github.com/tauri-apps/global-hotkey/../../FabianLars)) Fixed an issue causing compilation to fail for 32-bit targets.
18 |
19 | ## \[0.6.1]
20 |
21 | - [`7d15d09`](https://www.github.com/tauri-apps/global-hotkey/commit/7d15d09e518130bf0a1b44e3512cb6f5ed361164) ([#99](https://www.github.com/tauri-apps/global-hotkey/pull/99) by [@madsmtm](https://www.github.com/tauri-apps/global-hotkey/../../madsmtm)) Use `objc2` internally, leading to slightly better memory- and type-safety.
22 |
23 | ## \[0.6.0]
24 |
25 | - [`8b13a61`](https://www.github.com/tauri-apps/global-hotkey/commit/8b13a6159d776a6a282ad7ca5c4b896cc91e325a) Removed `Sync` and `Send` implementation for `GlobalHotKeyManager`
26 | - [`8b13a61`](https://www.github.com/tauri-apps/global-hotkey/commit/8b13a6159d776a6a282ad7ca5c4b896cc91e325a) Update `windows-sys` crate to `0.59`
27 |
28 | ## \[0.5.5]
29 |
30 | - [`c750004`](https://www.github.com/tauri-apps/global-hotkey/commit/c7500047fb62154cf861878efb334c61bd98988a) ([#92](https://www.github.com/tauri-apps/global-hotkey/pull/92) by [@IAmJSD](https://www.github.com/tauri-apps/global-hotkey/../../IAmJSD)) Fix a panic when parsing `HotKey` from a string and return an error instead, if the hotkey string consists of only modifiers and doesn't contain a key.
31 |
32 | ## \[0.5.4]
33 |
34 | - [`e9d263c`](https://www.github.com/tauri-apps/global-hotkey/commit/e9d263c2d9b9535af8d64c7b8950308d16b57b94) Fix parsing of `MEDIATRACKPREV` and `MEDIATRACKPREVIOUS` keys.
35 |
36 | ## \[0.5.3]
37 |
38 | - [`a468ede`](https://www.github.com/tauri-apps/global-hotkey/commit/a468ede66aa2102f146bebd71ad618eff550997a)([#75](https://www.github.com/tauri-apps/global-hotkey/pull/75)) Add `serde` feature flag and implement `Deserialize` and `Serialize` for `GlobalHotKeyEvent`, `HotKeyState` and `HotKey` types.
39 | - [`a468ede`](https://www.github.com/tauri-apps/global-hotkey/commit/a468ede66aa2102f146bebd71ad618eff550997a)([#75](https://www.github.com/tauri-apps/global-hotkey/pull/75)) Add `HotKey::into_string` method and implement `Display` for `HotKey`.
40 |
41 | ## \[0.5.2]
42 |
43 | - [`c530be0`](https://www.github.com/tauri-apps/global-hotkey/commit/c530be0dbf939d2dd8d05eacc2071f493769a834)([#71](https://www.github.com/tauri-apps/global-hotkey/pull/71)) Support registering media play/pause/stop/next/prev keys.
44 | - [`24f41b0`](https://www.github.com/tauri-apps/global-hotkey/commit/24f41b0fd9f54e822e6397bc95d9e717c67aab72)([#73](https://www.github.com/tauri-apps/global-hotkey/pull/73)) Always service all pending events to avoid a queue of events from building up.
45 |
46 | ## \[0.5.1]
47 |
48 | - [`89199d9`](https://www.github.com/tauri-apps/global-hotkey/commit/89199d930db3a71f1e19a29d6c1d6ff2e8cffb11)([#64](https://www.github.com/tauri-apps/global-hotkey/pull/64)) Add no-op implementations for unsupported targets.
49 |
50 | ## \[0.5.0]
51 |
52 | - [`7d99bd7`](https://www.github.com/tauri-apps/global-hotkey/commit/7d99bd78a383e11ae6bb8fce0525afcc9e427c8f)([#61](https://www.github.com/tauri-apps/global-hotkey/pull/61)) Refactored the errors when parsing accelerator from string:
53 |
54 | - Added `HotKeyParseError` error enum.
55 | - Removed `Error::UnrecognizedHotKeyCode` enum variant
56 | - Removed `Error::EmptyHotKeyToken` enum variant
57 | - Removed `Error::UnexpectedHotKeyFormat` enum variant
58 | - Changed `Error::HotKeyParseError` inner value from `String` to the newly added `HotKeyParseError` enum.
59 | - [`7d99bd7`](https://www.github.com/tauri-apps/global-hotkey/commit/7d99bd78a383e11ae6bb8fce0525afcc9e427c8f)([#61](https://www.github.com/tauri-apps/global-hotkey/pull/61)) Avoid panicing when parsing an invalid `HotKey` from a string such as `SHIFT+SHIFT` and return an error instead.
60 |
61 | ## \[0.4.2]
62 |
63 | - [`b538534`](https://www.github.com/tauri-apps/global-hotkey/commit/b538534f9181ccd38e76d93368378fc6ed3a3a08) Changed window class name used interally so it wouldn't conflict with `tray-icon` crate implementation.
64 |
65 | ## \[0.4.1]
66 |
67 | - [`1f9be3e`](https://www.github.com/tauri-apps/global-hotkey/commit/1f9be3e0631817a9c96a4d98289158286cb689e8)([#47](https://www.github.com/tauri-apps/global-hotkey/pull/47)) Add support for `Code::Backquote` on Linux.
68 | - [`1f9be3e`](https://www.github.com/tauri-apps/global-hotkey/commit/1f9be3e0631817a9c96a4d98289158286cb689e8)([#47](https://www.github.com/tauri-apps/global-hotkey/pull/47)) On Linux, fix hotkey `press/release` events order and sometimes missing `release` event when the modifiers have been already released before the key itself has been released.
69 | - [`1f9be3e`](https://www.github.com/tauri-apps/global-hotkey/commit/1f9be3e0631817a9c96a4d98289158286cb689e8)([#47](https://www.github.com/tauri-apps/global-hotkey/pull/47)) On Linux, improve the performance of `GlobalHotKeyManager::register_all` and `GlobalHotKeyManager::unregister_all` to 2711x faster.
70 |
71 | ## \[0.4.0]
72 |
73 | - [`53961a1`](https://www.github.com/tauri-apps/global-hotkey/commit/53961a1ade623bb97ce96db71fbe1193ffc9d6a7)([#35](https://www.github.com/tauri-apps/global-hotkey/pull/35)) Support Pressed and Released stats of the hotkey, you can check the newly added `state` field or using the `state()` method on the `GlobalHotKeyEvent`.
74 |
75 | ## \[0.3.0]
76 |
77 | - [`fa47029`](https://www.github.com/tauri-apps/global-hotkey/commit/fa47029435ed953b07f5809d9e521bcd2c24bf54) Update `keyboard-types` to `0.7`
78 |
79 | ## \[0.2.4]
80 |
81 | - [`b0975f9`](https://www.github.com/tauri-apps/global-hotkey/commit/b0975f9983aa023df3cd72bbd8d3158165e9f6eb) Export `CMD_OR_CTRL` const.
82 | - [`dc9e619`](https://www.github.com/tauri-apps/global-hotkey/commit/dc9e6197362164ef6b8aae90df41a6a2b459f5fb) Add `GlobalHotKeyEvent::id` method.
83 | - [`b960609`](https://www.github.com/tauri-apps/global-hotkey/commit/b96060952daf8959939f07c968b8bd58e33f4abd) Impl `TryFrom<&str>` and `TryFrom` for `HotKey`.
84 |
85 | ## \[0.2.3]
86 |
87 | - [`589ecd9`](https://www.github.com/tauri-apps/global-hotkey/commit/589ecd9afd79aab93b25b357b4c70afdf69f9f6d)([#25](https://www.github.com/tauri-apps/global-hotkey/pull/25)) Fix `GlobalHotKeyManager::unregister_all` actually registering the hotkeys instead of unregistering.
88 |
89 | ## \[0.2.2]
90 |
91 | - [`bbd3ffb`](https://www.github.com/tauri-apps/global-hotkey/commit/bbd3ffbea2a76eaae7cd344a019a942456f94a26)([#23](https://www.github.com/tauri-apps/global-hotkey/pull/23)) Generate a hash-based id for hotkeys. Previously each hotkey had a unique id which is not necessary given that only one hotkey with the same combination can be used at a time.
92 |
93 | ## \[0.2.1]
94 |
95 | - [`b503530`](https://www.github.com/tauri-apps/global-hotkey/commit/b503530eb49a7fe8da3e49080e3f72f82a70b7a2)([#20](https://www.github.com/tauri-apps/global-hotkey/pull/20)) Make `GlobalHotKeyManager` Send + Sync on macOS.
96 |
97 | ## \[0.2.0]
98 |
99 | - Support more variants for `HotKey::from_str` and support case-insensitive htokey.
100 | - [25cbda5](https://www.github.com/tauri-apps/global-hotkey/commit/25cbda58c503b8230af00c6192e87d5ce1fc2742) feat: add more variants and case-insensitive hotkey parsing ([#19](https://www.github.com/tauri-apps/global-hotkey/pull/19)) on 2023-04-19
101 |
102 | ## \[0.1.2]
103 |
104 | - On Windows, fix registering htokeys failing all the time.
105 | - [65d1f6d](https://www.github.com/tauri-apps/global-hotkey/commit/65d1f6dffd54bafe46d1ae776639b5dd10e78b96) fix(window): correctly check error result on 2023-02-13
106 | - Fix crash on wayland, and emit a warning instead.
107 | - [4c08d82](https://www.github.com/tauri-apps/global-hotkey/commit/4c08d82fa4a20c82988b49f718688ec29de8a781) fix: emit error on non x11 window systems on 2023-02-13
108 |
109 | ## \[0.1.1]
110 |
111 | - Update docs
112 | - [6409e5d](https://www.github.com/tauri-apps/global-hotkey/commit/6409e5dd351e1cae808c0042f4507e9afad70a05) docs: update docs on 2023-02-08
113 |
114 | ## \[0.1.0]
115 |
116 | - Initial Release.
117 | - [72873f6](https://www.github.com/tauri-apps/global-hotkey/commit/72873f629b47565888d5f2a4264476c9974686b6) chore: add initial release change file on 2023-01-16
118 | - [d0f1d9c](https://www.github.com/tauri-apps/global-hotkey/commit/d0f1d9c58eba60015f658f7a742c200c2d1bd55e) chore: adjust change file on 2023-01-16
119 |
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "global-hotkey"
3 | version = "0.7.0"
4 | description = "Global hotkeys for Desktop Applications"
5 | edition = "2021"
6 | keywords = ["windowing", "global", "global-hotkey", "hotkey"]
7 | license = "Apache-2.0 OR MIT"
8 | readme = "README.md"
9 | repository = "https://github.com/amrbashir/global-hotkey"
10 | documentation = "https://docs.rs/global-hotkey"
11 | categories = ["gui"]
12 | rust-version = "1.71"
13 |
14 | [features]
15 | serde = ["dep:serde"]
16 | tracing = ["dep:tracing"]
17 |
18 | [dependencies]
19 | crossbeam-channel = "0.5"
20 | keyboard-types = "0.7"
21 | once_cell = "1"
22 | thiserror = "2"
23 | serde = { version = "1", optional = true, features = ["derive"] }
24 | tracing = { version = "0.1", optional = true }
25 |
26 | [target.'cfg(target_os = "macos")'.dependencies]
27 | objc2 = "0.6.0"
28 | objc2-app-kit = { version = "0.3.0", default-features = false, features = [
29 | "std",
30 | "NSEvent",
31 | ] }
32 |
33 | [target.'cfg(target_os = "windows")'.dependencies.windows-sys]
34 | version = "0.59"
35 | features = [
36 | "Win32_UI_WindowsAndMessaging",
37 | "Win32_Foundation",
38 | "Win32_System_SystemServices",
39 | "Win32_Graphics_Gdi",
40 | "Win32_UI_Shell",
41 | "Win32_UI_Input_KeyboardAndMouse",
42 | ]
43 |
44 | [target.'cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))'.dependencies]
45 | x11rb = { version = "0.13.1", features = ["xkb"] }
46 | xkeysym = "0.2.1"
47 |
48 | [dev-dependencies]
49 | winit = "0.30"
50 | tao = "0.30"
51 | eframe = "0.27"
52 | iced = "0.13.1"
53 | async-std = "1.12.0"
54 |
--------------------------------------------------------------------------------
/LICENSE-APACHE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/LICENSE-MIT:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2022-2022 Tauri Programme within The Commons Conservancy
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/LICENSE.spdx:
--------------------------------------------------------------------------------
1 | SPDXVersion: SPDX-2.1
2 | DataLicense: CC0-1.0
3 | PackageName: global-hotkey
4 | DataFormat: SPDXRef-1
5 | PackageSupplier: Organization: The Tauri Programme in the Commons Conservancy
6 | PackageHomePage: https://tauri.app
7 | PackageLicenseDeclared: Apache-2.0
8 | PackageLicenseDeclared: MIT
9 | PackageCopyrightText: 2020-2022, The Tauri Programme in the Commons Conservancy
10 | PackageSummary: Menu Utilities for Desktop Applications.
11 |
12 | PackageComment: The package includes the following libraries; see
13 | Relationship information.
14 |
15 | Created: 2022-12-05T09:00:00Z
16 | PackageDownloadLocation: git://github.com/tauri-apps/global-hotkey
17 | PackageDownloadLocation: git+https://github.com/tauri-apps/global-hotkey.git
18 | PackageDownloadLocation: git+ssh://github.com/tauri-apps/global-hotkey.git
19 | Creator: Person: Daniel Thompson-Yvetot
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | global_hotkey lets you register Global HotKeys for Desktop Applications.
2 |
3 | ## Platforms-supported:
4 |
5 | - Windows
6 | - macOS
7 | - Linux (X11 Only)
8 |
9 | ## Platform-specific notes:
10 |
11 | - On Windows a win32 event loop must be running on the thread. It doesn't need to be the main thread but you have to create the global hotkey manager on the same thread as the event loop.
12 | - On macOS, an event loop must be running on the main thread so you also need to create the global hotkey manager on the main thread.
13 |
14 | ## Example
15 |
16 | ```rs
17 | use global_hotkey::{GlobalHotKeyManager, hotkey::{HotKey, Modifiers, Code}};
18 |
19 | // initialize the hotkeys manager
20 | let manager = GlobalHotKeyManager::new().unwrap();
21 |
22 | // construct the hotkey
23 | let hotkey = HotKey::new(Some(Modifiers::SHIFT), Code::KeyD);
24 |
25 | // register it
26 | manager.register(hotkey);
27 | ```
28 |
29 | ## Processing global hotkey events
30 |
31 | You can also listen for the menu events using `GlobalHotKeyEvent::receiver` to get events for the hotkey pressed events.
32 |
33 | ```rs
34 | use global_hotkey::GlobalHotKeyEvent;
35 |
36 | if let Ok(event) = GlobalHotKeyEvent::receiver().try_recv() {
37 | println!("{:?}", event);
38 | }
39 | ```
40 |
41 | ## License
42 |
43 | Apache-2.0/MIT
44 |
--------------------------------------------------------------------------------
/examples/egui.rs:
--------------------------------------------------------------------------------
1 | #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] // hide console window on Windows in release
2 |
3 | use std::time::Duration;
4 |
5 | use eframe::egui;
6 | use global_hotkey::{hotkey::HotKey, GlobalHotKeyEvent, GlobalHotKeyManager};
7 | use keyboard_types::{Code, Modifiers};
8 |
9 | fn main() -> Result<(), eframe::Error> {
10 | let manager = GlobalHotKeyManager::new().unwrap();
11 | let hotkey = HotKey::new(Some(Modifiers::SHIFT), Code::KeyD);
12 |
13 | manager.register(hotkey).unwrap();
14 | let receiver = GlobalHotKeyEvent::receiver();
15 | std::thread::spawn(|| loop {
16 | if let Ok(event) = receiver.try_recv() {
17 | println!("tray event: {event:?}");
18 | }
19 | std::thread::sleep(Duration::from_millis(100));
20 | });
21 |
22 | eframe::run_native(
23 | "My egui App",
24 | eframe::NativeOptions::default(),
25 | Box::new(|_cc| Box::::default()),
26 | )
27 | }
28 |
29 | struct MyApp {
30 | name: String,
31 | age: u32,
32 | }
33 |
34 | impl Default for MyApp {
35 | fn default() -> Self {
36 | Self {
37 | name: "Arthur".to_owned(),
38 | age: 42,
39 | }
40 | }
41 | }
42 |
43 | impl eframe::App for MyApp {
44 | fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
45 | egui::CentralPanel::default().show(ctx, |ui| {
46 | ui.heading("My egui Application");
47 | ui.horizontal(|ui| {
48 | let name_label = ui.label("Your name: ");
49 | ui.text_edit_singleline(&mut self.name)
50 | .labelled_by(name_label.id);
51 | });
52 | ui.add(egui::Slider::new(&mut self.age, 0..=120).text("age"));
53 | if ui.button("Click each year").clicked() {
54 | self.age += 1;
55 | }
56 | ui.label(format!("Hello '{}', age {}", self.name, self.age));
57 | });
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/examples/iced.rs:
--------------------------------------------------------------------------------
1 | use global_hotkey::hotkey::{Code, HotKey, Modifiers};
2 | use global_hotkey::{GlobalHotKeyEvent, GlobalHotKeyManager};
3 |
4 | use iced::futures::{SinkExt, Stream};
5 | use iced::stream::channel;
6 | use iced::widget::{container, row, text};
7 | use iced::{application, Element, Subscription, Task, Theme};
8 |
9 | fn main() -> iced::Result {
10 | application("Iced Example!", update, view)
11 | .subscription(subscription)
12 | .theme(|_| Theme::Dark)
13 | .run_with(new)
14 | }
15 |
16 | struct Example {
17 | last_pressed: String,
18 | // store the global manager otherwise it will be dropped and events will not be emitted
19 | _manager: GlobalHotKeyManager,
20 | }
21 |
22 | #[derive(Debug, Clone)]
23 | enum ProgramCommands {
24 | // message received when the subscription calls back to the main gui thread
25 | Received(String),
26 | }
27 |
28 | fn new() -> (Example, Task) {
29 | let manager = GlobalHotKeyManager::new().unwrap();
30 | let hotkey_1 = HotKey::new(Some(Modifiers::CONTROL), Code::ArrowRight);
31 | let hotkey_2 = HotKey::new(None, Code::ArrowUp);
32 |
33 | manager.register(hotkey_1).unwrap();
34 | manager.register(hotkey_2).unwrap();
35 |
36 | (
37 | Example {
38 | last_pressed: "".to_string(),
39 | _manager: manager,
40 | },
41 | Task::none(),
42 | )
43 | }
44 |
45 | fn update(state: &mut Example, msg: ProgramCommands) -> Task {
46 | match msg {
47 | ProgramCommands::Received(code) => {
48 | // update the text widget
49 | state.last_pressed = code.to_string();
50 |
51 | Task::none()
52 | }
53 | }
54 | }
55 |
56 | fn view(state: &Example) -> Element<'_, ProgramCommands> {
57 | container(row![
58 | text("You pressed: "),
59 | text(state.last_pressed.clone())
60 | ])
61 | .into()
62 | }
63 |
64 | fn subscription(_state: &Example) -> Subscription {
65 | Subscription::run(hotkey_sub)
66 | }
67 |
68 | fn hotkey_sub() -> impl Stream- {
69 | channel(32, |mut sender| async move {
70 | let receiver = GlobalHotKeyEvent::receiver();
71 | // poll for global hotkey events every 50ms
72 | loop {
73 | if let Ok(event) = receiver.try_recv() {
74 | sender
75 | .send(ProgramCommands::Received(format!("{:?}", event)))
76 | .await
77 | .unwrap();
78 | }
79 | async_std::task::sleep(std::time::Duration::from_millis(50)).await;
80 | }
81 | })
82 | }
83 |
--------------------------------------------------------------------------------
/examples/tao.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2022-2022 Tauri Programme within The Commons Conservancy
2 | // SPDX-License-Identifier: Apache-2.0
3 | // SPDX-License-Identifier: MIT
4 |
5 | use global_hotkey::{
6 | hotkey::{Code, HotKey, Modifiers},
7 | GlobalHotKeyEvent, GlobalHotKeyManager, HotKeyState,
8 | };
9 | use tao::event_loop::{ControlFlow, EventLoopBuilder};
10 |
11 | fn main() {
12 | let event_loop = EventLoopBuilder::new().build();
13 |
14 | let hotkeys_manager = GlobalHotKeyManager::new().unwrap();
15 |
16 | let hotkey = HotKey::new(Some(Modifiers::SHIFT), Code::KeyD);
17 | let hotkey2 = HotKey::new(Some(Modifiers::SHIFT | Modifiers::ALT), Code::KeyD);
18 | let hotkey3 = HotKey::new(None, Code::KeyF);
19 | let hotkey4 = {
20 | #[cfg(target_os = "macos")]
21 | {
22 | HotKey::new(
23 | Some(Modifiers::SHIFT | Modifiers::ALT),
24 | Code::MediaPlayPause,
25 | )
26 | }
27 | #[cfg(not(target_os = "macos"))]
28 | {
29 | HotKey::new(Some(Modifiers::SHIFT | Modifiers::ALT), Code::MediaPlay)
30 | }
31 | };
32 |
33 | hotkeys_manager.register(hotkey).unwrap();
34 | hotkeys_manager.register(hotkey2).unwrap();
35 | hotkeys_manager.register(hotkey3).unwrap();
36 | hotkeys_manager.register(hotkey4).unwrap();
37 |
38 | let global_hotkey_channel = GlobalHotKeyEvent::receiver();
39 |
40 | event_loop.run(move |_event, _, control_flow| {
41 | *control_flow = ControlFlow::Poll;
42 |
43 | if let Ok(event) = global_hotkey_channel.try_recv() {
44 | println!("{event:?}");
45 |
46 | if hotkey2.id() == event.id && event.state == HotKeyState::Released {
47 | hotkeys_manager.unregister(hotkey2).unwrap();
48 | }
49 | }
50 | })
51 | }
52 |
--------------------------------------------------------------------------------
/examples/winit.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2022-2022 Tauri Programme within The Commons Conservancy
2 | // SPDX-License-Identifier: Apache-2.0
3 | // SPDX-License-Identifier: MIT
4 |
5 | use global_hotkey::{
6 | hotkey::{Code, HotKey, Modifiers},
7 | GlobalHotKeyEvent, GlobalHotKeyManager, HotKeyState,
8 | };
9 | use winit::{
10 | application::ApplicationHandler,
11 | event::WindowEvent,
12 | event_loop::{ActiveEventLoop, EventLoop},
13 | window::WindowId,
14 | };
15 |
16 | fn main() {
17 | let hotkeys_manager = GlobalHotKeyManager::new().unwrap();
18 |
19 | let hotkey = HotKey::new(Some(Modifiers::SHIFT), Code::KeyD);
20 | let hotkey2 = HotKey::new(Some(Modifiers::SHIFT | Modifiers::ALT), Code::KeyD);
21 | let hotkey3 = HotKey::new(None, Code::KeyF);
22 |
23 | hotkeys_manager.register(hotkey).unwrap();
24 | hotkeys_manager.register(hotkey2).unwrap();
25 | hotkeys_manager.register(hotkey3).unwrap();
26 |
27 | let event_loop = EventLoop::::with_user_event().build().unwrap();
28 | let proxy = event_loop.create_proxy();
29 |
30 | GlobalHotKeyEvent::set_event_handler(Some(move |event| {
31 | let _ = proxy.send_event(AppEvent::HotKey(event));
32 | }));
33 |
34 | let mut app = App {
35 | hotkeys_manager,
36 | hotkey2,
37 | };
38 |
39 | event_loop.run_app(&mut app).unwrap()
40 | }
41 |
42 | #[derive(Debug)]
43 | enum AppEvent {
44 | HotKey(GlobalHotKeyEvent),
45 | }
46 |
47 | struct App {
48 | hotkeys_manager: GlobalHotKeyManager,
49 | hotkey2: HotKey,
50 | }
51 |
52 | impl ApplicationHandler for App {
53 | fn resumed(&mut self, _event_loop: &ActiveEventLoop) {}
54 |
55 | fn window_event(
56 | &mut self,
57 | _event_loop: &ActiveEventLoop,
58 | _window_id: WindowId,
59 | _event: WindowEvent,
60 | ) {
61 | }
62 |
63 | fn user_event(&mut self, _event_loop: &ActiveEventLoop, event: AppEvent) {
64 | match event {
65 | AppEvent::HotKey(event) => {
66 | println!("{event:?}");
67 |
68 | if self.hotkey2.id() == event.id && event.state == HotKeyState::Released {
69 | self.hotkeys_manager.unregister(self.hotkey2).unwrap();
70 | }
71 | }
72 | }
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/renovate.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json",
3 | "extends": ["config:base", ":disableDependencyDashboard"]
4 | }
--------------------------------------------------------------------------------
/src/error.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2022-2022 Tauri Programme within The Commons Conservancy
2 | // SPDX-License-Identifier: Apache-2.0
3 | // SPDX-License-Identifier: MIT
4 |
5 | use thiserror::Error;
6 |
7 | use crate::hotkey::HotKey;
8 |
9 | /// Errors returned by tray-icon.
10 | #[non_exhaustive]
11 | #[derive(Error, Debug)]
12 | pub enum Error {
13 | #[error(transparent)]
14 | OsError(#[from] std::io::Error),
15 | #[error("{0}")]
16 | HotKeyParseError(String),
17 | #[error("Couldn't recognize \"{0}\" as a valid HotKey Code, if you feel like it should be, please report this to https://github.com/tauri-apps/global-hotkey")]
18 | UnrecognizedHotKeyCode(String),
19 | #[error("Unexpected empty token while parsing hotkey: \"{0}\"")]
20 | EmptyHotKeyToken(String),
21 | #[error("Unexpected hotkey string format: \"{0}\", a hotkey should have the modifiers first and only contain one main key")]
22 | UnexpectedHotKeyFormat(String),
23 | #[error("Unable to register hotkey: {0}")]
24 | FailedToRegister(String),
25 | #[error("Failed to unregister hotkey: {0:?}")]
26 | FailedToUnRegister(HotKey),
27 | #[error("HotKey already registered: {0:?}")]
28 | AlreadyRegistered(HotKey),
29 | #[error("Failed to watch media key event")]
30 | FailedToWatchMediaKeyEvent,
31 | }
32 |
33 | /// Convenient type alias of Result type for tray-icon.
34 | pub type Result = std::result::Result;
35 |
--------------------------------------------------------------------------------
/src/hotkey.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2022-2022 Tauri Programme within The Commons Conservancy
2 | // SPDX-License-Identifier: Apache-2.0
3 | // SPDX-License-Identifier: MIT
4 |
5 | //! HotKeys describe keyboard global shortcuts.
6 | //!
7 | //! [`HotKey`s](crate::hotkey::HotKey) are used to define a keyboard shortcut consisting
8 | //! of an optional combination of modifier keys (provided by [`Modifiers`](crate::hotkey::Modifiers)) and
9 | //! one key ([`Code`](crate::hotkey::Code)).
10 | //!
11 | //! # Examples
12 | //! They can be created directly
13 | //! ```no_run
14 | //! # use global_hotkey::hotkey::{HotKey, Modifiers, Code};
15 | //! let hotkey = HotKey::new(Some(Modifiers::SHIFT), Code::KeyQ);
16 | //! let hotkey_without_mods = HotKey::new(None, Code::KeyQ);
17 | //! ```
18 | //! or from `&str`, note that all modifiers
19 | //! have to be listed before the non-modifier key, `shift+alt+KeyQ` is legal,
20 | //! whereas `shift+q+alt` is not.
21 | //! ```no_run
22 | //! # use global_hotkey::hotkey::{HotKey};
23 | //! let hotkey: HotKey = "shift+alt+KeyQ".parse().unwrap();
24 | //! # // This assert exists to ensure a test breaks once the
25 | //! # // statement above about ordering is no longer valid.
26 | //! # assert!("shift+KeyQ+alt".parse::().is_err());
27 | //! ```
28 | //!
29 |
30 | pub use keyboard_types::{Code, Modifiers};
31 | use std::{borrow::Borrow, fmt::Display, hash::Hash, str::FromStr};
32 |
33 | #[cfg(target_os = "macos")]
34 | pub const CMD_OR_CTRL: Modifiers = Modifiers::SUPER;
35 | #[cfg(not(target_os = "macos"))]
36 | pub const CMD_OR_CTRL: Modifiers = Modifiers::CONTROL;
37 |
38 | #[derive(thiserror::Error, Debug)]
39 | pub enum HotKeyParseError {
40 | #[error("Couldn't recognize \"{0}\" as a valid key for hotkey, if you feel like it should be, please report this to https://github.com/tauri-apps/muda")]
41 | UnsupportedKey(String),
42 | #[error("Found empty token while parsing hotkey: {0}")]
43 | EmptyToken(String),
44 | #[error("Invalid hotkey format: \"{0}\", an hotkey should have the modifiers first and only one main key, for example: \"Shift + Alt + K\"")]
45 | InvalidFormat(String),
46 | }
47 |
48 | /// A keyboard shortcut that consists of an optional combination
49 | /// of modifier keys (provided by [`Modifiers`](crate::hotkey::Modifiers)) and
50 | /// one key ([`Code`](crate::hotkey::Code)).
51 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
52 | pub struct HotKey {
53 | /// The hotkey modifiers.
54 | pub mods: Modifiers,
55 | /// The hotkey key.
56 | pub key: Code,
57 | /// The hotkey id.
58 | pub id: u32,
59 | }
60 |
61 | #[cfg(feature = "serde")]
62 | impl<'de> serde::Deserialize<'de> for HotKey {
63 | fn deserialize(deserializer: D) -> Result
64 | where
65 | D: serde::Deserializer<'de>,
66 | {
67 | let hotkey = String::deserialize(deserializer)?;
68 | hotkey
69 | .parse()
70 | .map_err(|e: HotKeyParseError| serde::de::Error::custom(e.to_string()))
71 | }
72 | }
73 |
74 | #[cfg(feature = "serde")]
75 | impl serde::Serialize for HotKey {
76 | fn serialize
(&self, serializer: S) -> Result
77 | where
78 | S: serde::Serializer,
79 | {
80 | self.to_string().serialize(serializer)
81 | }
82 | }
83 |
84 | impl HotKey {
85 | /// Creates a new hotkey to define keyboard shortcuts throughout your application.
86 | /// Only [`Modifiers::ALT`], [`Modifiers::SHIFT`], [`Modifiers::CONTROL`], and [`Modifiers::SUPER`]
87 | pub fn new(mods: Option, key: Code) -> Self {
88 | let mut mods = mods.unwrap_or_else(Modifiers::empty);
89 | if mods.contains(Modifiers::META) {
90 | mods.remove(Modifiers::META);
91 | mods.insert(Modifiers::SUPER);
92 | }
93 |
94 | Self {
95 | mods,
96 | key,
97 | id: (mods.bits() << 16) | key as u32,
98 | }
99 | }
100 |
101 | /// Returns the id associated with this hotKey
102 | /// which is a hash of the string represention of modifiers and key within this hotKey.
103 | pub fn id(&self) -> u32 {
104 | self.id
105 | }
106 |
107 | /// Returns `true` if this [`Code`] and [`Modifiers`] matches this hotkey.
108 | pub fn matches(&self, modifiers: impl Borrow, key: impl Borrow) -> bool {
109 | // Should be a const but const bit_or doesn't work here.
110 | let base_mods = Modifiers::SHIFT | Modifiers::CONTROL | Modifiers::ALT | Modifiers::SUPER;
111 | let modifiers = modifiers.borrow();
112 | let key = key.borrow();
113 | self.mods == *modifiers & base_mods && self.key == *key
114 | }
115 |
116 | /// Converts this hotkey into a string.
117 | pub fn into_string(self) -> String {
118 | let mut hotkey = String::new();
119 | if self.mods.contains(Modifiers::SHIFT) {
120 | hotkey.push_str("shift+")
121 | }
122 | if self.mods.contains(Modifiers::CONTROL) {
123 | hotkey.push_str("control+")
124 | }
125 | if self.mods.contains(Modifiers::ALT) {
126 | hotkey.push_str("alt+")
127 | }
128 | if self.mods.contains(Modifiers::SUPER) {
129 | hotkey.push_str("super+")
130 | }
131 | hotkey.push_str(&self.key.to_string());
132 | hotkey
133 | }
134 | }
135 |
136 | impl Display for HotKey {
137 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138 | write!(f, "{}", self.into_string())
139 | }
140 | }
141 |
142 | // HotKey::from_str is available to be backward
143 | // compatible with tauri and it also open the option
144 | // to generate hotkey from string
145 | impl FromStr for HotKey {
146 | type Err = HotKeyParseError;
147 | fn from_str(hotkey_string: &str) -> Result {
148 | parse_hotkey(hotkey_string)
149 | }
150 | }
151 |
152 | impl TryFrom<&str> for HotKey {
153 | type Error = HotKeyParseError;
154 |
155 | fn try_from(value: &str) -> Result {
156 | parse_hotkey(value)
157 | }
158 | }
159 |
160 | impl TryFrom for HotKey {
161 | type Error = HotKeyParseError;
162 |
163 | fn try_from(value: String) -> Result {
164 | parse_hotkey(&value)
165 | }
166 | }
167 |
168 | fn parse_hotkey(hotkey: &str) -> Result {
169 | let tokens = hotkey.split('+').collect::>();
170 |
171 | let mut mods = Modifiers::empty();
172 | let mut key = None;
173 |
174 | match tokens.len() {
175 | // single key hotkey
176 | 1 => {
177 | key = Some(parse_key(tokens[0])?);
178 | }
179 | // modifiers and key comobo hotkey
180 | _ => {
181 | for raw in tokens {
182 | let token = raw.trim();
183 |
184 | if token.is_empty() {
185 | return Err(HotKeyParseError::EmptyToken(hotkey.to_string()));
186 | }
187 |
188 | if key.is_some() {
189 | // At this point we have parsed the modifiers and a main key, so by reaching
190 | // this code, the function either received more than one main key or
191 | // the hotkey is not in the right order
192 | // examples:
193 | // 1. "Ctrl+Shift+C+A" => only one main key should be allowd.
194 | // 2. "Ctrl+C+Shift" => wrong order
195 | return Err(HotKeyParseError::InvalidFormat(hotkey.to_string()));
196 | }
197 |
198 | match token.to_uppercase().as_str() {
199 | "OPTION" | "ALT" => {
200 | mods |= Modifiers::ALT;
201 | }
202 | "CONTROL" | "CTRL" => {
203 | mods |= Modifiers::CONTROL;
204 | }
205 | "COMMAND" | "CMD" | "SUPER" => {
206 | mods |= Modifiers::SUPER;
207 | }
208 | "SHIFT" => {
209 | mods |= Modifiers::SHIFT;
210 | }
211 | #[cfg(target_os = "macos")]
212 | "COMMANDORCONTROL" | "COMMANDORCTRL" | "CMDORCTRL" | "CMDORCONTROL" => {
213 | mods |= Modifiers::SUPER;
214 | }
215 | #[cfg(not(target_os = "macos"))]
216 | "COMMANDORCONTROL" | "COMMANDORCTRL" | "CMDORCTRL" | "CMDORCONTROL" => {
217 | mods |= Modifiers::CONTROL;
218 | }
219 | _ => {
220 | key = Some(parse_key(token)?);
221 | }
222 | }
223 | }
224 | }
225 | }
226 |
227 | Ok(HotKey::new(
228 | Some(mods),
229 | key.ok_or_else(|| HotKeyParseError::InvalidFormat(hotkey.to_string()))?,
230 | ))
231 | }
232 |
233 | fn parse_key(key: &str) -> Result {
234 | use Code::*;
235 | match key.to_uppercase().as_str() {
236 | "BACKQUOTE" | "`" => Ok(Backquote),
237 | "BACKSLASH" | "\\" => Ok(Backslash),
238 | "BRACKETLEFT" | "[" => Ok(BracketLeft),
239 | "BRACKETRIGHT" | "]" => Ok(BracketRight),
240 | "PAUSE" | "PAUSEBREAK" => Ok(Pause),
241 | "COMMA" | "," => Ok(Comma),
242 | "DIGIT0" | "0" => Ok(Digit0),
243 | "DIGIT1" | "1" => Ok(Digit1),
244 | "DIGIT2" | "2" => Ok(Digit2),
245 | "DIGIT3" | "3" => Ok(Digit3),
246 | "DIGIT4" | "4" => Ok(Digit4),
247 | "DIGIT5" | "5" => Ok(Digit5),
248 | "DIGIT6" | "6" => Ok(Digit6),
249 | "DIGIT7" | "7" => Ok(Digit7),
250 | "DIGIT8" | "8" => Ok(Digit8),
251 | "DIGIT9" | "9" => Ok(Digit9),
252 | "EQUAL" | "=" => Ok(Equal),
253 | "KEYA" | "A" => Ok(KeyA),
254 | "KEYB" | "B" => Ok(KeyB),
255 | "KEYC" | "C" => Ok(KeyC),
256 | "KEYD" | "D" => Ok(KeyD),
257 | "KEYE" | "E" => Ok(KeyE),
258 | "KEYF" | "F" => Ok(KeyF),
259 | "KEYG" | "G" => Ok(KeyG),
260 | "KEYH" | "H" => Ok(KeyH),
261 | "KEYI" | "I" => Ok(KeyI),
262 | "KEYJ" | "J" => Ok(KeyJ),
263 | "KEYK" | "K" => Ok(KeyK),
264 | "KEYL" | "L" => Ok(KeyL),
265 | "KEYM" | "M" => Ok(KeyM),
266 | "KEYN" | "N" => Ok(KeyN),
267 | "KEYO" | "O" => Ok(KeyO),
268 | "KEYP" | "P" => Ok(KeyP),
269 | "KEYQ" | "Q" => Ok(KeyQ),
270 | "KEYR" | "R" => Ok(KeyR),
271 | "KEYS" | "S" => Ok(KeyS),
272 | "KEYT" | "T" => Ok(KeyT),
273 | "KEYU" | "U" => Ok(KeyU),
274 | "KEYV" | "V" => Ok(KeyV),
275 | "KEYW" | "W" => Ok(KeyW),
276 | "KEYX" | "X" => Ok(KeyX),
277 | "KEYY" | "Y" => Ok(KeyY),
278 | "KEYZ" | "Z" => Ok(KeyZ),
279 | "MINUS" | "-" => Ok(Minus),
280 | "PERIOD" | "." => Ok(Period),
281 | "QUOTE" | "'" => Ok(Quote),
282 | "SEMICOLON" | ";" => Ok(Semicolon),
283 | "SLASH" | "/" => Ok(Slash),
284 | "BACKSPACE" => Ok(Backspace),
285 | "CAPSLOCK" => Ok(CapsLock),
286 | "ENTER" => Ok(Enter),
287 | "SPACE" => Ok(Space),
288 | "TAB" => Ok(Tab),
289 | "DELETE" => Ok(Delete),
290 | "END" => Ok(End),
291 | "HOME" => Ok(Home),
292 | "INSERT" => Ok(Insert),
293 | "PAGEDOWN" => Ok(PageDown),
294 | "PAGEUP" => Ok(PageUp),
295 | "PRINTSCREEN" => Ok(PrintScreen),
296 | "SCROLLLOCK" => Ok(ScrollLock),
297 | "ARROWDOWN" | "DOWN" => Ok(ArrowDown),
298 | "ARROWLEFT" | "LEFT" => Ok(ArrowLeft),
299 | "ARROWRIGHT" | "RIGHT" => Ok(ArrowRight),
300 | "ARROWUP" | "UP" => Ok(ArrowUp),
301 | "NUMLOCK" => Ok(NumLock),
302 | "NUMPAD0" | "NUM0" => Ok(Numpad0),
303 | "NUMPAD1" | "NUM1" => Ok(Numpad1),
304 | "NUMPAD2" | "NUM2" => Ok(Numpad2),
305 | "NUMPAD3" | "NUM3" => Ok(Numpad3),
306 | "NUMPAD4" | "NUM4" => Ok(Numpad4),
307 | "NUMPAD5" | "NUM5" => Ok(Numpad5),
308 | "NUMPAD6" | "NUM6" => Ok(Numpad6),
309 | "NUMPAD7" | "NUM7" => Ok(Numpad7),
310 | "NUMPAD8" | "NUM8" => Ok(Numpad8),
311 | "NUMPAD9" | "NUM9" => Ok(Numpad9),
312 | "NUMPADADD" | "NUMADD" | "NUMPADPLUS" | "NUMPLUS" => Ok(NumpadAdd),
313 | "NUMPADDECIMAL" | "NUMDECIMAL" => Ok(NumpadDecimal),
314 | "NUMPADDIVIDE" | "NUMDIVIDE" => Ok(NumpadDivide),
315 | "NUMPADENTER" | "NUMENTER" => Ok(NumpadEnter),
316 | "NUMPADEQUAL" | "NUMEQUAL" => Ok(NumpadEqual),
317 | "NUMPADMULTIPLY" | "NUMMULTIPLY" => Ok(NumpadMultiply),
318 | "NUMPADSUBTRACT" | "NUMSUBTRACT" => Ok(NumpadSubtract),
319 | "ESCAPE" | "ESC" => Ok(Escape),
320 | "F1" => Ok(F1),
321 | "F2" => Ok(F2),
322 | "F3" => Ok(F3),
323 | "F4" => Ok(F4),
324 | "F5" => Ok(F5),
325 | "F6" => Ok(F6),
326 | "F7" => Ok(F7),
327 | "F8" => Ok(F8),
328 | "F9" => Ok(F9),
329 | "F10" => Ok(F10),
330 | "F11" => Ok(F11),
331 | "F12" => Ok(F12),
332 | "AUDIOVOLUMEDOWN" | "VOLUMEDOWN" => Ok(AudioVolumeDown),
333 | "AUDIOVOLUMEUP" | "VOLUMEUP" => Ok(AudioVolumeUp),
334 | "AUDIOVOLUMEMUTE" | "VOLUMEMUTE" => Ok(AudioVolumeMute),
335 | "MEDIAPLAY" => Ok(MediaPlay),
336 | "MEDIAPAUSE" => Ok(MediaPause),
337 | "MEDIAPLAYPAUSE" => Ok(MediaPlayPause),
338 | "MEDIASTOP" => Ok(MediaStop),
339 | "MEDIATRACKNEXT" => Ok(MediaTrackNext),
340 | "MEDIATRACKPREV" | "MEDIATRACKPREVIOUS" => Ok(MediaTrackPrevious),
341 | "F13" => Ok(F13),
342 | "F14" => Ok(F14),
343 | "F15" => Ok(F15),
344 | "F16" => Ok(F16),
345 | "F17" => Ok(F17),
346 | "F18" => Ok(F18),
347 | "F19" => Ok(F19),
348 | "F20" => Ok(F20),
349 | "F21" => Ok(F21),
350 | "F22" => Ok(F22),
351 | "F23" => Ok(F23),
352 | "F24" => Ok(F24),
353 |
354 | _ => Err(HotKeyParseError::UnsupportedKey(key.to_string())),
355 | }
356 | }
357 |
358 | #[test]
359 | fn test_parse_hotkey() {
360 | macro_rules! assert_parse_hotkey {
361 | ($key:literal, $lrh:expr) => {
362 | let r = parse_hotkey($key).unwrap();
363 | let l = $lrh;
364 | assert_eq!(r.mods, l.mods);
365 | assert_eq!(r.key, l.key);
366 | };
367 | }
368 |
369 | assert_parse_hotkey!(
370 | "KeyX",
371 | HotKey {
372 | mods: Modifiers::empty(),
373 | key: Code::KeyX,
374 | id: 0,
375 | }
376 | );
377 |
378 | assert_parse_hotkey!(
379 | "CTRL+KeyX",
380 | HotKey {
381 | mods: Modifiers::CONTROL,
382 | key: Code::KeyX,
383 | id: 0,
384 | }
385 | );
386 |
387 | assert_parse_hotkey!(
388 | "SHIFT+KeyC",
389 | HotKey {
390 | mods: Modifiers::SHIFT,
391 | key: Code::KeyC,
392 | id: 0,
393 | }
394 | );
395 |
396 | assert_parse_hotkey!(
397 | "SHIFT+KeyC",
398 | HotKey {
399 | mods: Modifiers::SHIFT,
400 | key: Code::KeyC,
401 | id: 0,
402 | }
403 | );
404 |
405 | assert_parse_hotkey!(
406 | "super+ctrl+SHIFT+alt+ArrowUp",
407 | HotKey {
408 | mods: Modifiers::SUPER | Modifiers::CONTROL | Modifiers::SHIFT | Modifiers::ALT,
409 | key: Code::ArrowUp,
410 | id: 0,
411 | }
412 | );
413 | assert_parse_hotkey!(
414 | "Digit5",
415 | HotKey {
416 | mods: Modifiers::empty(),
417 | key: Code::Digit5,
418 | id: 0,
419 | }
420 | );
421 | assert_parse_hotkey!(
422 | "KeyG",
423 | HotKey {
424 | mods: Modifiers::empty(),
425 | key: Code::KeyG,
426 | id: 0,
427 | }
428 | );
429 |
430 | assert_parse_hotkey!(
431 | "SHiFT+F12",
432 | HotKey {
433 | mods: Modifiers::SHIFT,
434 | key: Code::F12,
435 | id: 0,
436 | }
437 | );
438 |
439 | assert_parse_hotkey!(
440 | "CmdOrCtrl+Space",
441 | HotKey {
442 | #[cfg(target_os = "macos")]
443 | mods: Modifiers::SUPER,
444 | #[cfg(not(target_os = "macos"))]
445 | mods: Modifiers::CONTROL,
446 | key: Code::Space,
447 | id: 0,
448 | }
449 | );
450 |
451 | // Ensure that if it is just multiple modifiers, we do not panic.
452 | // This would be a regression if this happened.
453 | if HotKey::from_str("Shift+Ctrl").is_ok() {
454 | panic!("This is not a valid hotkey");
455 | }
456 | }
457 |
458 | #[test]
459 | fn test_equality() {
460 | let h1 = parse_hotkey("Shift+KeyR").unwrap();
461 | let h2 = parse_hotkey("Shift+KeyR").unwrap();
462 | let h3 = HotKey::new(Some(Modifiers::SHIFT), Code::KeyR);
463 | let h4 = parse_hotkey("Alt+KeyR").unwrap();
464 | let h5 = parse_hotkey("Alt+KeyR").unwrap();
465 | let h6 = parse_hotkey("KeyR").unwrap();
466 |
467 | assert!(h1 == h2 && h2 == h3 && h3 != h4 && h4 == h5 && h5 != h6);
468 | assert!(
469 | h1.id() == h2.id()
470 | && h2.id() == h3.id()
471 | && h3.id() != h4.id()
472 | && h4.id() == h5.id()
473 | && h5.id() != h6.id()
474 | );
475 | }
476 |
--------------------------------------------------------------------------------
/src/lib.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2022-2022 Tauri Programme within The Commons Conservancy
2 | // SPDX-License-Identifier: Apache-2.0
3 | // SPDX-License-Identifier: MIT
4 |
5 | #![allow(clippy::uninlined_format_args)]
6 |
7 | //! global_hotkey lets you register Global HotKeys for Desktop Applications.
8 | //!
9 | //! ## Platforms-supported:
10 | //!
11 | //! - Windows
12 | //! - macOS
13 | //! - Linux (X11 Only)
14 | //!
15 | //! ## Platform-specific notes:
16 | //!
17 | //! - On Windows a win32 event loop must be running on the thread. It doesn't need to be the main thread but you have to create the global hotkey manager on the same thread as the event loop.
18 | //! - On macOS, an event loop must be running on the main thread so you also need to create the global hotkey manager on the main thread.
19 | //!
20 | //! # Example
21 | //!
22 | //! ```no_run
23 | //! use global_hotkey::{GlobalHotKeyManager, hotkey::{HotKey, Modifiers, Code}};
24 | //!
25 | //! // initialize the hotkeys manager
26 | //! let manager = GlobalHotKeyManager::new().unwrap();
27 | //!
28 | //! // construct the hotkey
29 | //! let hotkey = HotKey::new(Some(Modifiers::SHIFT), Code::KeyD);
30 | //!
31 | //! // register it
32 | //! manager.register(hotkey);
33 | //! ```
34 | //!
35 | //!
36 | //! # Processing global hotkey events
37 | //!
38 | //! You can also listen for the menu events using [`GlobalHotKeyEvent::receiver`] to get events for the hotkey pressed events.
39 | //! ```no_run
40 | //! use global_hotkey::GlobalHotKeyEvent;
41 | //!
42 | //! if let Ok(event) = GlobalHotKeyEvent::receiver().try_recv() {
43 | //! println!("{:?}", event);
44 | //! }
45 | //! ```
46 | //!
47 | //! # Platforms-supported:
48 | //!
49 | //! - Windows
50 | //! - macOS
51 | //! - Linux (X11 Only)
52 |
53 | use crossbeam_channel::{unbounded, Receiver, Sender};
54 | use once_cell::sync::{Lazy, OnceCell};
55 |
56 | mod error;
57 | pub mod hotkey;
58 | mod platform_impl;
59 |
60 | pub use self::error::*;
61 | use hotkey::HotKey;
62 |
63 | /// Describes the state of the [`HotKey`].
64 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
65 | #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
66 | pub enum HotKeyState {
67 | /// The [`HotKey`] is pressed (the key is down).
68 | Pressed,
69 | /// The [`HotKey`] is released (the key is up).
70 | Released,
71 | }
72 |
73 | /// Describes a global hotkey event emitted when a [`HotKey`] is pressed or released.
74 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
75 | #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
76 | pub struct GlobalHotKeyEvent {
77 | /// Id of the associated [`HotKey`].
78 | pub id: u32,
79 | /// State of the associated [`HotKey`].
80 | pub state: HotKeyState,
81 | }
82 |
83 | /// A reciever that could be used to listen to global hotkey events.
84 | pub type GlobalHotKeyEventReceiver = Receiver;
85 | type GlobalHotKeyEventHandler = Box;
86 |
87 | static GLOBAL_HOTKEY_CHANNEL: Lazy<(Sender, GlobalHotKeyEventReceiver)> =
88 | Lazy::new(unbounded);
89 | static GLOBAL_HOTKEY_EVENT_HANDLER: OnceCell