├── .changes ├── config.json ├── context-menu-convert-back.md ├── gtk-feature.md └── 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 ├── icon.png ├── tao.rs ├── windows-common-controls-v6 │ ├── .gitignore │ ├── Cargo.toml │ ├── app.exe.manifest │ ├── build.rs │ ├── manifest.rc │ └── src │ │ └── main.rs ├── winit.rs └── wry.rs ├── renovate.json └── src ├── about_metadata.rs ├── accelerator.rs ├── builders ├── check.rs ├── icon.rs ├── mod.rs ├── normal.rs └── submenu.rs ├── error.rs ├── icon.rs ├── items ├── check.rs ├── icon.rs ├── mod.rs ├── normal.rs ├── predefined.rs └── submenu.rs ├── lib.rs ├── menu.rs ├── menu_id.rs ├── platform_impl ├── gtk │ ├── accelerator.rs │ ├── icon.rs │ └── mod.rs ├── macos │ ├── accelerator.rs │ ├── icon.rs │ ├── mod.rs │ └── util.rs ├── mod.rs └── windows │ ├── accelerator.rs │ ├── dark_menu_bar.rs │ ├── icon.rs │ ├── mod.rs │ └── util.rs └── util.rs /.changes/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "gitSiteUrl": "https://www.github.com/tauri-apps/muda/", 3 | "timeout": 3600000, 4 | "pkgManagers": { 5 | "rust": { 6 | "version": true, 7 | "getPublishedVersion": "cargo search ${ pkg.pkg } --limit 1 | sed -nE 's/^[^\"]*\"//; s/\".*//1p' -", 8 | "prepublish": [ 9 | "sudo apt-get update", 10 | "sudo apt-get install -y libgtk-3-dev libxdo-dev" 11 | ], 12 | "publish": [ 13 | { 14 | "command": "cargo package --no-verify", 15 | "dryRunCommand": true 16 | }, 17 | { 18 | "command": "echo '
\n

Cargo Publish

\n\n```'", 19 | "dryRunCommand": true, 20 | "pipe": true 21 | }, 22 | { 23 | "command": "cargo publish", 24 | "dryRunCommand": "cargo publish --dry-run", 25 | "pipe": true 26 | }, 27 | { 28 | "command": "echo '```\n\n
\n'", 29 | "dryRunCommand": true, 30 | "pipe": true 31 | } 32 | ], 33 | "postpublish": [ 34 | "git tag ${ pkg.pkg }-v${ pkgFile.versionMajor } -f", 35 | "git tag ${ pkg.pkg }-v${ pkgFile.versionMajor }.${ pkgFile.versionMinor } -f", 36 | "git push --tags -f" 37 | ] 38 | } 39 | }, 40 | "packages": { 41 | "muda": { 42 | "path": ".", 43 | "manager": "rust", 44 | "assets": [ 45 | { 46 | "path": "${ pkg.path }/target/package/muda-${ pkgFile.version }.crate", 47 | "name": "${ pkg.pkg }-${ pkgFile.version }.crate" 48 | } 49 | ] 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /.changes/context-menu-convert-back.md: -------------------------------------------------------------------------------- 1 | --- 2 | "muda": "minor" 3 | --- 4 | 5 | Add helper methods on `ContextMenu` trait to convert it back to a concrete type: 6 | 7 | - `ContextMenu::as_menu` 8 | - `ContextMenu::as_menu_unchecked` 9 | - `ContextMenu::as_submenu` 10 | - `ContextMenu::as_submenu_unchecked` 11 | -------------------------------------------------------------------------------- /.changes/gtk-feature.md: -------------------------------------------------------------------------------- 1 | --- 2 | "muda": minor 3 | --- 4 | 5 | Make gtk an optional feature (enabled by default) 6 | -------------------------------------------------------------------------------- /.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 | "muda": 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@v1 32 | with: 33 | token: ${{ secrets.GITHUB_TOKEN }} -------------------------------------------------------------------------------- /.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 libwebkit2gtk-4.1-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 }} -------------------------------------------------------------------------------- /.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 libwebkit2gtk-4.1-dev 37 | 38 | - uses: dtolnay/rust-toolchain@1.71 39 | - run: cargo build 40 | 41 | - uses: dtolnay/rust-toolchain@stable 42 | - run: cargo test 43 | 44 | - uses: dtolnay/rust-toolchain@nightly 45 | with: 46 | components: miri 47 | - run: cargo +nightly miri test 48 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Copyright 2022-2022 Tauri Programme within The Commons Conservancy 2 | # SPDX-License-Identifier: Apache-2.0 3 | # SPDX-License-Identifier: MIT 4 | 5 | /target 6 | /.vscode -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "muda" 3 | version = "0.16.1" 4 | description = "Menu Utilities for Desktop Applications" 5 | edition = "2021" 6 | keywords = ["windowing", "menu"] 7 | license = "Apache-2.0 OR MIT" 8 | readme = "README.md" 9 | repository = "https://github.com/amrbashir/muda" 10 | documentation = "https://docs.rs/muda" 11 | categories = ["gui"] 12 | rust-version = "1.71" 13 | 14 | [features] 15 | default = ["libxdo", "gtk"] 16 | libxdo = ["dep:libxdo"] 17 | gtk = ["dep:gtk"] 18 | common-controls-v6 = [] 19 | serde = ["dep:serde", "dpi/serde"] 20 | 21 | [dependencies] 22 | crossbeam-channel = "0.5" 23 | keyboard-types = "0.7" 24 | once_cell = "1" 25 | thiserror = "2" 26 | serde = { version = "1", optional = true } 27 | dpi = "0.1" 28 | 29 | [target.'cfg(target_os = "windows")'.dependencies.windows-sys] 30 | version = "0.59" 31 | features = [ 32 | "Win32_UI_WindowsAndMessaging", 33 | "Win32_Foundation", 34 | "Win32_Graphics_Gdi", 35 | "Win32_UI_Shell", 36 | "Win32_Globalization", 37 | "Win32_UI_Input_KeyboardAndMouse", 38 | "Win32_System_SystemServices", 39 | "Win32_UI_Accessibility", 40 | "Win32_UI_HiDpi", 41 | "Win32_System_LibraryLoader", 42 | "Win32_UI_Controls", 43 | ] 44 | 45 | [target.'cfg(target_os = "linux")'.dependencies] 46 | gtk = { version = "0.18", optional = true } 47 | libxdo = { version = "0.6.0", optional = true } 48 | 49 | [target.'cfg(target_os = "macos")'.dependencies] 50 | objc2 = "0.6.0" 51 | objc2-core-foundation = { version = "0.3.0", default-features = false, features = [ 52 | "std", 53 | "CFCGTypes", 54 | ] } 55 | objc2-foundation = { version = "0.3.0", default-features = false, features = [ 56 | "std", 57 | "NSAttributedString", 58 | "NSData", 59 | "NSDictionary", 60 | "NSGeometry", 61 | "NSString", 62 | "NSThread", 63 | ] } 64 | objc2-app-kit = { version = "0.3.0", default-features = false, features = [ 65 | "std", 66 | "objc2-core-foundation", 67 | "NSApplication", 68 | "NSCell", 69 | "NSEvent", 70 | "NSImage", 71 | "NSMenu", 72 | "NSMenuItem", 73 | "NSResponder", 74 | "NSRunningApplication", 75 | "NSView", 76 | "NSWindow", 77 | ] } 78 | png = "0.17" 79 | 80 | [dev-dependencies] 81 | winit = "0.30" 82 | tao = "0.30" 83 | wry = "0.45" 84 | image = "0.25" 85 | -------------------------------------------------------------------------------- /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: muda 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/muda 17 | PackageDownloadLocation: git+https://github.com/tauri-apps/muda.git 18 | PackageDownloadLocation: git+ssh://github.com/tauri-apps/muda.git 19 | Creator: Person: Daniel Thompson-Yvetot -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### muda 2 | 3 | Menu Utilities library for Desktop Applications. 4 | 5 | [![Documentation](https://img.shields.io/docsrs/muda)](https://docs.rs/muda/latest/muda/) 6 | 7 | ## Platforms supported: 8 | 9 | - Windows 10 | - macOS 11 | - Linux (gtk Only) 12 | 13 | ## Platform-specific notes: 14 | 15 | - On Windows, accelerators don't work unless the win32 message loop calls 16 | [`TranslateAcceleratorW`](https://docs.rs/windows-sys/latest/windows_sys/Win32/UI/WindowsAndMessaging/fn.TranslateAcceleratorW.html). 17 | See [`Menu::init_for_hwnd`](https://docs.rs/muda/latest/x86_64-pc-windows-msvc/muda/struct.Menu.html#method.init_for_hwnd) for more details 18 | 19 | ### Cargo Features 20 | 21 | - `common-controls-v6`: Use `TaskDialogIndirect` API from `ComCtl32.dll` v6 on Windows for showing the predefined `About` menu item dialog. 22 | - `libxdo`: Enables linking to `libxdo` on Linux which is used for the predefined `Copy`, `Cut`, `Paste` and `SelectAll` menu item. 23 | - `serde`: Enables de/serializing the dpi types. 24 | - `gtk`: Enables the `gtk` crate dependency on Linux. This is required for `muda` to function properly on Linux. 25 | 26 | ## Dependencies (Linux Only) 27 | 28 | `gtk` is used for menus and `libxdo` is used to make the predfined `Copy`, `Cut`, `Paste` and `SelectAll` menu items work. Be sure to install following packages before building: 29 | 30 | #### Arch Linux / Manjaro: 31 | 32 | ```sh 33 | pacman -S gtk3 xdotool 34 | ``` 35 | 36 | #### Debian / Ubuntu: 37 | 38 | ```sh 39 | sudo apt install libgtk-3-dev libxdo-dev 40 | ``` 41 | 42 | ## Example 43 | 44 | Create the menu and add your items 45 | 46 | ```rs 47 | let menu = Menu::new(); 48 | let menu_item2 = MenuItem::new("Menu item #2", false, None); 49 | let submenu = Submenu::with_items("Submenu Outer", true,&[ 50 | &MenuItem::new("Menu item #1", true, Some(Accelerator::new(Some(Modifiers::ALT), Code::KeyD))), 51 | &PredefinedMenuItem::separator(), 52 | &menu_item2, 53 | &MenuItem::new("Menu item #3", true, None), 54 | &PredefinedMenuItem::separator(), 55 | &Submenu::with_items("Submenu Inner", true,&[ 56 | &MenuItem::new("Submenu item #1", true, None), 57 | &PredefinedMenuItem::separator(), 58 | &menu_item2, 59 | ]) 60 | ]); 61 | 62 | ``` 63 | 64 | Then add your root menu to a Window on Windows and Linux 65 | or use it as your global app menu on macOS 66 | 67 | ```rs 68 | // --snip-- 69 | #[cfg(target_os = "windows")] 70 | unsafe { menu.init_for_hwnd(window.hwnd() as isize) }; 71 | #[cfg(target_os = "linux")] 72 | menu.init_for_gtk_window(>k_window, Some(&vertical_gtk_box)); 73 | #[cfg(target_os = "macos")] 74 | menu.init_for_nsapp(); 75 | ``` 76 | 77 | ## Context menus (Popup menus) 78 | 79 | You can also use a [`Menu`] or a [`Submenu`] show a context menu. 80 | 81 | ```rs 82 | // --snip-- 83 | let position = muda::PhysicalPosition { x: 100., y: 120. }; 84 | #[cfg(target_os = "windows")] 85 | unsafe { menu.show_context_menu_for_hwnd(window.hwnd() as isize, Some(position.into())) }; 86 | #[cfg(target_os = "linux")] 87 | menu.show_context_menu_for_gtk_window(>k_window, Some(position.into())); 88 | #[cfg(target_os = "macos")] 89 | unsafe { menu.show_context_menu_for_nsview(nsview, Some(position.into())) }; 90 | ``` 91 | 92 | ## Processing menu events 93 | 94 | You can use `MenuEvent::receiver` to get a reference to the `MenuEventReceiver` 95 | which you can use to listen to events when a menu item is activated 96 | 97 | ```rs 98 | if let Ok(event) = MenuEvent::receiver().try_recv() { 99 | match event.id { 100 | _ if event.id == save_item.id() => { 101 | println!("Save menu item activated"); 102 | }, 103 | _ => {} 104 | } 105 | } 106 | ``` 107 | 108 | ### Note for [winit] or [tao] users: 109 | 110 | You should use [`MenuEvent::set_event_handler`] and forward 111 | the menu events to the event loop by using [`EventLoopProxy`] 112 | so that the event loop is awakened on each menu event. 113 | 114 | ```rust 115 | enum UserEvent { 116 | MenuEvent(muda::MenuEvent) 117 | } 118 | 119 | let event_loop = EventLoop::::with_user_event().build().unwrap(); 120 | 121 | let proxy = event_loop.create_proxy(); 122 | muda::MenuEvent::set_event_handler(Some(move |event| { 123 | proxy.send_event(UserEvent::MenuEvent(event)); 124 | })); 125 | ``` 126 | 127 | [`EventLoopProxy`]: https://docs.rs/winit/latest/winit/event_loop/struct.EventLoopProxy.html 128 | [winit]: https://docs.rs/winit 129 | [tao]: https://docs.rs/tao 130 | 131 | ## License 132 | 133 | Apache-2.0/MIT 134 | -------------------------------------------------------------------------------- /examples/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tauri-apps/muda/8e986af3cea96a729413abc75c3702dec3990bd2/examples/icon.png -------------------------------------------------------------------------------- /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 | #![allow(unused)] 6 | use muda::{ 7 | accelerator::{Accelerator, Code, Modifiers}, 8 | dpi::{PhysicalPosition, Position}, 9 | AboutMetadata, CheckMenuItem, ContextMenu, IconMenuItem, Menu, MenuEvent, MenuItem, 10 | PredefinedMenuItem, Submenu, 11 | }; 12 | #[cfg(target_os = "macos")] 13 | use tao::platform::macos::WindowExtMacOS; 14 | #[cfg(target_os = "linux")] 15 | use tao::platform::unix::WindowExtUnix; 16 | #[cfg(target_os = "windows")] 17 | use tao::platform::windows::{EventLoopBuilderExtWindows, WindowExtWindows}; 18 | use tao::{ 19 | event::{ElementState, Event, MouseButton, WindowEvent}, 20 | event_loop::{ControlFlow, EventLoopBuilder}, 21 | window::{Window, WindowBuilder}, 22 | }; 23 | 24 | enum UserEvent { 25 | MenuEvent(muda::MenuEvent), 26 | } 27 | 28 | fn main() { 29 | let mut event_loop_builder = EventLoopBuilder::::with_user_event(); 30 | 31 | let menu_bar = Menu::new(); 32 | 33 | // setup accelerator handler on Windows 34 | #[cfg(target_os = "windows")] 35 | { 36 | let menu_bar = menu_bar.clone(); 37 | event_loop_builder.with_msg_hook(move |msg| { 38 | use windows_sys::Win32::UI::WindowsAndMessaging::{TranslateAcceleratorW, MSG}; 39 | unsafe { 40 | let msg = msg as *const MSG; 41 | let translated = TranslateAcceleratorW((*msg).hwnd, menu_bar.haccel() as _, msg); 42 | translated == 1 43 | } 44 | }); 45 | } 46 | 47 | let event_loop = event_loop_builder.build(); 48 | 49 | // set a menu event handler that wakes up the event loop 50 | let proxy = event_loop.create_proxy(); 51 | muda::MenuEvent::set_event_handler(Some(move |event| { 52 | proxy.send_event(UserEvent::MenuEvent(event)); 53 | })); 54 | 55 | let window = WindowBuilder::new() 56 | .with_title("Window 1") 57 | .build(&event_loop) 58 | .unwrap(); 59 | let window2 = WindowBuilder::new() 60 | .with_title("Window 2") 61 | .build(&event_loop) 62 | .unwrap(); 63 | 64 | #[cfg(target_os = "macos")] 65 | { 66 | let app_m = Submenu::new("App", true); 67 | menu_bar.append(&app_m); 68 | app_m.append_items(&[ 69 | &PredefinedMenuItem::about(None, None), 70 | &PredefinedMenuItem::separator(), 71 | &PredefinedMenuItem::services(None), 72 | &PredefinedMenuItem::separator(), 73 | &PredefinedMenuItem::hide(None), 74 | &PredefinedMenuItem::hide_others(None), 75 | &PredefinedMenuItem::show_all(None), 76 | &PredefinedMenuItem::separator(), 77 | &PredefinedMenuItem::quit(None), 78 | ]); 79 | } 80 | 81 | let file_m = Submenu::new("&File", true); 82 | let edit_m = Submenu::new("&Edit", true); 83 | let window_m = Submenu::new("&Window", true); 84 | 85 | menu_bar.append_items(&[&file_m, &edit_m, &window_m]); 86 | 87 | let custom_i_1 = MenuItem::with_id( 88 | "custom-i-1", 89 | "C&ustom 1", 90 | true, 91 | Some(Accelerator::new(Some(Modifiers::ALT), Code::KeyC)), 92 | ); 93 | 94 | let path = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/icon.png"); 95 | let icon = load_icon(std::path::Path::new(path)); 96 | let image_item = IconMenuItem::with_id( 97 | "image-custom-1", 98 | "Image custom 1", 99 | true, 100 | Some(icon), 101 | Some(Accelerator::new(Some(Modifiers::CONTROL), Code::KeyC)), 102 | ); 103 | 104 | let check_custom_i_1 = 105 | CheckMenuItem::with_id("check-custom-1", "Check Custom 1", true, true, None); 106 | let check_custom_i_2 = 107 | CheckMenuItem::with_id("check-custom-2", "Check Custom 2", false, true, None); 108 | let check_custom_i_3 = CheckMenuItem::with_id( 109 | "check-custom-3", 110 | "Check Custom 3", 111 | true, 112 | true, 113 | Some(Accelerator::new(Some(Modifiers::SHIFT), Code::KeyD)), 114 | ); 115 | 116 | let copy_i = PredefinedMenuItem::copy(None); 117 | let cut_i = PredefinedMenuItem::cut(None); 118 | let paste_i = PredefinedMenuItem::paste(None); 119 | 120 | file_m.append_items(&[ 121 | &custom_i_1, 122 | &image_item, 123 | &window_m, 124 | &PredefinedMenuItem::separator(), 125 | &check_custom_i_1, 126 | &check_custom_i_2, 127 | ]); 128 | 129 | window_m.append_items(&[ 130 | &PredefinedMenuItem::minimize(None), 131 | &PredefinedMenuItem::maximize(None), 132 | &PredefinedMenuItem::close_window(Some("Close")), 133 | &PredefinedMenuItem::fullscreen(None), 134 | &PredefinedMenuItem::bring_all_to_front(None), 135 | &PredefinedMenuItem::about( 136 | None, 137 | Some(AboutMetadata { 138 | name: Some("tao".to_string()), 139 | version: Some("1.2.3".to_string()), 140 | copyright: Some("Copyright tao".to_string()), 141 | ..Default::default() 142 | }), 143 | ), 144 | &check_custom_i_3, 145 | &image_item, 146 | &custom_i_1, 147 | ]); 148 | 149 | edit_m.append_items(&[©_i, &PredefinedMenuItem::separator(), &paste_i]); 150 | 151 | #[cfg(target_os = "windows")] 152 | unsafe { 153 | menu_bar.init_for_hwnd(window.hwnd() as _); 154 | menu_bar.init_for_hwnd(window2.hwnd() as _); 155 | } 156 | #[cfg(target_os = "linux")] 157 | { 158 | menu_bar.init_for_gtk_window(window.gtk_window(), window.default_vbox()); 159 | menu_bar.init_for_gtk_window(window2.gtk_window(), window2.default_vbox()); 160 | } 161 | #[cfg(target_os = "macos")] 162 | { 163 | menu_bar.init_for_nsapp(); 164 | window_m.set_as_windows_menu_for_nsapp(); 165 | } 166 | 167 | let menu_channel = MenuEvent::receiver(); 168 | let mut window_cursor_position = PhysicalPosition { x: 0., y: 0. }; 169 | let mut use_window_pos = false; 170 | 171 | event_loop.run(move |event, _, control_flow| { 172 | *control_flow = ControlFlow::Wait; 173 | 174 | match event { 175 | Event::WindowEvent { 176 | event: WindowEvent::CloseRequested, 177 | .. 178 | } => *control_flow = ControlFlow::Exit, 179 | Event::WindowEvent { 180 | event: WindowEvent::CursorMoved { position, .. }, 181 | window_id, 182 | .. 183 | } => { 184 | window_cursor_position.x = position.x; 185 | window_cursor_position.y = position.y; 186 | } 187 | Event::WindowEvent { 188 | event: 189 | WindowEvent::MouseInput { 190 | state: ElementState::Released, 191 | button: MouseButton::Right, 192 | .. 193 | }, 194 | window_id, 195 | .. 196 | } => { 197 | show_context_menu( 198 | if window_id == window.id() { 199 | &window 200 | } else { 201 | &window2 202 | }, 203 | &file_m, 204 | if use_window_pos { 205 | Some(window_cursor_position.into()) 206 | } else { 207 | None 208 | }, 209 | ); 210 | use_window_pos = !use_window_pos; 211 | } 212 | Event::MainEventsCleared => { 213 | window.request_redraw(); 214 | } 215 | 216 | Event::UserEvent(UserEvent::MenuEvent(event)) => { 217 | if event.id == custom_i_1.id() { 218 | file_m.insert(&MenuItem::new("New Menu Item", true, None), 2); 219 | } 220 | println!("{event:?}"); 221 | } 222 | _ => (), 223 | } 224 | }) 225 | } 226 | 227 | fn show_context_menu(window: &Window, menu: &dyn ContextMenu, position: Option) { 228 | println!("Show context menu at position {position:?}"); 229 | #[cfg(target_os = "windows")] 230 | unsafe { 231 | menu.show_context_menu_for_hwnd(window.hwnd() as _, position); 232 | } 233 | #[cfg(target_os = "linux")] 234 | menu.show_context_menu_for_gtk_window(window.gtk_window().as_ref(), position); 235 | #[cfg(target_os = "macos")] 236 | unsafe { 237 | menu.show_context_menu_for_nsview(window.ns_view() as _, position); 238 | } 239 | } 240 | 241 | fn load_icon(path: &std::path::Path) -> muda::Icon { 242 | let (icon_rgba, icon_width, icon_height) = { 243 | let image = image::open(path) 244 | .expect("Failed to open icon path") 245 | .into_rgba8(); 246 | let (width, height) = image.dimensions(); 247 | let rgba = image.into_raw(); 248 | (rgba, width, height) 249 | }; 250 | muda::Icon::from_rgba(icon_rgba, icon_width, icon_height).expect("Failed to open icon") 251 | } 252 | -------------------------------------------------------------------------------- /examples/windows-common-controls-v6/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock -------------------------------------------------------------------------------- /examples/windows-common-controls-v6/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "windows-common-controls-v6" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | muda = { path = "../../", features = ["common-controls-v6"] } 10 | tao = "0.28" 11 | image = "0.25" 12 | 13 | [target."cfg(target_os = \"windows\")".dependencies.windows-sys] 14 | version = "0.59" 15 | features = ["Win32_UI_WindowsAndMessaging", "Win32_Foundation"] 16 | 17 | [build-dependencies] 18 | embed-resource = "2" 19 | -------------------------------------------------------------------------------- /examples/windows-common-controls-v6/app.exe.manifest: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /examples/windows-common-controls-v6/build.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | #[cfg(target_os = "windows")] 3 | embed_resource::compile("manifest.rc", embed_resource::NONE); 4 | } 5 | -------------------------------------------------------------------------------- /examples/windows-common-controls-v6/manifest.rc: -------------------------------------------------------------------------------- 1 | #define RT_MANIFEST 24 2 | 1 RT_MANIFEST "app.exe.manifest" -------------------------------------------------------------------------------- /examples/windows-common-controls-v6/src/main.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(unused)] 6 | use muda::{ 7 | accelerator::{Accelerator, Code, Modifiers}, 8 | dpi::{PhysicalPosition, Position}, 9 | AboutMetadata, CheckMenuItem, ContextMenu, IconMenuItem, Menu, MenuEvent, MenuItem, 10 | PredefinedMenuItem, Submenu, 11 | }; 12 | #[cfg(target_os = "macos")] 13 | use tao::platform::macos::{EventLoopBuilderExtMacOS, WindowExtMacOS}; 14 | #[cfg(target_os = "windows")] 15 | use tao::platform::windows::{EventLoopBuilderExtWindows, WindowExtWindows}; 16 | use tao::{ 17 | event::{ElementState, Event, MouseButton, WindowEvent}, 18 | event_loop::{ControlFlow, EventLoopBuilder}, 19 | window::{Window, WindowBuilder}, 20 | }; 21 | 22 | fn main() { 23 | let mut event_loop_builder = EventLoopBuilder::new(); 24 | 25 | let menu_bar = Menu::new(); 26 | 27 | #[cfg(target_os = "windows")] 28 | { 29 | let menu_bar = menu_bar.clone(); 30 | event_loop_builder.with_msg_hook(move |msg| { 31 | use windows_sys::Win32::UI::WindowsAndMessaging::{TranslateAcceleratorW, MSG}; 32 | unsafe { 33 | let msg = msg as *const MSG; 34 | let translated = TranslateAcceleratorW((*msg).hwnd, menu_bar.haccel() as _, msg); 35 | translated == 1 36 | } 37 | }); 38 | } 39 | #[cfg(target_os = "macos")] 40 | event_loop_builder.with_default_menu(false); 41 | 42 | let event_loop = event_loop_builder.build(); 43 | 44 | let window = WindowBuilder::new() 45 | .with_title("Window 1") 46 | .build(&event_loop) 47 | .unwrap(); 48 | let window2 = WindowBuilder::new() 49 | .with_title("Window 2") 50 | .build(&event_loop) 51 | .unwrap(); 52 | 53 | #[cfg(target_os = "macos")] 54 | { 55 | let app_m = Submenu::new("App", true); 56 | menu_bar.append(&app_m); 57 | app_m.append_items(&[ 58 | &PredefinedMenuItem::about(None, None), 59 | &PredefinedMenuItem::separator(), 60 | &PredefinedMenuItem::services(None), 61 | &PredefinedMenuItem::separator(), 62 | &PredefinedMenuItem::hide(None), 63 | &PredefinedMenuItem::hide_others(None), 64 | &PredefinedMenuItem::show_all(None), 65 | &PredefinedMenuItem::separator(), 66 | &PredefinedMenuItem::quit(None), 67 | ]); 68 | } 69 | 70 | let file_m = Submenu::new("&File", true); 71 | let edit_m = Submenu::new("&Edit", true); 72 | let window_m = Submenu::new("&Window", true); 73 | 74 | menu_bar.append_items(&[&file_m, &edit_m, &window_m]); 75 | 76 | let custom_i_1 = MenuItem::new( 77 | "C&ustom 1", 78 | true, 79 | Some(Accelerator::new(Some(Modifiers::ALT), Code::KeyC)), 80 | ); 81 | 82 | let path = concat!(env!("CARGO_MANIFEST_DIR"), "../../icon.png"); 83 | let icon = load_icon(std::path::Path::new(path)); 84 | let image_item = IconMenuItem::new("Image Custom 1", true, Some(icon), None); 85 | 86 | let check_custom_i_1 = CheckMenuItem::new("Check Custom 1", true, true, None); 87 | let check_custom_i_2 = CheckMenuItem::new("Check Custom 2", false, true, None); 88 | let check_custom_i_3 = CheckMenuItem::new( 89 | "Check Custom 3", 90 | true, 91 | true, 92 | Some(Accelerator::new(Some(Modifiers::SHIFT), Code::KeyD)), 93 | ); 94 | 95 | let copy_i = PredefinedMenuItem::copy(None); 96 | let cut_i = PredefinedMenuItem::cut(None); 97 | let paste_i = PredefinedMenuItem::paste(None); 98 | 99 | file_m.append_items(&[ 100 | &custom_i_1, 101 | &image_item, 102 | &window_m, 103 | &PredefinedMenuItem::separator(), 104 | &check_custom_i_1, 105 | &check_custom_i_2, 106 | ]); 107 | 108 | window_m.append_items(&[ 109 | &PredefinedMenuItem::minimize(None), 110 | &PredefinedMenuItem::maximize(None), 111 | &PredefinedMenuItem::close_window(Some("Close")), 112 | &PredefinedMenuItem::fullscreen(None), 113 | &PredefinedMenuItem::bring_all_to_front(None), 114 | &PredefinedMenuItem::about( 115 | None, 116 | Some(AboutMetadata { 117 | name: Some("tao".to_string()), 118 | version: Some("1.2.3".to_string()), 119 | copyright: Some("Copyright tao".to_string()), 120 | ..Default::default() 121 | }), 122 | ), 123 | &check_custom_i_3, 124 | &image_item, 125 | &custom_i_1, 126 | ]); 127 | 128 | edit_m.append_items(&[©_i, &PredefinedMenuItem::separator(), &paste_i]); 129 | 130 | #[cfg(target_os = "windows")] 131 | { 132 | use tao::rwh_06::*; 133 | if let RawWindowHandle::Win32(handle) = window.window_handle().unwrap().as_raw() { 134 | menu_bar.init_for_hwnd(handle.hwnd.get()); 135 | } 136 | if let RawWindowHandle::Win32(handle) = window2.window_handle().unwrap().as_raw() { 137 | menu_bar.init_for_hwnd(handle.hwnd.get()); 138 | } 139 | } 140 | #[cfg(target_os = "macos")] 141 | { 142 | menu_bar.init_for_nsapp(); 143 | window_m.set_as_windows_menu_for_nsapp(); 144 | } 145 | 146 | let menu_channel = MenuEvent::receiver(); 147 | let mut window_cursor_position = PhysicalPosition { x: 0., y: 0. }; 148 | let mut use_window_pos = false; 149 | 150 | event_loop.run(move |event, event_loop, control_flow| { 151 | *control_flow = ControlFlow::Wait; 152 | 153 | match event { 154 | Event::WindowEvent { 155 | event: WindowEvent::CloseRequested, 156 | .. 157 | } => *control_flow = ControlFlow::Exit, 158 | Event::WindowEvent { 159 | event: WindowEvent::CursorMoved { position, .. }, 160 | window_id, 161 | .. 162 | } => { 163 | window_cursor_position.x = position.x; 164 | window_cursor_position.y = position.y; 165 | } 166 | Event::WindowEvent { 167 | event: 168 | WindowEvent::MouseInput { 169 | state: ElementState::Pressed, 170 | button: MouseButton::Right, 171 | .. 172 | }, 173 | window_id, 174 | .. 175 | } => { 176 | show_context_menu( 177 | if window_id == window.id() { 178 | &window 179 | } else { 180 | &window2 181 | }, 182 | &file_m, 183 | if use_window_pos { 184 | Some(window_cursor_position.into()) 185 | } else { 186 | None 187 | }, 188 | ); 189 | use_window_pos = !use_window_pos; 190 | } 191 | _ => (), 192 | } 193 | 194 | if let Ok(event) = menu_channel.try_recv() { 195 | if event.id == custom_i_1.id() { 196 | file_m.insert(&MenuItem::new("New Menu Item", true, None), 2); 197 | } 198 | println!("{event:?}"); 199 | } 200 | }); 201 | } 202 | 203 | fn show_context_menu(window: &Window, menu: &dyn ContextMenu, position: Option) { 204 | println!("Show context menu at position {position:?}"); 205 | #[cfg(target_os = "windows")] 206 | { 207 | use tao::rwh_06::*; 208 | if let RawWindowHandle::Win32(handle) = window.window_handle().unwrap().as_raw() { 209 | menu.show_context_menu_for_hwnd(handle.hwnd.get(), position); 210 | } 211 | } 212 | #[cfg(target_os = "macos")] 213 | { 214 | use tao::rwh_06::*; 215 | if let RawWindowHandle::AppKit(handle) = window.window_handle().unwrap().as_raw() { 216 | unsafe { menu.show_context_menu_for_nsview(handle.ns_view.as_ptr() as _, position) }; 217 | } 218 | } 219 | } 220 | 221 | fn load_icon(path: &std::path::Path) -> muda::Icon { 222 | let (icon_rgba, icon_width, icon_height) = { 223 | let image = image::open(path) 224 | .expect("Failed to open icon path") 225 | .into_rgba8(); 226 | let (width, height) = image.dimensions(); 227 | let rgba = image.into_raw(); 228 | (rgba, width, height) 229 | }; 230 | muda::Icon::from_rgba(icon_rgba, icon_width, icon_height).expect("Failed to open icon") 231 | } 232 | -------------------------------------------------------------------------------- /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 | #![allow(unused)] 6 | use std::collections::HashMap; 7 | 8 | use muda::{ 9 | accelerator::{Accelerator, Code, Modifiers}, 10 | dpi::{PhysicalPosition, Position}, 11 | AboutMetadata, CheckMenuItem, ContextMenu, IconMenuItem, Menu, MenuEvent, MenuItem, 12 | PredefinedMenuItem, Submenu, 13 | }; 14 | #[cfg(target_os = "macos")] 15 | use winit::platform::macos::{EventLoopBuilderExtMacOS, WindowExtMacOS}; 16 | #[cfg(target_os = "windows")] 17 | use winit::platform::windows::{EventLoopBuilderExtWindows, WindowExtWindows}; 18 | #[cfg(any(windows, target_os = "macos"))] 19 | use winit::raw_window_handle::*; 20 | use winit::{ 21 | application::ApplicationHandler, 22 | event::{ElementState, Event, MouseButton, StartCause, WindowEvent}, 23 | event_loop::{ActiveEventLoop, ControlFlow, EventLoop, EventLoopBuilder}, 24 | window::{Window, WindowAttributes, WindowId}, 25 | }; 26 | 27 | enum AppEvent { 28 | MenuEvent(muda::MenuEvent), 29 | } 30 | 31 | fn main() { 32 | let mut event_loop_builder = EventLoop::::with_user_event(); 33 | 34 | let menu_bar = Menu::new(); 35 | 36 | // setup accelerator handler on Windows 37 | #[cfg(target_os = "windows")] 38 | { 39 | let menu_bar = menu_bar.clone(); 40 | event_loop_builder.with_msg_hook(move |msg| { 41 | use windows_sys::Win32::UI::WindowsAndMessaging::{TranslateAcceleratorW, MSG}; 42 | unsafe { 43 | let msg = msg as *const MSG; 44 | let translated = TranslateAcceleratorW((*msg).hwnd, menu_bar.haccel() as _, msg); 45 | translated == 1 46 | } 47 | }); 48 | } 49 | #[cfg(target_os = "macos")] 50 | event_loop_builder.with_default_menu(false); 51 | 52 | let event_loop = event_loop_builder.build().unwrap(); 53 | 54 | // set a menu event handler that wakes up the event loop 55 | let proxy = event_loop.create_proxy(); 56 | muda::MenuEvent::set_event_handler(Some(move |event| { 57 | proxy.send_event(AppEvent::MenuEvent(event)); 58 | })); 59 | 60 | let mut app = App { 61 | app_menu: AppMenu::new(menu_bar), 62 | windows: HashMap::default(), 63 | cursor_position: PhysicalPosition::new(0., 0.), 64 | use_window_pos: false, 65 | }; 66 | 67 | event_loop.run_app(&mut app).unwrap() 68 | } 69 | 70 | struct App { 71 | app_menu: AppMenu, 72 | windows: HashMap, 73 | cursor_position: PhysicalPosition, 74 | use_window_pos: bool, 75 | } 76 | 77 | impl ApplicationHandler for App { 78 | fn resumed(&mut self, event_loop: &ActiveEventLoop) {} 79 | 80 | fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) { 81 | if cause == StartCause::Init { 82 | let window_attrs = WindowAttributes::default().with_title("Window 1"); 83 | let window = event_loop.create_window(window_attrs).unwrap(); 84 | 85 | let window_attrs2 = WindowAttributes::default().with_title("Window 2"); 86 | let window2 = event_loop.create_window(window_attrs2).unwrap(); 87 | 88 | #[cfg(target_os = "windows")] 89 | { 90 | use winit::raw_window_handle::*; 91 | if let RawWindowHandle::Win32(handle) = window.window_handle().unwrap().as_raw() { 92 | unsafe { self.app_menu.menu_bar.init_for_hwnd(handle.hwnd.get()) }; 93 | } 94 | if let RawWindowHandle::Win32(handle) = window2.window_handle().unwrap().as_raw() { 95 | unsafe { self.app_menu.menu_bar.init_for_hwnd(handle.hwnd.get()) }; 96 | } 97 | } 98 | #[cfg(target_os = "macos")] 99 | { 100 | self.app_menu.menu_bar.init_for_nsapp(); 101 | self.app_menu.window_menu.set_as_windows_menu_for_nsapp(); 102 | } 103 | 104 | self.windows.insert(window.id(), window); 105 | self.windows.insert(window2.id(), window2); 106 | } 107 | } 108 | 109 | fn window_event( 110 | &mut self, 111 | event_loop: &ActiveEventLoop, 112 | window_id: WindowId, 113 | event: WindowEvent, 114 | ) { 115 | match event { 116 | WindowEvent::CloseRequested => { 117 | self.windows.remove(&window_id); 118 | if self.windows.is_empty() { 119 | event_loop.exit(); 120 | } 121 | } 122 | 123 | WindowEvent::CursorMoved { position, .. } => { 124 | self.cursor_position = position; 125 | } 126 | 127 | WindowEvent::MouseInput { 128 | button: MouseButton::Right, 129 | state: ElementState::Pressed, 130 | .. 131 | } => { 132 | show_context_menu( 133 | self.windows.get(&window_id).unwrap(), 134 | &self.app_menu.file_menu, 135 | if self.use_window_pos { 136 | Some(self.cursor_position.into()) 137 | } else { 138 | None 139 | }, 140 | ); 141 | self.use_window_pos = !self.use_window_pos; 142 | } 143 | 144 | _ => {} 145 | } 146 | } 147 | 148 | fn user_event(&mut self, event_loop: &ActiveEventLoop, event: AppEvent) { 149 | match event { 150 | AppEvent::MenuEvent(event) => { 151 | println!("{event:?}"); 152 | 153 | if event.id == self.app_menu.custom_item.id() { 154 | let new_item = MenuItem::new("New Menu Item", true, None); 155 | self.app_menu.file_menu.insert(&new_item, 2); 156 | } 157 | } 158 | } 159 | } 160 | } 161 | 162 | struct AppMenu { 163 | menu_bar: Menu, 164 | file_menu: Submenu, 165 | edit_menu: Submenu, 166 | window_menu: Submenu, 167 | custom_item: MenuItem, 168 | } 169 | 170 | impl AppMenu { 171 | fn new(menu_bar: Menu) -> Self { 172 | #[cfg(target_os = "macos")] 173 | { 174 | let app_menu = Submenu::new("App", true); 175 | app_menu.append_items(&[ 176 | &PredefinedMenuItem::about(None, None), 177 | &PredefinedMenuItem::separator(), 178 | &PredefinedMenuItem::services(None), 179 | &PredefinedMenuItem::separator(), 180 | &PredefinedMenuItem::hide(None), 181 | &PredefinedMenuItem::hide_others(None), 182 | &PredefinedMenuItem::show_all(None), 183 | &PredefinedMenuItem::separator(), 184 | &PredefinedMenuItem::quit(None), 185 | ]); 186 | menu_bar.append(&app_menu); 187 | } 188 | 189 | let file_menu = Submenu::new("&File", true); 190 | let edit_menu = Submenu::new("&Edit", true); 191 | let window_menu = Submenu::new("&Window", true); 192 | 193 | menu_bar.append_items(&[&file_menu, &edit_menu, &window_menu]); 194 | 195 | let custom_i_1 = MenuItem::new( 196 | "C&ustom 1", 197 | true, 198 | Some(Accelerator::new(Some(Modifiers::ALT), Code::KeyC)), 199 | ); 200 | 201 | let path = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/icon.png"); 202 | let icon = load_icon(std::path::Path::new(path)); 203 | let image_item = IconMenuItem::new("Image Custom 1", true, Some(icon), None); 204 | 205 | let check_custom_i_1 = CheckMenuItem::new("Check Custom 1", true, true, None); 206 | let check_custom_i_2 = CheckMenuItem::new("Check Custom 2", false, true, None); 207 | let check_custom_i_3 = CheckMenuItem::new( 208 | "Check Custom 3", 209 | true, 210 | true, 211 | Some(Accelerator::new(Some(Modifiers::SHIFT), Code::KeyD)), 212 | ); 213 | 214 | let copy_i = PredefinedMenuItem::copy(None); 215 | let cut_i = PredefinedMenuItem::cut(None); 216 | let paste_i = PredefinedMenuItem::paste(None); 217 | 218 | file_menu.append_items(&[ 219 | &custom_i_1, 220 | &image_item, 221 | &window_menu, 222 | &PredefinedMenuItem::separator(), 223 | &check_custom_i_1, 224 | &check_custom_i_2, 225 | ]); 226 | 227 | window_menu.append_items(&[ 228 | &PredefinedMenuItem::minimize(None), 229 | &PredefinedMenuItem::maximize(None), 230 | &PredefinedMenuItem::close_window(Some("Close")), 231 | &PredefinedMenuItem::fullscreen(None), 232 | &PredefinedMenuItem::bring_all_to_front(None), 233 | &PredefinedMenuItem::about( 234 | None, 235 | Some(AboutMetadata { 236 | name: Some("winit".to_string()), 237 | version: Some("1.2.3".to_string()), 238 | copyright: Some("Copyright winit".to_string()), 239 | ..Default::default() 240 | }), 241 | ), 242 | &check_custom_i_3, 243 | &image_item, 244 | &custom_i_1, 245 | ]); 246 | 247 | edit_menu.append_items(&[©_i, &PredefinedMenuItem::separator(), &paste_i]); 248 | 249 | Self { 250 | menu_bar, 251 | file_menu, 252 | edit_menu, 253 | window_menu, 254 | custom_item: custom_i_1, 255 | } 256 | } 257 | } 258 | 259 | fn show_context_menu(window: &Window, menu: &dyn ContextMenu, position: Option) { 260 | println!("Show context menu at position {position:?}"); 261 | #[cfg(target_os = "windows")] 262 | { 263 | if let RawWindowHandle::Win32(handle) = window.window_handle().unwrap().as_raw() { 264 | unsafe { menu.show_context_menu_for_hwnd(handle.hwnd.get(), position) }; 265 | } 266 | } 267 | #[cfg(target_os = "macos")] 268 | { 269 | if let RawWindowHandle::AppKit(handle) = window.window_handle().unwrap().as_raw() { 270 | unsafe { menu.show_context_menu_for_nsview(handle.ns_view.as_ptr() as _, position) }; 271 | } 272 | } 273 | } 274 | 275 | fn load_icon(path: &std::path::Path) -> muda::Icon { 276 | let (icon_rgba, icon_width, icon_height) = { 277 | let image = image::open(path) 278 | .expect("Failed to open icon path") 279 | .into_rgba8(); 280 | let (width, height) = image.dimensions(); 281 | let rgba = image.into_raw(); 282 | (rgba, width, height) 283 | }; 284 | muda::Icon::from_rgba(icon_rgba, icon_width, icon_height).expect("Failed to open icon") 285 | } 286 | -------------------------------------------------------------------------------- /examples/wry.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(unused)] 6 | use std::rc::Rc; 7 | 8 | use muda::{ 9 | accelerator::{Accelerator, Code, Modifiers}, 10 | dpi::Position, 11 | AboutMetadata, CheckMenuItem, ContextMenu, IconMenuItem, Menu, MenuEvent, MenuItem, 12 | PredefinedMenuItem, Submenu, 13 | }; 14 | #[cfg(target_os = "macos")] 15 | use tao::platform::macos::WindowExtMacOS; 16 | #[cfg(target_os = "linux")] 17 | use tao::platform::unix::WindowExtUnix; 18 | #[cfg(target_os = "windows")] 19 | use tao::platform::windows::{EventLoopBuilderExtWindows, WindowExtWindows}; 20 | use tao::{ 21 | event::{Event, WindowEvent}, 22 | event_loop::{ControlFlow, EventLoopBuilder}, 23 | window::{Window, WindowBuilder}, 24 | }; 25 | #[cfg(target_os = "linux")] 26 | use wry::WebViewBuilderExtUnix; 27 | use wry::{http::Request, WebViewBuilder}; 28 | 29 | enum UserEvent { 30 | MenuEvent(muda::MenuEvent), 31 | } 32 | 33 | fn main() -> wry::Result<()> { 34 | let mut event_loop_builder = EventLoopBuilder::::with_user_event(); 35 | 36 | let menu_bar = Menu::new(); 37 | 38 | // setup accelerator handler on Windows 39 | #[cfg(target_os = "windows")] 40 | { 41 | let menu_bar = menu_bar.clone(); 42 | event_loop_builder.with_msg_hook(move |msg| { 43 | use windows_sys::Win32::UI::WindowsAndMessaging::{TranslateAcceleratorW, MSG}; 44 | unsafe { 45 | let msg = msg as *const MSG; 46 | let translated = TranslateAcceleratorW((*msg).hwnd, menu_bar.haccel() as _, msg); 47 | translated == 1 48 | } 49 | }); 50 | } 51 | 52 | let event_loop = event_loop_builder.build(); 53 | 54 | // set a menu event handler that wakes up the event loop 55 | let proxy = event_loop.create_proxy(); 56 | muda::MenuEvent::set_event_handler(Some(move |event| { 57 | proxy.send_event(UserEvent::MenuEvent(event)); 58 | })); 59 | 60 | let window = WindowBuilder::new() 61 | .with_title("Window 1") 62 | .build(&event_loop) 63 | .unwrap(); 64 | 65 | let window2 = WindowBuilder::new() 66 | .with_title("Window 2") 67 | .build(&event_loop) 68 | .unwrap(); 69 | 70 | #[cfg(target_os = "macos")] 71 | { 72 | let app_m = Submenu::new("App", true); 73 | menu_bar.append(&app_m).unwrap(); 74 | app_m 75 | .append_items(&[ 76 | &PredefinedMenuItem::about(None, None), 77 | &PredefinedMenuItem::separator(), 78 | &PredefinedMenuItem::services(None), 79 | &PredefinedMenuItem::separator(), 80 | &PredefinedMenuItem::hide(None), 81 | &PredefinedMenuItem::hide_others(None), 82 | &PredefinedMenuItem::show_all(None), 83 | &PredefinedMenuItem::separator(), 84 | &PredefinedMenuItem::quit(None), 85 | ]) 86 | .unwrap(); 87 | } 88 | 89 | let file_m = Submenu::new("&File", true); 90 | let edit_m = Submenu::new("&Edit", true); 91 | let window_m = Submenu::new("&Window", true); 92 | 93 | menu_bar 94 | .append_items(&[&file_m, &edit_m, &window_m]) 95 | .unwrap(); 96 | 97 | let custom_i_1 = MenuItem::new( 98 | "C&ustom 1", 99 | true, 100 | Some(Accelerator::new(Some(Modifiers::ALT), Code::KeyC)), 101 | ); 102 | 103 | let path = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/icon.png"); 104 | let icon = load_icon(std::path::Path::new(path)); 105 | let image_item = IconMenuItem::new( 106 | "Image custom 1", 107 | true, 108 | Some(icon), 109 | Some(Accelerator::new(Some(Modifiers::CONTROL), Code::KeyC)), 110 | ); 111 | 112 | let check_custom_i_1 = CheckMenuItem::new("Check Custom 1", true, true, None); 113 | let check_custom_i_2 = CheckMenuItem::new("Check Custom 2", false, true, None); 114 | let check_custom_i_3 = CheckMenuItem::new( 115 | "Check Custom 3", 116 | true, 117 | true, 118 | Some(Accelerator::new(Some(Modifiers::SHIFT), Code::KeyD)), 119 | ); 120 | 121 | let copy_i = PredefinedMenuItem::copy(None); 122 | let cut_i = PredefinedMenuItem::cut(None); 123 | let paste_i = PredefinedMenuItem::paste(None); 124 | 125 | file_m 126 | .append_items(&[ 127 | &custom_i_1, 128 | &image_item, 129 | &window_m, 130 | &PredefinedMenuItem::separator(), 131 | &check_custom_i_1, 132 | &check_custom_i_2, 133 | ]) 134 | .unwrap(); 135 | 136 | window_m 137 | .append_items(&[ 138 | &PredefinedMenuItem::minimize(None), 139 | &PredefinedMenuItem::maximize(None), 140 | &PredefinedMenuItem::close_window(Some("Close")), 141 | &PredefinedMenuItem::fullscreen(None), 142 | &PredefinedMenuItem::bring_all_to_front(None), 143 | &PredefinedMenuItem::about( 144 | None, 145 | Some(AboutMetadata { 146 | name: Some("tao".to_string()), 147 | version: Some("1.2.3".to_string()), 148 | copyright: Some("Copyright tao".to_string()), 149 | ..Default::default() 150 | }), 151 | ), 152 | &check_custom_i_3, 153 | &image_item, 154 | &custom_i_1, 155 | ]) 156 | .unwrap(); 157 | 158 | edit_m 159 | .append_items(&[ 160 | ©_i, 161 | &PredefinedMenuItem::separator(), 162 | &cut_i, 163 | &PredefinedMenuItem::separator(), 164 | &paste_i, 165 | ]) 166 | .unwrap(); 167 | 168 | #[cfg(target_os = "windows")] 169 | unsafe { 170 | menu_bar.init_for_hwnd(window.hwnd() as _).unwrap(); 171 | menu_bar.init_for_hwnd(window2.hwnd() as _).unwrap(); 172 | } 173 | #[cfg(target_os = "linux")] 174 | { 175 | menu_bar 176 | .init_for_gtk_window(window.gtk_window(), window.default_vbox()) 177 | .unwrap(); 178 | menu_bar 179 | .init_for_gtk_window(window2.gtk_window(), window2.default_vbox()) 180 | .unwrap(); 181 | } 182 | #[cfg(target_os = "macos")] 183 | { 184 | menu_bar.init_for_nsapp(); 185 | window_m.set_as_windows_menu_for_nsapp(); 186 | } 187 | 188 | #[cfg(windows)] 189 | let condition = "e.button !== 2"; 190 | #[cfg(not(windows))] 191 | let condition = "e.button == 2 && e.buttons === 0"; 192 | let html: String = format!( 193 | r#" 194 | 195 | 196 | 214 |
215 |

WRYYYYYYYYYYYYYYYYYYYYYY!

216 |
217 | 238 | 239 | 240 | "#, 241 | ); 242 | 243 | let window = Rc::new(window); 244 | let window2 = Rc::new(window2); 245 | 246 | let create_ipc_handler = |window: &Rc| { 247 | let window = window.clone(); 248 | let file_m_c = file_m.clone(); 249 | let menu_bar = menu_bar.clone(); 250 | move |req: Request| { 251 | let req = req.body(); 252 | if req == "showContextMenu" { 253 | show_context_menu(&window, &file_m_c, None) 254 | } else if let Some(rest) = req.strip_prefix("showContextMenuPos:") { 255 | let (x, mut y) = rest 256 | .split_once(',') 257 | .map(|(x, y)| (x.parse::().unwrap(), y.parse::().unwrap())) 258 | .unwrap(); 259 | 260 | #[cfg(target_os = "linux")] 261 | if let Some(menu_bar) = menu_bar 262 | .clone() 263 | .gtk_menubar_for_gtk_window(window.gtk_window()) 264 | { 265 | use gtk::prelude::*; 266 | y += menu_bar.allocated_height(); 267 | } 268 | 269 | show_context_menu(&window, &file_m_c, Some(Position::Logical((x, y).into()))) 270 | } 271 | } 272 | }; 273 | 274 | fn create_webview(window: &Rc) -> WebViewBuilder<'_> { 275 | #[cfg(not(target_os = "linux"))] 276 | return WebViewBuilder::new(window); 277 | #[cfg(target_os = "linux")] 278 | WebViewBuilder::new_gtk(window.default_vbox().unwrap()) 279 | }; 280 | 281 | let webview = create_webview(&window) 282 | .with_html(&html) 283 | .with_ipc_handler(create_ipc_handler(&window)) 284 | .build()?; 285 | let webview2 = create_webview(&window2) 286 | .with_html(html) 287 | .with_ipc_handler(create_ipc_handler(&window2)) 288 | .build()?; 289 | 290 | let menu_channel = MenuEvent::receiver(); 291 | 292 | event_loop.run(move |event, _, control_flow| { 293 | *control_flow = ControlFlow::Wait; 294 | 295 | match event { 296 | Event::WindowEvent { 297 | event: WindowEvent::CloseRequested, 298 | .. 299 | } => *control_flow = ControlFlow::Exit, 300 | 301 | Event::UserEvent(UserEvent::MenuEvent(event)) => { 302 | if event.id == custom_i_1.id() { 303 | file_m.insert(&MenuItem::new("New Menu Item", true, None), 2); 304 | } 305 | println!("{event:?}"); 306 | } 307 | _ => {} 308 | } 309 | }) 310 | } 311 | 312 | fn show_context_menu(window: &Window, menu: &dyn ContextMenu, position: Option) { 313 | println!("Show context menu at position {position:?}"); 314 | #[cfg(target_os = "windows")] 315 | unsafe { 316 | menu.show_context_menu_for_hwnd(window.hwnd() as _, position); 317 | } 318 | #[cfg(target_os = "linux")] 319 | menu.show_context_menu_for_gtk_window(window.gtk_window().as_ref(), position); 320 | #[cfg(target_os = "macos")] 321 | unsafe { 322 | menu.show_context_menu_for_nsview(window.ns_view() as _, position); 323 | } 324 | } 325 | 326 | fn load_icon(path: &std::path::Path) -> muda::Icon { 327 | let (icon_rgba, icon_width, icon_height) = { 328 | let image = image::open(path) 329 | .expect("Failed to open icon path") 330 | .into_rgba8(); 331 | let (width, height) = image.dimensions(); 332 | let rgba = image.into_raw(); 333 | (rgba, width, height) 334 | }; 335 | muda::Icon::from_rgba(icon_rgba, icon_width, icon_height).expect("Failed to open icon") 336 | } 337 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": ["config:base", ":disableDependencyDashboard"] 4 | } 5 | -------------------------------------------------------------------------------- /src/about_metadata.rs: -------------------------------------------------------------------------------- 1 | //! Types and functions to create [`AboutMetadata`] for the [`PredefinedMenuItem::about`](crate::PredefinedMenuItem::about) dialog. 2 | 3 | use crate::icon::Icon; 4 | 5 | /// Application metadata for the [`PredefinedMenuItem::about`](crate::PredefinedMenuItem::about) dialog. 6 | #[derive(Debug, Clone, Default)] 7 | pub struct AboutMetadata { 8 | /// Sets the application name. 9 | pub name: Option, 10 | /// The application version. 11 | pub version: Option, 12 | /// The short version, e.g. "1.0". 13 | /// 14 | /// ## Platform-specific 15 | /// 16 | /// - **Windows / Linux:** Appended to the end of `version` in parentheses. 17 | pub short_version: Option, 18 | /// The authors of the application. 19 | /// 20 | /// ## Platform-specific 21 | /// 22 | /// - **macOS:** Unsupported. 23 | pub authors: Option>, 24 | /// Application comments. 25 | /// 26 | /// ## Platform-specific 27 | /// 28 | /// - **macOS:** Unsupported. 29 | pub comments: Option, 30 | /// The copyright of the application. 31 | pub copyright: Option, 32 | /// The license of the application. 33 | /// 34 | /// ## Platform-specific 35 | /// 36 | /// - **macOS:** Unsupported. 37 | pub license: Option, 38 | /// The application website. 39 | /// 40 | /// ## Platform-specific 41 | /// 42 | /// - **macOS:** Unsupported. 43 | pub website: Option, 44 | /// The website label. 45 | /// 46 | /// ## Platform-specific 47 | /// 48 | /// - **macOS:** Unsupported. 49 | pub website_label: Option, 50 | /// The credits. 51 | /// 52 | /// ## Platform-specific 53 | /// 54 | /// - **Windows / Linux:** Unsupported. 55 | pub credits: Option, 56 | /// The application icon. 57 | /// 58 | /// ## Platform-specific 59 | /// 60 | /// - **Windows:** Unsupported. 61 | pub icon: Option, 62 | } 63 | 64 | impl AboutMetadata { 65 | #[allow(unused)] 66 | pub(crate) fn full_version(&self) -> Option { 67 | Some(format!( 68 | "{}{}", 69 | (self.version.as_ref())?, 70 | (self.short_version.as_ref()) 71 | .map(|v| format!(" ({v})")) 72 | .unwrap_or_default() 73 | )) 74 | } 75 | } 76 | 77 | /// Creates [`AboutMetadata`] from [Cargo metadata][cargo]. The following fields are set by this function. 78 | /// 79 | /// - [`AboutMetadata::name`] (from `CARGO_PKG_NAME`) 80 | /// - [`AboutMetadata::version`] (from `CARGO_PKG_VERSION`) 81 | /// - [`AboutMetadata::short_version`] (from `CARGO_PKG_VERSION_MAJOR` and `CARGO_PKG_VERSION_MINOR`) 82 | /// - [`AboutMetadata::authors`] (from `CARGO_PKG_AUTHORS`) 83 | /// - [`AboutMetadata::comments`] (from `CARGO_PKG_DESCRIPTION`) 84 | /// - [`AboutMetadata::license`] (from `CARGO_PKG_LICENSE`) 85 | /// - [`AboutMetadata::website`] (from `CARGO_PKG_HOMEPAGE`) 86 | /// 87 | /// [cargo]: https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates 88 | #[macro_export] 89 | #[doc(hidden)] 90 | macro_rules! from_cargo_metadata { 91 | () => {{ 92 | #[allow(unused_mut)] 93 | let mut m = $crate::about_metadata::AboutMetadata { 94 | name: Some(::std::env!("CARGO_PKG_NAME").into()), 95 | version: Some(::std::env!("CARGO_PKG_VERSION").into()), 96 | short_version: Some(::std::format!( 97 | "{}.{}", 98 | env!("CARGO_PKG_VERSION_MAJOR"), 99 | env!("CARGO_PKG_VERSION_MINOR"), 100 | )), 101 | ..::std::default::Default::default() 102 | }; 103 | 104 | #[cfg(not(target_os = "macos"))] 105 | { 106 | let authors = env!("CARGO_PKG_AUTHORS") 107 | .split(':') 108 | .map(|a| a.trim().to_string()) 109 | .collect::<::std::vec::Vec<_>>(); 110 | 111 | m.authors = if !authors.is_empty() { 112 | Some(authors) 113 | } else { 114 | None 115 | }; 116 | 117 | #[inline] 118 | fn non_empty(s: &str) -> Option { 119 | if !s.is_empty() { 120 | Some(s.to_string()) 121 | } else { 122 | None 123 | } 124 | } 125 | 126 | m.comments = non_empty(::std::env!("CARGO_PKG_DESCRIPTION")); 127 | m.license = non_empty(::std::env!("CARGO_PKG_LICENSE")); 128 | m.website = non_empty(::std::env!("CARGO_PKG_HOMEPAGE")); 129 | } 130 | 131 | m 132 | }}; 133 | } 134 | 135 | pub use from_cargo_metadata; 136 | 137 | /// A builder type for [`AboutMetadata`]. 138 | #[derive(Clone, Debug, Default)] 139 | pub struct AboutMetadataBuilder(AboutMetadata); 140 | 141 | impl AboutMetadataBuilder { 142 | pub fn new() -> Self { 143 | Default::default() 144 | } 145 | 146 | /// Sets the application name. 147 | pub fn name>(mut self, name: Option) -> Self { 148 | self.0.name = name.map(|s| s.into()); 149 | self 150 | } 151 | /// Sets the application version. 152 | pub fn version>(mut self, version: Option) -> Self { 153 | self.0.version = version.map(|s| s.into()); 154 | self 155 | } 156 | /// Sets the short version, e.g. "1.0". 157 | /// 158 | /// ## Platform-specific 159 | /// 160 | /// - **Windows / Linux:** Appended to the end of `version` in parentheses. 161 | pub fn short_version>(mut self, short_version: Option) -> Self { 162 | self.0.short_version = short_version.map(|s| s.into()); 163 | self 164 | } 165 | /// Sets the authors of the application. 166 | /// 167 | /// ## Platform-specific 168 | /// 169 | /// - **macOS:** Unsupported. 170 | pub fn authors(mut self, authors: Option>) -> Self { 171 | self.0.authors = authors; 172 | self 173 | } 174 | /// Application comments. 175 | /// 176 | /// ## Platform-specific 177 | /// 178 | /// - **macOS:** Unsupported. 179 | pub fn comments>(mut self, comments: Option) -> Self { 180 | self.0.comments = comments.map(|s| s.into()); 181 | self 182 | } 183 | /// Sets the copyright of the application. 184 | pub fn copyright>(mut self, copyright: Option) -> Self { 185 | self.0.copyright = copyright.map(|s| s.into()); 186 | self 187 | } 188 | /// Sets the license of the application. 189 | /// 190 | /// ## Platform-specific 191 | /// 192 | /// - **macOS:** Unsupported. 193 | pub fn license>(mut self, license: Option) -> Self { 194 | self.0.license = license.map(|s| s.into()); 195 | self 196 | } 197 | /// Sets the application website. 198 | /// 199 | /// ## Platform-specific 200 | /// 201 | /// - **macOS:** Unsupported. 202 | pub fn website>(mut self, website: Option) -> Self { 203 | self.0.website = website.map(|s| s.into()); 204 | self 205 | } 206 | /// Sets the website label. 207 | /// 208 | /// ## Platform-specific 209 | /// 210 | /// - **macOS:** Unsupported. 211 | pub fn website_label>(mut self, website_label: Option) -> Self { 212 | self.0.website_label = website_label.map(|s| s.into()); 213 | self 214 | } 215 | /// Sets the credits. 216 | /// 217 | /// ## Platform-specific 218 | /// 219 | /// - **Windows / Linux:** Unsupported. 220 | pub fn credits>(mut self, credits: Option) -> Self { 221 | self.0.credits = credits.map(|s| s.into()); 222 | self 223 | } 224 | /// Sets the application icon. 225 | /// 226 | /// ## Platform-specific 227 | /// 228 | /// - **Windows:** Unsupported. 229 | pub fn icon(mut self, icon: Option) -> Self { 230 | self.0.icon = icon; 231 | self 232 | } 233 | 234 | /// Construct the final [`AboutMetadata`] 235 | pub fn build(self) -> AboutMetadata { 236 | self.0 237 | } 238 | } 239 | 240 | #[cfg(test)] 241 | mod tests { 242 | 243 | #[test] 244 | fn test_build_from_metadata() { 245 | let m = from_cargo_metadata!(); 246 | assert_eq!(m.name, Some("muda".to_string())); 247 | assert!(m.version.is_some()); 248 | assert!(m.short_version.is_some()); 249 | 250 | #[cfg(not(target_os = "macos"))] 251 | { 252 | assert!(matches!(m.authors, Some(a) if !a.is_empty())); 253 | assert!(m.comments.is_some()); 254 | assert!(m.license.is_some()); 255 | // Note: `m.website` is not tested because this package doesn't have the "website" field 256 | } 257 | } 258 | } 259 | -------------------------------------------------------------------------------- /src/builders/check.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 crate::{accelerator::Accelerator, CheckMenuItem, MenuId}; 6 | 7 | /// A builder type for [`CheckMenuItem`] 8 | #[derive(Clone, Debug, Default)] 9 | pub struct CheckMenuItemBuilder { 10 | text: String, 11 | enabled: bool, 12 | checked: bool, 13 | accelerator: Option, 14 | id: Option, 15 | } 16 | 17 | impl CheckMenuItemBuilder { 18 | pub fn new() -> Self { 19 | Default::default() 20 | } 21 | 22 | /// Set the id this check menu item. 23 | pub fn id(mut self, id: MenuId) -> Self { 24 | self.id.replace(id); 25 | self 26 | } 27 | 28 | /// Set the text for this check menu item. 29 | /// 30 | /// See [`CheckMenuItem::set_text`] for more info. 31 | pub fn text>(mut self, text: S) -> Self { 32 | self.text = text.into(); 33 | self 34 | } 35 | 36 | /// Enable or disable this menu item. 37 | pub fn enabled(mut self, enabled: bool) -> Self { 38 | self.enabled = enabled; 39 | self 40 | } 41 | 42 | /// Check or uncheck this menu item. 43 | pub fn checked(mut self, checked: bool) -> Self { 44 | self.checked = checked; 45 | self 46 | } 47 | 48 | /// Set this check menu item accelerator. 49 | pub fn accelerator>( 50 | mut self, 51 | accelerator: Option, 52 | ) -> crate::Result 53 | where 54 | crate::Error: From<>::Error>, 55 | { 56 | self.accelerator = accelerator.map(|a| a.try_into()).transpose()?; 57 | Ok(self) 58 | } 59 | 60 | /// Build this check menu item. 61 | pub fn build(self) -> CheckMenuItem { 62 | if let Some(id) = self.id { 63 | CheckMenuItem::with_id(id, self.text, self.enabled, self.checked, self.accelerator) 64 | } else { 65 | CheckMenuItem::new(self.text, self.enabled, self.checked, self.accelerator) 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/builders/icon.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 crate::{ 6 | accelerator::Accelerator, 7 | icon::{Icon, NativeIcon}, 8 | IconMenuItem, MenuId, 9 | }; 10 | 11 | /// A builder type for [`IconMenuItem`] 12 | #[derive(Clone, Debug, Default)] 13 | pub struct IconMenuItemBuilder { 14 | text: String, 15 | enabled: bool, 16 | id: Option, 17 | accelerator: Option, 18 | icon: Option, 19 | native_icon: Option, 20 | } 21 | 22 | impl IconMenuItemBuilder { 23 | pub fn new() -> Self { 24 | Default::default() 25 | } 26 | 27 | /// Set the id this icon menu item. 28 | pub fn id(mut self, id: MenuId) -> Self { 29 | self.id.replace(id); 30 | self 31 | } 32 | 33 | /// Set the text for this icon menu item. 34 | /// 35 | /// See [`IconMenuItem::set_text`] for more info. 36 | pub fn text>(mut self, text: S) -> Self { 37 | self.text = text.into(); 38 | self 39 | } 40 | 41 | /// Enable or disable this menu item. 42 | pub fn enabled(mut self, enabled: bool) -> Self { 43 | self.enabled = enabled; 44 | self 45 | } 46 | 47 | /// Set this icon menu item icon. 48 | pub fn icon(mut self, icon: Option) -> Self { 49 | self.icon = icon; 50 | self.native_icon = None; 51 | self 52 | } 53 | 54 | /// Set this icon menu item native icon. 55 | pub fn native_icon(mut self, icon: Option) -> Self { 56 | self.native_icon = icon; 57 | self.icon = None; 58 | self 59 | } 60 | 61 | /// Set this icon menu item accelerator. 62 | pub fn accelerator>( 63 | mut self, 64 | accelerator: Option, 65 | ) -> crate::Result 66 | where 67 | crate::Error: From<>::Error>, 68 | { 69 | self.accelerator = accelerator.map(|a| a.try_into()).transpose()?; 70 | Ok(self) 71 | } 72 | 73 | /// Build this icon menu item. 74 | pub fn build(self) -> IconMenuItem { 75 | if let Some(id) = self.id { 76 | if self.icon.is_some() { 77 | IconMenuItem::with_id(id, self.text, self.enabled, self.icon, self.accelerator) 78 | } else { 79 | IconMenuItem::with_id_and_native_icon( 80 | id, 81 | self.text, 82 | self.enabled, 83 | self.native_icon, 84 | self.accelerator, 85 | ) 86 | } 87 | } else if self.icon.is_some() { 88 | IconMenuItem::new(self.text, self.enabled, self.icon, self.accelerator) 89 | } else { 90 | IconMenuItem::with_native_icon( 91 | self.text, 92 | self.enabled, 93 | self.native_icon, 94 | self.accelerator, 95 | ) 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/builders/mod.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 | //! A module containting builder types 6 | 7 | mod check; 8 | mod icon; 9 | mod normal; 10 | mod submenu; 11 | 12 | pub use crate::about_metadata::AboutMetadataBuilder; 13 | pub use check::*; 14 | pub use icon::*; 15 | pub use normal::*; 16 | pub use submenu::*; 17 | -------------------------------------------------------------------------------- /src/builders/normal.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 crate::{accelerator::Accelerator, MenuId, MenuItem}; 6 | 7 | /// A builder type for [`MenuItem`] 8 | #[derive(Clone, Debug, Default)] 9 | pub struct MenuItemBuilder { 10 | text: String, 11 | enabled: bool, 12 | id: Option, 13 | accelerator: Option, 14 | } 15 | 16 | impl MenuItemBuilder { 17 | pub fn new() -> Self { 18 | Default::default() 19 | } 20 | 21 | /// Set the id this menu item. 22 | pub fn id(mut self, id: MenuId) -> Self { 23 | self.id.replace(id); 24 | self 25 | } 26 | 27 | /// Set the text for this menu item. 28 | /// 29 | /// See [`MenuItem::set_text`] for more info. 30 | pub fn text>(mut self, text: S) -> Self { 31 | self.text = text.into(); 32 | self 33 | } 34 | 35 | /// Enable or disable this menu item. 36 | pub fn enabled(mut self, enabled: bool) -> Self { 37 | self.enabled = enabled; 38 | self 39 | } 40 | 41 | /// Set this menu item accelerator. 42 | pub fn accelerator>( 43 | mut self, 44 | accelerator: Option, 45 | ) -> crate::Result 46 | where 47 | crate::Error: From<>::Error>, 48 | { 49 | self.accelerator = accelerator.map(|a| a.try_into()).transpose()?; 50 | Ok(self) 51 | } 52 | 53 | /// Build this menu item. 54 | pub fn build(self) -> MenuItem { 55 | if let Some(id) = self.id { 56 | MenuItem::with_id(id, self.text, self.enabled, self.accelerator) 57 | } else { 58 | MenuItem::new(self.text, self.enabled, self.accelerator) 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/builders/submenu.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 crate::{IsMenuItem, MenuId, Submenu}; 6 | 7 | /// A builder type for [`Submenu`] 8 | #[derive(Clone, Default)] 9 | pub struct SubmenuBuilder<'a> { 10 | text: String, 11 | enabled: bool, 12 | id: Option, 13 | items: Vec<&'a dyn IsMenuItem>, 14 | } 15 | 16 | impl std::fmt::Debug for SubmenuBuilder<'_> { 17 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 18 | f.debug_struct("SubmenuBuilder") 19 | .field("text", &self.text) 20 | .field("enabled", &self.enabled) 21 | .finish() 22 | } 23 | } 24 | 25 | impl<'a> SubmenuBuilder<'a> { 26 | pub fn new() -> Self { 27 | Default::default() 28 | } 29 | 30 | /// Set the id this submenu. 31 | pub fn id(mut self, id: MenuId) -> Self { 32 | self.id.replace(id); 33 | self 34 | } 35 | 36 | /// Set the text for this submenu. 37 | /// 38 | /// See [`Submenu::set_text`] for more info. 39 | pub fn text>(mut self, text: S) -> Self { 40 | self.text = text.into(); 41 | self 42 | } 43 | 44 | /// Enable or disable this submenu. 45 | pub fn enabled(mut self, enabled: bool) -> Self { 46 | self.enabled = enabled; 47 | self 48 | } 49 | 50 | /// Add an item to this submenu. 51 | pub fn item(mut self, item: &'a dyn IsMenuItem) -> Self { 52 | self.items.push(item); 53 | self 54 | } 55 | 56 | /// Add these items to this submenu. 57 | pub fn items(mut self, items: &[&'a dyn IsMenuItem]) -> Self { 58 | self.items.extend_from_slice(items); 59 | self 60 | } 61 | 62 | /// Build this menu item. 63 | pub fn build(self) -> crate::Result { 64 | if let Some(id) = self.id { 65 | Submenu::with_id_and_items(id, self.text, self.enabled, &self.items) 66 | } else { 67 | Submenu::with_items(self.text, self.enabled, &self.items) 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /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 | pub use crate::accelerator::AcceleratorParseError; 8 | 9 | /// Errors returned by muda. 10 | #[non_exhaustive] 11 | #[derive(Error, Debug)] 12 | pub enum Error { 13 | #[error("This menu item is not a child of this `Menu` or `Submenu`")] 14 | NotAChildOfThisMenu, 15 | #[cfg(windows)] 16 | #[error("This menu has not been initialized for this hwnd`")] 17 | NotInitialized, 18 | #[cfg(all(target_os = "linux", feature = "gtk"))] 19 | #[error("This menu has not been initialized for this gtk window`")] 20 | NotInitialized, 21 | #[cfg(windows)] 22 | #[error("This menu has already been initialized for this hwnd`")] 23 | AlreadyInitialized, 24 | #[cfg(all(target_os = "linux", feature = "gtk"))] 25 | #[error("This menu has already been initialized for this gtk window`")] 26 | AlreadyInitialized, 27 | #[error(transparent)] 28 | AcceleratorParseError(#[from] AcceleratorParseError), 29 | } 30 | 31 | /// Convenient type alias of Result type for muda. 32 | pub type Result = std::result::Result; 33 | -------------------------------------------------------------------------------- /src/icon.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 | // taken from https://github.com/rust-windowing/winit/blob/92fdf5ba85f920262a61cee4590f4a11ad5738d1/src/icon.rs 6 | 7 | use crate::platform_impl::PlatformIcon; 8 | use std::{error::Error, fmt, io, mem}; 9 | 10 | #[repr(C)] 11 | #[derive(Debug)] 12 | pub(crate) struct Pixel { 13 | pub(crate) r: u8, 14 | pub(crate) g: u8, 15 | pub(crate) b: u8, 16 | pub(crate) a: u8, 17 | } 18 | 19 | pub(crate) const PIXEL_SIZE: usize = mem::size_of::(); 20 | 21 | #[derive(Debug)] 22 | /// An error produced when using [`Icon::from_rgba`] with invalid arguments. 23 | pub enum BadIcon { 24 | /// Produced when the length of the `rgba` argument isn't divisible by 4, thus `rgba` can't be 25 | /// safely interpreted as 32bpp RGBA pixels. 26 | ByteCountNotDivisibleBy4 { byte_count: usize }, 27 | /// Produced when the number of pixels (`rgba.len() / 4`) isn't equal to `width * height`. 28 | /// At least one of your arguments is incorrect. 29 | DimensionsVsPixelCount { 30 | width: u32, 31 | height: u32, 32 | width_x_height: usize, 33 | pixel_count: usize, 34 | }, 35 | /// Produced when underlying OS functionality failed to create the icon 36 | OsError(io::Error), 37 | } 38 | 39 | impl fmt::Display for BadIcon { 40 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 41 | match self { 42 | BadIcon::ByteCountNotDivisibleBy4 { byte_count } => write!(f, 43 | "The length of the `rgba` argument ({:?}) isn't divisible by 4, making it impossible to interpret as 32bpp RGBA pixels.", 44 | byte_count, 45 | ), 46 | BadIcon::DimensionsVsPixelCount { 47 | width, 48 | height, 49 | width_x_height, 50 | pixel_count, 51 | } => write!(f, 52 | "The specified dimensions ({:?}x{:?}) don't match the number of pixels supplied by the `rgba` argument ({:?}). For those dimensions, the expected pixel count is {:?}.", 53 | width, height, pixel_count, width_x_height, 54 | ), 55 | BadIcon::OsError(e) => write!(f, "OS error when instantiating the icon: {:?}", e), 56 | } 57 | } 58 | } 59 | 60 | impl Error for BadIcon { 61 | fn source(&self) -> Option<&(dyn Error + 'static)> { 62 | Some(self) 63 | } 64 | } 65 | 66 | #[derive(Debug, Clone, PartialEq, Eq)] 67 | pub(crate) struct RgbaIcon { 68 | pub(crate) rgba: Vec, 69 | pub(crate) width: u32, 70 | pub(crate) height: u32, 71 | } 72 | 73 | /// For platforms which don't have window icons (e.g. web) 74 | #[derive(Debug, Clone, PartialEq, Eq)] 75 | pub(crate) struct NoIcon; 76 | 77 | #[allow(dead_code)] // These are not used on every platform 78 | mod constructors { 79 | use super::*; 80 | 81 | impl RgbaIcon { 82 | pub fn from_rgba(rgba: Vec, width: u32, height: u32) -> Result { 83 | if rgba.len() % PIXEL_SIZE != 0 { 84 | return Err(BadIcon::ByteCountNotDivisibleBy4 { 85 | byte_count: rgba.len(), 86 | }); 87 | } 88 | let pixel_count = rgba.len() / PIXEL_SIZE; 89 | if pixel_count != (width * height) as usize { 90 | Err(BadIcon::DimensionsVsPixelCount { 91 | width, 92 | height, 93 | width_x_height: (width * height) as usize, 94 | pixel_count, 95 | }) 96 | } else { 97 | Ok(RgbaIcon { 98 | rgba, 99 | width, 100 | height, 101 | }) 102 | } 103 | } 104 | } 105 | 106 | impl NoIcon { 107 | pub fn from_rgba(rgba: Vec, width: u32, height: u32) -> Result { 108 | // Create the rgba icon anyway to validate the input 109 | let _ = RgbaIcon::from_rgba(rgba, width, height)?; 110 | Ok(NoIcon) 111 | } 112 | } 113 | } 114 | 115 | /// An icon used for the window titlebar, taskbar, etc. 116 | #[derive(Clone)] 117 | pub struct Icon { 118 | pub(crate) inner: PlatformIcon, 119 | } 120 | 121 | impl fmt::Debug for Icon { 122 | fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { 123 | fmt::Debug::fmt(&self.inner, formatter) 124 | } 125 | } 126 | 127 | impl Icon { 128 | /// Creates an icon from 32bpp RGBA data. 129 | /// 130 | /// The length of `rgba` must be divisible by 4, and `width * height` must equal 131 | /// `rgba.len() / 4`. Otherwise, this will return a `BadIcon` error. 132 | pub fn from_rgba(rgba: Vec, width: u32, height: u32) -> Result { 133 | Ok(Icon { 134 | inner: PlatformIcon::from_rgba(rgba, width, height)?, 135 | }) 136 | } 137 | 138 | /// Create an icon from a file path. 139 | /// 140 | /// Specify `size` to load a specific icon size from the file, or `None` to load the default 141 | /// icon size from the file. 142 | /// 143 | /// In cases where the specified size does not exist in the file, Windows may perform scaling 144 | /// to get an icon of the desired size. 145 | #[cfg(windows)] 146 | pub fn from_path>( 147 | path: P, 148 | size: Option<(u32, u32)>, 149 | ) -> Result { 150 | let win_icon = PlatformIcon::from_path(path, size)?; 151 | Ok(Icon { inner: win_icon }) 152 | } 153 | 154 | /// Create an icon from a resource embedded in this executable or library. 155 | /// 156 | /// Specify `size` to load a specific icon size from the file, or `None` to load the default 157 | /// icon size from the file. 158 | /// 159 | /// In cases where the specified size does not exist in the file, Windows may perform scaling 160 | /// to get an icon of the desired size. 161 | #[cfg(windows)] 162 | pub fn from_resource(ordinal: u16, size: Option<(u32, u32)>) -> Result { 163 | let win_icon = PlatformIcon::from_resource(ordinal, size)?; 164 | Ok(Icon { inner: win_icon }) 165 | } 166 | } 167 | 168 | /// A native Icon to be used for the menu item 169 | /// 170 | /// ## Platform-specific: 171 | /// 172 | /// - **Windows / Linux**: Unsupported. 173 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] 174 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 175 | pub enum NativeIcon { 176 | /// An add item template image. 177 | Add, 178 | /// Advanced preferences toolbar icon for the preferences window. 179 | Advanced, 180 | /// A Bluetooth template image. 181 | Bluetooth, 182 | /// Bookmarks image suitable for a template. 183 | Bookmarks, 184 | /// A caution image. 185 | Caution, 186 | /// A color panel toolbar icon. 187 | ColorPanel, 188 | /// A column view mode template image. 189 | ColumnView, 190 | /// A computer icon. 191 | Computer, 192 | /// An enter full-screen mode template image. 193 | EnterFullScreen, 194 | /// Permissions for all users. 195 | Everyone, 196 | /// An exit full-screen mode template image. 197 | ExitFullScreen, 198 | /// A cover flow view mode template image. 199 | FlowView, 200 | /// A folder image. 201 | Folder, 202 | /// A burnable folder icon. 203 | FolderBurnable, 204 | /// A smart folder icon. 205 | FolderSmart, 206 | /// A link template image. 207 | FollowLinkFreestanding, 208 | /// A font panel toolbar icon. 209 | FontPanel, 210 | /// A `go back` template image. 211 | GoLeft, 212 | /// A `go forward` template image. 213 | GoRight, 214 | /// Home image suitable for a template. 215 | Home, 216 | /// An iChat Theater template image. 217 | IChatTheater, 218 | /// An icon view mode template image. 219 | IconView, 220 | /// An information toolbar icon. 221 | Info, 222 | /// A template image used to denote invalid data. 223 | InvalidDataFreestanding, 224 | /// A generic left-facing triangle template image. 225 | LeftFacingTriangle, 226 | /// A list view mode template image. 227 | ListView, 228 | /// A locked padlock template image. 229 | LockLocked, 230 | /// An unlocked padlock template image. 231 | LockUnlocked, 232 | /// A horizontal dash, for use in menus. 233 | MenuMixedState, 234 | /// A check mark template image, for use in menus. 235 | MenuOnState, 236 | /// A MobileMe icon. 237 | MobileMe, 238 | /// A drag image for multiple items. 239 | MultipleDocuments, 240 | /// A network icon. 241 | Network, 242 | /// A path button template image. 243 | Path, 244 | /// General preferences toolbar icon for the preferences window. 245 | PreferencesGeneral, 246 | /// A Quick Look template image. 247 | QuickLook, 248 | /// A refresh template image. 249 | RefreshFreestanding, 250 | /// A refresh template image. 251 | Refresh, 252 | /// A remove item template image. 253 | Remove, 254 | /// A reveal contents template image. 255 | RevealFreestanding, 256 | /// A generic right-facing triangle template image. 257 | RightFacingTriangle, 258 | /// A share view template image. 259 | Share, 260 | /// A slideshow template image. 261 | Slideshow, 262 | /// A badge for a `smart` item. 263 | SmartBadge, 264 | /// Small green indicator, similar to iChat’s available image. 265 | StatusAvailable, 266 | /// Small clear indicator. 267 | StatusNone, 268 | /// Small yellow indicator, similar to iChat’s idle image. 269 | StatusPartiallyAvailable, 270 | /// Small red indicator, similar to iChat’s unavailable image. 271 | StatusUnavailable, 272 | /// A stop progress template image. 273 | StopProgressFreestanding, 274 | /// A stop progress button template image. 275 | StopProgress, 276 | /// An image of the empty trash can. 277 | TrashEmpty, 278 | /// An image of the full trash can. 279 | TrashFull, 280 | /// Permissions for a single user. 281 | User, 282 | /// User account toolbar icon for the preferences window. 283 | UserAccounts, 284 | /// Permissions for a group of users. 285 | UserGroup, 286 | /// Permissions for guests. 287 | UserGuest, 288 | } 289 | -------------------------------------------------------------------------------- /src/items/check.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2022-2022 Tauri Programme within The Commons Conservancy 2 | // SPDX-License-Identifier: Apache-2.inner 3 | // SPDX-License-Identifier: MIT 4 | 5 | use std::{cell::RefCell, mem, rc::Rc}; 6 | 7 | use crate::{accelerator::Accelerator, sealed::IsMenuItemBase, IsMenuItem, MenuId, MenuItemKind}; 8 | 9 | /// A check menu item inside a [`Menu`] or [`Submenu`] 10 | /// and usually contains a text and a check mark or a similar toggle 11 | /// that corresponds to a checked and unchecked states. 12 | /// 13 | /// [`Menu`]: crate::Menu 14 | /// [`Submenu`]: crate::Submenu 15 | #[derive(Clone)] 16 | pub struct CheckMenuItem { 17 | pub(crate) id: Rc, 18 | pub(crate) inner: Rc>, 19 | } 20 | 21 | impl IsMenuItemBase for CheckMenuItem {} 22 | impl IsMenuItem for CheckMenuItem { 23 | fn kind(&self) -> MenuItemKind { 24 | MenuItemKind::Check(self.clone()) 25 | } 26 | 27 | fn id(&self) -> &MenuId { 28 | self.id() 29 | } 30 | 31 | fn into_id(self) -> MenuId { 32 | self.into_id() 33 | } 34 | } 35 | 36 | impl CheckMenuItem { 37 | /// Create a new check menu item. 38 | /// 39 | /// - `text` could optionally contain an `&` before a character to assign this character as the mnemonic 40 | /// for this check menu item. To display a `&` without assigning a mnemenonic, use `&&`. 41 | pub fn new>( 42 | text: S, 43 | enabled: bool, 44 | checked: bool, 45 | accelerator: Option, 46 | ) -> Self { 47 | let item = crate::platform_impl::MenuChild::new_check( 48 | text.as_ref(), 49 | enabled, 50 | checked, 51 | accelerator, 52 | None, 53 | ); 54 | Self { 55 | id: Rc::new(item.id().clone()), 56 | inner: Rc::new(RefCell::new(item)), 57 | } 58 | } 59 | 60 | /// Create a new check menu item with the specified id. 61 | /// 62 | /// - `text` could optionally contain an `&` before a character to assign this character as the mnemonic 63 | /// for this check menu item. To display a `&` without assigning a mnemenonic, use `&&`. 64 | pub fn with_id, S: AsRef>( 65 | id: I, 66 | text: S, 67 | enabled: bool, 68 | checked: bool, 69 | accelerator: Option, 70 | ) -> Self { 71 | let id = id.into(); 72 | Self { 73 | id: Rc::new(id.clone()), 74 | inner: Rc::new(RefCell::new(crate::platform_impl::MenuChild::new_check( 75 | text.as_ref(), 76 | enabled, 77 | checked, 78 | accelerator, 79 | Some(id), 80 | ))), 81 | } 82 | } 83 | 84 | /// Returns a unique identifier associated with this submenu. 85 | pub fn id(&self) -> &MenuId { 86 | &self.id 87 | } 88 | 89 | /// Get the text for this check menu item. 90 | pub fn text(&self) -> String { 91 | self.inner.borrow().text() 92 | } 93 | 94 | /// Set the text for this check menu item. `text` could optionally contain 95 | /// an `&` before a character to assign this character as the mnemonic 96 | /// for this check menu item. To display a `&` without assigning a mnemenonic, use `&&`. 97 | pub fn set_text>(&self, text: S) { 98 | self.inner.borrow_mut().set_text(text.as_ref()) 99 | } 100 | 101 | /// Get whether this check menu item is enabled or not. 102 | pub fn is_enabled(&self) -> bool { 103 | self.inner.borrow().is_enabled() 104 | } 105 | 106 | /// Enable or disable this check menu item. 107 | pub fn set_enabled(&self, enabled: bool) { 108 | self.inner.borrow_mut().set_enabled(enabled) 109 | } 110 | 111 | /// Set this check menu item accelerator. 112 | pub fn set_accelerator(&self, accelerator: Option) -> crate::Result<()> { 113 | self.inner.borrow_mut().set_accelerator(accelerator) 114 | } 115 | 116 | /// Get whether this check menu item is checked or not. 117 | pub fn is_checked(&self) -> bool { 118 | self.inner.borrow().is_checked() 119 | } 120 | 121 | /// Check or Uncheck this check menu item. 122 | pub fn set_checked(&self, checked: bool) { 123 | self.inner.borrow_mut().set_checked(checked) 124 | } 125 | 126 | /// Convert this menu item into its menu ID. 127 | pub fn into_id(mut self) -> MenuId { 128 | // Note: `Rc::into_inner` is available from Rust 1.70 129 | if let Some(id) = Rc::get_mut(&mut self.id) { 130 | mem::take(id) 131 | } else { 132 | self.id().clone() 133 | } 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /src/items/icon.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2022-2022 Tauri Programme within The Commons Conservancy 2 | // SPDX-License-Identifier: Apache-2.inner 3 | // SPDX-License-Identifier: MIT 4 | 5 | use std::{cell::RefCell, mem, rc::Rc}; 6 | 7 | use crate::{ 8 | accelerator::Accelerator, 9 | icon::{Icon, NativeIcon}, 10 | sealed::IsMenuItemBase, 11 | IsMenuItem, MenuId, MenuItemKind, 12 | }; 13 | 14 | /// An icon menu item inside a [`Menu`] or [`Submenu`] 15 | /// and usually contains an icon and a text. 16 | /// 17 | /// [`Menu`]: crate::Menu 18 | /// [`Submenu`]: crate::Submenu 19 | #[derive(Clone)] 20 | pub struct IconMenuItem { 21 | pub(crate) id: Rc, 22 | pub(crate) inner: Rc>, 23 | } 24 | 25 | impl IsMenuItemBase for IconMenuItem {} 26 | impl IsMenuItem for IconMenuItem { 27 | fn kind(&self) -> MenuItemKind { 28 | MenuItemKind::Icon(self.clone()) 29 | } 30 | 31 | fn id(&self) -> &MenuId { 32 | self.id() 33 | } 34 | 35 | fn into_id(self) -> MenuId { 36 | self.into_id() 37 | } 38 | } 39 | 40 | impl IconMenuItem { 41 | /// Create a new icon menu item. 42 | /// 43 | /// - `text` could optionally contain an `&` before a character to assign this character as the mnemonic 44 | /// for this icon menu item. To display a `&` without assigning a mnemenonic, use `&&`. 45 | pub fn new>( 46 | text: S, 47 | enabled: bool, 48 | icon: Option, 49 | accelerator: Option, 50 | ) -> Self { 51 | let item = crate::platform_impl::MenuChild::new_icon( 52 | text.as_ref(), 53 | enabled, 54 | icon, 55 | accelerator, 56 | None, 57 | ); 58 | Self { 59 | id: Rc::new(item.id().clone()), 60 | inner: Rc::new(RefCell::new(item)), 61 | } 62 | } 63 | 64 | /// Create a new icon menu item with the specified id. 65 | /// 66 | /// - `text` could optionally contain an `&` before a character to assign this character as the mnemonic 67 | /// for this icon menu item. To display a `&` without assigning a mnemenonic, use `&&`. 68 | pub fn with_id, S: AsRef>( 69 | id: I, 70 | text: S, 71 | enabled: bool, 72 | icon: Option, 73 | accelerator: Option, 74 | ) -> Self { 75 | let id = id.into(); 76 | Self { 77 | id: Rc::new(id.clone()), 78 | inner: Rc::new(RefCell::new(crate::platform_impl::MenuChild::new_icon( 79 | text.as_ref(), 80 | enabled, 81 | icon, 82 | accelerator, 83 | Some(id), 84 | ))), 85 | } 86 | } 87 | 88 | /// Create a new icon menu item but with a native icon. 89 | /// 90 | /// See [`IconMenuItem::new`] for more info. 91 | /// 92 | /// ## Platform-specific: 93 | /// 94 | /// - **Windows / Linux**: Unsupported. 95 | pub fn with_native_icon>( 96 | text: S, 97 | enabled: bool, 98 | native_icon: Option, 99 | accelerator: Option, 100 | ) -> Self { 101 | let item = crate::platform_impl::MenuChild::new_native_icon( 102 | text.as_ref(), 103 | enabled, 104 | native_icon, 105 | accelerator, 106 | None, 107 | ); 108 | Self { 109 | id: Rc::new(item.id().clone()), 110 | inner: Rc::new(RefCell::new(item)), 111 | } 112 | } 113 | 114 | /// Create a new icon menu item but with the specified id and a native icon. 115 | /// 116 | /// See [`IconMenuItem::new`] for more info. 117 | /// 118 | /// ## Platform-specific: 119 | /// 120 | /// - **Windows / Linux**: Unsupported. 121 | pub fn with_id_and_native_icon, S: AsRef>( 122 | id: I, 123 | text: S, 124 | enabled: bool, 125 | native_icon: Option, 126 | accelerator: Option, 127 | ) -> Self { 128 | let id = id.into(); 129 | Self { 130 | id: Rc::new(id.clone()), 131 | inner: Rc::new(RefCell::new( 132 | crate::platform_impl::MenuChild::new_native_icon( 133 | text.as_ref(), 134 | enabled, 135 | native_icon, 136 | accelerator, 137 | Some(id), 138 | ), 139 | )), 140 | } 141 | } 142 | 143 | /// Returns a unique identifier associated with this submenu. 144 | pub fn id(&self) -> &MenuId { 145 | &self.id 146 | } 147 | 148 | /// Get the text for this check menu item. 149 | pub fn text(&self) -> String { 150 | self.inner.borrow().text() 151 | } 152 | 153 | /// Set the text for this check menu item. `text` could optionally contain 154 | /// an `&` before a character to assign this character as the mnemonic 155 | /// for this check menu item. To display a `&` without assigning a mnemenonic, use `&&`. 156 | pub fn set_text>(&self, text: S) { 157 | self.inner.borrow_mut().set_text(text.as_ref()) 158 | } 159 | 160 | /// Get whether this check menu item is enabled or not. 161 | pub fn is_enabled(&self) -> bool { 162 | self.inner.borrow().is_enabled() 163 | } 164 | 165 | /// Enable or disable this check menu item. 166 | pub fn set_enabled(&self, enabled: bool) { 167 | self.inner.borrow_mut().set_enabled(enabled) 168 | } 169 | 170 | /// Set this icon menu item accelerator. 171 | pub fn set_accelerator(&self, accelerator: Option) -> crate::Result<()> { 172 | self.inner.borrow_mut().set_accelerator(accelerator) 173 | } 174 | 175 | /// Change this menu item icon or remove it. 176 | pub fn set_icon(&self, icon: Option) { 177 | self.inner.borrow_mut().set_icon(icon) 178 | } 179 | 180 | /// Change this menu item icon to a native image or remove it. 181 | /// 182 | /// ## Platform-specific: 183 | /// 184 | /// - **Windows / Linux**: Unsupported. 185 | pub fn set_native_icon(&self, _icon: Option) { 186 | #[cfg(target_os = "macos")] 187 | self.inner.borrow_mut().set_native_icon(_icon) 188 | } 189 | 190 | /// Convert this menu item into its menu ID. 191 | pub fn into_id(mut self) -> MenuId { 192 | // Note: `Rc::into_inner` is available from Rust 1.70 193 | if let Some(id) = Rc::get_mut(&mut self.id) { 194 | mem::take(id) 195 | } else { 196 | self.id().clone() 197 | } 198 | } 199 | } 200 | -------------------------------------------------------------------------------- /src/items/mod.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 | mod check; 6 | mod icon; 7 | mod normal; 8 | mod predefined; 9 | mod submenu; 10 | 11 | pub use check::*; 12 | pub use icon::*; 13 | pub use normal::*; 14 | pub use predefined::*; 15 | pub use submenu::*; 16 | 17 | #[cfg(test)] 18 | mod test { 19 | use crate::{CheckMenuItem, IconMenuItem, MenuId, MenuItem, PredefinedMenuItem, Submenu}; 20 | 21 | #[test] 22 | #[cfg_attr(all(miri, not(target_os = "linux")), ignore)] 23 | fn it_returns_same_id() { 24 | let id = MenuId::new("1"); 25 | assert_eq!(id, MenuItem::with_id(id.clone(), "", true, None).id()); 26 | assert_eq!(id, Submenu::with_id(id.clone(), "", true).id()); 27 | assert_eq!( 28 | id, 29 | CheckMenuItem::with_id(id.clone(), "", true, true, None).id() 30 | ); 31 | assert_eq!( 32 | id, 33 | IconMenuItem::with_id(id.clone(), "", true, None, None).id() 34 | ); 35 | } 36 | 37 | #[test] 38 | #[cfg_attr(all(miri, not(target_os = "linux")), ignore)] 39 | fn test_convert_from_id_and_into_id() { 40 | let id = "TEST ID"; 41 | let expected = MenuId(id.to_string()); 42 | 43 | let item = CheckMenuItem::with_id(id, "test", true, true, None); 44 | assert_eq!(item.id(), &expected); 45 | assert_eq!(item.into_id(), expected); 46 | 47 | let item = IconMenuItem::with_id(id, "test", true, None, None); 48 | assert_eq!(item.id(), &expected); 49 | assert_eq!(item.into_id(), expected); 50 | 51 | let item = MenuItem::with_id(id, "test", true, None); 52 | assert_eq!(item.id(), &expected); 53 | assert_eq!(item.into_id(), expected); 54 | 55 | let item = Submenu::with_id(id, "test", true); 56 | assert_eq!(item.id(), &expected); 57 | assert_eq!(item.into_id(), expected); 58 | 59 | let item = PredefinedMenuItem::separator(); 60 | assert_eq!(item.id().clone(), item.into_id()); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/items/normal.rs: -------------------------------------------------------------------------------- 1 | use std::{cell::RefCell, mem, rc::Rc}; 2 | 3 | use crate::{accelerator::Accelerator, sealed::IsMenuItemBase, IsMenuItem, MenuId, MenuItemKind}; 4 | 5 | /// A menu item inside a [`Menu`] or [`Submenu`] and contains only text. 6 | /// 7 | /// [`Menu`]: crate::Menu 8 | /// [`Submenu`]: crate::Submenu 9 | #[derive(Clone)] 10 | pub struct MenuItem { 11 | pub(crate) id: Rc, 12 | pub(crate) inner: Rc>, 13 | } 14 | 15 | impl IsMenuItemBase for MenuItem {} 16 | impl IsMenuItem for MenuItem { 17 | fn kind(&self) -> MenuItemKind { 18 | MenuItemKind::MenuItem(self.clone()) 19 | } 20 | 21 | fn id(&self) -> &MenuId { 22 | self.id() 23 | } 24 | 25 | fn into_id(self) -> MenuId { 26 | self.into_id() 27 | } 28 | } 29 | 30 | impl MenuItem { 31 | /// Create a new menu item. 32 | /// 33 | /// - `text` could optionally contain an `&` before a character to assign this character as the mnemonic 34 | /// for this menu item. To display a `&` without assigning a mnemenonic, use `&&`. 35 | pub fn new>(text: S, enabled: bool, accelerator: Option) -> Self { 36 | let item = crate::platform_impl::MenuChild::new(text.as_ref(), enabled, accelerator, None); 37 | Self { 38 | id: Rc::new(item.id().clone()), 39 | inner: Rc::new(RefCell::new(item)), 40 | } 41 | } 42 | 43 | /// Create a new menu item with the specified id. 44 | /// 45 | /// - `text` could optionally contain an `&` before a character to assign this character as the mnemonic 46 | /// for this menu item. To display a `&` without assigning a mnemenonic, use `&&`. 47 | pub fn with_id, S: AsRef>( 48 | id: I, 49 | text: S, 50 | enabled: bool, 51 | accelerator: Option, 52 | ) -> Self { 53 | let id = id.into(); 54 | Self { 55 | id: Rc::new(id.clone()), 56 | inner: Rc::new(RefCell::new(crate::platform_impl::MenuChild::new( 57 | text.as_ref(), 58 | enabled, 59 | accelerator, 60 | Some(id), 61 | ))), 62 | } 63 | } 64 | 65 | /// Returns a unique identifier associated with this menu item. 66 | pub fn id(&self) -> &MenuId { 67 | &self.id 68 | } 69 | 70 | /// Set the text for this menu item. 71 | pub fn text(&self) -> String { 72 | self.inner.borrow().text() 73 | } 74 | 75 | /// Set the text for this menu item. `text` could optionally contain 76 | /// an `&` before a character to assign this character as the mnemonic 77 | /// for this menu item. To display a `&` without assigning a mnemenonic, use `&&`. 78 | pub fn set_text>(&self, text: S) { 79 | self.inner.borrow_mut().set_text(text.as_ref()) 80 | } 81 | 82 | /// Get whether this menu item is enabled or not. 83 | pub fn is_enabled(&self) -> bool { 84 | self.inner.borrow().is_enabled() 85 | } 86 | 87 | /// Enable or disable this menu item. 88 | pub fn set_enabled(&self, enabled: bool) { 89 | self.inner.borrow_mut().set_enabled(enabled) 90 | } 91 | 92 | /// Set this menu item accelerator. 93 | pub fn set_accelerator(&self, accelerator: Option) -> crate::Result<()> { 94 | self.inner.borrow_mut().set_accelerator(accelerator) 95 | } 96 | 97 | /// Convert this menu item into its menu ID. 98 | pub fn into_id(mut self) -> MenuId { 99 | // Note: `Rc::into_inner` is available from Rust 1.70 100 | if let Some(id) = Rc::get_mut(&mut self.id) { 101 | mem::take(id) 102 | } else { 103 | self.id().clone() 104 | } 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/items/predefined.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2022-2022 Tauri Programme within The Commons Conservancy 2 | // SPDX-License-Identifier: Apache-2.inner 3 | // SPDX-License-Identifier: MIT 4 | 5 | use std::{cell::RefCell, mem, rc::Rc}; 6 | 7 | use crate::{ 8 | accelerator::{Accelerator, CMD_OR_CTRL}, 9 | sealed::IsMenuItemBase, 10 | AboutMetadata, IsMenuItem, MenuId, MenuItemKind, 11 | }; 12 | use keyboard_types::{Code, Modifiers}; 13 | 14 | /// A predefined (native) menu item which has a predfined behavior by the OS or by this crate. 15 | #[derive(Clone)] 16 | pub struct PredefinedMenuItem { 17 | pub(crate) id: Rc, 18 | pub(crate) inner: Rc>, 19 | } 20 | 21 | impl IsMenuItemBase for PredefinedMenuItem {} 22 | impl IsMenuItem for PredefinedMenuItem { 23 | fn kind(&self) -> MenuItemKind { 24 | MenuItemKind::Predefined(self.clone()) 25 | } 26 | 27 | fn id(&self) -> &MenuId { 28 | self.id() 29 | } 30 | 31 | fn into_id(self) -> MenuId { 32 | self.into_id() 33 | } 34 | } 35 | 36 | impl PredefinedMenuItem { 37 | /// Separator menu item 38 | pub fn separator() -> PredefinedMenuItem { 39 | PredefinedMenuItem::new::<&str>(PredefinedMenuItemType::Separator, None) 40 | } 41 | 42 | /// Copy menu item 43 | pub fn copy(text: Option<&str>) -> PredefinedMenuItem { 44 | PredefinedMenuItem::new(PredefinedMenuItemType::Copy, text) 45 | } 46 | 47 | /// Cut menu item 48 | pub fn cut(text: Option<&str>) -> PredefinedMenuItem { 49 | PredefinedMenuItem::new(PredefinedMenuItemType::Cut, text) 50 | } 51 | 52 | /// Paste menu item 53 | pub fn paste(text: Option<&str>) -> PredefinedMenuItem { 54 | PredefinedMenuItem::new(PredefinedMenuItemType::Paste, text) 55 | } 56 | 57 | /// SelectAll menu item 58 | pub fn select_all(text: Option<&str>) -> PredefinedMenuItem { 59 | PredefinedMenuItem::new(PredefinedMenuItemType::SelectAll, text) 60 | } 61 | 62 | /// Undo menu item 63 | /// 64 | /// ## Platform-specific: 65 | /// 66 | /// - **Windows / Linux:** Unsupported. 67 | pub fn undo(text: Option<&str>) -> PredefinedMenuItem { 68 | PredefinedMenuItem::new(PredefinedMenuItemType::Undo, text) 69 | } 70 | /// Redo menu item 71 | /// 72 | /// ## Platform-specific: 73 | /// 74 | /// - **Windows / Linux:** Unsupported. 75 | pub fn redo(text: Option<&str>) -> PredefinedMenuItem { 76 | PredefinedMenuItem::new(PredefinedMenuItemType::Redo, text) 77 | } 78 | 79 | /// Minimize window menu item 80 | /// 81 | /// ## Platform-specific: 82 | /// 83 | /// - **Linux:** Unsupported. 84 | pub fn minimize(text: Option<&str>) -> PredefinedMenuItem { 85 | PredefinedMenuItem::new(PredefinedMenuItemType::Minimize, text) 86 | } 87 | 88 | /// Maximize window menu item 89 | /// 90 | /// ## Platform-specific: 91 | /// 92 | /// - **Linux:** Unsupported. 93 | pub fn maximize(text: Option<&str>) -> PredefinedMenuItem { 94 | PredefinedMenuItem::new(PredefinedMenuItemType::Maximize, text) 95 | } 96 | 97 | /// Fullscreen menu item 98 | /// 99 | /// ## Platform-specific: 100 | /// 101 | /// - **Windows / Linux:** Unsupported. 102 | pub fn fullscreen(text: Option<&str>) -> PredefinedMenuItem { 103 | PredefinedMenuItem::new(PredefinedMenuItemType::Fullscreen, text) 104 | } 105 | 106 | /// Hide window menu item 107 | /// 108 | /// ## Platform-specific: 109 | /// 110 | /// - **Linux:** Unsupported. 111 | pub fn hide(text: Option<&str>) -> PredefinedMenuItem { 112 | PredefinedMenuItem::new(PredefinedMenuItemType::Hide, text) 113 | } 114 | 115 | /// Hide other windows menu item 116 | /// 117 | /// ## Platform-specific: 118 | /// 119 | /// - **Linux:** Unsupported. 120 | pub fn hide_others(text: Option<&str>) -> PredefinedMenuItem { 121 | PredefinedMenuItem::new(PredefinedMenuItemType::HideOthers, text) 122 | } 123 | 124 | /// Show all app windows menu item 125 | /// 126 | /// ## Platform-specific: 127 | /// 128 | /// - **Windows / Linux:** Unsupported. 129 | pub fn show_all(text: Option<&str>) -> PredefinedMenuItem { 130 | PredefinedMenuItem::new(PredefinedMenuItemType::ShowAll, text) 131 | } 132 | 133 | /// Close window menu item 134 | /// 135 | /// ## Platform-specific: 136 | /// 137 | /// - **Linux:** Unsupported. 138 | pub fn close_window(text: Option<&str>) -> PredefinedMenuItem { 139 | PredefinedMenuItem::new(PredefinedMenuItemType::CloseWindow, text) 140 | } 141 | 142 | /// Quit app menu item 143 | /// 144 | /// ## Platform-specific: 145 | /// 146 | /// - **Linux:** Unsupported. 147 | pub fn quit(text: Option<&str>) -> PredefinedMenuItem { 148 | PredefinedMenuItem::new(PredefinedMenuItemType::Quit, text) 149 | } 150 | 151 | /// About app menu item 152 | pub fn about(text: Option<&str>, metadata: Option) -> PredefinedMenuItem { 153 | PredefinedMenuItem::new(PredefinedMenuItemType::About(metadata), text) 154 | } 155 | 156 | /// Services menu item 157 | /// 158 | /// ## Platform-specific: 159 | /// 160 | /// - **Windows / Linux:** Unsupported. 161 | pub fn services(text: Option<&str>) -> PredefinedMenuItem { 162 | PredefinedMenuItem::new(PredefinedMenuItemType::Services, text) 163 | } 164 | 165 | /// 'Bring all to front' menu item 166 | /// 167 | /// ## Platform-specific: 168 | /// 169 | /// - **Windows / Linux:** Unsupported. 170 | pub fn bring_all_to_front(text: Option<&str>) -> PredefinedMenuItem { 171 | PredefinedMenuItem::new(PredefinedMenuItemType::BringAllToFront, text) 172 | } 173 | 174 | fn new>(item: PredefinedMenuItemType, text: Option) -> Self { 175 | let item = crate::platform_impl::MenuChild::new_predefined( 176 | item, 177 | text.map(|t| t.as_ref().to_string()), 178 | ); 179 | Self { 180 | id: Rc::new(item.id().clone()), 181 | inner: Rc::new(RefCell::new(item)), 182 | } 183 | } 184 | 185 | /// Returns a unique identifier associated with this predefined menu item. 186 | pub fn id(&self) -> &MenuId { 187 | &self.id 188 | } 189 | 190 | /// Get the text for this predefined menu item. 191 | pub fn text(&self) -> String { 192 | self.inner.borrow().text() 193 | } 194 | 195 | /// Set the text for this predefined menu item. 196 | pub fn set_text>(&self, text: S) { 197 | self.inner.borrow_mut().set_text(text.as_ref()) 198 | } 199 | 200 | /// Convert this menu item into its menu ID. 201 | pub fn into_id(mut self) -> MenuId { 202 | // Note: `Rc::into_inner` is available from Rust 1.70 203 | if let Some(id) = Rc::get_mut(&mut self.id) { 204 | mem::take(id) 205 | } else { 206 | self.id().clone() 207 | } 208 | } 209 | } 210 | 211 | #[test] 212 | fn test_about_metadata() { 213 | assert_eq!( 214 | AboutMetadata { 215 | ..Default::default() 216 | } 217 | .full_version(), 218 | None 219 | ); 220 | 221 | assert_eq!( 222 | AboutMetadata { 223 | version: Some("Version: 1.inner".into()), 224 | ..Default::default() 225 | } 226 | .full_version(), 227 | Some("Version: 1.inner".into()) 228 | ); 229 | 230 | assert_eq!( 231 | AboutMetadata { 232 | version: Some("Version: 1.inner".into()), 233 | short_version: Some("Universal".into()), 234 | ..Default::default() 235 | } 236 | .full_version(), 237 | Some("Version: 1.inner (Universal)".into()) 238 | ); 239 | } 240 | 241 | #[derive(Debug, Clone)] 242 | #[non_exhaustive] 243 | #[allow(clippy::large_enum_variant)] 244 | pub(crate) enum PredefinedMenuItemType { 245 | Separator, 246 | Copy, 247 | Cut, 248 | Paste, 249 | SelectAll, 250 | Undo, 251 | Redo, 252 | Minimize, 253 | Maximize, 254 | Fullscreen, 255 | Hide, 256 | HideOthers, 257 | ShowAll, 258 | CloseWindow, 259 | Quit, 260 | About(Option), 261 | Services, 262 | BringAllToFront, 263 | None, 264 | } 265 | 266 | impl Default for PredefinedMenuItemType { 267 | fn default() -> Self { 268 | Self::None 269 | } 270 | } 271 | 272 | impl PredefinedMenuItemType { 273 | pub(crate) fn text(&self) -> &str { 274 | match self { 275 | PredefinedMenuItemType::Separator => "", 276 | PredefinedMenuItemType::Copy => "&Copy", 277 | PredefinedMenuItemType::Cut => "Cu&t", 278 | PredefinedMenuItemType::Paste => "&Paste", 279 | PredefinedMenuItemType::SelectAll => "Select &All", 280 | PredefinedMenuItemType::Undo => "Undo", 281 | PredefinedMenuItemType::Redo => "Redo", 282 | PredefinedMenuItemType::Minimize => "&Minimize", 283 | #[cfg(target_os = "macos")] 284 | PredefinedMenuItemType::Maximize => "Zoom", 285 | #[cfg(not(target_os = "macos"))] 286 | PredefinedMenuItemType::Maximize => "Ma&ximize", 287 | PredefinedMenuItemType::Fullscreen => "Toggle Full Screen", 288 | PredefinedMenuItemType::Hide => "&Hide", 289 | PredefinedMenuItemType::HideOthers => "Hide Others", 290 | PredefinedMenuItemType::ShowAll => "Show All", 291 | #[cfg(windows)] 292 | PredefinedMenuItemType::CloseWindow => "Close", 293 | #[cfg(not(windows))] 294 | PredefinedMenuItemType::CloseWindow => "C&lose Window", 295 | #[cfg(windows)] 296 | PredefinedMenuItemType::Quit => "&Exit", 297 | #[cfg(not(windows))] 298 | PredefinedMenuItemType::Quit => "&Quit", 299 | PredefinedMenuItemType::About(_) => "&About", 300 | PredefinedMenuItemType::Services => "Services", 301 | PredefinedMenuItemType::BringAllToFront => "Bring All to Front", 302 | PredefinedMenuItemType::None => "", 303 | } 304 | } 305 | 306 | pub(crate) fn accelerator(&self) -> Option { 307 | match self { 308 | PredefinedMenuItemType::Copy => Some(Accelerator::new(Some(CMD_OR_CTRL), Code::KeyC)), 309 | PredefinedMenuItemType::Cut => Some(Accelerator::new(Some(CMD_OR_CTRL), Code::KeyX)), 310 | PredefinedMenuItemType::Paste => Some(Accelerator::new(Some(CMD_OR_CTRL), Code::KeyV)), 311 | PredefinedMenuItemType::Undo => Some(Accelerator::new(Some(CMD_OR_CTRL), Code::KeyZ)), 312 | #[cfg(target_os = "macos")] 313 | PredefinedMenuItemType::Redo => Some(Accelerator::new( 314 | Some(CMD_OR_CTRL | Modifiers::SHIFT), 315 | Code::KeyZ, 316 | )), 317 | #[cfg(not(target_os = "macos"))] 318 | PredefinedMenuItemType::Redo => Some(Accelerator::new(Some(CMD_OR_CTRL), Code::KeyY)), 319 | PredefinedMenuItemType::SelectAll => { 320 | Some(Accelerator::new(Some(CMD_OR_CTRL), Code::KeyA)) 321 | } 322 | PredefinedMenuItemType::Minimize => { 323 | Some(Accelerator::new(Some(CMD_OR_CTRL), Code::KeyM)) 324 | } 325 | #[cfg(target_os = "macos")] 326 | PredefinedMenuItemType::Fullscreen => Some(Accelerator::new( 327 | Some(Modifiers::META | Modifiers::CONTROL), 328 | Code::KeyF, 329 | )), 330 | PredefinedMenuItemType::Hide => Some(Accelerator::new(Some(CMD_OR_CTRL), Code::KeyH)), 331 | PredefinedMenuItemType::HideOthers => Some(Accelerator::new( 332 | Some(CMD_OR_CTRL | Modifiers::ALT), 333 | Code::KeyH, 334 | )), 335 | #[cfg(target_os = "macos")] 336 | PredefinedMenuItemType::CloseWindow => { 337 | Some(Accelerator::new(Some(CMD_OR_CTRL), Code::KeyW)) 338 | } 339 | #[cfg(not(target_os = "macos"))] 340 | PredefinedMenuItemType::CloseWindow => { 341 | Some(Accelerator::new(Some(Modifiers::ALT), Code::F4)) 342 | } 343 | #[cfg(target_os = "macos")] 344 | PredefinedMenuItemType::Quit => Some(Accelerator::new(Some(CMD_OR_CTRL), Code::KeyQ)), 345 | _ => None, 346 | } 347 | } 348 | } 349 | -------------------------------------------------------------------------------- /src/items/submenu.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2022-2022 Tauri Programme within The Commons Conservancy 2 | // SPDX-License-Identifier: Apache-2.inner 3 | // SPDX-License-Identifier: MIT 4 | 5 | use std::{cell::RefCell, mem, rc::Rc}; 6 | 7 | use crate::{ 8 | dpi::Position, sealed::IsMenuItemBase, util::AddOp, ContextMenu, IsMenuItem, MenuId, 9 | MenuItemKind, 10 | }; 11 | 12 | /// A menu that can be added to a [`Menu`] or another [`Submenu`]. 13 | /// 14 | /// [`Menu`]: crate::Menu 15 | #[derive(Clone)] 16 | pub struct Submenu { 17 | pub(crate) id: Rc, 18 | pub(crate) inner: Rc>, 19 | } 20 | 21 | impl IsMenuItemBase for Submenu {} 22 | impl IsMenuItem for Submenu { 23 | fn kind(&self) -> MenuItemKind { 24 | MenuItemKind::Submenu(self.clone()) 25 | } 26 | 27 | fn id(&self) -> &MenuId { 28 | self.id() 29 | } 30 | 31 | fn into_id(self) -> MenuId { 32 | self.into_id() 33 | } 34 | } 35 | 36 | impl Submenu { 37 | /// Create a new submenu. 38 | /// 39 | /// - `text` could optionally contain an `&` before a character to assign this character as the mnemonic 40 | /// for this submenu. To display a `&` without assigning a mnemenonic, use `&&`. 41 | pub fn new>(text: S, enabled: bool) -> Self { 42 | let submenu = crate::platform_impl::MenuChild::new_submenu(text.as_ref(), enabled, None); 43 | Self { 44 | id: Rc::new(submenu.id().clone()), 45 | inner: Rc::new(RefCell::new(submenu)), 46 | } 47 | } 48 | 49 | /// Create a new submenu with the specified id. 50 | /// 51 | /// - `text` could optionally contain an `&` before a character to assign this character as the mnemonic 52 | /// for this submenu. To display a `&` without assigning a mnemenonic, use `&&`. 53 | pub fn with_id, S: AsRef>(id: I, text: S, enabled: bool) -> Self { 54 | let id = id.into(); 55 | 56 | Self { 57 | id: Rc::new(id.clone()), 58 | inner: Rc::new(RefCell::new(crate::platform_impl::MenuChild::new_submenu( 59 | text.as_ref(), 60 | enabled, 61 | Some(id), 62 | ))), 63 | } 64 | } 65 | 66 | /// Creates a new submenu with given `items`. It calls [`Submenu::new`] and [`Submenu::append_items`] internally. 67 | pub fn with_items>( 68 | text: S, 69 | enabled: bool, 70 | items: &[&dyn IsMenuItem], 71 | ) -> crate::Result { 72 | let menu = Self::new(text, enabled); 73 | menu.append_items(items)?; 74 | Ok(menu) 75 | } 76 | 77 | /// Creates a new submenu with the specified id and given `items`. It calls [`Submenu::new`] and [`Submenu::append_items`] internally. 78 | pub fn with_id_and_items, S: AsRef>( 79 | id: I, 80 | text: S, 81 | enabled: bool, 82 | items: &[&dyn IsMenuItem], 83 | ) -> crate::Result { 84 | let menu = Self::with_id(id, text, enabled); 85 | menu.append_items(items)?; 86 | Ok(menu) 87 | } 88 | 89 | /// Returns a unique identifier associated with this submenu. 90 | pub fn id(&self) -> &MenuId { 91 | &self.id 92 | } 93 | 94 | /// Add a menu item to the end of this menu. 95 | pub fn append(&self, item: &dyn IsMenuItem) -> crate::Result<()> { 96 | self.inner.borrow_mut().add_menu_item(item, AddOp::Append) 97 | } 98 | 99 | /// Add menu items to the end of this submenu. It calls [`Submenu::append`] in a loop. 100 | pub fn append_items(&self, items: &[&dyn IsMenuItem]) -> crate::Result<()> { 101 | for item in items { 102 | self.append(*item)? 103 | } 104 | 105 | Ok(()) 106 | } 107 | 108 | /// Add a menu item to the beginning of this submenu. 109 | pub fn prepend(&self, item: &dyn IsMenuItem) -> crate::Result<()> { 110 | self.inner 111 | .borrow_mut() 112 | .add_menu_item(item, AddOp::Insert(0)) 113 | } 114 | 115 | /// Add menu items to the beginning of this submenu. 116 | /// It calls [`Menu::prepend`](crate::Menu::prepend) on the first element and 117 | /// passes the rest to [`Menu::insert_items`](crate::Menu::insert_items) with position of `1`. 118 | pub fn prepend_items(&self, items: &[&dyn IsMenuItem]) -> crate::Result<()> { 119 | self.insert_items(items, 0) 120 | } 121 | 122 | /// Insert a menu item at the specified `postion` in the submenu. 123 | pub fn insert(&self, item: &dyn IsMenuItem, position: usize) -> crate::Result<()> { 124 | self.inner 125 | .borrow_mut() 126 | .add_menu_item(item, AddOp::Insert(position)) 127 | } 128 | 129 | /// Insert menu items at the specified `postion` in the submenu. 130 | pub fn insert_items(&self, items: &[&dyn IsMenuItem], position: usize) -> crate::Result<()> { 131 | for (i, item) in items.iter().enumerate() { 132 | self.insert(*item, position + i)? 133 | } 134 | 135 | Ok(()) 136 | } 137 | 138 | /// Remove a menu item from this submenu. 139 | pub fn remove(&self, item: &dyn IsMenuItem) -> crate::Result<()> { 140 | self.inner.borrow_mut().remove(item) 141 | } 142 | 143 | /// Remove the menu item at the specified position from this submenu and returns it. 144 | pub fn remove_at(&self, position: usize) -> Option { 145 | let mut items = self.items(); 146 | if items.len() > position { 147 | let item = items.remove(position); 148 | let _ = self.remove(item.as_ref()); 149 | Some(item) 150 | } else { 151 | None 152 | } 153 | } 154 | 155 | /// Returns a list of menu items that has been added to this submenu. 156 | pub fn items(&self) -> Vec { 157 | self.inner.borrow().items() 158 | } 159 | 160 | /// Get the text for this submenu. 161 | pub fn text(&self) -> String { 162 | self.inner.borrow().text() 163 | } 164 | 165 | /// Set the text for this submenu. `text` could optionally contain 166 | /// an `&` before a character to assign this character as the mnemonic 167 | /// for this submenu. To display a `&` without assigning a mnemenonic, use `&&`. 168 | pub fn set_text>(&self, text: S) { 169 | self.inner.borrow_mut().set_text(text.as_ref()) 170 | } 171 | 172 | /// Get whether this submenu is enabled or not. 173 | pub fn is_enabled(&self) -> bool { 174 | self.inner.borrow().is_enabled() 175 | } 176 | 177 | /// Enable or disable this submenu. 178 | pub fn set_enabled(&self, enabled: bool) { 179 | self.inner.borrow_mut().set_enabled(enabled) 180 | } 181 | 182 | /// Set this submenu as the Window menu for the application on macOS. 183 | /// 184 | /// This will cause macOS to automatically add window-switching items and 185 | /// certain other items to the menu. 186 | #[cfg(target_os = "macos")] 187 | pub fn set_as_windows_menu_for_nsapp(&self) { 188 | self.inner.borrow_mut().set_as_windows_menu_for_nsapp() 189 | } 190 | 191 | /// Set this submenu as the Help menu for the application on macOS. 192 | /// 193 | /// This will cause macOS to automatically add a search box to the menu. 194 | /// 195 | /// If no menu is set as the Help menu, macOS will automatically use any menu 196 | /// which has a title matching the localized word "Help". 197 | #[cfg(target_os = "macos")] 198 | pub fn set_as_help_menu_for_nsapp(&self) { 199 | self.inner.borrow_mut().set_as_help_menu_for_nsapp() 200 | } 201 | 202 | /// Convert this submenu into its menu ID. 203 | pub fn into_id(mut self) -> MenuId { 204 | // Note: `Rc::into_inner` is available from Rust 1.70 205 | if let Some(id) = Rc::get_mut(&mut self.id) { 206 | mem::take(id) 207 | } else { 208 | self.id().clone() 209 | } 210 | } 211 | } 212 | 213 | impl ContextMenu for Submenu { 214 | #[cfg(target_os = "windows")] 215 | fn hpopupmenu(&self) -> isize { 216 | self.inner.borrow().hpopupmenu() 217 | } 218 | 219 | #[cfg(target_os = "windows")] 220 | unsafe fn show_context_menu_for_hwnd(&self, hwnd: isize, position: Option) -> bool { 221 | self.inner 222 | .borrow_mut() 223 | .show_context_menu_for_hwnd(hwnd, position) 224 | } 225 | 226 | #[cfg(target_os = "windows")] 227 | unsafe fn attach_menu_subclass_for_hwnd(&self, hwnd: isize) { 228 | self.inner.borrow().attach_menu_subclass_for_hwnd(hwnd) 229 | } 230 | 231 | #[cfg(target_os = "windows")] 232 | unsafe fn detach_menu_subclass_from_hwnd(&self, hwnd: isize) { 233 | self.inner.borrow().detach_menu_subclass_from_hwnd(hwnd) 234 | } 235 | 236 | #[cfg(all(target_os = "linux", feature = "gtk"))] 237 | fn show_context_menu_for_gtk_window( 238 | &self, 239 | w: >k::Window, 240 | position: Option, 241 | ) -> bool { 242 | self.inner 243 | .borrow_mut() 244 | .show_context_menu_for_gtk_window(w, position) 245 | } 246 | 247 | #[cfg(all(target_os = "linux", feature = "gtk"))] 248 | fn gtk_context_menu(&self) -> gtk::Menu { 249 | self.inner.borrow_mut().gtk_context_menu() 250 | } 251 | 252 | #[cfg(target_os = "macos")] 253 | unsafe fn show_context_menu_for_nsview( 254 | &self, 255 | view: *const std::ffi::c_void, 256 | position: Option, 257 | ) -> bool { 258 | self.inner 259 | .borrow_mut() 260 | .show_context_menu_for_nsview(view, position) 261 | } 262 | 263 | #[cfg(target_os = "macos")] 264 | fn ns_menu(&self) -> *mut std::ffi::c_void { 265 | self.inner.borrow().ns_menu() 266 | } 267 | 268 | fn as_submenu(&self) -> Option<&Submenu> { 269 | Some(self) 270 | } 271 | } 272 | -------------------------------------------------------------------------------- /src/menu.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2022-2022 Tauri Programme within The Commons Conservancy 2 | // SPDX-License-Identifier: Apache-2.inner 3 | // SPDX-License-Identifier: MIT 4 | 5 | use std::{cell::RefCell, rc::Rc}; 6 | 7 | use crate::{dpi::Position, util::AddOp, ContextMenu, IsMenuItem, MenuId, MenuItemKind}; 8 | 9 | /// A root menu that can be added to a Window on Windows and Linux 10 | /// and used as the app global menu on macOS. 11 | #[derive(Clone)] 12 | pub struct Menu { 13 | id: Rc, 14 | inner: Rc>, 15 | } 16 | 17 | impl Default for Menu { 18 | fn default() -> Self { 19 | Self::new() 20 | } 21 | } 22 | 23 | impl Menu { 24 | /// Creates a new menu. 25 | pub fn new() -> Self { 26 | let menu = crate::platform_impl::Menu::new(None); 27 | Self { 28 | id: Rc::new(menu.id().clone()), 29 | inner: Rc::new(RefCell::new(menu)), 30 | } 31 | } 32 | 33 | /// Creates a new menu with the specified id. 34 | pub fn with_id>(id: I) -> Self { 35 | let id = id.into(); 36 | Self { 37 | id: Rc::new(id.clone()), 38 | inner: Rc::new(RefCell::new(crate::platform_impl::Menu::new(Some(id)))), 39 | } 40 | } 41 | 42 | /// Creates a new menu with given `items`. It calls [`Menu::new`] and [`Menu::append_items`] internally. 43 | pub fn with_items(items: &[&dyn IsMenuItem]) -> crate::Result { 44 | let menu = Self::new(); 45 | menu.append_items(items)?; 46 | Ok(menu) 47 | } 48 | 49 | /// Creates a new menu with the specified id and given `items`. It calls [`Menu::new`] and [`Menu::append_items`] internally. 50 | pub fn with_id_and_items>( 51 | id: I, 52 | items: &[&dyn IsMenuItem], 53 | ) -> crate::Result { 54 | let menu = Self::with_id(id); 55 | menu.append_items(items)?; 56 | Ok(menu) 57 | } 58 | 59 | /// Returns a unique identifier associated with this menu. 60 | pub fn id(&self) -> &MenuId { 61 | &self.id 62 | } 63 | 64 | /// Add a menu item to the end of this menu. 65 | /// 66 | /// ## Platform-spcific: 67 | /// 68 | /// - **macOS:** Only [`Submenu`] can be added to the menu 69 | /// 70 | /// [`Submenu`]: crate::Submenu 71 | pub fn append(&self, item: &dyn IsMenuItem) -> crate::Result<()> { 72 | self.inner.borrow_mut().add_menu_item(item, AddOp::Append) 73 | } 74 | 75 | /// Add menu items to the end of this menu. It calls [`Menu::append`] in a loop internally. 76 | /// 77 | /// ## Platform-spcific: 78 | /// 79 | /// - **macOS:** Only [`Submenu`] can be added to the menu 80 | /// 81 | /// [`Submenu`]: crate::Submenu 82 | pub fn append_items(&self, items: &[&dyn IsMenuItem]) -> crate::Result<()> { 83 | for item in items { 84 | self.append(*item)? 85 | } 86 | 87 | Ok(()) 88 | } 89 | 90 | /// Add a menu item to the beginning of this menu. 91 | /// 92 | /// ## Platform-spcific: 93 | /// 94 | /// - **macOS:** Only [`Submenu`] can be added to the menu 95 | /// 96 | /// [`Submenu`]: crate::Submenu 97 | pub fn prepend(&self, item: &dyn IsMenuItem) -> crate::Result<()> { 98 | self.inner 99 | .borrow_mut() 100 | .add_menu_item(item, AddOp::Insert(0)) 101 | } 102 | 103 | /// Add menu items to the beginning of this menu. It calls [`Menu::insert_items`] with position of `0` internally. 104 | /// 105 | /// ## Platform-spcific: 106 | /// 107 | /// - **macOS:** Only [`Submenu`] can be added to the menu 108 | /// 109 | /// [`Submenu`]: crate::Submenu 110 | pub fn prepend_items(&self, items: &[&dyn IsMenuItem]) -> crate::Result<()> { 111 | self.insert_items(items, 0) 112 | } 113 | 114 | /// Insert a menu item at the specified `postion` in the menu. 115 | /// 116 | /// ## Platform-spcific: 117 | /// 118 | /// - **macOS:** Only [`Submenu`] can be added to the menu 119 | /// 120 | /// [`Submenu`]: crate::Submenu 121 | pub fn insert(&self, item: &dyn IsMenuItem, position: usize) -> crate::Result<()> { 122 | self.inner 123 | .borrow_mut() 124 | .add_menu_item(item, AddOp::Insert(position)) 125 | } 126 | 127 | /// Insert menu items at the specified `postion` in the menu. 128 | /// 129 | /// ## Platform-spcific: 130 | /// 131 | /// - **macOS:** Only [`Submenu`] can be added to the menu 132 | /// 133 | /// [`Submenu`]: crate::Submenu 134 | pub fn insert_items(&self, items: &[&dyn IsMenuItem], position: usize) -> crate::Result<()> { 135 | for (i, item) in items.iter().enumerate() { 136 | self.insert(*item, position + i)? 137 | } 138 | 139 | Ok(()) 140 | } 141 | 142 | /// Remove a menu item from this menu. 143 | pub fn remove(&self, item: &dyn IsMenuItem) -> crate::Result<()> { 144 | self.inner.borrow_mut().remove(item) 145 | } 146 | 147 | /// Remove the menu item at the specified position from this menu and returns it. 148 | pub fn remove_at(&self, position: usize) -> Option { 149 | let mut items = self.items(); 150 | if items.len() > position { 151 | let item = items.remove(position); 152 | let _ = self.remove(item.as_ref()); 153 | Some(item) 154 | } else { 155 | None 156 | } 157 | } 158 | 159 | /// Returns a list of menu items that has been added to this menu. 160 | pub fn items(&self) -> Vec { 161 | self.inner.borrow().items() 162 | } 163 | 164 | /// Adds this menu to a [`gtk::Window`] 165 | /// 166 | /// - `container`: this is an optional paramter to specify a container for the [`gtk::MenuBar`], 167 | /// it is highly recommended to pass a container, otherwise the menubar will be added directly to the window, 168 | /// which is usually not the desired behavior. 169 | /// If using a [`gtk::Box`] as a container, it is added using [`Box::pack_start(menubar, false, false, 0)`](gtk::prelude::BoxExt::pack_start) then 170 | /// reordered to be the first child of [`gtk::Box`] using [`Box::reorder_child(menubar, 0)`](gtk::prelude::BoxExt::reorder_child). 171 | /// 172 | /// ## Example: 173 | /// ```no_run 174 | /// let window = gtk::Window::builder().build(); 175 | /// let vbox = gtk::Box::new(gtk::Orientation::Vertical, 0); 176 | /// let menu = muda::Menu::new(); 177 | /// // -- snip, add your menu items -- 178 | /// menu.init_for_gtk_window(&window, Some(&vbox)); 179 | /// // then proceed to add your widgets to the `vbox` 180 | /// ``` 181 | /// 182 | /// ## Panics: 183 | /// 184 | /// Panics if the gtk event loop hasn't been initialized on the thread. 185 | #[cfg(all(target_os = "linux", feature = "gtk"))] 186 | pub fn init_for_gtk_window(&self, window: &W, container: Option<&C>) -> crate::Result<()> 187 | where 188 | W: gtk::prelude::IsA, 189 | W: gtk::prelude::IsA, 190 | C: gtk::prelude::IsA, 191 | { 192 | self.inner 193 | .borrow_mut() 194 | .init_for_gtk_window(window, container) 195 | } 196 | 197 | /// Adds this menu to a win32 window. 198 | /// 199 | /// # Safety 200 | /// 201 | /// The `hwnd` must be a valid window HWND. 202 | /// 203 | /// ## Note about accelerators: 204 | /// 205 | /// For accelerators to work, the event loop needs to call 206 | /// [`TranslateAcceleratorW`](windows_sys::Win32::UI::WindowsAndMessaging::TranslateAcceleratorW) 207 | /// with the [`HACCEL`](windows_sys::Win32::UI::WindowsAndMessaging::HACCEL) returned from [`Menu::haccel`] 208 | /// 209 | /// #### Example: 210 | /// ```no_run 211 | /// # use muda::Menu; 212 | /// # use windows_sys::Win32::UI::WindowsAndMessaging::{MSG, GetMessageW, TranslateMessage, DispatchMessageW, TranslateAcceleratorW}; 213 | /// let menu = Menu::new(); 214 | /// unsafe { 215 | /// let mut msg: MSG = std::mem::zeroed(); 216 | /// while GetMessageW(&mut msg, std::ptr::null_mut(), 0, 0) == 1 { 217 | /// let translated = TranslateAcceleratorW(msg.hwnd, menu.haccel() as _, &msg as *const _); 218 | /// if translated != 1{ 219 | /// TranslateMessage(&msg); 220 | /// DispatchMessageW(&msg); 221 | /// } 222 | /// } 223 | /// } 224 | /// ``` 225 | #[cfg(target_os = "windows")] 226 | pub unsafe fn init_for_hwnd(&self, hwnd: isize) -> crate::Result<()> { 227 | self.inner.borrow_mut().init_for_hwnd(hwnd) 228 | } 229 | 230 | /// Adds this menu to a win32 window using the specified theme. 231 | /// 232 | /// See [Menu::init_for_hwnd] for more info. 233 | /// 234 | /// Note that the theme only affects the menu bar itself and not submenus or context menu. 235 | /// 236 | /// # Safety 237 | /// 238 | /// The `hwnd` must be a valid window HWND. 239 | #[cfg(target_os = "windows")] 240 | pub unsafe fn init_for_hwnd_with_theme( 241 | &self, 242 | hwnd: isize, 243 | theme: MenuTheme, 244 | ) -> crate::Result<()> { 245 | self.inner 246 | .borrow_mut() 247 | .init_for_hwnd_with_theme(hwnd, theme) 248 | } 249 | 250 | /// Set a theme for the menu bar on this window. 251 | /// 252 | /// Note that the theme only affects the menu bar itself and not submenus or context menu. 253 | /// 254 | /// # Safety 255 | /// 256 | /// The `hwnd` must be a valid window HWND. 257 | #[cfg(target_os = "windows")] 258 | pub unsafe fn set_theme_for_hwnd(&self, hwnd: isize, theme: MenuTheme) -> crate::Result<()> { 259 | self.inner.borrow().set_theme_for_hwnd(hwnd, theme) 260 | } 261 | 262 | /// Returns The [`HACCEL`](windows_sys::Win32::UI::WindowsAndMessaging::HACCEL) associated with this menu 263 | /// It can be used with [`TranslateAcceleratorW`](windows_sys::Win32::UI::WindowsAndMessaging::TranslateAcceleratorW) 264 | /// in the event loop to enable accelerators 265 | /// 266 | /// The returned [`HACCEL`](windows_sys::Win32::UI::WindowsAndMessaging::HACCEL) is valid as long as the [Menu] is. 267 | #[cfg(target_os = "windows")] 268 | pub fn haccel(&self) -> isize { 269 | self.inner.borrow_mut().haccel() 270 | } 271 | 272 | /// Removes this menu from a [`gtk::Window`] 273 | #[cfg(all(target_os = "linux", feature = "gtk"))] 274 | pub fn remove_for_gtk_window(&self, window: &W) -> crate::Result<()> 275 | where 276 | W: gtk::prelude::IsA, 277 | { 278 | self.inner.borrow_mut().remove_for_gtk_window(window) 279 | } 280 | 281 | /// Removes this menu from a win32 window 282 | /// 283 | /// # Safety 284 | /// 285 | /// The `hwnd` must be a valid window HWND. 286 | #[cfg(target_os = "windows")] 287 | pub unsafe fn remove_for_hwnd(&self, hwnd: isize) -> crate::Result<()> { 288 | self.inner.borrow_mut().remove_for_hwnd(hwnd) 289 | } 290 | 291 | /// Hides this menu from a [`gtk::Window`] 292 | #[cfg(all(target_os = "linux", feature = "gtk"))] 293 | pub fn hide_for_gtk_window(&self, window: &W) -> crate::Result<()> 294 | where 295 | W: gtk::prelude::IsA, 296 | { 297 | self.inner.borrow_mut().hide_for_gtk_window(window) 298 | } 299 | 300 | /// Hides this menu from a win32 window 301 | /// 302 | /// # Safety 303 | /// 304 | /// The `hwnd` must be a valid window HWND. 305 | #[cfg(target_os = "windows")] 306 | pub unsafe fn hide_for_hwnd(&self, hwnd: isize) -> crate::Result<()> { 307 | self.inner.borrow().hide_for_hwnd(hwnd) 308 | } 309 | 310 | /// Shows this menu on a [`gtk::Window`] 311 | #[cfg(all(target_os = "linux", feature = "gtk"))] 312 | pub fn show_for_gtk_window(&self, window: &W) -> crate::Result<()> 313 | where 314 | W: gtk::prelude::IsA, 315 | { 316 | self.inner.borrow_mut().show_for_gtk_window(window) 317 | } 318 | 319 | /// Shows this menu on a win32 window 320 | /// 321 | /// # Safety 322 | /// 323 | /// The `hwnd` must be a valid window HWND. 324 | #[cfg(target_os = "windows")] 325 | pub unsafe fn show_for_hwnd(&self, hwnd: isize) -> crate::Result<()> { 326 | self.inner.borrow().show_for_hwnd(hwnd) 327 | } 328 | 329 | /// Returns whether this menu visible on a [`gtk::Window`] 330 | #[cfg(all(target_os = "linux", feature = "gtk"))] 331 | pub fn is_visible_on_gtk_window(&self, window: &W) -> bool 332 | where 333 | W: gtk::prelude::IsA, 334 | { 335 | self.inner.borrow().is_visible_on_gtk_window(window) 336 | } 337 | 338 | #[cfg(all(target_os = "linux", feature = "gtk"))] 339 | /// Returns the [`gtk::MenuBar`] that is associated with this window if it exists. 340 | /// This is useful to get information about the menubar for example its height. 341 | pub fn gtk_menubar_for_gtk_window(self, window: &W) -> Option 342 | where 343 | W: gtk::prelude::IsA, 344 | { 345 | self.inner.borrow().gtk_menubar_for_gtk_window(window) 346 | } 347 | 348 | /// Returns whether this menu visible on a on a win32 window 349 | /// 350 | /// # Safety 351 | /// 352 | /// The `hwnd` must be a valid window HWND. 353 | #[cfg(target_os = "windows")] 354 | pub unsafe fn is_visible_on_hwnd(&self, hwnd: isize) -> bool { 355 | self.inner.borrow().is_visible_on_hwnd(hwnd) 356 | } 357 | 358 | /// Adds this menu to an NSApp. 359 | #[cfg(target_os = "macos")] 360 | pub fn init_for_nsapp(&self) { 361 | self.inner.borrow_mut().init_for_nsapp() 362 | } 363 | 364 | /// Removes this menu from an NSApp. 365 | #[cfg(target_os = "macos")] 366 | pub fn remove_for_nsapp(&self) { 367 | self.inner.borrow_mut().remove_for_nsapp() 368 | } 369 | } 370 | 371 | impl ContextMenu for Menu { 372 | #[cfg(target_os = "windows")] 373 | fn hpopupmenu(&self) -> isize { 374 | self.inner.borrow().hpopupmenu() 375 | } 376 | 377 | #[cfg(target_os = "windows")] 378 | unsafe fn show_context_menu_for_hwnd(&self, hwnd: isize, position: Option) -> bool { 379 | self.inner 380 | .borrow_mut() 381 | .show_context_menu_for_hwnd(hwnd, position) 382 | } 383 | 384 | #[cfg(target_os = "windows")] 385 | unsafe fn attach_menu_subclass_for_hwnd(&self, hwnd: isize) { 386 | self.inner.borrow().attach_menu_subclass_for_hwnd(hwnd) 387 | } 388 | 389 | #[cfg(target_os = "windows")] 390 | unsafe fn detach_menu_subclass_from_hwnd(&self, hwnd: isize) { 391 | self.inner.borrow().detach_menu_subclass_from_hwnd(hwnd) 392 | } 393 | 394 | #[cfg(all(target_os = "linux", feature = "gtk"))] 395 | fn show_context_menu_for_gtk_window( 396 | &self, 397 | window: >k::Window, 398 | position: Option, 399 | ) -> bool { 400 | self.inner 401 | .borrow_mut() 402 | .show_context_menu_for_gtk_window(window, position) 403 | } 404 | 405 | #[cfg(all(target_os = "linux", feature = "gtk"))] 406 | fn gtk_context_menu(&self) -> gtk::Menu { 407 | self.inner.borrow_mut().gtk_context_menu() 408 | } 409 | 410 | #[cfg(target_os = "macos")] 411 | unsafe fn show_context_menu_for_nsview( 412 | &self, 413 | view: *const std::ffi::c_void, 414 | position: Option, 415 | ) -> bool { 416 | self.inner 417 | .borrow_mut() 418 | .show_context_menu_for_nsview(view, position) 419 | } 420 | 421 | #[cfg(target_os = "macos")] 422 | fn ns_menu(&self) -> *mut std::ffi::c_void { 423 | self.inner.borrow().ns_menu() 424 | } 425 | 426 | fn as_menu(&self) -> Option<&Menu> { 427 | Some(self) 428 | } 429 | } 430 | 431 | /// The window menu bar theme 432 | #[cfg(windows)] 433 | #[repr(usize)] 434 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] 435 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 436 | pub enum MenuTheme { 437 | Dark = 0, 438 | Light = 1, 439 | Auto = 2, 440 | } 441 | -------------------------------------------------------------------------------- /src/menu_id.rs: -------------------------------------------------------------------------------- 1 | use std::{convert::Infallible, str::FromStr}; 2 | 3 | /// An unique id that is associated with a menu or a menu item. 4 | #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Default, Hash)] 5 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 6 | pub struct MenuId(pub String); 7 | 8 | impl MenuId { 9 | /// Create a new menu id. 10 | pub fn new>(id: S) -> Self { 11 | Self(id.as_ref().to_string()) 12 | } 13 | } 14 | 15 | impl AsRef for MenuId { 16 | fn as_ref(&self) -> &str { 17 | self.0.as_ref() 18 | } 19 | } 20 | 21 | impl From for MenuId { 22 | fn from(value: T) -> Self { 23 | Self::new(value.to_string()) 24 | } 25 | } 26 | 27 | impl FromStr for MenuId { 28 | type Err = Infallible; 29 | 30 | fn from_str(s: &str) -> std::result::Result { 31 | Ok(Self::new(s)) 32 | } 33 | } 34 | 35 | impl PartialEq<&str> for MenuId { 36 | fn eq(&self, other: &&str) -> bool { 37 | self.0 == *other 38 | } 39 | } 40 | 41 | impl PartialEq<&str> for &MenuId { 42 | fn eq(&self, other: &&str) -> bool { 43 | self.0 == *other 44 | } 45 | } 46 | 47 | impl PartialEq for MenuId { 48 | fn eq(&self, other: &String) -> bool { 49 | self.0 == *other 50 | } 51 | } 52 | 53 | impl PartialEq for &MenuId { 54 | fn eq(&self, other: &String) -> bool { 55 | self.0 == *other 56 | } 57 | } 58 | 59 | impl PartialEq<&String> for MenuId { 60 | fn eq(&self, other: &&String) -> bool { 61 | self.0 == **other 62 | } 63 | } 64 | 65 | impl PartialEq<&MenuId> for MenuId { 66 | fn eq(&self, other: &&MenuId) -> bool { 67 | other.0 == self.0 68 | } 69 | } 70 | 71 | #[cfg(test)] 72 | mod test { 73 | use crate::MenuId; 74 | 75 | #[test] 76 | fn is_eq() { 77 | assert_eq!(MenuId::new("t"), "t",); 78 | assert_eq!(MenuId::new("t"), String::from("t")); 79 | assert_eq!(MenuId::new("t"), &String::from("t")); 80 | assert_eq!(MenuId::new("t"), MenuId::new("t")); 81 | assert_eq!(MenuId::new("t"), &MenuId::new("t")); 82 | assert_eq!(&MenuId::new("t"), &MenuId::new("t")); 83 | assert_eq!(MenuId::new("t").as_ref(), "t"); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/platform_impl/gtk/accelerator.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 gtk::gdk; 6 | use keyboard_types::{Code, Modifiers}; 7 | 8 | use crate::accelerator::{Accelerator, AcceleratorParseError}; 9 | 10 | pub fn to_gtk_mnemonic>(string: S) -> String { 11 | string 12 | .as_ref() 13 | .replace("&&", "[~~]") 14 | .replace('&', "_") 15 | .replace("[~~]", "&&") 16 | .replace("[~~]", "&") 17 | } 18 | 19 | pub fn from_gtk_mnemonic>(string: S) -> String { 20 | string 21 | .as_ref() 22 | .replace("__", "[~~]") 23 | .replace('_', "&") 24 | .replace("[~~]", "__") 25 | } 26 | 27 | pub fn parse_accelerator( 28 | accelerator: &Accelerator, 29 | ) -> Result<(gdk::ModifierType, u32), AcceleratorParseError> { 30 | let key = match &accelerator.key { 31 | Code::KeyA => 'A' as u32, 32 | Code::KeyB => 'B' as u32, 33 | Code::KeyC => 'C' as u32, 34 | Code::KeyD => 'D' as u32, 35 | Code::KeyE => 'E' as u32, 36 | Code::KeyF => 'F' as u32, 37 | Code::KeyG => 'G' as u32, 38 | Code::KeyH => 'H' as u32, 39 | Code::KeyI => 'I' as u32, 40 | Code::KeyJ => 'J' as u32, 41 | Code::KeyK => 'K' as u32, 42 | Code::KeyL => 'L' as u32, 43 | Code::KeyM => 'M' as u32, 44 | Code::KeyN => 'N' as u32, 45 | Code::KeyO => 'O' as u32, 46 | Code::KeyP => 'P' as u32, 47 | Code::KeyQ => 'Q' as u32, 48 | Code::KeyR => 'R' as u32, 49 | Code::KeyS => 'S' as u32, 50 | Code::KeyT => 'T' as u32, 51 | Code::KeyU => 'U' as u32, 52 | Code::KeyV => 'V' as u32, 53 | Code::KeyW => 'W' as u32, 54 | Code::KeyX => 'X' as u32, 55 | Code::KeyY => 'Y' as u32, 56 | Code::KeyZ => 'Z' as u32, 57 | Code::Digit0 => '0' as u32, 58 | Code::Digit1 => '1' as u32, 59 | Code::Digit2 => '2' as u32, 60 | Code::Digit3 => '3' as u32, 61 | Code::Digit4 => '4' as u32, 62 | Code::Digit5 => '5' as u32, 63 | Code::Digit6 => '6' as u32, 64 | Code::Digit7 => '7' as u32, 65 | Code::Digit8 => '8' as u32, 66 | Code::Digit9 => '9' as u32, 67 | Code::Comma => ',' as u32, 68 | Code::Minus => '-' as u32, 69 | Code::Period => '.' as u32, 70 | Code::Space => ' ' as u32, 71 | Code::Equal => '=' as u32, 72 | Code::Semicolon => ';' as u32, 73 | Code::Slash => '/' as u32, 74 | Code::Backslash => '\\' as u32, 75 | Code::Quote => '\'' as u32, 76 | Code::Backquote => '`' as u32, 77 | Code::BracketLeft => '[' as u32, 78 | Code::BracketRight => ']' as u32, 79 | key => { 80 | if let Some(gdk_key) = key_to_raw_key(key) { 81 | *gdk_key 82 | } else { 83 | return Err(AcceleratorParseError::UnsupportedKey(key.to_string())); 84 | } 85 | } 86 | }; 87 | 88 | Ok((modifiers_to_gdk_modifier_type(accelerator.mods), key)) 89 | } 90 | 91 | fn modifiers_to_gdk_modifier_type(modifiers: Modifiers) -> gdk::ModifierType { 92 | let mut result = gdk::ModifierType::empty(); 93 | 94 | result.set( 95 | gdk::ModifierType::MOD1_MASK, 96 | modifiers.contains(Modifiers::ALT), 97 | ); 98 | result.set( 99 | gdk::ModifierType::CONTROL_MASK, 100 | modifiers.contains(Modifiers::CONTROL), 101 | ); 102 | result.set( 103 | gdk::ModifierType::SHIFT_MASK, 104 | modifiers.contains(Modifiers::SHIFT), 105 | ); 106 | result.set( 107 | gdk::ModifierType::META_MASK, 108 | modifiers.contains(Modifiers::SUPER), 109 | ); 110 | 111 | result 112 | } 113 | 114 | fn key_to_raw_key(src: &Code) -> Option { 115 | use gdk::keys::constants::*; 116 | Some(match src { 117 | Code::Escape => Escape, 118 | Code::Backspace => BackSpace, 119 | 120 | Code::Tab => Tab, 121 | Code::Enter => Return, 122 | 123 | Code::ControlLeft => Control_L, 124 | Code::AltLeft => Alt_L, 125 | Code::ShiftLeft => Shift_L, 126 | Code::MetaLeft => Super_L, 127 | 128 | Code::ControlRight => Control_R, 129 | Code::AltRight => Alt_R, 130 | Code::ShiftRight => Shift_R, 131 | Code::MetaRight => Super_R, 132 | 133 | Code::CapsLock => Caps_Lock, 134 | Code::F1 => F1, 135 | Code::F2 => F2, 136 | Code::F3 => F3, 137 | Code::F4 => F4, 138 | Code::F5 => F5, 139 | Code::F6 => F6, 140 | Code::F7 => F7, 141 | Code::F8 => F8, 142 | Code::F9 => F9, 143 | Code::F10 => F10, 144 | Code::F11 => F11, 145 | Code::F12 => F12, 146 | Code::F13 => F13, 147 | Code::F14 => F14, 148 | Code::F15 => F15, 149 | Code::F16 => F16, 150 | Code::F17 => F17, 151 | Code::F18 => F18, 152 | Code::F19 => F19, 153 | Code::F20 => F20, 154 | Code::F21 => F21, 155 | Code::F22 => F22, 156 | Code::F23 => F23, 157 | Code::F24 => F24, 158 | 159 | Code::PrintScreen => Print, 160 | Code::ScrollLock => Scroll_Lock, 161 | // Pause/Break not audio. 162 | Code::Pause => Pause, 163 | 164 | Code::Insert => Insert, 165 | Code::Delete => Delete, 166 | Code::Home => Home, 167 | Code::End => End, 168 | Code::PageUp => Page_Up, 169 | Code::PageDown => Page_Down, 170 | 171 | Code::NumLock => Num_Lock, 172 | 173 | Code::ArrowUp => Up, 174 | Code::ArrowDown => Down, 175 | Code::ArrowLeft => Left, 176 | Code::ArrowRight => Right, 177 | 178 | Code::ContextMenu => Menu, 179 | Code::WakeUp => WakeUp, 180 | _ => return None, 181 | }) 182 | } 183 | -------------------------------------------------------------------------------- /src/platform_impl/gtk/icon.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2014-2021 The winit contributors 2 | // Copyright 2021-2022 Tauri Programme within The Commons Conservancy 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | use gtk::gdk_pixbuf::{Colorspace, Pixbuf}; 6 | 7 | use crate::icon::BadIcon; 8 | 9 | /// An icon used for the window titlebar, taskbar, etc. 10 | #[derive(Debug, Clone)] 11 | pub struct PlatformIcon { 12 | raw: Vec, 13 | width: i32, 14 | height: i32, 15 | row_stride: i32, 16 | } 17 | 18 | impl From for Pixbuf { 19 | fn from(icon: PlatformIcon) -> Self { 20 | Pixbuf::from_mut_slice( 21 | icon.raw, 22 | gtk::gdk_pixbuf::Colorspace::Rgb, 23 | true, 24 | 8, 25 | icon.width, 26 | icon.height, 27 | icon.row_stride, 28 | ) 29 | } 30 | } 31 | 32 | impl PlatformIcon { 33 | /// Creates an `Icon` from 32bpp RGBA data. 34 | /// 35 | /// The length of `rgba` must be divisible by 4, and `width * height` must equal 36 | /// `rgba.len() / 4`. Otherwise, this will return a `BadIcon` error. 37 | pub fn from_rgba(rgba: Vec, width: u32, height: u32) -> Result { 38 | let row_stride = 39 | Pixbuf::calculate_rowstride(Colorspace::Rgb, true, 8, width as i32, height as i32); 40 | Ok(Self { 41 | raw: rgba, 42 | width: width as i32, 43 | height: height as i32, 44 | row_stride, 45 | }) 46 | } 47 | 48 | pub fn to_pixbuf(&self) -> Pixbuf { 49 | Pixbuf::from_mut_slice( 50 | self.raw.clone(), 51 | gtk::gdk_pixbuf::Colorspace::Rgb, 52 | true, 53 | 8, 54 | self.width, 55 | self.height, 56 | self.row_stride, 57 | ) 58 | } 59 | 60 | pub fn to_pixbuf_scale(&self, w: i32, h: i32) -> Pixbuf { 61 | self.to_pixbuf() 62 | .scale_simple(w, h, gtk::gdk_pixbuf::InterpType::Bilinear) 63 | .unwrap() 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/platform_impl/macos/accelerator.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 keyboard_types::{Code, Modifiers}; 6 | use objc2_app_kit::NSEventModifierFlags; 7 | 8 | use crate::accelerator::{Accelerator, AcceleratorParseError}; 9 | 10 | impl Accelerator { 11 | /// Return the string value of this hotkey, without modifiers. 12 | /// 13 | /// Returns the empty string if no key equivalent is known. 14 | pub fn key_equivalent(self) -> Result { 15 | Ok(match self.key { 16 | Code::KeyA => "a".into(), 17 | Code::KeyB => "b".into(), 18 | Code::KeyC => "c".into(), 19 | Code::KeyD => "d".into(), 20 | Code::KeyE => "e".into(), 21 | Code::KeyF => "f".into(), 22 | Code::KeyG => "g".into(), 23 | Code::KeyH => "h".into(), 24 | Code::KeyI => "i".into(), 25 | Code::KeyJ => "j".into(), 26 | Code::KeyK => "k".into(), 27 | Code::KeyL => "l".into(), 28 | Code::KeyM => "m".into(), 29 | Code::KeyN => "n".into(), 30 | Code::KeyO => "o".into(), 31 | Code::KeyP => "p".into(), 32 | Code::KeyQ => "q".into(), 33 | Code::KeyR => "r".into(), 34 | Code::KeyS => "s".into(), 35 | Code::KeyT => "t".into(), 36 | Code::KeyU => "u".into(), 37 | Code::KeyV => "v".into(), 38 | Code::KeyW => "w".into(), 39 | Code::KeyX => "x".into(), 40 | Code::KeyY => "y".into(), 41 | Code::KeyZ => "z".into(), 42 | Code::Digit0 => "0".into(), 43 | Code::Digit1 => "1".into(), 44 | Code::Digit2 => "2".into(), 45 | Code::Digit3 => "3".into(), 46 | Code::Digit4 => "4".into(), 47 | Code::Digit5 => "5".into(), 48 | Code::Digit6 => "6".into(), 49 | Code::Digit7 => "7".into(), 50 | Code::Digit8 => "8".into(), 51 | Code::Digit9 => "9".into(), 52 | Code::Comma => ",".into(), 53 | Code::Minus => "-".into(), 54 | Code::Period => ".".into(), 55 | Code::Space => "\u{0020}".into(), 56 | Code::Equal => "=".into(), 57 | Code::Semicolon => ";".into(), 58 | Code::Slash => "/".into(), 59 | Code::Backslash => "\\".into(), 60 | Code::Quote => "\'".into(), 61 | Code::Backquote => "`".into(), 62 | Code::BracketLeft => "[".into(), 63 | Code::BracketRight => "]".into(), 64 | Code::Tab => "⇥".into(), 65 | Code::Escape => "\u{001b}".into(), 66 | // from NSText.h 67 | Code::Enter => "\u{0003}".into(), 68 | Code::Backspace => "\u{0008}".into(), 69 | Code::Delete => "\u{007f}".into(), 70 | // from NSEvent.h 71 | Code::Insert => "\u{F727}".into(), 72 | Code::Home => "\u{F729}".into(), 73 | Code::End => "\u{F72B}".into(), 74 | Code::PageUp => "\u{F72C}".into(), 75 | Code::PageDown => "\u{F72D}".into(), 76 | Code::PrintScreen => "\u{F72E}".into(), 77 | Code::ScrollLock => "\u{F72F}".into(), 78 | Code::ArrowUp => "\u{F700}".into(), 79 | Code::ArrowDown => "\u{F701}".into(), 80 | Code::ArrowLeft => "\u{F702}".into(), 81 | Code::ArrowRight => "\u{F703}".into(), 82 | Code::F1 => "\u{F704}".into(), 83 | Code::F2 => "\u{F705}".into(), 84 | Code::F3 => "\u{F706}".into(), 85 | Code::F4 => "\u{F707}".into(), 86 | Code::F5 => "\u{F708}".into(), 87 | Code::F6 => "\u{F709}".into(), 88 | Code::F7 => "\u{F70A}".into(), 89 | Code::F8 => "\u{F70B}".into(), 90 | Code::F9 => "\u{F70C}".into(), 91 | Code::F10 => "\u{F70D}".into(), 92 | Code::F11 => "\u{F70E}".into(), 93 | Code::F12 => "\u{F70F}".into(), 94 | Code::F13 => "\u{F710}".into(), 95 | Code::F14 => "\u{F711}".into(), 96 | Code::F15 => "\u{F712}".into(), 97 | Code::F16 => "\u{F713}".into(), 98 | Code::F17 => "\u{F714}".into(), 99 | Code::F18 => "\u{F715}".into(), 100 | Code::F19 => "\u{F716}".into(), 101 | Code::F20 => "\u{F717}".into(), 102 | Code::F21 => "\u{F718}".into(), 103 | Code::F22 => "\u{F719}".into(), 104 | Code::F23 => "\u{F71A}".into(), 105 | Code::F24 => "\u{F71B}".into(), 106 | key => return Err(AcceleratorParseError::UnsupportedKey(key.to_string())), 107 | }) 108 | } 109 | 110 | /// Return the modifiers of this hotkey, as an NSEventModifierFlags bitflag. 111 | pub fn key_modifier_mask(self) -> NSEventModifierFlags { 112 | let mods: Modifiers = self.mods; 113 | let mut flags = NSEventModifierFlags::empty(); 114 | if mods.contains(Modifiers::SHIFT) { 115 | flags.insert(NSEventModifierFlags::Shift); 116 | } 117 | if mods.contains(Modifiers::SUPER) { 118 | flags.insert(NSEventModifierFlags::Command); 119 | } 120 | if mods.contains(Modifiers::ALT) { 121 | flags.insert(NSEventModifierFlags::Option); 122 | } 123 | if mods.contains(Modifiers::CONTROL) { 124 | flags.insert(NSEventModifierFlags::Control); 125 | } 126 | flags 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /src/platform_impl/macos/icon.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 objc2::{rc::Retained, AllocAnyThread}; 6 | use objc2_app_kit::NSImage; 7 | use objc2_core_foundation::CGFloat; 8 | use objc2_foundation::{NSData, NSSize}; 9 | 10 | use crate::icon::{BadIcon, RgbaIcon}; 11 | use std::io::Cursor; 12 | 13 | #[derive(Debug, Clone)] 14 | pub struct PlatformIcon(RgbaIcon); 15 | 16 | impl PlatformIcon { 17 | pub fn from_rgba(rgba: Vec, width: u32, height: u32) -> Result { 18 | Ok(PlatformIcon(RgbaIcon::from_rgba(rgba, width, height)?)) 19 | } 20 | 21 | pub fn get_size(&self) -> (u32, u32) { 22 | (self.0.width, self.0.height) 23 | } 24 | 25 | pub fn to_png(&self) -> Vec { 26 | let mut png = Vec::new(); 27 | 28 | { 29 | let mut encoder = 30 | png::Encoder::new(Cursor::new(&mut png), self.0.width as _, self.0.height as _); 31 | encoder.set_color(png::ColorType::Rgba); 32 | encoder.set_depth(png::BitDepth::Eight); 33 | 34 | let mut writer = encoder.write_header().unwrap(); 35 | writer.write_image_data(&self.0.rgba).unwrap(); 36 | } 37 | 38 | png 39 | } 40 | 41 | pub fn to_nsimage(&self, fixed_height: Option) -> Retained { 42 | let (width, height) = self.get_size(); 43 | let icon = self.to_png(); 44 | 45 | let (icon_width, icon_height) = match fixed_height { 46 | Some(fixed_height) => { 47 | let icon_height: CGFloat = fixed_height as CGFloat; 48 | let icon_width: CGFloat = (width as CGFloat) / (height as CGFloat / icon_height); 49 | 50 | (icon_width, icon_height) 51 | } 52 | 53 | None => (width as CGFloat, height as CGFloat), 54 | }; 55 | 56 | let nsdata = NSData::with_bytes(&icon); 57 | 58 | let nsimage = NSImage::initWithData(NSImage::alloc(), &nsdata).unwrap(); 59 | let new_size = NSSize::new(icon_width, icon_height); 60 | unsafe { nsimage.setSize(new_size) }; 61 | 62 | nsimage 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/platform_impl/macos/util.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 std::str; 6 | 7 | /// Strips single `&` characters from the string. 8 | /// 9 | /// `&` can be escaped as `&&` to prevent stripping, in which case a single `&` will be output. 10 | pub fn strip_mnemonic>(string: S) -> String { 11 | string 12 | .as_ref() 13 | .replace("&&", "[~~]") 14 | .replace('&', "") 15 | .replace("[~~]", "&") 16 | } 17 | -------------------------------------------------------------------------------- /src/platform_impl/mod.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 | #[cfg(target_os = "windows")] 6 | #[path = "windows/mod.rs"] 7 | mod platform; 8 | #[cfg(all(target_os = "linux", feature = "gtk"))] 9 | #[path = "gtk/mod.rs"] 10 | mod platform; 11 | #[cfg(target_os = "macos")] 12 | #[path = "macos/mod.rs"] 13 | mod platform; 14 | 15 | use std::{ 16 | cell::{Ref, RefCell, RefMut}, 17 | rc::Rc, 18 | }; 19 | 20 | use crate::{items::*, IsMenuItem, MenuItemKind, MenuItemType}; 21 | 22 | pub(crate) use self::platform::*; 23 | 24 | impl dyn IsMenuItem + '_ { 25 | fn child(&self) -> Rc> { 26 | match self.kind() { 27 | MenuItemKind::MenuItem(i) => i.inner, 28 | MenuItemKind::Submenu(i) => i.inner, 29 | MenuItemKind::Predefined(i) => i.inner, 30 | MenuItemKind::Check(i) => i.inner, 31 | MenuItemKind::Icon(i) => i.inner, 32 | } 33 | } 34 | } 35 | 36 | /// Internal utilities 37 | impl MenuChild { 38 | fn kind(&self, c: Rc>) -> MenuItemKind { 39 | match self.item_type() { 40 | MenuItemType::Submenu => { 41 | let id = c.borrow().id().clone(); 42 | MenuItemKind::Submenu(Submenu { 43 | id: Rc::new(id), 44 | inner: c, 45 | }) 46 | } 47 | MenuItemType::MenuItem => { 48 | let id = c.borrow().id().clone(); 49 | MenuItemKind::MenuItem(MenuItem { 50 | id: Rc::new(id), 51 | inner: c, 52 | }) 53 | } 54 | MenuItemType::Predefined => { 55 | let id = c.borrow().id().clone(); 56 | MenuItemKind::Predefined(PredefinedMenuItem { 57 | id: Rc::new(id), 58 | inner: c, 59 | }) 60 | } 61 | MenuItemType::Check => { 62 | let id = c.borrow().id().clone(); 63 | MenuItemKind::Check(CheckMenuItem { 64 | id: Rc::new(id), 65 | inner: c, 66 | }) 67 | } 68 | MenuItemType::Icon => { 69 | let id = c.borrow().id().clone(); 70 | MenuItemKind::Icon(IconMenuItem { 71 | id: Rc::new(id), 72 | inner: c, 73 | }) 74 | } 75 | } 76 | } 77 | } 78 | 79 | #[allow(unused)] 80 | impl MenuItemKind { 81 | pub(crate) fn as_ref(&self) -> &dyn IsMenuItem { 82 | match self { 83 | MenuItemKind::MenuItem(i) => i, 84 | MenuItemKind::Submenu(i) => i, 85 | MenuItemKind::Predefined(i) => i, 86 | MenuItemKind::Check(i) => i, 87 | MenuItemKind::Icon(i) => i, 88 | } 89 | } 90 | 91 | pub(crate) fn child(&self) -> Ref { 92 | match self { 93 | MenuItemKind::MenuItem(i) => i.inner.borrow(), 94 | MenuItemKind::Submenu(i) => i.inner.borrow(), 95 | MenuItemKind::Predefined(i) => i.inner.borrow(), 96 | MenuItemKind::Check(i) => i.inner.borrow(), 97 | MenuItemKind::Icon(i) => i.inner.borrow(), 98 | } 99 | } 100 | 101 | pub(crate) fn child_mut(&self) -> RefMut { 102 | match self { 103 | MenuItemKind::MenuItem(i) => i.inner.borrow_mut(), 104 | MenuItemKind::Submenu(i) => i.inner.borrow_mut(), 105 | MenuItemKind::Predefined(i) => i.inner.borrow_mut(), 106 | MenuItemKind::Check(i) => i.inner.borrow_mut(), 107 | MenuItemKind::Icon(i) => i.inner.borrow_mut(), 108 | } 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /src/platform_impl/windows/accelerator.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 std::fmt; 6 | 7 | use keyboard_types::{Code, Modifiers}; 8 | use windows_sys::Win32::UI::{ 9 | Input::KeyboardAndMouse::*, 10 | WindowsAndMessaging::{ACCEL, FALT, FCONTROL, FSHIFT, FVIRTKEY}, 11 | }; 12 | 13 | use crate::accelerator::{Accelerator, AcceleratorParseError}; 14 | 15 | impl Accelerator { 16 | // Convert a hotkey to an accelerator. 17 | pub fn to_accel(&self, menu_id: u16) -> crate::Result { 18 | let mut virt_key = FVIRTKEY; 19 | let key_mods: Modifiers = self.mods; 20 | if key_mods.contains(Modifiers::CONTROL) { 21 | virt_key |= FCONTROL; 22 | } 23 | if key_mods.contains(Modifiers::ALT) { 24 | virt_key |= FALT; 25 | } 26 | if key_mods.contains(Modifiers::SHIFT) { 27 | virt_key |= FSHIFT; 28 | } 29 | 30 | let vk_code = key_to_vk(&self.key)?; 31 | let mod_code = vk_code >> 8; 32 | if mod_code & 0x1 != 0 { 33 | virt_key |= FSHIFT; 34 | } 35 | if mod_code & 0x02 != 0 { 36 | virt_key |= FCONTROL; 37 | } 38 | if mod_code & 0x04 != 0 { 39 | virt_key |= FALT; 40 | } 41 | let raw_key = vk_code & 0x00ff; 42 | 43 | Ok(ACCEL { 44 | fVirt: virt_key, 45 | key: raw_key, 46 | cmd: menu_id, 47 | }) 48 | } 49 | } 50 | 51 | // used to build accelerators table from Key 52 | fn key_to_vk(key: &Code) -> Result { 53 | Ok(match key { 54 | Code::KeyA => VK_A, 55 | Code::KeyB => VK_B, 56 | Code::KeyC => VK_C, 57 | Code::KeyD => VK_D, 58 | Code::KeyE => VK_E, 59 | Code::KeyF => VK_F, 60 | Code::KeyG => VK_G, 61 | Code::KeyH => VK_H, 62 | Code::KeyI => VK_I, 63 | Code::KeyJ => VK_J, 64 | Code::KeyK => VK_K, 65 | Code::KeyL => VK_L, 66 | Code::KeyM => VK_M, 67 | Code::KeyN => VK_N, 68 | Code::KeyO => VK_O, 69 | Code::KeyP => VK_P, 70 | Code::KeyQ => VK_Q, 71 | Code::KeyR => VK_R, 72 | Code::KeyS => VK_S, 73 | Code::KeyT => VK_T, 74 | Code::KeyU => VK_U, 75 | Code::KeyV => VK_V, 76 | Code::KeyW => VK_W, 77 | Code::KeyX => VK_X, 78 | Code::KeyY => VK_Y, 79 | Code::KeyZ => VK_Z, 80 | Code::Digit0 => VK_0, 81 | Code::Digit1 => VK_1, 82 | Code::Digit2 => VK_2, 83 | Code::Digit3 => VK_3, 84 | Code::Digit4 => VK_4, 85 | Code::Digit5 => VK_5, 86 | Code::Digit6 => VK_6, 87 | Code::Digit7 => VK_7, 88 | Code::Digit8 => VK_8, 89 | Code::Digit9 => VK_9, 90 | Code::Equal => VK_OEM_PLUS, 91 | Code::Comma => VK_OEM_COMMA, 92 | Code::Minus => VK_OEM_MINUS, 93 | Code::Period => VK_OEM_PERIOD, 94 | Code::Semicolon => VK_OEM_1, 95 | Code::Slash => VK_OEM_2, 96 | Code::Backquote => VK_OEM_3, 97 | Code::BracketLeft => VK_OEM_4, 98 | Code::Backslash => VK_OEM_5, 99 | Code::BracketRight => VK_OEM_6, 100 | Code::Quote => VK_OEM_7, 101 | Code::Backspace => VK_BACK, 102 | Code::Tab => VK_TAB, 103 | Code::Space => VK_SPACE, 104 | Code::Enter => VK_RETURN, 105 | Code::Pause => VK_PAUSE, 106 | Code::CapsLock => VK_CAPITAL, 107 | Code::KanaMode => VK_KANA, 108 | Code::Escape => VK_ESCAPE, 109 | Code::NonConvert => VK_NONCONVERT, 110 | Code::PageUp => VK_PRIOR, 111 | Code::PageDown => VK_NEXT, 112 | Code::End => VK_END, 113 | Code::Home => VK_HOME, 114 | Code::ArrowLeft => VK_LEFT, 115 | Code::ArrowUp => VK_UP, 116 | Code::ArrowRight => VK_RIGHT, 117 | Code::ArrowDown => VK_DOWN, 118 | Code::PrintScreen => VK_SNAPSHOT, 119 | Code::Insert => VK_INSERT, 120 | Code::Delete => VK_DELETE, 121 | Code::Help => VK_HELP, 122 | Code::ContextMenu => VK_APPS, 123 | Code::F1 => VK_F1, 124 | Code::F2 => VK_F2, 125 | Code::F3 => VK_F3, 126 | Code::F4 => VK_F4, 127 | Code::F5 => VK_F5, 128 | Code::F6 => VK_F6, 129 | Code::F7 => VK_F7, 130 | Code::F8 => VK_F8, 131 | Code::F9 => VK_F9, 132 | Code::F10 => VK_F10, 133 | Code::F11 => VK_F11, 134 | Code::F12 => VK_F12, 135 | Code::F13 => VK_F13, 136 | Code::F14 => VK_F14, 137 | Code::F15 => VK_F15, 138 | Code::F16 => VK_F16, 139 | Code::F17 => VK_F17, 140 | Code::F18 => VK_F18, 141 | Code::F19 => VK_F19, 142 | Code::F20 => VK_F20, 143 | Code::F21 => VK_F21, 144 | Code::F22 => VK_F22, 145 | Code::F23 => VK_F23, 146 | Code::F24 => VK_F24, 147 | Code::NumLock => VK_NUMLOCK, 148 | Code::ScrollLock => VK_SCROLL, 149 | Code::BrowserBack => VK_BROWSER_BACK, 150 | Code::BrowserForward => VK_BROWSER_FORWARD, 151 | Code::BrowserRefresh => VK_BROWSER_REFRESH, 152 | Code::BrowserStop => VK_BROWSER_STOP, 153 | Code::BrowserSearch => VK_BROWSER_SEARCH, 154 | Code::BrowserFavorites => VK_BROWSER_FAVORITES, 155 | Code::BrowserHome => VK_BROWSER_HOME, 156 | Code::AudioVolumeMute => VK_VOLUME_MUTE, 157 | Code::AudioVolumeDown => VK_VOLUME_DOWN, 158 | Code::AudioVolumeUp => VK_VOLUME_UP, 159 | Code::MediaTrackNext => VK_MEDIA_NEXT_TRACK, 160 | Code::MediaTrackPrevious => VK_MEDIA_PREV_TRACK, 161 | Code::MediaStop => VK_MEDIA_STOP, 162 | Code::MediaPlayPause => VK_MEDIA_PLAY_PAUSE, 163 | Code::LaunchMail => VK_LAUNCH_MAIL, 164 | Code::Convert => VK_CONVERT, 165 | key => return Err(AcceleratorParseError::UnsupportedKey(key.to_string())), 166 | }) 167 | } 168 | 169 | impl fmt::Display for Accelerator { 170 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 171 | let key_mods: Modifiers = self.mods; 172 | if key_mods.contains(Modifiers::CONTROL) { 173 | write!(f, "Ctrl+")?; 174 | } 175 | if key_mods.contains(Modifiers::SHIFT) { 176 | write!(f, "Shift+")?; 177 | } 178 | if key_mods.contains(Modifiers::ALT) { 179 | write!(f, "Alt+")?; 180 | } 181 | if key_mods.contains(Modifiers::SUPER) { 182 | write!(f, "Windows+")?; 183 | } 184 | match &self.key { 185 | Code::KeyA => write!(f, "A"), 186 | Code::KeyB => write!(f, "B"), 187 | Code::KeyC => write!(f, "C"), 188 | Code::KeyD => write!(f, "D"), 189 | Code::KeyE => write!(f, "E"), 190 | Code::KeyF => write!(f, "F"), 191 | Code::KeyG => write!(f, "G"), 192 | Code::KeyH => write!(f, "H"), 193 | Code::KeyI => write!(f, "I"), 194 | Code::KeyJ => write!(f, "J"), 195 | Code::KeyK => write!(f, "K"), 196 | Code::KeyL => write!(f, "L"), 197 | Code::KeyM => write!(f, "M"), 198 | Code::KeyN => write!(f, "N"), 199 | Code::KeyO => write!(f, "O"), 200 | Code::KeyP => write!(f, "P"), 201 | Code::KeyQ => write!(f, "Q"), 202 | Code::KeyR => write!(f, "R"), 203 | Code::KeyS => write!(f, "S"), 204 | Code::KeyT => write!(f, "T"), 205 | Code::KeyU => write!(f, "U"), 206 | Code::KeyV => write!(f, "V"), 207 | Code::KeyW => write!(f, "W"), 208 | Code::KeyX => write!(f, "X"), 209 | Code::KeyY => write!(f, "Y"), 210 | Code::KeyZ => write!(f, "Z"), 211 | Code::Digit0 => write!(f, "0"), 212 | Code::Digit1 => write!(f, "1"), 213 | Code::Digit2 => write!(f, "2"), 214 | Code::Digit3 => write!(f, "3"), 215 | Code::Digit4 => write!(f, "4"), 216 | Code::Digit5 => write!(f, "5"), 217 | Code::Digit6 => write!(f, "6"), 218 | Code::Digit7 => write!(f, "7"), 219 | Code::Digit8 => write!(f, "8"), 220 | Code::Digit9 => write!(f, "9"), 221 | Code::Comma => write!(f, ","), 222 | Code::Minus => write!(f, "-"), 223 | Code::Period => write!(f, "."), 224 | Code::Space => write!(f, "Space"), 225 | Code::Equal => write!(f, "="), 226 | Code::Semicolon => write!(f, ";"), 227 | Code::Slash => write!(f, "/"), 228 | Code::Backslash => write!(f, "\\"), 229 | Code::Quote => write!(f, "\'"), 230 | Code::Backquote => write!(f, "`"), 231 | Code::BracketLeft => write!(f, "["), 232 | Code::BracketRight => write!(f, "]"), 233 | Code::Tab => write!(f, "Tab"), 234 | Code::Escape => write!(f, "Esc"), 235 | Code::Delete => write!(f, "Del"), 236 | Code::Insert => write!(f, "Ins"), 237 | Code::PageUp => write!(f, "PgUp"), 238 | Code::PageDown => write!(f, "PgDn"), 239 | // These names match LibreOffice. 240 | Code::ArrowLeft => write!(f, "Left"), 241 | Code::ArrowRight => write!(f, "Right"), 242 | Code::ArrowUp => write!(f, "Up"), 243 | Code::ArrowDown => write!(f, "Down"), 244 | _ => write!(f, "{:?}", self.key), 245 | } 246 | } 247 | } 248 | -------------------------------------------------------------------------------- /src/platform_impl/windows/dark_menu_bar.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 | // this is a port of combination of https://github.com/hrydgard/ppsspp/blob/master/Windows/W32Util/UAHMenuBar.cpp and https://github.com/ysc3839/win32-darkmode/blob/master/win32-darkmode/DarkMode.h 6 | 7 | #![allow(non_snake_case, clippy::upper_case_acronyms)] 8 | 9 | use std::cell::Cell; 10 | 11 | use once_cell::sync::Lazy; 12 | use windows_sys::{ 13 | s, 14 | Win32::{ 15 | Foundation::{HWND, LPARAM, RECT, WPARAM}, 16 | Graphics::Gdi::*, 17 | System::LibraryLoader::{GetProcAddress, LoadLibraryA}, 18 | UI::{ 19 | Accessibility::HIGHCONTRASTA, 20 | Controls::*, 21 | WindowsAndMessaging::{ 22 | GetClientRect, GetMenuBarInfo, GetMenuItemInfoW, GetWindowRect, 23 | SystemParametersInfoA, HMENU, MENUBARINFO, MENUITEMINFOW, MIIM_STRING, OBJID_MENU, 24 | SPI_GETHIGHCONTRAST, WM_NCACTIVATE, WM_NCPAINT, 25 | }, 26 | }, 27 | }, 28 | }; 29 | 30 | pub const WM_UAHDRAWMENU: u32 = 0x0091; 31 | pub const WM_UAHDRAWMENUITEM: u32 = 0x0092; 32 | 33 | #[repr(C)] 34 | struct UAHMENUITEMMETRICS0 { 35 | cx: u32, 36 | cy: u32, 37 | } 38 | 39 | #[repr(C)] 40 | struct UAHMENUITEMMETRICS { 41 | rgsizeBar: [UAHMENUITEMMETRICS0; 2], 42 | rgsizePopup: [UAHMENUITEMMETRICS0; 4], 43 | } 44 | 45 | #[repr(C)] 46 | struct UAHMENUPOPUPMETRICS { 47 | rgcx: [u32; 4], 48 | fUpdateMaxWidths: u32, 49 | } 50 | 51 | #[repr(C)] 52 | struct UAHMENU { 53 | hmenu: HMENU, 54 | hdc: HDC, 55 | dwFlags: u32, 56 | } 57 | #[repr(C)] 58 | struct UAHMENUITEM { 59 | iPosition: u32, 60 | umim: UAHMENUITEMMETRICS, 61 | umpm: UAHMENUPOPUPMETRICS, 62 | } 63 | #[repr(C)] 64 | struct UAHDRAWMENUITEM { 65 | dis: DRAWITEMSTRUCT, 66 | um: UAHMENU, 67 | umi: UAHMENUITEM, 68 | } 69 | 70 | #[derive(Debug)] 71 | struct Win32Brush(Cell); 72 | 73 | impl Win32Brush { 74 | const fn null() -> Win32Brush { 75 | Self(Cell::new(0 as _)) 76 | } 77 | 78 | fn get_or_set(&self, color: u32) -> HBRUSH { 79 | if self.0.get().is_null() { 80 | self.0.set(unsafe { CreateSolidBrush(color) }); 81 | } 82 | self.0.get() 83 | } 84 | } 85 | 86 | impl Drop for Win32Brush { 87 | fn drop(&mut self) { 88 | unsafe { DeleteObject(self.0.get()) }; 89 | } 90 | } 91 | 92 | fn background_brush() -> HBRUSH { 93 | thread_local! { 94 | static BACKGROUND_BRUSH: Win32Brush = const { Win32Brush::null() }; 95 | } 96 | const BACKGROUND_COLOR: u32 = 2829099; 97 | BACKGROUND_BRUSH.with(|brush| brush.get_or_set(BACKGROUND_COLOR)) 98 | } 99 | 100 | fn selected_background_brush() -> HBRUSH { 101 | thread_local! { 102 | static SELECTED_BACKGROUND_BRUSH: Win32Brush = const { Win32Brush::null() }; 103 | } 104 | const SELECTED_BACKGROUND_COLOR: u32 = 4276545; 105 | SELECTED_BACKGROUND_BRUSH.with(|brush| brush.get_or_set(SELECTED_BACKGROUND_COLOR)) 106 | } 107 | 108 | /// Draws a dark menu bar if needed and returns whether it draws it or not 109 | pub fn draw(hwnd: super::Hwnd, msg: u32, _wparam: WPARAM, lparam: LPARAM) { 110 | match msg { 111 | // draw over the annoying white line blow menubar 112 | // ref: https://github.com/notepad-plus-plus/notepad-plus-plus/pull/9985 113 | WM_NCACTIVATE | WM_NCPAINT => { 114 | let mut mbi = MENUBARINFO { 115 | cbSize: std::mem::size_of::() as _, 116 | ..unsafe { std::mem::zeroed() } 117 | }; 118 | unsafe { GetMenuBarInfo(hwnd as _, OBJID_MENU, 0, &mut mbi) }; 119 | 120 | let mut client_rc: RECT = unsafe { std::mem::zeroed() }; 121 | unsafe { 122 | GetClientRect(hwnd as _, &mut client_rc); 123 | MapWindowPoints( 124 | hwnd as _, 125 | std::ptr::null_mut(), 126 | &mut client_rc as *mut _ as *mut _, 127 | 2, 128 | ); 129 | }; 130 | 131 | let mut window_rc: RECT = unsafe { std::mem::zeroed() }; 132 | unsafe { GetWindowRect(hwnd as _, &mut window_rc) }; 133 | 134 | unsafe { OffsetRect(&mut client_rc, -window_rc.left, -window_rc.top) }; 135 | 136 | let mut annoying_rc = client_rc; 137 | annoying_rc.bottom = annoying_rc.top; 138 | annoying_rc.top -= 1; 139 | 140 | unsafe { 141 | let hdc = GetWindowDC(hwnd as _); 142 | FillRect(hdc, &annoying_rc, background_brush()); 143 | ReleaseDC(hwnd as _, hdc); 144 | } 145 | } 146 | 147 | // draw menu bar background 148 | WM_UAHDRAWMENU => { 149 | let pudm = lparam as *const UAHMENU; 150 | 151 | // get the menubar rect 152 | let rc = { 153 | let mut mbi = MENUBARINFO { 154 | cbSize: std::mem::size_of::() as _, 155 | ..unsafe { std::mem::zeroed() } 156 | }; 157 | unsafe { GetMenuBarInfo(hwnd as _, OBJID_MENU, 0, &mut mbi) }; 158 | 159 | let mut window_rc: RECT = unsafe { std::mem::zeroed() }; 160 | unsafe { GetWindowRect(hwnd as _, &mut window_rc) }; 161 | 162 | let mut rc = mbi.rcBar; 163 | // the rcBar is offset by the window rect 164 | unsafe { OffsetRect(&mut rc, -window_rc.left, -window_rc.top) }; 165 | rc.top -= 1; 166 | rc 167 | }; 168 | 169 | unsafe { FillRect((*pudm).hdc, &rc, background_brush()) }; 170 | } 171 | 172 | // draw menu bar items 173 | WM_UAHDRAWMENUITEM => { 174 | let pudmi = lparam as *mut UAHDRAWMENUITEM; 175 | 176 | // get the menu item string 177 | let (label, cch) = { 178 | let mut label = Vec::::with_capacity(256); 179 | let mut info: MENUITEMINFOW = unsafe { std::mem::zeroed() }; 180 | info.cbSize = std::mem::size_of::() as _; 181 | info.fMask = MIIM_STRING; 182 | info.dwTypeData = label.as_mut_ptr(); 183 | info.cch = (std::mem::size_of_val(&label) / 2 - 1) as _; 184 | unsafe { 185 | GetMenuItemInfoW( 186 | (*pudmi).um.hmenu, 187 | (*pudmi).umi.iPosition, 188 | true.into(), 189 | &mut info, 190 | ) 191 | }; 192 | (label, info.cch) 193 | }; 194 | 195 | // get the item state for drawing 196 | let mut dw_flags = DT_CENTER | DT_SINGLELINE | DT_VCENTER; 197 | let mut i_text_state_id = 0; 198 | let mut i_background_state_id = 0; 199 | 200 | unsafe { 201 | if (((*pudmi).dis.itemState & ODS_INACTIVE) 202 | | ((*pudmi).dis.itemState & ODS_DEFAULT)) 203 | != 0 204 | { 205 | // normal display 206 | i_text_state_id = MPI_NORMAL; 207 | i_background_state_id = MPI_NORMAL; 208 | } 209 | if (*pudmi).dis.itemState & ODS_HOTLIGHT != 0 { 210 | // hot tracking 211 | i_text_state_id = MPI_HOT; 212 | i_background_state_id = MPI_HOT; 213 | } 214 | if (*pudmi).dis.itemState & ODS_SELECTED != 0 { 215 | // clicked -- MENU_POPUPITEM has no state for this, though MENU_BARITEM does 216 | i_text_state_id = MPI_HOT; 217 | i_background_state_id = MPI_HOT; 218 | } 219 | if ((*pudmi).dis.itemState & ODS_GRAYED) != 0 220 | || ((*pudmi).dis.itemState & ODS_DISABLED) != 0 221 | { 222 | // disabled / grey text 223 | i_text_state_id = MPI_DISABLED; 224 | i_background_state_id = MPI_DISABLED; 225 | } 226 | if ((*pudmi).dis.itemState & ODS_NOACCEL) != 0 { 227 | dw_flags |= DT_HIDEPREFIX; 228 | } 229 | 230 | let bg_brush = match i_background_state_id { 231 | MPI_HOT => selected_background_brush(), 232 | _ => background_brush(), 233 | }; 234 | 235 | FillRect((*pudmi).um.hdc, &(*pudmi).dis.rcItem, bg_brush); 236 | 237 | const TEXT_COLOR: u32 = 16777215; 238 | const DISABLED_TEXT_COLOR: u32 = 7171437; 239 | 240 | let text_brush = match i_text_state_id { 241 | MPI_DISABLED => DISABLED_TEXT_COLOR, 242 | _ => TEXT_COLOR, 243 | }; 244 | 245 | SetBkMode((*pudmi).um.hdc, 0); 246 | SetTextColor((*pudmi).um.hdc, text_brush); 247 | DrawTextW( 248 | (*pudmi).um.hdc, 249 | label.as_ptr(), 250 | cch as _, 251 | &mut (*pudmi).dis.rcItem, 252 | dw_flags, 253 | ); 254 | } 255 | } 256 | 257 | _ => {} 258 | }; 259 | } 260 | 261 | pub fn should_use_dark_mode(hwnd: super::Hwnd) -> bool { 262 | should_apps_use_dark_mode() && !is_high_contrast() && is_dark_mode_allowed_for_window(hwnd as _) 263 | } 264 | 265 | static HUXTHEME: Lazy = Lazy::new(|| unsafe { LoadLibraryA(s!("uxtheme.dll")) as _ }); 266 | 267 | fn should_apps_use_dark_mode() -> bool { 268 | const UXTHEME_SHOULDAPPSUSEDARKMODE_ORDINAL: u16 = 132; 269 | type ShouldAppsUseDarkMode = unsafe extern "system" fn() -> bool; 270 | static SHOULD_APPS_USE_DARK_MODE: Lazy> = Lazy::new(|| unsafe { 271 | if *HUXTHEME == 0 { 272 | return None; 273 | } 274 | 275 | GetProcAddress( 276 | (*HUXTHEME) as *mut _, 277 | UXTHEME_SHOULDAPPSUSEDARKMODE_ORDINAL as usize as *mut _, 278 | ) 279 | .map(|handle| std::mem::transmute(handle)) 280 | }); 281 | 282 | SHOULD_APPS_USE_DARK_MODE 283 | .map(|should_apps_use_dark_mode| unsafe { (should_apps_use_dark_mode)() }) 284 | .unwrap_or(false) 285 | } 286 | 287 | fn is_dark_mode_allowed_for_window(hwnd: HWND) -> bool { 288 | const UXTHEME_ISDARKMODEALLOWEDFORWINDOW_ORDINAL: u16 = 137; 289 | type IsDarkModeAllowedForWindow = unsafe extern "system" fn(HWND) -> bool; 290 | static IS_DARK_MODE_ALLOWED_FOR_WINDOW: Lazy> = 291 | Lazy::new(|| unsafe { 292 | if *HUXTHEME == 0 { 293 | return None; 294 | } 295 | 296 | GetProcAddress( 297 | (*HUXTHEME) as *mut _, 298 | UXTHEME_ISDARKMODEALLOWEDFORWINDOW_ORDINAL as usize as *mut _, 299 | ) 300 | .map(|handle| std::mem::transmute(handle)) 301 | }); 302 | 303 | if let Some(_is_dark_mode_allowed_for_window) = *IS_DARK_MODE_ALLOWED_FOR_WINDOW { 304 | unsafe { _is_dark_mode_allowed_for_window(hwnd) } 305 | } else { 306 | false 307 | } 308 | } 309 | 310 | fn is_high_contrast() -> bool { 311 | const HCF_HIGHCONTRASTON: u32 = 1; 312 | 313 | let mut hc = HIGHCONTRASTA { 314 | cbSize: 0, 315 | dwFlags: Default::default(), 316 | lpszDefaultScheme: std::ptr::null_mut(), 317 | }; 318 | 319 | let ok = unsafe { 320 | SystemParametersInfoA( 321 | SPI_GETHIGHCONTRAST, 322 | std::mem::size_of_val(&hc) as _, 323 | &mut hc as *mut _ as _, 324 | Default::default(), 325 | ) 326 | }; 327 | 328 | ok != 0 && (HCF_HIGHCONTRASTON & hc.dwFlags) != 0 329 | } 330 | -------------------------------------------------------------------------------- /src/platform_impl/windows/icon.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 | // taken from https://github.com/rust-windowing/winit/blob/92fdf5ba85f920262a61cee4590f4a11ad5738d1/src/platform_impl/windows/icon.rs 6 | 7 | use std::{fmt, io, mem, path::Path, sync::Arc}; 8 | 9 | use windows_sys::{ 10 | core::PCWSTR, 11 | Win32::{ 12 | Foundation::RECT, 13 | Graphics::Gdi::{ 14 | CreateCompatibleDC, CreateDIBSection, DeleteDC, GetDC, ReleaseDC, SelectObject, 15 | BITMAPINFO, BITMAPINFOHEADER, BI_RGB, DIB_RGB_COLORS, HBITMAP, 16 | }, 17 | UI::WindowsAndMessaging::{ 18 | CreateIcon, DestroyIcon, DrawIconEx, LoadImageW, DI_NORMAL, HICON, IMAGE_ICON, 19 | LR_DEFAULTSIZE, LR_LOADFROMFILE, 20 | }, 21 | }, 22 | }; 23 | 24 | use crate::icon::*; 25 | 26 | use super::util; 27 | 28 | impl Pixel { 29 | fn convert_to_bgra(&mut self) { 30 | mem::swap(&mut self.r, &mut self.b); 31 | } 32 | } 33 | 34 | impl RgbaIcon { 35 | fn into_windows_icon(self) -> Result { 36 | let rgba = self.rgba; 37 | let pixel_count = rgba.len() / PIXEL_SIZE; 38 | let mut and_mask = Vec::with_capacity(pixel_count); 39 | let pixels = 40 | unsafe { std::slice::from_raw_parts_mut(rgba.as_ptr() as *mut Pixel, pixel_count) }; 41 | for pixel in pixels { 42 | and_mask.push(pixel.a.wrapping_sub(u8::MAX)); // invert alpha channel 43 | pixel.convert_to_bgra(); 44 | } 45 | assert_eq!(and_mask.len(), pixel_count); 46 | let handle = unsafe { 47 | CreateIcon( 48 | std::ptr::null_mut(), 49 | self.width as i32, 50 | self.height as i32, 51 | 1, 52 | (PIXEL_SIZE * 8) as u8, 53 | and_mask.as_ptr(), 54 | rgba.as_ptr(), 55 | ) 56 | }; 57 | if !handle.is_null() { 58 | Ok(WinIcon::from_handle(handle)) 59 | } else { 60 | Err(BadIcon::OsError(io::Error::last_os_error())) 61 | } 62 | } 63 | } 64 | 65 | #[derive(Debug)] 66 | struct RaiiIcon { 67 | handle: HICON, 68 | } 69 | 70 | #[derive(Clone)] 71 | pub(crate) struct WinIcon { 72 | inner: Arc, 73 | } 74 | 75 | unsafe impl Send for WinIcon {} 76 | 77 | impl WinIcon { 78 | pub unsafe fn to_hbitmap(&self) -> HBITMAP { 79 | let hdc = CreateCompatibleDC(std::ptr::null_mut()); 80 | 81 | let rc = RECT { 82 | left: 0, 83 | top: 0, 84 | right: 16, 85 | bottom: 16, 86 | }; 87 | 88 | let mut bitmap_info: BITMAPINFO = std::mem::zeroed(); 89 | bitmap_info.bmiHeader.biSize = std::mem::size_of::() as _; 90 | bitmap_info.bmiHeader.biWidth = rc.right; 91 | bitmap_info.bmiHeader.biHeight = rc.bottom; 92 | bitmap_info.bmiHeader.biPlanes = 1; 93 | bitmap_info.bmiHeader.biBitCount = 32; 94 | bitmap_info.bmiHeader.biCompression = BI_RGB as _; 95 | 96 | let h_dc_bitmap = GetDC(std::ptr::null_mut()); 97 | 98 | let hbitmap = CreateDIBSection( 99 | h_dc_bitmap, 100 | &bitmap_info, 101 | DIB_RGB_COLORS, 102 | 0 as _, 103 | std::ptr::null_mut(), 104 | 0, 105 | ); 106 | 107 | ReleaseDC(std::ptr::null_mut(), h_dc_bitmap); 108 | 109 | let h_bitmap_old = SelectObject(hdc, hbitmap); 110 | 111 | DrawIconEx( 112 | hdc, 113 | 0, 114 | 0, 115 | self.inner.handle, 116 | rc.right, 117 | rc.bottom, 118 | 0, 119 | std::ptr::null_mut(), 120 | DI_NORMAL, 121 | ); 122 | 123 | SelectObject(hdc, h_bitmap_old); 124 | DeleteDC(hdc); 125 | 126 | hbitmap 127 | } 128 | 129 | pub fn from_rgba(rgba: Vec, width: u32, height: u32) -> Result { 130 | let rgba_icon = RgbaIcon::from_rgba(rgba, width, height)?; 131 | rgba_icon.into_windows_icon() 132 | } 133 | 134 | fn from_handle(handle: HICON) -> Self { 135 | Self { 136 | #[allow(clippy::arc_with_non_send_sync)] 137 | inner: Arc::new(RaiiIcon { handle }), 138 | } 139 | } 140 | 141 | pub(crate) fn from_path>( 142 | path: P, 143 | size: Option<(u32, u32)>, 144 | ) -> Result { 145 | // width / height of 0 along with LR_DEFAULTSIZE tells windows to load the default icon size 146 | let (width, height) = size.unwrap_or((0, 0)); 147 | 148 | let wide_path = util::encode_wide(path.as_ref()); 149 | 150 | let handle = unsafe { 151 | LoadImageW( 152 | std::ptr::null_mut(), 153 | wide_path.as_ptr(), 154 | IMAGE_ICON, 155 | width as i32, 156 | height as i32, 157 | LR_DEFAULTSIZE | LR_LOADFROMFILE, 158 | ) 159 | }; 160 | if !handle.is_null() { 161 | Ok(WinIcon::from_handle(handle as HICON)) 162 | } else { 163 | Err(BadIcon::OsError(io::Error::last_os_error())) 164 | } 165 | } 166 | 167 | pub(crate) fn from_resource( 168 | resource_id: u16, 169 | size: Option<(u32, u32)>, 170 | ) -> Result { 171 | // width / height of 0 along with LR_DEFAULTSIZE tells windows to load the default icon size 172 | let (width, height) = size.unwrap_or((0, 0)); 173 | let handle = unsafe { 174 | LoadImageW( 175 | util::get_instance_handle(), 176 | resource_id as PCWSTR, 177 | IMAGE_ICON, 178 | width as i32, 179 | height as i32, 180 | LR_DEFAULTSIZE, 181 | ) 182 | }; 183 | if !handle.is_null() { 184 | Ok(WinIcon::from_handle(handle as HICON)) 185 | } else { 186 | Err(BadIcon::OsError(io::Error::last_os_error())) 187 | } 188 | } 189 | } 190 | 191 | impl Drop for RaiiIcon { 192 | fn drop(&mut self) { 193 | unsafe { DestroyIcon(self.handle) }; 194 | } 195 | } 196 | 197 | impl fmt::Debug for WinIcon { 198 | fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { 199 | (*self.inner).fmt(formatter) 200 | } 201 | } 202 | -------------------------------------------------------------------------------- /src/platform_impl/windows/util.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 std::ops::{Deref, DerefMut}; 6 | 7 | use once_cell::sync::Lazy; 8 | use windows_sys::{ 9 | core::HRESULT, 10 | Win32::{ 11 | Foundation::{FARPROC, HWND, S_OK}, 12 | Graphics::Gdi::{ 13 | GetDC, GetDeviceCaps, MonitorFromWindow, HMONITOR, LOGPIXELSX, MONITOR_DEFAULTTONEAREST, 14 | }, 15 | System::LibraryLoader::{GetProcAddress, LoadLibraryW}, 16 | UI::{ 17 | HiDpi::{MDT_EFFECTIVE_DPI, MONITOR_DPI_TYPE}, 18 | WindowsAndMessaging::{IsProcessDPIAware, ACCEL}, 19 | }, 20 | }, 21 | }; 22 | 23 | pub fn encode_wide>(string: S) -> Vec { 24 | std::os::windows::prelude::OsStrExt::encode_wide(string.as_ref()) 25 | .chain(std::iter::once(0)) 26 | .collect() 27 | } 28 | 29 | #[allow(non_snake_case)] 30 | pub fn LOWORD(dword: u32) -> u16 { 31 | (dword & 0xFFFF) as u16 32 | } 33 | 34 | pub fn decode_wide(w_str: *mut u16) -> String { 35 | let len = unsafe { windows_sys::Win32::Globalization::lstrlenW(w_str) } as usize; 36 | let w_str_slice = unsafe { std::slice::from_raw_parts(w_str, len) }; 37 | String::from_utf16_lossy(w_str_slice) 38 | } 39 | 40 | /// ACCEL wrapper to implement Debug 41 | #[derive(Clone)] 42 | #[repr(transparent)] 43 | pub struct Accel(pub ACCEL); 44 | 45 | impl std::fmt::Debug for Accel { 46 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 47 | f.debug_struct("ACCEL") 48 | .field("key", &self.0.key) 49 | .field("cmd", &self.0.cmd) 50 | .field("fVirt", &self.0.fVirt) 51 | .finish() 52 | } 53 | } 54 | 55 | impl Deref for Accel { 56 | type Target = ACCEL; 57 | 58 | fn deref(&self) -> &Self::Target { 59 | &self.0 60 | } 61 | } 62 | 63 | impl DerefMut for Accel { 64 | fn deref_mut(&mut self) -> &mut Self::Target { 65 | &mut self.0 66 | } 67 | } 68 | 69 | // taken from winit's code base 70 | // https://github.com/rust-windowing/winit/blob/ee88e38f13fbc86a7aafae1d17ad3cd4a1e761df/src/platform_impl/windows/util.rs#L138 71 | pub fn get_instance_handle() -> windows_sys::Win32::Foundation::HMODULE { 72 | // Gets the instance handle by taking the address of the 73 | // pseudo-variable created by the microsoft linker: 74 | // https://devblogs.microsoft.com/oldnewthing/20041025-00/?p=37483 75 | 76 | // This is preferred over GetModuleHandle(NULL) because it also works in DLLs: 77 | // https://stackoverflow.com/questions/21718027/getmodulehandlenull-vs-hinstance 78 | 79 | extern "C" { 80 | static __ImageBase: windows_sys::Win32::System::SystemServices::IMAGE_DOS_HEADER; 81 | } 82 | 83 | unsafe { &__ImageBase as *const _ as _ } 84 | } 85 | 86 | fn get_function_impl(library: &str, function: &str) -> FARPROC { 87 | let library = encode_wide(library); 88 | assert_eq!(function.chars().last(), Some('\0')); 89 | 90 | // Library names we will use are ASCII so we can use the A version to avoid string conversion. 91 | let module = unsafe { LoadLibraryW(library.as_ptr()) }; 92 | if module.is_null() { 93 | return None; 94 | } 95 | 96 | unsafe { GetProcAddress(module, function.as_ptr()) } 97 | } 98 | 99 | macro_rules! get_function { 100 | ($lib:expr, $func:ident) => { 101 | crate::platform_impl::platform::util::get_function_impl( 102 | $lib, 103 | concat!(stringify!($func), '\0'), 104 | ) 105 | .map(|f| unsafe { std::mem::transmute::<_, $func>(f) }) 106 | }; 107 | } 108 | 109 | pub type GetDpiForWindow = unsafe extern "system" fn(hwnd: HWND) -> u32; 110 | pub type GetDpiForMonitor = unsafe extern "system" fn( 111 | hmonitor: HMONITOR, 112 | dpi_type: MONITOR_DPI_TYPE, 113 | dpi_x: *mut u32, 114 | dpi_y: *mut u32, 115 | ) -> HRESULT; 116 | 117 | static GET_DPI_FOR_WINDOW: Lazy> = 118 | Lazy::new(|| get_function!("user32.dll", GetDpiForWindow)); 119 | static GET_DPI_FOR_MONITOR: Lazy> = 120 | Lazy::new(|| get_function!("shcore.dll", GetDpiForMonitor)); 121 | 122 | pub const BASE_DPI: u32 = 96; 123 | pub fn dpi_to_scale_factor(dpi: u32) -> f64 { 124 | dpi as f64 / BASE_DPI as f64 125 | } 126 | 127 | #[allow(non_snake_case)] 128 | pub unsafe fn hwnd_dpi(hwnd: HWND) -> u32 { 129 | if let Some(GetDpiForWindow) = *GET_DPI_FOR_WINDOW { 130 | // We are on Windows 10 Anniversary Update (1607) or later. 131 | match GetDpiForWindow(hwnd) { 132 | 0 => BASE_DPI, // 0 is returned if hwnd is invalid 133 | #[allow(clippy::unnecessary_cast)] 134 | dpi => dpi as u32, 135 | } 136 | } else if let Some(GetDpiForMonitor) = *GET_DPI_FOR_MONITOR { 137 | // We are on Windows 8.1 or later. 138 | let monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST); 139 | if monitor.is_null() { 140 | return BASE_DPI; 141 | } 142 | 143 | let mut dpi_x = 0; 144 | let mut dpi_y = 0; 145 | #[allow(clippy::unnecessary_cast)] 146 | if GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y) == S_OK { 147 | dpi_x as u32 148 | } else { 149 | BASE_DPI 150 | } 151 | } else { 152 | let hdc = GetDC(hwnd); 153 | if hdc.is_null() { 154 | return BASE_DPI; 155 | } 156 | 157 | // We are on Vista or later. 158 | if IsProcessDPIAware() == 1 { 159 | // If the process is DPI aware, then scaling must be handled by the application using 160 | // this DPI value. 161 | GetDeviceCaps(hdc, LOGPIXELSX as _) as u32 162 | } else { 163 | // If the process is DPI unaware, then scaling is performed by the OS; we thus return 164 | // 96 (scale factor 1.0) to prevent the window from being re-scaled by both the 165 | // application and the WM. 166 | BASE_DPI 167 | } 168 | } 169 | } 170 | -------------------------------------------------------------------------------- /src/util.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 std::sync::atomic::{AtomicU32, Ordering}; 6 | 7 | #[derive(Clone, Copy, Debug)] 8 | pub enum AddOp { 9 | Append, 10 | Insert(usize), 11 | } 12 | 13 | pub struct Counter(AtomicU32); 14 | 15 | impl Counter { 16 | #[allow(unused)] 17 | pub const fn new() -> Self { 18 | Self(AtomicU32::new(1)) 19 | } 20 | 21 | #[allow(unused)] 22 | pub const fn new_with_start(start: u32) -> Self { 23 | Self(AtomicU32::new(start)) 24 | } 25 | 26 | pub fn next(&self) -> u32 { 27 | self.0.fetch_add(1, Ordering::Relaxed) 28 | } 29 | } 30 | --------------------------------------------------------------------------------