Files
amnesia/java-client/src/overlay.cpp
T
2026-11-09 21:22:29 -06:00

1431 lines
71 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include "overlay.h"
#include "gl_state.h"
#include "game.h"
#include "bedrock_clickgui.h"
#include "bedrock_account_screen.h"
#include "bedrock_startup_intro.h"
#include "bedrock_music_player.h"
#include "modules/fps_counter.h"
#include "modules/keystrokes.h"
#include "modules/watermark.h"
#include "modules/themes.h"
#include "gui/target_hud_layout.h"
#include "game/chat_logic.h"
#include "imgui_impl_win32.h"
#include "imgui_impl_opengl3.h"
#include <commctrl.h>
#include <shlobj.h>
#include <gl/GL.h>
#include <algorithm>
#include <array>
#include <cmath>
#include <cstdio>
#include <fstream>
#include <iomanip>
#include <numbers>
#include <sstream>
extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND,UINT,WPARAM,LPARAM);
namespace java::overlay {
void addNote(std::string title,std::string body);
namespace {
constexpr UINT_PTR subclass = 0x414d4a31;
constexpr ImGuiWindowFlags hudFlags=ImGuiWindowFlags_NoDecoration|ImGuiWindowFlags_AlwaysAutoResize|
ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_NoNav|ImGuiWindowFlags_NoFocusOnAppearing|ImGuiWindowFlags_NoBackground;
HWND hwnd;
ImGuiContext* context;
bool& menu=g_menu_open;
bool chat, pendingMenu, pendingChat, escapeRequested, closeRequested, capture, dirty;
bool chatFocus, chatScroll;
Clock::time_point nextSave, frameStart;
double frameMs{}, updateMs{};
std::array<ImVec2,ModuleCount> positions{};
std::array<ImVec2,ModuleCount> renderPositions{};
std::array<ImVec2,ModuleCount> sizes{};
std::array<bool,ModuleCount> hasPosition{}, centerX{}, centerY{};
std::filesystem::path dir;
std::wstring credentialTarget=L"amnesia/java/remembered-login/v1";
std::string activeProfile="default";
std::string profileError;
char filter[128]{}, waypointName[65]="waypoint", chatInput[257]{};
int bindingKey{};
java_ui_modules adapters;
std::array<module*,ModuleCount> views{};
theme_editor* themes{};
music_player* musicView{};
std::vector<std::function<void(bool)>> controls;
chat_logic::sent_history sentHistory;
java_ui_texture customIcon;
float iconAspect=1;
std::string loadedIcon;
unsigned iconRevision=~0u;
licensing::service* license;
licensing::account account;
std::array<bool,ModuleCount> defaults{};
struct InventoryOverlay {
ImVec2 buttons{}, picker{}, pickerSize{};
Clock::time_point shown{};
unsigned epoch{};
int mode=-1,scroll{},visible{};
bool left{},right{};
} inventoryUi;
std::vector<std::deque<setting>> defaultUi;
float chatWidth=560,chatHeight=260,chatOpacity=.96f;
bool xpPercent=true,xpRemaining=true,xpBar=true,targetBar=true,targetFollow=true;
float xpWidth=220,targetOffsetX=24,targetOffsetY=0,targetSwitch=.24f,targetLinger=2;
float chatNameColor[]{.7f,.5f,.9f,1},chatMessageColor[]{1,1,1,1},chatSystemColor[]{.65f,.65f,.65f,1};
bool sprintStatus=true,freelookStatus=true,fortressStatus=true,fortressMarker=true;
template<class... Args>
std::string formatted(const char* format,Args... args) {
char buf[256];
const int n=std::snprintf(buf,sizeof(buf),format,args...);
return std::string(buf,n<0 ? 0 : std::min(size_t(n),sizeof(buf)-1));
}
template<size_t N>
void copy(char (&dest)[N],std::string_view src) {
const auto size=std::min(src.size(),N-1);
std::copy_n(src.begin(),size,dest);
dest[size]=0;
}
void change() { dirty=true; nextSave=Clock::now()+std::chrono::milliseconds(400); }
void addPoint(Vec pos,const char* name);
void initViews();
void mirror(bool read);
void seedTheme();
std::string uiState();
void readUi(std::istream& row);
void readColor(std::istream& in,float* values);
struct java_hud : text_hud {
ModuleId id;
static const char* title(ModuleId id) {
switch (id) {
case Fps: return "fps counter";
case Cps: return "cps counter";
case Armor: return "armor hud";
default: return java::modules[id].title;
}
}
explicit java_hud(ModuleId value,category group)
: text_hud(title(value),java::modules[value].detail,group),id(value) {
if (id==Diagnostics) background_->bool_value=false;
}
bool is_hud() const override {
if (id==ToggleSprint) return sprintStatus;
if (id==Freelook) return freelookStatus;
if (id==Fortress) return fortressStatus;
return cat()==category::hud;
}
ImVec2 hud_size() const override { return sizes[id]; }
ImVec2 hud_render_position() const override { return renderPositions[id]; }
bool hud_position_locked() const override { return id==Xp && java::settings.xpLock; }
float scale() const { return scale_->float_value; }
bool background() const { return background_->bool_value; }
ImU32 color() const { return setting_color(*color_); }
void renderText(const char* label,const std::string& value,const char* reserve="") {
label_=label;
text_=value;
reserve_=reserve;
sizes[id]=text_hud::hud_size();
draw_text();
}
};
template<class T>
void option(module& view,const char* name,T& value,T low={},T high={}) {
setting* s;
if constexpr(std::is_same_v<T,bool>) s=&view.add_toggle(name,value);
if constexpr(std::is_same_v<T,float>) s=&view.add_float(name,value,low,high);
if constexpr(std::is_same_v<T,int>) s=&view.add_int(name,value,low,high);
controls.push_back([s,&value](bool read) {
auto& source=[&]() -> T& {
if constexpr(std::is_same_v<T,bool>) return s->bool_value;
if constexpr(std::is_same_v<T,float>) return s->float_value;
if constexpr(std::is_same_v<T,int>) return s->int_value;
}();
if (read) source=value;
else value=source;
});
}
void mode(module& view,const char* name,int& value,std::vector<std::string> modes) {
auto* s=&view.add_mode(name,std::move(modes),value);
controls.push_back([s,&value](bool read) {
if (read) s->int_value=std::clamp(value,0,int(s->modes.size()-1));
else value=s->int_value;
});
}
template<size_t N>
void textOption(module& view,const char* name,char (&value)[N]) {
auto* s=&view.add_text(name,value,int(N-1));
controls.push_back([s,&value](bool read) { if (read) s->text_value=value; else copy(value,s->text_value); });
}
void colorOption(module& view,const char* name,float (&value)[4]) {
auto* s=&view.add_color(name,value[0],value[1],value[2],value[3]);
controls.push_back([s,&value](bool read) { if (read) std::copy_n(value,4,s->color); else std::copy_n(s->color,4,value); });
}
void initViews() {
auto themeView=std::make_unique<theme_editor>();
themes=themeView.get();
adapters.items.push_back(std::move(themeView));
for (int i=0;i<ModuleCount;++i) {
const auto id=ModuleId(i);
const std::string_view group=java::modules[id].category;
std::unique_ptr<module> view;
if (id==Keystrokes) view=std::make_unique<keystrokes>();
else if (id==Watermark) view=std::make_unique<watermark>();
else if (id==MiniPlayer) {
auto media=std::make_unique<music_player>();
musicView=media.get();
view=std::move(media);
} else if (group=="hud" || id==SoundIndicators) view=std::make_unique<java_hud>(id,category::hud);
else if (id==ToggleSprint || id==Freelook) view=std::make_unique<java_hud>(id,category::utility);
else if (id==Fortress) view=std::make_unique<java_hud>(id,category::visual);
else view=std::make_unique<module>(id==ClientTime ? "time changer":java::modules[id].title,java::modules[id].detail,
group=="utility" || id==NameChanger ? category::utility : category::visual);
views[id]=view.get();
auto& m=*view;
switch (id) {
case Fov: option(m,"field of view",settings.fov,30.f,145.f); break;
case Zoom: option(m,"hold c fov",settings.zoom,8.f,70.f); break;
case Fullbright: option(m,"gamma",settings.gamma,1.f,16.f); break;
case Optimize: option(m,"entity distance",settings.entityDistance,.5f,1.f); break;
case Atmosphere:
option(m,"rain",settings.rain,0.f,1.f);
option(m,"thunder",settings.thunder,0.f,1.f);
break;
case ClientTime: option(m,"sky time",settings.time,0,23999); break;
case NameChanger: textOption(m,"local display name",settings.displayName); break;
case Xp:
option(m,"width",xpWidth,150.f,400.f); option(m,"percentage",xpPercent);
option(m,"XP remaining",xpRemaining); option(m,"progress bar",xpBar);
option(m,"lock above vanilla xp bar",settings.xpLock);
break;
case Crosshair:
option(m,"length",settings.length,1.f,28.f); option(m,"width",settings.width,1.f,8.f);
option(m,"gap",settings.gap,0.f,22.f); colorOption(m,"color",settings.crosshairColor);
option(m,"black outline",settings.crossOutline); option(m,"gradient",settings.gradient);
colorOption(m,"gradient color",settings.crosshairGradient);
option(m,"dynamic gap",settings.dynamicGap); option(m,"gap speed",settings.gapSpeed,.5f,12.f);
option(m,"gap easing",settings.gapEase,1.f,30.f);
option(m,"dynamic length",settings.dynamicLength); option(m,"length speed",settings.lengthSpeed,.5f,12.f);
option(m,"length easing",settings.lengthEase,1.f,30.f); option(m,"reactive instead of pulse",settings.reactive);
option(m,"spin",settings.spin); option(m,"spin speed",settings.spinSpeed,.5f,12.f);
option(m,"spin easing",settings.spinEase,1.f,30.f);
break;
case Outlines:
colorOption(m,"color",settings.outlineColor); option(m,"width",settings.outlineWidth,1.f,6.f);
option(m,"black outline",settings.blockBlack);
break;
case Target:
option(m,"linger (seconds)",targetLinger,0.f,5.f); option(m,"health bar",targetBar);
option(m,"follow target",targetFollow);
option(m,"horizontal offset",targetOffsetX,-300.f,300.f); option(m,"vertical offset",targetOffsetY,-300.f,300.f);
option(m,"tracking speed",settings.tracking,8.f,60.f); option(m,"switch duration",targetSwitch,0.f,.8f);
break;
case Waypoints:
textOption(m,"label",waypointName);
m.add_action("save current position",[]{addPoint(data.position,waypointName);});
break;
case Fortress:
option(m,"scan radius (blocks)",settings.fortressRadius,32,192);
option(m,"show status",fortressStatus); option(m,"world marker",fortressMarker);
m.add_action("rescan",[]{if (data.dimension=="minecraft:the_nether") requestFortress();});
m.add_action("save fortress waypoint",[]{if (data.foundFortress) addPoint(data.fortress,"fortress candidate");});
break;
case ToggleSprint: option(m,"show status",sprintStatus); break;
case Freelook: option(m,"show status",freelookStatus); break;
case InventoryTools:
option(m,"UI buttons",settings.inventoryButtons); option(m,"include hotbar when dumping",settings.inventoryHotbar);
option(m,"action delay (ms)",settings.inventoryDelay,30,500);
option(m,"buttons X (screen fraction)",settings.inventoryX,0.f,1.f);
option(m,"buttons Y (screen fraction)",settings.inventoryY,0.f,1.f);
textOption(m,"item filter",filter);
m.add_action("steal",[]{if (data.inContainer && java::modules[InventoryTools].on) requestTransfer(false,filter);});
m.add_action("dump",[]{if (data.inContainer && java::modules[InventoryTools].on) requestTransfer(true,filter);});
m.add_action("stop",[]{stopTransfer();});
break;
case Chat:
option(m,"hide vanilla overlay",settings.hideChat);
option(m,"chat width",chatWidth,280.f,1000.f); option(m,"chat height",chatHeight,140.f,600.f);
option(m,"background opacity",chatOpacity,.3f,1.f);
colorOption(m,"name color",chatNameColor); colorOption(m,"message color",chatMessageColor);
colorOption(m,"system message color",chatSystemColor);
m.add_action("clear chat history",[]{data.chat.clear();});
break;
case Notifier:
option(m,"incoming chat",settings.messages); option(m,"sleep time",settings.notifyNight);
option(m,"low health",settings.notifyHealth); option(m,"low hunger",settings.notifyHunger);
break;
case MiniPlayer:
for (auto& s:m.settings()) if (s.name=="lyrics") {
auto* setting=&s;
controls.push_back([setting](bool read){if (read) setting->bool_value=settings.lyrics; else settings.lyrics=setting->bool_value;});
}
break;
case MobAttack:
option(m,"include animals",settings.animals); option(m,"range",settings.mobRange,1.f,3.f);
mode(m,"mode",settings.critical,{"normal","critical timing"});
break;
case AutoClick:
option(m,"clicks per second",settings.cps,1.f,20.f); option(m,"right mouse instead of left",settings.rightClick);
break;
case AntiAfk: option(m,"idle seconds",settings.antiAfkSeconds,20,900); break;
case ParticleControls: mode(m,"particles",settings.particleMode,{"decreased","minimal"}); break;
case FriendsLocator: textOption(m,"friends",settings.friends); break;
default: break;
}
adapters.items.push_back(std::move(view));
}
constexpr ModuleId bedrockOrder[]{Fps,Keystrokes,Watermark,Crosshair,Optimize,Fullbright,Fov,Zoom,MiniPlayer,
InventoryTools,AntiAfk,EndermanLook,Trajectories,AutoWeapon,AutoTool,AutoClick,MobAttack,Speed,Looking,EntityCount,
Breadcrumbs,Logout,Tracers,Radar,Active,Tab,Xp,ToggleSprint,Cps,ClockHud,Outlines,Atmosphere,Armor,NameChanger,
BetterTags,FriendsLocator,Target,ClientTime,Freelook,Coordinates,Waypoints,Fortress,Compass,Stats,Durability,
Notifier,Chat,Tool,Effects,ParticleControls,SoundIndicators,Diagnostics};
const auto rank=[&](const auto& view) {
if (view.get()==themes) return 0;
for (int i=0;i<int(std::size(bedrockOrder));++i)
if (view.get()==views[bedrockOrder[i]]) return i+1;
return int(std::size(bedrockOrder))+1;
};
std::ranges::stable_sort(adapters.items,{},rank);
for (const auto& m:adapters.items) defaultUi.push_back(m->settings());
}
void mirror(bool read) {
for (auto& sync:controls) sync(read);
if (!read) { themes->synchronize(); settings.grid=hud_editor::options.grid_size; }
}
void seedTheme() {
for (auto& s:themes->settings()) {
for (size_t i=0;i<std::size(theme::color_definitions);++i)
if (s.name==theme::color_definitions[i].name) {
const auto& c=theme::current.colors[i];
s.color[0]=c.x; s.color[1]=c.y; s.color[2]=c.z; s.color[3]=c.w;
break;
}
if (s.name=="watermark name") s.text_value=theme::current.name;
if (s.name=="body size") s.int_value=theme::current.body_size;
}
}
std::string uiState() {
std::ostringstream file;
file << "grid-options " << hud_editor::options.snap << ' ' << hud_editor::options.show_grid << ' '
<< hud_editor::options.grid_size << '\n';
for (const auto& m:adapters.items) {
file << "bind " << std::quoted(m->name()) << ' ' << m->toggle_key() << '\n';
for (const auto& s:m->settings()) {
if (s.type==setting_type::action) continue;
file << "ui " << std::quoted(m->name()) << ' ' << std::quoted(s.name) << ' ';
switch(s.type) {
case setting_type::toggle: file << s.bool_value; break;
case setting_type::slider_float: file << s.float_value; break;
case setting_type::color: for (float c:s.color) file << c << ' '; break;
case setting_type::text: file << std::quoted(s.text_value); break;
default: file << s.int_value; break;
}
file << '\n';
}
}
return file.str();
}
void readUi(std::istream& row) {
std::string type,name,key;
if (!(row >> type)) return;
if (type=="grid-options") {
auto& grid=hud_editor::options;
if (row >> grid.snap >> grid.show_grid >> grid.grid_size) grid.grid_size=std::clamp(grid.grid_size,4,64);
return;
}
if (!(row >> std::quoted(name))) return;
auto m=std::ranges::find_if(adapters.items,[&](const auto& item){return item->name()==name;});
if (m==adapters.items.end()) return;
if (type=="bind") {
int vk{};
if (row >> vk && vk>=0 && vk<255 && vk!=VK_RSHIFT) (*m)->set_toggle_key(vk);
return;
}
if (!(row >> std::quoted(key))) return;
for (auto& s:(*m)->settings()) {
if (key!=s.name) continue;
int integer{};
float value{};
switch (s.type) {
case setting_type::toggle: row >> s.bool_value; break;
case setting_type::slider_float:
if (row >> value && std::isfinite(value)) s.float_value=std::clamp(value,s.float_min,s.float_max);
break;
case setting_type::color: readColor(row,s.color); break;
case setting_type::text: if (row >> std::quoted(name)) s.text_value=name.substr(0,s.int_max); break;
case setting_type::mode:
if (row >> integer && integer>=0 && size_t(integer)<s.modes.size()) s.int_value=integer;
break;
case setting_type::slider_int:
if (row >> integer) s.int_value=std::clamp(integer,s.int_min,s.int_max);
break;
case setting_type::keybind:
if (row >> integer && integer>=0 && integer<255) s.int_value=integer;
break;
default: break;
}
break;
}
}
// Keep the settings list shared by the profile reader and writer.
#define OPTIONS(F) F(fov) F(zoom) F(gamma) F(tracking) F(mobRange) F(cps) F(entityDistance) F(length) F(width) \
F(gap) F(gapSpeed) F(lengthSpeed) F(spinSpeed) F(gapEase) F(lengthEase) F(spinEase) F(outlineWidth) F(rain) F(thunder) \
F(time) F(grid) F(fortressRadius) F(critical) F(antiAfkSeconds) F(particleMode) \
F(animals) F(rightClick) F(messages) F(crossOutline) F(blockBlack) F(gradient) F(spin) F(dynamicLength) F(dynamicGap) \
F(reactive) F(xpLock) F(lyrics) F(hideChat) F(notifyNight) F(notifyHealth) F(notifyHunger)
std::filesystem::path profilePath() { return dir/(activeProfile+".profile"); }
void save() {
if (dir.empty() || !dirty) return;
const auto path=profilePath();
auto temp=path; temp+=L".tmp";
std::ofstream file(temp,std::ios::trunc);
if (!file) { profileError="could not open the profile for saving"; return; }
file << "amnesia-java 1\n";
for (int i=0;i<ModuleCount;++i) {
file << "module " << std::quoted(modules[i].title) << ' ' << modules[i].on << '\n';
if (hasPosition[i] || centerX[i] || centerY[i])
file << "position " << std::quoted(modules[i].title) << ' ' << positions[i].x << ' ' << positions[i].y
<< ' ' << hasPosition[i] << ' ' << centerX[i] << ' ' << centerY[i] << '\n';
}
#define WRITE(key) file << #key " " << settings.key << '\n';
OPTIONS(WRITE)
#undef WRITE
file << "name " << std::quoted(settings.displayName) << "\nfriends " << std::quoted(settings.friends)
<< "\nbrand " << std::quoted(theme::current.name)
<< "\nfont " << theme::current.body_size << '\n';
for (size_t i=0;i<theme::current.colors.size();++i) {
const auto& c=theme::current.colors[i];
file << "theme " << i << ' ' << c.x << ' ' << c.y << ' ' << c.z << ' ' << c.w << '\n';
}
for (const auto& [label,c] : {std::pair{"crosshairColor",settings.crosshairColor},
std::pair{"crosshairGradient",settings.crosshairGradient},std::pair{"outlineColor",settings.outlineColor}})
file << label << ' ' << c[0] << ' ' << c[1] << ' ' << c[2] << ' ' << c[3] << '\n';
for (const auto& point:data.waypoints)
file << "waypoint " << std::quoted(point.name) << ' ' << std::quoted(point.dimension)
<< ' ' << point.pos.x << ' ' << point.pos.y << ' ' << point.pos.z << '\n';
file << uiState();
file.close();
if (file && MoveFileExW(temp.c_str(),path.c_str(),MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH)) {
dirty=false; profileError.clear();
} else profileError="could not replace the profile file";
}
void readColor(std::istream& in,float* values) {
std::array<float,4> result{};
if (in >> result[0] >> result[1] >> result[2] >> result[3])
for (size_t i=0;i<4;++i) values[i]=std::isfinite(result[i]) ? std::clamp(result[i],0.f,1.f) : 1.f;
}
void readProfile() {
settings={};
theme::current={};
for (size_t i=0;i<adapters.items.size();++i) {
auto& m=*adapters.items[i];
m.set_toggle_key(0);
for (size_t j=0;j<m.settings().size();++j) m.settings()[j]=defaultUi[i][j];
}
hud_editor::options={};
settings.grid=hud_editor::options.grid_size;
data.waypoints.clear();
hasPosition.fill(false); centerX.fill(false); centerY.fill(false);
for (int i=0;i<ModuleCount;++i) modules[i].on=defaults[i];
std::ifstream file(profilePath());
std::string text;
if (!std::getline(file,text) || text!="amnesia-java 1") {
mirror(true); seedTheme(); mirror(false);
return;
}
std::vector<std::string> uiRows;
unsigned limit=0;
while (++limit<=2000 && std::getline(file,text) && text.size()<2048) {
std::istringstream row(text);
std::string key, value;
row >> key;
if (key=="module" || key=="position") {
row >> std::quoted(value);
auto it=std::ranges::find_if(modules,[&](const Module& m){return value==m.title;});
if (it==modules.end()) continue;
const auto i=it-modules.begin();
if (key=="module") row >> it->on;
if (key=="position") row >> positions[i].x >> positions[i].y >> hasPosition[i] >> centerX[i] >> centerY[i];
} else if (key=="theme") {
size_t i{};
if (row >> i && i<theme::current.colors.size()) readColor(row,&theme::current.colors[i].x);
} else if (key=="waypoint") {
Waypoint point;
if (row >> std::quoted(point.name) >> std::quoted(point.dimension) >> point.pos.x >> point.pos.y >> point.pos.z &&
data.waypoints.size()<128 && !point.name.empty() && std::isfinite(point.pos.length()))
data.waypoints.push_back(std::move(point));
} else if (key=="name" || key=="friends" || key=="brand" || key=="api") {
if (!(row >> std::quoted(value))) continue;
if (key=="name") copy(settings.displayName,value);
if (key=="friends") copy(settings.friends,value);
if (key=="brand") theme::current.name=value;
if (key=="api" && !account_ui::configured) copy(account_ui::address,value);
} else if (key=="font") row >> theme::current.body_size;
else if (key=="ui" || key=="bind" || key=="grid-options") uiRows.push_back(text);
else if (key=="crosshairColor") readColor(row,settings.crosshairColor);
else if (key=="crosshairGradient") readColor(row,settings.crosshairGradient);
else if (key=="outlineColor") readColor(row,settings.outlineColor);
#define READ(name) else if (key==#name) row >> settings.name;
OPTIONS(READ)
#undef READ
}
settings.grid=std::clamp(settings.grid,1,64);
settings.fortressRadius=std::clamp(settings.fortressRadius,32,192);
settings.antiAfkSeconds=std::clamp(settings.antiAfkSeconds,20,900);
theme::current.body_size=std::clamp(theme::current.body_size,9,18);
hud_editor::options.grid_size=std::clamp(settings.grid,4,64);
mirror(true);
seedTheme();
for (const auto& line:uiRows) { std::istringstream row(line); readUi(row); }
mirror(false);
}
#undef OPTIONS
bool validProfile(std::string_view name) {
return !name.empty() && name.size()<49 && name.front()!=' ' && name.back()!=' ' && std::ranges::all_of(name,[](char c) {
return (c>='a'&&c<='z') || (c>='A'&&c<='Z') || (c>='0'&&c<='9') || c=='_' || c=='-' || c==' ';
});
}
bool switchProfile(const std::string& name,bool create) {
profileError.clear();
if (dir.empty() || !validProfile(name)) { profileError="enter a valid profile name"; return false; }
save();
if (dirty) return false;
const auto previous=activeProfile;
activeProfile=name;
if (create) {
change(); save();
if (dirty) { activeProfile=previous; return false; }
}
else readProfile();
std::ofstream(dir/"selected") << name;
return true;
}
void initConfig() {
wchar_t overridePath[32768]{};
const auto length=GetEnvironmentVariableW(L"AMNESIA_JAVA_PROFILE_DIR",overridePath,DWORD(std::size(overridePath)));
if (length && length<std::size(overridePath)) {
std::filesystem::path custom(overridePath);
if (custom.is_absolute()) {
dir=custom.lexically_normal();
credentialTarget=L"amnesia/java/portable/"+std::to_wstring(std::hash<std::wstring>{}(dir.native()))+L"/v1";
}
}
PWSTR path{};
if (dir.empty() && SUCCEEDED(SHGetKnownFolderPath(FOLDERID_LocalAppData,0,nullptr,&path))) {
dir=std::filesystem::path(path)/"amnesia"/"java";
CoTaskMemFree(path);
}
if (!dir.empty()) {
std::error_code error;
std::filesystem::create_directories(dir,error);
if (error) dir.clear();
}
for (int i=0;i<ModuleCount;++i) defaults[i]=modules[i].on;
if (dir.empty()) return;
std::string remembered;
std::ifstream(dir/"selected") >> remembered;
if (validProfile(remembered)) activeProfile=remembered;
readProfile();
}
bool inputMessage(UINT msg) {
return (msg>=WM_KEYFIRST && msg<=WM_KEYLAST) || (msg>=WM_MOUSEFIRST && msg<=WM_MOUSELAST) ||
msg==WM_INPUT || msg==WM_SETCURSOR || msg==WM_UNICHAR;
}
void closePicker() { inventoryUi.mode=-1; readInventoryPicker(false); }
bool inventoryInput(UINT msg,WPARAM wp,LPARAM lp) {
auto& ui=inventoryUi;
if (msg==WM_LBUTTONUP && std::exchange(ui.left,false)) return true;
if (msg==WM_RBUTTONUP && std::exchange(ui.right,false)) return true;
if (capture || !account.allowed() || !data.inContainer || !settings.inventoryButtons ||
!java::modules[InventoryTools].on || Clock::now()-ui.shown>std::chrono::milliseconds(150)) {
closePicker();
return false;
}
if (ui.epoch!=data.containerEpoch || data.containerCursor) closePicker();
if (ui.mode>=0 && msg==WM_KEYDOWN && wp==VK_ESCAPE) { closePicker(); return true; }
if (ui.mode>=0 && msg==WM_MOUSEWHEEL) {
const auto& items=data.inventoryChoices[ui.mode];
ui.scroll=std::clamp(ui.scroll-short(HIWORD(wp))/WHEEL_DELTA,0,std::max(0,int(items.size())-ui.visible));
return true;
}
const bool left=msg==WM_LBUTTONDOWN || msg==WM_LBUTTONDBLCLK;
const bool right=msg==WM_RBUTTONDOWN || msg==WM_RBUTTONDBLCLK;
if (!left && !right) return false;
const float x=short(LOWORD(lp)),y=short(HIWORD(lp));
if (ui.mode>=0) {
const auto& p=ui.picker;
if (left && x>=p.x && x<p.x+ui.pickerSize.x && y>=p.y+28 && y<p.y+28+ui.visible*22) {
const auto& choices=data.inventoryChoices[ui.mode];
const int row=ui.scroll+int((y-p.y-28)/22);
if (row>=0 && size_t(row)<choices.size()) requestTransfer(ui.mode==1,choices[row].type,true);
}
closePicker();
if (left) ui.left=true; else ui.right=true;
return true;
}
const float offset=x-ui.buttons.x;
if (y<ui.buttons.y || y>=ui.buttons.y+26 || offset<0 || offset>=308 || int(offset)%104>=100) {
if (left && data.containerBusy) stopTransfer();
return false;
}
const int button=int(offset)/104;
if (button==2 && !data.containerBusy) return false;
if (right && button==2) return false;
if (left) ui.left=true; else ui.right=true;
if (data.containerTransfer && !data.containerCursor) {
if (button==2) stopTransfer();
else if (left) requestTransfer(button==1,{});
else {
stopTransfer();
ui.mode=button;
ui.scroll=ui.visible=0;
ui.epoch=data.containerEpoch;
readInventoryPicker(true);
}
}
return true;
}
LRESULT CALLBACK procedure(HWND window,UINT msg,WPARAM wp,LPARAM lp,UINT_PTR, DWORD_PTR) {
if (!context) return DefSubclassProc(window,msg,wp,lp);
if (inventoryInput(msg,wp,lp)) return 0;
if (msg==WM_KILLFOCUS && (capture || chat)) closeRequested=true;
if (msg==WM_KEYDOWN && !(lp&(1L<<30))) {
const auto scan=UINT((lp>>16)&255);
if (wp==VK_RSHIFT || (wp==VK_SHIFT && MapVirtualKeyW(scan,MAPVK_VSC_TO_VK_EX)==VK_RSHIFT)) {
pendingMenu=true;
return 0;
}
if (capture && gui().binding()) {
bindingKey=wp==VK_SHIFT || wp==VK_CONTROL || wp==VK_MENU ?
int(MapVirtualKeyW(scan|((lp&(1L<<24)) ? 0xe000 : 0),MAPVK_VSC_TO_VK_EX)):int(wp);
return 0;
}
if (wp==VK_ESCAPE && capture) {
escapeRequested=true;
return 0;
}
if ((wp=='T' || wp==VK_OEM_2) && !capture && account.allowed() && data.inWorld && !data.inScreen && modules[Chat].on) {
if (wp==VK_OEM_2 && !*chatInput) copy(chatInput,"/");
pendingChat=true;
return 0;
}
}
if (capture) {
if (msg==WM_INPUT) return DefWindowProcW(window,msg,wp,lp);
ImGui_ImplWin32_WndProcHandler(window,msg,wp,lp);
if (inputMessage(msg)) return 0;
}
if (data.orbiting && msg==WM_INPUT) {
RAWINPUT raw{};
UINT size=sizeof(raw);
if (GetRawInputData(reinterpret_cast<HRAWINPUT>(lp),RID_INPUT,&raw,&size,sizeof(RAWINPUTHEADER))==sizeof(raw) &&
raw.header.dwType==RIM_TYPEMOUSE && !(raw.data.mouse.usFlags&MOUSE_MOVE_ABSOLUTE)) {
orbit(raw.data.mouse.lLastX,raw.data.mouse.lLastY);
return DefWindowProcW(window,msg,wp,lp);
}
}
if (data.orbiting && msg==WM_MOUSEMOVE) return 0;
if (!capture && data.inWorld && !data.inScreen && (msg==WM_LBUTTONDOWN || msg==WM_RBUTTONDOWN))
click(msg==WM_RBUTTONDOWN);
return DefSubclassProc(window,msg,wp,lp);
}
ImVec2 place(int id,ImVec2 fallback,ImVec2 size) {
const auto display=ImGui::GetIO().DisplaySize;
auto p=hasPosition[id] ? positions[id] : fallback;
if (centerX[id]) p.x=(display.x-size.x)*.5f;
if (centerY[id]) p.y=(display.y-size.y)*.5f;
p=hud_editor::constrain(p,size,display,false,10);
sizes[id]=size;
views[id]->hud_pos=p;
renderPositions[id]=p;
return p;
}
bool screenPoint(Vec value,ImVec2& screen) {
const auto y=data.cameraYaw*std::numbers::pi/180,p=data.cameraPitch*std::numbers::pi/180;
const auto delta=value-data.camera;
const auto depth=-std::sin(y)*std::cos(p)*delta.x-std::sin(p)*delta.y+std::cos(y)*std::cos(p)*delta.z;
if (depth<.05) return false;
const auto horizontal=-std::cos(y)*delta.x-std::sin(y)*delta.z;
const auto vertical=-std::sin(y)*std::sin(p)*delta.x+std::cos(p)*delta.y+std::cos(y)*std::sin(p)*delta.z;
const auto size=ImGui::GetIO().DisplaySize;
const auto scale=size.y*.5/std::tan(std::clamp(double(data.cameraFov),5.,165.)*std::numbers::pi/360);
screen={float(size.x*.5+horizontal*scale/depth),float(size.y*.5-vertical*scale/depth)};
return std::abs(screen.x)<size.x*3 && std::abs(screen.y)<size.y*3;
}
void pointLabel(Vec where,const std::string& text,ImU32 color) {
ImVec2 p;
if (!screenPoint(where,p)) return;
auto* draw=ImGui::GetBackgroundDrawList();
const auto size=ImGui::CalcTextSize(text.c_str());
draw->AddRectFilled({p.x-size.x*.5f-4,p.y-2},{p.x+size.x*.5f+4,p.y+size.y+2},IM_COL32(15,15,15,222));
draw->AddText({p.x-size.x*.5f,p.y},color,text.c_str());
}
void worldLine(Vec a,Vec b,ImU32 color,float width=1.5f) {
ImVec2 p,q;
if (screenPoint(a,p) && screenPoint(b,q)) ImGui::GetBackgroundDrawList()->AddLine(p,q,color,width);
}
bool isFriend(const std::string& name) {
std::string_view list(settings.friends);
while (!list.empty()) {
const auto end=list.find(',');
auto item=list.substr(0,end);
while (!item.empty() && item.front()==' ') item.remove_prefix(1);
while (!item.empty() && item.back()==' ') item.remove_suffix(1);
if (item.size()==name.size() && _strnicmp(item.data(),name.c_str(),item.size())==0) return true;
if (end==std::string_view::npos) break;
list.remove_prefix(end+1);
}
return false;
}
void worldDraw() {
const auto accent=theme::u32(theme::accent());
const auto viewport=ImGui::GetIO().DisplaySize;
auto* draw=ImGui::GetBackgroundDrawList();
if (modules[Waypoints].on)
for (const auto& point:data.waypoints) if (point.dimension==data.dimension)
pointLabel(point.pos,point.name+formatted(" %.0fm",(point.pos-data.position).length()),accent);
if (modules[Fortress].on && fortressMarker && data.foundFortress)
pointLabel(data.fortress,formatted("fortress candidate %.0fm",(data.fortress-data.position).length()),accent);
if (modules[Logout].on)
for (const auto& spot:data.logouts) pointLabel(spot.pos,spot.name+" / logout",accent);
if (modules[Breadcrumbs].on)
for (size_t i=1;i<data.trail.size();++i) worldLine(data.trail[i-1],data.trail[i],accent);
if (modules[Trajectories].on && data.projectile.size()>1) {
for (size_t i=1;i<data.projectile.size();++i) worldLine(data.projectile[i-1],data.projectile[i],accent,2);
ImVec2 p;
if (screenPoint(data.projectile.back(),p)) draw->AddCircle(p,5,accent,20,2);
}
if (modules[Tracers].on || modules[BetterTags].on)
for (const auto& a:data.actors) {
ImVec2 point;
if (modules[Tracers].on && screenPoint(a.pos+Vec{0,a.height*.5,0},point))
draw->AddLine({viewport.x*.5f,viewport.y*.9f},point,accent,1);
if (modules[BetterTags].on && a.player)
pointLabel(a.pos+Vec{0,a.height+.28,0},a.name+formatted(" %.0f hp / %.0fm",a.hp,(a.pos-data.position).length()),accent);
}
if (modules[FriendsLocator].on && data.realm)
for (const auto& a:data.actors)
if (a.player && isFriend(a.name)) {
ImVec2 head, feet;
if (screenPoint(a.pos+Vec{0,a.height,0},head) && screenPoint(a.pos,feet)) {
const float radius=std::max(3.f,std::abs(feet.y-head.y)*.23f);
draw->AddRect({head.x-radius,std::min(head.y,feet.y)},{head.x+radius,std::max(head.y,feet.y)},accent);
}
pointLabel(a.pos+Vec{0,a.height+.25,0},a.name+formatted(" %.0fm",(a.pos-data.position).length()),accent);
}
if (modules[SoundIndicators].on)
for (const auto& sound:data.sounds)
pointLabel(sound.position,sound.name+formatted(" %.0fm",(sound.position-data.position).length()),accent);
if (modules[Outlines].on && data.blockTarget) {
const auto color=ImGui::ColorConvertFloat4ToU32({settings.outlineColor[0],settings.outlineColor[1],settings.outlineColor[2],settings.outlineColor[3]});
std::array<Vec,8> corners;
for (int i=0;i<8;++i) corners[i]=data.hitBlock+Vec{double(i&1),double((i>>1)&1),double((i>>2)&1)};
for (int i=0;i<8;++i) for (int axis:{1,2,4}) if (!(i&axis)) {
if (settings.blockBlack) worldLine(corners[i],corners[i|axis],IM_COL32_BLACK,settings.outlineWidth+2);
worldLine(corners[i],corners[i|axis],color,settings.outlineWidth);
}
}
}
void crosshair() {
if (!modules[Crosshair].on) return;
const auto size=ImGui::GetIO().DisplaySize;
const ImVec2 center{size.x*.5f,size.y*.5f};
const float t=float(ImGui::GetTime());
const float dt=ImGui::GetIO().DeltaTime;
const float reactive=float(std::clamp(data.speed*.09+data.leftCps*.03,0.,1.));
const auto pulse=[&](float speed){return settings.reactive ? reactive : .5f+.5f*std::sin(t*speed);};
static float lengthOffset{}, gapOffset{}, rotation{}, spinRate{};
lengthOffset+=((settings.dynamicLength ? pulse(settings.lengthSpeed)*5 : 0)-lengthOffset)*(1-std::exp(-settings.lengthEase*dt));
gapOffset+=((settings.dynamicGap ? pulse(settings.gapSpeed)*4 : 0)-gapOffset)*(1-std::exp(-settings.gapEase*dt));
spinRate+=((settings.spin ? settings.spinSpeed : 0)-spinRate)*(1-std::exp(-settings.spinEase*dt));
rotation=settings.spin ? std::remainder(rotation+spinRate*dt,2*std::numbers::pi_v<float>) : rotation*std::exp(-settings.spinEase*dt);
const float length=settings.length+lengthOffset;
const float gap=settings.gap+gapOffset;
const auto color=[](const float* c){return ImGui::ColorConvertFloat4ToU32({c[0],c[1],c[2],c[3]});};
auto* draw=ImGui::GetBackgroundDrawList();
for (int i=0;i<4;++i) {
const float angle=i*std::numbers::pi_v<float>/2+rotation;
const ImVec2 v{std::cos(angle),std::sin(angle)};
const ImVec2 a{center.x+v.x*gap,center.y+v.y*gap};
const ImVec2 b{a.x+v.x*length,a.y+v.y*length};
if (settings.crossOutline) draw->AddLine(a,b,IM_COL32_BLACK,settings.width+2);
if (settings.gradient) {
const auto c=ImGui::ColorConvertU32ToFloat4(color(settings.crosshairColor));
const auto d=ImGui::ColorConvertU32ToFloat4(color(settings.crosshairGradient));
for (int s=0;s<8;++s) {
const float l=float(s)/8,r=float(s+1)/8;
draw->AddLine({a.x+v.x*length*l,a.y+v.y*length*l},{a.x+v.x*length*r,a.y+v.y*length*r},
ImGui::ColorConvertFloat4ToU32({c.x+(d.x-c.x)*l,c.y+(d.y-c.y)*l,c.z+(d.z-c.z)*l,c.w+(d.w-c.w)*l}),settings.width);
}
} else draw->AddLine(a,b,color(settings.crosshairColor),settings.width);
}
}
std::string itemLabel(const Item& item) {
if (item.name.empty()) return "empty";
return item.name+(item.maximum ? formatted(" %d/%d",item.maximum-item.used,item.maximum) :
item.count>1 ? formatted(" ×%d",item.count) : "");
}
const Waypoint* closestWaypoint() {
const Waypoint* best=nullptr;
double distance=INFINITY;
for (const auto& point:data.waypoints)
if (point.dimension==data.dimension) {
const auto d=(point.pos-data.position).length();
if (d<distance) { distance=d; best=&point; }
}
return best;
}
bool hudVisible(int id) {
if (!java::modules[id].on) return false;
if (menu) return true;
if (data.guiHidden || data.inScreen) return false;
if (id==Watermark || id==MiniPlayer || id==Diagnostics || id==Fps) return true;
if (!data.inWorld) return false;
if (id==Tab) return is_key_down(VK_TAB);
return true;
}
void huds() {
const auto screen=ImGui::GetIO().DisplaySize;
auto* draw=ImGui::GetBackgroundDrawList();
if (hudVisible(Watermark)) {
auto& view=static_cast<watermark&>(*views[Watermark]);
place(Watermark,{10,10},view.hud_size());
view.draw(account);
sizes[Watermark]=view.hud_size();
}
if (hudVisible(Keystrokes)) {
auto& view=static_cast<keystrokes&>(*views[Keystrokes]);
place(Keystrokes,{10,60},view.hud_size());
view.on_render();
}
if (hudVisible(MiniPlayer)) {
place(MiniPlayer,{10,560},musicView->hud_size());
musicView->on_render();
}
const auto one=[&](ModuleId id,ImVec2 fallback,const char* title,const std::string& value,const char* reserve="") {
if (!hudVisible(id)) return;
auto& m=static_cast<java_hud&>(*views[id]);
place(id,fallback,hud_card::size(title,value.c_str(),m.scale(),reserve));
m.renderText(title,value,reserve);
};
const auto rows=[&](ModuleId id,ImVec2 fallback,const char* title,const std::vector<std::string>& values,float width=0.f) {
auto& m=static_cast<java_hud&>(*views[id]);
const float scale=m.scale(), font=fonts::k_body_size*scale;
if (!width) {
width=fonts::text_size(fonts::body,font,title).x;
for (const auto& row:values) width=std::max(width,fonts::text_size(fonts::semibold,font,row.c_str()).x);
width=width/scale+2*hud_card::pad_x;
}
const float count=float(values.size()+(*title ? 1:0));
const ImVec2 size{width*scale,hud_card::rows_height(int(std::max(count,1.f)))*scale};
const auto p=place(id,fallback,size);
hud_card::background(draw,p,size,scale,m.background());
draw->PushClipRect(p,{p.x+size.x,p.y+size.y},true);
float y=p.y+hud_card::pad_y*scale;
const float x=p.x+hud_card::pad_x*scale;
if (*title) {
hud_card::text(draw,fonts::body,scale,{x,y},theme::u32(theme::muted()),title,m.background());
y+=20*scale;
}
for (const auto& row:values) {
hud_card::text(draw,fonts::semibold,scale,{x,y},m.color(),row.c_str(),m.background());
y+=20*scale;
}
draw->PopClipRect();
};
const float y0=10+sizes[Watermark].y+5;
one(Fps,{10,y0},"fps",std::to_string(data.fps),"000");
one(Cps,{10,185},"cps",formatted("%d l / %d r",data.leftCps,data.rightCps));
one(Coordinates,{10,515},"xyz",formatted("%.1f %.1f %.1f | %.1f blocks/s",data.position.x,data.position.y,data.position.z,data.speed));
if (hudVisible(ClockHud)) {
SYSTEMTIME now{}; GetLocalTime(&now);
one(ClockHud,{10,220},"time",formatted("%02d:%02d:%02d",now.wHour,now.wMinute,now.wSecond));
}
one(Speed,{10,250},"speed",formatted("%.1f blocks/s",data.speed));
if (sprintStatus) one(ToggleSprint,{10,275},"sprint",data.sprinting ? "active":"ready","active");
if (freelookStatus) one(Freelook,{10,470},"freelook",data.orbiting ? "active":"ready","active");
if (fortressStatus && hudVisible(Fortress)) {
std::string text="enter the nether";
if (data.dimension=="minecraft:the_nether") {
if (data.foundFortress) text=formatted("possible | %.0fm | %.0f %.0f %.0f",(data.fortress-data.position).length(),
data.fortress.x,data.fortress.y,data.fortress.z);
else if (data.scanning) text=formatted("scanning %u%%",data.toScan ? data.scanned*100/data.toScan : 0);
else text="none found nearby";
}
one(Fortress,{10,265},"fortress finder",text);
}
one(Looking,{10,280},"looking at",data.looking.empty() ? "air" : data.looking);
one(EntityCount,{10,310},"entities",formatted("%zu nearby / %zu hostile / %zu players",data.actors.size(),
size_t(std::ranges::count_if(data.actors,[](const Actor& a){return a.monster;})),
size_t(std::ranges::count_if(data.actors,[](const Actor& a){return a.player;}))));
if (hudVisible(Armor)) {
std::vector<std::string> items;
for (auto it=data.armor.rbegin();it!=data.armor.rend();++it) items.push_back(itemLabel(*it));
if (items.empty()) items={"head","chest","legs","feet"};
rows(Armor,{10,345},"armor",items,180);
}
if (hudVisible(Tool)) {
std::vector<std::string> items{itemLabel(data.held)};
if (data.offhand.count) items.push_back("offhand "+itemLabel(data.offhand));
rows(Tool,{10,485},"tool",items);
}
if (hudVisible(Effects)) rows(Effects,{10,610},"status effects",data.effects.empty()?std::vector<std::string>{"none"}:data.effects,180);
if (hudVisible(SoundIndicators)) {
std::vector<std::string> values;
for (auto it=data.sounds.rbegin();it!=data.sounds.rend() && values.size()<4;++it)
values.push_back(it->name+formatted(" | %.0fm",(it->position-data.position).length()));
rows(SoundIndicators,{10,740},"sound indicators",values,230);
}
if (hudVisible(Radar)) {
std::vector<const Actor*> players;
for (const auto& a:data.actors) if (a.player) players.push_back(&a);
std::ranges::sort(players,{},[](const Actor* a){return (a->pos-data.position).length();});
std::vector<std::string> roster;
for (size_t i=0;i<std::min(size_t(10),players.size());++i)
roster.push_back(players[i]->name+formatted(" %.0fm",(players[i]->pos-data.position).length()));
rows(Radar,{10,700},"player radar",roster,180);
}
if (hudVisible(Tab)) {
std::vector<std::string> roster;
for (size_t i=0;i<std::min(size_t(20),data.online.size());++i)
roster.push_back(data.online[i].first+formatted(" %dms",data.online[i].second));
rows(Tab,{330,35},("online "+std::to_string(data.online.size())).c_str(),roster,180);
}
if (hudVisible(Active)) {
std::vector<std::string> names;
for (int i=0;i<ModuleCount;++i) if (i!=Active && java::modules[i].on) names.push_back(views[i]->name());
rows(Active,{screen.x-190,40},"active modules",names,180);
}
if (hudVisible(Compass)) {
constexpr const char* cardinal[]{"s","sw","w","nw","n","ne","e","se"};
auto& m=static_cast<java_hud&>(*views[Compass]);
const float s=m.scale(),w=320,h=57;
const auto origin=place(Compass,{(screen.x-w*s)*.5f,10},{w*s,h*s});
const auto p=[&](float x,float y){return ImVec2(origin.x+x*s,origin.y+y*s);};
hud_card::background(draw,origin,{w*s,h*s},s,m.background());
const auto angle=std::remainder(data.yaw,360.f);
draw->PushClipRect(p(6,2),p(w-6,h-2),true);
for (int i=-7;i<=7;++i) {
const float tick=std::floor(angle/15)*15+15*i,x=w*.5f+(tick-angle)*3.4f;
draw->AddLine(p(x,24),p(x,tick==std::floor(tick/45)*45 ? 31.f:28.f),theme::u32(theme::muted()));
if (tick==std::floor(tick/45)*45) {
const auto* name=cardinal[(int(tick/45)+16)%8];
const auto size=fonts::text_size(fonts::semibold,fonts::k_body_size*s,name);
hud_card::text(draw,fonts::semibold,s,p(x-size.x/s*.5f,8),m.color(),name,m.background());
}
}
draw->AddTriangleFilled(p(w*.5f,33),p(w*.5f-3,38),p(w*.5f+3,38),theme::u32(theme::accent()));
hud_card::text(draw,fonts::body,.78f*s,p(12,40),theme::u32(theme::muted()),formatted("%03.0f",std::fmod(angle+360,360)).c_str(),m.background());
if (const auto point=closestWaypoint()) {
const auto label=point->name+formatted(" %.0fm",(point->pos-data.position).length());
hud_card::text(draw,fonts::body,.8f*s,p(w*.5f,41),m.color(),label.c_str(),m.background());
}
draw->PopClipRect();
}
if (hudVisible(Stats)) {
const auto minutes=std::chrono::duration_cast<std::chrono::minutes>(Clock::now()-data.joined).count();
rows(Stats,{10,650},"session stats",{formatted("%lldm / %.0fm travelled / %d containers",data.inWorld ? minutes : 0,data.distance,data.containers)});
}
if (hudVisible(Diagnostics))
rows(Diagnostics,{screen.x-310,10},"",{formatted("%.2f ms frame %.2f ms java sample",frameMs,updateMs),
formatted("%d fps %zu actors %zu chat %u chunks",data.fps,data.actors.size(),data.chat.size(),data.scanned),data.status});
if (hudVisible(Xp)) {
auto& m=static_cast<java_hud&>(*views[Xp]);
const float s=m.scale(),font=fonts::k_body_size*s;
const int level=data.inWorld ? data.xpLevel:28;
const float progress=data.inWorld ? std::clamp(data.xp,0.f,1.f):.3f;
std::string text=formatted("level %d",level);
if (xpPercent) text+=formatted(" %.1f%%",progress*100);
if (xpRemaining) text+=formatted(" %d XP to go",int(std::ceil((1-progress)*(data.inWorld ? data.xpNext:65))));
const float inner=(xpWidth-24)*s;
fonts::push_font(fonts::semibold,font);
const auto textSize=ImGui::CalcTextSize(text.c_str(),nullptr,false,inner);
ImGui::PopFont();
const ImVec2 size{xpWidth*s,(14+(xpBar ? 16.f:0.f))*s+textSize.y};
auto p=place(Xp,{10,445},size);
if (settings.xpLock) {
static float lift{};
lift+=((data.hotbarTextTicks>0 ? 23.f:0.f)-lift)*(1.f-std::exp(-14*ImGui::GetIO().DeltaTime));
p=hud_editor::constrain({(screen.x-size.x)*.5f,screen.y-size.y-91-lift},size,screen,false,10);
renderPositions[Xp]=p;
}
hud_card::background(draw,p,size,s,m.background());
draw->PushClipRect(p,{p.x+size.x,p.y+size.y},true);
draw->AddText(fonts::semibold,font,{std::floor(p.x+12*s),std::floor(p.y+7*s)},theme::display_color(m.color()),text.c_str(),nullptr,inner);
if (xpBar) theme::accent_bar(draw,{p.x+12*s,p.y+18*s+textSize.y},{p.x+size.x-12*s,p.y+23*s+textSize.y},progress);
draw->PopClipRect();
}
static target_hud_layout::motion motion;
static float opacity{};
if (hudVisible(Target)) {
const bool active=data.targetTime!=Clock::time_point{} && std::chrono::duration<float>(Clock::now()-data.targetTime).count()<=targetLinger;
ImVec2 projected;
const bool show=menu || (active && (!targetFollow || screenPoint(data.target.pos+Vec{0,data.target.height*.5,0},projected)));
opacity=theme::approach(opacity,show ? 1.f:0.f,ImGui::GetIO().DeltaTime*10);
if (opacity>=.01f) {
auto& m=static_cast<java_hud&>(*views[Target]);
const float s=m.scale(),font=fonts::k_body_size*s;
const bool preview=menu && !active;
const bool known=!preview && data.target.maxHp>0;
const auto name=preview || data.target.name.empty() ? "target preview":data.target.name.c_str();
const auto health=known ? formatted("%.0f / %.0f hp | %.1fm",data.target.hp,data.target.maxHp,(data.target.pos-data.position).length()) :
std::string("health unknown | preview");
const float fraction=known ? std::clamp(data.target.hp/data.target.maxHp,0.f,1.f):0;
const float width=std::max({240.f,fonts::text_size(fonts::semibold,font,name).x/s+76,
fonts::text_size(fonts::body,font*.8f,health.c_str()).x/s+68});
const ImVec2 size{width*s,64*s};
auto origin=place(Target,{320,365},size);
if (!menu && targetFollow && show) {
const auto goal=target_hud_layout::follow(projected,size,screen,{targetOffsetX,targetOffsetY},s);
origin=motion.update(goal,data.target.id,ImGui::GetIO().DeltaTime,settings.tracking,targetSwitch);
renderPositions[Target]=origin;
} else if (!menu && targetFollow && motion.valid) origin=motion.position;
else motion.reset();
const auto p=[&](float x,float y){return ImVec2(origin.x+x*s,origin.y+y*s);};
const auto base=ImGui::ColorConvertU32ToFloat4(m.color());
const auto color=theme::u32(theme::with_alpha(base,base.w*opacity));
hud_card::background(draw,origin,size,s,m.background(),opacity);
const auto a=p(10,10),b=p(46,46);
if (!preview && data.target.portrait) {
const ImVec2 crispA{std::round(a.x),std::round(a.y)},crispB{std::round(b.x),std::round(b.y)};
const auto tint=theme::u32({1,1,1,opacity});
draw->AddImage(ImTextureID(data.target.portrait),crispA,crispB,{.125f,.125f},{.25f,.25f},tint);
draw->AddImage(ImTextureID(data.target.portrait),crispA,crispB,{.625f,.125f},{.75f,.25f},tint);
} else {
static std::unordered_map<std::string,target_portraits::picture> portraits;
auto key=preview ? std::string("minecraft:player"):data.target.type;
if (key.starts_with("entity.")) {
key.erase(0,7);
if (auto dot=key.find('.');dot!=std::string::npos) key[dot]=':';
}
if (portraits.size()>256) portraits.clear();
auto [entry,added]=portraits.try_emplace(key);
if (added) entry->second=target_portraits::mob(key);
target_hud_layout::portrait(draw,entry->second,a,36*s,opacity);
}
hud_card::text(draw,fonts::semibold,s,p(56,8),color,name,m.background());
const auto percent=known ? formatted("%.0f%%",fraction*100):"--%";
const auto percentWidth=fonts::text_size(fonts::semibold,font*.7f,percent.c_str()).x/s;
hud_card::text(draw,fonts::semibold,s*.7f,p(width-12-percentWidth,27),color,percent.c_str(),m.background());
if (targetBar) theme::accent_bar(draw,p(56,40),p(width-12,44),fraction,opacity);
hud_card::text(draw,fonts::body,s*.8f,p(56,49),theme::u32(theme::with_alpha(theme::muted(),opacity)),health.c_str(),m.background());
} else motion.reset();
} else { opacity=0; motion.reset(); }
}
void addPoint(Vec pos,const char* name) {
if (!data.inWorld || data.waypoints.size()>=128) return;
data.waypoints.push_back({*name ? name : "waypoint",data.dimension,pos});
modules[Waypoints].on=true;
change();
}
void inventoryDraw() {
auto& ui=inventoryUi;
if (!data.inContainer || !settings.inventoryButtons || !java::modules[InventoryTools].on || capture) {
ui.shown={};
closePicker();
return;
}
const auto screen=ImGui::GetIO().DisplaySize;
ui.buttons={std::clamp(screen.x*settings.inventoryX-156,0.f,std::max(0.f,screen.x-312)),
std::clamp(screen.y*settings.inventoryY,0.f,std::max(0.f,screen.y-28))};
ui.shown=Clock::now();
auto* draw=ImGui::GetForegroundDrawList();
const char* labels[]{"steal","dump","stop"};
for (int i=0;i<(data.containerBusy ? 3:2);++i) {
const ImVec2 at{ui.buttons.x+i*104.f,ui.buttons.y};
hud_card::background(draw,at,{100,26},1,true);
const auto color=theme::u32(!data.containerTransfer || data.containerCursor ? theme::muted():theme::fg());
const auto text=fonts::text_size(fonts::semibold,fonts::k_body_size,labels[i]);
hud_card::text(draw,fonts::semibold,1,{at.x+(100-text.x)*.5f,at.y+(26-text.y)*.5f},color,labels[i],true);
}
if (ui.mode<0) return;
if (ui.epoch!=data.containerEpoch || data.containerCursor) { closePicker(); return; }
const auto& choices=data.inventoryChoices[ui.mode];
ui.visible=std::min(int(choices.size()),std::min(10,std::max(1,int((screen.y-64)/22))));
ui.scroll=std::clamp(ui.scroll,0,std::max(0,int(choices.size())-ui.visible));
ui.pickerSize={264,48.f+22*std::max(1,ui.visible)};
const auto y=ui.buttons.y+32+ui.pickerSize.y<=screen.y ? ui.buttons.y+32:ui.buttons.y-ui.pickerSize.y-6;
ui.picker=hud_editor::constrain({ui.buttons.x+ui.mode*104,y},ui.pickerSize,screen,false,10);
const auto p=ui.picker;
theme::panel(draw,p,{p.x+ui.pickerSize.x,p.y+ui.pickerSize.y});
hud_card::text(draw,fonts::semibold,1,{p.x+12,p.y+7},theme::u32(theme::fg()),ui.mode==0 ? "steal item":"dump item",true);
const auto mouse=ImGui::GetIO().MousePos;
if (choices.empty()) hud_card::text(draw,fonts::body,1,{p.x+12,p.y+31},theme::u32(theme::muted()),"no items available",true);
for (int i=0;i<ui.visible;++i) {
const auto& item=choices[ui.scroll+i];
const float top=p.y+28+22*i;
if (mouse.x>=p.x && mouse.x<p.x+ui.pickerSize.x && mouse.y>=top && mouse.y<top+22)
theme::control(draw,{p.x+4,top},{p.x+ui.pickerSize.x-4,top+21},false,true);
draw->PushClipRect({p.x+12,top},{p.x+ui.pickerSize.x-58,top+22},true);
hud_card::text(draw,fonts::body,1,{p.x+12,top+5},theme::u32(theme::fg()),item.name.c_str(),true);
draw->PopClipRect();
const auto count=std::to_string(item.count);
const auto width=fonts::text_size(fonts::body,fonts::k_body_size,count.c_str()).x;
hud_card::text(draw,fonts::body,1,{p.x+ui.pickerSize.x-12-width,top+5},theme::u32(theme::muted()),count.c_str(),true);
}
hud_card::text(draw,fonts::body,.8f,{p.x+12,p.y+ui.pickerSize.y-16},theme::u32(theme::muted()),
int(choices.size())>ui.visible ? "all matching stacks / wheel to scroll":"transfers all matching stacks",true);
}
void drawChat() {
const auto display=ImGui::GetIO().DisplaySize;
if (display.x<120 || display.y<120) { chat=false; return; }
const float width=std::clamp(chatWidth,100.f,display.x-20.f),height=std::clamp(chatHeight,100.f,display.y-20.f);
ImGui::SetNextWindowPos({10,display.y-height-10});
ImGui::SetNextWindowSize({width,height});
ImGui::SetNextWindowBgAlpha(chatOpacity);
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding,{10,8});
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing,{6,5});
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding,{6,3});
ImGui::Begin("##amnesia_custom_chat",nullptr,ImGuiWindowFlags_NoDecoration|ImGuiWindowFlags_NoMove|
ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_NoNav);
const auto pos=ImGui::GetWindowPos();
ImGui::GetWindowDrawList()->AddRectFilled({pos.x+1,pos.y+1},{pos.x+width-1,pos.y+3},theme::u32(theme::accent()));
ImGui::TextUnformatted("chat");
ImGui::SameLine();
ImGui::TextDisabled("/ enter to send / escape to close");
ImGui::BeginChild("##chat_history",{0,-32});
const bool atBottom=ImGui::GetScrollY()>=ImGui::GetScrollMaxY()-8;
if (data.chat.empty()) ImGui::TextDisabled("messages will appear here");
fonts::push_font(fonts::media,fonts::k_body_size);
ImGui::PushTextWrapPos(0);
for (const auto& msg:data.chat) {
const auto tint=[](const float* c){return ImGui::ColorConvertFloat4ToU32({c[0],c[1],c[2],c[3]});};
const auto end=msg.body.starts_with('<') ? msg.body.find('>'):std::string::npos;
auto text=rich_text::parse(msg.body,tint(end==std::string::npos ? chatSystemColor:chatMessageColor));
if (end!=std::string::npos) rich_text::tint_range(text,1,end,tint(chatNameColor));
rich_text::widget(text);
}
ImGui::PopTextWrapPos();
ImGui::PopFont();
if (atBottom || chatScroll) { ImGui::SetScrollHereY(1); chatScroll=false; }
ImGui::EndChild();
if (std::exchange(chatFocus,false)) ImGui::SetKeyboardFocusHere();
ImGui::SetNextItemWidth(std::max(40.f,ImGui::GetContentRegionAvail().x-66));
fonts::push_font(fonts::media,fonts::k_body_size);
const auto history=[](ImGuiInputTextCallbackData* entry) {
const auto text=sentHistory.move(entry->EventKey==ImGuiKey_UpArrow ? -1:1,entry->Buf);
entry->DeleteChars(0,entry->BufTextLen);
entry->InsertChars(0,text.c_str());
return 0;
};
const bool enter=ImGui::InputTextWithHint("##chat_message","message or /command",chatInput,sizeof(chatInput),
ImGuiInputTextFlags_EnterReturnsTrue|ImGuiInputTextFlags_CallbackHistory,history);
ImGui::PopFont();
ImGui::SameLine();
if ((ImGui::Button("send",{60,0}) || enter) && chat_logic::valid_submission(chatInput)) {
sentHistory.remember(chatInput);
submit(chatInput);
chatInput[0]=0;
closeRequested=true;
}
ImGui::End();
ImGui::PopStyleVar(3);
}
bool drawIcon(ImDrawList* draw,ImVec2 at,float size,float alpha) {
if (!customIcon) return false;
const auto aspect=iconAspect;
const ImVec2 bounds{aspect>=1 ? size:size*aspect,aspect>=1 ? size/aspect:size};
at={std::round(at.x+(size-bounds.x)*.5f),std::round(at.y+(size-bounds.y)*.5f)};
draw->AddImage(ImTextureID(customIcon.Get()),at,{at.x+bounds.x,at.y+bounds.y},{0,0},{1,1},theme::u32({1,1,1,alpha}));
return true;
}
void updateIcon() {
theme::custom_icon=&drawIcon;
if (loadedIcon==theme::current.icon_path && iconRevision==theme::current.icon_revision) return;
loadedIcon=theme::current.icon_path; iconRevision=theme::current.icon_revision;
customIcon.Reset(); theme_assets::last_error.clear();
if (loadedIcon.empty()) return;
std::ifstream file(client_files::path(loadedIcon),std::ios::binary|std::ios::ate);
const auto length=file ? file.tellg():std::streampos(-1);
if (length<=0 || length>4*1024*1024) { theme_assets::last_error="icon could not be loaded; choose an image up to 4 mb"; return; }
std::vector<unsigned char> bytes(static_cast<size_t>(length));
file.seekg(0);
if (!file.read(reinterpret_cast<char*>(bytes.data()),std::streamsize(length))) { theme_assets::last_error="icon could not be read"; return; }
const HRESULT result=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
const auto image=media::decode_art(bytes);
if (SUCCEEDED(result)) CoUninitialize();
if (!image) { theme_assets::last_error="unsupported or damaged icon image"; return; }
iconAspect=float(image->width)/image->height;
customIcon.upload(image->width,image->height,image->rgba.data());
}
} // namespace
bool start(HWND window) {
hwnd=window;
g_game_window=window;
context=ImGui::CreateContext();
ImGui::SetCurrentContext(context);
if (!ImGui_ImplWin32_Init(hwnd)) { ImGui::DestroyContext(context); context=nullptr; return false; }
if (!ImGui_ImplOpenGL3_Init("#version 150")) {
ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext(context); context=nullptr;
return false;
}
if (!SetWindowSubclass(hwnd,procedure,subclass,0)) {
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext(context); context=nullptr;
return false;
}
initViews();
initConfig();
gui().init();
license=new licensing::service(licensing::fingerprint,std::chrono::seconds(60),java_ui_credential());
license->start();
account_ui::load_config();
startup_intro::loading_stage=startup_intro::stage::ready;
return true;
}
void draw(JNIEnv* env) {
ImGui::SetCurrentContext(context);
const auto now=Clock::now();
if (frameStart!=Clock::time_point{}) frameMs+=.10*(std::chrono::duration<double,std::milli>(now-frameStart).count()-frameMs);
frameStart=now;
static bool previousLicense;
if (license) account=license->latest();
const bool allowed=account.allowed();
if (previousLicense && !allowed) {
restoreFeatures(env);
stopTransfer();
musicView->set_enabled(false);
gui().close();
account_ui::dismissed=false;
}
previousLicense=allowed;
const bool intro=!startup_intro::animation.finished;
const bool shift=std::exchange(pendingMenu,false);
if (shift && !intro) {
if (!allowed) account_ui::dismissed=!account_ui::dismissed;
else if (menu) gui().close();
else gui().open();
chat=false;
}
if (std::exchange(pendingChat,false) && allowed && !intro) {
chat=chatFocus=chatScroll=true;
sentHistory.reset();
gui().close();
}
if (std::exchange(escapeRequested,false)) {
if (chat) chat=false;
else if (account_ui::requested || !allowed) { account_ui::requested=false; account_ui::dismissed=true; }
else gui().escape();
}
if (std::exchange(closeRequested,false) || (!allowed && chat)) {
gui().close(); chat=false;
account_ui::requested=false;
if (!allowed && capture) account_ui::dismissed=true;
}
bool showAccount=!intro && (allowed ? account_ui::requested:!account_ui::dismissed);
const bool wanted=menu || chat || showAccount;
if (capture!=wanted) {
capture=wanted;
mouse(env,capture);
}
if (allowed && !intro) {
for (int i=0;i<ModuleCount;++i) {
auto& view=*views[i];
view.set_enabled(java::modules[i].on);
view.update_key(capture || !data.inWorld || data.inScreen);
if (java::modules[i].on!=view.enabled()) {
java::modules[i].on=view.enabled();
if (i==Fortress && view.enabled()) requestFortress();
change();
}
}
setChatHidden(settings.hideChat);
const auto begin=Clock::now();
update(env,GetForegroundWindow()==hwnd,capture);
updateMs+=.1*(std::chrono::duration<double,std::milli>(Clock::now()-begin).count()-updateMs);
}
if (dirty && now>=nextSave) save();
GlState graphics;
fonts::apply_selection();
updateIcon();
theme::apply();
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
if (intro) {
startup_intro::initialize_texture();
startup_intro::draw(true,shift,account.username.c_str());
} else if (allowed) {
gui().update();
if (data.inWorld && !data.inScreen && !capture && !data.guiHidden) { worldDraw(); crosshair(); }
gui().draw_backdrop();
huds();
if (menu) {
const auto profile=activeProfile;
const auto before=uiState();
const auto originalPositions=renderPositions;
gui().draw();
if (activeProfile==profile) {
for (int i=0;i<ModuleCount;++i) {
auto& view=*views[i];
if (view.enabled()!=java::modules[i].on) {
java::modules[i].on=view.enabled();
if (i==Fortress && view.enabled()) requestFortress();
change();
}
if (view.is_hud() && sizes[i].x>0 && !(i==Xp && settings.xpLock) &&
(view.hud_pos.x!=originalPositions[i].x || view.hud_pos.y!=originalPositions[i].y)) {
positions[i]=view.hud_pos;
hasPosition[i]=true; centerX[i]=centerY[i]=false;
change();
}
}
mirror(false);
if (before!=uiState()) change();
}
} else gui().draw();
if (chat) drawChat();
inventoryDraw();
showAccount=account_ui::requested;
}
if (showAccount) account_ui::draw(allowed);
if (!intro) notifications::draw();
CURSORINFO cursor{sizeof(cursor)};
ImGui::GetIO().MouseDrawCursor=capture && !(GetCursorInfo(&cursor) && (cursor.flags&CURSOR_SHOWING));
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
bindingKey=0;
static bool firstMenu=true;
if ((menu || showAccount) && std::exchange(firstMenu,false)) diagnostic("rendered the shared Bedrock interface");
static bool firstLicensedMenu=true,firstEditor=true;
if (menu && allowed && std::exchange(firstLicensedMenu,false)) diagnostic("rendered the licensed ClickGUI");
if (menu && allowed && gui().editing_hud() && std::exchange(firstEditor,false)) diagnostic("rendered the HUD editor");
}
void addNote(std::string title,std::string body) {
const auto kind=title=="durability" || title.starts_with("low ") ? notifications::kind::warning:notifications::kind::info;
const bool chatNote=title=="chat" || title=="system";
std::vector<rich_text::run> runs;
if (chatNote) {
const auto tint=[](const float* c){return ImGui::ColorConvertFloat4ToU32({c[0],c[1],c[2],c[3]});};
runs=rich_text::parse(body,tint(title=="chat" ? chatMessageColor:chatSystemColor));
const auto end=body.starts_with('<') ? body.find('>'):std::string::npos;
if (end!=std::string::npos) rich_text::tint_range(runs,1,end,tint(chatNameColor));
runs=rich_text::shorten(runs,280);
}
notifications::push(std::move(title),std::move(body),kind,chatNote ? 4:3,{},-1,std::move(runs),chatNote);
}
void cleanup(JNIEnv*) {
save();
RemoveWindowSubclass(hwnd,procedure,subclass);
ImGui::SetCurrentContext(context);
if (musicView) musicView->release_texture();
customIcon.Reset();
startup_intro::texture.Reset();
theme::custom_icon=nullptr;
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext(context);
fonts::forget();
context=nullptr;
}
void stopWorkers() {
if (license) { license->stop(); delete license; license=nullptr; }
lyrics::shutdown();
media::shutdown();
}
} // namespace java::overlay
java_ui_modules& modules() { return java::overlay::adapters; }
java_ui_profiles& profiles() { static java_ui_profiles storage; return storage; }
licensing::service& java_ui_account_service() { return *java::overlay::license; }
const wchar_t* java_ui_credential() { return java::overlay::credentialTarget.c_str(); }
std::filesystem::path java_ui_account_path() {
const auto& dir=java::overlay::dir;
return dir.empty() ? std::filesystem::path{} : dir/"licensing.ini";
}
bool java_ui_binding_key(int key) { return java::overlay::bindingKey==key && key!=VK_RSHIFT; }
bool input::ui_open() { return java::overlay::capture; }
void java_ui_module_extra(module& view,float width) {
using namespace java;
using namespace java::overlay;
if (&view==views[Waypoints]) {
for (size_t i=0;i<data.waypoints.size();) {
ImGui::PushID(int(i));
const auto& p=data.waypoints[i];
ImGui::TextWrapped("%s / %s\n%.0f %.0f %.0f",p.name.c_str(),p.dimension.c_str(),p.pos.x,p.pos.y,p.pos.z);
const bool remove=widgets::button("##remove","remove",false,width,22);
ImGui::PopID();
if (remove) { data.waypoints.erase(data.waypoints.begin()+i); change(); }
else ++i;
}
} else if (&view==views[Fortress]) {
if (data.scanning) ImGui::TextDisabled("%u / %u chunks",data.scanned,data.toScan);
else if (data.dimension!="minecraft:the_nether") ImGui::TextDisabled("enter the nether to scan");
} else if (&view==views[InventoryTools] && !data.inContainer) ImGui::TextDisabled("open a container to transfer items");
else if (&view==views[FriendsLocator]) ImGui::TextDisabled("%s",data.realm ? "realm connection detected":"only active in a mojang realm");
}
const std::string& java_ui_profiles::active() const { return java::overlay::activeProfile; }
const std::string& java_ui_profiles::last_error() const { return java::overlay::profileError; }
bool java_ui_profiles::blocked() const { return !last_error().empty(); }
bool java_ui_profiles::dirty() const { return java::overlay::dirty; }
void java_ui_profiles::refresh() const {}
void java_ui_profiles::save() { java::overlay::change(); java::overlay::save(); }
void java_ui_profiles::switch_to(const std::string& name) {
if (name!=active()) java::overlay::switchProfile(name,false);
}
std::vector<std::string> java_ui_profiles::names() const {
using namespace java::overlay;
std::vector<std::string> values{"default"};
if (dir.empty()) return values;
std::error_code error;
for (std::filesystem::directory_iterator it(dir,error),end;it!=end && !error;it.increment(error)) {
if (it->path().extension()!=".profile") continue;
const auto name=it->path().stem().string();
if (name!="default" && validProfile(name)) values.push_back(name);
}
std::ranges::sort(values);
return values;
}
bool java_ui_profiles::create(const std::string& name) {
using namespace java::overlay;
const auto list=names();
if (std::ranges::any_of(list,[&](const auto& item){return _stricmp(item.c_str(),name.c_str())==0;})) {
profileError="that profile already exists";
return false;
}
return switchProfile(name,true);
}
bool java_ui_profiles::rename(const std::string& name) {
using namespace java::overlay;
if (active()=="default") { profileError="default is protected"; return false; }
const auto old=profilePath();
if (!create(name)) return false;
std::error_code error;
std::filesystem::remove(old,error);
if (error) { profileError="copied profile, but the old file could not be removed"; return false; }
return true;
}
bool java_ui_profiles::remove_active() {
using namespace java::overlay;
if (active()=="default") { profileError="default is protected"; return false; }
const auto old=profilePath();
if (!switchProfile("default",false)) return false;
std::error_code error;
std::filesystem::remove(old,error);
if (error) { profileError="profile file could not be removed"; return false; }
return true;
}
void java::tell(std::string title,std::string body) { overlay::addNote(std::move(title),std::move(body)); }