83 Commits
Author SHA1 Message Date
futile 0d7dde929d 0.5.3 2025-04-24 13:24:35 +01:00
futile 3ab802fd56 make RED, YELLOW, and GREEN slightly brighter 2025-04-23 14:33:08 +01:00
futile 53030cc5f7 add debug menu feature to change blocked_status of GameNetworking 2025-04-23 14:32:29 +01:00
futile 383224c2fa update readme 2025-04-23 14:31:50 +01:00
futile 575a6a4f1d update readme 2025-04-22 20:03:09 +01:00
futile 17579de277 update readme 2025-04-22 19:57:09 +01:00
futile 00727b9913 add compilation instructions to the repo 2025-04-22 14:34:37 +01:00
futile 1f6fc22525 check for app elevation in Default of Flags 2025-04-21 12:38:20 +01:00
futile 27b09be76e update screenshot in readme 2025-04-20 12:06:57 +01:00
futile 6f15e8c348 0.5.2 2025-04-20 10:52:21 +01:00
futile d294aa9861 reduce amount of underlying dependencies 2025-04-20 10:48:32 +01:00
futile f688f1c3c4 strip = true doesn't do anything extra anymore 2025-04-20 10:15:33 +01:00
futile 58ec9f6567 clippy 2025-04-20 08:01:41 +01:00
futile 1c9ce2a4d3 remember to place to_color32 for BlockedStatus in the correct place 2025-04-20 07:57:41 +01:00
futile 8a5d6cf38c simplify features::game_networking 2025-04-20 07:56:54 +01:00
futile d789b0f62d rework networking indicator dot 2025-04-20 07:33:34 +01:00
futile 6079a72f47 use SendInput instead of keybd_event for anti afk 2025-04-20 07:07:51 +01:00
futile 914ffe46d2 add tooltip to game networking indicator 2025-04-20 06:55:43 +01:00
futile 935703e1ab listen to a few clippy lints 2025-04-20 06:19:29 +01:00
futile 202554e03b 0.5.1 2025-04-20 01:47:16 +01:00
futile da2b15a0b6 redesign features::force_close internals a bit 2025-04-20 01:42:06 +01:00
futile ccc27b1944 slightly tweak features::game_networking design & add visual indicator for blocking failing due to game being closed 2025-04-20 01:25:25 +01:00
futile 10168e84d1 update readme 2025-04-19 10:52:20 +01:00
futile e72964a9f8 0.5.0 2025-04-19 10:37:06 +01:00
futile 18052d0c78 add red/green circle indicator beside Block/Unblock buttons 2025-04-19 10:35:47 +01:00
futile 09f5a3895b use windows api instead of netsh command to manage game's network access 2025-04-19 10:34:10 +01:00
futile 89892ef592 change a couple of imports in gui::app 2025-04-19 07:20:49 +01:00
futile 61de3aeee3 move debug viewport code to own module 2025-04-19 06:48:56 +01:00
futile 4ed00e6ac3 don't assign PersistentState to variable when setting 2025-04-19 05:23:11 +01:00
futile 332db0ea03 document the process of gui::run::app_creator with comments 2025-04-19 05:18:04 +01:00
futile 64d13e3964 move EmptySession::run_timers back into main update loop so it actually runs 2025-04-19 05:02:24 +01:00
futile feb3a793d9 redesign how anti afk activates 2025-04-19 04:54:02 +01:00
futile 585f454bc0 hunt down some unused pubs 2025-04-19 04:45:47 +01:00
futile 27524e855a numerous improvements in gui and feature code 2025-04-19 04:28:24 +01:00
futile 0257834d04 add checkbox to debug to spoof new version of the app beign available 2025-04-18 20:32:39 +01:00
futile 64e94bf790 change how vks are stored 2025-04-18 05:26:28 +01:00
futile 668a6eb38b get rid of clippy-related allows 2025-04-18 04:44:11 +01:00
futile 0de79769d2 reorganize some consts 2025-04-18 03:17:40 +01:00
futile b79c5f62b3 update screenshot in readme 2025-04-18 03:09:14 +01:00
futile 2c3092026a 0.4.2 2025-04-18 02:44:11 +01:00
futile 69eda1103d improve panic hook 2025-04-18 01:50:19 +01:00
futile 19b1ade758 remove 1 to_string and replace some others with to_owned 2025-04-18 00:59:07 +01:00
futile 18f667a91a improve util::codeberg (error handling & general) 2025-04-18 00:43:40 +01:00
futile 186371f835 include new release's version in download hover 2025-04-17 22:36:10 +01:00
futile ce2022db55 get sysinfo from the git repo, to bump windows 2025-04-17 22:36:10 +01:00
futile d992d6b8f6 refactor gui module 2025-04-17 20:52:19 +01:00
futile b71dbbdf03 change for loop syntax in build_combo_box 2025-04-17 20:38:16 +01:00
futile c85a169765 move gui::persistent_state to util::persistent_state 2025-04-17 20:36:42 +01:00
futile 9df757c169 add button to download latest gta-tools exe 2025-04-17 20:28:25 +01:00
futile 92cbec7934 return window size to [240.0, 240.0] 2025-04-17 04:45:01 +01:00
futile 41cfb12ea8 fix some idiotic const use in features::empty_session 2025-04-17 04:42:31 +01:00
futile e328eb91f6 get CREATE_NO_WINDOW from windows crate 2025-04-17 04:40:06 +01:00
futile 10c840ac4d update readme 2025-04-17 04:26:19 +01:00
futile 2fc0aa2005 update screenshot in readme 2025-04-17 04:16:34 +01:00
futile 29f726b1bd add LICENSE 2025-04-17 03:42:22 +01:00
futile 16d3c2cd96 update justfile 2025-04-17 03:41:24 +01:00
futile 4ce7f3459d 0.4.1 2025-04-17 02:33:27 +01:00
futile c8cbb51f43 thgank you clippy that's very smar thtat's very clever 2025-04-17 02:27:10 +01:00
futile 9c53239276 remove an i32 cast from is_any_key_pressed 2025-04-17 02:25:07 +01:00
futile af5ea259e9 implicit type signature on buffer var in is_window_focused 2025-04-17 02:12:34 +01:00
futile 162350699a change flow of util::win::is_elevated 2025-04-17 02:01:31 +01:00
futile 2977398437 slightly reduce unsafe scopes 2025-04-17 01:48:45 +01:00
futile 36dce5aa1e reduce ai idiocy 2025-04-17 01:39:01 +01:00
futile 6935b852ce clippy 2025-04-17 01:31:49 +01:00
futile 1c048e6aff revert 33fbbc7f 2025-04-17 00:50:09 +01:00
futile 84a659a2b1 add button to debug to open app storage path 2025-04-17 00:49:20 +01:00
futile db4ca22f95 log panics to a file 2025-04-17 00:44:06 +01:00
futile 284c4bb46d add a mouse cursor check to anti afk activation 2025-04-16 23:59:50 +01:00
futile 5fe697223c 0.4.0 2025-04-11 17:27:28 +01:00
futile 33fbbc7fc0 change windows_subsystem = "windows" requirement to debug also 2025-04-11 17:27:22 +01:00
futile 5bcdccdfea use windows vkcodes instead of defining our own 2025-04-10 18:19:12 +01:00
futile 31ac09cd25 make the thing nicer 2025-04-10 18:14:24 +01:00
futile 1283f34174 make Frame of "Game's network access" area invisible 2025-04-10 17:40:40 +01:00
futile 072c8ae406 clippy 2025-04-10 17:28:58 +01:00
futile e283393889 move header 2025-04-10 17:23:22 +01:00
futile cf5c37c7dc add bolder ubuntu font for headers & move rest of setup code into app_creator 2025-04-10 17:19:42 +01:00
futile c6cd0cf2f9 reintroduce ScrollArea to CentralPanel and increase WINDOW_SIZE to accommodate 2025-04-10 16:52:20 +01:00
futile d182ca5318 implement ComboBox builder 2025-04-10 16:32:30 +01:00
futile 42ee688639 move persistent state into own file 2025-04-10 15:17:19 +01:00
futile ba49ed0e67 add basic settings 2025-04-10 13:56:00 +01:00
futile f9f326904e turn crate::gui into a dir module 2025-04-10 08:38:51 +01:00
futile c3a1e864a7 improvements 2025-04-10 08:26:24 +01:00
futile 7f795ba52e make label text not selectable 2025-04-10 07:48:58 +01:00
29 changed files with 1679 additions and 2110 deletions
Generated
+470 -1489
View File
File diff suppressed because it is too large Load Diff
+15 -5
View File
@@ -1,26 +1,37 @@
[package]
name = "gta-tools"
version = "0.3.0"
version = "0.5.3"
edition = "2024"
[dependencies]
catppuccin-egui = { version = "5.5.0", default-features = false, features = [
"egui31",
] }
chrono = { version = "0.4.40", default-features = false, features = ["clock"] }
dirs = "6.0.0"
eframe = "0.31.1"
egui_extras = { version = "0.31.1", features = ["image"] }
eframe = { version = "0.31.1", default-features = false, features = [
"glow",
"default_fonts",
] }
egui_extras = { version = "0.31.1", default-features = false, features = [
"image",
"svg",
] }
image = { version = "0.25.6", default-features = false, features = ["png"] }
open = "5.3.2"
semver = "1.0.26"
serde = { version = "1.0.219", features = ["derive"] }
serde_json = "1.0.140"
sysinfo = "0.34.2"
strum = { version = "0.27.1", features = ["derive"] }
sysinfo = { git = "https://github.com/GuillaumeGomez/sysinfo", rev = "bcbb7b2b389b8800ff457773f48b130e710458fc" }
ureq = { version = "3.0.11", features = ["json"] }
windows = { version = "0.61.1", features = [
"Win32_UI_Input_KeyboardAndMouse",
"Win32_System_Threading",
"Win32_UI_Shell",
"Win32_UI_WindowsAndMessaging",
"Win32_Security",
"Win32_NetworkManagement_WindowsFirewall",
] }
winreg = "0.55.0"
@@ -29,6 +40,5 @@ static_vcruntime = "2.0.0"
winresource = "0.1.20"
[profile.release]
strip = true
lto = true
codegen-units = 1
+176
View File
@@ -0,0 +1,176 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
+12 -2
View File
@@ -1,3 +1,13 @@
more spaghetti than the nation of italy
# GTA Tools
![](https://i.ibb.co/SwdWRfGj/gta-tools-WEQ02u-ROT5.png)
A toolset of convenient things for GTA V Online.
![](https://i.vgy.me/maLh8W.png)
## Installing
**Option 1** — <ins>Download</ins>
Download the latest release [here](https://codeberg.org/futile/gta-tools/releases/download/latest/gta-tools.exe) and place it somewhere convenient for you, such as Documents. You could then make a shortcut titled "GTA Tools", and pin it to taskbar or Start.
**Option 2** — <ins>Build from source</ins>
You will need the Rust toolchain, which can be obtained [here](https://rustup.rs). Follow the instructions of its installer. Once you have Rust installed, clone this repo and navigate to it. At this point, you should probably `git checkout x.x.x`, where `x.x.x` is the latest tag. You can then run `cargo build --release`. Once you do that, you can use the binary located at `.\target\release\gta-tools.exe` in the same way as **Option 1**.
Binary file not shown.
+23
View File
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="512"
height="512"
viewBox="0 0 512 512"
version="1.1"
id="svg1"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs1" />
<g
id="layer1">
<circle
style="fill:#ffffff"
id="path1"
cx="256"
cy="256"
r="256" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 458 B

+1 -4
View File
@@ -1,9 +1,6 @@
set windows-shell := ["pwsh", "-NoLogo", "-NoProfileLoadTime", "-Command"]
build:
install:
cargo build --release
upx .\target\release\gta-tools.exe --best
install: build
cp .\target\release\gta-tools.exe ~\.cargo\bin
cp .\target\release\gta-tools.exe ~\Documents
+34 -26
View File
@@ -1,12 +1,12 @@
use crate::util::{self, consts::GTA_WINDOW_TITLE};
use crate::util::{self, consts::game::WINDOW_TITLE};
use std::time::{Duration, Instant};
use windows::Win32::UI::Input::KeyboardAndMouse::{
KEYBD_EVENT_FLAGS, MAP_VIRTUAL_KEY_TYPE, MapVirtualKeyW, keybd_event,
INPUT, INPUT_KEYBOARD, KEYBD_EVENT_FLAGS, KEYBDINPUT, KEYEVENTF_KEYUP, MAPVK_VK_TO_VSC,
MapVirtualKeyW, SendInput, VIRTUAL_KEY, VK_NUMPAD4, VK_NUMPAD6,
};
pub const INTERVAL: Duration = Duration::from_secs(60);
const VK_NUMPAD4: u8 = 0x64;
const VK_NUMPAD6: u8 = 0x66;
const INTERVAL: Duration = Duration::from_secs(60);
const PRESS_KEYS: [VIRTUAL_KEY; 2] = [VK_NUMPAD4, VK_NUMPAD6];
#[derive(Debug)]
pub struct AntiAfk {
@@ -24,31 +24,39 @@ impl Default for AntiAfk {
}
impl AntiAfk {
pub fn activate(&mut self) {
if util::is_window_focused(GTA_WINDOW_TITLE)
&& !util::is_key_pressed(VK_NUMPAD4 as i32)
&& !util::is_key_pressed(VK_NUMPAD6 as i32)
{
send(VK_NUMPAD4);
send(VK_NUMPAD6);
pub fn can_activate(&self) -> bool {
use util::win::{is_any_key_pressed, is_cursor_visible, is_window_focused};
is_window_focused(WINDOW_TITLE) && !is_any_key_pressed(&PRESS_KEYS) && !is_cursor_visible()
}
pub fn should_activate(&self) -> bool {
self.enabled && self.interval.elapsed() >= INTERVAL
}
pub fn activate(&mut self) {
send(&PRESS_KEYS);
self.interval = Instant::now();
}
}
pub fn send(vk_code: u8) {
unsafe {
keybd_event(
vk_code,
u8::try_from(MapVirtualKeyW(u32::from(vk_code), MAP_VIRTUAL_KEY_TYPE(0))).unwrap(),
KEYBD_EVENT_FLAGS(0),
0,
);
keybd_event(
vk_code,
u8::try_from(MapVirtualKeyW(u32::from(vk_code), MAP_VIRTUAL_KEY_TYPE(0))).unwrap(),
KEYBD_EVENT_FLAGS(2),
0,
);
fn send(vk_codes: &[VIRTUAL_KEY]) {
let mut inputs = Vec::new();
for &vk_code in vk_codes {
let scan_code = unsafe { MapVirtualKeyW(u32::from(vk_code.0), MAPVK_VK_TO_VSC) as u16 };
for event in [KEYBD_EVENT_FLAGS(0), KEYEVENTF_KEYUP] {
let mut input = INPUT {
r#type: INPUT_KEYBOARD,
..Default::default()
};
input.Anonymous.ki = KEYBDINPUT {
wVk: vk_code,
wScan: scan_code,
dwFlags: event,
time: 0,
dwExtraInfo: 0,
};
inputs.push(input);
}
unsafe { SendInput(&inputs, size_of::<INPUT>() as i32) };
}
}
+32 -17
View File
@@ -1,4 +1,7 @@
use crate::{features, gui::App, util::countdown::Countdown};
use crate::util::{
consts::game::{EXE_ENHANCED, EXE_LEGACY},
countdown::Countdown,
};
use std::time::{Duration, Instant};
use sysinfo::System;
use windows::Win32::{
@@ -6,9 +9,7 @@ use windows::Win32::{
System::Threading::{OpenProcess, PROCESS_SUSPEND_RESUME},
};
pub const INTERVAL: Duration = Duration::from_secs(10);
const ENHANCED: &str = "GTA5_Enhanced.exe";
const LEGACY: &str = "GTA5.exe";
const INTERVAL: Duration = Duration::from_secs(10);
#[derive(Debug)]
pub struct EmptySession {
@@ -22,15 +23,29 @@ impl Default for EmptySession {
Self {
disabled: false,
interval: Instant::now(),
countdown: Countdown::new(features::empty_session::INTERVAL.as_secs()),
countdown: Countdown::new(INTERVAL.as_secs()),
}
}
}
impl EmptySession {
pub fn run_timers(&mut self, game_handle: &mut HANDLE) {
if self.disabled {
self.countdown.count();
} else {
self.countdown.reset();
}
if self.interval.elapsed() >= INTERVAL {
deactivate(game_handle);
self.disabled = false;
}
}
}
#[link(name = "ntdll")]
unsafe extern "system" {
pub unsafe fn NtSuspendProcess(ProcessHandle: HANDLE) -> NTSTATUS;
pub unsafe fn NtResumeProcess(ProcessHandle: HANDLE) -> NTSTATUS;
unsafe fn NtSuspendProcess(ProcessHandle: HANDLE) -> NTSTATUS;
unsafe fn NtResumeProcess(ProcessHandle: HANDLE) -> NTSTATUS;
}
fn get_gta_pid(sysinfo: &mut System) -> u32 {
@@ -38,29 +53,29 @@ fn get_gta_pid(sysinfo: &mut System) -> u32 {
if let Some((pid, _)) = sysinfo
.processes()
.iter()
.find(|(_, p)| p.name() == ENHANCED || p.name() == LEGACY)
.find(|(_, p)| p.name() == EXE_ENHANCED || p.name() == EXE_LEGACY)
{
return pid.as_u32();
};
}
u32::MAX
}
pub fn activate(app: &mut App) {
let pid = get_gta_pid(&mut app.sysinfo);
pub fn activate(game_handle: &mut HANDLE, sysinfo: &mut System) {
let pid = get_gta_pid(sysinfo);
if pid == u32::MAX {
return;
}
unsafe {
app.game_handle = OpenProcess(PROCESS_SUSPEND_RESUME, false, pid).unwrap();
let _ = NtSuspendProcess(app.game_handle);
*game_handle = OpenProcess(PROCESS_SUSPEND_RESUME, false, pid).unwrap();
let _ = NtSuspendProcess(*game_handle);
}
}
pub fn deactivate(app: &mut App) {
pub fn deactivate(game_handle: &mut HANDLE) {
unsafe {
if !app.game_handle.is_invalid() {
let _ = NtResumeProcess(app.game_handle);
let _ = CloseHandle(app.game_handle);
if !game_handle.is_invalid() {
let _ = NtResumeProcess(*game_handle);
let _ = CloseHandle(*game_handle);
}
}
}
+37 -13
View File
@@ -1,38 +1,62 @@
use crate::util::consts::{ENHANCED, LEGACY};
use std::time::Instant;
use crate::util::consts::game::{EXE_ENHANCED, EXE_LEGACY};
use std::time::{Duration, Instant};
use sysinfo::System;
const INTERVAL: Duration = Duration::from_secs(3);
#[derive(Debug)]
pub struct ForceClose {
pub button_text: String,
pub prompting: bool,
pub interval: Instant,
timer: Instant,
counting: bool,
current_frame: bool,
}
impl Default for ForceClose {
fn default() -> Self {
Self {
button_text: "Force close game".to_string(),
prompting: false,
interval: Instant::now(),
button_text: "Force close game".to_owned(),
timer: Instant::now(),
counting: false,
current_frame: false,
}
}
}
impl ForceClose {
pub fn prompting(&mut self) {
self.button_text = "Are you sure?".to_string();
self.prompting = true;
self.interval = Instant::now();
pub fn prompt(&mut self, force_close_button_clicked: bool, sysinfo: &mut System) {
if force_close_button_clicked && !self.counting {
self.button_text = "Are you sure?".to_owned();
self.timer = Instant::now();
self.counting = true;
self.current_frame = true;
}
if self.counting && self.timer.elapsed() >= INTERVAL {
self.reset();
} else if force_close_button_clicked && !self.current_frame {
activate(sysinfo);
self.reset();
}
self.finish_current_frame();
}
fn reset(&mut self) {
*self = Self::default();
}
fn finish_current_frame(&mut self) {
if self.current_frame {
self.current_frame = false;
}
}
}
pub fn activate(sysinfo: &mut System) {
fn activate(sysinfo: &mut System) {
sysinfo.refresh_all();
sysinfo
.processes()
.iter()
.filter(|(_, p)| p.name() == ENHANCED || p.name() == LEGACY)
.filter(|(_, p)| p.name() == EXE_ENHANCED || p.name() == EXE_LEGACY)
.for_each(|(_, p)| {
p.kill();
});
+133 -58
View File
@@ -1,72 +1,147 @@
#![allow(clippy::zombie_processes)]
use crate::util::consts::{ENHANCED, LEGACY};
use std::{os::windows::process::CommandExt, path::Path, process::Command};
use crate::util::consts::game::{EXE_ENHANCED, EXE_LEGACY};
use std::{
path::Path,
time::{Duration, Instant},
};
use strum::{Display, EnumIter};
use sysinfo::System;
use windows::{
Win32::{
NetworkManagement::WindowsFirewall::{
INetFwPolicy2, INetFwRule, NET_FW_ACTION_BLOCK, NET_FW_IP_PROTOCOL_ANY,
NET_FW_RULE_DIR_IN, NET_FW_RULE_DIR_OUT, NetFwPolicy2, NetFwRule,
},
System::Com::{
CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx,
CoUninitialize,
},
},
core::BSTR,
};
const FILTER_NAME: &str = "[GTA Tools] Block all traffic for GTA V";
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
const FILTER_NAME_IN: &str = "[GTA Tools] Block all inbound traffic for GTA V";
const FILTER_NAME_OUT: &str = "[GTA Tools] Block all outbound traffic for GTA V";
const INTERVAL: Duration = Duration::from_secs(3);
#[derive(Clone, Copy, Debug, Display, PartialEq, Eq, EnumIter)]
pub enum BlockedStatus {
Blocked,
Failed,
Unblocked,
}
impl From<bool> for BlockedStatus {
fn from(value: bool) -> Self {
if value {
Self::Blocked
} else {
Self::Unblocked
}
}
}
#[derive(Debug)]
pub struct GameNetworking {
com_initialized: bool,
pub blocked_status: BlockedStatus,
timer: Instant,
counting: bool,
}
impl Default for GameNetworking {
fn default() -> Self {
Self {
blocked_status: Self::is_blocked().into(),
com_initialized: unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }.is_ok(),
timer: Instant::now(),
counting: false,
}
}
}
impl Drop for GameNetworking {
fn drop(&mut self) {
unsafe {
if self.com_initialized {
CoUninitialize();
}
}
}
}
impl GameNetworking {
pub fn block_all(&mut self, sysinfo: &mut System) {
let Some(exe_path) = get_game_exe_path(sysinfo) else {
self.blocked_status = BlockedStatus::Failed;
return;
};
let policy: INetFwPolicy2 =
unsafe { CoCreateInstance(&NetFwPolicy2, None, CLSCTX_INPROC_SERVER).unwrap() };
let rules = unsafe { policy.Rules().unwrap() };
let exe_path = BSTR::from(exe_path.to_string_lossy().to_string());
for filter in [
(FILTER_NAME_IN, NET_FW_RULE_DIR_IN),
(FILTER_NAME_OUT, NET_FW_RULE_DIR_OUT),
] {
let _ = unsafe { rules.Remove(&BSTR::from(filter.0)) };
unsafe {
let rule: INetFwRule =
CoCreateInstance(&NetFwRule, None, CLSCTX_INPROC_SERVER).unwrap();
rule.SetName(&BSTR::from(filter.0)).unwrap();
rule.SetApplicationName(&exe_path).unwrap();
rule.SetDirection(filter.1).unwrap();
rule.SetEnabled(true.into()).unwrap();
rule.SetAction(NET_FW_ACTION_BLOCK).unwrap();
rule.SetProtocol(NET_FW_IP_PROTOCOL_ANY.0).unwrap();
rules.Add(&rule).unwrap();
}
}
self.blocked_status = Self::is_blocked().into();
}
pub fn unblock_all(&mut self) {
let policy: INetFwPolicy2 =
unsafe { CoCreateInstance(&NetFwPolicy2, None, CLSCTX_INPROC_SERVER).unwrap() };
let rules = unsafe { policy.Rules().unwrap() };
unsafe { rules.Remove(&BSTR::from(FILTER_NAME_IN)).unwrap() };
unsafe { rules.Remove(&BSTR::from(FILTER_NAME_OUT)).unwrap() };
self.blocked_status = Self::is_blocked().into();
}
fn is_blocked() -> bool {
let policy: INetFwPolicy2 =
unsafe { CoCreateInstance(&NetFwPolicy2, None, CLSCTX_INPROC_SERVER).unwrap() };
let rules = unsafe { policy.Rules().unwrap() };
let in_rule_exists = unsafe { rules.Item(&BSTR::from(FILTER_NAME_IN)).is_ok() };
let out_rule_exists = unsafe { rules.Item(&BSTR::from(FILTER_NAME_OUT)).is_ok() };
in_rule_exists || out_rule_exists
}
pub fn if_failed_return_to_unblocked(&mut self) {
if self.blocked_status == BlockedStatus::Failed && !self.counting {
self.counting = true;
self.timer = Instant::now();
}
if self.blocked_status == BlockedStatus::Failed
&& self.counting
&& self.timer.elapsed() >= INTERVAL
{
self.counting = false;
self.blocked_status = BlockedStatus::Unblocked;
}
}
}
fn get_game_exe_path(sysinfo: &mut System) -> Option<&Path> {
sysinfo.refresh_all();
if let Some((_, process)) = sysinfo
.processes()
.iter()
.find(|(_, p)| p.name() == ENHANCED || p.name() == LEGACY)
.find(|(_, p)| p.name() == EXE_ENHANCED || p.name() == EXE_LEGACY)
{
process.exe()
} else {
None
}
}
pub fn block_all(sysinfo: &mut System) {
let Some(exe_path) = get_game_exe_path(sysinfo) else {
return;
};
let exe_path = exe_path.display().to_string();
Command::new("netsh")
.args([
"advfirewall",
"firewall",
"add",
"rule",
&format!("name={FILTER_NAME}"),
"dir=out",
"action=block",
"protocol=ANY",
&format!("program={exe_path}"),
])
.creation_flags(CREATE_NO_WINDOW)
.spawn()
.unwrap();
Command::new("netsh")
.args([
"advfirewall",
"firewall",
"add",
"rule",
&format!("name={FILTER_NAME}"),
"dir=in",
"action=block",
"protocol=ANY",
&format!("program={exe_path}"),
])
.creation_flags(CREATE_NO_WINDOW)
.spawn()
.unwrap();
}
pub fn unblock_all() {
Command::new("netsh")
.args([
"advfirewall",
"firewall",
"delete",
"rule",
&format!("name={FILTER_NAME}"),
])
.creation_flags(CREATE_NO_WINDOW)
.spawn()
.unwrap();
}
+5 -13
View File
@@ -1,26 +1,18 @@
use serde::{Deserialize, Serialize};
use std::{fmt::Display, path::PathBuf, process::Command};
use std::{path::PathBuf, process::Command};
use strum::{Display, EnumIter};
use winreg::{RegKey, enums::HKEY_LOCAL_MACHINE};
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Clone, Copy, Default, Debug, Display, PartialEq, Eq, Serialize, Deserialize, EnumIter)]
pub enum Platform {
#[default]
Steam,
#[strum(to_string = "Rockstar Games")]
Rockstar,
#[strum(to_string = "Epic Games")]
Epic,
}
impl Display for Platform {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let x = match self {
Self::Steam => "Steam",
Self::Rockstar => "Rockstar Games",
Self::Epic => "Epic Games",
};
write!(f, "{x}")
}
}
#[derive(Debug, Default)]
pub struct Launch {
pub selected: Platform,
-409
View File
@@ -1,409 +0,0 @@
use crate::{
features::{
self,
anti_afk::AntiAfk,
empty_session::EmptySession,
force_close::ForceClose,
launch::{Launch, Platform},
},
util::{
self,
consts::{ENHANCED, GTA_WINDOW_TITLE, LEGACY},
elevation,
},
};
use eframe::egui;
use serde::{Deserialize, Serialize};
use std::{
fs::{self, File},
io::Write,
path::PathBuf,
sync::LazyLock,
time::{Duration, Instant},
};
use sysinfo::System;
use windows::Win32::Foundation::HANDLE;
const THEME: catppuccin_egui::Theme = catppuccin_egui::MOCHA;
const WINDOW_SIZE: [f32; 2] = [240.0, 240.0];
static CONFIG_PATH: LazyLock<PathBuf> = LazyLock::new(|| {
dirs::config_local_dir()
.unwrap()
.join("GTA Tools")
.join("config.json")
});
#[derive(Serialize, Deserialize)]
struct PersistentState {
launcher: Platform,
}
#[derive(Debug, Default, PartialEq, Eq)]
pub enum Stage {
#[default]
Main,
About,
}
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug)]
pub struct App {
stage: Stage,
closing: bool,
debug: bool,
initialized: bool,
elevated: bool,
current_frame: bool,
pub sysinfo: System,
pub game_handle: HANDLE,
launch: Launch,
force_close: ForceClose,
empty_session: EmptySession,
anti_afk: AntiAfk,
}
impl Default for App {
fn default() -> Self {
Self {
stage: Stage::default(),
closing: false,
initialized: false,
debug: false,
elevated: elevation::is_elevated(),
current_frame: false,
sysinfo: System::new_all(),
game_handle: HANDLE::default(),
launch: Launch::default(),
force_close: ForceClose::default(),
empty_session: EmptySession::default(),
anti_afk: AntiAfk::default(),
}
}
}
impl eframe::App for App {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
if !self.initialized {
catppuccin_egui::set_theme(ctx, THEME);
egui_extras::install_image_loaders(ctx);
if let Ok(config) = fs::read_to_string(CONFIG_PATH.as_path()) {
if let Ok(persistent_state) = serde_json::from_str::<PersistentState>(&config) {
self.launch.selected = persistent_state.launcher;
}
}
ctx.style_mut(|style| style.spacing.item_spacing = egui::vec2(4.0, 4.0));
self.initialized = true;
}
self.run_timers();
egui::TopBottomPanel::bottom("bottom_panel")
.exact_height(25.0)
.show(ctx, |ui| {
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
ui.selectable_value(&mut self.stage, Stage::Main, "Main");
ui.selectable_value(&mut self.stage, Stage::About, "About");
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let button = ui
.add_enabled(!self.elevated, egui::Button::new("Elevate"))
.on_hover_text("Relaunch ourselves as administrator.")
.on_disabled_hover_text("We are already running elevated.");
if button.clicked() {
elevation::elevate(&mut self.closing);
}
});
});
});
egui::CentralPanel::default().show(ctx, |ui| match self.stage {
Stage::Main => {
self.header(ui, "Game");
self.show_game(ctx, ui);
self.header(ui, "Session");
self.show_session(ctx, ui);
self.header(ui, "Network");
self.show_network(ctx, ui);
}
Stage::About => self.show_about(ctx, ui),
});
if check_debug_keycombo_pressed(ctx) {
self.debug = !self.debug;
}
if check_debug_viewport_close_button_pressed(ctx) {
self.debug = false;
}
if self.debug {
let main_rect = ctx.input(|i| {
i.viewport()
.clone()
.outer_rect
.unwrap_or(egui::Rect::EVERYTHING)
});
let position = [main_rect.right(), main_rect.min.y];
ctx.show_viewport_immediate(
egui::ViewportId::from_hash_of("debug_viewport"),
egui::ViewportBuilder::default()
.with_title("GTA Tools Debug")
.with_minimize_button(false)
.with_maximize_button(false)
.with_inner_size(WINDOW_SIZE)
.with_position(position)
.with_icon(load_icon()),
|ctx, _class| {
if check_debug_keycombo_pressed(ctx) {
self.debug = !self.debug;
}
egui::CentralPanel::default().show(ctx, |ui| {
egui::ScrollArea::both()
.auto_shrink([false, false])
.show(ui, |ui| {
self.show_debug(ctx, ui);
});
});
},
);
}
ctx.request_repaint_after(Duration::from_millis(100));
if self.closing {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
}
}
impl App {
#[allow(clippy::unused_self)]
fn header(&self, ui: &mut egui::Ui, text: &str) {
ui.horizontal(|ui| {
ui.label(text);
ui.add(egui::Separator::default().horizontal());
});
}
fn show_game(&mut self, _ctx: &egui::Context, ui: &mut egui::Ui) {
ui.horizontal(|ui| {
if ui.button("Launch").clicked() {
features::launch::launch(&self.launch.selected);
};
egui::ComboBox::from_label("")
.selected_text(self.launch.selected.to_string())
.width(120.0)
.show_ui(ui, |ui| {
ui.selectable_value(
&mut self.launch.selected,
Platform::Steam,
Platform::Steam.to_string(),
);
ui.selectable_value(
&mut self.launch.selected,
Platform::Rockstar,
Platform::Rockstar.to_string(),
);
ui.selectable_value(
&mut self.launch.selected,
Platform::Epic,
Platform::Epic.to_string(),
);
});
});
let force_close_button = ui.add_sized(
[104.0, 0.0],
egui::Button::new(&self.force_close.button_text),
);
if force_close_button.clicked() && !self.force_close.prompting {
self.force_close.prompting();
self.current_frame = true;
};
if self.force_close.prompting
&& self.force_close.interval.elapsed() <= Duration::from_secs(3)
{
if force_close_button.clicked() && !self.current_frame {
features::force_close::activate(&mut self.sysinfo);
self.force_close = ForceClose::default();
}
} else {
self.force_close = ForceClose::default();
}
if self.current_frame {
self.current_frame = false;
}
}
fn show_session(&mut self, _ctx: &egui::Context, ui: &mut egui::Ui) {
ui.add_enabled_ui(!self.empty_session.disabled, |ui| {
ui.horizontal(|ui| {
if ui.button("Empty current session").clicked() {
self.empty_session.interval = Instant::now();
self.empty_session.disabled = true;
features::empty_session::activate(self);
}
ui.label(&self.empty_session.countdown.i_string);
});
});
ui.horizontal(|ui| {
ui.checkbox(&mut self.anti_afk.enabled, "Anti AFK")
.on_hover_text("You should be tabbed in\nfor this to work.");
if self.anti_afk.enabled {
ui.add_space(8.0);
ui.add_enabled_ui(false, |ui| {
ui.label(if util::is_window_focused(GTA_WINDOW_TITLE) {
"GTA is focused."
} else {
"GTA is not focused!"
})
});
}
});
if self.anti_afk.enabled && self.anti_afk.interval.elapsed() >= features::anti_afk::INTERVAL
{
self.anti_afk.activate();
}
}
fn show_network(&mut self, _ctx: &egui::Context, ui: &mut egui::Ui) {
egui::Frame::new()
.inner_margin(egui::vec2(4.0, 4.0))
.stroke(egui::Stroke::new(1.0, THEME.overlay1))
.show(ui, |ui| {
let response = ui.add_enabled_ui(self.elevated, |ui| {
let label = ui.label("Game's network access");
ui.horizontal(|ui| {
let available_width = label.rect.width();
let spacing = ui.spacing().item_spacing.x;
let button_width = (available_width - spacing) / 2.0;
if ui
.add_sized([button_width, 18.0], egui::Button::new("Block"))
.clicked()
{
features::game_networking::block_all(&mut self.sysinfo);
};
if ui
.add_sized([button_width, 18.0], egui::Button::new("Unblock"))
.clicked()
{
features::game_networking::unblock_all();
};
});
});
response.response.on_disabled_hover_text(
"This requires administrator.\nUse the Elevate button.",
);
});
}
#[allow(clippy::unused_self)]
fn show_about(&self, _ctx: &egui::Context, ui: &mut egui::Ui) {
ui.with_layout(egui::Layout::bottom_up(egui::Align::Center), |ui| {
ui.horizontal(|ui| {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 0.0;
ui.label("with love from ");
ui.hyperlink_to("futile", "http://futile.eu");
});
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.label(format!(
"v{} {}",
env!("CARGO_PKG_VERSION"),
if cfg!(debug_assertions) { "(dev)" } else { "" }
));
});
});
ui.add(egui::Image::new(egui::include_image!("../assets/icon.png")));
});
}
fn show_debug(&mut self, _ctx: &egui::Context, ui: &mut egui::Ui) {
ui.collapsing("times", |ui| {
ui.label(format!(
"anti afk timer: {}",
self.anti_afk.interval.elapsed().as_secs()
))
});
ui.collapsing("sysinfo", |ui| {
if ui.button("refresh all").clicked() {
self.sysinfo.refresh_all();
}
let pid = self
.sysinfo
.processes()
.iter()
.find(|(_, p)| p.name() == ENHANCED || p.name() == LEGACY)
.map_or_else(
|| "no pid found!".to_string(),
|(pid, _)| pid.as_u32().to_string(),
);
ui.label(format!("gta pid: {pid}"));
});
ui.collapsing("app state", |ui| ui.label(format!("{self:#?}")));
}
fn run_timers(&mut self) {
if self.empty_session.disabled {
self.empty_session.countdown.count();
} else {
self.empty_session.countdown.reset();
}
if self.empty_session.interval.elapsed() >= features::empty_session::INTERVAL {
features::empty_session::deactivate(self);
self.empty_session.disabled = false;
}
}
}
impl Drop for App {
fn drop(&mut self) {
// save any persistent state to config file
let persistent_state = PersistentState {
launcher: self.launch.selected,
};
let config_path = CONFIG_PATH.as_path();
let config_path_parent = config_path.parent().unwrap();
if !config_path_parent.exists() {
fs::create_dir(config_path_parent).unwrap();
}
let mut config_file = File::create(config_path).unwrap();
let json = serde_json::to_string_pretty(&persistent_state).unwrap();
config_file.write_all(json.as_bytes()).unwrap();
// make sure we are not suspending game
features::empty_session::deactivate(self);
}
}
fn check_debug_keycombo_pressed(ctx: &egui::Context) -> bool {
ctx.input(|i| i.modifiers.all() && i.key_pressed(egui::Key::D))
}
fn check_debug_viewport_close_button_pressed(ctx: &egui::Context) -> bool {
ctx.input(|i| {
i.raw
.viewports
.get(&egui::ViewportId::from_hash_of("debug_viewport"))
.filter(|vp| vp.close_requested())
.is_some()
})
}
fn load_icon() -> eframe::egui::IconData {
let icon = include_bytes!("../assets/icon.png");
let image = image::load_from_memory(icon).unwrap().into_rgba8();
let (width, height) = image.dimensions();
eframe::egui::IconData {
rgba: image.into_raw(),
width,
height,
}
}
pub fn run() {
let options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_resizable(false)
.with_maximize_button(false)
.with_inner_size(WINDOW_SIZE)
.with_icon(load_icon()),
centered: true,
..Default::default()
};
eframe::run_native(
"GTA Tools",
options,
Box::new(|_cc| Ok(Box::<App>::default())),
)
.unwrap();
}
+258
View File
@@ -0,0 +1,258 @@
use crate::{
features,
gui::{settings::Settings, tools},
util::{consts::game::WINDOW_TITLE, meta::Meta, persistent_state::PersistentState, win},
};
use eframe::egui;
use std::time::{Duration, Instant};
use strum::{Display, EnumIter};
pub const WINDOW_SIZE: [f32; 2] = [240.0, 240.0];
#[derive(Clone, Copy, Debug, Default, Display, PartialEq, Eq, EnumIter)]
enum Stage {
#[default]
Main,
Settings,
About,
}
#[derive(Debug)]
pub struct Flags {
pub elevated: bool,
pub debug: bool,
closing: bool,
}
impl Default for Flags {
fn default() -> Self {
Self {
elevated: win::is_elevated(),
debug: false,
closing: false,
}
}
}
#[derive(Debug, Default)]
pub struct App {
pub meta: Meta,
pub settings: Settings,
stage: Stage,
pub flags: Flags,
pub sysinfo: sysinfo::System,
game_handle: windows::Win32::Foundation::HANDLE,
pub anti_afk: features::anti_afk::AntiAfk,
empty_session: features::empty_session::EmptySession,
force_close: features::force_close::ForceClose,
pub game_networking: features::game_networking::GameNetworking,
pub launch: features::launch::Launch,
}
impl eframe::App for App {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
ctx.request_repaint_after(Duration::from_millis(100));
self.empty_session.run_timers(&mut self.game_handle);
egui::TopBottomPanel::bottom("bottom_panel")
.exact_height(25.0)
.show(ctx, |ui| {
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
tools::build_menu::<Stage>(ui, &mut self.stage);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let button = ui
.add_enabled(!self.flags.elevated, egui::Button::new("Elevate"))
.on_hover_text("Relaunch ourselves as administrator.")
.on_disabled_hover_text("We are already running elevated.");
if button.clicked() {
win::elevate(win::ElevationExitMethod::Gentle(&mut self.flags.closing));
}
});
});
});
egui::CentralPanel::default().show(ctx, |ui| {
egui::ScrollArea::vertical()
.auto_shrink([false, true])
.show(ui, |ui| match self.stage {
Stage::Main => self.show_main_stage(ctx, ui),
Stage::Settings => self.show_settings_stage(ctx, ui),
Stage::About => self.show_about_stage(ctx, ui),
});
});
if tools::debug_keycombo_pressed(ctx) || tools::debug_viewport_close_pressed(ctx) {
self.flags.debug = !self.flags.debug;
}
if self.flags.debug {
self.show_debug_viewport(ctx);
}
if self.flags.closing {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
}
}
impl App {
fn show_game_section(&mut self, _ctx: &egui::Context, ui: &mut egui::Ui) {
tools::header(ui, "Game");
ui.horizontal(|ui| {
if ui.button("Launch").clicked() {
features::launch::launch(&self.launch.selected);
}
egui::ComboBox::from_id_salt("Launch")
.selected_text(self.launch.selected.to_string())
.width(120.0)
.show_ui(ui, |ui| {
tools::build_menu(ui, &mut self.launch.selected);
});
});
let force_close_button = ui.add_sized(
[104.0, 0.0],
egui::Button::new(&self.force_close.button_text),
);
self.force_close
.prompt(force_close_button.clicked(), &mut self.sysinfo);
}
fn show_session_section(&mut self, _ctx: &egui::Context, ui: &mut egui::Ui) {
tools::header(ui, "Session");
ui.add_enabled_ui(!self.empty_session.disabled, |ui| {
ui.horizontal(|ui| {
if ui.button("Empty current session").clicked() {
self.empty_session.interval = Instant::now();
self.empty_session.disabled = true;
features::empty_session::activate(&mut self.game_handle, &mut self.sysinfo);
}
ui.label(&self.empty_session.countdown.i_string);
});
});
ui.horizontal(|ui| {
ui.checkbox(&mut self.anti_afk.enabled, "Anti AFK")
.on_hover_text("You should be tabbed in\nfor this to work.");
if self.anti_afk.enabled {
ui.add_space(8.0);
ui.add_enabled_ui(false, |ui| {
ui.label(if win::is_window_focused(WINDOW_TITLE) {
"GTA is focused."
} else {
"GTA is not focused!"
})
});
}
});
if self.anti_afk.can_activate() && self.anti_afk.should_activate() {
self.anti_afk.activate();
}
}
fn show_network_section(&mut self, _ctx: &egui::Context, ui: &mut egui::Ui) {
tools::header(ui, "Network");
egui::Frame::new()
.outer_margin(egui::vec2(0.0, -2.0))
.show(ui, |ui| {
let response = ui.add_enabled_ui(self.flags.elevated, |ui| {
let label = ui.horizontal(|ui| {
let label = ui.label("Game's network access");
ui.add_space(1.0);
ui.add(
egui::Image::new(egui::include_image!("../../assets/circle.svg"))
.max_size([4.0, 4.0].into())
.tint(self.game_networking.blocked_status.to_color32()),
)
.on_hover_text("This turns yellow if GTA Tools\ncannot find your game.");
self.game_networking.if_failed_return_to_unblocked();
label
});
ui.horizontal(|ui| {
let available_width = label.inner.rect.width();
let spacing = ui.spacing().item_spacing.x;
let button_width = (available_width - spacing) / 2.0;
if ui
.add_sized([button_width, 18.0], egui::Button::new("Block"))
.clicked()
{
self.game_networking.block_all(&mut self.sysinfo);
}
if ui
.add_sized([button_width, 18.0], egui::Button::new("Unblock"))
.clicked()
{
self.game_networking.unblock_all();
}
});
});
response.response.on_disabled_hover_text(
"This requires administrator.\nUse the Elevate button.",
);
});
}
fn show_main_stage(&mut self, ctx: &egui::Context, ui: &mut egui::Ui) {
self.show_game_section(ctx, ui);
self.show_session_section(ctx, ui);
self.show_network_section(ctx, ui);
}
fn show_settings_stage(&mut self, ctx: &egui::Context, ui: &mut egui::Ui) {
ui.horizontal(|ui| {
let selection = self.settings.theme;
ui.label("Theme");
egui::ComboBox::from_id_salt("Theme")
.selected_text(self.settings.theme.to_string())
.show_ui(ui, |ui| {
tools::build_menu(ui, &mut self.settings.theme);
});
if selection != self.settings.theme {
catppuccin_egui::set_theme(ctx, self.settings.theme.into());
}
});
ui.checkbox(&mut self.settings.start_elevated, "Always start elevated");
}
fn show_about_stage(&self, _ctx: &egui::Context, ui: &mut egui::Ui) {
ui.with_layout(egui::Layout::bottom_up(egui::Align::Center), |ui| {
ui.horizontal(|ui| {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 0.0;
ui.label("with ");
ui.hyperlink_to("", "https://codeberg.org/futile/gta-tools");
ui.label(" from ");
ui.hyperlink_to("futile", "http://futile.eu");
});
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.label(format!(
"v{} {}",
self.meta.current_version,
if cfg!(debug_assertions) { "(dev)" } else { "" }
));
let button = ui.add_enabled_ui(self.meta.newer_version_available, |ui| {
ui.style_mut().spacing.button_padding = egui::Vec2::new(3.0, 0.0);
ui.button("")
.on_disabled_hover_text("Already up to date.")
.on_hover_text(format!(
"New version available! ({})",
self.meta.latest_release.version
))
});
if button.inner.clicked() {
open::that(&self.meta.latest_release.download_url).unwrap();
}
});
});
ui.add(egui::Image::new(egui::include_image!(
"../../assets/icon.png"
)));
});
}
}
impl Drop for App {
fn drop(&mut self) {
// save any persistent state to config file
PersistentState {
launcher: self.launch.selected,
settings: self.settings.clone(),
}
.set();
// make sure we are not suspending game
features::empty_session::deactivate(&mut self.game_handle);
}
}
+22
View File
@@ -0,0 +1,22 @@
use crate::features::game_networking::BlockedStatus;
use eframe::egui;
pub const RED: egui::Color32 = egui::Color32::from_rgb(255, 96, 96);
pub const YELLOW: egui::Color32 = egui::Color32::from_rgb(255, 255, 96);
pub const GREEN: egui::Color32 = egui::Color32::from_rgb(96, 255, 96);
impl From<BlockedStatus> for egui::Color32 {
fn from(value: BlockedStatus) -> Self {
match value {
BlockedStatus::Blocked => RED,
BlockedStatus::Failed => YELLOW,
BlockedStatus::Unblocked => GREEN,
}
}
}
impl BlockedStatus {
pub fn to_color32(self) -> egui::Color32 {
self.into()
}
}
+94
View File
@@ -0,0 +1,94 @@
use crate::{
gui::{
app::{App, WINDOW_SIZE},
tools,
},
util::consts::{
APP_STORAGE_PATH,
game::{EXE_ENHANCED, EXE_LEGACY},
},
};
use eframe::egui;
impl App {
pub fn show_debug_viewport(&mut self, ctx: &egui::Context) {
let main = ctx.input(|i| i.viewport().outer_rect.unwrap_or(egui::Rect::EVERYTHING));
let builder = egui::ViewportBuilder::default()
.with_title("GTA Tools Debug")
.with_minimize_button(false)
.with_maximize_button(false)
.with_inner_size(WINDOW_SIZE)
.with_position([main.right() - 12.0, main.min.y])
.with_icon(tools::load_icon());
ctx.show_viewport_immediate(
egui::ViewportId::from_hash_of("debug_viewport"),
builder,
|ctx, _class| {
if tools::debug_keycombo_pressed(ctx) {
self.flags.debug = !self.flags.debug;
}
egui::CentralPanel::default().show(ctx, |ui| {
egui::ScrollArea::both()
.auto_shrink([false, true])
.show(ui, |ui| {
ui.collapsing("misc", |ui| {
if ui.button("open storage path").clicked() {
open::that_detached(APP_STORAGE_PATH.as_path()).unwrap();
}
ui.checkbox(
&mut self.meta.newer_version_available,
"spoof new version available",
)
.on_hover_text("(this could already be checked if\nthere actually IS a new version)");
ui.scope(|ui| {
use windows::Win32::UI::WindowsAndMessaging::{GetForegroundWindow, GetWindowTextW};
let mut buffer = [0; 512];
let current_title = unsafe {
let hwnd = GetForegroundWindow();
let length = GetWindowTextW(hwnd, &mut buffer);
String::from_utf16_lossy(&buffer[..length as usize])
};
ui.label(format!("focused: \"{current_title}\""));
});
ui.horizontal(|ui| {
ui.label("blocked_status");
egui::ComboBox::from_id_salt("blocked_status")
.selected_text(&self.game_networking.blocked_status.to_string())
.show_ui(ui, |ui| {
tools::build_menu(ui, &mut self.game_networking.blocked_status);
});
});
});
ui.collapsing("anti afk", |ui| {
ui.label(format!(
"timer: {}",
self.anti_afk.interval.elapsed().as_secs()
));
ui.label(format!(
"can activate: {}",
self.anti_afk.can_activate()
));
});
ui.collapsing("sysinfo", |ui| {
if ui.button("refresh all").clicked() {
self.sysinfo.refresh_all();
}
let pid = self
.sysinfo
.processes()
.iter()
.find(|(_, p)| p.name() == EXE_ENHANCED || p.name() == EXE_LEGACY)
.map_or_else(
|| "no pid found!".to_owned(),
|(pid, _)| pid.as_u32().to_string(),
);
ui.label(format!("gta pid: {pid}"));
});
ui.collapsing("app state", |ui| ui.label(format!("{self:#?}")));
});
});
},
);
}
}
+6
View File
@@ -0,0 +1,6 @@
mod app;
mod colours;
mod debug;
pub mod run;
pub mod settings;
mod tools;
+77
View File
@@ -0,0 +1,77 @@
use crate::{
gui::{
app::{App, WINDOW_SIZE},
tools,
},
util::{self, consts::APP_STORAGE_PATH, persistent_state::PersistentState},
};
use eframe::egui;
use std::{fs::File, io::Write};
fn panic_hook(panic_info: &std::panic::PanicHookInfo<'_>) {
let log_path = APP_STORAGE_PATH.join("panic.log");
let mut file = File::options()
.create(true)
.append(true)
.open(log_path)
.unwrap();
let timestamp = chrono::Local::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, false);
let backtrace = std::backtrace::Backtrace::force_capture();
let message = format!("[{timestamp}]\n{panic_info}\nstack backtrace:\n{backtrace}\n");
file.write_all(message.as_bytes()).unwrap();
}
fn app_creator(
cc: &eframe::CreationContext<'_>,
) -> Result<Box<dyn eframe::App>, Box<dyn std::error::Error + Send + Sync>> {
// use our own panic hook which logs all panics to a file
std::panic::set_hook(Box::new(panic_hook));
// initialize App early to modify some things before returning it
let mut app = Box::<App>::default();
// load previously selected launch platform & settings from persistent state
if let Some(persistent_state) = PersistentState::get() {
app.launch.selected = persistent_state.launcher;
app.settings = persistent_state.settings;
}
// check if we're elevated. if not, and the user wants an elevated launch - relaunch elevated
if !app.flags.elevated && app.settings.start_elevated {
util::win::elevate(util::win::ElevationExitMethod::Forced);
}
// refresh sysinfo because it initializes with nothing
app.sysinfo.refresh_all();
// enable image loading support in egui
egui_extras::install_image_loaders(&cc.egui_ctx);
// set our initial theme, from earlier loaded settings
catppuccin_egui::set_theme(&cc.egui_ctx, app.settings.theme.into());
// apply some global styling that we like
cc.egui_ctx.style_mut(|style| {
style.spacing.item_spacing = egui::vec2(4.0, 4.0);
style.interaction.selectable_labels = false;
});
// load any extra fonts that we need
let mut fonts = egui::FontDefinitions::default();
fonts.font_data.insert(
"Ubuntu-Regular".to_owned(),
egui::FontData::from_static(include_bytes!("../../assets/Ubuntu-Regular.ttf")).into(),
);
fonts.families.insert(
egui::FontFamily::Name("Ubuntu-Regular".into()),
vec!["Ubuntu-Regular".to_owned()],
);
cc.egui_ctx.set_fonts(fonts);
// finally return the App
Ok(app)
}
pub fn run() {
let options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_resizable(false)
.with_maximize_button(false)
.with_inner_size(WINDOW_SIZE)
.with_icon(tools::load_icon()),
centered: true,
..Default::default()
};
eframe::run_native("GTA Tools", options, Box::new(app_creator)).unwrap();
}
+40
View File
@@ -0,0 +1,40 @@
use serde::{Deserialize, Serialize};
use strum::{Display, EnumIter};
#[derive(Clone, Copy, Debug, Display, PartialEq, Eq, Serialize, Deserialize, EnumIter)]
pub enum Theme {
#[strum(to_string = "Catppuccin Latte")]
CatppuccinLatte,
#[strum(to_string = "Catppuccin Frappe")]
CatppuccinFrappe,
#[strum(to_string = "Catppuccin Macchiato")]
CatppuccinMacchiato,
#[strum(to_string = "Catppuccin Mocha")]
CatppuccinMocha,
}
impl From<Theme> for catppuccin_egui::Theme {
fn from(val: Theme) -> Self {
match val {
Theme::CatppuccinLatte => catppuccin_egui::LATTE,
Theme::CatppuccinFrappe => catppuccin_egui::FRAPPE,
Theme::CatppuccinMacchiato => catppuccin_egui::MACCHIATO,
Theme::CatppuccinMocha => catppuccin_egui::MOCHA,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Settings {
pub theme: Theme,
pub start_elevated: bool,
}
impl Default for Settings {
fn default() -> Self {
Self {
theme: Theme::CatppuccinMocha,
start_elevated: false,
}
}
}
+45
View File
@@ -0,0 +1,45 @@
use eframe::egui;
pub fn load_icon() -> egui::IconData {
let icon = include_bytes!("../../assets/icon.png");
let image = image::load_from_memory(icon).unwrap().into_rgba8();
let (width, height) = image.dimensions();
egui::IconData {
rgba: image.into_raw(),
width,
height,
}
}
pub fn header(ui: &mut egui::Ui, text: &str) {
ui.horizontal(|ui| {
ui.label(egui::RichText::new(text).font(egui::FontId::new(
12.5,
egui::FontFamily::Name("Ubuntu-Regular".into()),
)));
ui.add(egui::Separator::default().horizontal());
});
}
pub fn build_menu<E>(ui: &mut egui::Ui, current_value: &mut E)
where
E: strum::IntoEnumIterator + std::fmt::Display + std::cmp::PartialEq + Copy,
{
E::iter().for_each(|variant| {
ui.selectable_value(current_value, variant, variant.to_string());
});
}
pub fn debug_keycombo_pressed(ctx: &egui::Context) -> bool {
ctx.input(|i| i.modifiers.all() && i.key_pressed(egui::Key::D))
}
pub fn debug_viewport_close_pressed(ctx: &egui::Context) -> bool {
ctx.input(|i| {
i.raw
.viewports
.get(&egui::ViewportId::from_hash_of("debug_viewport"))
.filter(|vp| vp.close_requested())
.is_some()
})
}
+1 -1
View File
@@ -5,5 +5,5 @@ mod gui;
mod util;
fn main() {
gui::run();
gui::run::run();
}
+35
View File
@@ -0,0 +1,35 @@
use semver::Version;
const APP_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"));
const CODEBERG_ENDPOINT_ROOT: &str = "https://codeberg.org/api/v1";
#[derive(Debug)]
pub struct Release {
pub version: Version,
pub download_url: String,
}
impl Default for Release {
fn default() -> Self {
Self {
version: Version::parse(env!("CARGO_PKG_VERSION")).unwrap(),
download_url: String::new(),
}
}
}
pub fn get_latest_release() -> Option<Release> {
let request_url = format!("{CODEBERG_ENDPOINT_ROOT}/repos/futile/gta-tools/releases/latest");
let ureq: ureq::Agent = ureq::Agent::config_builder()
.user_agent(APP_USER_AGENT)
.build()
.into();
let mut response = ureq.get(request_url).call().ok()?;
let json = response.body_mut().read_json::<serde_json::Value>().ok()?;
let tag_name = json["tag_name"].as_str()?;
let browser_download_url = json["assets"][0]["browser_download_url"].as_str()?;
Some(Release {
version: Version::parse(tag_name).expect("expected a valid semver pattern"),
download_url: String::from(browser_download_url),
})
}
+9 -3
View File
@@ -1,4 +1,10 @@
pub const ENHANCED: &str = "GTA5_Enhanced.exe";
pub const LEGACY: &str = "GTA5.exe";
use std::{path::PathBuf, sync::LazyLock};
pub const GTA_WINDOW_TITLE: &str = "Grand Theft Auto V";
pub static APP_STORAGE_PATH: LazyLock<PathBuf> =
LazyLock::new(|| dirs::config_local_dir().unwrap().join("GTA Tools"));
pub mod game {
pub const EXE_ENHANCED: &str = "GTA5_Enhanced.exe";
pub const EXE_LEGACY: &str = "GTA5.exe";
pub const WINDOW_TITLE: &str = "Grand Theft Auto V";
}
+5 -5
View File
@@ -2,11 +2,11 @@ use std::time::{Duration, Instant};
#[derive(Debug)]
pub struct Countdown {
pub i: u64,
pub i_original: u64,
i: u64,
i_original: u64,
pub i_string: String,
pub interval: Instant,
pub first_count: bool,
interval: Instant,
first_count: bool,
}
impl Countdown {
@@ -36,6 +36,6 @@ impl Countdown {
self.i_string = self.i.to_string();
if self.i == 0 {
self.reset();
};
}
}
}
-45
View File
@@ -1,45 +0,0 @@
use windows::{
Win32::Foundation::{CloseHandle, HANDLE},
Win32::Security::{GetTokenInformation, TOKEN_ELEVATION, TOKEN_QUERY, TokenElevation},
Win32::System::Threading::{GetCurrentProcess, OpenProcessToken},
Win32::UI::{Shell::ShellExecuteW, WindowsAndMessaging::SW_HIDE},
core::{HSTRING, PCWSTR},
};
pub fn elevate(closing: &mut bool) {
let exe = std::env::current_exe().unwrap();
unsafe {
ShellExecuteW(
None,
&HSTRING::from("runas"),
&HSTRING::from(exe.as_path()),
PCWSTR::null(),
PCWSTR::null(),
SW_HIDE,
);
}
*closing = true;
}
pub fn is_elevated() -> bool {
unsafe {
let mut token: HANDLE = HANDLE::default();
if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token).is_ok() {
let mut elevation = TOKEN_ELEVATION::default();
let size = u32::try_from(std::mem::size_of::<TOKEN_ELEVATION>()).unwrap();
let mut ret_size = size;
let result = GetTokenInformation(
token,
TokenElevation,
Some((&raw mut elevation).cast()),
size,
&mut ret_size,
);
CloseHandle(token).unwrap();
if result.is_ok() && elevation.TokenIsElevated != 0 {
return true;
}
}
false
}
}
+25
View File
@@ -0,0 +1,25 @@
use crate::util::codeberg;
use semver::Version;
#[derive(Debug)]
pub struct Meta {
pub current_version: Version,
pub latest_release: codeberg::Release,
pub newer_version_available: bool,
}
impl Default for Meta {
fn default() -> Self {
let current_version = Version::parse(env!("CARGO_PKG_VERSION")).unwrap();
let latest_release = codeberg::get_latest_release().unwrap_or_default();
let newer_version_available = matches!(
&current_version.cmp_precedence(&latest_release.version),
std::cmp::Ordering::Less
);
Self {
current_version,
latest_release,
newer_version_available,
}
}
}
+4 -20
View File
@@ -1,22 +1,6 @@
mod codeberg;
pub mod consts;
pub mod countdown;
pub mod elevation;
use windows::Win32::UI::{
Input::KeyboardAndMouse::GetAsyncKeyState,
WindowsAndMessaging::{GetForegroundWindow, GetWindowTextW},
};
pub fn is_window_focused(target_title: &str) -> bool {
unsafe {
let hwnd = GetForegroundWindow();
let mut buffer: [u16; 512] = [0; 512];
let length = GetWindowTextW(hwnd, &mut buffer);
let current_title = String::from_utf16_lossy(&buffer[..length as usize]);
current_title == target_title
}
}
pub fn is_key_pressed(key: i32) -> bool {
unsafe { (GetAsyncKeyState(key) as i32 & 0x8000) != 0 }
}
pub mod meta;
pub mod persistent_state;
pub mod win;
+35
View File
@@ -0,0 +1,35 @@
use crate::{features::launch::Platform, gui::settings::Settings, util::consts::APP_STORAGE_PATH};
use serde::{Deserialize, Serialize};
use std::{
fs::{self, File},
io::Write,
path::PathBuf,
sync::LazyLock,
};
static CONFIG_PATH: LazyLock<PathBuf> = LazyLock::new(|| APP_STORAGE_PATH.join("config.json"));
#[derive(Serialize, Deserialize)]
pub struct PersistentState {
pub launcher: Platform,
pub settings: Settings,
}
impl PersistentState {
pub fn get() -> Option<Self> {
fs::read_to_string(CONFIG_PATH.as_path())
.ok()
.and_then(|config| serde_json::from_str::<Self>(&config).ok())
}
pub fn set(&self) {
let config_path = CONFIG_PATH.as_path();
let config_path_parent = config_path.parent().unwrap();
if !config_path_parent.exists() {
fs::create_dir(config_path_parent).unwrap();
}
let mut config_file = File::create(config_path).unwrap();
let json = serde_json::to_string_pretty(&self).unwrap();
config_file.write_all(json.as_bytes()).unwrap();
}
}
+85
View File
@@ -0,0 +1,85 @@
use windows::{
Win32::{
Foundation::{CloseHandle, HANDLE},
Security::{GetTokenInformation, TOKEN_ELEVATION, TOKEN_QUERY, TokenElevation},
System::Threading::{GetCurrentProcess, OpenProcessToken},
UI::{
Input::KeyboardAndMouse::{GetAsyncKeyState, VIRTUAL_KEY},
Shell::ShellExecuteW,
WindowsAndMessaging::{
CURSOR_SHOWING, CURSORINFO, GetCursorInfo, GetForegroundWindow, GetWindowTextW,
SW_NORMAL,
},
},
},
core::{HSTRING, PCWSTR},
};
pub enum ElevationExitMethod<'a> {
Gentle(&'a mut bool),
Forced,
}
pub fn is_cursor_visible() -> bool {
let mut ci = CURSORINFO {
cbSize: u32::try_from(std::mem::size_of::<CURSORINFO>()).unwrap(),
..Default::default()
};
unsafe {
GetCursorInfo(&mut ci).unwrap();
}
ci.flags == CURSOR_SHOWING
}
pub fn is_window_focused(target_title: &str) -> bool {
let mut buffer = [0; 512];
unsafe {
let hwnd = GetForegroundWindow();
let length = GetWindowTextW(hwnd, &mut buffer);
let current_title = String::from_utf16_lossy(&buffer[..length as usize]);
current_title == target_title
}
}
pub fn is_any_key_pressed(keys: &[VIRTUAL_KEY]) -> bool {
keys.iter()
.any(|&key| unsafe { (GetAsyncKeyState(i32::from(key.0)) & i16::MIN) != 0 })
}
pub fn elevate(closing: ElevationExitMethod) {
let exe = std::env::current_exe().unwrap();
unsafe {
ShellExecuteW(
None,
&HSTRING::from("runas"),
&HSTRING::from(exe.as_path()),
PCWSTR::null(),
PCWSTR::null(),
SW_NORMAL,
);
}
match closing {
ElevationExitMethod::Gentle(closing) => *closing = true,
ElevationExitMethod::Forced => std::process::exit(0),
}
}
pub fn is_elevated() -> bool {
let mut token: HANDLE = HANDLE::default();
unsafe {
if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token).is_err() {
return false;
}
let mut elevation = TOKEN_ELEVATION::default();
let mut size = u32::try_from(std::mem::size_of::<TOKEN_ELEVATION>()).unwrap();
let result = GetTokenInformation(
token,
TokenElevation,
Some((&raw mut elevation).cast()),
size,
&mut size,
);
CloseHandle(token).unwrap();
result.is_ok() && elevation.TokenIsElevated != 0
}
}