using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; using GameLauncher.Helpers; using GameLauncher.Models; namespace GameLauncher.Services { /// /// ティラノスクリプトゲームの個別改造設定オプション /// public class TyranoModOptions { public bool UnlockAllCg { get; set; } = true; public bool FastMessage { get; set; } = true; public bool EnableDevTools { get; set; } = true; public bool ShowCheatMenu { get; set; } = true; } /// /// ティラノスクリプト(TyranoScript)ゲームのMOD適用・解除・管理を行うサービス /// public class TyranoModService { public const string ModScriptFileName = "tyrano_launcher_mod.js"; public const string IndexBackupSuffix = ".original_launcher_backup"; /// /// index.html に改造スクリプトが適用されているかどうか判定します。 /// public static bool CheckIsModded(string indexPath) { if (string.IsNullOrEmpty(indexPath)) return false; string extPath = AsarArchiveService.ToExtendedPath(indexPath); if (!File.Exists(extPath)) return false; try { string content = File.ReadAllText(extPath); return content.Contains(ModScriptFileName); } catch { return false; } } /// /// ティラノスクリプトゲームに改造スクリプトを適用します。 /// public (bool Success, string Message) ApplyMod(TkoolGameItem game, Dictionary? pluginSettings) { var rawIndexPath = game.PluginsJsPath; // ティラノの場合は index.html パス if (string.IsNullOrEmpty(rawIndexPath)) { return (false, "index.html が見つかりません。ASARを解凍してください。"); } var indexPath = AsarArchiveService.ToExtendedPath(rawIndexPath); if (!File.Exists(indexPath)) { return (false, "index.html が見つかりません。ASARを解凍してください。"); } try { var dir = Path.GetDirectoryName(indexPath)!; var gameBackupDir = AppPathHelper.GetGameBackupDirectory(game.FolderName, game.RootDirectory); var backupPath = Path.Combine(gameBackupDir, "index.html" + IndexBackupSuffix); var legacyBackupPath = indexPath + IndexBackupSuffix; // 1. バックアップの作成(存在しない場合、Backups フォルダに保存) if (!File.Exists(backupPath)) { if (File.Exists(legacyBackupPath)) { File.Copy(legacyBackupPath, backupPath, true); } else { string originalContent = File.ReadAllText(indexPath, Encoding.UTF8); // 既にタグが含まれていた場合は除去したものをバックアップとする string cleanContent = RemoveScriptTag(originalContent); File.WriteAllText(backupPath, cleanContent, new UTF8Encoding(false)); } } // 2. 有効化する機能の判定 bool unlockCg = game.IsPluginEnabled("TyranoUnlockAllCg", pluginSettings, fallbackVal: true); bool fastMsg = game.IsPluginEnabled("TyranoFastMessage", pluginSettings, fallbackVal: true); bool devTools = game.IsPluginEnabled("TyranoDevTools", pluginSettings, fallbackVal: true); bool cheatMenu = game.IsPluginEnabled("TyranoCheatMenu", pluginSettings, fallbackVal: true); // 3. tyrano_launcher_mod.js を生成して配置 string modJsContent = BuildModScript(unlockCg, fastMsg, devTools, cheatMenu); string modJsPath = Path.Combine(dir, ModScriptFileName); File.WriteAllText(modJsPath, modJsContent, new UTF8Encoding(false)); // 4. index.html にスクリプトタグを注入 string baseContent = File.ReadAllText(backupPath, Encoding.UTF8); string injectedContent = InjectScriptTag(baseContent); File.WriteAllText(indexPath, injectedContent, new UTF8Encoding(false)); game.IsModded = true; return (true, "ティラノスクリプト用改造を正常に適用しました。(全CG解放/高速化/DevTools/チートメニュー)"); } catch (Exception ex) { return (false, $"ティラノ改造適用中にエラーが発生しました: {ex.Message}"); } } /// /// ティラノスクリプトゲームの改造を解除し、元のオリジナル状態に復元します。 /// public (bool Success, string Message) RestoreOriginal(TkoolGameItem game) { var rawIndexPath = game.PluginsJsPath; if (string.IsNullOrEmpty(rawIndexPath)) { return (false, "index.html のパスが設定されていません。"); } var indexPath = AsarArchiveService.ToExtendedPath(rawIndexPath); try { var dir = Path.GetDirectoryName(indexPath)!; var gameBackupDir = AppPathHelper.GetGameBackupDirectory(game.FolderName, game.RootDirectory); var backupPath = Path.Combine(gameBackupDir, "index.html" + IndexBackupSuffix); var legacyBackupPath = indexPath + IndexBackupSuffix; var modJsPath = Path.Combine(dir, ModScriptFileName); // 1. index.html の復元 (Backups フォルダを優先) if (File.Exists(backupPath)) { File.Copy(backupPath, indexPath, true); } else if (File.Exists(legacyBackupPath)) { File.Copy(legacyBackupPath, indexPath, true); try { File.Copy(legacyBackupPath, backupPath, true); } catch { } } else if (File.Exists(indexPath)) { string content = File.ReadAllText(indexPath, Encoding.UTF8); string clean = RemoveScriptTag(content); File.WriteAllText(indexPath, clean, new UTF8Encoding(false)); } // ゲームフォルダ内の旧バックアップがあれば削除 if (File.Exists(legacyBackupPath)) { try { File.Delete(legacyBackupPath); } catch { } } // 2. tyrano_launcher_mod.js の削除 if (File.Exists(modJsPath)) { try { File.Delete(modJsPath); } catch { } } game.IsModded = false; return (true, "ティラノスクリプトの改造を解除し、オリジナル状態に復元しました。"); } catch (Exception ex) { return (false, $"復元中にエラーが発生しました: {ex.Message}"); } } private static string InjectScriptTag(string html) { string tag = $""; if (html.Contains(ModScriptFileName)) { return html; } if (html.Contains("", StringComparison.OrdinalIgnoreCase)) { return Regex.Replace(html, @"()", tag + "\n$1", RegexOptions.IgnoreCase); } else if (html.Contains("", StringComparison.OrdinalIgnoreCase)) { return Regex.Replace(html, @"()", tag + "\n$1", RegexOptions.IgnoreCase); } return html + "\n" + tag; } private static string RemoveScriptTag(string html) { return Regex.Replace(html, @"]*src=""\./" + Regex.Escape(ModScriptFileName) + @"""[^>]*>\r?\n?", "", RegexOptions.IgnoreCase); } private static string BuildModScript(bool unlockCg, bool fastMessage, bool devTools, bool cheatMenu) { var sb = new StringBuilder(); sb.AppendLine("/* =============================================================== */"); sb.AppendLine("/* GameLauncher - TyranoScript Mod Plugin */"); sb.AppendLine("/* =============================================================== */"); sb.AppendLine("(function() {"); sb.AppendLine(" 'use strict';"); sb.AppendLine(" console.log('[GameLauncher] TyranoScript Mod active.');"); // 1. DevTools if (devTools) { sb.AppendLine(@" // F12キーで開発者ツールを開く window.addEventListener('keydown', function(e) { if (e.key === 'F12') { try { if (typeof require !== 'undefined') { var electron = require('electron'); var remote = electron.remote || (electron.remote ? electron.remote : null); var win = remote ? remote.getCurrentWindow() : null; if (win && win.webContents) { if (win.webContents.isDevToolsOpened()) win.webContents.closeDevTools(); else win.webContents.openDevTools({ mode: 'detach' }); } } else if (typeof nw !== 'undefined') { nw.Window.get().showDevTools(); } } catch (err) { console.warn('[GameLauncher] DevTools open failed:', err); } } });"); } sb.AppendLine(@" function onTyranoReady() { if (!window.TYRANO || !window.TYRANO.kag) { setTimeout(onTyranoReady, 100); return; } var kag = window.TYRANO.kag; console.log('[GameLauncher] TYRANO.kag detected.');"); // 2. FastMessage if (fastMessage) { sb.AppendLine(@" // メッセージ高速化・ウェイト短縮 try { if (kag.config) { kag.config.defaultAutoSpeed = 10; kag.config.defaultSkipSpeed = 5; } if (kag.stat && kag.stat.ch_speed !== undefined) { kag.stat.ch_speed = 0; } if (kag.ftag && kag.ftag.master_tag && kag.ftag.master_tag.wait) { var origWait = kag.ftag.master_tag.wait.start; kag.ftag.master_tag.wait.start = function(pm) { if (pm && pm.time) pm.time = Math.min(pm.time, 50); return origWait.apply(this, arguments); }; } } catch (e) { console.warn('[GameLauncher] FastMessage hook error:', e); }"); } // 3. UnlockAllCg if (unlockCg) { sb.AppendLine(@" // 全CG・全回想フラグの全開放 try { function unlockFlags() { if (kag.variable && kag.variable.sf) { var sf = kag.variable.sf; for (var key in sf) { if (sf.hasOwnProperty(key)) { var val = sf[key]; if (typeof val === 'object' && val !== null) { for (var sub in val) { if (val.hasOwnProperty(sub)) { if (typeof val[sub] === 'boolean') val[sub] = true; else if (typeof val[sub] === 'number' && val[sub] === 0) val[sub] = 1; } } } } } console.log('[GameLauncher] System variables (sf) unlocked for CG/scenes.'); } } setTimeout(unlockFlags, 1000); setTimeout(unlockFlags, 3000); } catch (e) { console.warn('[GameLauncher] UnlockAllCg error:', e); }"); } // 4. CheatMenu if (cheatMenu) { sb.AppendLine(@" // 画面上フローティングチートメニュー try { var btn = document.createElement('div'); btn.innerHTML = '⚙ チート'; btn.style.cssText = 'position:fixed;top:10px;right:10px;z-index:999999;background:rgba(20,20,30,0.85);color:#00B894;padding:6px 12px;border-radius:6px;font-size:12px;cursor:pointer;border:1px solid #00B894;font-family:sans-serif;user-select:none;font-weight:bold;box-shadow:0 2px 6px rgba(0,0,0,0.5);'; var modal = document.createElement('div'); modal.style.cssText = 'display:none;position:fixed;top:45px;right:10px;width:340px;max-height:480px;background:rgba(24,24,32,0.96);border:1px solid #555;border-radius:8px;z-index:999999;padding:12px;overflow-y:auto;color:#E0E0E6;font-size:12px;font-family:sans-serif;box-shadow:0 4px 12px rgba(0,0,0,0.7);'; btn.onclick = function() { if (modal.style.display === 'none') { renderVars(); modal.style.display = 'block'; } else { modal.style.display = 'none'; } }; function renderVars() { modal.innerHTML = '
🎮 ゲーム内変数 (f) エディタ✕
'; document.getElementById('_tkl_close').onclick = function() { modal.style.display = 'none'; }; var list = document.getElementById('_tkl_list'); var f = (kag.stat && kag.stat.f) ? kag.stat.f : (kag.variable ? kag.variable.f : null); if (!f || Object.keys(f).length === 0) { list.innerHTML = '
変数(f)が見つかりません。ゲームを開始してからお試しください。
'; return; } for (var k in f) { if (!f.hasOwnProperty(k)) continue; var val = f[k]; if (typeof val === 'number' || typeof val === 'string' || typeof val === 'boolean') { (function(key, currentVal) { var row = document.createElement('div'); row.style.cssText = 'display:flex;justify-content:space-between;align-items:center;margin-bottom:4px;'; var nameSpan = document.createElement('span'); nameSpan.innerText = key; nameSpan.style.cssText = 'max-width:140px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#FAB1A0;'; var input = document.createElement('input'); input.value = currentVal; input.style.cssText = 'width:120px;background:#16161E;color:#fff;border:1px solid #444;border-radius:4px;padding:2px 4px;font-size:11px;'; input.onchange = function() { var n = Number(input.value); f[key] = isNaN(n) ? input.value : n; console.log('[GameLauncher] Updated f.' + key + ' =', f[key]); }; row.appendChild(nameSpan); row.appendChild(input); list.appendChild(row); })(k, val); } } } document.body.appendChild(btn); document.body.appendChild(modal); } catch (e) { console.warn('[GameLauncher] CheatMenu error:', e); }"); } sb.AppendLine(" }"); sb.AppendLine(" setTimeout(onTyranoReady, 300);"); sb.AppendLine("})();"); return sb.ToString(); } } }