void SaveTree() { Directory.CreateDirectory(Path.GetDirectoryName(FoldersXmlPath)); File.WriteAllText(FoldersXmlPath, TreeToXml()); if (mainForm != null) { for (int i = 1; i < mainForm.listViewGames.Items.Count; i++) { if (deletedGames.Contains(mainForm.listViewGames.Items[i].Tag as NesApplication)) { mainForm.listViewGames.Items[i].Checked = false; } } ConfigIni.Save(); } }
bool FlashOriginalKernel() { var workerForm = new WorkerForm(); workerForm.Task = WorkerForm.Tasks.FlashKernel; workerForm.KernelDump = KernelDump; workerForm.Mod = null; workerForm.Start(); var result = workerForm.DialogResult == DialogResult.OK; if (result) { ConfigIni.CustomFlashed = false; ConfigIni.Save(); } return(result); }
bool FlashCustomKernel() { var workerForm = new WorkerForm(); workerForm.Task = WorkerForm.Tasks.FlashKernel; workerForm.KernelDump = KernelDump; workerForm.Mod = "mod_kernel"; workerForm.Start(); var result = workerForm.DialogResult == DialogResult.OK; if (result) { ConfigIni.CustomFlashed = true; ConfigIni.Save(); } return(result); }
private void SaveSelectedGames() { var selected = new List <string>(); foreach (var game in checkedListBoxGames.CheckedItems) { if (game is NesGame) { selected.Add((game as NesGame).Code); } else { selected.Add("default"); } } ConfigIni.SelectedGames = string.Join(";", selected.ToArray()); ConfigIni.Save(); }
// load public static bool Load() { string configPath = Shared.PathCombine(Program.BaseDirectoryExternal, ConfigDir, ConfigFile); if (File.Exists(configPath)) { Trace.WriteLine("Loading configuration"); try { instance = JsonConvert.DeserializeObject <ConfigIni>(File.ReadAllText(configPath)); return(true); } catch (Exception ex) { Trace.WriteLine("Unexpected error loading config file : " + ex.Message + ex.StackTrace); instance = null; } } return(false); }
void SaveTree() { Directory.CreateDirectory(Path.GetDirectoryName(FoldersXmlPath)); File.WriteAllText(FoldersXmlPath, TreeToXml()); if (mainForm != null) { List <string> codes = new List <string>(); foreach (INesMenuElement elem in deletedGames) { codes.Add(elem.Code); } if (codes.Count() > 0) { Manager.GameManager.GetInstance().Unselect(codes.ToArray()); } ConfigIni.Save(); } }
void SaveTree() { File.WriteAllText(FoldersXmlPath, TreeToXml()); if (mainForm != null) { for (int i = 0; i < mainForm.checkedListBoxGames.Items.Count; i++) { if (deletedGames.Contains(mainForm.checkedListBoxGames.Items[i] as NesMiniApplication)) { mainForm.checkedListBoxGames.SetItemChecked(i, false); } } for (int i = 0; i < mainForm.checkedListBoxDefaultGames.Items.Count; i++) { if (deletedGames.Contains(mainForm.checkedListBoxDefaultGames.Items[i] as NesDefaultGame)) { mainForm.checkedListBoxDefaultGames.SetItemChecked(i, false); } } ConfigIni.Save(); } }
void SaveTree() { Directory.CreateDirectory(Path.GetDirectoryName(FoldersXmlPath)); File.WriteAllText(FoldersXmlPath, TreeToXml()); if (mainForm != null) { for (int i = 1; i < mainForm.listViewGames.Items.Count; i++) { if (deletedGames.Contains(mainForm.listViewGames.Items[i].Tag as NesApplication)) { mainForm.listViewGames.Items[i].Checked = false; } } switch (comboBoxBackPosition.SelectedIndex) { case 0: ConfigIni.Instance.BackFolderPosition = NesMenuFolder.Priority.LeftBack; break; case 1: ConfigIni.Instance.BackFolderPosition = NesMenuFolder.Priority.Back; break; } ConfigIni.Instance.HomeFolder = checkBoxAddHome.Checked; ConfigIni.Save(); } }
public static void Shell_OnConnected(ISystemShell caller) { // set calling shell as current used shell and disable others Shell = caller; shells.ForEach(shell => { if (shell != caller) { shell.Enabled = false; } }); try { if (!Shell.IsOnline) { throw new IOException("Shell connection should be online!"); } DetectedConsoleType = ConsoleType.Unknown; MinimalMemboot = Shell.Execute("source /hakchi/config; [ \"$cf_memboot\" = \"y\" ]") == 0; UniqueID = Shell.ExecuteSimple("hakchi hwid").Replace(" ", ""); Trace.WriteLine($"Detected device unique ID: {UniqueID}"); // execution stops here for a minimal memboot if (!MinimalMemboot) { var versionExists = Shell.ExecuteSimple("[ -f /var/version ] && echo \"yes\"", 2000, true) == "yes"; if (versionExists) { var versions = Shell.ExecuteSimple("source /var/version && echo \"$bootVersion $kernelVersion $hakchiVersion\"", 2000, true).Split(' '); RawBootVersion = versions[0]; RawKernelVersion = versions[1]; RawScriptVersion = versions[2]; Trace.WriteLine($"Detected versions: boot {RawBootVersion}, kernel {RawKernelVersion}, script {RawScriptVersion}"); CanInteract = !SystemRequiresReflash() && !SystemRequiresRootfsUpdate(); } else { RawBootVersion = "1.0.0"; RawKernelVersion = "3.4.112-00"; RawScriptVersion = "v1.0.0-000"; Trace.WriteLine("Detected versions: severely outdated!"); CanInteract = false; } if (CanInteract) { // disable sync on legacy clovershell CanSync = !(caller is ClovershellConnection); // detect console firmware/type SystemCode = Shell.ExecuteSimple("hakchi eval 'echo \"$sftype-$sfregion\"'", 2000, true).Trim(); if (SystemCodeToConsoleType.ContainsKey(SystemCode)) { DetectedConsoleType = SystemCodeToConsoleType[SystemCode]; } CustomFirmwareLoaded = Shell.ExecuteSimple("hakchi currentFirmware", 2000, true) != "_nand_"; // detect basic paths RemoteGameSyncPath = Shell.ExecuteSimple("hakchi findGameSyncStorage", 2000, true).Trim(); OriginalGamesPath = Shell.ExecuteSimple("hakchi get gamepath", 2000, true).Trim(); RootFsPath = Shell.ExecuteSimple("hakchi get rootfs", 2000, true).Trim(); SquashFsPath = Shell.ExecuteSimple("hakchi get squashfs", 2000, true).Trim(); // load config ConfigIni.SetConfigDictionary(LoadConfig()); // calculate stats MemoryStats.Refresh(); } } // chain to other OnConnected events Connected = Shell.IsOnline; OnConnected(caller); } catch (Exception ex) { Trace.WriteLine(ex.Message + ex.StackTrace); CanInteract = false; MinimalMemboot = false; } }
static void Main() { #if DEBUG try { AllocConsole(); IntPtr stdHandle = CreateFile("CONOUT$", GENERIC_WRITE, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); SafeFileHandle safeFileHandle = new SafeFileHandle(stdHandle, true); FileStream fileStream = new FileStream(safeFileHandle, FileAccess.Write); Encoding encoding = System.Text.Encoding.GetEncoding(MY_CODE_PAGE); StreamWriter standardOutput = new StreamWriter(fileStream, encoding); standardOutput.AutoFlush = true; Console.SetOut(standardOutput); Debug.Listeners.Add(new TextWriterTraceListener(System.Console.Out)); } catch { } try { Stream logFile = File.Create("debuglog.txt"); Debug.Listeners.Add(new TextWriterTraceListener(logFile)); } catch (Exception ex) { Debug.WriteLine(ex.Message + ex.StackTrace); } Debug.AutoFlush = true; #endif try { bool createdNew = true; using (Mutex mutex = new Mutex(true, "hakchi2", out createdNew)) { if (createdNew) { BaseDirectoryInternal = Path.GetDirectoryName(Application.ExecutablePath); if (ApplicationDeployment.IsNetworkDeployed) { // This is not correct way for Windows 7+... BaseDirectoryExternal = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "hakchi2"); // So if it's not exists, lets try to get documents library path (Win7+) try { if (!Directory.Exists(BaseDirectoryExternal)) { BaseDirectoryExternal = Path.Combine(GetDocumentsLibraryPath(), "hakchi2"); } } catch (Exception ex) { // TODO: Test it on Windows XP Debug.WriteLine(ex.Message); } } else { BaseDirectoryExternal = BaseDirectoryInternal; } Debug.WriteLine("Base directory: " + BaseDirectoryExternal); ConfigIni.Load(); try { if (!string.IsNullOrEmpty(ConfigIni.Language)) { Thread.CurrentThread.CurrentUICulture = new CultureInfo(ConfigIni.Language); } } catch { } // There are some folders which should be accessed by user // Moving them to "My documents" if (ApplicationDeployment.IsNetworkDeployed && ApplicationDeployment.CurrentDeployment.IsFirstRun) { var externalDirs = new string[] { "art", "folder_images", "patches", "user_mods" }; foreach (var dir in externalDirs) { DirectoryCopy(Path.Combine(BaseDirectoryInternal, dir), Path.Combine(BaseDirectoryExternal, dir), true); } } string languagesDirectory = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "languages"); const string langFileNames = "hakchi.resources.dll"; AppDomain.CurrentDomain.AppendPrivatePath(languagesDirectory); // For updates var oldFiles = Directory.GetFiles(Path.GetDirectoryName(Application.ExecutablePath), langFileNames, SearchOption.AllDirectories); foreach (var d in oldFiles) { if (!d.Contains(@"\languages\")) { var dir = Path.GetDirectoryName(d); Debug.WriteLine("Removing old directory: " + dir); if (ApplicationDeployment.IsNetworkDeployed) { var targetDir = Path.Combine(languagesDirectory, Path.GetFileName(dir)); Directory.CreateDirectory(targetDir); var targetFile = Path.Combine(targetDir, langFileNames); if (File.Exists(targetFile)) { File.Delete(targetFile); } File.Move(Path.Combine(dir, langFileNames), targetFile); } else { Directory.Delete(dir, true); } } } Debug.WriteLine("Starting, version: " + Assembly.GetExecutingAssembly().GetName().Version); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); Debug.WriteLine("Done."); } else { Process current = Process.GetCurrentProcess(); foreach (Process process in Process.GetProcessesByName("hakchi")) { if (process.Id != current.Id) { ShowWindow(process.MainWindowHandle, 9); // Restore SetForegroundWindow(process.MainWindowHandle); // Foreground break; } } } } } catch (Exception ex) { Debug.WriteLine(ex.Message + ex.StackTrace); MessageBox.Show(ex.Message + ex.StackTrace, Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void CustomBorderManager_FormClosing(object sender, FormClosingEventArgs e) { SaveSelectedBorders(); ConfigIni.Save(); }
private void buttonSync_Click(object sender, EventArgs e) { const string src_backgroundPath = "/var/lib/hakchi/squashfs/usr/share/backgrounds"; const string dest_backgroundPath = "/var/lib/hakchi/rootfs/usr/share/backgrounds"; var clovershell = MainForm.Clovershell; string bgDirectory = BorderElement.BackgroundsDirectory; SaveSelectedBorders(); ConfigIni.Save(); string baseDirectoryInternal = Program.BaseDirectoryInternal; string tempDirectory; #if DEBUG tempDirectory = Path.Combine(baseDirectoryInternal, "temp"); #else tempDirectory = Path.Combine(Path.GetTempPath(), "hakchi-temp"); #endif string tempBordersDirectory = Path.Combine(tempDirectory, "borders"); Directory.CreateDirectory(tempDirectory); Directory.CreateDirectory(tempBordersDirectory); labelSyncing.Text = "Making sync"; progressBarSync.Value = 0; labelSyncing.Visible = true; progressBarSync.Visible = true; labelSyncing.Refresh(); progressBarSync.Refresh(); if (clovershell.IsOnline) { this.Enabled = false; try { /*labelSyncing.Text = "Deleting a file"; * labelSyncing.Refresh(); * progressBarSync.Value = 10; * progressBarSync.Refresh(); * string del_cmd = $"rm /etc/preinit.d/p8173_ownbgs"; * clovershell.ExecuteSimple(del_cmd, 3000); * Thread.Sleep(1000); * labelSyncing.Text = "Reboot..."; * labelSyncing.Refresh(); * progressBarSync.Value = 20; * progressBarSync.Refresh(); * clovershell.ExecuteSimple("reboot", 3000); * Thread.Sleep(2000); * labelSyncing.Text = "Waiting reboot..."; * labelSyncing.Refresh(); * progressBarSync.Value = 30; * progressBarSync.Refresh(); * while (!(clovershell.IsOnline)) * { * Debug.WriteLine("Wait reboot"); * Thread.Sleep(2000); * } */ labelSyncing.Text = "Creating directory..."; labelSyncing.Refresh(); progressBarSync.Value = 10; progressBarSync.Refresh(); string command = $"src=\"{src_backgroundPath}\" && " + $"dst=\"{dest_backgroundPath}\" && " + $"rm -rf \"$dst\" && " + $"mkdir -p \"$dst\""; clovershell.ExecuteSimple(command, 10000, true); foreach (ListViewItem border in listViewBorders.CheckedItems) { if (border.Tag is BorderElement) { string repName = (border.Tag as BorderElement).Name; DirectoryInfo diSource = new DirectoryInfo(bgDirectory + "/" + repName); DirectoryInfo diTarget = new DirectoryInfo(tempBordersDirectory + "/" + repName); CopyAll(diSource, diTarget); } } string[] lines = { "overmount /usr/share/backgrounds/", "" }; System.IO.File.WriteAllLines(tempBordersDirectory + "/" + "p8173_ownbgs", lines); labelSyncing.Text = "Uploading user borders..."; labelSyncing.Refresh(); progressBarSync.Value = 20; progressBarSync.Refresh(); using (var bordersTar = new TarStream(tempBordersDirectory)) { if (bordersTar.Length > 0) { bordersTar.OnReadProgress += delegate(long pos, long len) { Debug.WriteLine("SetProgress(" + pos.ToString() + ", " + len.ToString()); }; clovershell.Execute(string.Format("tar -xvC {0}", dest_backgroundPath), bordersTar, null, null, 30000, true); } } string move_cmd = $"mv {dest_backgroundPath}/p8173_ownbgs /etc/preinit.d/"; clovershell.ExecuteSimple(move_cmd, 3000, true); labelSyncing.Text = "Managing default borders..."; labelSyncing.Refresh(); progressBarSync.Value = 80; progressBarSync.Refresh(); if (listViewBorders.Items[0].Checked) { var selected = new List <string>(); foreach (DefaultBorder border in checkedListBoxDefaultBorders.CheckedItems) { selected.Add(border.Name); } foreach (string bordername in selected) { string cmd = $"src=\"{src_backgroundPath}/{bordername}\" && " + $"dst=\"{dest_backgroundPath}/{bordername}\" && " + $"ln -s \"$src\" \"$dst\""; clovershell.ExecuteSimple(cmd, 10000, true); } } } finally { try { labelSyncing.Text = "Reboot..."; labelSyncing.Refresh(); progressBarSync.Value = 100; progressBarSync.Refresh(); Directory.Delete(tempDirectory, true); if (clovershell.IsOnline) { clovershell.ExecuteSimple("reboot", 100); } } catch { } MessageBox.Show(this, "work is done", "Custom borders", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Enabled = true; this.Close(); } } }
public static void Shell_OnConnected(ISystemShell caller) { // set calling shell as current used shell and disable others Shell = caller; shells.ForEach(shell => { if (shell != caller) { shell.Enabled = false; } }); try { Connected = Shell.IsOnline; if (!Shell.IsOnline) { throw new IOException("Shell connection should be online!"); } MinimalMemboot = Shell.Execute("source /hakchi/config; [ \"$cf_memboot\" = \"y\" ]") == 0; // detect unique id UniqueID = Shell.ExecuteSimple("echo \"`devmem 0x01C23800``devmem 0x01C23804``devmem 0x01C23808``devmem 0x01C2380C`\"").Trim().Replace("0x", ""); Debug.WriteLine($"Detected device unique ID: {UniqueID}"); // execution stops here for a minimal memboot if (!MinimalMemboot) { // detect running/mounted firmware string board = Shell.ExecuteSimple("cat /etc/clover/boardtype", 3000, true); string region = Shell.ExecuteSimple("cat /etc/clover/REGION", 3000, true); DetectedConsoleType = translateConsoleType(board, region); if (DetectedConsoleType == ConsoleType.Unknown) { throw new IOException("Unable to determine mounted firmware"); } var customFirmwareLoaded = Shell.ExecuteSimple("hakchi currentFirmware"); CustomFirmwareLoaded = customFirmwareLoaded != "_nand_"; Debug.WriteLine(string.Format("Detected mounted board: {0}, region: {1}, firmware: {2}", board, region, customFirmwareLoaded)); // detect running versions var versions = Shell.ExecuteSimple("source /var/version && echo \"$bootVersion $kernelVersion $hakchiVersion\"", 500, true).Split(' '); BootVersion = versions[0]; KernelVersion = versions[1]; ScriptVersion = versions[2]; Debug.WriteLine($"Detected versions: boot {BootVersion}, kernel {KernelVersion}, script {ScriptVersion}"); CanInteract = !SystemRequiresReflash() && !SystemRequiresRootfsUpdate(); // only do more interaction if safe to do so if (CanInteract) { // detect basic paths RemoteGameSyncPath = Shell.ExecuteSimple("hakchi findGameSyncStorage", 2000, true).Trim(); SystemCode = Shell.ExecuteSimple("hakchi eval 'echo \"$sftype-$sfregion\"'", 2000, true).Trim(); OriginalGamesPath = Shell.ExecuteSimple("hakchi get gamepath", 2000, true).Trim(); RootFsPath = Shell.ExecuteSimple("hakchi get rootfs", 2000, true).Trim(); SquashFsPath = Shell.ExecuteSimple("hakchi get squashfs", 2000, true).Trim(); // load config ConfigIni.SetConfigDictionary(LoadConfig()); // calculate stats MemoryStats.Refresh(); } } // chain to other OnConnected events OnConnected(caller); } catch (Exception ex) { Debug.WriteLine(ex.Message + ex.StackTrace); CanInteract = false; MinimalMemboot = false; } }
public static void Clovershell_OnConnected() { // clear up values Clovershell_OnDisconnected(); try { var Clovershell = MainForm.Clovershell; if (!Clovershell.IsOnline) { throw new IOException("Clovershell connection unexpectedly offline"); } MinimalMemboot = Clovershell.Execute("stat /generalmemboot.flag &>/dev/null") == 0; // detect unique id UniqueID = Clovershell.ExecuteSimple("echo \"`devmem 0x01C23800``devmem 0x01C23804``devmem 0x01C23808``devmem 0x01C2380C`\"").Trim().Replace("0x", ""); Debug.WriteLine($"Detected device unique ID: {UniqueID}"); if (MinimalMemboot) { return; } // detect running/mounted firmware string board = Clovershell.ExecuteSimple("cat /etc/clover/boardtype", 3000, true); string region = Clovershell.ExecuteSimple("cat /etc/clover/REGION", 3000, true); Debug.WriteLine(string.Format("Detected mounted board: {0}", board)); Debug.WriteLine(string.Format("Detected mounted region: {0}", region)); DetectedMountedConsoleType = translateConsoleType(board, region); if (DetectedMountedConsoleType == MainForm.ConsoleType.Unknown) { throw new IOException("Unable to determine mounted firmware"); } // detect running versions var versions = MainForm.Clovershell.ExecuteSimple("source /var/version && echo \"$bootVersion $kernelVersion $hakchiVersion\"", 500, true).Split(' '); BootVersion = versions[0]; KernelVersion = versions[1]; ScriptVersion = versions[2]; CanInteract = !SystemRequiresReflash() && !SystemRequiresRootfsUpdate(); // only do more interaction if safe to do so if (CanInteract) { // detect root firmware var customFirmwareLoaded = Clovershell.ExecuteSimple("hakchi currentFirmware") != "_nand_"; if (customFirmwareLoaded) { Clovershell.ExecuteSimple("cryptsetup open /dev/nandb root-crypt --readonly --type plain --cipher aes-xts-plain --key-file /etc/key-file", 3000); Clovershell.ExecuteSimple("mkdir -p /var/squashfs-original", 3000, true); Clovershell.ExecuteSimple("mount /dev/mapper/root-crypt /var/squashfs-original", 3000, true); board = Clovershell.ExecuteSimple("cat /var/squashfs-original/etc/clover/boardtype", 3000, true); region = Clovershell.ExecuteSimple("cat /var/squashfs-original/etc/clover/REGION", 3000, true); Debug.WriteLine(string.Format("Detected system board: {0}", board)); Debug.WriteLine(string.Format("Detected system region: {0}", region)); Clovershell.ExecuteSimple("umount /var/squashfs-original", 3000, true); Clovershell.ExecuteSimple("rm -rf /var/squashfs-original", 3000, true); Clovershell.ExecuteSimple("cryptsetup close root-crypt", 3000, true); } DetectedConsoleType = translateConsoleType(board, region); // detect basic paths RemoteGameSyncPath = MainForm.Clovershell.ExecuteSimple("hakchi findGameSyncStorage", 2000, true).Trim(); SystemCode = MainForm.Clovershell.ExecuteSimple("hakchi eval 'echo \"$sftype-$sfregion\"'", 2000, true).Trim(); // load config ConfigIni.SetConfigDictionary(LoadConfig()); } } catch (Exception ex) { Debug.WriteLine(ex.Message); CanInteract = false; MinimalMemboot = false; } }
// legacy loading code for transition public static bool LoadLegacy() { var fileName = Shared.PathCombine(Program.BaseDirectoryExternal, ConfigDir, LegacyConfigFile); if (File.Exists(fileName)) { try { Trace.WriteLine("Loading legacy configuration file"); instance = new ConfigIni(); var configLines = File.ReadAllLines(fileName); List <string> list; string section = ""; foreach (var line in configLines) { var l = line.Trim(); if (l.StartsWith("[") && l.EndsWith("]")) { section = l.Substring(1, l.Length - 2).ToLower(); } int pos = l.IndexOf('='); if (pos <= 0) { continue; } var param = l.Substring(0, pos).Trim(); var value = l.Substring(pos + 1).Trim(); switch (section) { case "config": param = param.ToLower(); switch (param) { case "lastversion": instance.LastVersion = value; break; case "language": instance.Language = value; break; case "selectedgames": case "selectedgamesnes": instance.gamesCollectionSettings[hakchi.ConsoleType.NES].SelectedGames = value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (instance.gamesCollectionSettings[hakchi.ConsoleType.Famicom].SelectedGames.Count == 0) { instance.gamesCollectionSettings[hakchi.ConsoleType.Famicom].SelectedGames = instance.gamesCollectionSettings[hakchi.ConsoleType.NES].SelectedGames.ToList(); } break; case "selectedgamesfamicom": instance.gamesCollectionSettings[hakchi.ConsoleType.Famicom].SelectedGames = value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList(); break; case "selectedgamessnes": instance.gamesCollectionSettings[hakchi.ConsoleType.SNES_EUR].SelectedGames = value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList(); instance.gamesCollectionSettings[hakchi.ConsoleType.SNES_USA].SelectedGames = value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (instance.gamesCollectionSettings[hakchi.ConsoleType.SuperFamicom].SelectedGames.Count == 0) { instance.gamesCollectionSettings[hakchi.ConsoleType.SuperFamicom].SelectedGames = instance.gamesCollectionSettings[hakchi.ConsoleType.SNES_EUR].SelectedGames.ToList(); } break; case "selectedgamessuperfamicom": instance.gamesCollectionSettings[hakchi.ConsoleType.SuperFamicom].SelectedGames = value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList(); break; case "hiddengames": list = value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList(); instance.gamesCollectionSettings[hakchi.ConsoleType.NES].OriginalGames = NesApplication.DefaultGames[hakchi.ConsoleType.NES].Where(code => !list.Contains(code)).ToList(); break; case "hiddengamesfamicom": list = value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList(); instance.gamesCollectionSettings[hakchi.ConsoleType.Famicom].OriginalGames = NesApplication.DefaultGames[hakchi.ConsoleType.Famicom].Where(code => !list.Contains(code)).ToList(); break; case "hiddengamessnes": list = value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList(); instance.gamesCollectionSettings[hakchi.ConsoleType.SNES_EUR].OriginalGames = NesApplication.DefaultGames[hakchi.ConsoleType.SNES_EUR].Where(code => !list.Contains(code)).ToList(); instance.gamesCollectionSettings[hakchi.ConsoleType.SNES_USA].OriginalGames = NesApplication.DefaultGames[hakchi.ConsoleType.SNES_USA].Where(code => !list.Contains(code)).ToList(); break; case "hiddengamessuperfamicom": list = value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList(); instance.gamesCollectionSettings[hakchi.ConsoleType.SuperFamicom].OriginalGames = NesApplication.DefaultGames[hakchi.ConsoleType.SuperFamicom].Where(code => !list.Contains(code)).ToList(); break; case "originalgamesposition": instance.OriginalGamesPosition = (MainForm.OriginalGamesPosition) byte.Parse(value); break; case "groupgamesbyapptype": instance.GamesSorting = !value.ToLower().Equals("false") ? MainForm.GamesSorting.System : MainForm.GamesSorting.Name; break; case "customflashednes": case "customflashedfamicom": case "customflashedsnes": case "customflashedsuperfamicom": case "usefont": case "usefontfamicom": case "usefontsnes": case "usefontsuperfamicom": case "antiarmetlevel": case "resethack": case "cloverconhack": case "resethacksnes": case "autofirehack": case "autofirehacksnes": case "autofirexyhack": case "resetcombination": case "resetcombinationsnes": case "usbhostnes": case "usbhostfamicom": case "usbhostsnes": case "usbhostsuperfamicom": // ignoring these settings, using defaults break; case "runcount": instance.RunCount = int.Parse(value); break; case "consoletype": instance.ConsoleType = (hakchi.ConsoleType) byte.Parse(value); if (instance.ConsoleType == hakchi.ConsoleType.SNES_USA) // compensate for new 5th console type { instance.ConsoleType = hakchi.ConsoleType.SuperFamicom; } break; case "extracommandlinearguments": instance.consoleSettings[0].ExtraCommandLineArguments[ExtraCmdLineTypes.Kachikachi] = value; break; case "extracommandlineargumentssnes": instance.consoleSettings[0].ExtraCommandLineArguments[ExtraCmdLineTypes.Canoe] = value; break; case "fcstart": instance.consoleSettings[0].FcStart = !value.ToLower().Equals("false"); break; case "maxgamesperfolder": instance.gamesCollectionSettings[hakchi.ConsoleType.NES].MaxGamesPerFolder = byte.Parse(value); break; case "maxgamesperfolderfamicom": instance.gamesCollectionSettings[hakchi.ConsoleType.Famicom].MaxGamesPerFolder = byte.Parse(value); break; case "maxgamesperfoldersnes": instance.gamesCollectionSettings[hakchi.ConsoleType.SNES_EUR].MaxGamesPerFolder = instance.gamesCollectionSettings[hakchi.ConsoleType.SNES_USA].MaxGamesPerFolder = byte.Parse(value); break; case "maxgamesperfoldersuperfamicom": instance.gamesCollectionSettings[hakchi.ConsoleType.SuperFamicom].MaxGamesPerFolder = byte.Parse(value); break; case "foldersmode": instance.gamesCollectionSettings[hakchi.ConsoleType.NES].FoldersMode = (NesMenuCollection.SplitStyle) byte.Parse(value); break; case "foldersmodefamicom": instance.gamesCollectionSettings[hakchi.ConsoleType.Famicom].FoldersMode = (NesMenuCollection.SplitStyle) byte.Parse(value); break; case "foldersmodesnes": instance.gamesCollectionSettings[hakchi.ConsoleType.SNES_EUR].FoldersMode = instance.gamesCollectionSettings[hakchi.ConsoleType.SNES_USA].FoldersMode = (NesMenuCollection.SplitStyle) byte.Parse(value); break; case "foldersmodesuperfamicom": instance.gamesCollectionSettings[hakchi.ConsoleType.SuperFamicom].FoldersMode = (NesMenuCollection.SplitStyle) byte.Parse(value); break; case "usesfromtool": instance.UseSFROMTool = !value.ToLower().Equals("false"); break; case "usepcmpatch": instance.UsePCMPatch = !value.ToLower().Equals("false"); break; case "compress": instance.Compress = !value.ToLower().Equals("false"); break; case "compresscover": instance.CompressCover = !value.ToLower().Equals("false"); break; case "centerthumbnail": instance.CenterThumbnail = !value.ToLower().Equals("false"); break; case "disablepopups": instance.DisablePopups = !value.ToLower().Equals("false"); break; case "ftpserver": //instance.FtpServer = !value.ToLower().Equals("false"); break; case "ftpcommand": instance.FtpCommand = value; break; case "ftparguments": instance.FtpArguments = value; break; case "telnetserver": //instance.TelnetServer = !value.ToLower().Equals("false"); break; case "telnetcommand": instance.TelnetCommand = value; break; case "telnetarguments": instance.TelnetArguments = value; break; case "separategamestorage": instance.SeparateGameStorage = !value.ToLower().Equals("false"); break; case "exportlinked": instance.ExportLinked = !value.ToLower().Equals("false"); break; case "synclinked": instance.SyncLinked = !value.ToLower().Equals("false"); break; case "exportregion": //instance.ExportRegion = value; break; case "membootuboot": if (value == "uboot.bin") { instance.MembootUboot = UbootType.Normal; } else { instance.MembootUboot = UbootType.SD; } break; case "hmodlistsort": instance.hmodListSort = (Hmod.ListSort) byte.Parse(value); break; } break; case "presets": instance.gamesCollectionSettings[hakchi.ConsoleType.NES].Presets[param] = value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList(); instance.gamesCollectionSettings[hakchi.ConsoleType.Famicom].Presets[param] = value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList(); instance.gamesCollectionSettings[hakchi.ConsoleType.SNES_EUR].Presets[param] = value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList(); instance.gamesCollectionSettings[hakchi.ConsoleType.SNES_USA].Presets[param] = value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList(); instance.gamesCollectionSettings[hakchi.ConsoleType.SuperFamicom].Presets[param] = value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList(); break; } } // cleanup instance.gamesCollectionSettings.ToList().ForEach(pair => pair.Value.SelectedGames.Remove("default")); // success return(true); } catch (Exception ex) { Trace.WriteLine("Error loading legacy configuration file : " + ex.Message + ex.StackTrace); instance = null; } } // failure return(false); }
private void fillActions(Version lastVersion, Version currentVersion) { actions.AddRange(new Action[] { new Action() { startingVersion = new Version("0.0.0.0"), targetVersion = new Version("3.0.0.0"), action = new ActionFunc(() => { mainForm.ResetOriginalGamesForAllSystems(false); return(true); }) }, new Action() { startingVersion = new Version("3.0.0.0"), targetVersion = new Version("3.1.0.5"), action = new ActionFunc(() => { string f = Path.Combine(Program.BaseDirectoryExternal, ConfigIni.ConfigDir, "folders_snes.xml"); string f1 = Path.Combine(Program.BaseDirectoryExternal, ConfigIni.ConfigDir, "folders_snes_eur.xml"); string f2 = Path.Combine(Program.BaseDirectoryExternal, ConfigIni.ConfigDir, "folders_snes_usa.xml"); if (File.Exists(f)) { Trace.WriteLine("Converting folders_snes.xml file into eur and usa counterparts."); if (!File.Exists(f1)) { File.Copy(f, f1); } if (!File.Exists(f2)) { File.Copy(f, f2); } File.Delete(f); } return(true); }) }, new Action() { startingVersion = new Version("3.1.0.5"), targetVersion = new Version("3.2.2.0"), action = new ActionFunc(() => { string i = Program.BaseDirectoryInternal; string e = Program.BaseDirectoryExternal; string[] unusedFiles = new string[] { Path.Combine(i, "data", "fes1.bin"), Path.Combine(i, "data", "splash.gz"), Path.Combine(i, "data", "uboot.bin"), Path.Combine(i, "data", "ubootSD.bin"), Path.Combine(i, "data", "zImage"), Path.Combine(i, "data", "zImageMemboot"), Path.Combine(i, "tools", "cpio.exe"), Path.Combine(i, "tools", "cyggcc_s-1.dll"), Path.Combine(i, "tools", "cygiconv-2.dll"), Path.Combine(i, "tools", "cygintl-8.dll"), Path.Combine(i, "tools", "cygwin1.dll"), Path.Combine(i, "tools", "lzop.exe"), Path.Combine(i, "tools", "mkbootfs.exe"), Path.Combine(i, "tools", "mkbootimg.exe"), Path.Combine(i, "tools", "unpackbootimg.exe"), Path.Combine(i, "tools", "xz.exe"), Path.Combine(e, "user_mods", "hakchi-v1.0.3-110.hmod") }; string[] unusedDirectories = new string[] { Path.Combine(i, "languages", "en-GB"), Path.Combine(i, "mods"), Path.Combine(e, "user_mods", "music_hack.hmod") }; foreach (var dir in unusedDirectories) { try { Directory.Delete(dir, true); } catch (DirectoryNotFoundException) { } catch (UnauthorizedAccessException) { Trace.WriteLine($"Could not delete directory \"{dir}\". UAC restrictions. No big deal"); } catch { } } foreach (var file in unusedFiles) { try { File.Delete(file); } catch (FileNotFoundException) { } catch (UnauthorizedAccessException) { Trace.WriteLine($"Could not delete file \"{file}\". UAC restrictions. No big deal"); } catch { } } return(true); }) }, new Action() { startingVersion = new Version("3.2.2.0"), targetVersion = new Version("3.3.0.0"), action = new ActionFunc(() => { if (ConfigIni.Instance.LastVersion != "0.0.0.0") { ConfigIni.Instance.SeparateGameLocalStorage = true; } return(true); }) }, new Action() { startingVersion = new Version("3.4.1.0"), targetVersion = new Version("3.4.1.1"), action = new ActionFunc(() => { var tempConfig = ConfigIni.GetCleanInstance(); ConfigIni.Instance.TelnetCommand = tempConfig.TelnetCommand; ConfigIni.Instance.TelnetArguments = tempConfig.TelnetArguments; ConfigIni.Instance.FtpCommand = tempConfig.FtpCommand; ConfigIni.Instance.FtpArguments = tempConfig.FtpArguments; return(true); }) }, new Action() { startingVersion = new Version("3.5.0.0"), targetVersion = new Version("3.5.3.0"), action = new ActionFunc(() => { ConfigIni.Instance.repos = ConfigIni.Instance.repos.Where(repo => repo.URL != "modstore://").ToArray(); return(true); }) }, new Action() { startingVersion = new Version("0.0.0.0"), targetVersion = new Version("3.6.1.1008"), action = new ActionFunc(() => { if (lastVersion.CompareTo(new Version(0, 0, 0, 0)) != 0) { mainForm.ResetOriginalGamesForAllSystems(true); } ConfigIni.Instance.gamesCollectionSettings[hakchi.ConsoleType.MD_USA].MaxGamesPerFolder = 42; ConfigIni.Instance.gamesCollectionSettings[hakchi.ConsoleType.MD_USA].FolderImagesSet = "TheWez1981-Genesis"; ConfigIni.Instance.gamesCollectionSettings[hakchi.ConsoleType.MD_EUR].MaxGamesPerFolder = 42; ConfigIni.Instance.gamesCollectionSettings[hakchi.ConsoleType.MD_EUR].FolderImagesSet = "TheWez1981-MegaDrive"; ConfigIni.Instance.gamesCollectionSettings[hakchi.ConsoleType.MD_JPN].MaxGamesPerFolder = 42; ConfigIni.Instance.gamesCollectionSettings[hakchi.ConsoleType.MD_JPN].FolderImagesSet = "TheWez1981-MegaDrive-JP"; ConfigIni.Instance.gamesCollectionSettings[hakchi.ConsoleType.MD_ASIA].MaxGamesPerFolder = 42; ConfigIni.Instance.gamesCollectionSettings[hakchi.ConsoleType.MD_ASIA].FolderImagesSet = "TheWez1981-MegaDrive"; return(true); }) } }); }
static void Main(string[] args) { SevenZip.SevenZipExtractor.SetLibraryPath(Path.Combine(Program.BaseDirectoryInternal, IntPtr.Size == 8 ? @"tools\7z64.dll" : @"tools\7z.dll")); #if DEBUG try { AllocConsole(); IntPtr stdHandle = CreateFile("CONOUT$", GENERIC_WRITE, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); SafeFileHandle safeFileHandle = new SafeFileHandle(stdHandle, true); FileStream consoleFileStream = new FileStream(safeFileHandle, FileAccess.Write); Encoding encoding = System.Text.Encoding.GetEncoding(MY_CODE_PAGE); StreamWriter standardOutput = new StreamWriter(consoleFileStream, encoding); standardOutput.AutoFlush = true; Console.SetOut(standardOutput); debugStreams.Add(consoleFileStream); Debug.Listeners.Add(new TextWriterTraceListener(System.Console.Out)); } catch { } try { Stream logFile = File.Create("debuglog.txt"); debugStreams.Add(logFile); Debug.Listeners.Add(new TextWriterTraceListener(logFile)); } catch (Exception ex) { Debug.WriteLine(ex.Message + ex.StackTrace); } Debug.AutoFlush = true; #else Trace.Listeners.Clear(); #endif #if TRACE try { MemoryStream inMemoryLog = new MemoryStream(); debugStreams.Add(inMemoryLog); Trace.Listeners.Add(new TextWriterTraceListener(new StreamWriter(inMemoryLog, System.Text.Encoding.GetEncoding(MY_CODE_PAGE)))); } catch (Exception ex) { Trace.WriteLine(ex.Message + ex.StackTrace); } Trace.AutoFlush = true; #endif isPortable = !args.Contains("/nonportable") || args.Contains("/portable"); if (File.Exists(Path.Combine(BaseDirectoryInternal, "nonportable.flag"))) { isPortable = false; } bool isFirstRun = false; if (!isPortable) { isFirstRun = Shared.isFirstRun(); } try { bool createdNew = true; using (Mutex mutex = new Mutex(true, "hakchi2", out createdNew)) { if (createdNew) { if (!isPortable) { // This is not correct way for Windows 7+... BaseDirectoryExternal = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "hakchi2"); // So if it's not exists, lets try to get documents library path (Win7+) try { if (!Directory.Exists(BaseDirectoryExternal)) { BaseDirectoryExternal = Path.Combine(GetDocumentsLibraryPath(), "hakchi2"); } // There are some folders which should be accessed by user // Moving them to "My documents" if (isFirstRun) { var externalDirs = new string[] { "art", "folder_images", "patches", "user_mods", "sfrom_tool" }; foreach (var dir in externalDirs) { Shared.DirectoryCopy(Path.Combine(BaseDirectoryInternal, dir), Path.Combine(BaseDirectoryExternal, dir), true, false, true, false); } } } catch (Exception ex) { // TODO: Test it on Windows XP Trace.WriteLine(ex.Message); } } else { BaseDirectoryExternal = BaseDirectoryInternal; } Trace.WriteLine("Base directory: " + BaseDirectoryExternal + " (" + (isPortable ? "portable" : "non-portable") + " mode)"); ConfigIni.Load(); try { if (!string.IsNullOrEmpty(ConfigIni.Instance.Language)) { Thread.CurrentThread.CurrentUICulture = new CultureInfo(ConfigIni.Instance.Language); } } catch { } string languagesDirectory = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "languages"); const string langFileNames = "hakchi.resources.dll"; AppDomain.CurrentDomain.AppendPrivatePath(languagesDirectory); // For updates var oldFiles = Directory.GetFiles(Path.GetDirectoryName(Application.ExecutablePath), langFileNames, SearchOption.AllDirectories); foreach (var d in oldFiles) { if (!d.Contains(Path.DirectorySeparatorChar + "languages" + Path.DirectorySeparatorChar)) { var dir = Path.GetDirectoryName(d); Trace.WriteLine("Removing old directory: " + dir); if (!isPortable) { var targetDir = Path.Combine(languagesDirectory, Path.GetFileName(dir)); Directory.CreateDirectory(targetDir); var targetFile = Path.Combine(targetDir, langFileNames); if (File.Exists(targetFile)) { File.Delete(targetFile); } File.Copy(Path.Combine(dir, langFileNames), targetFile); } else { Directory.Delete(dir, true); } } } Trace.WriteLine("Starting, version: " + Shared.AppDisplayVersion); System.Net.ServicePointManager.SecurityProtocol = (System.Net.SecurityProtocolType) 4080; // set default security protocol Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); FormContext.AllFormsClosed += Process.GetCurrentProcess().Kill; // Suicide! Just easy and dirty way to kill all threads. FormContext.AddForm(new MainForm()); Application.Run(FormContext); Trace.WriteLine("Done."); } else { Process current = Process.GetCurrentProcess(); foreach (Process process in Process.GetProcessesByName("hakchi")) { if (process.Id != current.Id) { ShowWindow(process.MainWindowHandle, 9); // Restore SetForegroundWindow(process.MainWindowHandle); // Foreground break; } } } } } catch (Exception ex) { Trace.WriteLine(ex.Message + ex.StackTrace); MessageBox.Show(ex.Message + ex.StackTrace, Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Error); } }