[
  {
    "path": ".gitignore",
    "content": "# Generated by Cargo\n# will have compiled files and executables\ndebug/\ntarget/\n\n# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries\n# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html\nCargo.lock\n\n# These are backup files generated by rustfmt\n**/*.rs.bk\n\n# MSVC Windows builds of rustc generate these, which store debugging information\n*.pdb\n"
  },
  {
    "path": ".vscode/launch.json",
    "content": "{\n    // Use IntelliSense to learn about possible attributes.\n    // Hover to view descriptions of existing attributes.\n    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387\n    \"version\": \"0.2.0\",\n    \"configurations\": [\n        {\n            \"name\": \"(Windows) Launch\",\n            \"type\": \"cppvsdbg\",\n            \"request\": \"launch\",\n            \"program\": \"${workspaceFolder}/target/debug/no_english_mode.exe\",\n            \"args\": [],\n            \"stopAtEntry\": false,\n            \"cwd\": \"${fileDirname}\",\n            \"environment\": [],\n            \"console\": \"externalTerminal\"\n        }\n\n    ]\n}"
  },
  {
    "path": ".vscode/tasks.json",
    "content": "{\n\t\"version\": \"2.0.0\",\n\t\"tasks\": [\n\t\t{\n\t\t\t\"type\": \"cargo\",\n\t\t\t\"command\": \"build\",\n\t\t\t\"problemMatcher\": [\n\t\t\t\t\"$rustc\"\n\t\t\t],\n\t\t\t\"group\": \"build\",\n\t\t\t\"label\": \"rust: cargo build\"\n\t\t},\n\t\t{\n\t\t\t\"type\": \"cargo\",\n\t\t\t\"command\": \"clippy\",\n\t\t\t\"problemMatcher\": [\n\t\t\t\t\"$rustc\"\n\t\t\t],\n\t\t\t\"group\": \"build\",\n\t\t\t\"label\": \"rust: cargo clippy\"\n\t\t}\n\t]\n}"
  },
  {
    "path": "Cargo.toml",
    "content": "[package]\nname = \"no_english_mode\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\nbuild = \"build.rs\"\n\n[dependencies]\n\n[dependencies.windows]\nversion = \"0.58\"\nfeatures = [\n    \"Data_Xml_Dom\",\n    \"Win32_Foundation\",\n    \"Win32_Graphics_Gdi\",\n    \"Win32_Security\",\n    \"Win32_System_LibraryLoader\",\n    \"Win32_System_SystemServices\",\n    \"Win32_System_Threading\",\n    \"Win32_UI_Accessibility\",\n    \"Win32_UI_Input_Ime\",\n    \"Win32_UI_Input_KeyboardAndMouse\",\n    \"Win32_UI_Input\",\n    \"Win32_UI_Shell\",\n    \"Win32_UI_TextServices\",\n    \"Win32_UI_WindowsAndMessaging\",\n]\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# NO English Mode!\n防止微软拼音输入法启动切换到英文模式\n\n和AutoHotkey脚本的区别是这个程序监听focus事件而不是一直循环，运行在后台几乎不消耗资源，用户完全无感知。\n\n![Screenshot](assets/screenshot.png)\n\n# 安装\n下载以后直接运行exe即可。需要开机启动可以执行 `copy_to_startup.bat`，这个脚本会把exe复制到startup目录。\n在运行的时候托盘会有一个图标，在图标上点击右键可以退出程序。\n\n# 编译\n代码用Rust编写，安装Rust环境以后执行下面的命令\n`cargo build [--release]`\n"
  },
  {
    "path": "assets/app.rc",
    "content": "#define IDI_ICON1 101\nIDI_ICON1 ICON \"app.ico\"\n"
  },
  {
    "path": "assets/copy_to_startup.bat",
    "content": "@echo off\nsetlocal\n\n:: Get the path to the current user's Startup folder\nset STARTUP_FOLDER=%USERPROFILE%\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\n\n:: Specify the path to your application's executable\nset APP_EXE=no_english_mode.exe\n\n:: Copy the application to the Startup folder\ncopy /Y \"%APP_EXE%\" \"%STARTUP_FOLDER%\"\n\n:: Inform the user\necho Your application has been copied to the Startup folder.\npause\nendlocal\n"
  },
  {
    "path": "build.rs",
    "content": "fn main() {\n    // use std::process::Command;\n    // // Get the path to the output directory\n    // let out_dir = env::var(\"OUT_DIR\").unwrap();\n\n    // // Define paths for the .rc and .res files\n    // let rc_path = \"assets/app.rc\";\n    // let res_path = Path::new(&out_dir).join(\"app.res\");\n\n    // // Compile the resource file\n    // Command::new(\"rc\")\n    //     .args(&[\"/fo\", res_path.to_str().unwrap(), rc_path])\n    //     .status()\n    //     .unwrap();\n\n    // // Tell cargo to link the resource file\n    // println!(\"cargo:rustc-link-search=native={}\", out_dir);\n    // println!(\"cargo:rustc-link-arg=app.res\");\n\n    println!(\"cargo:rustc-link-arg=assets/app.res\");\n}\n"
  },
  {
    "path": "rustfmt.toml",
    "content": "reorder_imports = true\nimports_granularity = \"Crate\"\ngroup_imports = \"StdExternalCrate\""
  },
  {
    "path": "src/main.rs",
    "content": "#![windows_subsystem = \"windows\"]\n\nuse std::{thread, time::Duration};\n\nuse windows::{\n    core::*,\n    Win32::{\n        Foundation::*,\n        System::LibraryLoader::GetModuleHandleW,\n        UI::{\n            Accessibility::*,\n            Input::{Ime::*, KeyboardAndMouse::*},\n            Shell::*,\n            WindowsAndMessaging::*,\n        },\n    },\n};\n\nunsafe extern \"system\" fn event_hook_callback(\n    _h_win_event_hook: HWINEVENTHOOK,\n    _event: u32,\n    hwnd: HWND,\n    _id_object: i32,\n    _id_child: i32,\n    _id_event_thread: u32,\n    _dwms_event_time: u32,\n) {\n    // Get the thread ID of the window that has come to the foreground.\n    let thread_id = GetWindowThreadProcessId(hwnd, None);\n\n    // Get the current keyboard layout\n    let hkl = GetKeyboardLayout(thread_id);\n\n    // Check if the current IME status matches Chinese (0x804)~\n    if ((hkl.0 as u32 & 0xffff) == 0x804) && (hwnd.0 != std::ptr::null_mut()) {\n        // Get the ime window handle\n        let ime_hwnd = ImmGetDefaultIMEWnd(hwnd);\n        // Switch the IME state\n        println!(\"Chinese input method detected, forcing Chinese mode.\");\n        // Sometimes the message will miss if we don't sleep for a little while.\n        thread::sleep(Duration::from_millis(50));\n        SendMessageW(\n            ime_hwnd,\n            WM_IME_CONTROL,\n            WPARAM(IMC_SETCONVERSIONMODE as usize),\n            LPARAM(1025), // Chinese\n        );\n    }\n}\n\n// Make sure this is the same as the icon id in the rc file\nconst IDI_ICON1: u16 = 101;\nconst IDM_EXIT: u32 = 1001;\nconst NOTIFYICONMESSAGE: u32 = WM_USER + 100;\n\nfn add_tray_icon(hwnd: HWND) -> windows::core::Result<()> {\n    let h_instance = unsafe { GetModuleHandleW(None) }?;\n\n    let mut nid = NOTIFYICONDATAW {\n        uFlags: NIF_MESSAGE | NIF_ICON | NIF_TIP,\n        hWnd: hwnd,\n        uCallbackMessage: NOTIFYICONMESSAGE,\n        hIcon: unsafe { LoadIconW(h_instance, PCWSTR(IDI_ICON1 as *const u16))? }, // Load the app icon\n        szTip: [0; 128],                                                           // Tooltip text\n        ..Default::default()\n    };\n\n    unsafe {\n        // Convert the tooltip to a wide string\n        let tooltip = \"NoEnglishMode\\0\";\n        for (i, c) in tooltip.encode_utf16().enumerate() {\n            nid.szTip[i] = c;\n        }\n\n        // Add the icon\n        Shell_NotifyIconW(NIM_ADD, &mut nid);\n    }\n    Ok(())\n}\n\nunsafe extern \"system\" fn window_proc(\n    hwnd: HWND,\n    msg: u32,\n    wparam: WPARAM,\n    lparam: LPARAM,\n) -> LRESULT {\n    match msg {\n        NOTIFYICONMESSAGE => match lparam.0 as u32 {\n            WM_RBUTTONUP => {\n                let mut point = POINT::default();\n                let _ = GetCursorPos(&mut point);\n\n                let hmenu = CreatePopupMenu().unwrap();\n                let menu_item_str: &'static str = \"Exit\";\n                let menu_item_wstr: Vec<u16> = menu_item_str\n                    .encode_utf16()\n                    .chain(std::iter::once(0))\n                    .collect();\n                let _ = AppendMenuW(\n                    hmenu,\n                    MENU_ITEM_FLAGS(0),\n                    IDM_EXIT as usize,\n                    PCWSTR(menu_item_wstr.as_ptr()),\n                );\n\n                // Set the foreground window to the current window to ensure the menu closes properly\n                SetForegroundWindow(hwnd);\n\n                // Track the popup menu at the cursor position\n                TrackPopupMenu(hmenu, TPM_RIGHTBUTTON, point.x, point.y, 0, hwnd, None);\n\n                // Required to make sure the menu closes on time\n                let _ = PostMessageW(hwnd, WM_NULL, WPARAM(0), LPARAM(0));\n            }\n            _ => {}\n        },\n        WM_COMMAND => {\n            match wparam.0 as u32 {\n                IDM_EXIT => {\n                    // Handle the \"Exit\" menu item\n                    PostQuitMessage(0);\n                }\n                _ => {}\n            }\n        }\n        WM_DESTROY => {\n            PostQuitMessage(0);\n        }\n        _ => return DefWindowProcW(hwnd, msg, wparam, lparam),\n    }\n\n    LRESULT(0)\n}\n\nfn main() -> windows::core::Result<()> {\n    unsafe {\n        let class_name_str: &'static str = \"hidden_window_class\";\n        let class_name_wide: Vec<u16> = class_name_str\n            .encode_utf16()\n            .chain(std::iter::once(0))\n            .collect();\n        let class_name = PCWSTR(class_name_wide.as_ptr());\n        let window_name_str: &'static str = \"hidden_window\";\n        let window_name_str: Vec<u16> = window_name_str\n            .encode_utf16()\n            .chain(std::iter::once(0))\n            .collect();\n        let window_name = PCWSTR(window_name_str.as_ptr());\n\n        let instance = GetModuleHandleW(None)?;\n\n        // Define a window class\n        let wc = WNDCLASSW {\n            lpfnWndProc: Some(window_proc),\n            hInstance: HINSTANCE(instance.0),\n            lpszClassName: class_name,\n            ..Default::default()\n        };\n\n        // Register the window class\n        let class_atom = RegisterClassW(&wc);\n        if class_atom == 0 {\n            // Handle error\n            return Err(windows::core::Error::from_win32());\n        }\n\n        // Create the hidden window\n        let hwnd = CreateWindowExW(\n            Default::default(),\n            class_name,\n            window_name,\n            WS_OVERLAPPEDWINDOW,\n            CW_USEDEFAULT,\n            CW_USEDEFAULT,\n            CW_USEDEFAULT,\n            CW_USEDEFAULT,\n            None,\n            None,\n            instance,\n            None,\n        );\n\n        if hwnd.as_ref().map_or(true, |h| h.0.is_null()) {\n            // Handle error\n            return Err(windows::core::Error::from_win32());\n        }\n\n        // Add the tray icon using 'hwnd'\n        add_tray_icon(hwnd.unwrap())?;\n\n        // Set the hook\n        let hook = SetWinEventHook(\n            EVENT_OBJECT_FOCUS,\n            EVENT_OBJECT_FOCUS,\n            None, // Handle to the DLL with the callback function, None for the current process\n            Some(event_hook_callback),\n            0,\n            0,\n            WINEVENT_OUTOFCONTEXT,\n        );\n\n        // Check if the hook was set successfully\n        if hook.0 == std::ptr::null_mut() {\n            // Handle the error if the hook is not set\n            println!(\"Failed to set hook!\");\n            return Err(Error::from_win32());\n        }\n\n        // Message loop\n        let mut message = MSG::default();\n        while GetMessageW(&mut message, HWND(std::ptr::null_mut()), 0, 0).into() {\n            TranslateMessage(&message);\n            DispatchMessageW(&message);\n        }\n\n        // Unhook before exit\n        UnhookWinEvent(hook);\n    }\n\n    Ok(())\n}\n"
  }
]