```
├── .clangd
├── .gitattributes
├── .github/
├── workflows/
├── xmake.yml
├── .gitignore
├── .gitmodules
├── .vscode/
├── settings.json
├── CONFIG.md
├── DONATE.md
├── LICENSE
├── README.md
├── README_zh.md
├── dependencies/
├── blook.lua
├── glfw.lua
├── quickjs-ng.lua
├── reflect-cpp.lua
├── resources/
├── animated-preview1.webp
├── bloom.webp
├── breeze.html
├── code.webp
├── icon-small.png
├── icon.7z
├── icon.png
├── icon.webp
├── inject-en.webp
├── inject.webp
├── preview1.webp
├── schema.json
├── scripts/
├── bindgen/
├── .gitignore
├── c-type-parser.ts
├── clang-ast.d.ts
├── generate-bindings.bat
├── index.ts
├── package.json
├── quickjs-types.txt
├── typegen.ts
├── yarn.lock
├── debug.cmd
├── rebuild.ps1
├── right_click.ahk
├── src/
├── inject/
├── data_directory.inc
├── inject.cc
├── shell/
├── build_info.h.in
├── config.cc
├── config.h
├── contextmenu/
├── contextmenu.cc
├── contextmenu.h
├── menu_render.cc
├── menu_render.h
├── menu_widget.cc
├── menu_widget.h
├── entry.cc
├── entry.h
├── error_handler.cc
├── error_handler.h
├── fix_win11_menu.cc
├── fix_win11_menu.h
├── logger.cc
├── logger.h
├── res_string_loader.cc
├── res_string_loader.h
├── script/
├── FileWatch.hpp
```
## /.clangd
```clangd path="/.clangd"
CompileFlags:
Add: ["-std:latest", "/clang:-std=c++23"]
```
## /.gitattributes
```gitattributes path="/.gitattributes"
*.h linguist-vendored
*.c linguist-vendored
```
## /.github/workflows/xmake.yml
```yml path="/.github/workflows/xmake.yml"
name: Build
permissions: write-all
on:
push:
branches: [ "master" ]
pull_request:
branches: [ "master" ]
release:
types: [created]
jobs:
build:
runs-on: windows-2025
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
- uses: xmake-io/github-action-setup-xmake@v1
with:
xmake-version: latest
actions-cache-folder: '.xmake-cache'
actions-cache-key: 'ci'
package-cache: true
package-cache-key: windows-2025
# build-cache: true
# build-cache-key: ${{ matrix.os }}-${{ matrix.build_type }}
- name: Xmake configure
run: |
xmake config --yes --toolchain=clang-cl --mode=releasedbg
- name: build-releasedbg
run: |
xmake b --yes --verbose inject
xmake b --yes --verbose shell
- name: Upload Artifacts
uses: actions/upload-artifact@v4.6.0
with:
path: ./build/windows/x64/
name: windows-build
- name: Create Archive
if: github.event_name == 'release'
run: |
Compress-Archive -Path ./build/windows/* -DestinationPath windows-build-pdb.zip
Remove-Item -Path ./build/windows/x64/releasedbg/*.pdb -Force
Remove-Item -Path ./build/windows/x64/releasedbg/ui.lib -Force
Compress-Archive -Path ./build/windows/* -DestinationPath windows-build.zip
- name: Upload Release Assets
if: github.event_name == 'release'
uses: softprops/action-gh-release@v1
with:
files: |
windows-build.zip
windows-build-pdb.zip
token: ${{ secrets.GITHUB_TOKEN }}
```
## /.gitignore
```gitignore path="/.gitignore"
build
compile_commands.json
.xmake
.cache
build_info.h
/test
```
## /.gitmodules
```gitmodules path="/.gitmodules"
[submodule "blook"]
path = dependencies/blook
url = https://github.com/std-microblock/blook
[submodule "dependencies/glfw"]
path = dependencies/glfw
url = https://github.com/breeze-shell/glfw
```
## /.vscode/settings.json
```json path="/.vscode/settings.json"
{
"cmake.ignoreCMakeListsMissing": true,
"files.associations": {
"xstring": "cpp"
}
}
```
## /CONFIG.md
# 配置文件格式说明
本项目的配置文件采用 JSON 格式,推荐使用 VSCode 进行编辑。
本项目配置文件默认位于 `%USERPROFILE%/.breeze-shell/config.json`。
编辑配置文件并保存后,插件将会自动重载配置,无需重新启动。
**如果保存后弹出了黑窗口,这大概是因为你的配置文件有错误,请阅读黑窗口内的报错信息并修复错误**
## Schema
Breeze Shell 配置文件的 JSON Schema 位于
[resources/schema.json](./resources/schema.json),在配置文件内写入
```json
{
"$schema": "https://raw.githubusercontent.com/std-microblock/breeze-shell/refs/heads/master/resources/schema.json"
}
```
即可在 VSCode 中看到配置文件类型检查及补全。
## 配置文件结构
以下为一份带有注释的完整默认 JSON 配置,注意其**不能**直接填入 config.json
当中,因为配置文件解析当前不支持注释
```json5
{
"context_menu": {
"theme": {
// 在 Windows 11 下使用 DWM 圆角而不是 SetWindowRgn 圆角
"use_dwm_if_available": true,
// 启用亚克力背景效果
"acrylic": true,
// 圆角大小,仅在不使用 DWM 圆角时生效
"radius": 6.0,
// 字体大小,可调整此项以对齐缩放后的整数倍率字体大小以避免模糊
"font_size": 14.0,
// 项高度
"item_height": 23.0,
// 项间距
"item_gap": 3.0,
// 项圆角大小
"item_radius": 5.0,
// 外边距
"margin": 5.0,
// 内边距
"padding": 6.0,
// 文笔内边距
"text_padding": 8.0,
// 图标内边距
"icon_padding": 4.0,
// 右侧图标(展开图标)边距
"right_icon_padding": 20.0,
// 横排按钮间距(此处为负值以抵消项边距的效果)
"multibutton_line_gap": -6.0,
// 在亮色主题下的亚克力背景颜色
"acrylic_color_light": "#fefefe00",
// 在暗色主题下的亚克力背景颜色
"acrylic_color_dark": "#28282800",
// 背景透明度
"background_opacity":1.0,
// 动画相关
"animation": {
// 菜单项动画
"item": {
// animated_float_conf: 通用动画配置
"opacity": {
// 持续时长
"duration": 200.0,
// 动画曲线
// 可为:
// mutation (关闭动画)
// linear (线性)
// ease_in, ease_out, ease_in_out (三种缓动曲线)
"easing": "ease_in_out",
// 对延迟时间的缩放
// 即:如果本来是在开始总动画 50ms 后显示该动画,
// 若 delay_scale 为 2 则在 100ms 后才显示
"delay_scale": 1.0
},
// 同 opacity,以下均省略
"x": animated_float_conf,
"y": animated_float_conf,
"width": animated_float_conf
},
// 主菜单的背景
"main_bg": {
"opacity": animated_float_conf,
"x": animated_float_conf,
"y": animated_float_conf,
"w": animated_float_conf,
"h": animated_float_conf
},
// 子菜单的背景,同主菜单
"submenu_bg": {
...
}
}
},
// 启用垂直同步
"vsync": true,
// 不替换 owner draw 的菜单
"ignore_owner_draw": true,
// 在向上展开时将所有项反向
"reverse_if_open_to_up": true,
// 调试选项,搜索更大范围的图标,不建议打开
"search_large_dwItemData_range": false,
// 定位相关
"position": {
// 竖直边距
"padding_vertical": 20,
// 水平边距
"padding_horizontal": 0
}
},
// 开启调试窗口
"debug_console": false,
// 主字体
"font_path_main": "C:\\WINDOWS\\Fonts\\segoeui.ttf",
// 副字体
"font_path_fallback": "C:\\WINDOWS\\Fonts\\msyh.ttc",
// 使用 hook 方式加载更多 resid
"res_string_loader_use_hook": false,
// 调试选项,避免更改 UI 窗口大小
"avoid_resize_ui": false,
// 插件加载顺序,在越前面的越先加载
// 格式为插件的无拓展名文件名
// 如:Windows 11 Icon Pack
"plugin_load_order": [],
// 全局默认动画效果
"default_animation": animated_float_conf
}
```
## 示例配置文件
#### 禁用所有动画
```json
{
"default_animation": {
"easing": "mutation"
}
}
```
## /DONATE.md
### Donate to this project
Donate to me if you like the project~
#### 中国大陆
## /LICENSE
``` path="/LICENSE"
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright © 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based on the Program.
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
```
## /README.md
> [!WARNING]
> This project is still in active development. File a bug report if you meet
> any!\
> 此项目仍在开发阶段,如果遇到问题请发送 Issue
>
> Both English and Chinese issues are accepted.
> Issue 中使用中文或英文均可
[中文](./README_zh.md) [Donate Me](./DONATE.md) [Discord](https://discord.gg/MgpHk8pa3d)
Breeze Shell
Bring fluency & delication back to Windows
Breeze is an **alternative context menu** for Windows 10 and Windows 11.
## Fluent
Breeze is designed with animations in mind.
All animations are configurable and can be scaled and disabled as you want.
## Extensible
Empowered by the embedded JavaScript script api, Breeze enables you to extend
the functionalities of your context menu in a few lines of code.
```javascript
shell.menu_controller.add_menu_listener((e) => {
e.menu.add({
type: "button",
name: "Shuffle Buttons",
action: () => {
for (const item of menus) {
item.set_position(Math.floor(menus.length * Math.random()));
}
},
}, 0);
});
```
[See full bindings →](./src/shell/script/binding_types.d.ts)
Send pull requests to [this repo](https://github.com/breeze-shell/plugins) to add your script to the plugin market!
## Configurable
Breeze shell exposed a bunch of configurations ranging from item height to background radius method. Customize them as you need.
[Configuration Document →](./CONFIG.md)
The config menu of breeze-shell can be found as you open your `Data Folder` and right-click anywhere inside it.
## Lightweight & Fast
Breeze uses breeze-ui, which is implemented to be a cross-platform, simple,
animation-friendly and fast ui library for modern C++, with the support of both
NanoVG and ThorVG render context. This allowed Breeze to have a delicated user
interface in ~2MiB.
# Try it out!
Download and extract the zip, and Run `breeze.exe`.

# Building
Breeze uses xmake. You'd have to install xmake in your computer first. Then,
type `xmake` in the project dir and follow the instructions. Both clang-cl and
MSVC 2019+ can build this project.
# Developing
After building successfully once, you can oprn the project dir in VSCode for
development. Install clangd plugin for full intellisense.
# Credits
#### Third-party libraries
- https://github.com/std-microblock/blook
- https://github.com/quickjs-ng/quickjs
- https://github.com/ftk/quickjspp
- https://github.com/getml/reflect-cpp
- https://github.com/glfw/glfw
- https://github.com/Dav1dde/glad
- https://github.com/memononen/nanovg
- https://github.com/memononen/nanosvg
- https://github.com/freetype/freetype
#### Others
- [@lipraty](https://github.com/lipraty) - Icon Design
- [moudey/Shell](https://github.com/moudey/Shell) - Inspiration
## /README_zh.md
Breeze Shell
为 Windows 重新带来流畅与精致体验
Breeze 是专为 Windows 10/11 设计的现代化**次世代右键菜单解决方案**。
## 丝滑流畅
Breeze 以交互动画为核心设计理念。
## 无限扩展
通过嵌入式 JavaScript 脚本 API,您可以用寥寥数行代码为右键菜单增添全新功能。
```javascript
shell.menu_controller.add_menu_listener((e) => {
e.menu.add({
type: "button",
name: "Shuffle Buttons",
action: () => {
for (const item of menus) {
item.set_position(Math.floor(menus.length * Math.random()));
}
},
}, 0);
});
```
[查看完整 API 文档 →](./src/shell/script/binding_types.d.ts)
## 轻量高速
Breeze 基于自研 breeze-ui 框架实现,这是一个跨平台、简洁优雅、动画友好的现代 C++ UI 库,支持 NanoVG 和 ThorVG 双渲染后端。这使得 Breeze 能在约 2MB 的体积下实现精致的视觉体验。
# 立即体验
从 Releases 下载,然后解压压缩包并运行 `breeze.exe`
# 构建指南
本项目使用 xmake 构建系统。请先安装 xmake,在项目根目录执行 `xmake` 命令并按提示操作。支持 clang-cl 和 MSVC 2019+ 编译器。
# 开发指南
首次构建成功后,可使用 VSCode 打开项目进行开发。建议安装 clangd 插件以获得完整的代码智能提示。
## /dependencies/blook.lua
```lua path="/dependencies/blook.lua"
package("blook")
add_deps("cmake")
add_syslinks("advapi32")
set_sourcedir(path.join(os.scriptdir(), "blook"))
on_install(function (package)
local fcdir = package:cachedir() .. "/fetchcontent"
import("package.tools.cmake").install(package, {
"-DCMAKE_INSTALL_PREFIX=" .. package:installdir(),
"-DCMAKE_PREFIX_PATH=" .. package:installdir(),
"-DFETCHCONTENT_QUIET=OFF",
"-DFETCHCONTENT_BASE_DIR=" .. fcdir,
})
os.cp("include/blook/**", package:installdir("include/blook/"))
os.cp("external/zasm/zasm/include/**", package:installdir("include/zasm/"))
os.cp(fcdir .. "/zydis-src/dependencies/zycore/include/**", package:installdir("include/zycore/"))
os.cp(package:buildir() .. "/blook.lib", package:installdir("lib"))
os.cp(package:buildir() .. "/external/zasm/zasm.lib", package:installdir("lib"))
end)
package_end()
```
## /dependencies/glfw.lua
```lua path="/dependencies/glfw.lua"
package("breeze-glfw")
set_base("glfw")
set_urls("https://github.com/breeze-shell/glfw.git")
add_versions("2025.04.13", "71513247ae3cc7eca66ca88f0789c64b5e693115")
```
## /dependencies/quickjs-ng.lua
```lua path="/dependencies/quickjs-ng.lua"
package("quickjs-ng")
set_homepage("https://github.com/quickjs-ng/quickjs")
set_description("QuickJS, the Next Generation: a mighty JavaScript engine")
set_license("MIT")
add_urls("https://github.com/quickjs-ng/quickjs/archive/refs/tags/$(version).tar.gz",
"https://github.com/quickjs-ng/quickjs.git", {submodules = false})
add_versions("v0.8.0", "7e60e1e0dcd07d25664331308a2f4aee2a88d60d85896e828d25df7c3d40204e")
add_configs("libc", {description = "Build standard library modules as part of the library", default = false, type = "boolean"})
if is_plat("linux", "bsd") then
add_syslinks("m", "pthread")
end
add_deps("cmake")
if on_check then
on_check("windows", function (package)
local vs_toolset = package:toolchain("msvc"):config("vs_toolset")
if vs_toolset then
local vs_toolset_ver = import("core.base.semver").new(vs_toolset)
local minor = vs_toolset_ver:minor()
assert(minor and minor >= 30, "package(quickjs-ng) require vs_toolset >= 14.3")
end
end)
on_check("wasm", "cross", function (package)
if package:version():eq("0.8.0") then
raise("package(quickjs-ng v0.8.0) unsupported platform")
end
end)
end
on_install("!iphoneos and (!windows or windows|!x86)", function (package)
io.replace("CMakeLists.txt", "xcheck_add_c_compiler_flag(-Werror)", "", {plain = true})
io.replace("CMakeLists.txt", "if(NOT WIN32 AND NOT EMSCRIPTEN)", "if(0)", {plain = true})
local configs = {}
table.insert(configs, "-DCMAKE_BUILD_TYPE=" .. (package:is_debug() and "Debug" or "Release"))
if package:is_plat("windows") then
if false then
-- add /debug to link flags
table.insert(configs, "-DCMAKE_EXE_LINKER_FLAGS_RELEASE=\"/DEBUG\"")
table.insert(configs, "-DCMAKE_SHARED_LINKER_FLAGS_RELEASE=\"/DEBUG\"")
-- also add /DEBUG to cflags, and /Zi to cxxflags
table.insert(configs, "-DCMAKE_C_FLAGS_RELEASE=/Zi /DEBUG")
table.insert(configs, "-DCMAKE_CXX_FLAGS_RELEASE=/Zi /DEBUG")
end
end
table.insert(configs, "-DBUILD_SHARED_LIBS=" .. (package:config("shared") and "ON" or "OFF"))
table.insert(configs, "-DCONFIG_ASAN=" .. (package:config("asan") and "ON" or "OFF"))
table.insert(configs, "-DCONFIG_MSAN=" .. (package:config("msan") and "ON" or "OFF"))
table.insert(configs, "-DCONFIG_UBSAN=" .. (package:config("ubsan") and "ON" or "OFF"))
table.insert(configs, "-DBUILD_QJS_LIBC=" .. (package:config("libc") and "ON" or "OFF"))
if package:config("shared") and package:is_plat("windows") then
table.insert(configs, "-DCMAKE_WINDOWS_EXPORT_ALL_SYMBOLS=ON")
end
import("package.tools.cmake").install(package, configs)
if package:is_plat("windows") and package:is_debug() then
local dir = package:installdir(package:config("shared") and "bin" or "lib")
os.vcp(path.join(package:buildir(), "*.pdb"), dir)
end
end)
on_test(function (package)
assert(package:has_cfuncs("JS_NewRuntime", {includes = "quickjs.h"}))
end)
```
## /dependencies/reflect-cpp.lua
```lua path="/dependencies/reflect-cpp.lua"
package("reflect-cpp")
set_homepage("https://github.com/getml/reflect-cpp")
set_description("A C++20 library for fast serialization, deserialization and validation using reflection. Supports JSON, BSON, CBOR, flexbuffers, msgpack, TOML, XML, YAML / msgpack.org[C++20]")
set_license("MIT")
add_urls("https://github.com/getml/reflect-cpp/archive/refs/tags/$(version).tar.gz",
"https://github.com/getml/reflect-cpp.git", {submodules = false})
add_versions("v0.17.0", "08b6406cbe4c6c14ff1a619fe93a94f92f6d9eb22213d93529ad975993945e45")
add_versions("v0.16.0", "a84d94dbd353d788926d6e54507b44c046863f7bc4ecb35afe0338374a68a77d")
add_versions("v0.14.1", "639aec9d33025703a58d32c231ab1ab474c0cc4fb0ff90eadcaffb49271c41cd")
add_versions("v0.14.0", "ea92a2460a71184b7d4fa4e9baad9910efad092df78b114459a7d6b0ee558d3c")
add_versions("v0.13.0", "a7a31832fe8bbaa7f7299da46dfd4ccc8b99a13242e16a1d93f8669de1fca9c6")
add_versions("v0.12.0", "13d448dd5eaee13ecb7ab5cb61cb263c7111ba75230503adc823a888f68e1eaa")
add_versions("v0.11.1", "e45f112fb3f14507a4aa53b99ae2d4ab6a4e7b2d5f04dd06fec00bf7faa7bbdc")
add_versions("v0.10.0", "d2c8876d993ddc8c57c5804e767786bdb46a2bdf1a6cd81f4b14f57b1552dfd7")
add_patches("0.16.0", "patches/0.16.0/cmake.patch", "1b2a6e0ed81dd0bd373bd1daaf52010de965f3829e5e19406c53e8ebf0a5b9fc")
add_patches("0.11.1", "patches/0.11.1/cmake.patch", "a43ae2c6de455054ab860adfb309da7bd376c31c493c8bab0ebe07aae0805205")
add_patches("0.10.0", "patches/0.10.0/cmake.patch", "b8929c0a13bd4045cbdeea0127e08a784e2dc8c43209ca9f056fff4a3ab5c4d3")
add_configs("bson", {description = "Enable Bson Support.", default = false, type = "boolean", readonly = true})
add_configs("yyjson", {description = "Enable yyjson Support.", default = true, type = "boolean"})
add_configs("cbor", {description = "Enable Cbor Support.", default = false, type = "boolean"})
add_configs("flatbuffers", {description = "Enable Flexbuffers Support.", default = false, type = "boolean"})
add_configs("msgpack", {description = "Enable Msgpack Support.", default = false, type = "boolean"})
add_configs("xml", {description = "Enable Xml Support.", default = false, type = "boolean"})
add_configs("toml", {description = "Enable Toml Support.", default = false, type = "boolean"})
add_configs("yaml", {description = "Enable Yaml Support.", default = false, type = "boolean"})
add_configs("ubjson", {description = "Enable UBJSON Support.", default = false, type = "boolean"})
if is_plat("windows") then
add_configs("shared", {description = "Build shared library.", default = false, type = "boolean", readonly = true})
end
on_check(function (package)
if package:is_plat("windows") then
local vs = package:toolchain("msvc"):config("vs")
assert(vs and tonumber(vs) >= 2022, "package(reflect-cpp): need vs >= 2022")
else
assert(package:check_cxxsnippets({test = [[
#include
#include
#include
void test() {
constexpr std::string_view message = "Hello, C++20!";
for (char c : std::views::filter(message, [](char c) { return std::islower(c); }))
std::cout << std::source_location::current().line() << ": " << c << '\n';
}
]]}, {configs = {languages = "c++20"}}), "package(reflect-cpp) Require at least C++20.")
end
end)
on_load(function (package)
if package:config("yyjson") then
package:add("deps", "yyjson")
end
if package:config("cbor") then
package:add("deps", "tinycbor")
end
if package:config("flatbuffers") then
package:add("deps", "flatbuffers")
end
if package:config("msgpack") then
package:add("deps", "msgpack-c")
end
if package:config("xml") then
package:add("deps", "pugixml")
end
if package:config("toml") then
package:add("deps", "toml++")
end
if package:config("yaml") then
package:add("deps", "yaml-cpp")
end
if package:config("ubjson") then
package:add("deps", "jsoncons")
end
local version = package:version()
if version then
if version:lt("0.13.0") then
package:set("kind", "library", {headeronly = true})
end
if version:ge("0.11.1") then
package:add("deps", "ctre", {configs = {cmake = true}})
if version:eq("0.11.1") then
package:add("defines", "REFLECTCPP_NO_BUNDLED_DEPENDENCIES")
end
end
end
if package:gitref() or version:lt("0.11.1") or version:ge("0.13.0") then
package:add("deps", "cmake")
end
end)
on_install(function (package)
local version = package:version()
if package:gitref() or version:lt("0.11.1") or version:ge("0.13.0") then
local configs = {
"-DREFLECTCPP_USE_BUNDLED_DEPENDENCIES=OFF",
"-DREFLECTCPP_USE_VCPKG=OFF",
}
table.insert(configs, "-DCMAKE_BUILD_TYPE=" .. (package:is_debug() and "Debug" or "Release"))
table.insert(configs, "-DBUILD_SHARED_LIBS=" .. (package:config("shared") and "ON" or "OFF"))
table.insert(configs, "-DREFLECTCPP_BSON=" .. (package:config("bson") and "ON" or "OFF"))
table.insert(configs, "-DREFLECTCPP_CBOR=" .. (package:config("cbor") and "ON" or "OFF"))
table.insert(configs, "-DREFLECTCPP_FLEXBUFFERS=" .. (package:config("flatbuffers") and "ON" or "OFF"))
table.insert(configs, "-DREFLECTCPP_MSGPACK=" .. (package:config("msgpack") and "ON" or "OFF"))
table.insert(configs, "-DREFLECTCPP_XML=" .. (package:config("xml") and "ON" or "OFF"))
table.insert(configs, "-DREFLECTCPP_TOML=" .. (package:config("toml") and "ON" or "OFF"))
table.insert(configs, "-DREFLECTCPP_UBJSON=" .. (package:config("ubjson") and "ON" or "OFF"))
table.insert(configs, "-DREFLECTCPP_YAML=" .. (package:config("yaml") and "ON" or "OFF"))
import("package.tools.cmake").install(package, configs)
os.rm("include/thirdparty")
os.cp("include", package:installdir())
else
os.rm("include/thirdparty")
os.cp("include", package:installdir())
end
end)
on_test(function (package)
assert(package:check_cxxsnippets({test = [[
#include
#include
struct Person {
std::string first_name;
std::string last_name;
int age;
};
const auto homer = Person{.first_name = "Homer",
.last_name = "Simpson",
.age = 45};
void test() {
const std::string json_string = rfl::json::write(homer);
auto homer2 = rfl::json::read(json_string).value();
}
]]}, {configs = {languages = "c++20"}}))
if package:config("msgpack") then
assert(package:check_cxxsnippets({test = [[
#include
#include
struct Person {
std::string first_name;
std::string last_name;
int age;
};
const auto homer = Person{.first_name = "Homer",
.last_name = "Simpson",
.age = 45};
void test() {
std::vector msgpack_str_vec = rfl::msgpack::write(homer);
auto homer2 = rfl::msgpack::read(msgpack_str_vec).value();
}
]]}, {configs = {languages = "c++20"}}))
end
end)
```
## /resources/animated-preview1.webp
Binary file available at https://raw.githubusercontent.com/std-microblock/breeze-shell/refs/heads/main/resources/animated-preview1.webp
## /resources/bloom.webp
Binary file available at https://raw.githubusercontent.com/std-microblock/breeze-shell/refs/heads/main/resources/bloom.webp
## /resources/breeze.html
```html path="/resources/breeze.html"
breeze-shell | MicroBlock
breeze-shell
Bring fluency & dedication back to Windows
Flexible
Try once or inject consistently, it's your choice.
Extensible
Extend your context menu in a few lines of code.
Fluent
Beautiful and customizable UI with fluent animation.
```
## /resources/code.webp
Binary file available at https://raw.githubusercontent.com/std-microblock/breeze-shell/refs/heads/main/resources/code.webp
## /resources/icon-small.png
Binary file available at https://raw.githubusercontent.com/std-microblock/breeze-shell/refs/heads/main/resources/icon-small.png
## /resources/icon.7z
Binary file available at https://raw.githubusercontent.com/std-microblock/breeze-shell/refs/heads/main/resources/icon.7z
## /resources/icon.png
Binary file available at https://raw.githubusercontent.com/std-microblock/breeze-shell/refs/heads/main/resources/icon.png
## /resources/icon.webp
Binary file available at https://raw.githubusercontent.com/std-microblock/breeze-shell/refs/heads/main/resources/icon.webp
## /resources/inject-en.webp
Binary file available at https://raw.githubusercontent.com/std-microblock/breeze-shell/refs/heads/main/resources/inject-en.webp
## /resources/inject.webp
Binary file available at https://raw.githubusercontent.com/std-microblock/breeze-shell/refs/heads/main/resources/inject.webp
## /resources/preview1.webp
Binary file available at https://raw.githubusercontent.com/std-microblock/breeze-shell/refs/heads/main/resources/preview1.webp
## /resources/schema.json
```json path="/resources/schema.json"
{
"$schema": "http://json-schema.org/draft-06/schema#",
"$ref": "#/definitions/Config",
"definitions": {
"Config": {
"type": "object",
"additionalProperties": false,
"properties": {
"context_menu": {
"$ref": "#/definitions/ContextMenu"
},
"debug_console": {
"type": "boolean"
},
"font_path_main": {
"type": "string"
},
"font_path_fallback": {
"type": "string"
},
"res_string_loader_use_hook": {
"type": "boolean"
},
"avoid_resize_ui": {
"type": "boolean"
},
"plugin_load_order": {
"type": "array",
"items": {}
},
"$schema": {
"type": "string"
},
"default_animation": {
"$ref": "#/definitions/AnimFloatConfig"
}
},
"required": [],
"title": "Config"
},
"ContextMenu": {
"type": "object",
"additionalProperties": false,
"properties": {
"theme": {
"$ref": "#/definitions/Theme"
},
"vsync": {
"type": "boolean"
},
"ignore_owner_draw": {
"type": "boolean"
},
"reverse_if_open_to_up": {
"type": "boolean"
},
"search_large_dwItemData_range": {
"type": "boolean"
},
"position": {
"$ref": "#/definitions/Position"
}
},
"required": [],
"title": "ContextMenu"
},
"Position": {
"type": "object",
"additionalProperties": false,
"properties": {
"padding_vertical": {
"type": "integer"
},
"padding_horizontal": {
"type": "integer"
}
},
"required": [],
"title": "Position"
},
"Theme": {
"type": "object",
"additionalProperties": false,
"properties": {
"use_dwm_if_available": {
"type": "boolean"
},
"background_opacity": {
"type": "integer"
},
"acrylic": {
"type": "boolean"
},
"radius": {
"type": "integer"
},
"font_size": {
"type": "integer"
},
"item_height": {
"type": "integer"
},
"item_gap": {
"type": "integer"
},
"item_radius": {
"type": "integer"
},
"margin": {
"type": "integer"
},
"padding": {
"type": "integer"
},
"text_padding": {
"type": "integer"
},
"icon_padding": {
"type": "integer"
},
"right_icon_padding": {
"type": "integer"
},
"multibutton_line_gap": {
"type": "integer"
},
"acrylic_color_light": {
"type": "string"
},
"acrylic_color_dark": {
"type": "string"
},
"acrylic_opacity": {
"type": "number"
},
"animation": {
"$ref": "#/definitions/Animation"
}
},
"required": [],
"title": "Theme"
},
"Animation": {
"type": "object",
"additionalProperties": false,
"properties": {
"item": {
"$ref": "#/definitions/Item"
},
"main_bg": {
"$ref": "#/definitions/Bg"
},
"submenu_bg": {
"$ref": "#/definitions/Bg"
}
},
"required": [],
"title": "Animation"
},
"Item": {
"type": "object",
"additionalProperties": false,
"properties": {
"opacity": {
"$ref": "#/definitions/AnimFloatConfig"
},
"x": {
"$ref": "#/definitions/AnimFloatConfig"
},
"y": {
"$ref": "#/definitions/AnimFloatConfig"
},
"width": {
"$ref": "#/definitions/AnimFloatConfig"
}
},
"required": [],
"title": "Item"
},
"AnimFloatConfig": {
"type": "object",
"additionalProperties": false,
"properties": {
"duration": {
"type": "integer"
},
"easing": {
"type": "string"
},
"delay_scale": {
"type": "integer"
}
},
"required": [],
"title": "AnimFloatConfig"
},
"Bg": {
"type": "object",
"additionalProperties": false,
"properties": {
"opacity": {
"$ref": "#/definitions/AnimFloatConfig"
},
"x": {
"$ref": "#/definitions/AnimFloatConfig"
},
"y": {
"$ref": "#/definitions/AnimFloatConfig"
},
"w": {
"$ref": "#/definitions/AnimFloatConfig"
},
"h": {
"$ref": "#/definitions/AnimFloatConfig"
}
},
"required": [],
"title": "Bg"
}
}
}
```
## /scripts/bindgen/.gitignore
```gitignore path="/scripts/bindgen/.gitignore"
node_modules
```
## /scripts/bindgen/c-type-parser.ts
```ts path="/scripts/bindgen/c-type-parser.ts"
export interface CTypeNode {
function: boolean;
template: boolean;
type: string;
argsTemplate: CTypeNode[];
argsFunc: CTypeNode[];
}
export class CTypeParser {
tokens: string[] = [];
cursor = 0;
lex(str: string) {
this.tokens = []
let current = ''
const BREAK_TOKENS = [' ', '(', ')', ',', '<', '>'];
for (let i = 0; i < str.length; i++) {
const c = str[i];
if (BREAK_TOKENS.includes(c)) {
if (current.length > 0) {
this.tokens.push(current);
current = '';
}
if (c !== ' ') {
this.tokens.push(c);
}
} else {
current += c;
}
}
if (current.length > 0) {
this.tokens.push(current);
}
}
parse(str: string | null = null) {
if (str) {
this.lex(str)
this.cursor = 0
}
const type: CTypeNode = {
argsFunc: [],
argsTemplate: [],
function: false,
template: false,
type: '',
}
do {
const parseCommaList = (arr) => {
do {
const res = this.parse();
if (res)
arr.push(res)
} while (this.eat(','));
}
if (this.eat('(')) {
type.function = true;
if (!this.next(')'))
parseCommaList(type.argsFunc);
this.eat(')', true)
} else if (this.eat('<')) {
type.template = true;
if (!this.next('>'))
parseCommaList(type.argsTemplate)
this.eat('>', true)
} else {
type.type = this.tokens[this.cursor]
this.cursor++;
}
if (this.next('(') || this.next('<')) {
continue;
}
break;
} while (true);
return type
}
eat(token, force = false) {
if (this.next(token)) {
this.cursor++;
return true;
} else {
if (force) throw new Error(`Excepted: ${token}, found ${this.next()} in ${this.tokens.join(' ')
}`)
}
return false
}
next(token: string | null = null) {
if (this.tokens[this.cursor] === token || !token) {
return this.tokens[this.cursor];
}
return false
}
formatToC(node: CTypeNode) {
let str = node.type;
if (node.template) {
str += '<' + node.argsTemplate.map(a => this.formatToC(a)).join(', ') + '>'
}
if (node.function) {
str += '(' + node.argsFunc.map(a => this.formatToC(a)).join(', ') + ')'
}
return str
}
formatToTypeScript(node: CTypeNode) {
node.type = node.type.split('::').pop() ?? node.type
const typeMap = {
'int': 'number',
'float': 'number',
'double': 'number',
'string': 'string',
'vector': 'Array',
'bool': 'boolean',
}
let tsBasicType = (typeMap[node.type] ?? node.type) + (node.template ? '<' + node.argsTemplate.map(a => this.formatToTypeScript(a)).join(', ') + '>' : '')
const ignoreTypes = ['variant', 'shared_ptr', 'function']
if (
ignoreTypes.includes(node.type)
) {
tsBasicType = node.argsTemplate.map(a => this.formatToTypeScript(a)).join(' | ')
} else if (node.type === 'optional') {
tsBasicType = `${this.formatToTypeScript(node.argsTemplate[0])} | undefined`
}
if (node.function) {
return `((${node.argsFunc.map(a => this.formatToTypeScript(a)).map((v, i) => `arg${i + 1}: ${v}`).join(', ')}) => ${tsBasicType})`
}
return tsBasicType;
}
}
export const cTypeToTypeScript = (str: string) => {
const parser = new CTypeParser();
parser.lex(str);
const res = parser.parse()
return parser.formatToTypeScript(res);
}
const parser = new CTypeParser();
const res = parser.parse('std::function(std::function)')
console.log(JSON.stringify(res, null, 2), parser.formatToTypeScript(res))
```
## /scripts/bindgen/clang-ast.d.ts
```ts path="/scripts/bindgen/clang-ast.d.ts"
export interface inner {
id?: string;
kind?: string;
loc?: loc;
range?: range;
inner?: inner[];
isImplicit?: boolean;
name?: string;
tagUsed?: string;
implicit?: boolean;
type?: type;
decl?: decl;
language?: string;
hasBraces?: boolean;
isReferenced?: boolean;
previousDecl?: string;
mangledName?: string;
variadic?: boolean;
inherited?: boolean;
storageClass?: string;
depth?: number;
index?: number;
completeDefinition?: boolean;
definitionData?: definitionData;
fixedUnderlyingType?: fixedUnderlyingType;
valueCategory?: string;
value?: boolean | string | number;
isDependent?: boolean;
isInstantiationDependent?: boolean;
isPostfix?: boolean;
opcode?: string;
canOverflow?: boolean;
isUsed?: boolean;
ownedTagDecl?: ownedTagDecl;
parentDeclContextId?: string;
scopedEnumTag?: string;
originalNamespace?: originalNamespace;
constexpr?: boolean;
explicitlyDefaulted?: string;
inline?: boolean;
visibility?: string;
castKind?: string;
referencedDecl?: referencedDecl;
cc?: string;
qualifiers?: string;
access?: string;
explicitlyDeleted?: boolean;
message?: string;
init?: string;
isPartOfExplicitCast?: boolean;
target?: target;
argType?: argType;
isArrow?: boolean;
referencedMemberDecl?: string;
templateName?: string;
isExpr?: boolean;
isAlias?: boolean;
defaultArg?: defaultArg;
bases?: bases[];
isParameterPack?: boolean;
isPack?: boolean;
containsUnexpandedPack?: boolean;
usesADL?: boolean;
lookups?: lookups[] | any[];
nonOdrUseReason?: string;
foundReferencedDecl?: foundReferencedDecl;
numElements?: number;
hasElse?: boolean;
computeLHSType?: computeLHSType;
computeResultType?: computeResultType;
storageDuration?: string;
size?: number;
qualifier?: string;
isFunction?: boolean;
const?: boolean;
volatile?: boolean;
refQualifier?: string;
exceptionSpec?: string;
isData?: boolean;
transformKind?: string;
member?: string;
isConstexpr?: boolean;
hasInClassInitializer?: boolean;
list?: boolean;
boundToLValueRef?: boolean;
anyInit?: anyInit;
ctorType?: ctorType;
zeroing?: boolean;
hadMultipleCandidates?: boolean;
constructionKind?: string;
virtual?: boolean;
baseInit?: baseInit;
path?: path[];
nrvo?: boolean;
conversionFunc?: conversionFunc;
cleanupsHaveSideEffects?: boolean;
temp?: string;
dtor?: dtor;
isGlobal?: boolean;
isPlacement?: boolean;
isInline?: boolean;
immediate?: boolean;
adl?: boolean;
['inherited from']?: InheritedFrom;
hasInit?: boolean;
initStyle?: string;
operatorNewDecl?: operatorNewDecl;
operatorDeleteDecl?: operatorDeleteDecl;
pack_index?: number;
mutable?: boolean;
pure?: boolean;
array_filler?: array_filler[];
isInvalid?: boolean;
}
export interface loc {
offset?: number;
file?: string;
line?: number;
col?: number;
tokLen?: number;
includedFrom?: includedFrom;
spellingLoc?: spellingLoc;
expansionLoc?: expansionLoc;
}
export interface range {
begin: begin;
end: end;
}
export interface begin {
offset?: number;
col?: number;
tokLen?: number;
includedFrom?: includedFrom;
line?: number;
spellingLoc?: spellingLoc;
expansionLoc?: expansionLoc;
file?: string;
}
export interface end {
offset?: number;
line?: number;
col?: number;
tokLen?: number;
includedFrom?: includedFrom;
spellingLoc?: spellingLoc;
expansionLoc?: expansionLoc;
}
export interface type {
qualType: string;
desugaredQualType?: string;
typeAliasDeclId?: string;
}
export interface decl {
id: string;
kind?: string;
name?: string;
}
export interface includedFrom {
file: string;
}
export interface definitionData {
canConstDefaultInit?: boolean;
copyAssign: copyAssign;
copyCtor: copyCtor;
defaultCtor: defaultCtor;
dtor: dtor;
hasConstexprNonCopyMoveConstructor?: boolean;
isAggregate?: boolean;
isEmpty?: boolean;
isLiteral?: boolean;
isPOD?: boolean;
isStandardLayout?: boolean;
isTrivial?: boolean;
isTriviallyCopyable?: boolean;
moveAssign: moveAssign;
moveCtor: moveCtor;
canPassInRegisters?: boolean;
hasUserDeclaredConstructor?: boolean;
hasVariantMembers?: boolean;
isPolymorphic?: boolean;
hasMutableFields?: boolean;
isGenericLambda?: boolean;
isLambda?: boolean;
isAbstract?: boolean;
}
export interface copyAssign {
hasConstParam: boolean;
implicitHasConstParam: boolean;
needsImplicit?: boolean;
simple?: boolean;
trivial?: boolean;
userDeclared?: boolean;
needsOverloadResolution?: boolean;
nonTrivial?: boolean;
}
export interface copyCtor {
hasConstParam: boolean;
implicitHasConstParam: boolean;
needsImplicit?: boolean;
simple?: boolean;
trivial?: boolean;
userDeclared?: boolean;
needsOverloadResolution?: boolean;
nonTrivial?: boolean;
}
export interface defaultCtor {
defaultedIsConstexpr?: boolean;
exists?: boolean;
isConstexpr?: boolean;
needsImplicit?: boolean;
trivial?: boolean;
nonTrivial?: boolean;
userProvided?: boolean;
}
export interface dtor {
irrelevant?: boolean;
needsImplicit?: boolean;
simple?: boolean;
trivial?: boolean;
nonTrivial?: boolean;
userDeclared?: boolean;
needsOverloadResolution?: boolean;
id?: string;
kind?: string;
name?: string;
type?: type;
}
export interface moveAssign {
exists?: boolean;
needsImplicit?: boolean;
simple?: boolean;
trivial?: boolean;
userDeclared?: boolean;
needsOverloadResolution?: boolean;
nonTrivial?: boolean;
}
export interface moveCtor {
exists?: boolean;
needsImplicit?: boolean;
simple?: boolean;
trivial?: boolean;
userDeclared?: boolean;
needsOverloadResolution?: boolean;
nonTrivial?: boolean;
}
export interface fixedUnderlyingType {
qualType: string;
desugaredQualType?: string;
typeAliasDeclId?: string;
}
export interface spellingLoc {
offset: number;
file?: string;
line?: number;
col: number;
tokLen: number;
includedFrom?: includedFrom;
presumedLine?: number;
}
export interface expansionLoc {
offset: number;
line?: number;
col: number;
tokLen: number;
includedFrom: includedFrom;
file?: string;
isMacroArgExpansion?: boolean;
}
export interface ownedTagDecl {
id: string;
kind: string;
name?: string;
}
export interface originalNamespace {
id: string;
kind: string;
name: string;
}
export interface referencedDecl {
id: string;
kind: string;
name?: string;
type: type;
}
export interface target {
id: string;
kind: string;
name: string;
type?: type;
}
export interface argType {
desugaredQualType?: string;
qualType: string;
typeAliasDeclId?: string;
}
export interface defaultArg {
kind: string;
type?: type;
isExpr?: boolean;
['inherited from']?: InheritedFrom;
}
export interface bases {
access: string;
type: type;
writtenAccess: string;
}
export interface lookups {
id: string;
kind: string;
name: string;
type?: type;
}
export interface foundReferencedDecl {
id: string;
kind: string;
name: string;
}
export interface computeLHSType {
qualType: string;
desugaredQualType?: string;
typeAliasDeclId?: string;
}
export interface computeResultType {
qualType: string;
desugaredQualType?: string;
typeAliasDeclId?: string;
}
export interface anyInit {
id: string;
kind: string;
name: string;
type: type;
}
export interface ctorType {
qualType: string;
desugaredQualType?: string;
}
export interface baseInit {
desugaredQualType?: string;
qualType: string;
typeAliasDeclId?: string;
}
export interface path {
name: string;
}
export interface conversionFunc {
id: string;
kind: string;
name: string;
type: type;
}
export interface InheritedFrom {
id: string;
kind: string;
name?: string;
type?: type;
}
export interface operatorNewDecl {
id: string;
kind: string;
name: string;
type: type;
}
export interface operatorDeleteDecl {
id: string;
kind: string;
name: string;
type: type;
}
export interface array_filler {
id: string;
kind: string;
range: range;
type: type;
valueCategory: string;
}
export type ClangASTD = inner;
```
## /scripts/bindgen/generate-bindings.bat
```bat path="/scripts/bindgen/generate-bindings.bat"
cd scripts
cd bindgen
clang++ -Xclang -ast-dump=json -fsyntax-only -Xclang -ast-dump-filter=mb_shell::js -std=c++2c ..\..\src\shell\script\binding_types.h > .\ast.json
yarn && yarn gen
echo Done
```
## /scripts/bindgen/index.ts
```ts path="/scripts/bindgen/index.ts"
import { ClangASTD } from "./clang-ast";
import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { cTypeToTypeScript } from "./c-type-parser";
const ast = JSON.parse(readFileSync(join(__dirname, "ast.json"), "utf-8")) as ClangASTD;
const targetFile = 'binding_types.h'
const outputFile = 'binding_qjs.h'
// filter out loc.file contains targetFile
const origFile = readFileSync(join(__dirname, '../../src/shell/script/binding_types.h'), 'utf-8').split('\n').map(v => v.trim())
let binding =
`// This file is generated by scripts/bindgen/index.ts
// Do not modify this file manually!
#pragma once
#include "binding_types.h"
#include "quickjs.h"
#include "quickjspp.hpp"
template
struct js_bind {
static void bind(qjs::Context::Module &mod) {}
};
`
let typescriptDef = `// This file is generated by scripts/bindgen/index.ts
// Do not modify this file manually!
declare module 'mshell' {
`
const parseFunctionQualType = (type: string) => {
// std::variant (std::string, std::string)
// std::function (int, std::string)
enum State {
ReturnType,
Args,
Done
}
let state = State.ReturnType;
let returnType = '';
let currentArg = '';
let args: string[] = [];
let depth = 0;
let angleBracketDepth = 0;
for (let i = 0; i < type.length; i++) {
const char = type[i];
if (char === '<') {
angleBracketDepth++;
} else if (char === '>') {
angleBracketDepth--;
}
switch (state) {
case State.ReturnType:
if (char === '(' && angleBracketDepth === 0) {
state = State.Args;
returnType = returnType.trim();
} else {
returnType += char;
}
break;
case State.Args:
if (char === '(') depth++;
if (char === ')') {
if (depth === 0 && angleBracketDepth === 0) {
if (currentArg.trim()) args.push(currentArg.trim());
state = State.Done;
break;
}
depth--;
}
if (char === ',' && depth === 0 && angleBracketDepth === 0) {
args.push(currentArg.trim());
currentArg = '';
} else {
currentArg += char;
}
break;
}
}
if (state !== State.Done) {
throw new Error('Invalid function type');
}
return {
returnType,
args
};
}
if (ast.kind !== 'NamespaceDecl') {
throw new Error('Root node is not a NamespaceDecl');
}
let currentNamespace = 'mb_shell::js'
const generateForRecordDecl = (node_struct: ClangASTD) => {
if (node_struct.kind !== 'CXXRecordDecl') {
throw new Error('Node is not a RecordDecl');
}
const structName = node_struct.name;
const fields: {
name: string;
type: string;
comment?: string;
}[] = [];
const methods: {
name: string;
returnType: string;
args: string[];
static: boolean;
comment?: string;
argNames?: string[];
}[] = [];
if (!node_struct.inner) return;
for (const node of node_struct.inner) {
if (node.name?.startsWith('$')) continue;
const lineNum = node.loc?.line;
// find comment above
let comment = '';
if (lineNum) {
let rangeCommentCnt = 0;
for (let i = lineNum - 2; i >= 0; i--) {
const line = origFile[i];
if (!line) continue;
if (line.startsWith('//')) {
comment = line.substring(2) + '\n' + comment;
continue;
}
if (line.startsWith('/*')) {
rangeCommentCnt++;
continue;
}
if (line.endsWith('*/')) {
rangeCommentCnt--;
continue;
}
if (rangeCommentCnt === 0) break;
else comment = line + '\n' + comment;
}
}
if (node.kind === 'FieldDecl') {
fields.push({
name: node.name!,
type: node.type!.qualType,
comment: comment.length > 0 ? comment : undefined
});
}
if (node.kind === 'CXXMethodDecl') {
const parsed = parseFunctionQualType(node.type!.qualType);
if (
['operator='].includes(node.name!)
) continue;
const argNames: string[] = [];
if (node.inner) {
for (const arg of node.inner) {
if (arg.kind === 'ParmVarDecl') {
argNames.push(arg.name!);
}
}
}
methods.push({
name: node.name!,
returnType: parsed.returnType,
args: parsed.args,
static: node.storageClass === 'static',
comment: comment.length > 0 ? comment : undefined,
argNames
});
}
}
// console.log({
// structName, fields, methods
// });
binding += `
template <> struct qjs::js_traits<${currentNamespace}::${structName}> {
static ${currentNamespace}::${structName} unwrap(JSContext *ctx, JSValueConst v) {
${currentNamespace}::${structName} obj;
`;
for (const field of fields) {
binding += `
obj.${field.name} = js_traits<${field.type}>::unwrap(ctx, JS_GetPropertyStr(ctx, v, "${field.name}"));
`;
}
binding += `
return obj;
}
static JSValue wrap(JSContext *ctx, const ${currentNamespace}::${structName} &val) noexcept {
JSValue obj = JS_NewObject(ctx);
`;
for (const field of fields) {
binding += `
JS_SetPropertyStr(ctx, obj, "${field.name}", js_traits<${field.type}>::wrap(ctx, val.${field.name}));
`;
}
binding += `
return obj;
}
};`;
/**
*
* module.class_("MyClass")
.constructor<>()
.constructor>("MyClassA")
.fun<&MyClass::member_variable>("member_variable")
.fun<&MyClass::member_function>("member_function")
.static_fun<&MyClass::static_function>("static_function")
*/
binding += `
template<> struct js_bind<${currentNamespace}::${structName}> {
static void bind(qjs::Context::Module &mod) {
mod.class_<${currentNamespace}::${structName}>("${structName}")
.constructor<>()`;
for (const method of methods) {
if (method.static) {
binding += `
.static_fun<&${currentNamespace}::${structName}::${method.name}>("${method.name}")`;
} else {
binding += `
.fun<&${currentNamespace}::${structName}::${method.name}>("${method.name}")`;
}
}
for (const field of fields) {
binding += `
.fun<&${currentNamespace}::${structName}::${field.name}>("${field.name}")`;
}
binding += `
;
}
};
`;
typescriptDef += `
export class ${structName} {
\t${fields.map(field => {
let fieldDef = `${field.name}${field.type.startsWith('std::optional') ? '?' : ''
}: ${cTypeToTypeScript(field.type)}`;
if (field.comment) {
fieldDef = `
/**
* ${field.comment.trim().split('\n').join('\n * ')}
*/
${fieldDef}
`
}
return fieldDef;
}).join('\n\t')}
\t${methods.map(method => {
let methodDef = `${method.static ? 'static ' : ''}${method.name}: ${cTypeToTypeScript(`${method.returnType}(${method.args.join(', ')})`)}`
// if (method.comment) {
// methodDef = method.comment.trim().split('\n').map(v => `// ${v}`).join('\n\t')
// + '\n\t' + methodDef;
// }
// if (method.argNames) {
// methodDef = '// Args: ' + method.argNames.join(', ') + '\n\t' + methodDef;
// }
let comments = '';
if (method.comment) {
comments += method.comment.trim();
}
methodDef = `
/**
* ${comments.split('\n').join('\n * ')}
* @param ${method.args.map((arg , i) => `${method.argNames![i]}: ${cTypeToTypeScript(arg)}`).join(', ')}
* @returns ${cTypeToTypeScript(method.returnType)}
*/
${methodDef}
`
return methodDef;
}).join('\n\t')}
}
`;
}
const structNames: string[] = []
for (const node of ast.inner!) {
if (node.kind === 'CXXRecordDecl') {
generateForRecordDecl(node);
if (node.name && node.inner)
structNames.push(node.name);
}
}
binding += `
inline void bindAll(qjs::Context::Module &mod) {
`
for (const structName of structNames) {
binding += `
js_bind<${currentNamespace}::${structName}>::bind(mod);
`
}
binding += `
}
`
typescriptDef += `
}
`
const paths = [
join(__dirname, 'src/shell/script'),
join(__dirname, '../src/shell/script'),
join(__dirname, '../../src/shell/script')
]
typescriptDef += readFileSync(join(__dirname, 'quickjs-types.txt'), 'utf-8');
for (const path of paths) {
try {
if (existsSync(join(path, targetFile))) {
writeFileSync(join(path, outputFile), binding);
writeFileSync(join(path, 'binding_types.d.ts'), typescriptDef);
break;
}
} catch (e) {
console.error(e);
}
}
rmSync(join(__dirname, 'ast.json'));
```
## /scripts/bindgen/package.json
```json path="/scripts/bindgen/package.json"
{
"packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e",
"name": "bindgen",
"version": "1.0.0",
"main": "index.js",
"author": "MicroBlock <66859419+std-microblock@users.noreply.github.com>",
"license": "MIT",
"dependencies": {
"@types/node": "^22.10.5",
"esbuild": "^0.24.2",
"esbuild-register": "^3.6.0"
},
"scripts": {
"gen": "node -r esbuild-register index.ts",
"typegen": "node -r esbuild-register typegen.ts",
"parser-test": "node -r esbuild-register c-type-parser.ts"
}
}
```
## /scripts/bindgen/quickjs-types.txt
declare module "mshell" {
export function println(...args: any[]);
type size_t = number;
type uint8_t = number;
type uint16_t = number;
type uint32_t = number;
type uint64_t = number;
type int8_t = number;
type int16_t = number;
type int32_t = number;
type int64_t = number;
type intptr_t = number;
type uintptr_t = number;
type ssize_t = number;
}
// helper to access field based on dot path
type FieldPath = K extends keyof T ? T[K] : K extends `${infer K1}.${infer K2}` ? K1 extends keyof T ? FieldPath : never : never;
declare function plugin(import_meta: { url: string }, default_config?: T): {
i18n: {
define(lang: string, data: { [key: string]: string }): void;
t(key: string): string;
};
set_on_menu(callback: (m:
import('mshell').menu_controller
) => void): void;
config_directory: string;
config: {
read_config(): void;
write_config(): void;
get(key: K): FieldPath;
set(key: K, value: FieldPath): void;
all(): T;
};
log(...args: any[]): void;
};
declare type ShellPluginHelper = ReturnType;
## /scripts/bindgen/typegen.ts
```ts path="/scripts/bindgen/typegen.ts"
import { readFileSync, writeFileSync } from "fs";
import { types } from "util";
type Type = {
isArr: boolean;
type: 'string' | 'number' | 'boolean' | string;
}
type TypeMap = {
[typeName: string]: {
[fieldName: string]: {
types: Type[];
isOptional: boolean;
}
};
};
function generateInterfaces(json: any): string {
const typeMap: TypeMap = {};
const traverse = (obj: any, k = "Main") => {
typeMap[k] ??= {
};
const typeCur = typeMap[k];
for (const key in typeCur) {
if (!obj[key]) {
typeCur[key].isOptional = true;
}
}
for (const key in obj) {
const value = obj[key];
typeCur[key] ??= {
types: [],
isOptional: false
};
const type = typeCur[key];
const pushIfNotExists = (t: Type) => {
if (type.types.findIndex(x => x.type === t.type && x.isArr === t.isArr) === -1) {
type.types.push(t);
}
}
if (Array.isArray(value)) {
if (value.length === 0) {
pushIfNotExists({
isArr: true,
type: 'any'
});
} else {
for (const val of value) {
if (typeof val === 'object') {
traverse(val, key);
pushIfNotExists({
isArr: true,
type: key
});
} else {
pushIfNotExists({
isArr: true,
type: typeof val
});
}
}
}
} else if (typeof value === 'object') {
pushIfNotExists({
isArr: false,
type: key
});
traverse(value, key);
} else {
pushIfNotExists({
isArr: false,
type: typeof value
});
}
}
}
traverse(json);
let ts = '';
const escapeForType = (type: string) => {
if (!type.includes(' ')) return type;
return type.split(' ').map(x => x[0].toUpperCase() + x.slice(1)).join('');
}
const escapeForField = (field: string) => {
const keywords = ['delete', 'export', 'import', 'in', 'instanceof', 'new', 'typeof', 'void', 'yield'];
if (keywords.includes(field) || field.includes('-') || field.includes(' ')) {
return `['${field}']`;
}
return field;
}
for (const type in typeMap) {
ts += `export interface ${escapeForType(type)} {\n`;
for (const field in typeMap[type]) {
const { types, isOptional } = typeMap[type][field];
ts += ` ${escapeForField(field)}${isOptional ? '?' : ''}: ${types.map(x => `${escapeForType(x.type)}${x.isArr ? '[]' : ''}`).join(' | ')};\n`;
}
ts += '}\n\n';
}
return ts;
}
const json = JSON.parse(
readFileSync('ast.json', 'utf-8')
)
const ts = generateInterfaces({
inner: json
});
writeFileSync('ast.d.ts', ts);
```
## /scripts/bindgen/yarn.lock
```lock path="/scripts/bindgen/yarn.lock"
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
"@esbuild/aix-ppc64@0.24.2":
version "0.24.2"
resolved "https://registry.yarnpkg.com/@esbuild/aix-ppc64/-/aix-ppc64-0.24.2.tgz#38848d3e25afe842a7943643cbcd387cc6e13461"
integrity sha512-thpVCb/rhxE/BnMLQ7GReQLLN8q9qbHmI55F4489/ByVg2aQaQ6kbcLb6FHkocZzQhxc4gx0sCk0tJkKBFzDhA==
"@esbuild/android-arm64@0.24.2":
version "0.24.2"
resolved "https://registry.yarnpkg.com/@esbuild/android-arm64/-/android-arm64-0.24.2.tgz#f592957ae8b5643129fa889c79e69cd8669bb894"
integrity sha512-cNLgeqCqV8WxfcTIOeL4OAtSmL8JjcN6m09XIgro1Wi7cF4t/THaWEa7eL5CMoMBdjoHOTh/vwTO/o2TRXIyzg==
"@esbuild/android-arm@0.24.2":
version "0.24.2"
resolved "https://registry.yarnpkg.com/@esbuild/android-arm/-/android-arm-0.24.2.tgz#72d8a2063aa630308af486a7e5cbcd1e134335b3"
integrity sha512-tmwl4hJkCfNHwFB3nBa8z1Uy3ypZpxqxfTQOcHX+xRByyYgunVbZ9MzUUfb0RxaHIMnbHagwAxuTL+tnNM+1/Q==
"@esbuild/android-x64@0.24.2":
version "0.24.2"
resolved "https://registry.yarnpkg.com/@esbuild/android-x64/-/android-x64-0.24.2.tgz#9a7713504d5f04792f33be9c197a882b2d88febb"
integrity sha512-B6Q0YQDqMx9D7rvIcsXfmJfvUYLoP722bgfBlO5cGvNVb5V/+Y7nhBE3mHV9OpxBf4eAS2S68KZztiPaWq4XYw==
"@esbuild/darwin-arm64@0.24.2":
version "0.24.2"
resolved "https://registry.yarnpkg.com/@esbuild/darwin-arm64/-/darwin-arm64-0.24.2.tgz#02ae04ad8ebffd6e2ea096181b3366816b2b5936"
integrity sha512-kj3AnYWc+CekmZnS5IPu9D+HWtUI49hbnyqk0FLEJDbzCIQt7hg7ucF1SQAilhtYpIujfaHr6O0UHlzzSPdOeA==
"@esbuild/darwin-x64@0.24.2":
version "0.24.2"
resolved "https://registry.yarnpkg.com/@esbuild/darwin-x64/-/darwin-x64-0.24.2.tgz#9ec312bc29c60e1b6cecadc82bd504d8adaa19e9"
integrity sha512-WeSrmwwHaPkNR5H3yYfowhZcbriGqooyu3zI/3GGpF8AyUdsrrP0X6KumITGA9WOyiJavnGZUwPGvxvwfWPHIA==
"@esbuild/freebsd-arm64@0.24.2":
version "0.24.2"
resolved "https://registry.yarnpkg.com/@esbuild/freebsd-arm64/-/freebsd-arm64-0.24.2.tgz#5e82f44cb4906d6aebf24497d6a068cfc152fa00"
integrity sha512-UN8HXjtJ0k/Mj6a9+5u6+2eZ2ERD7Edt1Q9IZiB5UZAIdPnVKDoG7mdTVGhHJIeEml60JteamR3qhsr1r8gXvg==
"@esbuild/freebsd-x64@0.24.2":
version "0.24.2"
resolved "https://registry.yarnpkg.com/@esbuild/freebsd-x64/-/freebsd-x64-0.24.2.tgz#3fb1ce92f276168b75074b4e51aa0d8141ecce7f"
integrity sha512-TvW7wE/89PYW+IevEJXZ5sF6gJRDY/14hyIGFXdIucxCsbRmLUcjseQu1SyTko+2idmCw94TgyaEZi9HUSOe3Q==
"@esbuild/linux-arm64@0.24.2":
version "0.24.2"
resolved "https://registry.yarnpkg.com/@esbuild/linux-arm64/-/linux-arm64-0.24.2.tgz#856b632d79eb80aec0864381efd29de8fd0b1f43"
integrity sha512-7HnAD6074BW43YvvUmE/35Id9/NB7BeX5EoNkK9obndmZBUk8xmJJeU7DwmUeN7tkysslb2eSl6CTrYz6oEMQg==
"@esbuild/linux-arm@0.24.2":
version "0.24.2"
resolved "https://registry.yarnpkg.com/@esbuild/linux-arm/-/linux-arm-0.24.2.tgz#c846b4694dc5a75d1444f52257ccc5659021b736"
integrity sha512-n0WRM/gWIdU29J57hJyUdIsk0WarGd6To0s+Y+LwvlC55wt+GT/OgkwoXCXvIue1i1sSNWblHEig00GBWiJgfA==
"@esbuild/linux-ia32@0.24.2":
version "0.24.2"
resolved "https://registry.yarnpkg.com/@esbuild/linux-ia32/-/linux-ia32-0.24.2.tgz#f8a16615a78826ccbb6566fab9a9606cfd4a37d5"
integrity sha512-sfv0tGPQhcZOgTKO3oBE9xpHuUqguHvSo4jl+wjnKwFpapx+vUDcawbwPNuBIAYdRAvIDBfZVvXprIj3HA+Ugw==
"@esbuild/linux-loong64@0.24.2":
version "0.24.2"
resolved "https://registry.yarnpkg.com/@esbuild/linux-loong64/-/linux-loong64-0.24.2.tgz#1c451538c765bf14913512c76ed8a351e18b09fc"
integrity sha512-CN9AZr8kEndGooS35ntToZLTQLHEjtVB5n7dl8ZcTZMonJ7CCfStrYhrzF97eAecqVbVJ7APOEe18RPI4KLhwQ==
"@esbuild/linux-mips64el@0.24.2":
version "0.24.2"
resolved "https://registry.yarnpkg.com/@esbuild/linux-mips64el/-/linux-mips64el-0.24.2.tgz#0846edeefbc3d8d50645c51869cc64401d9239cb"
integrity sha512-iMkk7qr/wl3exJATwkISxI7kTcmHKE+BlymIAbHO8xanq/TjHaaVThFF6ipWzPHryoFsesNQJPE/3wFJw4+huw==
"@esbuild/linux-ppc64@0.24.2":
version "0.24.2"
resolved "https://registry.yarnpkg.com/@esbuild/linux-ppc64/-/linux-ppc64-0.24.2.tgz#8e3fc54505671d193337a36dfd4c1a23b8a41412"
integrity sha512-shsVrgCZ57Vr2L8mm39kO5PPIb+843FStGt7sGGoqiiWYconSxwTiuswC1VJZLCjNiMLAMh34jg4VSEQb+iEbw==
"@esbuild/linux-riscv64@0.24.2":
version "0.24.2"
resolved "https://registry.yarnpkg.com/@esbuild/linux-riscv64/-/linux-riscv64-0.24.2.tgz#6a1e92096d5e68f7bb10a0d64bb5b6d1daf9a694"
integrity sha512-4eSFWnU9Hhd68fW16GD0TINewo1L6dRrB+oLNNbYyMUAeOD2yCK5KXGK1GH4qD/kT+bTEXjsyTCiJGHPZ3eM9Q==
"@esbuild/linux-s390x@0.24.2":
version "0.24.2"
resolved "https://registry.yarnpkg.com/@esbuild/linux-s390x/-/linux-s390x-0.24.2.tgz#ab18e56e66f7a3c49cb97d337cd0a6fea28a8577"
integrity sha512-S0Bh0A53b0YHL2XEXC20bHLuGMOhFDO6GN4b3YjRLK//Ep3ql3erpNcPlEFed93hsQAjAQDNsvcK+hV90FubSw==
"@esbuild/linux-x64@0.24.2":
version "0.24.2"
resolved "https://registry.yarnpkg.com/@esbuild/linux-x64/-/linux-x64-0.24.2.tgz#8140c9b40da634d380b0b29c837a0b4267aff38f"
integrity sha512-8Qi4nQcCTbLnK9WoMjdC9NiTG6/E38RNICU6sUNqK0QFxCYgoARqVqxdFmWkdonVsvGqWhmm7MO0jyTqLqwj0Q==
"@esbuild/netbsd-arm64@0.24.2":
version "0.24.2"
resolved "https://registry.yarnpkg.com/@esbuild/netbsd-arm64/-/netbsd-arm64-0.24.2.tgz#65f19161432bafb3981f5f20a7ff45abb2e708e6"
integrity sha512-wuLK/VztRRpMt9zyHSazyCVdCXlpHkKm34WUyinD2lzK07FAHTq0KQvZZlXikNWkDGoT6x3TD51jKQ7gMVpopw==
"@esbuild/netbsd-x64@0.24.2":
version "0.24.2"
resolved "https://registry.yarnpkg.com/@esbuild/netbsd-x64/-/netbsd-x64-0.24.2.tgz#7a3a97d77abfd11765a72f1c6f9b18f5396bcc40"
integrity sha512-VefFaQUc4FMmJuAxmIHgUmfNiLXY438XrL4GDNV1Y1H/RW3qow68xTwjZKfj/+Plp9NANmzbH5R40Meudu8mmw==
"@esbuild/openbsd-arm64@0.24.2":
version "0.24.2"
resolved "https://registry.yarnpkg.com/@esbuild/openbsd-arm64/-/openbsd-arm64-0.24.2.tgz#58b00238dd8f123bfff68d3acc53a6ee369af89f"
integrity sha512-YQbi46SBct6iKnszhSvdluqDmxCJA+Pu280Av9WICNwQmMxV7nLRHZfjQzwbPs3jeWnuAhE9Jy0NrnJ12Oz+0A==
"@esbuild/openbsd-x64@0.24.2":
version "0.24.2"
resolved "https://registry.yarnpkg.com/@esbuild/openbsd-x64/-/openbsd-x64-0.24.2.tgz#0ac843fda0feb85a93e288842936c21a00a8a205"
integrity sha512-+iDS6zpNM6EnJyWv0bMGLWSWeXGN/HTaF/LXHXHwejGsVi+ooqDfMCCTerNFxEkM3wYVcExkeGXNqshc9iMaOA==
"@esbuild/sunos-x64@0.24.2":
version "0.24.2"
resolved "https://registry.yarnpkg.com/@esbuild/sunos-x64/-/sunos-x64-0.24.2.tgz#8b7aa895e07828d36c422a4404cc2ecf27fb15c6"
integrity sha512-hTdsW27jcktEvpwNHJU4ZwWFGkz2zRJUz8pvddmXPtXDzVKTTINmlmga3ZzwcuMpUvLw7JkLy9QLKyGpD2Yxig==
"@esbuild/win32-arm64@0.24.2":
version "0.24.2"
resolved "https://registry.yarnpkg.com/@esbuild/win32-arm64/-/win32-arm64-0.24.2.tgz#c023afb647cabf0c3ed13f0eddfc4f1d61c66a85"
integrity sha512-LihEQ2BBKVFLOC9ZItT9iFprsE9tqjDjnbulhHoFxYQtQfai7qfluVODIYxt1PgdoyQkz23+01rzwNwYfutxUQ==
"@esbuild/win32-ia32@0.24.2":
version "0.24.2"
resolved "https://registry.yarnpkg.com/@esbuild/win32-ia32/-/win32-ia32-0.24.2.tgz#96c356132d2dda990098c8b8b951209c3cd743c2"
integrity sha512-q+iGUwfs8tncmFC9pcnD5IvRHAzmbwQ3GPS5/ceCyHdjXubwQWI12MKWSNSMYLJMq23/IUCvJMS76PDqXe1fxA==
"@esbuild/win32-x64@0.24.2":
version "0.24.2"
resolved "https://registry.yarnpkg.com/@esbuild/win32-x64/-/win32-x64-0.24.2.tgz#34aa0b52d0fbb1a654b596acfa595f0c7b77a77b"
integrity sha512-7VTgWzgMGvup6aSqDPLiW5zHaxYJGTO4OokMjIlrCtf+VpEL+cXKtCvg723iguPYI5oaUNdS+/V7OU2gvXVWEg==
"@types/node@^22.10.5":
version "22.10.5"
resolved "https://registry.yarnpkg.com/@types/node/-/node-22.10.5.tgz#95af89a3fb74a2bb41ef9927f206e6472026e48b"
integrity sha512-F8Q+SeGimwOo86fiovQh8qiXfFEh2/ocYv7tU5pJ3EXMSSxk1Joj5wefpFK2fHTf/N6HKGSxIDBT9f3gCxXPkQ==
dependencies:
undici-types "~6.20.0"
debug@^4.3.4:
version "4.4.0"
resolved "https://registry.yarnpkg.com/debug/-/debug-4.4.0.tgz#2b3f2aea2ffeb776477460267377dc8710faba8a"
integrity sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==
dependencies:
ms "^2.1.3"
esbuild-register@^3.6.0:
version "3.6.0"
resolved "https://registry.yarnpkg.com/esbuild-register/-/esbuild-register-3.6.0.tgz#cf270cfa677baebbc0010ac024b823cbf723a36d"
integrity sha512-H2/S7Pm8a9CL1uhp9OvjwrBh5Pvx0H8qVOxNu8Wed9Y7qv56MPtq+GGM8RJpq6glYJn9Wspr8uw7l55uyinNeg==
dependencies:
debug "^4.3.4"
esbuild@^0.24.2:
version "0.24.2"
resolved "https://registry.yarnpkg.com/esbuild/-/esbuild-0.24.2.tgz#b5b55bee7de017bff5fb8a4e3e44f2ebe2c3567d"
integrity sha512-+9egpBW8I3CD5XPe0n6BfT5fxLzxrlDzqydF3aviG+9ni1lDC/OvMHcxqEFV0+LANZG5R1bFMWfUrjVsdwxJvA==
optionalDependencies:
"@esbuild/aix-ppc64" "0.24.2"
"@esbuild/android-arm" "0.24.2"
"@esbuild/android-arm64" "0.24.2"
"@esbuild/android-x64" "0.24.2"
"@esbuild/darwin-arm64" "0.24.2"
"@esbuild/darwin-x64" "0.24.2"
"@esbuild/freebsd-arm64" "0.24.2"
"@esbuild/freebsd-x64" "0.24.2"
"@esbuild/linux-arm" "0.24.2"
"@esbuild/linux-arm64" "0.24.2"
"@esbuild/linux-ia32" "0.24.2"
"@esbuild/linux-loong64" "0.24.2"
"@esbuild/linux-mips64el" "0.24.2"
"@esbuild/linux-ppc64" "0.24.2"
"@esbuild/linux-riscv64" "0.24.2"
"@esbuild/linux-s390x" "0.24.2"
"@esbuild/linux-x64" "0.24.2"
"@esbuild/netbsd-arm64" "0.24.2"
"@esbuild/netbsd-x64" "0.24.2"
"@esbuild/openbsd-arm64" "0.24.2"
"@esbuild/openbsd-x64" "0.24.2"
"@esbuild/sunos-x64" "0.24.2"
"@esbuild/win32-arm64" "0.24.2"
"@esbuild/win32-ia32" "0.24.2"
"@esbuild/win32-x64" "0.24.2"
ms@^2.1.3:
version "2.1.3"
resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2"
integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==
undici-types@~6.20.0:
version "6.20.0"
resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-6.20.0.tgz#8171bf22c1f588d1554d55bf204bc624af388433"
integrity sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==
```
## /scripts/debug.cmd
```cmd path="/scripts/debug.cmd"
set LLDB_USE_NATIVE_PDB_READER=1
xmake b shell_test
xmake r -d shell_test
```
## /scripts/rebuild.ps1
```ps1 path="/scripts/rebuild.ps1"
$pids = (Get-WmiObject Win32_Process -Filter "name = 'explorer.exe'" | where { $_.CommandLine -like '*/factory,{75dff2b7-6936-4c06-a8bb-676a7b00b24b}*' }).ProcessId
foreach ($pidx in $pids) {
Stop-Process -Id $pidx -Force
}
xmake b --yes inject
xmake b --yes shell && xmake r inject new
```
## /scripts/right_click.ahk
```ahk path="/scripts/right_click.ahk"
Sleep, 1000
counter := 0
#SingleInstance force
Gui, Add, Edit, vLog w400 h400,
Gui, Show, w400 h400
stop := false
Loop
{
Send {RButton}
Sleep, 100
Send {Esc}
Sleep, 100
counter := counter + 1
GuiControl,, Log, %counter%
if (stop)
{
break
}
}
F10::
stop := true
```
## /src/inject/data_directory.inc
```inc path="/src/inject/data_directory.inc"
std::filesystem::path data_directory() {
static std::optional path;
static std::mutex mtx;
std::lock_guard lock(mtx);
if (!path) {
wchar_t home_dir[MAX_PATH];
GetEnvironmentVariableW(L"USERPROFILE", home_dir, MAX_PATH);
path = std::filesystem::path(home_dir) / ".breeze-shell";
}
if (!std::filesystem::exists(*path)) {
std::filesystem::create_directories(*path);
}
return path.value();
}
```
## /src/inject/inject.cc
```cc path="/src/inject/inject.cc"
#include
#include
#include
#include
#include
#include
#include "animator.h"
#include "ui.h"
#include "widget.h"
static unsigned char g_icon_png[] = {
#include "icon-small.png.h"
};
#include
#include "data_directory.inc"
#include
#include
#include
namespace fs = std::filesystem;
std::wstring GetModuleDirectory() {
wchar_t path[MAX_PATH];
GetModuleFileNameW(NULL, path, MAX_PATH);
return fs::path(path).parent_path().wstring();
}
std::vector GetExplorerPIDs() {
std::vector pids;
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot != INVALID_HANDLE_VALUE) {
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
if (Process32First(hSnapshot, &pe32)) {
do {
if (strcmp(pe32.szExeFile, "explorer.exe") == 0) {
pids.push_back(pe32.th32ProcessID);
}
} while (Process32Next(hSnapshot, &pe32));
}
CloseHandle(hSnapshot);
}
return pids;
}
void GetDebugPrivilege() {
HANDLE hToken;
LUID luid;
TOKEN_PRIVILEGES tkp;
if (!OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) {
std::cerr << "OpenProcessToken failed: " << GetLastError() << std::endl;
return;
}
if (!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid)) {
std::cerr << "LookupPrivilegeValue failed: " << GetLastError() << std::endl;
CloseHandle(hToken);
return;
}
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Luid = luid;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (!AdjustTokenPrivileges(hToken, FALSE, &tkp, sizeof(TOKEN_PRIVILEGES),
NULL, NULL)) {
std::cerr << "AdjustTokenPrivileges failed: " << GetLastError()
<< std::endl;
CloseHandle(hToken);
return;
}
CloseHandle(hToken);
}
int InjectToPID(int targetPID, std::wstring_view dllPath) {
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, targetPID);
if (hProcess == NULL) {
std::cerr << "OpenProcess failed: " << GetLastError() << std::endl;
return 1;
}
LPVOID remoteString =
VirtualAllocEx(hProcess, NULL, (dllPath.size() + 1) * sizeof(wchar_t),
MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if (remoteString == NULL) {
std::cerr << "VirtualAllocEx failed: " << GetLastError() << std::endl;
CloseHandle(hProcess);
return 1;
}
if (!WriteProcessMemory(hProcess, remoteString, dllPath.data(),
(dllPath.size() + 1) * sizeof(wchar_t), NULL)) {
std::cerr << "WriteProcessMemory failed: " << GetLastError() << std::endl;
VirtualFreeEx(hProcess, remoteString, 0, MEM_RELEASE);
CloseHandle(hProcess);
return 1;
}
HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
LPTHREAD_START_ROUTINE loadLibraryW =
(LPTHREAD_START_ROUTINE)GetProcAddress(hKernel32, "LoadLibraryW");
HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0, loadLibraryW,
remoteString, 0, NULL);
if (hThread == NULL) {
std::cerr << "CreateRemoteThread failed: " << GetLastError() << std::endl;
VirtualFreeEx(hProcess, remoteString, 0, MEM_RELEASE);
CloseHandle(hProcess);
return 1;
}
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
VirtualFreeEx(hProcess, remoteString, 0, MEM_RELEASE);
CloseHandle(hProcess);
std::cout << "DLL injected successfully." << std::endl;
return 0;
}
bool IsInjected(DWORD targetPID, std::wstring &dllPath) {
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
FALSE, targetPID);
if (hProcess == NULL) {
std::cerr << "OpenProcess failed: " << GetLastError() << std::endl;
return false;
}
HMODULE hMods[1024];
DWORD cbNeeded;
if (EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)) {
for (int i = 0; i < (cbNeeded / sizeof(HMODULE)); i++) {
wchar_t szModName[MAX_PATH];
if (GetModuleFileNameExW(hProcess, hMods[i], szModName,
sizeof(szModName) / sizeof(wchar_t))) {
if (dllPath.ends_with(
fs::path(szModName).filename().wstring().c_str())) {
CloseHandle(hProcess);
return true;
}
}
}
}
CloseHandle(hProcess);
return false;
}
static std::wstring dllPath;
int NewExplorerProcessAndInject() {
GetDebugPrivilege();
std::vector initialPIDs = GetExplorerPIDs();
ShellExecuteW(NULL, L"open", L"explorer.exe", L"C:/", NULL, SW_SHOW);
std::this_thread::sleep_for(std::chrono::seconds(1));
std::vector newPIDs = GetExplorerPIDs();
DWORD targetPID = 0;
for (DWORD pid : newPIDs) {
bool found = false;
for (DWORD initialPID : initialPIDs) {
if (pid == initialPID) {
found = true;
break;
}
}
if (!found) {
targetPID = pid;
break;
}
}
if (targetPID == 0) {
std::cerr << "Could not find new explorer.exe process." << std::endl;
return 1;
}
InjectToPID(targetPID, dllPath);
return 0;
}
static bool english = GetUserDefaultUILanguage() != 2052;
struct inject_ui_title : public ui::widget_flex {
inject_ui_title() {
gap = 10;
{
auto title = std::make_shared();
title->text = "breeze-shell";
title->font_size = 26;
title->color.reset_to({1, 1, 1, 1});
add_child(title);
}
{
auto title = std::make_shared();
title->text = "Bring fluency & delication back to Windows";
title->font_size = 14;
title->color.reset_to({1, 1, 1, 0.8});
add_child(title);
}
}
};
struct button_widget : public ui::padding_widget {
button_widget(const std::string &button_text) {
auto text = emplace_child();
text->text = button_text;
text->font_size = 14;
text->color.reset_to({1, 1, 1, 1});
padding_bottom->reset_to(10);
padding_top->reset_to(10);
padding_left->reset_to(22);
padding_right->reset_to(20);
}
ui::animated_color bg_color = {this, 40 / 255.f, 40 / 255.f, 40 / 255.f, 0.6};
virtual void on_click() = 0;
void render(ui::nanovg_context ctx) override {
ctx.fillColor(bg_color.nvg());
ctx.fillRoundedRect(*x, *y, *width, *height, 6);
padding_widget::render(ctx);
}
virtual void update_colors(bool is_active, bool is_hovered) {
if (is_active) {
bg_color.animate_to({0.3, 0.3, 0.3, 0.7});
} else if (is_hovered) {
bg_color.animate_to({0.35, 0.35, 0.35, 0.7});
} else {
bg_color.animate_to({0.3, 0.3, 0.3, 0.6});
}
}
ui::update_context *ctx;
void update(ui::update_context &ctx) override {
padding_widget::update(ctx);
if (ctx.mouse_clicked_on_hit(this)) {
this->ctx = &ctx;
on_click();
this->ctx = nullptr;
}
update_colors(ctx.mouse_down_on(this), ctx.hovered(this));
}
};
struct start_when_startup_switch : public button_widget {
bool start_when_startup = false;
static bool check_startup() {
HKEY hkey;
if (RegOpenKeyExW(HKEY_CURRENT_USER,
L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0,
KEY_READ, &hkey) != ERROR_SUCCESS) {
return false;
}
wchar_t path[MAX_PATH];
DWORD size = sizeof(path);
bool exists = RegQueryValueExW(hkey, L"breeze-shell", nullptr, nullptr,
(LPBYTE)path, &size) == ERROR_SUCCESS;
RegCloseKey(hkey);
return exists;
}
static void set_startup(bool startup) {
HKEY hkey;
if (RegOpenKeyExW(HKEY_CURRENT_USER,
L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0,
KEY_SET_VALUE, &hkey) != ERROR_SUCCESS) {
return;
}
if (startup) {
wchar_t path[MAX_PATH];
GetModuleFileNameW(NULL, path, MAX_PATH);
std::wstring command =
L"\"" + std::wstring(path) + L"\" inject-consistent";
RegSetValueExW(hkey, L"breeze-shell", 0, REG_SZ, (BYTE *)command.c_str(),
(command.size() + 1) * sizeof(wchar_t));
} else {
RegDeleteValueW(hkey, L"breeze-shell");
}
RegCloseKey(hkey);
}
start_when_startup_switch()
: button_widget(english ? "Start on boot" : "开机自启") {
start_when_startup = check_startup();
}
void on_click() override {
set_startup(!start_when_startup);
start_when_startup = check_startup();
if (!start_when_startup) {
RegDeleteKeyValueW(HKEY_CURRENT_USER,
L"Software\\Classes\\CLSID\\{86ca1aa0-34aa-4e8b-a509-"
L"50c905bae2a2}\\InprocServer32",
nullptr);
}
}
void update_colors(bool is_active, bool is_hovered) override {
if (start_when_startup) {
if (is_hovered) {
bg_color.animate_to({0.3, 0.8, 0.3, 0.7});
} else {
bg_color.animate_to({0.2, 0.7, 0.2, 0.6});
}
} else {
button_widget::update_colors(is_active, is_hovered);
}
}
};
void restart_explorer() {
std::vector pids = GetExplorerPIDs();
for (DWORD pid : pids) {
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
if (hProcess) {
TerminateProcess(hProcess, 0);
CloseHandle(hProcess);
}
}
Sleep(1000);
if (GetExplorerPIDs().empty()) {
ShellExecuteW(NULL, L"open", L"explorer.exe", L"", NULL, SW_SHOW);
}
}
struct restart_explorer_btn : public button_widget {
restart_explorer_btn()
: button_widget(english ? "Restart explorer" : "重启资源管理器") {}
void on_click() override {
std::thread([]() { restart_explorer(); }).detach();
}
};
struct injector_ui_main;
struct switch_lang_btn : public button_widget {
switch_lang_btn() : button_widget(english ? "中文" : "English") {}
void on_click() override {
english = !english;
auto old_i = ctx->rt.root->children.back();
auto new_i = ctx->rt.root->emplace_child();
old_i->dying_time = 200;
}
};
void InjectAllConsistent() {
GetDebugPrivilege();
std::vector injected;
while (true) {
std::vector pids = GetExplorerPIDs();
for (DWORD pid : pids) {
if (!std::ranges::contains(injected, pid) && !IsInjected(pid, dllPath)) {
InjectToPID(pid, dllPath);
injected.push_back(pid);
}
}
Sleep(1000);
MSG msg;
if (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
}
}
struct inject_all_switch : public button_widget {
bool injecting_all = false;
inject_all_switch() : button_widget(english ? "Inject All" : "全局注入") {
check_is_injecting_all();
}
void check_is_injecting_all() {
HANDLE mutex = CreateMutexW(NULL, TRUE, L"breeze-shell-inject-consistent");
if (GetLastError() == ERROR_ALREADY_EXISTS) {
injecting_all = true;
} else {
injecting_all = false;
}
CloseHandle(mutex);
}
void on_click() override {
injecting_all = !injecting_all;
if (injecting_all) {
wchar_t path[MAX_PATH];
GetModuleFileNameW(NULL, path, MAX_PATH);
SHELLEXECUTEINFOW sei = {sizeof(sei)};
sei.fMask = SEE_MASK_NOCLOSEPROCESS;
sei.lpFile = path;
sei.lpParameters = L"inject-consistent";
sei.nShow = SW_HIDE;
ShellExecuteExW(&sei);
} else {
HANDLE event = CreateEventW(NULL, TRUE, FALSE,
L"breeze-shell-inject-consistent-exit");
SetEvent(event);
CloseHandle(event);
}
std::thread([this]() {
Sleep(200);
check_is_injecting_all();
}).detach();
}
void update_colors(bool is_active, bool is_hovered) override {
if (injecting_all) {
if (is_hovered) {
bg_color.animate_to({0.3, 0.8, 0.3, 0.7});
} else {
bg_color.animate_to({0.2, 0.7, 0.2, 0.6});
}
} else {
button_widget::update_colors(is_active, is_hovered);
}
}
};
struct inject_once_switch : public button_widget {
inject_once_switch() : button_widget(english ? "Inject Once" : "注入一次") {}
void on_click() override {
std::thread([]() {
GetDebugPrivilege();
NewExplorerProcessAndInject();
}).detach();
}
};
struct data_dir_btn : public button_widget {
data_dir_btn() : button_widget(english ? "Data Folder" : "数据目录") {}
void on_click() override {
std::wstring path = data_directory().wstring();
ShellExecuteW(NULL, L"open", path.c_str(), NULL, NULL, SW_SHOW);
}
};
struct breeze_icon : public ui::widget {
std::optional image;
breeze_icon() {
width->reset_to(50);
height->reset_to(50);
}
void render(ui::nanovg_context ctx) override {
if (!image) {
image = nvgCreateImageMem(ctx.ctx, 0, g_icon_png, sizeof(g_icon_png));
}
auto paint = nvgImagePattern(ctx.ctx, *x + ctx.offset_x, *y + ctx.offset_y,
*height, *height, 0, *image, 1);
ctx.fillPaint(paint);
ctx.fillRect(*x, *y, *height, *height);
}
};
struct injector_ui_main : public ui::widget_flex {
ui::sp_anim_float opacity = anim_float(100);
injector_ui_main() {
x->reset_to(20);
y->reset_to(5);
opacity->reset_to(0);
opacity->set_easing(ui::easing_type::ease_in_out);
opacity->animate_to(1);
gap = 15;
emplace_child();
emplace_child();
auto switches_box = emplace_child();
switches_box->gap = 7;
auto switches = switches_box->emplace_child();
switches->gap = 7;
switches->horizontal = true;
switches->emplace_child();
switches->emplace_child();
switches->emplace_child();
switches = switches_box->emplace_child();
switches->gap = 7;
switches->horizontal = true;
switches->emplace_child();
switches->emplace_child();
switches->emplace_child();
}
void render(ui::nanovg_context ctx) override {
auto t = ctx.transaction();
ctx.globalAlpha(opacity->var());
ctx.fillColor(nvgRGB(32, 32, 32));
auto gradient_height = 130;
ctx.fillRect(0, gradient_height, 999, 999);
// 20->0 linear gradient
NVGpaint bg = nvgLinearGradient(ctx.ctx, 0, gradient_height, 0, 0,
nvgRGB(32, 32, 32), nvgRGBAf(0, 0, 0, 0));
ctx.beginPath();
ctx.moveTo(0, gradient_height);
ctx.lineTo(999, gradient_height);
ctx.lineTo(999, 0);
ctx.lineTo(0, 0);
ctx.fillPaint(bg);
ctx.fill();
widget_flex::render(ctx);
}
};
void StartInjectUI() {
if (auto r = ui::render_target::init_global(); !r) {
std::cerr << "Failed to initialize global render target." << std::endl;
return;
}
ui::render_target rt;
rt.acrylic = 0.1;
rt.transparent = true;
rt.width = 400;
rt.height = 230;
rt.title = "";
if (auto r = rt.init(); !r) {
std::cerr << "Failed to initialize render target." << std::endl;
return;
}
nvgCreateFont(rt.nvg, "main", "C:\\WINDOWS\\FONTS\\msyh.ttc");
rt.root->emplace_child();
rt.start_loop();
}
void UpdateDllPath() {
auto dllPathNew = data_directory().wstring() + L"\\shell.dll";
auto dllPathPacked = GetModuleDirectory() + L"\\shell.dll";
auto updateDllFile = [&](const std::wstring &packed,
const std::wstring &target) {
std::error_code ec;
fs::remove(target, ec);
if (ec) {
ec.clear();
std::wstring oldPath = fs::path(target).parent_path() / L"shell_old.dll";
if (fs::exists(oldPath)) {
fs::remove(oldPath, ec);
}
if (!ec) {
fs::rename(target, oldPath, ec);
if (!ec) {
fs::copy(packed, target, fs::copy_options::overwrite_existing);
}
}
} else {
fs::copy(packed, target, fs::copy_options::overwrite_existing);
}
};
if (fs::exists(dllPathNew)) {
if (fs::exists(dllPathPacked)) {
auto packedTime = fs::last_write_time(dllPathPacked);
auto newTime = fs::last_write_time(dllPathNew);
if (packedTime > newTime) {
updateDllFile(dllPathPacked, dllPathNew);
}
}
} else {
fs::create_directories(fs::path(dllPathNew).parent_path());
if (fs::exists(dllPathPacked)) {
fs::copy(dllPathPacked, dllPathNew);
}
}
dllPath = dllPathNew;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nShowCmd) {
int argc = 0;
auto argv = CommandLineToArgvW(GetCommandLineW(), &argc);
std::vector args;
for (int x = 0; x < argc; x++) {
args.push_back(argv[x]);
}
UpdateDllPath();
if (args.size() <= 1) {
if (false) {
AttachConsole(ATTACH_PARENT_PROCESS);
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
freopen("CONIN$", "r", stdin);
}
try {
std::println("breeze-shell injector started.");
} catch (std::exception &) {
freopen("NUL", "w", stdout);
freopen("NUL", "w", stderr);
}
StartInjectUI();
} else {
freopen("NUL", "w", stdout);
freopen("NUL", "w", stderr);
if (args[1] == L"new") {
NewExplorerProcessAndInject();
} else if (args[1] == L"inject-consistent") {
HANDLE mutex =
CreateMutexW(NULL, TRUE, L"breeze-shell-inject-consistent");
if (GetLastError() == ERROR_ALREADY_EXISTS) {
std::cerr << "Another instance is running." << std::endl;
return 1;
}
std::thread([]() {
HANDLE event = CreateEventW(NULL, TRUE, FALSE,
L"breeze-shell-inject-consistent-exit");
WaitForSingleObject(event, INFINITE);
CloseHandle(event);
exit(0);
}).detach();
InjectAllConsistent();
} else {
std::cerr << "Invalid argument." << std::endl;
}
}
return 0;
}
```
## /src/shell/build_info.h.in
```in path="/src/shell/build_info.h.in"
#pragma once
#define BREEZE_VERSION "${VERSION}"
#define BREEZE_VERSION_MAJOR ${VERSION_MAJOR}
#define BREEZE_VERSION_MINOR ${VERSION_MINOR}
#define BREEZE_GIT_COMMIT_HASH "${GIT_COMMIT_HASH}"
#define BREEZE_GIT_BRANCH_NAME "${GIT_BRANCH_NAME}"
#define BREEZE_BUILD_DATE_TIME "${BUILD_DATE_TIME}"
```
## /src/shell/config.cc
```cc path="/src/shell/config.cc"
#include "config.h"
#include
#include
#include
#include
#include
#include "logger.h"
#include "rfl.hpp"
#include "rfl/DefaultIfMissing.hpp"
#include "rfl/json.hpp"
#include "utils.h"
#include "windows.h"
namespace mb_shell {
std::unique_ptr config::current;
config::animated_float_conf config::_default_animation{
.duration = 150,
.easing = ui::easing_type::ease_in_out,
.delay_scale = 1,
};
void config::write_config() {
auto config_file = data_directory() / "config.json";
std::ofstream ofs(config_file);
if (!ofs) {
std::cerr << "Failed to write config file." << std::endl;
return;
}
ofs << rfl::json::write(*config::current);
}
void config::read_config() {
auto config_file = data_directory() / "config.json";
#ifdef __llvm__
std::ifstream ifs(config_file);
if (!std::filesystem::exists(config_file)) {
auto config_file = data_directory() / "config.json";
std::ofstream ofs(config_file);
if (!ofs) {
std::cerr << "Failed to write config file." << std::endl;
}
ofs << R"({
"$schema": "https://raw.githubusercontent.com/std-microblock/breeze-shell/refs/heads/master/resources/schema.json"
})";
}
if (!ifs) {
std::cerr
<< "Config file could not be opened. Using default config instead."
<< std::endl;
config::current = std::make_unique();
config::current->debug_console = true;
} else {
std::string json_str;
std::copy(std::istreambuf_iterator(ifs),
std::istreambuf_iterator(), std::back_inserter(json_str));
if (auto json =
rfl::json::read(
json_str)) {
// parse twice for default value
_default_animation = json.value().default_animation;
json = rfl::json::read(
json_str);
config::current = std::make_unique(json.value());
std::cout << "Config reloaded." << std::endl;
} else {
std::cerr << "Failed to read config file: " << json.error()->what()
<< "\nUsing default config instead." << std::endl;
config::current = std::make_unique();
config::current->debug_console = true;
}
}
#else
#pragma message \
"We don't support loading config file on MSVC because of a bug in MSVC."
dbgout("We don't support loading config file when compiled with MSVC "
"because of a bug in MSVC.");
config::current = std::make_unique();
config::current->debug_console = true;
#endif
if (config::current->debug_console) {
ShowWindow(GetConsoleWindow(), SW_SHOW);
} else {
ShowWindow(GetConsoleWindow(), SW_HIDE);
}
}
std::filesystem::path config::data_directory() {
static std::optional path;
static std::mutex mtx;
std::lock_guard lock(mtx);
if (!path) {
path = std::filesystem::path(env("USERPROFILE").value()) / ".breeze-shell";
}
if (!std::filesystem::exists(*path)) {
std::filesystem::create_directories(*path);
}
return path.value();
}
void config::run_config_loader() {
auto config_path = config::data_directory() / "config.json";
dbgout("config file: {}", config_path.string());
config::read_config();
std::thread([config_path]() {
auto last_mod = std::filesystem::last_write_time(config_path);
while (true) {
if (std::filesystem::last_write_time(config_path) != last_mod) {
last_mod = std::filesystem::last_write_time(config_path);
config::read_config();
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}).detach();
}
void config::animated_float_conf::apply_to(ui::sp_anim_float &anim,
float delay) {
anim->set_duration(duration);
anim->set_easing(easing);
anim->set_delay(delay * delay_scale);
}
void config::animated_float_conf::operator()(ui::sp_anim_float &anim,
float delay) {
apply_to(anim, delay);
}
std::filesystem::path config::default_main_font() {
return std::filesystem::path(env("WINDIR").value()) / "Fonts" / "segoeui.ttf";
}
std::filesystem::path config::default_fallback_font() {
return std::filesystem::path(env("WINDIR").value()) / "Fonts" / "msyh.ttc";
}
std::string config::dump_config() { return rfl::json::write(*config::current); }
} // namespace mb_shell
```
## /src/shell/config.h
```h path="/src/shell/config.h"
#pragma once
#include "animator.h"
#include
#include
#include
namespace mb_shell {
struct config {
static std::filesystem::path default_main_font();
static std::filesystem::path default_fallback_font();
struct animated_float_conf {
float duration = _default_animation.duration;
ui::easing_type easing = _default_animation.easing;
float delay_scale = _default_animation.delay_scale;
void apply_to(ui::sp_anim_float &anim, float delay = 0);
void operator()(ui::sp_anim_float &anim, float delay = 0);
} default_animation;
static animated_float_conf _default_animation;
struct context_menu {
struct theme {
bool use_dwm_if_available = true;
float background_opacity = 1;
bool acrylic = true;
float radius = 6;
float font_size = 14;
float item_height = 23;
float item_gap = 3;
float item_radius = 5;
float margin = 5;
float padding = 6;
float text_padding = 8;
float icon_padding = 4;
float right_icon_padding = 20;
float multibutton_line_gap = -6;
float scrollbar_width = 6;
float scrollbar_radius = 3;
std::string acrylic_color_light = "#fefefe00";
std::string acrylic_color_dark = "#28282800";
// unused, only for backward compatibility
float acrylic_opacity = 0.1;
struct animation {
struct main {
animated_float_conf y;
} main;
struct item {
animated_float_conf opacity;
animated_float_conf x, y;
animated_float_conf width;
} item;
struct bg {
animated_float_conf opacity;
animated_float_conf x, y, w, h;
} main_bg, submenu_bg;
} animation;
} theme;
bool vsync = true;
bool ignore_owner_draw = true;
bool reverse_if_open_to_up = true;
bool experimental_ownerdraw_support = false;
// debug purpose only
bool search_large_dwItemData_range = false;
struct position {
int padding_vertical = 20;
int padding_horizontal = 0;
} position;
} context_menu;
bool debug_console = false;
// Restart to apply font/hook changes
std::filesystem::path font_path_main = default_main_font();
std::filesystem::path font_path_fallback = default_fallback_font();
bool res_string_loader_use_hook = false;
bool avoid_resize_ui = false;
std::vector plugin_load_order = {};
std::string $schema;
static std::unique_ptr current;
static void read_config();
static void write_config();
static void run_config_loader();
static std::string dump_config();
static std::filesystem::path data_directory();
};
} // namespace mb_shell
```
## /src/shell/contextmenu/contextmenu.cc
```cc path="/src/shell/contextmenu/contextmenu.cc"
#include "contextmenu.h"
#include "../utils.h"
#include "menu_widget.h"
#include "ui.h"
#include
#include
#include "menu_render.h"
#include "../config.h"
#include "../res_string_loader.h"
#include "../logger.h"
#include "../entry.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
namespace mb_shell {
owner_draw_menu_info getBitmapFromOwnerDraw(MENUITEMINFOW *menuItemInfo,
HWND hwnd) {
owner_draw_menu_info result = {{}, 0, 0};
MEASUREITEMSTRUCT measureItem = {0};
measureItem.CtlType = ODT_MENU;
measureItem.CtlID = 0;
measureItem.itemID = menuItemInfo->wID;
measureItem.itemData = (ULONG_PTR)(menuItemInfo->dwItemData);
SendMessageW(hwnd, WM_MEASUREITEM, 0, reinterpret_cast(&measureItem));
result.width = measureItem.itemWidth;
result.height = measureItem.itemHeight;
if (result.width == 0 || result.height == 0) {
return result;
}
HDC hdc = GetDC(hwnd);
if (!hdc)
return result;
HDC memDC = CreateCompatibleDC(hdc);
if (!memDC) {
ReleaseDC(hwnd, hdc);
return result;
}
RECT rcItem = {0, 0, static_cast(result.width),
static_cast(result.height)};
FillRect(memDC, &rcItem, (HBRUSH)GetStockObject(WHITE_BRUSH));
DRAWITEMSTRUCT drawItem = {0};
drawItem.CtlType = ODT_MENU;
drawItem.CtlID = 0;
drawItem.itemID = menuItemInfo->wID;
drawItem.itemAction = ODA_DRAWENTIRE;
drawItem.itemState = 0;
drawItem.hwndItem = (HWND)menuItemInfo->hSubMenu;
drawItem.hDC = memDC;
drawItem.rcItem = rcItem;
drawItem.itemData = (ULONG_PTR)(menuItemInfo->dwItemData);
SendMessageW(hwnd, WM_DRAWITEM, 0,
reinterpret_cast(&drawItem)); // 发送绘制消息
result.bitmap = CreateCompatibleBitmap(hdc, result.width, result.height);
if (!result.bitmap) {
DeleteDC(memDC);
ReleaseDC(hwnd, hdc);
return result;
}
return result;
}
std::wstring strip_extra_infos(std::wstring_view str) {
// 1. Test&C -> Test
// 2. Test -> Test
// 3. Test\txxx -> Test
// 4. remove all unicode control characters
std::wstring result;
for (int i = 0; i < str.size(); i++) {
if (str[i] == '(' && i + 1 < str.size() && str[i + 1] == '&') {
while (str[i] != ')' && i < str.size()) {
i++;
}
continue;
}
if (str[i] == '&') {
continue;
}
if (str[i] == '\t') {
break;
}
result.push_back(str[i]);
}
return result;
}
menu menu::construct_with_hmenu(HMENU hMenu, HWND hWnd, bool is_top) {
menu m;
SendMessageW(hWnd, WM_INITMENUPOPUP, reinterpret_cast(hMenu),
0xFFFFFFFF);
for (int i = 0; i < GetMenuItemCount(hMenu); i++) {
menu_item item;
wchar_t buffer[256];
MENUITEMINFOW info = {sizeof(MENUITEMINFO)};
info.fMask = MIIM_STRING | MIIM_SUBMENU | MIIM_ID | MIIM_FTYPE |
MIIM_STATE | MIIM_BITMAP | MIIM_CHECKMARKS | MIIM_DATA;
info.dwTypeData = buffer;
info.cch = 256;
if (!GetMenuItemInfoW(hMenu, i, TRUE, &info)) {
std::cout << "Failed to get menu item info: " << GetLastError()
<< std::endl;
continue;
}
if ((info.fType & MFT_OWNERDRAW) &&
config::current->context_menu.experimental_ownerdraw_support) {
auto od = getBitmapFromOwnerDraw(&info, hWnd);
if (od.width && od.height) {
item.owner_draw = od;
}
}
if (info.fType & MFT_RADIOCHECK || info.fState & MFS_CHECKED) {
auto c = is_light_mode() ? 0 : 1;
if ((!item.icon_bitmap && !item.icon_svg)) {
item.icon_svg = std::format(
R"#( )#",
c ? "white" : "black");
}
}
if (info.hSubMenu) {
PostMessageW(hWnd, WM_INITMENUPOPUP,
reinterpret_cast(info.hSubMenu), 0xFFFFFFFF);
auto main_thread_id = GetCurrentThreadId();
item.submenu = [=](std::shared_ptr mw) {
auto task = [&]() {
mw->init_from_data(
menu::construct_with_hmenu(info.hSubMenu, hWnd, false));
};
if (main_thread_id == GetCurrentThreadId())
task();
else
entry::main_window_loop_hook.add_task(task).wait();
};
} else {
item.action = [=]() mutable {
menu_render::current.value()->selected_menu = info.wID;
menu_render::current.value()->rt->hide_as_close();
};
item.wID = info.wID;
}
if (info.fType & MFT_SEPARATOR || info.fType & MFT_MENUBARBREAK ||
info.fType & MFT_MENUBREAK) {
item.type = menu_item::type::spacer;
} else {
item.name = wstring_to_utf8(strip_extra_infos(buffer));
auto id_stripped = res_string_loader::string_to_id(buffer);
if (std::get_if(&id_stripped)) {
item.name_resid =
res_string_loader::string_to_id_string(strip_extra_infos(buffer));
} else {
item.name_resid = res_string_loader::string_to_id_string(buffer);
}
}
if (info.fType & MFT_BITMAP) {
item.icon_bitmap = (size_t)info.hbmpItem;
} else if (info.hbmpChecked || info.hbmpUnchecked) {
if (info.fState & MFS_CHECKED)
item.icon_bitmap = (size_t)info.hbmpChecked;
else
item.icon_bitmap = (size_t)info.hbmpUnchecked;
}
if (info.dwItemData) {
HBITMAP result{};
if (!IS_INTRESOURCE(info.dwItemData)) {
auto offsets =
config::current->context_menu.search_large_dwItemData_range
? ([]() -> std::vector {
std::vector offsets;
for (int i = 0; i <= 0xfff; i++) {
offsets.push_back(i);
}
return offsets;
}())
: std::vector{0x018, 0x220, 0x020, 0x000};
for (int offset : offsets) {
auto pHBitmap = reinterpret_cast(info.dwItemData + offset);
if (!is_memory_readable(pHBitmap)) {
continue;
}
result = *pHBitmap;
if (result && ::GetObjectType(result) == OBJ_BITMAP) {
BITMAP bitmap{};
if (::GetObjectW(result, sizeof(BITMAP), &bitmap) ==
sizeof(BITMAP)) {
auto bmWidthBytes =
((bitmap.bmWidth * bitmap.bmBitsPixel + 31) / 32) * 4;
if (bmWidthBytes == bitmap.bmWidthBytes &&
(bitmap.bmBitsPixel == 32 || bitmap.bmBitsPixel == 24 ||
bitmap.bmBitsPixel == 16 || bitmap.bmBitsPixel == 8) &&
bitmap.bmWidth >= 4 && bitmap.bmWidth <= 64 &&
bitmap.bmHeight >= 4 && bitmap.bmHeight <= 64) {
item.icon_bitmap = (size_t)result;
if (config::current->context_menu
.search_large_dwItemData_range) {
dbgout("Found icon at offset: {}", offset);
}
break;
}
}
}
}
}
}
if (info.fState & MFS_DISABLED) {
item.disabled = true;
}
m.items.push_back(item);
}
m.parent_window = hWnd;
m.is_top_level = is_top;
return m;
}
} // namespace mb_shell
```
## /src/shell/contextmenu/contextmenu.h
```h path="/src/shell/contextmenu/contextmenu.h"
#pragma once
#include "nanovg_wrapper.h"
#include
#include
#include
#include
#include
#define NOMINMAX
#include
namespace mb_shell {
struct menu_item;
struct menu_widget;
struct menu {
std::vector items;
void *parent_window = nullptr;
bool is_top_level = false;
static menu construct_with_hmenu(HMENU hMenu, HWND hWnd, bool is_top = true);
};
struct owner_draw_menu_info {
HBITMAP bitmap;
int width, height;
};
struct menu_item {
enum class type {
button,
spacer,
} type = type::button;
std::optional owner_draw{};
std::optional name;
std::optional> action;
std::optional)>> submenu;
std::optional icon_bitmap;
std::optional icon_svg;
bool icon_updated = false;
bool disabled = false;
// the two below are only for information; set them changes nothing
std::optional wID;
std::optional name_resid;
};
} // namespace mb_shell
```
## /src/shell/contextmenu/menu_render.cc
```cc path="/src/shell/contextmenu/menu_render.cc"
#include "menu_render.h"
#include "Windows.h"
#include "menu_widget.h"
#include "../script/binding_types.h"
#include "ui.h"
#include
#include
#include "../logger.h"
namespace mb_shell {
std::optional menu_render::current{};
menu_render menu_render::create(int x, int y, menu menu) {
if (auto res = ui::render_target::init_global(); !res) {
MessageBoxW(NULL, L"Failed to initialize global render target", L"Error",
MB_ICONERROR);
return {nullptr, std::nullopt};
}
constexpr int l_pad = 100, t_pad = -1;
static auto rt = []() {
auto rt = std::make_shared();
rt->transparent = true;
rt->no_focus = true;
rt->capture_all_input = true;
rt->decorated = false;
rt->topmost = true;
rt->vsync = config::current->context_menu.vsync;
if (config::current->avoid_resize_ui) {
rt->width = 3840;
rt->height = 2159;
}
if (auto res = rt->init(); !res) {
MessageBoxW(NULL, L"Failed to initialize render target", L"Error",
MB_ICONERROR);
}
nvgCreateFont(rt->nvg, "main",
config::current->font_path_main.string().c_str());
nvgCreateFont(rt->nvg, "fallback",
config::current->font_path_fallback.string().c_str());
nvgAddFallbackFont(rt->nvg, "main", "fallback");
return rt;
}();
auto render = menu_render(rt, std::nullopt);
auto current_js_context = std::make_shared(
js::js_menu_context::$from_window(menu.parent_window));
rt->parent = menu.parent_window;
// get the monitor in which the menu is being shown
auto monitor = MonitorFromPoint({x, y}, MONITOR_DEFAULTTONEAREST);
MONITORINFOEX monitor_info;
monitor_info.cbSize = sizeof(MONITORINFOEX);
GetMonitorInfo(monitor, &monitor_info);
// set the position of the window to fullscreen in this monitor + padding
dbgout("Monitor: {} {} {} {}", monitor_info.rcMonitor.left,
monitor_info.rcMonitor.top, monitor_info.rcMonitor.right,
monitor_info.rcMonitor.bottom);
rt->set_position(monitor_info.rcMonitor.left, monitor_info.rcMonitor.top);
if (!config::current->avoid_resize_ui)
rt->resize(
monitor_info.rcMonitor.right - monitor_info.rcMonitor.left + l_pad,
monitor_info.rcMonitor.bottom - monitor_info.rcMonitor.top + t_pad);
glfwMakeContextCurrent(rt->window);
glfwSwapInterval(config::current->context_menu.vsync ? 1 : 0);
rt->show();
auto menu_wid = std::make_shared(
menu,
// convert the x and y to the window coordinates
x - monitor_info.rcMonitor.left, y - monitor_info.rcMonitor.top);
rt->root->children.push_back(menu_wid);
js::menu_info_basic_js menu_info{
.menu = std::make_shared(menu_wid->menu_wid),
.context = current_js_context};
dbgout("[perf] JS plugins start");
auto before_js = rt->clock.now();
for (auto &listener : menu_callbacks_js) {
listener->operator()(menu_info);
}
dbgout("[perf] JS plugins costed {}ms",
std::chrono::duration_cast(
rt->clock.now() - before_js)
.count());
rt->on_focus_changed = [](bool focused) {
if (!focused) {
rt->hide_as_close();
}
};
dbgout("Current menu: {}", menu_render::current.has_value());
return render;
}
menu_render::menu_render(std::shared_ptr rt,
std::optional selected_menu)
: rt(std::move(rt)), selected_menu(selected_menu) {
current = this;
}
menu_render::~menu_render() {
if (this->rt) {
current = nullptr;
}
}
menu_render::menu_render(menu_render &&t) {
current = this;
rt = std::move(t.rt);
selected_menu = std::move(t.selected_menu);
}
menu_render &menu_render::operator=(menu_render &&t) {
current = this;
rt = std::move(t.rt);
selected_menu = std::move(t.selected_menu);
return *this;
}
}; // namespace mb_shell
```
## /src/shell/contextmenu/menu_render.h
```h path="/src/shell/contextmenu/menu_render.h"
#pragma once
#include "../utils.h"
#include "contextmenu.h"
#include "ui.h"
#include
namespace mb_shell {
struct menu_render {
std::shared_ptr rt;
std::optional selected_menu;
bool light_color = is_light_mode();
static std::optional current;
menu_render() = delete;
menu_render(std::shared_ptr rt,
std::optional selected_menu);
~menu_render();
const menu_render &operator=(const menu_render &) = delete;
menu_render(menu_render &&t);
menu_render &operator=(menu_render &&t);
static menu_render create(int x, int y, menu menu);
};
} // namespace mb_shell
```
## /src/shell/contextmenu/menu_widget.cc
```cc path="/src/shell/contextmenu/menu_widget.cc"
#include "menu_widget.h"
#include "../config.h"
#include "../utils.h"
#include "animator.h"
#include "contextmenu.h"
#include "hbitmap_utils.h"
#include "menu_render.h"
#include "nanovg.h"
#include "ui.h"
#include "widget.h"
#include
#include
#include
#include
#include
#include "../logger.h"
/*
| padding | icon_padding | icon | icon_padding | text_padding | text |
text_padding | right_icon_padding | right_icon | right_icon_padding |
*/
void mb_shell::menu_item_normal_widget::render(ui::nanovg_context ctx) {
super::render(ctx);
auto icon_width = config::current->context_menu.theme.font_size + 2;
auto has_icon = has_icon_padding || icon_img;
auto c = menu_render::current.value()->light_color ? 0 : 1;
if (item.type == menu_item::type::spacer) {
ctx.fillColor(nvgRGBAf(c, c, c, 0.1 * *opacity / 255.f));
ctx.fillRect(x->dest(), *y, *width, *height);
return;
}
ctx.fillColor(nvgRGBAf(c, c, c, *bg_opacity / 255.f));
float roundcorner = std::min(roundcorner = height->dest() / 2,
config::current->context_menu.theme.item_radius);
ctx.fillRoundedRect(*x + margin, *y, *width - margin * 2, *height,
roundcorner);
if (item.icon_bitmap.has_value() || item.icon_svg.has_value()) {
if (!icon_img || item.icon_updated)
reload_icon_img(ctx);
item.icon_updated = false;
auto paintY = floor(*y + (*height - icon_width) / 2);
auto imageX = *x + padding + margin + icon_padding;
auto paint = ctx.imagePattern(imageX, paintY, icon_width, icon_width, 0,
icon_img->id, *opacity / 255.f);
ctx.beginPath();
ctx.rect(imageX, paintY, icon_width, icon_width);
ctx.fillPaint(paint);
ctx.fill();
}
ctx.fillColor(nvgRGBAf(c, c, c, *opacity / 255.f));
ctx.fontFace("main");
auto font_size = config::current->context_menu.theme.font_size;
ctx.fontSize(font_size);
ctx.textAlign(NVG_ALIGN_LEFT | NVG_ALIGN_MIDDLE);
if (item.name)
ctx.text(round(*x + padding +
(has_icon ? (icon_width + icon_padding * 2) : 0) +
text_padding + margin),
round(*y + *height / 2), item.name->c_str(), nullptr);
if (item.submenu) {
if (!icon_unfold_img) {
auto icon_unfold = std::format(
// point to right
R"#( )#",
c ? "white" : "black");
auto icon_unfold_img_svg = nsvgParse(icon_unfold.data(), "px", 96);
this->icon_unfold_img =
ctx.imageFromSVG(icon_unfold_img_svg, ctx.rt->dpi_scale);
}
auto paintY = floor(*y + (*height - icon_width) / 2);
auto paintX =
*x + padding + width->dest() - right_icon_padding - icon_width;
auto paint2 = ctx.imagePattern(paintX, paintY, icon_width, icon_width, 0,
icon_unfold_img->id, *opacity / 255.f);
ctx.beginPath();
ctx.rect(paintX, paintY, icon_width, icon_width);
ctx.fillPaint(paint2);
ctx.fill();
}
}
void mb_shell::menu_item_normal_widget::update(ui::update_context &ctx) {
super::update(ctx);
if (parent->dying_time) {
bg_opacity->animate_to(0);
opacity->animate_to(0);
return;
}
if (item.type == menu_item::type::spacer) {
height->reset_to(1);
} else {
height->reset_to(config::current->context_menu.theme.item_height);
}
if (item.disabled) {
opacity->animate_to(128);
bg_opacity->animate_to(0);
if (submenu_wid) {
submenu_wid->close();
submenu_wid = nullptr;
}
return;
} else {
opacity->animate_to(255);
}
if (ctx.mouse_down_on(this)) {
bg_opacity->animate_to(40);
} else if (ctx.hovered(this)) {
bg_opacity->animate_to(20);
} else {
bg_opacity->animate_to(0);
}
if (ctx.mouse_clicked_on(this)) {
if (item.action) {
try {
item.action.value()();
} catch (std::exception &e) {
std::cerr << "Error in action: " << e.what() << std::endl;
}
}
}
if (item.submenu) {
if (ctx.hovered(this)) {
show_submenu_timer = std::min(show_submenu_timer + ctx.delta_t, 300.f);
} else if (ctx.within(parent).hovered(parent)) {
show_submenu_timer = std::max(show_submenu_timer - ctx.delta_t, 0.f);
}
if (show_submenu_timer >= 150.f) {
show_submenu(ctx);
} else {
hide_submenu();
}
} else {
hide_submenu();
}
if (submenu_wid && submenu_wid->dying_time.has_value) {
submenu_wid = nullptr;
}
}
float mb_shell::menu_item_normal_widget::measure_width(
ui::update_context &ctx) {
if (item.type == menu_item::type::spacer) {
return 1;
}
auto font_size = config::current->context_menu.theme.font_size;
float width = 0;
// left icon
if (has_icon_padding || icon_img)
width += icon_padding * 2 + font_size + 2;
// text
ctx.vg.fontSize(font_size);
if (item.name)
width += ctx.vg.measureText(item.name->c_str()).first + text_padding * 2;
// right icon
if (item.submenu) {
width += font_size + 2 + right_icon_padding * 2;
}
return width + margin * 2 + padding * 2;
}
std::shared_ptr
mb_shell::menu_widget::create_bg(bool is_main) {
std::shared_ptr bg;
if (is_acrylic_available() && config::current->context_menu.theme.acrylic) {
auto light_color = menu_render::current.value()->light_color;
auto acrylic_color =
light_color
? parse_color(
config::current->context_menu.theme.acrylic_color_light)
: parse_color(
config::current->context_menu.theme.acrylic_color_dark);
auto acrylic = std::make_shared(
config::current->context_menu.theme.use_dwm_if_available
? is_win11_or_later()
: false);
acrylic->acrylic_bg_color = acrylic_color;
acrylic->update_color();
bg = acrylic;
if (menu_render::current.value()->light_color)
bg->bg_color = nvgRGBAf(1, 1, 1, 0);
else
bg->bg_color = nvgRGBAf(0, 0, 0, 0);
} else {
bg = std::make_shared();
auto c = menu_render::current.value()->light_color ? 1 : 25 / 255.f;
bg->bg_color = nvgRGBAf(c, c, c, 1);
}
bg->radius->reset_to(config::current->context_menu.theme.radius);
bg->opacity->reset_to(0);
if (is_main)
config::current->context_menu.theme.animation.main_bg.opacity(bg->opacity,
0);
else {
config::current->context_menu.theme.animation.submenu_bg.opacity(
bg->opacity, 0);
config::current->context_menu.theme.animation.submenu_bg.x(bg->x, 0);
config::current->context_menu.theme.animation.submenu_bg.y(bg->y, 0);
config::current->context_menu.theme.animation.submenu_bg.w(bg->width, 0);
config::current->context_menu.theme.animation.submenu_bg.h(bg->height, 0);
}
bg->opacity->animate_to(
255 * config::current->context_menu.theme.background_opacity);
return bg;
}
mb_shell::menu_widget::menu_widget() : super() {
gap = config::current->context_menu.theme.item_gap;
width->set_easing(ui::easing_type::mutation);
height->set_easing(ui::easing_type::mutation);
config::current->context_menu.theme.animation.main.y(y);
}
void mb_shell::menu_widget::update(ui::update_context &ctx) {
if (dying_time) {
if (dying_time.changed()) {
y->animate_to(*y - 10);
}
if (bg_submenu)
bg_submenu->opacity->animate_to(0);
if (bg)
bg->opacity->animate_to(0);
}
if (bg) {
bg->x->reset_to(x->dest());
bg->y->reset_to(y->dest() - bg_padding_vertical);
bg->width->reset_to(width->dest());
bg->height->reset_to(height->dest() + bg_padding_vertical * 2);
bg->update(ctx);
}
if (current_submenu) {
if (!bg_submenu) {
bg_submenu = create_bg(false);
bg_submenu->x->reset_to(current_submenu->x->dest());
bg_submenu->y->reset_to(current_submenu->y->dest() - bg_padding_vertical);
bg_submenu->width->reset_to(current_submenu->width->dest());
bg_submenu->height->reset_to(current_submenu->height->dest() +
bg_padding_vertical * 2);
}
bg_submenu->dying_time = std::nullopt;
bg_submenu->opacity->animate_to(
config::current->context_menu.theme.background_opacity * 255.f);
bg_submenu->x->animate_to(current_submenu->x->dest());
bg_submenu->y->animate_to(current_submenu->y->dest() - bg_padding_vertical);
bg_submenu->width->animate_to(current_submenu->width->dest());
bg_submenu->height->animate_to(current_submenu->height->dest() +
bg_padding_vertical * 2);
} else {
if (bg_submenu) {
if (!bg_submenu->dying_time)
bg_submenu->dying_time = 200;
bg_submenu->opacity->animate_to(0);
if (bg_submenu->dying_time.time <= 0) {
bg_submenu = nullptr;
}
}
}
reverse = (direction == popup_direction::top_left ||
direction == popup_direction::top_right) &&
config::current->context_menu.reverse_if_open_to_up;
auto forkctx_1 = ctx.with_offset(*x, *y);
update_children(forkctx_1, rendering_submenus);
if (bg_submenu) {
bg_submenu->update(forkctx_1);
}
if (ctx.hovered(this)) {
scroll_top->animate_to(std::clamp(scroll_top->dest() + ctx.scroll_y * 100,
height->dest() - actual_height, 0.f));
}
widget::update(ctx);
ctx.hovered_hit(this);
auto forkctx = ctx.with_offset(*x, *y + *scroll_top);
update_children(forkctx, item_widgets);
reposition_children_flex(forkctx, item_widgets);
actual_height = height->dest();
height->reset_to(std::min(max_height, height->dest()));
if (bg) {
bg->update(ctx);
}
}
bool mb_shell::menu_widget::check_hit(const ui::update_context &ctx) {
auto hit = ui::widget::check_hit(ctx) || (bg && bg->check_hit(ctx));
return hit;
}
void mb_shell::menu_widget::render(ui::nanovg_context ctx) {
if (bg) {
ctx.transaction([&]() {
ctx.globalCompositeOperation(NVG_DESTINATION_IN);
auto cl = nvgRGBAf(0, 0, 0, 1 - *bg->opacity / 255.f);
ctx.fillColor(cl);
ctx.fillRoundedRect(*bg->x, *bg->y, *bg->width, *bg->height, *bg->radius);
});
bg->render(ctx);
}
ctx.transaction([&] {
super::render(ctx);
ctx.scissor(*x, *y, *width, *height);
render_children(ctx.with_offset(*x, *y + *scroll_top), item_widgets);
});
auto ctx2 = ctx.with_offset(*x, *y);
if (bg_submenu) {
ctx2.transaction([&]() {
ctx2.globalCompositeOperation(NVG_DESTINATION_IN);
ctx2.resetScissor();
auto cl = nvgRGBAf(0, 0, 0, 1 - *bg_submenu->opacity / 255.f);
ctx2.fillColor(cl);
ctx2.fillRoundedRect(*bg_submenu->x, *bg_submenu->y, *bg_submenu->width,
*bg_submenu->height, *bg_submenu->radius);
});
bg_submenu->render(ctx2);
}
render_children(ctx2, rendering_submenus);
// scrollbar
if (height->dest() < actual_height) {
auto scrollbar_width = config::current->context_menu.theme.scrollbar_width;
auto scrollbar_height = height->dest() * height->dest() / actual_height;
auto scrollbar_x = width->dest() - scrollbar_width - 2 + *x;
auto scrollbar_y = *y - *scroll_top / (actual_height - height->dest()) *
(height->dest() - scrollbar_height);
float c = menu_render::current.value()->light_color ? 0 : 1;
ctx.fillColor(nvgRGBAf(c, c, c, 0.1));
ctx.fillRoundedRect(scrollbar_x, scrollbar_y, scrollbar_width,
scrollbar_height,
config::current->context_menu.theme.scrollbar_radius);
}
}
void mb_shell::menu_item_normal_widget::reset_appear_animation(float delay) {
this->opacity->after_animate = [this](float dest) {
this->opacity->set_delay(0);
};
opacity->reset_to(0);
this->x->reset_to(-20);
config::current->context_menu.theme.animation.item.opacity(opacity, delay);
config::current->context_menu.theme.animation.item.x(x, delay);
config::current->context_menu.theme.animation.item.width(width);
opacity->animate_to(255);
this->y->progress = 1;
this->y->easing = ui::easing_type::mutation;
this->x->animate_to(0);
}
BOOL IsCursorVisible() {
CURSORINFO ci = {sizeof(CURSORINFO)};
if (GetCursorInfo(&ci)) {
return (ci.flags & CURSOR_SHOWING) != 0;
}
return FALSE;
}
mb_shell::mouse_menu_widget_main::mouse_menu_widget_main(menu menu_data,
float x, float y)
: widget(), anchor_x(x), anchor_y(y) {
menu_wid = std::make_shared();
menu_wid->init_from_data(menu_data);
}
void mb_shell::mouse_menu_widget_main::update(ui::update_context &ctx) {
ui::widget::update(ctx);
// process events of parents
PeekMessage(nullptr, nullptr, 0, 0, PM_REMOVE);
if (!direction_calibrated) {
calibrate_direction(ctx);
direction_calibrated = true;
calibrate_position(ctx, false);
position_calibrated = true;
}
if (!position_calibrated) {
calibrate_position(ctx);
position_calibrated = true;
}
menu_wid->update(ctx);
auto using_touchscreen = !IsCursorVisible();
if (ctx.hovered_widgets->empty()) {
glfwSetWindowAttrib(ctx.rt.window, GLFW_MOUSE_PASSTHROUGH,
using_touchscreen ? GLFW_FALSE : GLFW_TRUE);
if ((ctx.mouse_clicked || ctx.right_mouse_clicked) ||
GetAsyncKeyState(VK_LBUTTON) & 0x8000 ||
GetAsyncKeyState(VK_RBUTTON) & 0x8000) {
ctx.rt.hide_as_close();
}
} else {
glfwSetWindowAttrib(ctx.rt.window, GLFW_MOUSE_PASSTHROUGH, GLFW_FALSE);
}
// esc/alt to close
if ((GetAsyncKeyState(VK_ESCAPE) & 0x8000) ||
(GetAsyncKeyState(VK_MENU) & 0x8000) ||
(GetAsyncKeyState(VK_LMENU) & 0x8000)) {
ctx.rt.hide_as_close();
}
}
void mb_shell::mouse_menu_widget_main::render(ui::nanovg_context ctx) {
ui::widget::render(ctx);
menu_wid->render(ctx);
}
void mb_shell::menu_widget::reset_animation(bool reverse) {
if (animate_appear_started)
return;
animate_appear_started = true;
auto children = item_widgets | std::ranges::views::transform([](auto &w) {
return std::dynamic_pointer_cast(w);
});
// the show duration for the menu should be within 200ms
float delay = std::min(200.f / children.size(), 30.f);
if (config::current->context_menu.reverse_if_open_to_up && reverse)
reverse = !reverse;
for (size_t i = 0; i < children.size(); i++) {
auto child = children[i];
child->reset_appear_animation(delay * (reverse ? children.size() - i : i));
}
}
std::pair mb_shell::mouse_menu_widget_main::calculate_position(
menu_widget *menu_wid, ui::update_context &ctx, float anchor_x,
float anchor_y, popup_direction direction) {
menu_wid->update(ctx);
auto menu_width = menu_wid->measure_width(ctx);
auto menu_height = menu_wid->measure_height(ctx);
float x, y;
// avoid the menu to be out of the screen
constexpr auto mouse_padding = 1.f;
if (direction == popup_direction::top_left) {
x = anchor_x - menu_width * ctx.rt.dpi_scale - mouse_padding;
y = anchor_y - menu_height * ctx.rt.dpi_scale;
} else if (direction == popup_direction::top_right) {
x = anchor_x + mouse_padding;
y = anchor_y - menu_height * ctx.rt.dpi_scale;
} else if (direction == popup_direction::bottom_left) {
x = anchor_x - menu_width * ctx.rt.dpi_scale - mouse_padding;
y = anchor_y;
} else {
x = anchor_x + mouse_padding;
y = anchor_y;
}
auto padding_vertical =
config::current->context_menu.position.padding_horizontal *
ctx.rt.dpi_scale,
padding_horizontal =
config::current->context_menu.position.padding_vertical *
ctx.rt.dpi_scale;
if (x < padding_vertical) {
x = padding_vertical;
} else if (x + menu_width * ctx.rt.dpi_scale >
ctx.screen.width - padding_vertical) {
x = ctx.screen.width - menu_width * ctx.rt.dpi_scale - padding_vertical;
}
auto top_overflow = y < padding_horizontal;
auto bottom_overflow = y + menu_height * ctx.rt.dpi_scale >
ctx.screen.height - padding_horizontal;
if (menu_height * ctx.rt.dpi_scale >
ctx.screen.height - padding_horizontal * 2) {
y = padding_horizontal;
menu_wid->max_height =
ctx.screen.height / ctx.rt.dpi_scale - padding_horizontal * 2;
} else if (top_overflow) {
y = padding_horizontal;
} else if (bottom_overflow) {
y = ctx.screen.height - menu_height * ctx.rt.dpi_scale - padding_horizontal;
}
return {x, y};
}
mb_shell::popup_direction mb_shell::mouse_menu_widget_main::calculate_direction(
menu_widget *menu_wid, ui::update_context &ctx, float anchor_x,
float anchor_y, popup_direction prefer_direction) {
auto menu_width = menu_wid->measure_width(ctx);
auto menu_height = menu_wid->measure_height(ctx);
auto padding_vertical =
config::current->context_menu.position.padding_horizontal,
padding_horizontal =
config::current->context_menu.position.padding_vertical;
bool bottom_overflow = (anchor_y + menu_height * ctx.rt.dpi_scale >
ctx.screen.height - padding_vertical);
bool top_overflow =
(anchor_y - menu_height * ctx.rt.dpi_scale < padding_vertical);
bool right_overflow = (anchor_x + menu_width * ctx.rt.dpi_scale >
ctx.screen.width - padding_horizontal);
bool left_overflow =
(anchor_x - menu_width * ctx.rt.dpi_scale < padding_horizontal);
bool top_revert = false;
bool left_revert = false;
if (prefer_direction == popup_direction::bottom_right) {
if (bottom_overflow && !top_overflow)
top_revert = true;
if (right_overflow && !left_overflow)
left_revert = true;
} else if (prefer_direction == popup_direction::bottom_left) {
if (bottom_overflow && !top_overflow)
top_revert = true;
if (left_overflow && !right_overflow)
left_revert = true;
} else if (prefer_direction == popup_direction::top_right) {
if (top_overflow && !bottom_overflow)
top_revert = true;
if (right_overflow && !left_overflow)
left_revert = true;
} else if (prefer_direction == popup_direction::top_left) {
if (top_overflow && !bottom_overflow)
top_revert = true;
if (left_overflow && !right_overflow)
left_revert = true;
}
if (top_revert && left_revert) {
return popup_direction::top_left;
} else if (top_revert && !left_revert) {
return popup_direction::top_right;
} else if (!top_revert && left_revert) {
return popup_direction::bottom_left;
} else {
return popup_direction::bottom_right;
}
}
void mb_shell::mouse_menu_widget_main::calibrate_position(
ui::update_context &ctx, bool animated) {
menu_wid->update(ctx);
auto [x, y] =
calculate_position(menu_wid.get(), ctx, anchor_x, anchor_y, direction);
dbgout("Calibrated position: {} {} in screen {} {}", x, y, ctx.screen.width,
ctx.screen.height);
if (animated) {
this->menu_wid->x->animate_to(x / ctx.rt.dpi_scale);
this->menu_wid->y->animate_to(y / ctx.rt.dpi_scale);
} else {
this->menu_wid->x->reset_to(x / ctx.rt.dpi_scale);
this->menu_wid->y->reset_to(y / ctx.rt.dpi_scale);
}
}
void mb_shell::mouse_menu_widget_main::calibrate_direction(
ui::update_context &ctx) {
menu_wid->update(ctx);
direction = calculate_direction(menu_wid.get(), ctx, anchor_x, anchor_y);
menu_wid->direction = direction;
menu_wid->reset_animation(direction == popup_direction::top_left ||
direction == popup_direction::top_right);
dbgout("Calibrated direction: {}",
direction == popup_direction::top_left ? "top_left"
: direction == popup_direction::top_right ? "top_right"
: direction == popup_direction::bottom_left ? "bottom_left"
: direction == popup_direction::bottom_right ? "bottom_right"
: "unknown");
}
bool mb_shell::menu_item_normal_widget::check_hit(
const ui::update_context &ctx) {
return (ui::widget::check_hit(ctx)) ||
(submenu_wid && submenu_wid->check_hit(ctx));
}
mb_shell::menu_item_normal_widget::menu_item_normal_widget(menu_item item)
: super() {
opacity->reset_to(0);
this->item = item;
}
void mb_shell::menu_widget::init_from_data(menu menu_data) {
if (menu_data.is_top_level && !bg) {
bg = create_bg(true);
}
auto init_items = menu_data.items;
for (size_t i = 0; i < init_items.size(); i++) {
auto &item = init_items[i];
if (item.owner_draw) {
auto mi = std::make_shared(item);
item_widgets.push_back(mi);
} else {
auto mi = std::make_shared(item);
item_widgets.push_back(mi);
}
}
dbgout("Menu widget init from data: {}", menu_data.items.size());
update_icon_width();
this->menu_data = menu_data;
}
void mb_shell::menu_widget::update_icon_width() {
bool has_icon = std::ranges::any_of(item_widgets, [](auto &item) {
if (!item->template downcast())
return false;
auto i = item->template downcast()->item;
return i.icon_bitmap.has_value() || i.icon_svg.has_value();
});
for (auto &item : item_widgets) {
auto mi = item->template downcast();
if (!mi)
continue;
if (!has_icon) {
mi->has_icon_padding = 0;
} else {
mi->has_icon_padding = 1;
}
}
};
void mb_shell::menu_item_normal_widget::reload_icon_img(
ui::nanovg_context ctx) {
if (item.icon_bitmap)
icon_img = ui::LoadBitmapImage(ctx, (HBITMAP)item.icon_bitmap.value());
else if (item.icon_svg) {
std::string copy = item.icon_svg.value();
auto svg = nsvgParse(copy.data(), "px", 96);
auto icon_width = config::current->context_menu.theme.font_size + 2;
icon_img = ctx.imageFromSVG(svg, ctx.rt->dpi_scale);
} else {
icon_img = std::nullopt;
}
if (auto pa = parent->downcast()) {
pa->update_icon_width();
}
}
void mb_shell::menu_widget::close() {
if (menu_data.is_top_level) {
auto current = menu_render::current;
if (current) {
(*current)->rt->hide_as_close();
}
} else {
dying_time = 200;
if (parent_menu->current_submenu.get() == this) {
parent_menu->current_submenu = nullptr;
}
for (auto &item : item_widgets) {
auto mi = item->downcast();
if (mi) {
mi->hide_submenu();
}
}
}
}
mb_shell::menu_item_widget::menu_item_widget() {}
void mb_shell::menu_item_widget::reset_appear_animation(float delay) {
for (auto &child : get_children())
child->reset_appear_animation(delay);
}
void mb_shell::menu_item_parent_widget::update(ui::update_context &ctx) {
super::update(ctx);
float x = 0;
float gap = config::current->context_menu.theme.multibutton_line_gap;
float max_height = 0;
for (auto &item : children) {
item->x->reset_to(x);
item->y->reset_to(0);
auto item_width = item->measure_width(ctx);
item->width->reset_to(item_width);
x += item_width + gap;
max_height = std::max(max_height, item->measure_height(ctx));
}
width->reset_to(x - gap);
height->reset_to(max_height);
}
void mb_shell::menu_item_parent_widget::reset_appear_animation(float delay) {
y->set_easing(ui::easing_type::mutation);
x->reset_to(-20);
x->animate_to(0);
opacity->reset_to(0);
opacity->animate_to(255);
}
void mb_shell::menu_item_normal_widget::hide_submenu() {
if (submenu_wid != nullptr) {
submenu_wid->close();
submenu_wid = nullptr;
}
}
void mb_shell::menu_item_normal_widget::show_submenu(ui::update_context &ctx) {
if (submenu_wid != nullptr)
return;
submenu_wid = std::make_shared();
item.submenu.value()(submenu_wid);
// We calculate the position of the submenu in
// the screen space, then convert it to the
// window space.
auto anchor_x = width->dest() + *x + ctx.offset_x;
auto anchor_y = **y + ctx.offset_y;
anchor_x *= ctx.rt.dpi_scale;
anchor_y *= ctx.rt.dpi_scale;
ctx.mouse_clicked = false;
ctx.mouse_down = false;
submenu_wid->update(ctx);
auto direction = mouse_menu_widget_main::calculate_direction(
submenu_wid.get(), ctx, anchor_x, anchor_y,
popup_direction::bottom_right);
if (direction == popup_direction::top_left ||
direction == popup_direction::bottom_left) {
anchor_x -= *width * ctx.rt.dpi_scale;
}
if (direction == popup_direction::top_left ||
direction == popup_direction::top_right) {
anchor_y += *height * ctx.rt.dpi_scale;
}
auto [x, y] = mouse_menu_widget_main::calculate_position(
submenu_wid.get(), ctx, anchor_x, anchor_y, direction);
if (auto parent = search_parent())
y += *parent->scroll_top * ctx.rt.dpi_scale;
x -= ctx.offset_x * ctx.rt.dpi_scale;
y -= ctx.offset_y * ctx.rt.dpi_scale;
submenu_wid->direction = direction;
submenu_wid->x->reset_to(x / ctx.rt.dpi_scale);
submenu_wid->y->reset_to(y / ctx.rt.dpi_scale);
submenu_wid->reset_animation(direction == popup_direction::top_left ||
direction == popup_direction::top_right);
auto parent_menu = parent->downcast();
if (!parent_menu)
parent_menu = parent->parent->downcast();
parent_menu->current_submenu = submenu_wid;
parent_menu->rendering_submenus.push_back(submenu_wid);
submenu_wid->parent_menu = parent_menu.get();
}
void mb_shell::menu_item_ownerdraw_widget::update(ui::update_context &ctx) {
width->reset_to(owner_draw.width);
height->reset_to(owner_draw.height);
}
void mb_shell::menu_item_ownerdraw_widget::render(ui::nanovg_context ctx) {
if (!img)
img = ui::LoadBitmapImage(ctx, owner_draw.bitmap);
auto paint = ctx.imagePattern(*x, y->dest(), owner_draw.width,
owner_draw.height, 0, img->id, 1);
ctx.beginPath();
ctx.rect(*x, y->dest(), owner_draw.width, owner_draw.height);
ctx.fillPaint(paint);
ctx.fill();
}
void mb_shell::menu_item_ownerdraw_widget::reset_appear_animation(float delay) {
}
mb_shell::menu_item_ownerdraw_widget::menu_item_ownerdraw_widget(
menu_item item) {
this->item = item;
if (item.owner_draw) {
owner_draw = item.owner_draw.value();
width->reset_to(owner_draw.width);
height->reset_to(owner_draw.height);
}
}
```
## /src/shell/contextmenu/menu_widget.h
```h path="/src/shell/contextmenu/menu_widget.h"
#pragma once
#include "../config.h"
#include "animator.h"
#include "contextmenu.h"
#include "extra_widgets.h"
#include "nanovg_wrapper.h"
#include "ui.h"
#include "widget.h"
#include
#include
#include
namespace mb_shell {
struct menu_widget;
struct menu_item_widget : public ui::widget {
using super = ui::widget;
menu_item item;
ui::sp_anim_float opacity = anim_float(0, 200);
menu_item_widget();
virtual void reset_appear_animation(float delay);
};
struct menu_item_ownerdraw_widget : public menu_item_widget {
using super = menu_item_widget;
owner_draw_menu_info owner_draw;
std::optional img{};
menu_item_ownerdraw_widget(menu_item item);
void update(ui::update_context &ctx) override;
void render(ui::nanovg_context ctx) override;
void reset_appear_animation(float delay) override;
};
struct menu_item_parent_widget : public menu_item_widget {
using super = menu_item_widget;
void update(ui::update_context &ctx) override;
void reset_appear_animation(float delay) override;
};
struct menu_item_normal_widget : public menu_item_widget {
using super = menu_item_widget;
ui::sp_anim_float opacity = anim_float(0, 200);
float text_padding = config::current->context_menu.theme.text_padding;
float margin = config::current->context_menu.theme.margin;
bool has_icon_padding = false;
float padding = config::current->context_menu.theme.padding;
float icon_padding = config::current->context_menu.theme.icon_padding;
float right_icon_padding =
config::current->context_menu.theme.right_icon_padding;
menu_item_normal_widget(menu_item item);
void reset_appear_animation(float delay) override;
std::optional icon_img{};
std::optional icon_unfold_img{};
std::shared_ptr submenu_wid = nullptr;
float show_submenu_timer = 0.f;
ui::sp_anim_float bg_opacity = anim_float(0, 200);
void render(ui::nanovg_context ctx) override;
void update(ui::update_context &ctx) override;
float measure_width(ui::update_context &ctx) override;
bool check_hit(const ui::update_context &ctx) override;
void hide_submenu();
void show_submenu(ui::update_context &ctx);
void reload_icon_img(ui::nanovg_context ctx);
};
enum class popup_direction {
// 第一象限 ~ 第四象限
top_left,
top_right,
bottom_left,
bottom_right,
};
struct menu_widget : public ui::widget_flex {
using super = ui::widget_flex;
float bg_padding_vertical = 6;
float max_height = 99999;
float actual_height = 0;
ui::sp_anim_float scroll_top =
anim_float(0, 200, ui::easing_type::ease_in_out);
std::shared_ptr bg;
std::shared_ptr bg_submenu;
std::shared_ptr current_submenu;
std::vector> rendering_submenus;
std::vector> item_widgets;
menu_widget *parent_menu = nullptr;
std::shared_ptr create_bg(bool is_main);
menu menu_data;
menu_widget();
popup_direction direction = popup_direction::bottom_right;
void init_from_data(menu menu_data);
bool animate_appear_started = false;
void reset_animation(bool reverse = false);
void update(ui::update_context &ctx) override;
void update_icon_width();
void render(ui::nanovg_context ctx) override;
bool check_hit(const ui::update_context &ctx) override;
void close();
};
struct mouse_menu_widget_main : public ui::widget {
float anchor_x = 0, anchor_y = 0;
mouse_menu_widget_main(menu menu_data, float x, float y);
bool position_calibrated = false, direction_calibrated = false;
popup_direction direction;
std::shared_ptr menu_wid;
void update(ui::update_context &ctx);
void render(ui::nanovg_context ctx);
static std::pair
calculate_position(menu_widget *menu_wid, ui::update_context &ctx,
float anchor_x, float anchor_y, popup_direction direction);
static popup_direction calculate_direction(
menu_widget *menu_wid, ui::update_context &ctx, float anchor_x,
float anchor_y,
popup_direction prefer_direction = popup_direction::bottom_right);
void calibrate_position(ui::update_context &ctx, bool animated = true);
void calibrate_direction(ui::update_context &ctx);
};
} // namespace mb_shell
```
## /src/shell/entry.cc
```cc path="/src/shell/entry.cc"
#include "GLFW/glfw3.h"
#include "blook/blook.h"
#include "config.h"
#include "entry.h"
#include "error_handler.h"
#include "res_string_loader.h"
#include "script/binding_types.h"
#include "script/quickjspp.hpp"
#include "script/script.h"
#include "ui.h"
#include "utils.h"
#include "./contextmenu/contextmenu.h"
#include "./contextmenu/menu_render.h"
#include "./contextmenu/menu_widget.h"
#include "fix_win11_menu.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define NOMINMAX
#include
namespace mb_shell {
window_proc_hook entry::main_window_loop_hook{};
void main() {
set_thread_locale_utf8();
AllocConsole();
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
freopen("CONIN$", "r", stdin);
ShowWindow(GetConsoleWindow(), SW_HIDE);
install_error_handlers();
config::run_config_loader();
res_string_loader::init();
fix_win11_menu::install();
static std::atomic_bool has_active_menu = false;
std::thread([]() {
script_context ctx;
auto data_dir = config::data_directory();
auto script_dir = data_dir / "scripts";
if (!std::filesystem::exists(script_dir))
std::filesystem::create_directories(script_dir);
ctx.watch_folder(script_dir, [&]() { return !has_active_menu.load(); });
}).detach();
auto proc = blook::Process::self();
auto win32u = proc->module("win32u.dll");
auto user32 = proc->module("user32.dll");
auto NtUserTrackPopupMenu = win32u.value()->exports("NtUserTrackPopupMenuEx");
static auto NtUserTrackHook = NtUserTrackPopupMenu->inline_hook();
std::set_terminate([]() {
auto eptr = std::current_exception();
if (eptr) {
try {
std::rethrow_exception(eptr);
} catch (const std::exception &e) {
std::cerr << "Uncaught exception: " << e.what() << std::endl;
} catch (...) {
std::cerr << "Uncaught exception of unknown type" << std::endl;
}
ShowWindow(GetConsoleWindow(), SW_SHOW);
std::getchar();
}
std::abort();
});
std::thread([]() {
if (auto res = ui::render_target::init_global(); !res) {
MessageBoxW(NULL, L"Failed to initialize global render target", L"Error",
MB_ICONERROR);
return;
}
}).detach();
NtUserTrackHook->install(+[](HMENU hMenu, int64_t uFlags, int64_t x,
int64_t y, HWND hWnd, int64_t lptpm) {
if (GetPropW(hWnd, L"COwnerDrawPopupMenu_This") &&
config::current->context_menu.ignore_owner_draw) {
return NtUserTrackHook->call_trampoline(hMenu, uFlags, x, y,
hWnd, lptpm);
}
entry::main_window_loop_hook.install(hWnd);
has_active_menu = true;
perf_counter perf("TrackPopupMenuEx");
menu menu = menu::construct_with_hmenu(hMenu, hWnd);
perf.end("construct_with_hmenu");
auto menu_render = menu_render::create(x, y, menu);
menu_render.rt->last_time = menu_render.rt->clock.now();
perf.end("menu_render::create");
menu_render.rt->start_loop();
has_active_menu = false;
if (menu_render.selected_menu && !(uFlags & TPM_NONOTIFY)) {
PostMessageW(hWnd, WM_COMMAND, *menu_render.selected_menu, 0);
PostMessageW(hWnd, WM_NULL, 0, 0);
}
return (int32_t)menu_render.selected_menu.value_or(0);
});
}
} // namespace mb_shell
int APIENTRY DllMain(HINSTANCE hInstance, DWORD fdwReason, LPVOID lpvReserved) {
switch (fdwReason) {
case DLL_PROCESS_ATTACH: {
auto cmdline = std::string(GetCommandLineA());
std::ranges::transform(cmdline, cmdline.begin(), tolower);
mb_shell::main();
break;
}
}
return 1;
}
```
## /src/shell/entry.h
```h path="/src/shell/entry.h"
#pragma once
#include "window_proc_hook.h"
namespace mb_shell {
struct entry {
static window_proc_hook main_window_loop_hook;
};
} // namespace mb_shell
```
## /src/shell/error_handler.cc
```cc path="/src/shell/error_handler.cc"
#include "error_handler.h"
#include
#include
#include
#include
#include
#include
#include
#include "build_info.h"
#include "config.h"
#include "utils.h"
#include "Windows.h"
#include
void show_console() {
if (!GetConsoleWindow()) {
AllocConsole();
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
}
ShowWindow(GetConsoleWindow(), SW_SHOW);
SetForegroundWindow(GetConsoleWindow());
}
inline void output_crash_header(std::stringstream &ss) {
ss << "Breeze Shell " << BREEZE_VERSION << " crash report" << std::endl;
ss << "----------------------------------------" << std::endl;
ss << "Build date: " << BREEZE_BUILD_DATE_TIME << std::endl;
ss << "Git commit hash: " << BREEZE_GIT_COMMIT_HASH << std::endl;
ss << "Commit page: https://github.com/std-microblock/breeze-shell/commit/"
<< BREEZE_GIT_COMMIT_HASH << std::endl;
ss << "Git branch: " << BREEZE_GIT_BRANCH_NAME << std::endl;
ss << "Data directory: " << mb_shell::config::data_directory() << std::endl;
ss << "Windows version: "
<< (mb_shell::is_win11_or_later() ? "11 or later" : "10 or earlier")
<< std::endl;
ss << "----------------------------------------" << std::endl;
ss << "Config:" << std::endl;
ss << mb_shell::config::dump_config() << std::endl;
ss << "----------------------------------------" << std::endl;
}
std::wstring GetBacktrace(CONTEXT *contextRecord) {
std::wstring info;
wchar_t symbol_mem[sizeof(IMAGEHLP_SYMBOL64) + 256];
auto symbol = (IMAGEHLP_SYMBOL64 *)symbol_mem;
std::string current_module_path = std::string(MAX_PATH, '\0');
GetModuleFileNameA(nullptr, current_module_path.data(),
current_module_path.size());
std::filesystem::path current_module_path_fs = current_module_path;
auto current_module_folder = current_module_path_fs.parent_path();
// Initialize the symbol handler
SymInitializeW(GetCurrentProcess(),
current_module_folder.c_str(), TRUE);
// Initialize the stack frame
STACKFRAME64 stackFrame = {0};
#ifdef _WIN64
stackFrame.AddrPC.Offset = contextRecord->Rip;
stackFrame.AddrPC.Mode = AddrModeFlat;
stackFrame.AddrFrame.Offset = contextRecord->Rbp;
stackFrame.AddrFrame.Mode = AddrModeFlat;
stackFrame.AddrStack.Offset = contextRecord->Rsp;
stackFrame.AddrStack.Mode = AddrModeFlat;
#else
stackFrame.AddrPC.Offset = contextRecord->Eip;
stackFrame.AddrPC.Mode = AddrModeFlat;
stackFrame.AddrFrame.Offset = contextRecord->Ebp;
stackFrame.AddrFrame.Mode = AddrModeFlat;
stackFrame.AddrStack.Offset = contextRecord->Esp;
stackFrame.AddrStack.Mode = AddrModeFlat;
#endif
DWORD64 displacement = 0;
// Walk the call stack and append each frame to the string
while (StackWalk64(
#ifdef _WIN64
IMAGE_FILE_MACHINE_AMD64
#else
IMAGE_FILE_MACHINE_I386
#endif
,
GetCurrentProcess(), GetCurrentThread(), &stackFrame, contextRecord,
nullptr, SymFunctionTableAccess64, SymGetModuleBase64, nullptr)) {
// Get the module name and offset for this frame
DWORD64 moduleBase =
SymGetModuleBase64(GetCurrentProcess(), stackFrame.AddrPC.Offset);
wchar_t moduleName[MAX_PATH];
GetModuleFileNameW((HMODULE)moduleBase, moduleName, MAX_PATH);
DWORD64 offset = stackFrame.AddrPC.Offset - moduleBase;
symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
symbol->MaxNameLength = 255;
wchar_t name[256] = {};
SymGetSymFromAddr64(GetCurrentProcess(), stackFrame.AddrPC.Offset,
&displacement, symbol);
DWORD dwDisplacement;
IMAGEHLP_LINE64 line;
SymGetLineFromAddr64(GetCurrentProcess(), stackFrame.AddrPC.Offset,
&dwDisplacement, &line);
UnDecorateSymbolNameW(mb_shell::utf8_to_wstring(symbol->Name).c_str(), name,
256, UNDNAME_COMPLETE);
// Append the frame to the string
wchar_t frameInfo[1024];
swprintf_s(frameInfo, L"%s + %I64X", moduleName, offset);
info += std::wstring(frameInfo) + std::wstring(L"(") + std::wstring(name) +
std::wstring(L") at line ") + std::to_wstring(line.LineNumber) + L"\n";
}
// Cleanup the symbol handler
SymCleanup(GetCurrentProcess());
// Return the backtrace string
return info;
}
std::string GetExceptionName(EXCEPTION_POINTERS *ExceptionInfo) {
std::string exceptionName;
switch (ExceptionInfo->ExceptionRecord->ExceptionCode) {
case EXCEPTION_ACCESS_VIOLATION:
exceptionName = "ACCESS_VIOLATION";
break;
case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
exceptionName = "ARRAY_BOUNDS_EXCEEDED";
break;
case EXCEPTION_BREAKPOINT:
exceptionName = "BREAKPOINT";
break;
case EXCEPTION_DATATYPE_MISALIGNMENT:
exceptionName = "DATATYPE_MISALIGNMENT";
break;
case EXCEPTION_FLT_DENORMAL_OPERAND:
exceptionName = "FLT_DENORMAL_OPERAND";
break;
case EXCEPTION_FLT_DIVIDE_BY_ZERO:
exceptionName = "FLT_DIVIDE_BY_ZERO";
break;
case EXCEPTION_FLT_INEXACT_RESULT:
exceptionName = "FLT_INEXACT_RESULT";
break;
case EXCEPTION_FLT_INVALID_OPERATION:
exceptionName = "FLT_INVALID_OPERATION";
break;
case EXCEPTION_FLT_OVERFLOW:
exceptionName = "FLT_OVERFLOW";
break;
case EXCEPTION_FLT_STACK_CHECK:
exceptionName = "FLT_STACK_CHECK";
break;
case EXCEPTION_FLT_UNDERFLOW:
exceptionName = "FLT_UNDERFLOW";
break;
case EXCEPTION_ILLEGAL_INSTRUCTION:
exceptionName = "ILLEGAL_INSTRUCTION";
break;
case EXCEPTION_IN_PAGE_ERROR:
exceptionName = "IN_PAGE_ERROR";
break;
case EXCEPTION_INT_DIVIDE_BY_ZERO:
exceptionName = "INT_DIVIDE_BY_ZERO";
break;
case EXCEPTION_INT_OVERFLOW:
exceptionName = "INT_OVERFLOW";
break;
case EXCEPTION_INVALID_DISPOSITION:
exceptionName = "INVALID_DISPOSITION";
break;
case EXCEPTION_NONCONTINUABLE_EXCEPTION:
exceptionName = "NONCONTINUABLE_EXCEPTION";
break;
case EXCEPTION_PRIV_INSTRUCTION:
exceptionName = "PRIV_INSTRUCTION";
break;
case EXCEPTION_SINGLE_STEP:
exceptionName = "SINGLE_STEP";
break;
case EXCEPTION_STACK_OVERFLOW:
exceptionName = "STACK_OVERFLOW";
break;
default:
exceptionName = "UNKNOWN";
break;
}
return exceptionName;
}
void mb_shell::install_error_handlers() {
SetUnhandledExceptionFilter([](PEXCEPTION_POINTERS ex) -> LONG {
show_console();
std::ofstream file(config::data_directory().string() +
"\\crash_report.txt");
std::stringstream ss;
output_crash_header(ss);
ss << "Exception code: " << std::hex << ex->ExceptionRecord->ExceptionCode
<< "(" << GetExceptionName(ex) << ")" << std::endl;
ss << "Exception flags: " << std::hex << ex->ExceptionRecord->ExceptionFlags
<< std::endl;
ss << "Exception address: " << std::hex
<< ex->ExceptionRecord->ExceptionAddress << std::endl;
ss << "Registers:" << std::endl;
ss << "RAX: " << std::hex << ex->ContextRecord->Rax << std::endl;
ss << "RBX: " << std::hex << ex->ContextRecord->Rbx << std::endl;
ss << "RCX: " << std::hex << ex->ContextRecord->Rcx << std::endl;
ss << "RDX: " << std::hex << ex->ContextRecord->Rdx << std::endl;
ss << "R8: " << std::hex << ex->ContextRecord->R8 << std::endl;
ss << "R9: " << std::hex << ex->ContextRecord->R9 << std::endl;
ss << "R10: " << std::hex << ex->ContextRecord->R10 << std::endl;
ss << "R11: " << std::hex << ex->ContextRecord->R11 << std::endl;
ss << "R12: " << std::hex << ex->ContextRecord->R12 << std::endl;
ss << "R13: " << std::hex << ex->ContextRecord->R13 << std::endl;
ss << "R14: " << std::hex << ex->ContextRecord->R14 << std::endl;
ss << "R15: " << std::hex << ex->ContextRecord->R15 << std::endl;
ss << "RDI: " << std::hex << ex->ContextRecord->Rdi << std::endl;
ss << "RSI: " << std::hex << ex->ContextRecord->Rsi << std::endl;
ss << "RBP: " << std::hex << ex->ContextRecord->Rbp << std::endl;
ss << "RSP: " << std::hex << ex->ContextRecord->Rsp << std::endl;
ss << "RIP: " << std::hex << ex->ContextRecord->Rip << std::endl;
ss << "Stack trace:" << std::endl;
ss << wstring_to_utf8(GetBacktrace(ex->ContextRecord)) << std::endl;
if (file.is_open()) {
file << ss.str();
file.flush();
file.close();
}
std::cerr << ss.str();
Sleep(5000);
return EXCEPTION_CONTINUE_EXECUTION;
});
std::set_terminate([]() {
show_console();
std::stringstream ss;
output_crash_header(ss);
try {
throw std::current_exception();
} catch (const std::exception &e) {
ss << "Uncaught exception: " << e.what() << std::endl;
} catch (...) {
ss << "Uncaught exception of unknown type" << std::endl;
}
CONTEXT ctx;
RtlCaptureContext(&ctx);
ss << "Stack trace:" << std::endl;
ss << wstring_to_utf8(GetBacktrace(&ctx)) << std::endl;
std::ofstream file(config::data_directory().string() +
"\\crash_report.txt");
if (file.is_open()) {
file << ss.str();
file.flush();
file.close();
}
std::cerr << ss.str();
Sleep(5000);
});
}
```
## /src/shell/error_handler.h
```h path="/src/shell/error_handler.h"
#pragma once
namespace mb_shell {
void install_error_handlers();
}
```
## /src/shell/fix_win11_menu.cc
```cc path="/src/shell/fix_win11_menu.cc"
#include "fix_win11_menu.h"
#include
#include
#include
#include
#include
#include "blook/blook.h"
#include "blook/memo.h"
#include "utils.h"
#include "zasm/base/immediate.hpp"
#include "zasm/x86/mnemonic.hpp"
#include "zasm/x86/register.hpp"
// https://stackoverflow.com/questions/937044/determine-path-to-registry-key-from-hkey-handle-in-c
#include
#define WIN32_NO_STATUS
#include
#include
#pragma comment(lib, "ntdll")
#include
#include
#define REG_KEY_PATH_LENGTH 1024
typedef enum _KEY_INFORMATION_CLASS {
KeyBasicInformation,
KeyNodeInformation,
KeyFullInformation,
KeyNameInformation,
KeyCachedInformation,
KeyFlagsInformation,
KeyVirtualizationInformation,
KeyHandleTagsInformation,
KeyTrustInformation,
KeyLayerInformation,
MaxKeyInfoClass
} KEY_INFORMATION_CLASS;
typedef struct _KEY_NAME_INFORMATION {
ULONG NameLength;
WCHAR Name[1];
} KEY_NAME_INFORMATION, *PKEY_NAME_INFORMATION;
EXTERN_C NTSYSAPI NTSTATUS NTAPI NtQueryKey(
__in HANDLE /* KeyHandle */,
__in KEY_INFORMATION_CLASS /* KeyInformationClass */,
__out_opt PVOID /* KeyInformation */, __in ULONG /* Length */,
__out ULONG * /* ResultLength */
);
std::wstring RegQueryKeyPath(HKEY hKey) {
std::wstring keyPath;
NTSTATUS Status;
std::vector Buffer(FIELD_OFFSET(KEY_NAME_INFORMATION, Name) +
sizeof(WCHAR) * REG_KEY_PATH_LENGTH);
KEY_NAME_INFORMATION *pkni;
ULONG Length;
TryAgain:
Status = NtQueryKey(hKey, KeyNameInformation, Buffer.data(), Buffer.size(),
&Length);
switch (Status) {
case STATUS_BUFFER_TOO_SMALL:
case STATUS_BUFFER_OVERFLOW:
Buffer.resize(Length);
goto TryAgain;
case STATUS_SUCCESS:
pkni = reinterpret_cast(Buffer.data());
keyPath.assign(pkni->Name, pkni->NameLength / sizeof(WCHAR));
default:
break;
}
return keyPath;
}
void mb_shell::fix_win11_menu::install() {
auto proc = blook::Process::self();
// approch 1: simulated reg edit
auto advapi32 = proc->module("kernelbase.dll");
auto RegGetValueW = advapi32.value()->exports("RegGetValueW");
static auto RegGetValueHook = RegGetValueW->inline_hook();
RegGetValueHook->install(
(void *)+[](HKEY hkey, LPCWSTR lpSubKey, LPCWSTR lpValue, DWORD dwFlags,
LPDWORD pdwType, PVOID pvData, LPDWORD pcbData) {
// simulate
// reg.exe add
//
//
// "HKCU\Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\InprocServer32"
// /f /ve
auto path = wstring_to_utf8(RegQueryKeyPath(hkey));
if (path.ends_with("\\CLSID\\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}"
"\\InprocServer32")) {
if (pvData != nullptr && pcbData != nullptr) {
*pcbData = 0;
}
if (pdwType != nullptr) {
*pdwType = REG_SZ;
}
return ERROR_SUCCESS;
} else
return RegGetValueHook->call_trampoline(
hkey, lpSubKey, lpValue, dwFlags, pdwType, pvData, pcbData);
});
// approch 2: patch the shell32.dll to predent the shift key is pressed
std::thread([=]() {
if (auto shell32 = proc->module("shell32.dll")) {
// mov ecx, 10
// call GetKeyState/GetAsyncKeyState
auto disasm = shell32.value()->section(".text")->disassembly();
auto patch_area = [&](auto mem) {
for (auto it = mem.begin(); it != mem.end(); ++it) {
auto &insn = *it;
if (insn->getMnemonic() == zasm::x86::Mnemonic::Mov) {
if (insn->getOperand(0) == zasm::x86::ecx &&
insn->getOperand(1).template holds() &&
insn->getOperand(1)
.template get()
.template value() == 0x10) {
auto &next = *std::next(it);
if (next->getMnemonic() == zasm::x86::Mnemonic::Call &&
next->getOperand(0).template holds()) {
insn.ptr()
.reassembly([](auto a) {
a.mov(zasm::x86::eax, 0x0);
a.bts(zasm::x86::edi, 0x8);
a.nop();
a.nop();
a.nop();
})
.patch();
return true;
}
}
}
}
return false;
};
// the function to determine if show win10 menu or win11 menu calls
// SetMessageExtraInfo, so we use it as a hint
auto extraInfo =
GetProcAddress(LoadLibraryA("user32.dll"), "SetMessageExtraInfo");
for (auto &ins : disasm) {
if (ins->getMnemonic() == zasm::x86::Mnemonic::Call) {
auto xrefs = ins.xrefs();
if (xrefs.empty())
continue;
if (auto ptr = xrefs[0].try_read();
ptr.has_value() && ptr.value() == extraInfo) {
if (patch_area(ins.ptr()
.find_upwards({0x40, 0x55})
->range_size(0x150)
.disassembly()))
break;
}
}
}
}
}).detach();
}
```
## /src/shell/fix_win11_menu.h
```h path="/src/shell/fix_win11_menu.h"
#pragma once
namespace mb_shell {
struct fix_win11_menu {
static void install();
};
}
```
## /src/shell/logger.cc
```cc path="/src/shell/logger.cc"
#include "logger.h"
#include "config.h"
#include "utils.h"
#include
#include
#include
#include
namespace mb_shell {
void append_debug_string(const std::string &str) {
static std::mutex mutex;
static std::ofstream file(config::data_directory() / "debug.log",
std::ios::app);
std::lock_guard lock(mutex);
file << str;
file.flush();
printf("%s", str.c_str());
OutputDebugStringA(str.c_str());
}
} // namespace mb_shell
```
## /src/shell/logger.h
```h path="/src/shell/logger.h"
#pragma once
#include
#include
#include
namespace mb_shell {
void append_debug_string(const std::string &str);
template
void dbgout(const std::format_string fmt, types&&... args) {
std::string str = std::format(fmt, std::forward(args)...);
append_debug_string(str + "\n");
}
}
```
## /src/shell/res_string_loader.cc
```cc path="/src/shell/res_string_loader.cc"
#include "res_string_loader.h"
#include
#include
#include
#include
#include
#include
#include
#include "config.h"
#include "utils.h"
#include "blook/blook.h"
#include "logger.h"
#include "Windows.h"
namespace mb_shell {
static std::mutex lock_str_data;
static std::unordered_map
str_data;
static std::unordered_map module_name_cache;
res_string_loader::string_id res_string_loader::string_to_id(std::wstring str) {
std::lock_guard lock(lock_str_data);
auto it = str_data.find(str);
if (it != str_data.end()) {
return it->second;
}
return std::hash{}(str);
}
std::string get_module_name_from_instance(HINSTANCE hInstance) {
char buffer[MAX_PATH];
GetModuleFileNameA(hInstance, buffer, MAX_PATH);
return std::filesystem::path(buffer).filename().string();
}
size_t store_module_name(HINSTANCE hInstance) {
std::string module_name = get_module_name_from_instance(hInstance);
auto mod_hash = std::hash{}(module_name);
module_name_cache[mod_hash] = module_name;
return mod_hash;
}
void res_string_loader::init_hook() {
static std::atomic_bool inited = false;
if (inited.exchange(true)) {
return;
}
auto proc = blook::Process::self();
auto kernelbase = proc->module("kernelbase.dll").value();
static auto LoadStringWHook =
kernelbase->exports("LoadStringW")->inline_hook();
LoadStringWHook->install(+[](HINSTANCE hInstance, UINT uID, LPWSTR lpBuffer,
int cchBufferMax) -> int {
auto res = LoadStringWHook->call_trampoline(hInstance, uID, lpBuffer,
cchBufferMax);
if (res > 0) {
std::wstring str(lpBuffer, res);
std::lock_guard lock(lock_str_data);
if (str_data.find(str) != str_data.end())
return res;
str_data[str] = {uID, store_module_name(hInstance)};
}
return res;
});
static auto LoadStringAHook =
kernelbase->exports("LoadStringA")->inline_hook();
LoadStringAHook->install(+[](HINSTANCE hInstance, UINT uID, LPSTR lpBuffer,
int cchBufferMax) -> int {
auto res = LoadStringAHook->call_trampoline(hInstance, uID, lpBuffer,
cchBufferMax);
if (res > 0) {
std::string str(lpBuffer, res);
std::lock_guard lock(lock_str_data);
auto s = utf8_to_wstring(str);
if (str_data.find(s) != str_data.end())
return res;
str_data[s] = {uID, store_module_name(hInstance)};
}
return res;
});
}
std::string res_string_loader::string_to_id_string(std::wstring str) {
auto id = string_to_id(str);
if (auto *p = std::get_if(&id)) {
return std::to_string(p->id) + "@" + module_name_cache[p->module];
} else {
return std::to_string(std::get(id)) + "@0";
}
}
void res_string_loader::init() {
std::thread([]() {
init_known_strings();
if (config::current->res_string_loader_use_hook)
init_hook();
}).detach();
}
void EnumerateStringResources(
HMODULE mod, std::function callback) {
EnumResourceNamesW(
mod, MAKEINTRESOURCEW(6),
+[](HMODULE hModule, LPCWSTR /*lpType*/, LPWSTR lpName,
LONG_PTR lParam) -> BOOL {
auto &cb =
*reinterpret_cast *>(
lParam);
if (!IS_INTRESOURCE(lpName))
return TRUE;
HRSRC hRes = FindResourceW(hModule, lpName, MAKEINTRESOURCEW(6));
if (!hRes)
return TRUE;
HGLOBAL hData = LoadResource(hModule, hRes);
if (!hData)
return TRUE;
const BYTE *pData = static_cast(LockResource(hData));
if (!pData)
return TRUE;
DWORD dwSize = SizeofResource(hModule, hRes);
DWORD pos = 0;
for (int i = 0; i < 16 && pos < dwSize; ++i) {
WORD len = *reinterpret_cast