This commit is contained in:
Fazri Gading
2026-01-20 19:37:54 +08:00
15 changed files with 1418 additions and 517 deletions

View File

@@ -17,7 +17,6 @@ jobs:
with: with:
node-version: '22' node-version: '22'
cache: 'npm' cache: 'npm'
- run: npm install
- run: npm ci - run: npm ci
- run: npx electron-builder --linux --publish never - run: npx electron-builder --linux --publish never
- uses: actions/upload-artifact@v4 - uses: actions/upload-artifact@v4
@@ -35,7 +34,6 @@ jobs:
with: with:
node-version: '22' node-version: '22'
cache: 'npm' cache: 'npm'
- run: npm install
- run: npm ci - run: npm ci
- run: npx electron-builder --win --publish never - run: npx electron-builder --win --publish never
- uses: actions/upload-artifact@v4 - uses: actions/upload-artifact@v4
@@ -52,7 +50,6 @@ jobs:
with: with:
node-version: '22' node-version: '22'
cache: 'npm' cache: 'npm'
- run: npm install
- run: npm ci - run: npm ci
- run: npx electron-builder --mac --publish never - run: npx electron-builder --mac --publish never
- uses: actions/upload-artifact@v4 - uses: actions/upload-artifact@v4
@@ -66,7 +63,7 @@ jobs:
release: release:
needs: [build-linux, build-windows, build-macos] needs: [build-linux, build-windows, build-macos]
runs-on: ubuntu-latest runs-on: ubuntu-latest
if: startsWith(github.ref, 'refs/tags/v') if: startsWith(github.ref, 'refs/tags/v') || github.event_name == 'workflow_dispatch'
permissions: permissions:
contents: write contents: write
@@ -83,10 +80,14 @@ jobs:
- name: Create Release - name: Create Release
uses: softprops/action-gh-release@v2 uses: softprops/action-gh-release@v2
with: with:
tag_name: ${{ github.ref_type == 'tag' && github.ref_name || format('manual-{0}', github.sha) }}
name: ${{ github.ref_type == 'tag' && github.ref_name || format('Manual build {0}', github.sha) }}
files: | files: |
artifacts/linux-builds/* artifacts/linux-builds/**/*
artifacts/windows-builds/* artifacts/windows-builds/**/*
artifacts/macos-builds/* artifacts/macos-builds/**/*
generate_release_notes: true generate_release_notes: true
draft: false draft: false
prerelease: false prerelease: false

1
.gitignore vendored
View File

@@ -1,3 +1,4 @@
dist/* dist/*
node_modules/* node_modules/*
package-lock.json package-lock.json
bun.lock

View File

@@ -1,25 +1,32 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hytale F2P Launcher</title> <title>Hytale F2P Launcher</title>
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500;600;700&display=swap" rel="stylesheet"> <link
<link rel="stylesheet" href="style.css"> href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500;600;700&display=swap"
rel="stylesheet">
<link rel="stylesheet" href="style.css">
</head> </head>
<body class="bg-black text-white overflow-hidden font-sans select-none" tabindex="-1"> <body class="bg-black text-white overflow-hidden font-sans select-none" tabindex="-1">
<div class="absolute inset-0 z-0"> <div class="absolute inset-0 z-0">
<img src="https://i.imgur.com/Visrk66.png" alt="Background" class="w-full h-full object-cover" /> <img src="https://i.imgur.com/Visrk66.png" alt="Background" class="w-full h-full object-cover" />
<div class="absolute inset-0 bg-black/60"></div> <div class="absolute inset-0 bg-black/60"></div>
<div class="absolute inset-0 bg-[url('data:image/svg+xml,%3Csvg viewBox="0 0 256 256" xmlns="http://www.w3.org/2000/svg"%3E%3Cfilter id="noiseFilter"%3E%3CfeTurbulence type="fractalNoise" baseFrequency="0.65" numOctaves="3" stitchTiles="stitch"/%3E%3C/filter%3E%3Crect width="100%25" height="100%25" filter="url(%23noiseFilter)" opacity="0.1"/%3E%3C/svg%3E')] opacity-20"></div> <div class="absolute inset-0 bg-[url('data:image/svg+xml,%3Csvg viewBox=" 0 0 256 256"
xmlns="http://www.w3.org/2000/svg" %3E%3Cfilter id="noiseFilter" %3E%3CfeTurbulence type="fractalNoise"
baseFrequency="0.65" numOctaves="3" stitchTiles="stitch" /%3E%3C/filter%3E%3Crect width="100%25"
height="100%25" filter="url(%23noiseFilter)" opacity="0.1" /%3E%3C/svg%3E')] opacity-20"></div>
</div> </div>
<div class="flex w-full h-screen relative z-10"> <div class="flex w-full h-screen relative z-10">
<nav class="sidebar"> <nav class="sidebar">
<div class="sidebar-logo"> <div class="sidebar-logo">
<img src="./icon.png" alt="Hytale Logo" /> <img src="./icon.png" alt="Hytale Logo" />
</div> </div>
@@ -50,7 +57,7 @@
</div> </div>
</div> </div>
</nav> </nav>
<main class="main-content"> <main class="main-content">
@@ -61,6 +68,24 @@
<span id="onlineCount" class="counter-value">0</span> <span id="onlineCount" class="counter-value">0</span>
</div> </div>
<div class="profile-selector" id="profileSelector">
<button class="profile-btn" onclick="toggleProfileDropdown()">
<i class="fas fa-user-circle"></i>
<span id="currentProfileName">Default</span>
<i class="fas fa-chevron-down"></i>
</button>
<div class="profile-dropdown" id="profileDropdown">
<div class="profile-list" id="profileList">
<!-- Profiles populated by JS -->
</div>
<div class="profile-divider"></div>
<div class="profile-action" onclick="openProfileManager()">
<i class="fas fa-cog"></i>
<span>Manage Profiles</span>
</div>
</div>
</div>
<div class="window-controls"> <div class="window-controls">
<button class="control-btn minimize" onclick="window.electronAPI?.minimizeWindow()"> <button class="control-btn minimize" onclick="window.electronAPI?.minimizeWindow()">
<i class="fas fa-minus"></i> <i class="fas fa-minus"></i>
@@ -89,24 +114,26 @@
</h1> </h1>
<p class="install-subtitle">FREE TO PLAY LAUNCHER</p> <p class="install-subtitle">FREE TO PLAY LAUNCHER</p>
</div> </div>
<div class="install-form"> <div class="install-form">
<div class="form-group"> <div class="form-group">
<label class="form-label">Player Name</label> <label class="form-label">Player Name</label>
<input type="text" id="installPlayerName" placeholder="Enter your name" class="form-input" value="Player" /> <input type="text" id="installPlayerName" placeholder="Enter your name"
class="form-input" value="Player" />
</div> </div>
<div class="form-group"> <div class="form-group">
<label class="checkbox-group"> <label class="checkbox-group">
<input type="checkbox" id="installCustomCheck" class="custom-checkbox"> <input type="checkbox" id="installCustomCheck" class="custom-checkbox">
<span class="checkbox-label">Custom Installation</span> <span class="checkbox-label">Custom Installation</span>
</label> </label>
<div id="installCustomOptions" class="custom-options"> <div id="installCustomOptions" class="custom-options">
<div class="form-subgroup"> <div class="form-subgroup">
<label class="form-label">Installation Folder</label> <label class="form-label">Installation Folder</label>
<div class="input-with-button"> <div class="input-with-button">
<input type="text" id="installPath" placeholder="Default location" class="form-input" readonly /> <input type="text" id="installPath" placeholder="Default location"
class="form-input" readonly />
<button onclick="browseInstallPath()" class="browse-btn"> <button onclick="browseInstallPath()" class="browse-btn">
<i class="fas fa-folder-open"></i> <i class="fas fa-folder-open"></i>
</button> </button>
@@ -114,7 +141,7 @@
</div> </div>
</div> </div>
</div> </div>
<button id="installBtn" class="install-button" onclick="installGame()"> <button id="installBtn" class="install-button" onclick="installGame()">
<i class="fas fa-download mr-2"></i> <i class="fas fa-download mr-2"></i>
<span id="installText">INSTALL HYTALE</span> <span id="installText">INSTALL HYTALE</span>
@@ -134,7 +161,7 @@
</h2> </h2>
<p class="play-subtitle">Launch Hytale and enter the adventure</p> <p class="play-subtitle">Launch Hytale and enter the adventure</p>
</div> </div>
<button id="homePlayBtn" class="home-play-button" onclick="launch()"> <button id="homePlayBtn" class="home-play-button" onclick="launch()">
<i class="fas fa-play"></i> <i class="fas fa-play"></i>
<span>PLAY HYTALE</span> <span>PLAY HYTALE</span>
@@ -216,21 +243,17 @@
</div> </div>
</div> </div>
</div> </div>
<div class="chat-body"> <div class="chat-body">
<div id="chatMessages" class="chat-messages"> <div id="chatMessages" class="chat-messages">
</div> </div>
</div> </div>
<div class="chat-footer"> <div class="chat-footer">
<div class="chat-input-container"> <div class="chat-input-container">
<textarea <textarea id="chatInput" class="chat-input"
id="chatInput" placeholder="Type your message... (Links are automatically censored)" rows="1"
class="chat-input" maxlength="500"></textarea>
placeholder="Type your message... (Links are automatically censored)"
rows="1"
maxlength="500"
></textarea>
<button id="chatSendBtn" class="chat-send-btn"> <button id="chatSendBtn" class="chat-send-btn">
<i class="fas fa-paper-plane"></i> <i class="fas fa-paper-plane"></i>
</button> </button>
@@ -254,36 +277,32 @@
SETTINGS SETTINGS
</h2> </h2>
</div> </div>
<div class="settings-content"> <div class="settings-content">
<div class="settings-section"> <div class="settings-section">
<h3 class="settings-section-title"> <h3 class="settings-section-title">
<i class="fas fa-coffee"></i> <i class="fas fa-coffee"></i>
Java Runtime Java Runtime
</h3> </h3>
<div class="settings-option"> <div class="settings-option">
<label class="settings-checkbox"> <label class="settings-checkbox">
<input type="checkbox" id="customJavaCheck" /> <input type="checkbox" id="customJavaCheck" />
<span class="checkmark"></span> <span class="checkmark"></span>
<div class="checkbox-content"> <div class="checkbox-content">
<div class="checkbox-title">Use Custom Java Path</div> <div class="checkbox-title">Use Custom Java Path</div>
<div class="checkbox-description">Override the bundled Java runtime with your own installation</div> <div class="checkbox-description">Override the bundled Java runtime with
your own installation</div>
</div> </div>
</label> </label>
</div> </div>
<div id="customJavaOptions" class="custom-java-options" style="display: none;"> <div id="customJavaOptions" class="custom-java-options" style="display: none;">
<div class="settings-input-group"> <div class="settings-input-group">
<label class="settings-input-label">Java Executable Path</label> <label class="settings-input-label">Java Executable Path</label>
<div class="settings-input-with-button"> <div class="settings-input-with-button">
<input <input type="text" id="customJavaPath" class="settings-input"
type="text" placeholder="Select Java path..." readonly />
id="customJavaPath"
class="settings-input"
placeholder="Select Java path..."
readonly
/>
<button id="browseJavaBtn" class="settings-browse-btn"> <button id="browseJavaBtn" class="settings-browse-btn">
<i class="fas fa-folder-open"></i> <i class="fas fa-folder-open"></i>
Browse Browse
@@ -302,14 +321,15 @@
<i class="fab fa-discord"></i> <i class="fab fa-discord"></i>
Discord Integration Discord Integration
</h3> </h3>
<div class="settings-option"> <div class="settings-option">
<label class="settings-checkbox"> <label class="settings-checkbox">
<input type="checkbox" id="discordRPCCheck" checked /> <input type="checkbox" id="discordRPCCheck" checked />
<span class="checkmark"></span> <span class="checkmark"></span>
<div class="checkbox-content"> <div class="checkbox-content">
<div class="checkbox-title">Enable Discord Rich Presence</div> <div class="checkbox-title">Enable Discord Rich Presence</div>
<div class="checkbox-description">Show your launcher activity on Discord</div> <div class="checkbox-description">Show your launcher activity on Discord
</div>
</div> </div>
</label> </label>
</div> </div>
@@ -320,27 +340,23 @@
<i class="fas fa-gamepad"></i> <i class="fas fa-gamepad"></i>
Game Options Game Options
</h3> </h3>
<div class="settings-option"> <div class="settings-option">
<div class="settings-input-group"> <div class="settings-input-group">
<label class="settings-input-label">Player Name</label> <label class="settings-input-label">Player Name</label>
<input <input type="text" id="settingsPlayerName" class="settings-input"
type="text" placeholder="Enter your player name" maxlength="16" />
id="settingsPlayerName"
class="settings-input"
placeholder="Enter your player name"
maxlength="16"
/>
<p class="settings-hint"> <p class="settings-hint">
<i class="fas fa-user"></i> <i class="fas fa-user"></i>
This name will be used in-game (1-16 characters) This name will be used in-game (1-16 characters)
</p> </p>
</div> </div>
</div> </div>
<div class="settings-option"> <div class="settings-option">
<div class="settings-button-group"> <div class="settings-button-group">
<button id="openGameLocationBtn" class="settings-action-btn" onclick="openGameLocation()"> <button id="openGameLocationBtn" class="settings-action-btn"
onclick="openGameLocation()">
<i class="fas fa-folder-open"></i> <i class="fas fa-folder-open"></i>
<div class="btn-content"> <div class="btn-content">
<div class="btn-title">Open Game Location</div> <div class="btn-title">Open Game Location</div>
@@ -356,22 +372,18 @@
<i class="fas fa-fingerprint"></i> <i class="fas fa-fingerprint"></i>
Player UUID Management Player UUID Management
</h3> </h3>
<div class="settings-option"> <div class="settings-option">
<div class="settings-input-group"> <div class="settings-input-group">
<label class="settings-input-label">Current UUID</label> <label class="settings-input-label">Current UUID</label>
<div class="uuid-display-container"> <div class="uuid-display-container">
<input <input type="text" id="currentUuid" class="settings-input uuid-input"
type="text" readonly placeholder="Loading UUID..." />
id="currentUuid"
class="settings-input uuid-input"
readonly
placeholder="Loading UUID..."
/>
<button id="copyUuidBtn" class="uuid-btn copy-btn" title="Copy UUID"> <button id="copyUuidBtn" class="uuid-btn copy-btn" title="Copy UUID">
<i class="fas fa-copy"></i> <i class="fas fa-copy"></i>
</button> </button>
<button id="regenerateUuidBtn" class="uuid-btn regenerate-btn" title="Generate New UUID"> <button id="regenerateUuidBtn" class="uuid-btn regenerate-btn"
title="Generate New UUID">
<i class="fas fa-sync-alt"></i> <i class="fas fa-sync-alt"></i>
</button> </button>
</div> </div>
@@ -458,14 +470,8 @@
</p> </p>
<div class="chat-username-input-group"> <div class="chat-username-input-group">
<label for="chatUsernameInput" class="chat-username-label">Username</label> <label for="chatUsernameInput" class="chat-username-label">Username</label>
<input <input type="text" id="chatUsernameInput" class="chat-username-input"
type="text" placeholder="Enter your username..." maxlength="20" autocomplete="off" />
id="chatUsernameInput"
class="chat-username-input"
placeholder="Enter your username..."
maxlength="20"
autocomplete="off"
/>
<span class="chat-username-hint">3-20 characters, letters, numbers, - and _ only</span> <span class="chat-username-hint">3-20 characters, letters, numbers, - and _ only</span>
<span id="chatUsernameError" class="chat-username-error"></span> <span id="chatUsernameError" class="chat-username-error"></span>
</div> </div>
@@ -495,7 +501,7 @@
<i class="fas fa-times"></i> <i class="fas fa-times"></i>
</button> </button>
</div> </div>
<div class="uuid-modal-body"> <div class="uuid-modal-body">
<div class="uuid-current-section"> <div class="uuid-current-section">
<h3 class="uuid-section-title">Current User UUID</h3> <h3 class="uuid-section-title">Current User UUID</h3>
@@ -504,7 +510,8 @@
<button id="modalCopyUuidBtn" class="uuid-action-btn copy-btn" title="Copy UUID"> <button id="modalCopyUuidBtn" class="uuid-action-btn copy-btn" title="Copy UUID">
<i class="fas fa-copy"></i> <i class="fas fa-copy"></i>
</button> </button>
<button id="modalRegenerateUuidBtn" class="uuid-action-btn regenerate-btn" title="Generate New UUID"> <button id="modalRegenerateUuidBtn" class="uuid-action-btn regenerate-btn"
title="Generate New UUID">
<i class="fas fa-sync-alt"></i> <i class="fas fa-sync-alt"></i>
</button> </button>
</div> </div>
@@ -529,13 +536,9 @@
<div class="uuid-custom-section"> <div class="uuid-custom-section">
<h3 class="uuid-section-title">Set Custom UUID</h3> <h3 class="uuid-section-title">Set Custom UUID</h3>
<div class="uuid-custom-form"> <div class="uuid-custom-form">
<input <input type="text" id="customUuidInput" class="uuid-input"
type="text"
id="customUuidInput"
class="uuid-input"
placeholder="Enter custom UUID (format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)" placeholder="Enter custom UUID (format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)"
maxlength="36" maxlength="36" />
/>
<button id="setCustomUuidBtn" class="uuid-set-btn"> <button id="setCustomUuidBtn" class="uuid-set-btn">
<i class="fas fa-check"></i> <i class="fas fa-check"></i>
Set UUID Set UUID
@@ -550,27 +553,64 @@
</div> </div>
</div> </div>
<!-- Profile Manager Modal -->
<div id="profileManagerModal" class="profile-modal" style="display: none;">
<div class="profile-modal-content">
<div class="profile-modal-header">
<h2 class="profile-modal-title">
<i class="fas fa-users-cog mr-2"></i>
Manage Profiles
</h2>
<button class="modal-close-btn" onclick="closeProfileManager()">
<i class="fas fa-times"></i>
</button>
</div>
<div class="profile-modal-body">
<div class="profile-manager-list" id="managerProfileList">
<!-- Populated by JS -->
</div>
<div class="profile-create-section">
<input type="text" id="newProfileName" placeholder="New Profile Name" class="profile-input"
maxlength="20">
<button class="profile-create-btn" onclick="createNewProfile()">
<i class="fas fa-plus"></i> Create Profile
</button>
</div>
</div>
</div>
</div>
<footer class="fixed bottom-0 left-0 right-0 z-50 bg-black/80 backdrop-blur-sm px-4 py-2"> <footer class="fixed bottom-0 left-0 right-0 z-50 bg-black/80 backdrop-blur-sm px-4 py-2">
<div class="flex items-center justify-center text-xs text-gray-400"> <div class="flex items-center justify-center text-xs text-gray-400">
<span>Made by <a href="https://github.com/amiayweb" target="_blank" class="text-blue-400 hover:text-blue-300 transition-colors">@amiayweb</a> & <a href="https://github.com/Relyz1993" target="_blank" class="text-blue-400 hover:text-blue-300 transition-colors">@Relyz</a></span> <span>Made by <a href="https://github.com/amiayweb" target="_blank"
class="text-blue-400 hover:text-blue-300 transition-colors">@amiayweb</a> & <a
href="https://github.com/Relyz1993" target="_blank"
class="text-blue-400 hover:text-blue-300 transition-colors">@Relyz</a></span>
<span class="mx-2">|</span> <span class="mx-2">|</span>
<span>Contributors: <span>Contributors:
<a href="https://github.com/chasem-dev" target="_blank" class="text-blue-400 hover:text-blue-300 transition-colors">@chasem-dev</a>, <a href="https://github.com/chasem-dev" target="_blank"
<a href="https://github.com/crimera" target="_blank" class="text-blue-400 hover:text-blue-300 transition-colors">@crimera</a>, class="text-blue-400 hover:text-blue-300 transition-colors">@chasem-dev</a>,
<a href="https://github.com/sanasol" target="_blank" class="text-blue-400 hover:text-blue-300 transition-colors">@sanasol</a>, <a href="https://github.com/crimera" target="_blank"
<a href="https://github.com/Terromur" target="_blank" class="text-blue-400 hover:text-blue-300 transition-colors">@terromur</a>, class="text-blue-400 hover:text-blue-300 transition-colors">@crimera</a>,
<a href="https://github.com/ericiskoolbeans" target="_blank" class="text-blue-400 hover:text-blue-300 transition-colors">@ericiskoolbeans</a>, <a href="https://github.com/sanasol" target="_blank"
<a href="https://github.com/fazrigading" target="_blank" class="text-blue-400 hover:text-blue-300 transition-colors">@fazrigading</a> class="text-blue-400 hover:text-blue-300 transition-colors">@sanasol</a>,
<a href="https://github.com/Terromur" target="_blank"
class="text-blue-400 hover:text-blue-300 transition-colors">@terromur</a>,
<a href="https://github.com/ericiskoolbeans" target="_blank"
class="text-blue-400 hover:text-blue-300 transition-colors">@ericiskoolbeans</a>,
<a href="https://github.com/fazrigading" target="_blank"
class="text-blue-400 hover:text-blue-300 transition-colors">@fazrigading</a>
</span> </span>
</div> </div>
</footer> </footer>
<script type="module" src="js/script.js"></script> <!-- Discord Notification --> <script type="module" src="js/script.js"></script> <!-- Discord Notification -->
<div id="discordNotification" class="discord-notification"> <div id="discordNotification" class="discord-notification">
<div class="notification-content"> <div class="notification-content">
<i class="fab fa-discord"></i> <i class="fab fa-discord"></i>
<span class="notification-text">Join our Discord community!</span> <span class="notification-text">Join our Discord community!</span>
<button class="notification-action" onclick="window.electronAPI?.openExternal('https://discord.gg/n6HZ7NwSQd')"> <button class="notification-action"
onclick="window.electronAPI?.openExternal('https://discord.gg/n6HZ7NwSQd')">
Join Discord Join Discord
</button> </button>
</div> </div>
@@ -625,4 +665,4 @@
<script type="module" src="js/update.js"></script> <script type="module" src="js/update.js"></script>
</body> </body>
</html> </html>

View File

@@ -14,15 +14,15 @@ export function setupLauncher() {
uninstallBtn = document.getElementById('uninstallBtn'); uninstallBtn = document.getElementById('uninstallBtn');
playerNameInput = document.getElementById('playerName'); playerNameInput = document.getElementById('playerName');
javaPathInput = document.getElementById('javaPath'); javaPathInput = document.getElementById('javaPath');
if (playerNameInput) { if (playerNameInput) {
playerNameInput.addEventListener('change', savePlayerName); playerNameInput.addEventListener('change', savePlayerName);
} }
if (javaPathInput) { if (javaPathInput) {
javaPathInput.addEventListener('change', saveJavaPath); javaPathInput.addEventListener('change', saveJavaPath);
} }
if (window.electronAPI && window.electronAPI.onProgressUpdate) { if (window.electronAPI && window.electronAPI.onProgressUpdate) {
window.electronAPI.onProgressUpdate((data) => { window.electronAPI.onProgressUpdate((data) => {
if (!isDownloading) return; if (!isDownloading) return;
@@ -31,43 +31,207 @@ export function setupLauncher() {
} }
}); });
} }
if (window.electronAPI && window.electronAPI.onProgressUpdate) {
window.electronAPI.onProgressUpdate((data) => {
if (!isDownloading) return;
if (window.LauncherUI) {
window.LauncherUI.updateProgress(data);
}
});
}
// Initial Profile Load
loadProfiles();
// Close dropdown on outside click
document.addEventListener('click', (e) => {
const selector = document.getElementById('profileSelector');
if (selector && !selector.contains(e.target)) {
const dropdown = document.getElementById('profileDropdown');
if (dropdown) dropdown.classList.remove('show');
}
});
} }
// ==========================================
// PROFILE MANAGEMENT
// ==========================================
async function loadProfiles() {
try {
if (!window.electronAPI || !window.electronAPI.profile) return;
const profiles = await window.electronAPI.profile.list();
const activeProfile = await window.electronAPI.profile.getActive();
renderProfileList(profiles, activeProfile);
updateCurrentProfileUI(activeProfile);
} catch (error) {
console.error('Failed to load profiles:', error);
}
}
function renderProfileList(profiles, activeProfile) {
const list = document.getElementById('profileList');
const managerList = document.getElementById('managerProfileList');
if (!list) return;
// Dropdown List
list.innerHTML = profiles.map(p => `
<div class="profile-item ${p.id === activeProfile.id ? 'active' : ''}"
onclick="switchProfile('${p.id}')">
<span>${p.name}</span>
${p.id === activeProfile.id ? '<i class="fas fa-check ml-auto"></i>' : ''}
</div>
`).join('');
// Manager Modal List
if (managerList) {
managerList.innerHTML = profiles.map(p => `
<div class="profile-manager-item ${p.id === activeProfile.id ? 'active' : ''}">
<div class="flex items-center gap-3">
<i class="fas fa-user-circle text-xl text-gray-400"></i>
<div>
<div class="font-bold">${p.name}</div>
<div class="text-xs text-gray-500">ID: ${p.id.substring(0, 8)}...</div>
</div>
</div>
${p.id !== activeProfile.id ? `
<button class="profile-delete-btn" onclick="deleteProfile('${p.id}')" title="Delete Profile">
<i class="fas fa-trash"></i>
</button>
` : '<span class="text-xs text-green-500 font-bold px-2">ACTIVE</span>'}
</div>
`).join('');
}
}
function updateCurrentProfileUI(profile) {
const nameEl = document.getElementById('currentProfileName');
if (nameEl && profile) {
nameEl.textContent = profile.name;
}
}
window.toggleProfileDropdown = () => {
const dropdown = document.getElementById('profileDropdown');
if (dropdown) {
dropdown.classList.toggle('show');
}
};
window.openProfileManager = () => {
const modal = document.getElementById('profileManagerModal');
if (modal) {
modal.style.display = 'flex';
// Refresh list
loadProfiles();
}
// Close dropdown
const dropdown = document.getElementById('profileDropdown');
if (dropdown) dropdown.classList.remove('show');
};
window.closeProfileManager = () => {
const modal = document.getElementById('profileManagerModal');
if (modal) modal.style.display = 'none';
};
window.createNewProfile = async () => {
const input = document.getElementById('newProfileName');
if (!input || !input.value.trim()) return;
try {
const name = input.value.trim();
await window.electronAPI.profile.create(name);
input.value = '';
await loadProfiles();
} catch (error) {
console.error('Failed to create profile:', error);
alert('Failed to create profile: ' + error.message);
}
};
window.deleteProfile = async (id) => {
if (!confirm('Are you sure you want to delete this profile? parameters and mods configuration will be lost.')) return;
try {
await window.electronAPI.profile.delete(id);
await loadProfiles();
} catch (error) {
console.error('Failed to delete profile:', error);
alert('Failed to delete profile: ' + error.message);
}
};
window.switchProfile = async (id) => {
try {
if (window.LauncherUI) window.LauncherUI.showProgress();
if (window.LauncherUI) window.LauncherUI.updateProgress({ message: 'Switching Profile...' });
await window.electronAPI.profile.activate(id);
// Refresh UI
await loadProfiles();
// Refresh Mods
if (window.modsManager) {
if (window.modsManager.loadInstalledMods) await window.modsManager.loadInstalledMods();
if (window.modsManager.loadBrowseMods) await window.modsManager.loadBrowseMods();
}
// Close dropdown
const dropdown = document.getElementById('profileDropdown');
if (dropdown) dropdown.classList.remove('show');
if (window.LauncherUI) {
window.LauncherUI.updateProgress({ message: 'Profile Switched!' });
setTimeout(() => window.LauncherUI.hideProgress(), 1000);
}
} catch (error) {
console.error('Failed to switch profile:', error);
alert('Failed to switch profile: ' + error.message);
if (window.LauncherUI) window.LauncherUI.hideProgress();
}
};
export async function launch() { export async function launch() {
if (isDownloading || (playBtn && playBtn.disabled)) return; if (isDownloading || (playBtn && playBtn.disabled)) return;
let playerName = 'Player'; let playerName = 'Player';
if (window.SettingsAPI && window.SettingsAPI.getCurrentPlayerName) { if (window.SettingsAPI && window.SettingsAPI.getCurrentPlayerName) {
playerName = window.SettingsAPI.getCurrentPlayerName(); playerName = window.SettingsAPI.getCurrentPlayerName();
} else if (playerNameInput && playerNameInput.value.trim()) { } else if (playerNameInput && playerNameInput.value.trim()) {
playerName = playerNameInput.value.trim(); playerName = playerNameInput.value.trim();
} }
let javaPath = ''; let javaPath = '';
if (window.SettingsAPI && window.SettingsAPI.getCurrentJavaPath) { if (window.SettingsAPI && window.SettingsAPI.getCurrentJavaPath) {
javaPath = window.SettingsAPI.getCurrentJavaPath(); javaPath = window.SettingsAPI.getCurrentJavaPath();
} }
if (window.LauncherUI) window.LauncherUI.showProgress(); if (window.LauncherUI) window.LauncherUI.showProgress();
isDownloading = true; isDownloading = true;
if (playBtn) { if (playBtn) {
playBtn.disabled = true; playBtn.disabled = true;
playText.textContent = 'LAUNCHING...'; playText.textContent = 'LAUNCHING...';
} }
try { try {
if (window.LauncherUI) window.LauncherUI.updateProgress({ message: 'Starting game...' }); if (window.LauncherUI) window.LauncherUI.updateProgress({ message: 'Starting game...' });
if (window.electronAPI && window.electronAPI.launchGame) { if (window.electronAPI && window.electronAPI.launchGame) {
const result = await window.electronAPI.launchGame(playerName, javaPath, ''); const result = await window.electronAPI.launchGame(playerName, javaPath, '');
isDownloading = false; isDownloading = false;
if (window.LauncherUI) { if (window.LauncherUI) {
window.LauncherUI.hideProgress(); window.LauncherUI.hideProgress();
} }
resetPlayButton(); resetPlayButton();
if (result.success) { if (result.success) {
if (window.electronAPI.minimizeWindow) { if (window.electronAPI.minimizeWindow) {
setTimeout(() => { setTimeout(() => {
@@ -79,7 +243,7 @@ export async function launch() {
} }
} else { } else {
isDownloading = false; isDownloading = false;
if (window.LauncherUI) { if (window.LauncherUI) {
window.LauncherUI.hideProgress(); window.LauncherUI.hideProgress();
} }
@@ -87,7 +251,7 @@ export async function launch() {
} }
} catch (error) { } catch (error) {
isDownloading = false; isDownloading = false;
if (window.LauncherUI) { if (window.LauncherUI) {
window.LauncherUI.hideProgress(); window.LauncherUI.hideProgress();
} }
@@ -231,15 +395,15 @@ export async function uninstallGame() {
} }
async function performUninstall() { async function performUninstall() {
if (window.LauncherUI) window.LauncherUI.showProgress(); if (window.LauncherUI) window.LauncherUI.showProgress();
if (window.LauncherUI) window.LauncherUI.updateProgress({ message: 'Uninstalling game...' }); if (window.LauncherUI) window.LauncherUI.updateProgress({ message: 'Uninstalling game...' });
if (uninstallBtn) uninstallBtn.disabled = true; if (uninstallBtn) uninstallBtn.disabled = true;
try { try {
if (window.electronAPI && window.electronAPI.uninstallGame) { if (window.electronAPI && window.electronAPI.uninstallGame) {
const result = await window.electronAPI.uninstallGame(); const result = await window.electronAPI.uninstallGame();
if (result.success) { if (result.success) {
if (window.LauncherUI) { if (window.LauncherUI) {
window.LauncherUI.updateProgress({ message: 'Game uninstalled successfully!' }); window.LauncherUI.updateProgress({ message: 'Game uninstalled successfully!' });
@@ -304,7 +468,7 @@ async function saveJavaPath() {
function toggleCustomJava() { function toggleCustomJava() {
if (!customJavaOptions) return; if (!customJavaOptions) return;
if (customJavaCheck && customJavaCheck.checked) { if (customJavaCheck && customJavaCheck.checked) {
customJavaOptions.style.display = 'block'; customJavaOptions.style.display = 'block';
} else { } else {

View File

@@ -22,10 +22,10 @@ function setupModsEventListeners() {
let searchTimeout; let searchTimeout;
searchInput.addEventListener('input', (e) => { searchInput.addEventListener('input', (e) => {
searchQuery = e.target.value.toLowerCase().trim(); searchQuery = e.target.value.toLowerCase().trim();
clearTimeout(searchTimeout); clearTimeout(searchTimeout);
searchTimeout = setTimeout(() => { searchTimeout = setTimeout(() => {
modsPage = 0; modsPage = 0;
loadBrowseMods(); loadBrowseMods();
}, 500); }, 500);
}); });
@@ -52,7 +52,7 @@ function setupModsEventListeners() {
const prevPageBtn = document.getElementById('prevPage'); const prevPageBtn = document.getElementById('prevPage');
const nextPageBtn = document.getElementById('nextPage'); const nextPageBtn = document.getElementById('nextPage');
if (prevPageBtn) { if (prevPageBtn) {
prevPageBtn.addEventListener('click', () => { prevPageBtn.addEventListener('click', () => {
if (modsPage > 0) { if (modsPage > 0) {
@@ -61,7 +61,7 @@ function setupModsEventListeners() {
} }
}); });
} }
if (nextPageBtn) { if (nextPageBtn) {
nextPageBtn.addEventListener('click', () => { nextPageBtn.addEventListener('click', () => {
if (modsPage < modsTotalPages - 1) { if (modsPage < modsTotalPages - 1) {
@@ -97,7 +97,7 @@ async function loadInstalledMods() {
const mods = await window.electronAPI?.loadInstalledMods(modsPath); const mods = await window.electronAPI?.loadInstalledMods(modsPath);
installedMods = mods || []; installedMods = mods || [];
displayInstalledMods(installedMods); displayInstalledMods(installedMods);
} catch (error) { } catch (error) {
console.error('Error loading installed mods:', error); console.error('Error loading installed mods:', error);
@@ -196,13 +196,13 @@ async function loadBrowseMods() {
const offset = modsPage * modsPageSize; const offset = modsPage * modsPageSize;
let url = `${CURSEFORGE_API}/mods/search?gameId=${HYTALE_GAME_ID}&pageSize=${modsPageSize}&sortOrder=desc&sortField=6&index=${offset}`; let url = `${CURSEFORGE_API}/mods/search?gameId=${HYTALE_GAME_ID}&pageSize=${modsPageSize}&sortOrder=desc&sortField=6&index=${offset}`;
if (searchQuery && searchQuery.length > 0) { if (searchQuery && searchQuery.length > 0) {
url += `&searchFilter=${encodeURIComponent(searchQuery)}`; url += `&searchFilter=${encodeURIComponent(searchQuery)}`;
} }
console.log('Fetching mods from page', modsPage + 1, 'offset:', offset, 'search:', searchQuery || 'none', 'URL:', url); console.log('Fetching mods from page', modsPage + 1, 'offset:', offset, 'search:', searchQuery || 'none', 'URL:', url);
const response = await fetch(url, { const response = await fetch(url, {
headers: { headers: {
'x-api-key': API_KEY, 'x-api-key': API_KEY,
@@ -221,7 +221,7 @@ async function loadBrowseMods() {
const data = await response.json(); const data = await response.json();
console.log('API Response data:', data); console.log('API Response data:', data);
console.log('Total mods found:', data.data?.length || 0); console.log('Total mods found:', data.data?.length || 0);
browseMods = (data.data || []).map(mod => ({ browseMods = (data.data || []).map(mod => ({
id: mod.id.toString(), id: mod.id.toString(),
name: mod.name, name: mod.name,
@@ -282,18 +282,25 @@ function displayBrowseMods(mods) {
} }
function createBrowseModCard(mod) { function createBrowseModCard(mod) {
const isInstalled = installedMods.some(installed => const isInstalled = installedMods.some(installed => {
installed.name.toLowerCase().includes(mod.name.toLowerCase()) || // Check by CurseForge ID (most reliable)
installed.curseForgeId == mod.id if (installed.curseForgeId && installed.curseForgeId.toString() === mod.id.toString()) {
); return true;
}
// Check by exact name match for manually installed mods
if (installed.name.toLowerCase() === mod.name.toLowerCase()) {
return true;
}
return false;
});
return ` return `
<div class=\"mod-card ${isInstalled ? 'installed' : ''}\" data-mod-id=\"${mod.id}\"> <div class=\"mod-card ${isInstalled ? 'installed' : ''}\" data-mod-id=\"${mod.id}\">
<div class=\"mod-image\"> <div class=\"mod-image\">
${mod.thumbnailUrl ? ${mod.thumbnailUrl ?
`<img src=\"${mod.thumbnailUrl}\" alt=\"${mod.name}\" onerror=\"this.parentElement.innerHTML='<i class=\\\"fas fa-puzzle-piece\\\"></i>'\">` : `<img src=\"${mod.thumbnailUrl}\" alt=\"${mod.name}\" onerror=\"this.parentElement.innerHTML='<i class=\\\"fas fa-puzzle-piece\\\"></i>'\">` :
`<i class=\"fas fa-puzzle-piece\"></i>` `<i class=\"fas fa-puzzle-piece\"></i>`
} }
</div> </div>
<div class=\"mod-info\"> <div class=\"mod-info\">
@@ -319,16 +326,16 @@ function createBrowseModCard(mod) {
<i class=\"fas fa-external-link-alt\"></i> <i class=\"fas fa-external-link-alt\"></i>
VIEW VIEW
</button> </button>
${!isInstalled ? ${!isInstalled ?
`<button id=\"install-${mod.id}\" class=\"mod-btn-toggle bg-primary text-black hover:bg-primary/80\"> `<button id=\"install-${mod.id}\" class=\"mod-btn-toggle bg-primary text-black hover:bg-primary/80\">
<i class=\"fas fa-download\"></i> <i class=\"fas fa-download\"></i>
INSTALL INSTALL
</button>` : </button>` :
`<button class=\"mod-btn-toggle bg-white/10 text-white\" disabled> `<button class=\"mod-btn-toggle bg-white/10 text-white\" disabled>
<i class=\"fas fa-check\"></i> <i class=\"fas fa-check\"></i>
INSTALLED INSTALLED
</button>` </button>`
} }
</div> </div>
</div> </div>
`; `;
@@ -337,9 +344,9 @@ function createBrowseModCard(mod) {
async function downloadAndInstallMod(modInfo) { async function downloadAndInstallMod(modInfo) {
try { try {
window.LauncherUI?.showProgress(`Downloading ${modInfo.name}...`); window.LauncherUI?.showProgress(`Downloading ${modInfo.name}...`);
const result = await window.electronAPI?.downloadMod(modInfo); const result = await window.electronAPI?.downloadMod(modInfo);
if (result?.success) { if (result?.success) {
const newMod = { const newMod = {
id: result.modInfo.id, id: result.modInfo.id,
@@ -354,11 +361,11 @@ async function downloadAndInstallMod(modInfo) {
curseForgeId: modInfo.modId, curseForgeId: modInfo.modId,
curseForgeFileId: modInfo.fileId curseForgeFileId: modInfo.fileId
}; };
installedMods.push(newMod); installedMods.push(newMod);
await loadInstalledMods(); await loadInstalledMods();
await loadBrowseMods(); await loadBrowseMods();
window.LauncherUI?.hideProgress(); window.LauncherUI?.hideProgress();
showNotification(`${modInfo.name} installed successfully! 🎉`, 'success'); showNotification(`${modInfo.name} installed successfully! 🎉`, 'success');
} else { } else {
@@ -374,10 +381,10 @@ async function downloadAndInstallMod(modInfo) {
async function toggleMod(modId) { async function toggleMod(modId) {
try { try {
window.LauncherUI?.showProgress('Toggling mod...'); window.LauncherUI?.showProgress('Toggling mod...');
const modsPath = await window.electronAPI?.getModsPath(); const modsPath = await window.electronAPI?.getModsPath();
const result = await window.electronAPI?.toggleMod(modId, modsPath); const result = await window.electronAPI?.toggleMod(modId, modsPath);
if (result?.success) { if (result?.success) {
await loadInstalledMods(); await loadInstalledMods();
window.LauncherUI?.hideProgress(); window.LauncherUI?.hideProgress();
@@ -400,13 +407,13 @@ async function deleteMod(modId) {
async () => { async () => {
try { try {
window.LauncherUI?.showProgress('Deleting mod...'); window.LauncherUI?.showProgress('Deleting mod...');
const modsPath = await window.electronAPI?.getModsPath(); const modsPath = await window.electronAPI?.getModsPath();
const result = await window.electronAPI?.uninstallMod(modId, modsPath); const result = await window.electronAPI?.uninstallMod(modId, modsPath);
if (result?.success) { if (result?.success) {
await loadInstalledMods(); await loadInstalledMods();
await loadBrowseMods(); await loadBrowseMods();
window.LauncherUI?.hideProgress(); window.LauncherUI?.hideProgress();
showNotification(`"${mod.name}" deleted successfully`, 'success'); showNotification(`"${mod.name}" deleted successfully`, 'success');
} else { } else {
@@ -436,21 +443,21 @@ function showNotification(message, type = 'info', duration = 4000) {
const notification = document.createElement('div'); const notification = document.createElement('div');
notification.className = `mod-notification ${type}`; notification.className = `mod-notification ${type}`;
const icons = { const icons = {
success: 'fa-check-circle', success: 'fa-check-circle',
error: 'fa-exclamation-circle', error: 'fa-exclamation-circle',
info: 'fa-info-circle', info: 'fa-info-circle',
warning: 'fa-exclamation-triangle' warning: 'fa-exclamation-triangle'
}; };
const colors = { const colors = {
success: '#10b981', success: '#10b981',
error: '#ef4444', error: '#ef4444',
info: '#3b82f6', info: '#3b82f6',
warning: '#f59e0b' warning: '#f59e0b'
}; };
notification.innerHTML = ` notification.innerHTML = `
<div class="notification-content"> <div class="notification-content">
<i class="fas ${icons[type]}"></i> <i class="fas ${icons[type]}"></i>
@@ -460,7 +467,7 @@ function showNotification(message, type = 'info', duration = 4000) {
<i class="fas fa-times"></i> <i class="fas fa-times"></i>
</button> </button>
`; `;
notification.style.cssText = ` notification.style.cssText = `
position: fixed; position: fixed;
top: 20px; top: 20px;
@@ -481,14 +488,14 @@ function showNotification(message, type = 'info', duration = 4000) {
font-size: 14px; font-size: 14px;
font-weight: 500; font-weight: 500;
`; `;
const contentStyle = ` const contentStyle = `
display: flex; display: flex;
align-items: center; align-items: center;
gap: 10px; gap: 10px;
flex: 1; flex: 1;
`; `;
const closeStyle = ` const closeStyle = `
background: none; background: none;
border: none; border: none;
@@ -500,17 +507,17 @@ function showNotification(message, type = 'info', duration = 4000) {
transition: opacity 0.2s; transition: opacity 0.2s;
margin-left: 10px; margin-left: 10px;
`; `;
notification.querySelector('.notification-content').style.cssText = contentStyle; notification.querySelector('.notification-content').style.cssText = contentStyle;
notification.querySelector('.notification-close').style.cssText = closeStyle; notification.querySelector('.notification-close').style.cssText = closeStyle;
document.body.appendChild(notification); document.body.appendChild(notification);
// Animate in // Animate in
setTimeout(() => { setTimeout(() => {
notification.style.transform = 'translateX(0)'; notification.style.transform = 'translateX(0)';
}, 10); }, 10);
// Auto remove // Auto remove
setTimeout(() => { setTimeout(() => {
if (notification.parentElement) { if (notification.parentElement) {
@@ -651,13 +658,13 @@ function updatePagination() {
if (currentPageEl) currentPageEl.textContent = modsPage + 1; if (currentPageEl) currentPageEl.textContent = modsPage + 1;
if (totalPagesEl) totalPagesEl.textContent = modsTotalPages; if (totalPagesEl) totalPagesEl.textContent = modsTotalPages;
if (prevBtn) { if (prevBtn) {
prevBtn.disabled = modsPage === 0; prevBtn.disabled = modsPage === 0;
prevBtn.style.opacity = modsPage === 0 ? '0.5' : '1'; prevBtn.style.opacity = modsPage === 0 ? '0.5' : '1';
prevBtn.style.cursor = modsPage === 0 ? 'not-allowed' : 'pointer'; prevBtn.style.cursor = modsPage === 0 ? 'not-allowed' : 'pointer';
} }
if (nextBtn) { if (nextBtn) {
nextBtn.disabled = modsPage >= modsTotalPages - 1; nextBtn.disabled = modsPage >= modsTotalPages - 1;
nextBtn.style.opacity = modsPage >= modsTotalPages - 1 ? '0.5' : '1'; nextBtn.style.opacity = modsPage >= modsTotalPages - 1 ? '0.5' : '1';
@@ -681,7 +688,7 @@ function showInstalledModsError(message) {
function viewModPage(modId) { function viewModPage(modId) {
console.log('Looking for mod with ID:', modId, 'Type:', typeof modId); console.log('Looking for mod with ID:', modId, 'Type:', typeof modId);
console.log('Available mods:', browseMods.map(m => ({ id: m.id, name: m.name, type: typeof m.id }))); console.log('Available mods:', browseMods.map(m => ({ id: m.id, name: m.name, type: typeof m.id })));
const mod = browseMods.find(m => m.id.toString() === modId.toString()); const mod = browseMods.find(m => m.id.toString() === modId.toString());
if (mod) { if (mod) {
console.log('Found mod:', mod.name); console.log('Found mod:', mod.name);
@@ -694,9 +701,9 @@ function viewModPage(modId) {
const nameSlug = mod.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, ''); const nameSlug = mod.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
modUrl = `https://www.curseforge.com/hytale/mods/${nameSlug}`; modUrl = `https://www.curseforge.com/hytale/mods/${nameSlug}`;
} }
console.log('Opening URL:', modUrl); console.log('Opening URL:', modUrl);
if (window.electronAPI && window.electronAPI.openExternalLink) { if (window.electronAPI && window.electronAPI.openExternalLink) {
window.electronAPI.openExternalLink(modUrl); window.electronAPI.openExternalLink(modUrl);
} else { } else {
@@ -717,7 +724,9 @@ window.modsManager = {
deleteMod, deleteMod,
openMyModsModal, openMyModsModal,
closeMyModsModal, closeMyModsModal,
viewModPage viewModPage,
loadInstalledMods,
loadBrowseMods
}; };
document.addEventListener('DOMContentLoaded', initModsManager); document.addEventListener('DOMContentLoaded', initModsManager);

View File

@@ -45,22 +45,32 @@ function handleNavigation() {
function setupWindowControls() { function setupWindowControls() {
const minimizeBtn = document.querySelector('.window-controls .minimize'); const minimizeBtn = document.querySelector('.window-controls .minimize');
const closeBtn = document.querySelector('.window-controls .close'); const closeBtn = document.querySelector('.window-controls .close');
const windowControls = document.querySelector('.window-controls'); const windowControls = document.querySelector('.window-controls');
const header = document.querySelector('.header'); const header = document.querySelector('.header');
const profileSelector = document.querySelector('.profile-selector');
if (profileSelector) {
profileSelector.style.pointerEvents = 'auto';
profileSelector.style.zIndex = '10000';
}
if (windowControls) { if (windowControls) {
windowControls.style.pointerEvents = 'auto'; windowControls.style.pointerEvents = 'auto';
windowControls.style.zIndex = '10000'; windowControls.style.zIndex = '10000';
} }
if (header) { if (header) {
header.style.webkitAppRegion = 'drag'; header.style.webkitAppRegion = 'drag';
if (windowControls) { if (windowControls) {
windowControls.style.webkitAppRegion = 'no-drag'; windowControls.style.webkitAppRegion = 'no-drag';
} }
if (profileSelector) {
profileSelector.style.webkitAppRegion = 'no-drag';
}
} }
if (window.electronAPI) { if (window.electronAPI) {
if (minimizeBtn) { if (minimizeBtn) {
minimizeBtn.onclick = (e) => { minimizeBtn.onclick = (e) => {
@@ -82,7 +92,7 @@ function showLauncherOrInstall(isInstalled) {
const install = document.getElementById('install-page'); const install = document.getElementById('install-page');
const sidebar = document.querySelector('.sidebar'); const sidebar = document.querySelector('.sidebar');
const gameTitle = document.querySelector('.game-title-section'); const gameTitle = document.querySelector('.game-title-section');
if (isInstalled) { if (isInstalled) {
if (launcher) launcher.style.display = ''; if (launcher) launcher.style.display = '';
if (install) install.style.display = 'none'; if (install) install.style.display = 'none';
@@ -137,14 +147,14 @@ function updateProgress(data) {
if (data.message && progressText) { if (data.message && progressText) {
progressText.textContent = data.message; progressText.textContent = data.message;
} }
if (data.percent !== null && data.percent !== undefined) { if (data.percent !== null && data.percent !== undefined) {
const percent = Math.min(100, Math.max(0, Math.round(data.percent))); const percent = Math.min(100, Math.max(0, Math.round(data.percent)));
if (progressPercent) progressPercent.textContent = `${percent}%`; if (progressPercent) progressPercent.textContent = `${percent}%`;
if (progressBarFill) progressBarFill.style.width = `${percent}%`; if (progressBarFill) progressBarFill.style.width = `${percent}%`;
if (progressBar) progressBar.style.width = `${percent}%`; if (progressBar) progressBar.style.width = `${percent}%`;
} }
if (data.speed && data.downloaded && data.total) { if (data.speed && data.downloaded && data.total) {
const speedMB = (data.speed / 1024 / 1024).toFixed(2); const speedMB = (data.speed / 1024 / 1024).toFixed(2);
const downloadedMB = (data.downloaded / 1024 / 1024).toFixed(2); const downloadedMB = (data.downloaded / 1024 / 1024).toFixed(2);
@@ -157,13 +167,13 @@ function updateProgress(data) {
function setupAnimations() { function setupAnimations() {
document.body.style.opacity = '0'; document.body.style.opacity = '0';
document.body.style.transform = 'translateY(20px)'; document.body.style.transform = 'translateY(20px)';
setTimeout(() => { setTimeout(() => {
document.body.style.transition = 'all 0.6s ease'; document.body.style.transition = 'all 0.6s ease';
document.body.style.opacity = '1'; document.body.style.opacity = '1';
document.body.style.transform = 'translateY(0)'; document.body.style.transform = 'translateY(0)';
}, 100); }, 100);
const style = document.createElement('style'); const style = document.createElement('style');
style.textContent = ` style.textContent = `
@keyframes fadeInUp { @keyframes fadeInUp {
@@ -182,7 +192,7 @@ function setupAnimations() {
function setupFirstLaunchHandlers() { function setupFirstLaunchHandlers() {
console.log('Setting up first launch handlers...'); console.log('Setting up first launch handlers...');
window.electronAPI.onFirstLaunchUpdate((data) => { window.electronAPI.onFirstLaunchUpdate((data) => {
console.log('Received first launch update event:', data); console.log('Received first launch update event:', data);
showFirstLaunchUpdateDialog(data); showFirstLaunchUpdateDialog(data);
@@ -195,12 +205,12 @@ function setupFirstLaunchHandlers() {
showProgress(); showProgress();
updateProgress(data); updateProgress(data);
}); });
let lockButtonTimeout = null; let lockButtonTimeout = null;
window.electronAPI.onLockPlayButton((locked) => { window.electronAPI.onLockPlayButton((locked) => {
lockPlayButton(locked); lockPlayButton(locked);
if (locked) { if (locked) {
if (lockButtonTimeout) { if (lockButtonTimeout) {
clearTimeout(lockButtonTimeout); clearTimeout(lockButtonTimeout);
@@ -221,12 +231,12 @@ function setupFirstLaunchHandlers() {
function showFirstLaunchUpdateDialog(data) { function showFirstLaunchUpdateDialog(data) {
console.log('Creating first launch modal...'); console.log('Creating first launch modal...');
const existingModal = document.querySelector('.first-launch-modal-overlay'); const existingModal = document.querySelector('.first-launch-modal-overlay');
if (existingModal) { if (existingModal) {
existingModal.remove(); existingModal.remove();
} }
const modalOverlay = document.createElement('div'); const modalOverlay = document.createElement('div');
modalOverlay.className = 'first-launch-modal-overlay'; modalOverlay.className = 'first-launch-modal-overlay';
modalOverlay.style.cssText = ` modalOverlay.style.cssText = `
@@ -243,7 +253,7 @@ function showFirstLaunchUpdateDialog(data) {
justify-content: center !important; justify-content: center !important;
pointer-events: all !important; pointer-events: all !important;
`; `;
const modalDialog = document.createElement('div'); const modalDialog = document.createElement('div');
modalDialog.className = 'first-launch-modal-dialog'; modalDialog.className = 'first-launch-modal-dialog';
modalDialog.style.cssText = ` modalDialog.style.cssText = `
@@ -257,7 +267,7 @@ function showFirstLaunchUpdateDialog(data) {
overflow: hidden !important; overflow: hidden !important;
animation: modalSlideIn 0.3s ease-out !important; animation: modalSlideIn 0.3s ease-out !important;
`; `;
modalDialog.innerHTML = ` modalDialog.innerHTML = `
<div style="background: linear-gradient(135deg, rgba(147, 51, 234, 0.2), rgba(59, 130, 246, 0.2)); padding: 25px; border-bottom: 1px solid rgba(255,255,255,0.1);"> <div style="background: linear-gradient(135deg, rgba(147, 51, 234, 0.2), rgba(59, 130, 246, 0.2)); padding: 25px; border-bottom: 1px solid rgba(255,255,255,0.1);">
<h2 style="margin: 0; color: #fff; font-size: 1.5rem; font-weight: 600; text-align: center;"> <h2 style="margin: 0; color: #fff; font-size: 1.5rem; font-weight: 600; text-align: center;">
@@ -306,9 +316,9 @@ function showFirstLaunchUpdateDialog(data) {
</button> </button>
</div> </div>
`; `;
modalOverlay.appendChild(modalDialog); modalOverlay.appendChild(modalDialog);
modalOverlay.onclick = (e) => { modalOverlay.onclick = (e) => {
if (e.target === modalOverlay) { if (e.target === modalOverlay) {
e.preventDefault(); e.preventDefault();
@@ -316,7 +326,7 @@ function showFirstLaunchUpdateDialog(data) {
return false; return false;
} }
}; };
document.addEventListener('keydown', function preventEscape(e) { document.addEventListener('keydown', function preventEscape(e) {
if (e.key === 'Escape') { if (e.key === 'Escape') {
e.preventDefault(); e.preventDefault();
@@ -324,33 +334,33 @@ function showFirstLaunchUpdateDialog(data) {
return false; return false;
} }
}); });
document.body.appendChild(modalOverlay); document.body.appendChild(modalOverlay);
const updateBtn = document.getElementById('updateGameBtn'); const updateBtn = document.getElementById('updateGameBtn');
updateBtn.onclick = () => { updateBtn.onclick = () => {
acceptFirstLaunchUpdate(); acceptFirstLaunchUpdate();
}; };
window.firstLaunchExistingGame = data.existingGame; window.firstLaunchExistingGame = data.existingGame;
console.log('First launch modal created and displayed'); console.log('First launch modal created and displayed');
} }
function lockPlayButton(locked) { function lockPlayButton(locked) {
const playButton = document.getElementById('homePlayBtn'); const playButton = document.getElementById('homePlayBtn');
if (!playButton) { if (!playButton) {
console.warn('Play button not found'); console.warn('Play button not found');
return; return;
} }
if (locked) { if (locked) {
playButton.style.opacity = '0.5'; playButton.style.opacity = '0.5';
playButton.style.pointerEvents = 'none'; playButton.style.pointerEvents = 'none';
playButton.style.cursor = 'not-allowed'; playButton.style.cursor = 'not-allowed';
playButton.setAttribute('data-locked', 'true'); playButton.setAttribute('data-locked', 'true');
const spanElement = playButton.querySelector('span'); const spanElement = playButton.querySelector('span');
if (spanElement) { if (spanElement) {
if (!playButton.getAttribute('data-original-text')) { if (!playButton.getAttribute('data-original-text')) {
@@ -358,21 +368,21 @@ function lockPlayButton(locked) {
} }
spanElement.textContent = 'CHECKING...'; spanElement.textContent = 'CHECKING...';
} }
console.log('Play button locked'); console.log('Play button locked');
} else { } else {
playButton.style.opacity = ''; playButton.style.opacity = '';
playButton.style.pointerEvents = ''; playButton.style.pointerEvents = '';
playButton.style.cursor = ''; playButton.style.cursor = '';
playButton.removeAttribute('data-locked'); playButton.removeAttribute('data-locked');
const spanElement = playButton.querySelector('span'); const spanElement = playButton.querySelector('span');
const originalText = playButton.getAttribute('data-original-text'); const originalText = playButton.getAttribute('data-original-text');
if (spanElement && originalText) { if (spanElement && originalText) {
spanElement.textContent = originalText; spanElement.textContent = originalText;
playButton.removeAttribute('data-original-text'); playButton.removeAttribute('data-original-text');
} }
console.log('Play button unlocked'); console.log('Play button unlocked');
} }
} }
@@ -381,12 +391,12 @@ function lockPlayButton(locked) {
async function acceptFirstLaunchUpdate() { async function acceptFirstLaunchUpdate() {
const existingGame = window.firstLaunchExistingGame; const existingGame = window.firstLaunchExistingGame;
if (!existingGame) { if (!existingGame) {
showNotification('Error: Game data not found', 'error'); showNotification('Error: Game data not found', 'error');
return; return;
} }
const modal = document.querySelector('.first-launch-modal-overlay'); const modal = document.querySelector('.first-launch-modal-overlay');
if (modal) { if (modal) {
modal.style.pointerEvents = 'none'; modal.style.pointerEvents = 'none';
@@ -397,21 +407,21 @@ async function acceptFirstLaunchUpdate() {
btn.textContent = '🔄 Updating...'; btn.textContent = '🔄 Updating...';
} }
} }
try { try {
showProgress(); showProgress();
updateProgress({ message: 'Starting mandatory game update...', percent: 0 }); updateProgress({ message: 'Starting mandatory game update...', percent: 0 });
const result = await window.electronAPI.acceptFirstLaunchUpdate(existingGame); const result = await window.electronAPI.acceptFirstLaunchUpdate(existingGame);
window.electronAPI.markAsLaunched && window.electronAPI.markAsLaunched(); window.electronAPI.markAsLaunched && window.electronAPI.markAsLaunched();
if (modal) { if (modal) {
modal.remove(); modal.remove();
} }
lockPlayButton(false); lockPlayButton(false);
if (result.success) { if (result.success) {
hideProgress(); hideProgress();
showNotification('Game updated successfully! 🎉', 'success'); showNotification('Game updated successfully! 🎉', 'success');
@@ -434,7 +444,7 @@ function dismissFirstLaunchDialog() {
if (modal) { if (modal) {
modal.remove(); modal.remove();
} }
lockPlayButton(false); lockPlayButton(false);
window.electronAPI.markAsLaunched && window.electronAPI.markAsLaunched(); window.electronAPI.markAsLaunched && window.electronAPI.markAsLaunched();
} }
@@ -443,13 +453,13 @@ function showNotification(message, type = 'info') {
const notification = document.createElement('div'); const notification = document.createElement('div');
notification.className = `notification notification-${type}`; notification.className = `notification notification-${type}`;
notification.textContent = message; notification.textContent = message;
document.body.appendChild(notification); document.body.appendChild(notification);
setTimeout(() => { setTimeout(() => {
notification.classList.add('show'); notification.classList.add('show');
}, 100); }, 100);
setTimeout(() => { setTimeout(() => {
notification.remove(); notification.remove();
}, 5000); }, 5000);
@@ -463,9 +473,9 @@ function setupUI() {
progressPercent = document.getElementById('progressPercent'); progressPercent = document.getElementById('progressPercent');
progressSpeed = document.getElementById('progressSpeed'); progressSpeed = document.getElementById('progressSpeed');
progressSize = document.getElementById('progressSize'); progressSize = document.getElementById('progressSize');
lockPlayButton(true); lockPlayButton(true);
setTimeout(() => { setTimeout(() => {
const playButton = document.getElementById('homePlayBtn'); const playButton = document.getElementById('homePlayBtn');
if (playButton && playButton.getAttribute('data-locked') === 'true') { if (playButton && playButton.getAttribute('data-locked') === 'true') {
@@ -476,13 +486,13 @@ function setupUI() {
} }
} }
}, 25000); }, 25000);
handleNavigation(); handleNavigation();
setupWindowControls(); setupWindowControls();
setupSidebarLogo(); setupSidebarLogo();
setupAnimations(); setupAnimations();
setupFirstLaunchHandlers(); setupFirstLaunchHandlers();
document.body.focus(); document.body.focus();
} }

View File

@@ -10,7 +10,7 @@ body {
background: rgba(255, 255, 255, 0.05); background: rgba(255, 255, 255, 0.05);
backdrop-filter: blur(20px); backdrop-filter: blur(20px);
border: 1px solid rgba(255, 255, 255, 0.1); border: 1px solid rgba(255, 255, 255, 0.1);
box-shadow: box-shadow:
0 8px 32px rgba(0, 0, 0, 0.4), 0 8px 32px rgba(0, 0, 0, 0.4),
inset 0 1px 0 rgba(255, 255, 255, 0.1); inset 0 1px 0 rgba(255, 255, 255, 0.1);
} }
@@ -263,6 +263,7 @@ body {
.window-controls { .window-controls {
display: flex; display: flex;
width: fit-content;
gap: 0.5rem; gap: 0.5rem;
z-index: 9999; z-index: 9999;
position: relative; position: relative;
@@ -293,6 +294,7 @@ body {
transform: translateX(100%); transform: translateX(100%);
opacity: 0; opacity: 0;
} }
to { to {
transform: translateX(0); transform: translateX(0);
opacity: 1; opacity: 1;
@@ -552,7 +554,7 @@ body {
letter-spacing: 0.1em; letter-spacing: 0.1em;
cursor: pointer; cursor: pointer;
transition: all 0.3s ease; transition: all 0.3s ease;
box-shadow: box-shadow:
0 4px 0 0 #7c3aed, 0 4px 0 0 #7c3aed,
0 8px 20px rgba(147, 51, 234, 0.3); 0 8px 20px rgba(147, 51, 234, 0.3);
display: flex; display: flex;
@@ -564,7 +566,7 @@ body {
.install-button:hover { .install-button:hover {
background: linear-gradient(135deg, #7c3aed, #2563eb); background: linear-gradient(135deg, #7c3aed, #2563eb);
box-shadow: box-shadow:
0 2px 0 0 #7c3aed, 0 2px 0 0 #7c3aed,
0 12px 30px rgba(147, 51, 234, 0.4); 0 12px 30px rgba(147, 51, 234, 0.4);
transform: translateY(2px); transform: translateY(2px);
@@ -572,7 +574,7 @@ body {
.install-button:active { .install-button:active {
transform: translateY(4px); transform: translateY(4px);
box-shadow: box-shadow:
0 0px 0 0 #7c3aed, 0 0px 0 0 #7c3aed,
0 4px 15px rgba(147, 51, 234, 0.3); 0 4px 15px rgba(147, 51, 234, 0.3);
} }
@@ -590,6 +592,7 @@ body {
flex-direction: column; flex-direction: column;
height: 100%; height: 100%;
} }
.content-pages { .content-pages {
flex: 1; flex: 1;
overflow: hidden; overflow: hidden;
@@ -666,7 +669,7 @@ body {
letter-spacing: 0.05em; letter-spacing: 0.05em;
cursor: pointer; cursor: pointer;
transition: all 0.3s ease; transition: all 0.3s ease;
box-shadow: box-shadow:
0 4px 0 0 #7c3aed, 0 4px 0 0 #7c3aed,
0 8px 20px rgba(147, 51, 234, 0.3); 0 8px 20px rgba(147, 51, 234, 0.3);
display: flex; display: flex;
@@ -677,7 +680,7 @@ body {
.home-play-button:hover { .home-play-button:hover {
background: linear-gradient(135deg, #7c3aed, #2563eb); background: linear-gradient(135deg, #7c3aed, #2563eb);
box-shadow: box-shadow:
0 2px 0 0 #7c3aed, 0 2px 0 0 #7c3aed,
0 12px 30px rgba(147, 51, 234, 0.4); 0 12px 30px rgba(147, 51, 234, 0.4);
transform: translateY(2px); transform: translateY(2px);
@@ -685,7 +688,7 @@ body {
.home-play-button:active { .home-play-button:active {
transform: translateY(4px); transform: translateY(4px);
box-shadow: box-shadow:
0 0px 0 0 #7c3aed, 0 0px 0 0 #7c3aed,
0 4px 15px rgba(147, 51, 234, 0.3); 0 4px 15px rgba(147, 51, 234, 0.3);
} }
@@ -1347,7 +1350,7 @@ body {
letter-spacing: 0.1em; letter-spacing: 0.1em;
cursor: pointer; cursor: pointer;
transition: all 0.3s ease; transition: all 0.3s ease;
box-shadow: box-shadow:
0 4px 0 0 #15803d, 0 4px 0 0 #15803d,
0 8px 20px rgba(34, 197, 94, 0.3); 0 8px 20px rgba(34, 197, 94, 0.3);
z-index: 10; z-index: 10;
@@ -1357,7 +1360,7 @@ body {
.play-button:hover { .play-button:hover {
background: linear-gradient(135deg, #16a34a, #15803d); background: linear-gradient(135deg, #16a34a, #15803d);
box-shadow: box-shadow:
0 2px 0 0 #15803d, 0 2px 0 0 #15803d,
0 12px 30px rgba(34, 197, 94, 0.4); 0 12px 30px rgba(34, 197, 94, 0.4);
transform: translateY(2px); transform: translateY(2px);
@@ -1365,7 +1368,7 @@ body {
.play-button:active { .play-button:active {
transform: translateY(4px); transform: translateY(4px);
box-shadow: box-shadow:
0 0px 0 0 #15803d, 0 0px 0 0 #15803d,
0 4px 15px rgba(34, 197, 94, 0.3); 0 4px 15px rgba(34, 197, 94, 0.3);
} }
@@ -1415,7 +1418,7 @@ body {
border-radius: 16px; border-radius: 16px;
padding: 2rem; padding: 2rem;
z-index: 50; z-index: 50;
box-shadow: box-shadow:
0 8px 32px rgba(0, 0, 0, 0.6), 0 8px 32px rgba(0, 0, 0, 0.6),
0 0 40px rgba(147, 51, 234, 0.1), 0 0 40px rgba(147, 51, 234, 0.1),
inset 0 1px 0 rgba(255, 255, 255, 0.1); inset 0 1px 0 rgba(255, 255, 255, 0.1);
@@ -1424,14 +1427,15 @@ body {
@keyframes progressGlow { @keyframes progressGlow {
0% { 0% {
box-shadow: box-shadow:
0 8px 32px rgba(0, 0, 0, 0.6), 0 8px 32px rgba(0, 0, 0, 0.6),
0 0 40px rgba(147, 51, 234, 0.1), 0 0 40px rgba(147, 51, 234, 0.1),
inset 0 1px 0 rgba(255, 255, 255, 0.1); inset 0 1px 0 rgba(255, 255, 255, 0.1);
border-color: rgba(147, 51, 234, 0.3); border-color: rgba(147, 51, 234, 0.3);
} }
100% { 100% {
box-shadow: box-shadow:
0 8px 32px rgba(0, 0, 0, 0.6), 0 8px 32px rgba(0, 0, 0, 0.6),
0 0 60px rgba(147, 51, 234, 0.3), 0 0 60px rgba(147, 51, 234, 0.3),
inset 0 1px 0 rgba(255, 255, 255, 0.1); inset 0 1px 0 rgba(255, 255, 255, 0.1);
@@ -1463,8 +1467,15 @@ body {
} }
@keyframes textPulse { @keyframes textPulse {
0%, 100% { opacity: 0.8; }
50% { opacity: 1; } 0%,
100% {
opacity: 0.8;
}
50% {
opacity: 1;
}
} }
#progressPercent { #progressPercent {
@@ -1476,11 +1487,14 @@ body {
} }
@keyframes percentGlow { @keyframes percentGlow {
0%, 100% {
0%,
100% {
text-shadow: 0 0 20px rgba(147, 51, 234, 0.8); text-shadow: 0 0 20px rgba(147, 51, 234, 0.8);
transform: scale(1); transform: scale(1);
} }
50% {
50% {
text-shadow: 0 0 30px rgba(147, 51, 234, 1); text-shadow: 0 0 30px rgba(147, 51, 234, 1);
transform: scale(1.05); transform: scale(1.05);
} }
@@ -1493,7 +1507,7 @@ body {
border-radius: 12px; border-radius: 12px;
overflow: hidden; overflow: hidden;
position: relative; position: relative;
box-shadow: box-shadow:
inset 0 2px 4px rgba(0, 0, 0, 0.5), inset 0 2px 4px rgba(0, 0, 0, 0.5),
0 0 20px rgba(147, 51, 234, 0.1); 0 0 20px rgba(147, 51, 234, 0.1);
} }
@@ -1505,28 +1519,31 @@ body {
left: -100%; left: -100%;
width: 100%; width: 100%;
height: 100%; height: 100%;
background: linear-gradient(90deg, background: linear-gradient(90deg,
transparent, transparent,
rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0.2),
transparent transparent);
);
animation: shimmer 2s infinite; animation: shimmer 2s infinite;
} }
@keyframes shimmer { @keyframes shimmer {
0% { left: -100%; } 0% {
100% { left: 100%; } left: -100%;
}
100% {
left: 100%;
}
} }
.progress-bar-fill { .progress-bar-fill {
height: 100%; height: 100%;
background: linear-gradient(90deg, background: linear-gradient(90deg,
#9333ea 0%, #9333ea 0%,
#a855f7 25%, #a855f7 25%,
#3b82f6 50%, #3b82f6 50%,
#06b6d4 75%, #06b6d4 75%,
#10b981 100% #10b981 100%);
);
background-size: 200% 100%; background-size: 200% 100%;
border-radius: 10px; border-radius: 10px;
width: 0%; width: 0%;
@@ -1534,14 +1551,19 @@ body {
position: relative; position: relative;
overflow: hidden; overflow: hidden;
animation: progressFlow 3s linear infinite; animation: progressFlow 3s linear infinite;
box-shadow: box-shadow:
0 0 30px rgba(147, 51, 234, 0.6), 0 0 30px rgba(147, 51, 234, 0.6),
inset 0 1px 0 rgba(255, 255, 255, 0.3); inset 0 1px 0 rgba(255, 255, 255, 0.3);
} }
@keyframes progressFlow { @keyframes progressFlow {
0% { background-position: 200% 0; } 0% {
100% { background-position: -200% 0; } background-position: 200% 0;
}
100% {
background-position: -200% 0;
}
} }
.progress-bar-fill::after { .progress-bar-fill::after {
@@ -1552,16 +1574,22 @@ body {
right: 0; right: 0;
bottom: 0; bottom: 0;
background: linear-gradient(90deg, background: linear-gradient(90deg,
transparent 0%, transparent 0%,
rgba(255, 255, 255, 0.4) 50%, rgba(255, 255, 255, 0.4) 50%,
transparent 100% transparent 100%);
);
animation: progressPulse 1.5s ease-in-out infinite; animation: progressPulse 1.5s ease-in-out infinite;
} }
@keyframes progressPulse { @keyframes progressPulse {
0%, 100% { opacity: 0; }
50% { opacity: 1; } 0%,
100% {
opacity: 0;
}
50% {
opacity: 1;
}
} }
.progress-details { .progress-details {
@@ -1798,8 +1826,13 @@ body {
} }
@keyframes shimmer { @keyframes shimmer {
0% { transform: translateX(-100%); } 0% {
100% { transform: translateX(200%); } transform: translateX(-100%);
}
100% {
transform: translateX(200%);
}
} }
.mod-image img { .mod-image img {
@@ -2028,8 +2061,13 @@ body {
} }
@keyframes spin { @keyframes spin {
0% { transform: rotate(0deg); } 0% {
100% { transform: rotate(360deg); } transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
} }
.loading-mods span { .loading-mods span {
@@ -2312,39 +2350,39 @@ body {
.mods-header { .mods-header {
padding: 1rem 1.5rem; padding: 1rem 1.5rem;
} }
.mods-title { .mods-title {
font-size: 1.75rem; font-size: 1.75rem;
margin-bottom: 1rem; margin-bottom: 1rem;
} }
.mods-controls { .mods-controls {
gap: 0.75rem; gap: 0.75rem;
} }
.mods-controls button { .mods-controls button {
padding: 0.6rem 1.2rem; padding: 0.6rem 1.2rem;
font-size: 0.9rem; font-size: 0.9rem;
} }
.mods-main-content { .mods-main-content {
padding: 1.5rem; padding: 1.5rem;
} }
.mods-search-bar { .mods-search-bar {
flex-direction: column; flex-direction: column;
align-items: stretch; align-items: stretch;
gap: 1rem; gap: 1rem;
} }
.search-input-container { .search-input-container {
min-width: unset; min-width: unset;
} }
.mods-filters { .mods-filters {
gap: 0.75rem; gap: 0.75rem;
} }
.mods-list { .mods-list {
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 1rem; gap: 1rem;
@@ -2355,15 +2393,15 @@ body {
.mods-header { .mods-header {
padding: 1rem; padding: 1rem;
} }
.mods-main-content { .mods-main-content {
padding: 1rem; padding: 1rem;
} }
.mods-list { .mods-list {
grid-template-columns: 1fr; grid-template-columns: 1fr;
} }
.modal-content { .modal-content {
width: 95vw; width: 95vw;
padding: 1.5rem; padding: 1.5rem;
@@ -2593,7 +2631,7 @@ body {
justify-content: center; justify-content: center;
gap: 0.5rem; gap: 0.5rem;
overflow: hidden; overflow: hidden;
margin-top: 1%; margin-top: 1%;
} }
.mod-header { .mod-header {
@@ -2879,6 +2917,7 @@ body {
from { from {
opacity: 0; opacity: 0;
} }
to { to {
opacity: 1; opacity: 1;
} }
@@ -2902,6 +2941,7 @@ body {
transform: translateY(50px); transform: translateY(50px);
opacity: 0; opacity: 0;
} }
to { to {
transform: translateY(0); transform: translateY(0);
opacity: 1; opacity: 1;
@@ -3319,8 +3359,15 @@ body {
} }
@keyframes pulse-dot { @keyframes pulse-dot {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; } 0%,
100% {
opacity: 1;
}
50% {
opacity: 0.5;
}
} }
@@ -3373,6 +3420,7 @@ body {
opacity: 0; opacity: 0;
transform: translateY(10px); transform: translateY(10px);
} }
to { to {
opacity: 1; opacity: 1;
transform: translateY(0); transform: translateY(0);
@@ -3550,6 +3598,7 @@ body {
from { from {
opacity: 0; opacity: 0;
} }
to { to {
opacity: 1; opacity: 1;
} }
@@ -3571,6 +3620,7 @@ body {
opacity: 0; opacity: 0;
transform: translateY(30px); transform: translateY(30px);
} }
to { to {
opacity: 1; opacity: 1;
transform: translateY(0); transform: translateY(0);
@@ -3798,13 +3848,13 @@ body {
backdrop-filter: blur(10px); backdrop-filter: blur(10px);
} }
.settings-checkbox input[type="checkbox"]:checked + .checkmark { .settings-checkbox input[type="checkbox"]:checked+.checkmark {
background: linear-gradient(135deg, #9333ea, #3b82f6); background: linear-gradient(135deg, #9333ea, #3b82f6);
border-color: #9333ea; border-color: #9333ea;
box-shadow: 0 0 20px rgba(147, 51, 234, 0.4); box-shadow: 0 0 20px rgba(147, 51, 234, 0.4);
} }
.settings-checkbox input[type="checkbox"]:checked + .checkmark::after { .settings-checkbox input[type="checkbox"]:checked+.checkmark::after {
content: '✓'; content: '✓';
position: absolute; position: absolute;
top: 50%; top: 50%;
@@ -4051,7 +4101,7 @@ body {
background: linear-gradient(145deg, #1f2937 0%, #111827 50%, #0f172a 100%) !important; background: linear-gradient(145deg, #1f2937 0%, #111827 50%, #0f172a 100%) !important;
padding: 2rem !important; padding: 2rem !important;
border-radius: 1rem !important; border-radius: 1rem !important;
box-shadow: box-shadow:
0 25px 50px rgba(0, 0, 0, 0.8), 0 25px 50px rgba(0, 0, 0, 0.8),
0 0 0 1px rgba(255, 255, 255, 0.1), 0 0 0 1px rgba(255, 255, 255, 0.1),
inset 0 1px 0 rgba(255, 255, 255, 0.1) !important; inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;
@@ -4068,6 +4118,7 @@ body {
opacity: 0; opacity: 0;
transform: scale(0.8) translateY(-20px); transform: scale(0.8) translateY(-20px);
} }
to { to {
opacity: 1; opacity: 1;
transform: scale(1) translateY(0); transform: scale(1) translateY(0);
@@ -4166,7 +4217,7 @@ body {
border: none !important; border: none !important;
cursor: pointer !important; cursor: pointer !important;
transition: all 0.2s ease !important; transition: all 0.2s ease !important;
box-shadow: box-shadow:
0 4px 15px rgba(59, 130, 246, 0.3), 0 4px 15px rgba(59, 130, 246, 0.3),
0 0 0 1px rgba(255, 255, 255, 0.1) !important; 0 0 0 1px rgba(255, 255, 255, 0.1) !important;
text-decoration: none !important; text-decoration: none !important;
@@ -4176,7 +4227,7 @@ body {
.update-download-btn:hover:not(:disabled) { .update-download-btn:hover:not(:disabled) {
background: linear-gradient(135deg, #2563eb, #7c3aed) !important; background: linear-gradient(135deg, #2563eb, #7c3aed) !important;
transform: translateY(-1px) !important; transform: translateY(-1px) !important;
box-shadow: box-shadow:
0 8px 25px rgba(59, 130, 246, 0.4), 0 8px 25px rgba(59, 130, 246, 0.4),
0 0 0 1px rgba(255, 255, 255, 0.2) !important; 0 0 0 1px rgba(255, 255, 255, 0.2) !important;
} }
@@ -4189,7 +4240,7 @@ body {
background: linear-gradient(135deg, #6b7280, #9ca3af) !important; background: linear-gradient(135deg, #6b7280, #9ca3af) !important;
cursor: not-allowed !important; cursor: not-allowed !important;
transform: none !important; transform: none !important;
box-shadow: box-shadow:
0 2px 8px rgba(107, 114, 128, 0.3), 0 2px 8px rgba(107, 114, 128, 0.3),
0 0 0 1px rgba(255, 255, 255, 0.05) !important; 0 0 0 1px rgba(255, 255, 255, 0.05) !important;
} }
@@ -4208,8 +4259,15 @@ body {
} }
@keyframes updatePulse { @keyframes updatePulse {
0%, 100% { transform: scale(1); }
50% { transform: scale(1.02); } 0%,
100% {
transform: scale(1);
}
50% {
transform: scale(1.02);
}
} }
@@ -4330,6 +4388,7 @@ body {
opacity: 0; opacity: 0;
transform: translateY(-20px) scale(0.95); transform: translateY(-20px) scale(0.95);
} }
to { to {
opacity: 1; opacity: 1;
transform: translateY(0) scale(1); transform: translateY(0) scale(1);
@@ -4743,29 +4802,29 @@ body {
width: 95vw; width: 95vw;
max-height: 90vh; max-height: 90vh;
} }
.uuid-modal-body { .uuid-modal-body {
padding: 1rem; padding: 1rem;
gap: 1.5rem; gap: 1.5rem;
} }
.uuid-current-display, .uuid-current-display,
.uuid-custom-form { .uuid-custom-form {
flex-direction: column; flex-direction: column;
} }
.uuid-list-header { .uuid-list-header {
flex-direction: column; flex-direction: column;
align-items: stretch; align-items: stretch;
gap: 1rem; gap: 1rem;
} }
.uuid-list-item { .uuid-list-item {
flex-direction: column; flex-direction: column;
align-items: stretch; align-items: stretch;
gap: 1rem; gap: 1rem;
} }
.uuid-item-actions { .uuid-item-actions {
justify-content: center; justify-content: center;
} }
@@ -4773,16 +4832,27 @@ body {
/* Chat Badges et Animations */ /* Chat Badges et Animations */
@keyframes rainbow { @keyframes rainbow {
0% { background-position: 0% 50%; } 0% {
50% { background-position: 100% 50%; } background-position: 0% 50%;
100% { background-position: 0% 50%; } }
50% {
background-position: 100% 50%;
}
100% {
background-position: 0% 50%;
}
} }
@keyframes contributorGlow { @keyframes contributorGlow {
0%, 100% {
0%,
100% {
background-position: 0% 50%; background-position: 0% 50%;
filter: brightness(1); filter: brightness(1);
} }
50% { 50% {
background-position: 100% 50%; background-position: 100% 50%;
filter: brightness(1.2); filter: brightness(1.2);
@@ -4929,12 +4999,12 @@ body {
transition: all 0.3s ease; transition: all 0.3s ease;
} }
.color-type-option input[type="radio"]:checked + .radio-custom { .color-type-option input[type="radio"]:checked+.radio-custom {
border-color: #9333ea; border-color: #9333ea;
background: rgba(147, 51, 234, 0.2); background: rgba(147, 51, 234, 0.2);
} }
.color-type-option input[type="radio"]:checked + .radio-custom::after { .color-type-option input[type="radio"]:checked+.radio-custom::after {
content: ''; content: '';
position: absolute; position: absolute;
top: 50%; top: 50%;
@@ -5090,6 +5160,7 @@ body {
transform: translateY(-2px); transform: translateY(-2px);
box-shadow: 0 8px 16px rgba(147, 51, 234, 0.4); box-shadow: 0 8px 16px rgba(147, 51, 234, 0.4);
} }
.color-picker-container { .color-picker-container {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
@@ -5114,3 +5185,238 @@ body {
border-color: #fff; border-color: #fff;
box-shadow: 0 0 10px rgba(255, 255, 255, 0.5); box-shadow: 0 0 10px rgba(255, 255, 255, 0.5);
} }
/* Profile Selector Styles */
.profile-selector {
position: relative;
pointer-events: auto;
margin-right: auto;
margin-left: 1rem;
z-index: 9999 !important;
}
.profile-btn {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.5rem 1rem;
background: rgba(0, 0, 0, 0.4);
backdrop-filter: blur(20px);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 12px;
color: white;
cursor: pointer;
font-family: 'Space Grotesk', sans-serif;
font-weight: 600;
transition: all 0.2s ease;
z-index: 100000 !important;
pointer-events: auto !important;
}
.profile-btn:hover {
background: rgba(255, 255, 255, 0.1);
border-color: rgba(147, 51, 234, 0.4);
}
.profile-btn i {
color: #9333ea;
}
.profile-dropdown {
position: absolute;
top: 100%;
left: 0;
margin-top: 0.5rem;
width: 200px;
background: rgba(20, 20, 20, 0.95);
backdrop-filter: blur(20px);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 12px;
padding: 0.5rem;
display: none;
/* Toggled by JS */
flex-direction: column;
z-index: 2000;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
animation: fadeIn 0.1s ease;
}
.profile-dropdown.show {
display: flex;
}
.profile-item {
padding: 0.6rem 0.8rem;
border-radius: 8px;
cursor: pointer;
display: flex;
align-items: center;
gap: 0.5rem;
color: #ccc;
transition: all 0.2s;
}
.profile-item:hover {
background: rgba(255, 255, 255, 0.1);
color: white;
}
.profile-item.active {
background: rgba(147, 51, 234, 0.2);
color: white;
font-weight: bold;
}
.profile-item.active::before {
content: '•';
color: #9333ea;
font-size: 1.2rem;
}
.profile-divider {
height: 1px;
background: rgba(255, 255, 255, 0.1);
margin: 0.5rem 0;
}
.profile-action {
padding: 0.6rem 0.8rem;
border-radius: 8px;
cursor: pointer;
display: flex;
align-items: center;
gap: 0.5rem;
color: #9333ea;
font-weight: 600;
}
.profile-action:hover {
background: rgba(147, 51, 234, 0.1);
}
/* Profile Modal Styles */
.profile-modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.8);
backdrop-filter: blur(5px);
z-index: 9999;
display: flex;
justify-content: center;
align-items: center;
animation: fadeIn 0.2s ease;
}
.profile-modal-content {
background: #111;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 16px;
width: 500px;
max-width: 90%;
box-shadow: 0 20px 50px rgba(0, 0, 0, 0.6);
}
.profile-modal-header {
padding: 1.5rem;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
display: flex;
justify-content: space-between;
align-items: center;
}
.profile-modal-title {
margin: 0;
font-size: 1.5rem;
color: white;
}
.profile-modal-body {
padding: 1.5rem;
}
.profile-manager-list {
max-height: 300px;
overflow-y: auto;
margin-bottom: 1.5rem;
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.profile-manager-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.8rem;
background: rgba(255, 255, 255, 0.05);
border-radius: 8px;
border: 1px solid transparent;
}
.profile-manager-item:hover {
border-color: rgba(255, 255, 255, 0.1);
background: rgba(255, 255, 255, 0.08);
}
.profile-manager-item.active {
border-color: #9333ea;
background: rgba(147, 51, 234, 0.1);
}
.profile-delete-btn {
background: transparent;
border: none;
color: #ef4444;
cursor: pointer;
font-size: 1rem;
padding: 0.4rem;
border-radius: 6px;
transition: all 0.2s;
}
.profile-delete-btn:hover {
background: rgba(239, 68, 68, 0.1);
}
.profile-create-section {
display: flex;
gap: 0.5rem;
}
.profile-input {
flex: 1;
padding: 0.8rem;
border-radius: 8px;
border: 1px solid rgba(255, 255, 255, 0.1);
background: rgba(0, 0, 0, 0.5);
color: white;
}
.profile-create-btn {
padding: 0 1.2rem;
background: #9333ea;
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
font-weight: 600;
transition: all 0.2s;
}
.profile-create-btn:hover {
background: #7c3aed;
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}

View File

@@ -78,7 +78,14 @@ See [BUILD.md](BUILD.md) for comprehensive build instructions.
## 📋 Changelog ## 📋 Changelog
### 🆕 v2.0.2 *(Latest)* ### 🆕 v2.0.2a *(Minor Update)*
- 🧑‍🚀 **Profiles System** — Added proper profile management: create, switch, and delete profiles. Each profile now has its own **isolated mod list**.
- 🔒 **Mod Isolation** — Fixed ModManager so mods are **strictly scoped to the active profile**. Browsing and installing now only affects the selected profile.
- 🚨 **Critical Path Fix** — Resolved a macOS bug where mods were being saved to a Windows path (`~/AppData/Local`) instead of `~/Library/Application Support`. Mods now save to the **correct location** and load properly in-game.
- 🛡️ **Stability Improvements** — Added an **auto-sync step before every launch** to ensure the physical mods folder always matches the active profile.
- 🎨 **UI Enhancements** — Added a **profile selector dropdown** and a **profile management modal**.
### 🆕 v2.0.2
- 🎮 **Discord RPC Integration** - Added Discord Rich Presence with toggle in settings (enabled by default) - 🎮 **Discord RPC Integration** - Added Discord Rich Presence with toggle in settings (enabled by default)
- 🌐 **Cross-Platform Multiplayer** - Added multiplayer patch support for Windows, Linux, and macOS - 🌐 **Cross-Platform Multiplayer** - Added multiplayer patch support for Windows, Linux, and macOS
- 🎨 **Chat Improvements** - Simplified chat color system - 🎨 **Chat Improvements** - Simplified chat color system

View File

@@ -14,6 +14,10 @@ function getAuthDomain() {
} }
// Then check config file // Then check config file
const config = loadConfig(); const config = loadConfig();
if (config.activeProfileId && config.profiles && config.profiles[config.activeProfileId]) {
// Allow profile to override auth domain if ever needed
// but for now stick to global or env
}
if (config.authDomain) { if (config.authDomain) {
return config.authDomain; return config.authDomain;
} }
@@ -111,6 +115,16 @@ function saveJavaPath(javaPath) {
function loadJavaPath() { function loadJavaPath() {
const config = loadConfig(); const config = loadConfig();
// Prefer Active Profile's Java Path
if (config.activeProfileId && config.profiles && config.profiles[config.activeProfileId]) {
const profile = config.profiles[config.activeProfileId];
if (profile.javaPath && profile.javaPath.trim().length > 0) {
return profile.javaPath;
}
}
// Fallback to global setting
return config.javaPath || ''; return config.javaPath || '';
} }
@@ -135,14 +149,25 @@ function loadDiscordRPC() {
function saveModsToConfig(mods) { function saveModsToConfig(mods) {
try { try {
let config = loadConfig(); const config = loadConfig();
config.installedMods = mods;
// Config migration handles structure, but mod saves must go to the ACTIVE profile.
// Global installedMods is kept mainly for reference/migration.
// The profile is the source of truth for enabled mods.
if (config.activeProfileId && config.profiles && config.profiles[config.activeProfileId]) {
config.profiles[config.activeProfileId].mods = mods;
} else {
// Fallback for legacy or no-profile state
config.installedMods = mods;
}
const configDir = path.dirname(CONFIG_FILE); const configDir = path.dirname(CONFIG_FILE);
if (!fs.existsSync(configDir)) { if (!fs.existsSync(configDir)) {
fs.mkdirSync(configDir, { recursive: true }); fs.mkdirSync(configDir, { recursive: true });
} }
fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2)); fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
console.log('Mods saved to config.json'); console.log('Mods saved to config.json');
} catch (error) { } catch (error) {
@@ -153,6 +178,12 @@ function saveModsToConfig(mods) {
function loadModsFromConfig() { function loadModsFromConfig() {
try { try {
const config = loadConfig(); const config = loadConfig();
// Prefer Active Profile
if (config.activeProfileId && config.profiles && config.profiles[config.activeProfileId]) {
return config.profiles[config.activeProfileId].mods || [];
}
return config.installedMods || []; return config.installedMods || [];
} catch (error) { } catch (error) {
console.error('Error loading mods from config:', error); console.error('Error loading mods from config:', error);
@@ -162,19 +193,19 @@ function loadModsFromConfig() {
function isFirstLaunch() { function isFirstLaunch() {
const config = loadConfig(); const config = loadConfig();
if ('hasLaunchedBefore' in config) { if ('hasLaunchedBefore' in config) {
return !config.hasLaunchedBefore; return !config.hasLaunchedBefore;
} }
const hasUserData = config.installPath || config.username || config.javaPath || const hasUserData = config.installPath || config.username || config.javaPath ||
config.chatUsername || config.userUuids || config.chatUsername || config.userUuids ||
Object.keys(config).length > 0; Object.keys(config).length > 0;
if (!hasUserData) { if (!hasUserData) {
return true; return true;
} }
return true; return true;
} }
@@ -195,17 +226,17 @@ function getAllUuidMappings() {
function setUuidForUser(username, uuid) { function setUuidForUser(username, uuid) {
const { v4: uuidv4, validate: validateUuid } = require('uuid'); const { v4: uuidv4, validate: validateUuid } = require('uuid');
// Validate UUID format // Validate UUID format
if (!validateUuid(uuid)) { if (!validateUuid(uuid)) {
throw new Error('Invalid UUID format'); throw new Error('Invalid UUID format');
} }
const config = loadConfig(); const config = loadConfig();
const userUuids = config.userUuids || {}; const userUuids = config.userUuids || {};
userUuids[username] = uuid; userUuids[username] = uuid;
saveConfig({ userUuids }); saveConfig({ userUuids });
return uuid; return uuid;
} }
@@ -217,13 +248,13 @@ function generateNewUuid() {
function deleteUuidForUser(username) { function deleteUuidForUser(username) {
const config = loadConfig(); const config = loadConfig();
const userUuids = config.userUuids || {}; const userUuids = config.userUuids || {};
if (userUuids[username]) { if (userUuids[username]) {
delete userUuids[username]; delete userUuids[username];
saveConfig({ userUuids }); saveConfig({ userUuids });
return true; return true;
} }
return false; return false;
} }
@@ -231,7 +262,7 @@ function resetCurrentUserUuid() {
const username = loadUsername(); const username = loadUsername();
const { v4: uuidv4 } = require('uuid'); const { v4: uuidv4 } = require('uuid');
const newUuid = uuidv4(); const newUuid = uuidv4();
return setUuidForUser(username, newUuid); return setUuidForUser(username, newUuid);
} }

View File

@@ -77,32 +77,32 @@ function findClientPath(gameLatest) {
function findUserDataPath(gameLatest) { function findUserDataPath(gameLatest) {
const candidates = []; const candidates = [];
candidates.push(path.join(gameLatest, 'Client', 'UserData')); candidates.push(path.join(gameLatest, 'Client', 'UserData'));
candidates.push(path.join(gameLatest, 'Client', 'Hytale.app', 'Contents', 'UserData')); candidates.push(path.join(gameLatest, 'Client', 'Hytale.app', 'Contents', 'UserData'));
candidates.push(path.join(gameLatest, 'Hytale.app', 'Contents', 'UserData')); candidates.push(path.join(gameLatest, 'Hytale.app', 'Contents', 'UserData'));
candidates.push(path.join(gameLatest, 'UserData')); candidates.push(path.join(gameLatest, 'UserData'));
candidates.push(path.join(gameLatest, 'Client', 'UserData')); candidates.push(path.join(gameLatest, 'Client', 'UserData'));
for (const candidate of candidates) { for (const candidate of candidates) {
if (fs.existsSync(candidate)) { if (fs.existsSync(candidate)) {
return candidate; return candidate;
} }
} }
let defaultPath; let defaultPath;
if (process.platform === 'darwin') { if (process.platform === 'darwin') {
defaultPath = path.join(gameLatest, 'Client', 'UserData'); defaultPath = path.join(gameLatest, 'Client', 'UserData');
} else { } else {
defaultPath = path.join(gameLatest, 'Client', 'UserData'); defaultPath = path.join(gameLatest, 'Client', 'UserData');
} }
if (!fs.existsSync(defaultPath)) { if (!fs.existsSync(defaultPath)) {
fs.mkdirSync(defaultPath, { recursive: true }); fs.mkdirSync(defaultPath, { recursive: true });
} }
return defaultPath; return defaultPath;
} }
@@ -110,15 +110,15 @@ function findUserDataRecursive(gameLatest) {
function searchDirectory(dir) { function searchDirectory(dir) {
try { try {
const items = fs.readdirSync(dir, { withFileTypes: true }); const items = fs.readdirSync(dir, { withFileTypes: true });
for (const item of items) { for (const item of items) {
if (item.isDirectory()) { if (item.isDirectory()) {
const fullPath = path.join(dir, item.name); const fullPath = path.join(dir, item.name);
if (item.name === 'UserData') { if (item.name === 'UserData') {
return fullPath; return fullPath;
} }
const found = searchDirectory(fullPath); const found = searchDirectory(fullPath);
if (found) { if (found) {
return found; return found;
@@ -127,14 +127,14 @@ function findUserDataRecursive(gameLatest) {
} }
} catch (error) { } catch (error) {
} }
return null; return null;
} }
if (!fs.existsSync(gameLatest)) { if (!fs.existsSync(gameLatest)) {
return null; return null;
} }
const found = searchDirectory(gameLatest); const found = searchDirectory(gameLatest);
return found; return found;
} }
@@ -152,16 +152,14 @@ async function getModsPath(customInstallPath = null) {
} }
if (!installPath) { if (!installPath) {
const localAppData = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'); // Use the standard app directory logic which handles platforms correctly
installPath = path.join(localAppData, 'HytaleF2P'); installPath = getAppDir();
} else {
installPath = path.join(installPath, 'HytaleF2P');
} }
const gameLatest = path.join(installPath, 'release', 'package', 'game', 'latest'); const gameLatest = path.join(installPath, 'release', 'package', 'game', 'latest');
const userDataPath = findUserDataPath(gameLatest); const userDataPath = findUserDataPath(gameLatest);
const modsPath = path.join(userDataPath, 'Mods'); const modsPath = path.join(userDataPath, 'Mods');
const disabledModsPath = path.join(userDataPath, 'DisabledMods'); const disabledModsPath = path.join(userDataPath, 'DisabledMods');

View File

@@ -11,6 +11,7 @@ const { saveUsername, saveInstallPath, loadJavaPath, getUuidForUser, getAuthServ
const { resolveJavaPath, getJavaExec, getBundledJavaPath, detectSystemJava, JAVA_EXECUTABLE } = require('./javaManager'); const { resolveJavaPath, getJavaExec, getBundledJavaPath, detectSystemJava, JAVA_EXECUTABLE } = require('./javaManager');
const { getInstalledClientVersion, getLatestClientVersion } = require('../services/versionManager'); const { getInstalledClientVersion, getLatestClientVersion } = require('../services/versionManager');
const { updateGameFiles } = require('./gameManager'); const { updateGameFiles } = require('./gameManager');
const { syncModsForCurrentProfile } = require('./modManager');
// Client patcher for custom auth server (sanasol.ws) // Client patcher for custom auth server (sanasol.ws)
let clientPatcher = null; let clientPatcher = null;
@@ -130,7 +131,7 @@ async function launchGame(playerName = 'Player', progressCallback, javaPathOverr
} }
} else { } else {
javaBin = getJavaExec(customJreDir); javaBin = getJavaExec(customJreDir);
if (!getBundledJavaPath(customJreDir)) { if (!getBundledJavaPath(customJreDir)) {
const fallback = await detectSystemJava(); const fallback = await detectSystemJava();
if (fallback) { if (fallback) {
@@ -192,9 +193,9 @@ async function launchGame(playerName = 'Player', progressCallback, javaPathOverr
const serverDir = path.join(gameLatest, 'Server'); const serverDir = path.join(gameLatest, 'Server');
const signPath = async (targetPath, deep = false) => { const signPath = async (targetPath, deep = false) => {
await execAsync(`xattr -cr "${targetPath}"`).catch(() => {}); await execAsync(`xattr -cr "${targetPath}"`).catch(() => { });
const deepFlag = deep ? '--deep ' : ''; const deepFlag = deep ? '--deep ' : '';
await execAsync(`codesign --force ${deepFlag}--sign - "${targetPath}"`).catch(() => {}); await execAsync(`codesign --force ${deepFlag}--sign - "${targetPath}"`).catch(() => { });
}; };
if (fs.existsSync(appBundle)) { if (fs.existsSync(appBundle)) {
@@ -216,8 +217,8 @@ async function launchGame(playerName = 'Player', progressCallback, javaPathOverr
} }
if (fs.existsSync(serverDir)) { if (fs.existsSync(serverDir)) {
await execAsync(`xattr -cr "${serverDir}"`).catch(() => {}); await execAsync(`xattr -cr "${serverDir}"`).catch(() => { });
await execAsync(`find "${serverDir}" -type f -perm +111 -exec codesign --force --sign - {} \\;`).catch(() => {}); await execAsync(`find "${serverDir}" -type f -perm +111 -exec codesign --force --sign - {} \\;`).catch(() => { });
console.log('Signed server binaries (after patching)'); console.log('Signed server binaries (after patching)');
} }
@@ -260,11 +261,23 @@ exec "$REAL_JAVA" "\${ARGS[@]}"
if (progressCallback) { if (progressCallback) {
progressCallback('Starting game...', null, null, null, null); progressCallback('Starting game...', null, null, null, null);
} }
// Ensure mods are synced for the active profile before launching
try {
console.log('Syncing mods for active profile before launch...');
if (progressCallback) progressCallback('Syncing mods...', null, null, null, null);
await syncModsForCurrentProfile();
} catch (syncError) {
console.error('Failed to sync mods before launch:', syncError);
// Continue anyway? Or fail?
// Warn user but continue might be safer to avoid blocking play if sync is just glitchy
}
console.log('Starting game...'); console.log('Starting game...');
console.log(`Command: "${clientPath}" ${args.join(' ')}`); console.log(`Command: "${clientPath}" ${args.join(' ')}`);
const env = { ...process.env }; const env = { ...process.env };
const waylandEnv = setupWaylandEnvironment(); const waylandEnv = setupWaylandEnvironment();
Object.assign(env, waylandEnv); Object.assign(env, waylandEnv);
@@ -276,8 +289,8 @@ exec "$REAL_JAVA" "\${ARGS[@]}"
}; };
if (process.platform === 'win32') { if (process.platform === 'win32') {
spawnOptions.shell = false; spawnOptions.shell = false;
spawnOptions.windowsHide = true; spawnOptions.windowsHide = true;
} }
const child = spawn(clientPath, args, spawnOptions); const child = spawn(clientPath, args, spawnOptions);
@@ -371,12 +384,12 @@ async function launchGameWithVersionCheck(playerName = 'Player', progressCallbac
try { try {
await updateGameFiles(latestVersion, progressCallback, customGameDir, customToolsDir, customCacheDir); await updateGameFiles(latestVersion, progressCallback, customGameDir, customToolsDir, customCacheDir);
console.log('Game updated successfully, waiting before launch...'); console.log('Game updated successfully, waiting before launch...');
if (progressCallback) { if (progressCallback) {
progressCallback('Preparing game launch...', 90, null, null, null); progressCallback('Preparing game launch...', 90, null, null, null);
} }
await new Promise(resolve => setTimeout(resolve, 3000)); await new Promise(resolve => setTimeout(resolve, 3000));
} catch (updateError) { } catch (updateError) {
console.error('Update failed:', updateError); console.error('Update failed:', updateError);
if (progressCallback) { if (progressCallback) {

View File

@@ -4,6 +4,7 @@ const crypto = require('crypto');
const axios = require('axios'); const axios = require('axios');
const { getModsPath } = require('../core/paths'); const { getModsPath } = require('../core/paths');
const { saveModsToConfig, loadModsFromConfig } = require('../core/config'); const { saveModsToConfig, loadModsFromConfig } = require('../core/config');
const profileManager = require('./profileManager');
function generateModId(filename) { function generateModId(filename) {
return crypto.createHash('md5').update(filename).digest('hex').substring(0, 8); return crypto.createHash('md5').update(filename).digest('hex').substring(0, 8);
@@ -11,13 +12,13 @@ function generateModId(filename) {
function extractModName(filename) { function extractModName(filename) {
let name = path.parse(filename).name; let name = path.parse(filename).name;
name = name.replace(/-v?\d+\.[\d\.]+.*$/i, ''); name = name.replace(/-v?\d+\.[\d\.]+.*$/i, '');
name = name.replace(/-\d+\.[\d\.]+.*$/i, ''); name = name.replace(/-\d+\.[\d\.]+.*$/i, '');
name = name.replace(/[-_]/g, ' '); name = name.replace(/[-_]/g, ' ');
name = name.replace(/\b\w/g, l => l.toUpperCase()); name = name.replace(/\b\w/g, l => l.toUpperCase());
return name || 'Unknown Mod'; return name || 'Unknown Mod';
} }
@@ -26,77 +27,53 @@ function extractVersion(filename) {
return versionMatch ? versionMatch[1] : null; return versionMatch ? versionMatch[1] : null;
} }
// Helper to get mods from active profile
function getProfileMods() {
const profile = profileManager.getActiveProfile();
return profile ? (profile.mods || []) : [];
}
async function loadInstalledMods(modsPath) { async function loadInstalledMods(modsPath) {
try { try {
const configMods = loadModsFromConfig(); const activeProfile = profileManager.getActiveProfile();
const modsMap = new Map(); if (!activeProfile) return [];
configMods.forEach(mod => { const profileMods = activeProfile.mods || [];
modsMap.set(mod.fileName, mod); const profileModFiles = new Set(profileMods.map(m => m.fileName));
});
// We only return mods that are explicitly in the profile
if (fs.existsSync(modsPath)) { // Check which ones are physically present (either in mods/ or DisabledMods/)
const files = fs.readdirSync(modsPath);
const physicalModsPath = modsPath; // .../mods
for (const file of files) {
const filePath = path.join(modsPath, file);
const stats = fs.statSync(filePath);
if (stats.isFile() && (file.endsWith('.jar') || file.endsWith('.zip'))) {
const configMod = modsMap.get(file);
const modInfo = {
id: configMod?.id || generateModId(file),
name: configMod?.name || extractModName(file),
version: configMod?.version || extractVersion(file) || '1.0.0',
description: configMod?.description || 'Installed mod',
author: configMod?.author || 'Unknown',
enabled: true,
filePath: filePath,
fileName: file,
fileSize: configMod?.fileSize || stats.size,
dateInstalled: configMod?.dateInstalled || stats.birthtime || stats.mtime,
curseForgeId: configMod?.curseForgeId,
curseForgeFileId: configMod?.curseForgeFileId
};
modsMap.set(file, modInfo);
}
}
}
const disabledModsPath = path.join(path.dirname(modsPath), 'DisabledMods'); const disabledModsPath = path.join(path.dirname(modsPath), 'DisabledMods');
if (fs.existsSync(disabledModsPath)) {
const files = fs.readdirSync(disabledModsPath); const validMods = [];
for (const file of files) { for (const modConfig of profileMods) {
const filePath = path.join(disabledModsPath, file); // Check if file exists in either location
const stats = fs.statSync(filePath); const inEnabled = fs.existsSync(path.join(physicalModsPath, modConfig.fileName));
const inDisabled = fs.existsSync(path.join(disabledModsPath, modConfig.fileName));
if (stats.isFile() && (file.endsWith('.jar') || file.endsWith('.zip'))) {
const configMod = modsMap.get(file); if (inEnabled || inDisabled) {
validMods.push({
const modInfo = { ...modConfig,
id: configMod?.id || generateModId(file), // Set filePath based on physical location
name: configMod?.name || extractModName(file), filePath: inEnabled ? path.join(physicalModsPath, modConfig.fileName) : path.join(disabledModsPath, modConfig.fileName),
version: configMod?.version || extractVersion(file) || '1.0.0', enabled: modConfig.enabled !== false // Default true
description: configMod?.description || 'Disabled mod', });
author: configMod?.author || 'Unknown', } else {
enabled: false, console.warn(`[ModManager] Mod ${modConfig.fileName} listed in profile but not found on disk.`);
filePath: filePath, // Include it so user can see it's missing or remove it
fileName: file, validMods.push({
fileSize: configMod?.fileSize || stats.size, ...modConfig,
dateInstalled: configMod?.dateInstalled || stats.birthtime || stats.mtime, filePath: null,
curseForgeId: configMod?.curseForgeId, missing: true,
curseForgeFileId: configMod?.curseForgeFileId enabled: modConfig.enabled !== false
}; });
modsMap.set(file, modInfo);
}
} }
} }
return Array.from(modsMap.values()); return validMods;
} catch (error) { } catch (error) {
console.error('Error loading installed mods:', error); console.error('Error loading installed mods:', error);
return []; return [];
@@ -106,13 +83,13 @@ async function loadInstalledMods(modsPath) {
async function downloadMod(modInfo) { async function downloadMod(modInfo) {
try { try {
const modsPath = await getModsPath(); const modsPath = await getModsPath();
if (!modInfo.downloadUrl && !modInfo.fileId) { if (!modInfo.downloadUrl && !modInfo.fileId) {
throw new Error('No download URL or file ID provided'); throw new Error('No download URL or file ID provided');
} }
let downloadUrl = modInfo.downloadUrl; let downloadUrl = modInfo.downloadUrl;
if (!downloadUrl && modInfo.fileId && modInfo.modId) { if (!downloadUrl && modInfo.fileId && modInfo.modId) {
const response = await axios.get(`https://api.curseforge.com/v1/mods/${modInfo.modId}/files/${modInfo.fileId}`, { const response = await axios.get(`https://api.curseforge.com/v1/mods/${modInfo.modId}/files/${modInfo.fileId}`, {
headers: { headers: {
@@ -120,56 +97,61 @@ async function downloadMod(modInfo) {
'Accept': 'application/json' 'Accept': 'application/json'
} }
}); });
downloadUrl = response.data.data.downloadUrl; downloadUrl = response.data.data.downloadUrl;
} }
if (!downloadUrl) { if (!downloadUrl) {
throw new Error('Could not determine download URL'); throw new Error('Could not determine download URL');
} }
const fileName = modInfo.fileName || `mod-${modInfo.modId}.jar`; const fileName = modInfo.fileName || `mod-${modInfo.modId}.jar`;
const filePath = path.join(modsPath, fileName); const filePath = path.join(modsPath, fileName);
const response = await axios({ const response = await axios({
method: 'get', method: 'get',
url: downloadUrl, url: downloadUrl,
responseType: 'stream' responseType: 'stream'
}); });
const writer = fs.createWriteStream(filePath); const writer = fs.createWriteStream(filePath);
response.data.pipe(writer); response.data.pipe(writer);
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
writer.on('finish', () => { writer.on('finish', () => {
const configMods = loadModsFromConfig(); // NEW: Update Active Profile instead of global config
const newMod = { const activeProfile = profileManager.getActiveProfile();
id: modInfo.id || generateModId(fileName), if (activeProfile) {
name: modInfo.name || extractModName(fileName), const newMod = {
version: modInfo.version || '1.0.0', id: modInfo.id || generateModId(fileName),
description: modInfo.summary || modInfo.description || 'Downloaded from CurseForge', name: modInfo.name || extractModName(fileName),
author: modInfo.author || 'Unknown', version: modInfo.version || '1.0.0',
enabled: true, description: modInfo.summary || modInfo.description || 'Downloaded from CurseForge',
fileName: fileName, author: modInfo.author || 'Unknown',
fileSize: fs.statSync(filePath).size, enabled: true,
dateInstalled: new Date().toISOString(), fileName: fileName,
curseForgeId: modInfo.modId, fileSize: fs.statSync(filePath).size,
curseForgeFileId: modInfo.fileId dateInstalled: new Date().toISOString(),
}; curseForgeId: modInfo.modId,
curseForgeFileId: modInfo.fileId
configMods.push(newMod); };
saveModsToConfig(configMods);
const updatedMods = [...(activeProfile.mods || []), newMod];
resolve({ profileManager.updateProfile(activeProfile.id, { mods: updatedMods });
success: true,
filePath: filePath, resolve({
fileName: fileName, success: true,
modInfo: newMod filePath: filePath,
}); fileName: fileName,
modInfo: newMod
});
} else {
reject(new Error('No active profile to save mod to'));
}
}); });
writer.on('error', reject); writer.on('error', reject);
}); });
} catch (error) { } catch (error) {
console.error('Error downloading mod:', error); console.error('Error downloading mod:', error);
return { return {
@@ -181,36 +163,39 @@ async function downloadMod(modInfo) {
async function uninstallMod(modId, modsPath) { async function uninstallMod(modId, modsPath) {
try { try {
const configMods = loadModsFromConfig(); const activeProfile = profileManager.getActiveProfile();
const mod = configMods.find(m => m.id === modId); if (!activeProfile) throw new Error('No active profile');
const profileMods = activeProfile.mods || [];
const mod = profileMods.find(m => m.id === modId);
if (!mod) { if (!mod) {
throw new Error('Mod not found in config'); throw new Error('Mod not found in profile');
} }
const disabledModsPath = path.join(path.dirname(modsPath), 'DisabledMods'); const disabledModsPath = path.join(path.dirname(modsPath), 'DisabledMods');
const enabledPath = path.join(modsPath, mod.fileName); const enabledPath = path.join(modsPath, mod.fileName);
const disabledPath = path.join(disabledModsPath, mod.fileName); const disabledPath = path.join(disabledModsPath, mod.fileName);
let fileRemoved = false; let fileRemoved = false;
// Try to remove file from both locations to be safe
if (fs.existsSync(enabledPath)) { if (fs.existsSync(enabledPath)) {
fs.unlinkSync(enabledPath); fs.unlinkSync(enabledPath);
fileRemoved = true; fileRemoved = true;
console.log('Removed mod from Mods folder:', enabledPath);
} else if (fs.existsSync(disabledPath)) {
fs.unlinkSync(disabledPath);
fileRemoved = true;
console.log('Removed mod from DisabledMods folder:', disabledPath);
} }
if (fs.existsSync(disabledPath)) {
try { fs.unlinkSync(disabledPath); fileRemoved = true; } catch (e) { }
}
if (!fileRemoved) { if (!fileRemoved) {
console.warn('Mod file not found on filesystem, removing from config anyway'); console.warn('Mod file not found on filesystem, removing from profile anyway');
} }
const updatedMods = configMods.filter(m => m.id !== modId); const updatedMods = profileMods.filter(m => m.id !== modId);
saveModsToConfig(updatedMods); profileManager.updateProfile(activeProfile.id, { mods: updatedMods });
console.log('Mod removed from config.json');
console.log('Mod removed from profile');
return { success: true }; return { success: true };
} catch (error) { } catch (error) {
console.error('Error uninstalling mod:', error); console.error('Error uninstalling mod:', error);
@@ -223,38 +208,53 @@ async function uninstallMod(modId, modsPath) {
async function toggleMod(modId, modsPath) { async function toggleMod(modId, modsPath) {
try { try {
const mods = await loadInstalledMods(modsPath); const activeProfile = profileManager.getActiveProfile();
const mod = mods.find(m => m.id === modId); if (!activeProfile) throw new Error('No active profile');
if (!mod) { const profileMods = activeProfile.mods || [];
throw new Error('Mod not found'); const modIndex = profileMods.findIndex(m => m.id === modId);
if (modIndex === -1) {
throw new Error('Mod not found in profile');
} }
const mod = profileMods[modIndex];
const newEnabled = !mod.enabled; // Toggle
// Update Profile First
const updatedMods = [...profileMods];
updatedMods[modIndex] = { ...mod, enabled: newEnabled };
profileManager.updateProfile(activeProfile.id, { mods: updatedMods });
// Manually move the file to reflect the new state
const disabledModsPath = path.join(path.dirname(modsPath), 'DisabledMods'); const disabledModsPath = path.join(path.dirname(modsPath), 'DisabledMods');
if (!fs.existsSync(disabledModsPath)) { if (!fs.existsSync(disabledModsPath)) fs.mkdirSync(disabledModsPath, { recursive: true });
fs.mkdirSync(disabledModsPath, { recursive: true });
}
const currentPath = mod.filePath; const currentPath = mod.enabled ? path.join(modsPath, mod.fileName) : path.join(disabledModsPath, mod.fileName);
let newPath, newEnabled;
if (mod.enabled) { // Determine target paths
newPath = path.join(disabledModsPath, path.basename(currentPath));
newEnabled = false; const targetDir = newEnabled ? modsPath : disabledModsPath;
const targetPath = path.join(targetDir, mod.fileName);
if (fs.existsSync(currentPath)) {
fs.renameSync(currentPath, targetPath);
} else { } else {
newPath = path.join(modsPath, path.basename(currentPath)); // Fallback: check if it's already in target?
newEnabled = true;
if (fs.existsSync(targetPath)) {
// It's already there, maybe just state was wrong.
console.log(`[ModManager] Mod ${mod.fileName} is already in the correct state`);
} else {
// Try finding it
const altPath = mod.enabled ? path.join(disabledModsPath, mod.fileName) : path.join(modsPath, mod.fileName);
if (fs.existsSync(altPath)) fs.renameSync(altPath, targetPath);
}
} }
fs.renameSync(currentPath, newPath);
const configMods = loadModsFromConfig();
const configModIndex = configMods.findIndex(m => m.id === modId);
if (configModIndex !== -1) {
configMods[configModIndex].enabled = newEnabled;
saveModsToConfig(configMods);
}
return { success: true, enabled: newEnabled }; return { success: true, enabled: newEnabled };
} catch (error) { } catch (error) {
console.error('Error toggling mod:', error); console.error('Error toggling mod:', error);
@@ -265,11 +265,69 @@ async function toggleMod(modId, modsPath) {
} }
} }
async function syncModsForCurrentProfile() {
try {
const activeProfile = profileManager.getActiveProfile();
if (!activeProfile) {
console.warn('No active profile found during mod sync');
return;
}
console.log(`[ModManager] Syncing mods for profile: ${activeProfile.name}`);
const modsPath = await getModsPath();
const disabledModsPath = path.join(path.dirname(modsPath), 'DisabledMods');
if (!fs.existsSync(disabledModsPath)) {
fs.mkdirSync(disabledModsPath, { recursive: true });
}
// Get all physical files from both folders
const enabledFiles = fs.existsSync(modsPath) ? fs.readdirSync(modsPath).filter(f => f.endsWith('.jar') || f.endsWith('.zip')) : [];
const disabledFiles = fs.existsSync(disabledModsPath) ? fs.readdirSync(disabledModsPath).filter(f => f.endsWith('.jar') || f.endsWith('.zip')) : [];
const allFiles = new Set([...enabledFiles, ...disabledFiles]);
// Profile.mods contains the list of ALL mods for that profile, with their enabled state.
const profileMods = activeProfile.mods || [];
for (const fileName of allFiles) {
const modConfig = profileMods.find(m => m.fileName === fileName);
const shouldBeEnabled = modConfig && modConfig.enabled !== false; // Default to true if in list, unless explicitly false
// Logic:
// If it should be enabled -> Move to mods/
// If it should be disabled -> Move to DisabledMods/
const currentPath = enabledFiles.includes(fileName) ? path.join(modsPath, fileName) : path.join(disabledModsPath, fileName);
const targetDir = shouldBeEnabled ? modsPath : disabledModsPath;
const targetPath = path.join(targetDir, fileName);
if (path.dirname(currentPath) !== targetDir) {
console.log(`[Mod Sync] Moving ${fileName} to ${shouldBeEnabled ? 'Enabled' : 'Disabled'}`);
try {
fs.renameSync(currentPath, targetPath);
} catch (err) {
console.error(`Failed to move ${fileName}: ${err.message}`);
}
}
}
return { success: true };
} catch (error) {
console.error('[ModManager] Error syncing mods:', error);
return { success: false, error: error.message };
}
}
module.exports = { module.exports = {
loadInstalledMods, loadInstalledMods,
downloadMod, downloadMod,
uninstallMod, uninstallMod,
toggleMod, toggleMod,
syncModsForCurrentProfile,
generateModId, generateModId,
extractModName, extractModName,
extractVersion extractVersion

View File

@@ -0,0 +1,206 @@
const path = require('path');
const fs = require('fs');
const { v4: uuidv4 } = require('uuid');
const {
loadConfig,
saveConfig,
getModsPath
} = require('../core/config');
// Lazy-load modManager to avoid circular deps, or keep imports structured.
// For now, access mod paths directly or use helper helpers.
class ProfileManager {
constructor() {
this.initialized = false;
}
init() {
if (this.initialized) return;
const config = loadConfig();
// Migration: specific check to see if we have profiles yet
if (!config.profiles || Object.keys(config.profiles).length === 0) {
this.migrateLegacyConfig(config);
}
this.initialized = true;
console.log('[ProfileManager] Initialized');
}
migrateLegacyConfig(config) {
console.log('[ProfileManager] Migrating legacy config to profile system...');
// Create a default profile with current settings
const defaultProfileId = 'default';
const defaultProfile = {
id: defaultProfileId,
name: 'Default',
created: new Date().toISOString(),
lastUsed: new Date().toISOString(),
// settings specific to this profile
// If global settings existed, we copy them here
mods: config.installedMods || [], // Legacy mods are now part of default profile
javaPath: config.javaPath || '',
gameOptions: {
minMemory: '1G',
maxMemory: '4G',
args: []
}
};
const updates = {
profiles: {
[defaultProfileId]: defaultProfile
},
activeProfileId: defaultProfileId,
// Mods are currently treated as files on disk.
// The profile's `mods` array is the source of truth for enabled/known mods per profile.
};
saveConfig(updates);
console.log('[ProfileManager] Migration complete. Created Default profile.');
}
createProfile(name) {
if (!name || typeof name !== 'string') {
throw new Error('Invalid profile name');
}
const config = loadConfig();
const id = uuidv4();
const newProfile = {
id,
name: name.trim(),
created: new Date().toISOString(),
lastUsed: null,
mods: [], // Start with no mods enabled
javaPath: '',
gameOptions: {
minMemory: '1G',
maxMemory: '4G',
args: []
}
};
const profiles = config.profiles || {};
profiles[id] = newProfile;
saveConfig({ profiles });
console.log(`[ProfileManager] Created new profile: "${name}" (${id})`);
return newProfile;
}
getProfiles() {
const config = loadConfig();
return Object.values(config.profiles || {});
}
getProfile(id) {
const config = loadConfig();
return (config.profiles && config.profiles[id]) || null;
}
getActiveProfile() {
const config = loadConfig();
const activeId = config.activeProfileId;
if (!activeId || !config.profiles || !config.profiles[activeId]) {
// Fallback if something is corrupted
return this.getProfiles()[0] || null;
}
return config.profiles[activeId];
}
async activateProfile(id) {
const config = loadConfig();
if (!config.profiles || !config.profiles[id]) {
throw new Error(`Profile not found: ${id}`);
}
if (config.activeProfileId === id) {
console.log(`[ProfileManager] Profile ${id} is already active.`);
return config.profiles[id];
}
console.log(`[ProfileManager] Switching to profile: ${config.profiles[id].name} (${id})`);
// 1. Update config first
config.profiles[id].lastUsed = new Date().toISOString();
saveConfig({
activeProfileId: id,
profiles: config.profiles
});
// 2. Trigger Mod Sync
// We need to require this here to ensure it uses the *newly saved* active profile ID
const { syncModsForCurrentProfile } = require('./modManager');
await syncModsForCurrentProfile();
return config.profiles[id];
}
deleteProfile(id) {
const config = loadConfig();
const profiles = config.profiles || {};
if (!profiles[id]) {
throw new Error('Profile not found');
}
if (config.activeProfileId === id) {
throw new Error('Cannot delete the active profile');
}
// Don't allow deleting the last profile
if (Object.keys(profiles).length <= 1) {
throw new Error('Cannot delete the only remaining profile');
}
delete profiles[id];
saveConfig({ profiles });
console.log(`[ProfileManager] Deleted profile: ${id}`);
return true;
}
updateProfile(id, updates) {
const config = loadConfig();
const profiles = config.profiles || {};
if (!profiles[id]) {
throw new Error('Profile not found');
}
// Safety checks on updates
const allowedFields = ['name', 'javaPath', 'gameOptions', 'mods'];
const sanitizedUpdates = {};
Object.keys(updates).forEach(key => {
if (allowedFields.includes(key)) {
sanitizedUpdates[key] = updates[key];
}
});
profiles[id] = { ...profiles[id], ...sanitizedUpdates };
saveConfig({ profiles });
console.log(`[ProfileManager] Updated profile: ${id}`);
// If we updated mods for the *active* profile, we might need to sync immediately
if (config.activeProfileId === id && updates.mods) {
// Optionally trigger sync?
// Sync is usually triggered when toggling a single mod.
// For bulk updates, the caller should decide when to sync.
}
return profiles[id];
}
}
module.exports = new ProfileManager();

137
main.js
View File

@@ -4,6 +4,7 @@ const fs = require('fs');
const { launchGame, launchGameWithVersionCheck, installGame, saveUsername, loadUsername, saveChatUsername, loadChatUsername, saveChatColor, loadChatColor, saveJavaPath, loadJavaPath, saveInstallPath, loadInstallPath, saveDiscordRPC, loadDiscordRPC, isGameInstalled, uninstallGame, getHytaleNews, handleFirstLaunchCheck, proposeGameUpdate, markAsLaunched } = require('./backend/launcher'); const { launchGame, launchGameWithVersionCheck, installGame, saveUsername, loadUsername, saveChatUsername, loadChatUsername, saveChatColor, loadChatColor, saveJavaPath, loadJavaPath, saveInstallPath, loadInstallPath, saveDiscordRPC, loadDiscordRPC, isGameInstalled, uninstallGame, getHytaleNews, handleFirstLaunchCheck, proposeGameUpdate, markAsLaunched } = require('./backend/launcher');
const UpdateManager = require('./backend/updateManager'); const UpdateManager = require('./backend/updateManager');
const logger = require('./backend/logger'); const logger = require('./backend/logger');
const profileManager = require('./backend/managers/profileManager');
logger.interceptConsole(); logger.interceptConsole();
@@ -25,16 +26,16 @@ function initDiscordRPC() {
const { Client } = require('discord-rpc'); const { Client } = require('discord-rpc');
discordRPC = new Client({ transport: 'ipc' }); discordRPC = new Client({ transport: 'ipc' });
discordRPC.on('ready', () => { discordRPC.on('ready', () => {
console.log('Discord RPC connected'); console.log('Discord RPC connected');
setDiscordActivity(); setDiscordActivity();
}); });
discordRPC.on('disconnected', () => { discordRPC.on('disconnected', () => {
console.log('Discord RPC disconnected'); console.log('Discord RPC disconnected');
}); });
discordRPC.login({ clientId: DISCORD_CLIENT_ID }).catch(err => { discordRPC.login({ clientId: DISCORD_CLIENT_ID }).catch(err => {
console.log('Failed to connect to Discord:', err.message); console.log('Failed to connect to Discord:', err.message);
}); });
@@ -45,7 +46,7 @@ function initDiscordRPC() {
function setDiscordActivity() { function setDiscordActivity() {
if (!discordRPC) return; if (!discordRPC) return;
try { try {
discordRPC.setActivity({ discordRPC.setActivity({
details: 'Using HytaleF2P', details: 'Using HytaleF2P',
@@ -66,7 +67,7 @@ function setDiscordActivity() {
function toggleDiscordRPC(enabled) { function toggleDiscordRPC(enabled) {
console.log('Toggling Discord RPC:', enabled); console.log('Toggling Discord RPC:', enabled);
if (enabled && !discordRPC) { if (enabled && !discordRPC) {
console.log('Initializing Discord RPC...'); console.log('Initializing Discord RPC...');
initDiscordRPC(); initDiscordRPC();
@@ -119,11 +120,11 @@ function createWindow() {
mainWindow.webContents.send('show-update-popup', updateInfo); mainWindow.webContents.send('show-update-popup', updateInfo);
} }
}, 3000); }, 3000);
//mainWindow.webContents.openDevTools(); //mainWindow.webContents.openDevTools();
mainWindow.webContents.on('devtools-opened', () => { mainWindow.webContents.on('devtools-opened', () => {
mainWindow.webContents.closeDevTools(); mainWindow.webContents.closeDevTools();
}); });
mainWindow.webContents.on('before-input-event', (event, input) => { mainWindow.webContents.on('before-input-event', (event, input) => {
@@ -159,31 +160,36 @@ app.whenReady().then(async () => {
console.log('Electron version:', process.versions.electron); console.log('Electron version:', process.versions.electron);
console.log('Node.js version:', process.versions.node); console.log('Node.js version:', process.versions.node);
console.log('Log directory:', logger.getLogDirectory()); console.log('Log directory:', logger.getLogDirectory());
// Initialize Profile Manager (runs migration if needed)
profileManager.init();
createWindow(); createWindow();
setTimeout(async () => { setTimeout(async () => {
let timeoutReached = false; let timeoutReached = false;
const unlockPlayButton = () => { const unlockPlayButton = () => {
if (mainWindow && !mainWindow.isDestroyed()) { if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('lock-play-button', false); mainWindow.webContents.send('lock-play-button', false);
} }
}; };
const timeoutId = setTimeout(() => { const timeoutId = setTimeout(() => {
timeoutReached = true; timeoutReached = true;
console.warn('First launch check timeout reached, unlocking play button'); console.warn('First launch check timeout reached, unlocking play button');
unlockPlayButton(); unlockPlayButton();
}, 15000); }, 15000);
try { try {
console.log('Starting first launch check...'); console.log('Starting first launch check...');
if (mainWindow && !mainWindow.isDestroyed()) { if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('lock-play-button', true); mainWindow.webContents.send('lock-play-button', true);
} }
const progressCallback = (message, percent, speed, downloaded, total) => { const progressCallback = (message, percent, speed, downloaded, total) => {
if (mainWindow && !mainWindow.isDestroyed()) { if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('first-launch-progress', { message, percent, speed, downloaded, total }); mainWindow.webContents.send('first-launch-progress', { message, percent, speed, downloaded, total });
@@ -196,20 +202,20 @@ app.whenReady().then(async () => {
setTimeout(() => reject(new Error('First launch check timeout')), 12000); setTimeout(() => reject(new Error('First launch check timeout')), 12000);
}) })
]); ]);
clearTimeout(timeoutId); clearTimeout(timeoutId);
if (timeoutReached) { if (timeoutReached) {
console.log('Timeout already reached, skipping result processing'); console.log('Timeout already reached, skipping result processing');
return; return;
} }
console.log('First launch check result:', firstLaunchResult); console.log('First launch check result:', firstLaunchResult);
if (mainWindow && !mainWindow.isDestroyed()) { if (mainWindow && !mainWindow.isDestroyed()) {
if (firstLaunchResult.needsUpdate && firstLaunchResult.existingGame) { if (firstLaunchResult.needsUpdate && firstLaunchResult.existingGame) {
console.log('Sending show-first-launch-update event...'); console.log('Sending show-first-launch-update event...');
setTimeout(() => { setTimeout(() => {
if (mainWindow && !mainWindow.isDestroyed()) { if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('show-first-launch-update', { mainWindow.webContents.send('show-first-launch-update', {
@@ -218,10 +224,10 @@ app.whenReady().then(async () => {
}); });
} }
}, 1000); }, 1000);
} else if (firstLaunchResult.isFirstLaunch && !firstLaunchResult.existingGame) { } else if (firstLaunchResult.isFirstLaunch && !firstLaunchResult.existingGame) {
console.log('Sending show-first-launch-welcome event...'); console.log('Sending show-first-launch-welcome event...');
setTimeout(() => { setTimeout(() => {
if (mainWindow && !mainWindow.isDestroyed()) { if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('show-first-launch-welcome'); mainWindow.webContents.send('show-first-launch-welcome');
@@ -268,9 +274,9 @@ app.on('before-quit', () => {
app.on('window-all-closed', () => { app.on('window-all-closed', () => {
console.log('=== LAUNCHER CLOSING ==='); console.log('=== LAUNCHER CLOSING ===');
cleanupDiscordRPC(); cleanupDiscordRPC();
if (process.platform !== 'darwin') { if (process.platform !== 'darwin') {
app.quit(); app.quit();
} }
@@ -292,18 +298,18 @@ ipcMain.handle('launch-game', async (event, playerName, javaPath, installPath) =
}; };
const result = await launchGameWithVersionCheck(playerName, progressCallback, javaPath, installPath); const result = await launchGameWithVersionCheck(playerName, progressCallback, javaPath, installPath);
return result; return result;
} catch (error) { } catch (error) {
console.error('Launch error:', error); console.error('Launch error:', error);
const errorMessage = error.message || error.toString(); const errorMessage = error.message || error.toString();
if (mainWindow && !mainWindow.isDestroyed()) { if (mainWindow && !mainWindow.isDestroyed()) {
setTimeout(() => { setTimeout(() => {
mainWindow.webContents.send('progress-complete'); mainWindow.webContents.send('progress-complete');
}, 2000); }, 2000);
} }
return { success: false, error: errorMessage }; return { success: false, error: errorMessage };
} }
}); });
@@ -324,12 +330,12 @@ ipcMain.handle('install-game', async (event, playerName, javaPath, installPath)
}; };
const result = await installGame(playerName, progressCallback, javaPath, installPath); const result = await installGame(playerName, progressCallback, javaPath, installPath);
return result; return result;
} catch (error) { } catch (error) {
console.error('Install error:', error); console.error('Install error:', error);
const errorMessage = error.message || error.toString(); const errorMessage = error.message || error.toString();
return { success: false, error: errorMessage }; return { success: false, error: errorMessage };
} }
}); });
@@ -393,7 +399,7 @@ ipcMain.handle('select-install-path', async () => {
properties: ['openDirectory'], properties: ['openDirectory'],
title: 'Select Installation Folder' title: 'Select Installation Folder'
}); });
if (!result.canceled && result.filePaths.length > 0) { if (!result.canceled && result.filePaths.length > 0) {
return result.filePaths[0]; return result.filePaths[0];
} }
@@ -416,7 +422,7 @@ ipcMain.handle('accept-first-launch-update', async (event, existingGame) => {
}; };
const result = await proposeGameUpdate(existingGame, progressCallback); const result = await proposeGameUpdate(existingGame, progressCallback);
return result; return result;
} catch (error) { } catch (error) {
console.error('First launch update error:', error); console.error('First launch update error:', error);
@@ -481,7 +487,7 @@ ipcMain.handle('open-game-location', async () => {
try { try {
const { getResolvedAppDir } = require('./backend/launcher'); const { getResolvedAppDir } = require('./backend/launcher');
const gameDir = path.join(getResolvedAppDir(), 'release', 'package', 'game'); const gameDir = path.join(getResolvedAppDir(), 'release', 'package', 'game');
if (fs.existsSync(gameDir)) { if (fs.existsSync(gameDir)) {
await shell.openPath(gameDir); await shell.openPath(gameDir);
return { success: true }; return { success: true };
@@ -497,9 +503,9 @@ ipcMain.handle('open-game-location', async () => {
ipcMain.handle('browse-java-path', async () => { ipcMain.handle('browse-java-path', async () => {
const isWindows = process.platform === 'win32'; const isWindows = process.platform === 'win32';
const isMac = process.platform === 'darwin'; const isMac = process.platform === 'darwin';
let dialogOptions; let dialogOptions;
if (isWindows) { if (isWindows) {
dialogOptions = { dialogOptions = {
properties: ['openFile'], properties: ['openFile'],
@@ -528,9 +534,9 @@ ipcMain.handle('browse-java-path', async () => {
] ]
}; };
} }
const result = await dialog.showOpenDialog(mainWindow, dialogOptions); const result = await dialog.showOpenDialog(mainWindow, dialogOptions);
if (!result.canceled && result.filePaths.length > 0) { if (!result.canceled && result.filePaths.length > 0) {
return result.filePaths[0]; return result.filePaths[0];
} }
@@ -653,7 +659,7 @@ ipcMain.handle('select-mod-files', async () => {
{ name: 'All Files', extensions: ['*'] } { name: 'All Files', extensions: ['*'] }
] ]
}); });
if (!result.canceled && result.filePaths.length > 0) { if (!result.canceled && result.filePaths.length > 0) {
return result.filePaths; return result.filePaths;
} }
@@ -664,9 +670,9 @@ ipcMain.handle('copy-mod-file', async (event, sourcePath, modsPath) => {
try { try {
const fileName = path.basename(sourcePath); const fileName = path.basename(sourcePath);
const destPath = path.join(modsPath, fileName); const destPath = path.join(modsPath, fileName);
fs.copyFileSync(sourcePath, destPath); fs.copyFileSync(sourcePath, destPath);
return { success: true, fileName }; return { success: true, fileName };
} catch (error) { } catch (error) {
console.error('Error copying mod file:', error); console.error('Error copying mod file:', error);
@@ -686,13 +692,13 @@ ipcMain.handle('check-for-updates', async () => {
ipcMain.handle('open-download-page', async () => { ipcMain.handle('open-download-page', async () => {
try { try {
await shell.openExternal(updateManager.getDownloadUrl()); await shell.openExternal(updateManager.getDownloadUrl());
setTimeout(() => { setTimeout(() => {
if (mainWindow && !mainWindow.isDestroyed()) { if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.close(); mainWindow.close();
} }
}, 1000); }, 1000);
return { success: true }; return { success: true };
} catch (error) { } catch (error) {
console.error('Error opening download page:', error); console.error('Error opening download page:', error);
@@ -786,7 +792,7 @@ ipcMain.handle('get-recent-logs', async (event, maxLines = 100) => {
try { try {
const logDir = logger.getLogDirectory(); const logDir = logger.getLogDirectory();
if (!logDir) return null; if (!logDir) return null;
const files = fs.readdirSync(logDir) const files = fs.readdirSync(logDir)
.filter(file => file.startsWith('launcher-') && file.endsWith('.log')) .filter(file => file.startsWith('launcher-') && file.endsWith('.log'))
.map(file => ({ .map(file => ({
@@ -795,13 +801,13 @@ ipcMain.handle('get-recent-logs', async (event, maxLines = 100) => {
mtime: fs.statSync(path.join(logDir, file)).mtime mtime: fs.statSync(path.join(logDir, file)).mtime
})) }))
.sort((a, b) => b.mtime - a.mtime); .sort((a, b) => b.mtime - a.mtime);
if (files.length === 0) return null; if (files.length === 0) return null;
const latestLogFile = files[0].path; const latestLogFile = files[0].path;
const content = fs.readFileSync(latestLogFile, 'utf8'); const content = fs.readFileSync(latestLogFile, 'utf8');
const lines = content.split('\n'); const lines = content.split('\n');
return lines.slice(-maxLines).join('\n'); return lines.slice(-maxLines).join('\n');
} catch (error) { } catch (error) {
console.error('Error reading logs:', error); console.error('Error reading logs:', error);
@@ -809,3 +815,44 @@ ipcMain.handle('get-recent-logs', async (event, maxLines = 100) => {
} }
}); });
// Profile Management IPC
ipcMain.handle('profile-create', async (event, name) => {
try {
return profileManager.createProfile(name);
} catch (error) {
return { error: error.message };
}
});
ipcMain.handle('profile-list', async () => {
return profileManager.getProfiles();
});
ipcMain.handle('profile-get-active', async () => {
return profileManager.getActiveProfile();
});
ipcMain.handle('profile-activate', async (event, id) => {
try {
return await profileManager.activateProfile(id);
} catch (error) {
return { error: error.message };
}
});
ipcMain.handle('profile-delete', async (event, id) => {
try {
return profileManager.deleteProfile(id);
} catch (error) {
return { error: error.message };
}
});
ipcMain.handle('profile-update', async (event, id, updates) => {
try {
return profileManager.updateProfile(id, updates);
} catch (error) {
return { error: error.message };
}
});

View File

@@ -48,7 +48,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
onUpdatePopup: (callback) => { onUpdatePopup: (callback) => {
ipcRenderer.on('show-update-popup', (event, data) => callback(data)); ipcRenderer.on('show-update-popup', (event, data) => callback(data));
}, },
acceptFirstLaunchUpdate: (existingGame) => ipcRenderer.invoke('accept-first-launch-update', existingGame), acceptFirstLaunchUpdate: (existingGame) => ipcRenderer.invoke('accept-first-launch-update', existingGame),
markAsLaunched: () => ipcRenderer.invoke('mark-as-launched'), markAsLaunched: () => ipcRenderer.invoke('mark-as-launched'),
onFirstLaunchUpdate: (callback) => { onFirstLaunchUpdate: (callback) => {
@@ -66,12 +66,22 @@ contextBridge.exposeInMainWorld('electronAPI', {
getLogDirectory: () => ipcRenderer.invoke('get-log-directory'), getLogDirectory: () => ipcRenderer.invoke('get-log-directory'),
getRecentLogs: (maxLines) => ipcRenderer.invoke('get-recent-logs', maxLines), getRecentLogs: (maxLines) => ipcRenderer.invoke('get-recent-logs', maxLines),
// UUID Management methods // UUID Management methods
getCurrentUuid: () => ipcRenderer.invoke('get-current-uuid'), getCurrentUuid: () => ipcRenderer.invoke('get-current-uuid'),
getAllUuidMappings: () => ipcRenderer.invoke('get-all-uuid-mappings'), getAllUuidMappings: () => ipcRenderer.invoke('get-all-uuid-mappings'),
setUuidForUser: (username, uuid) => ipcRenderer.invoke('set-uuid-for-user', username, uuid), setUuidForUser: (username, uuid) => ipcRenderer.invoke('set-uuid-for-user', username, uuid),
generateNewUuid: () => ipcRenderer.invoke('generate-new-uuid'), generateNewUuid: () => ipcRenderer.invoke('generate-new-uuid'),
deleteUuidForUser: (username) => ipcRenderer.invoke('delete-uuid-for-user', username), deleteUuidForUser: (username) => ipcRenderer.invoke('delete-uuid-for-user', username),
resetCurrentUserUuid: () => ipcRenderer.invoke('reset-current-user-uuid') resetCurrentUserUuid: () => ipcRenderer.invoke('reset-current-user-uuid'),
// Profile API
profile: {
create: (name) => ipcRenderer.invoke('profile-create', name),
list: () => ipcRenderer.invoke('profile-list'),
getActive: () => ipcRenderer.invoke('profile-get-active'),
activate: (id) => ipcRenderer.invoke('profile-activate', id),
delete: (id) => ipcRenderer.invoke('profile-delete', id),
update: (id, updates) => ipcRenderer.invoke('profile-update', id, updates)
}
}); });