Exemple #1
0
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (this.DialogResult == DialogResult.OK)
            {
                if (!ValidateFolderSettings())
                {
                    e.Cancel = true;
                    return;
                }

                if (radStorageDocuments.Checked != (ConfigManager.HomeFolder == ConfigManager.DefaultDocumentsFolder))
                {
                    //Need to copy files and display confirmation
                    string targetFolder = radStorageDocuments.Checked ? ConfigManager.DefaultDocumentsFolder : ConfigManager.DefaultPortableFolder;
                    if (MesenMsgBox.Show("CopyMesenDataPrompt", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, ConfigManager.HomeFolder, targetFolder) == DialogResult.OK)
                    {
                        try {
                            MigrateData(ConfigManager.HomeFolder, targetFolder);
                        } catch (Exception ex) {
                            MesenMsgBox.Show("UnexpectedError", MessageBoxButtons.OK, MessageBoxIcon.Error, ex.ToString());
                            e.Cancel = true;
                        }
                    }
                    else
                    {
                        e.Cancel = true;
                        return;
                    }
                }
            }
            else
            {
                base.OnFormClosing(e);
            }
        }
Exemple #2
0
 private void TryEnableSync(bool retry = true)
 {
     if (CloudSyncHelper.EnableSync())
     {
         if (!CloudSyncHelper.Sync())
         {
             if (retry)
             {
                 TryEnableSync(false);
             }
             else
             {
                 MesenMsgBox.Show("GoogleDriveIntegrationError", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
         }
         else
         {
             UpdateCloudDisplay();
         }
     }
     else
     {
         MesenMsgBox.Show("GoogleDriveIntegrationError", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Exemple #3
0
        public static bool TestDll()
        {
            try {
                return(InteropEmu.TestDll());
            } catch {
            }

            if (!File.Exists("WinMesen.dll"))
            {
                MesenMsgBox.Show("UnableToStartMissingFiles", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                if (MesenMsgBox.Show("UnableToStartMissingDependencies", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    if (!RuntimeChecker.DownloadRuntime())
                    {
                        MesenMsgBox.Show("CouldNotInstallRuntime", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        Process.Start(Process.GetCurrentProcess().MainModule.FileName);
                    }
                }
            }
            return(false);
        }
Exemple #4
0
        public static bool TestDll()
        {
            try {
                return(EmuApi.TestDll());
            } catch {
            }

            bool dllExists;

            if (Program.IsMono)
            {
                dllExists = File.Exists(Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "libMesenSCore.dll"));
            }
            else
            {
                dllExists = File.Exists("MesenSCore.dll");
            }

            if (!dllExists)
            {
                MesenMsgBox.Show("UnableToStartMissingFiles", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                MesenMsgBox.Show("UnableToStartMissingDependencies", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return(false);
        }
Exemple #5
0
 public static bool RequestBiosFile(string fileName, int fileSize, RomFormat format)
 {
     if (MesenMsgBox.Show("BiosNotFound", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, fileName, fileSize.ToString()) == DialogResult.OK)
     {
         using (OpenFileDialog ofd = new OpenFileDialog()) {
             ofd.SetFilter(ResourceHelper.GetMessage("FilterAll"));
             if (ofd.ShowDialog(Application.OpenForms[0]) == DialogResult.OK)
             {
                 byte[] fileData;
                 string hash = GetFileHash(ofd.FileName, out fileData);
                 if (!GetExpectedHashes(format).Contains(hash))
                 {
                     if (MesenMsgBox.Show("BiosMismatch", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, GetExpectedHashes(format)[0], hash) != DialogResult.OK)
                     {
                         //Files don't match and user cancelled the action
                         return(false);
                     }
                 }
                 File.WriteAllBytes(Path.Combine(ConfigManager.HomeFolder, fileName), fileData);
                 return(true);
             }
         }
     }
     return(false);
 }
Exemple #6
0
 private void btnResetSettings_Click(object sender, EventArgs e)
 {
     if (MesenMsgBox.Show("ResetSettingsConfirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
     {
         ConfigManager.ResetSettings();
         this.Close();
     }
 }
 public static List <CheatInfo> Load(string filepath, string gameName, string gameCrc)
 {
     try {
         XmlDocument xml = new XmlDocument();
         xml.Load(filepath);
         return(NestopiaCheatLoader.Load(xml, gameName, gameCrc, filepath));
     } catch {
         //Invalid xml file
         MesenMsgBox.Show("InvalidXmlFile", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error, Path.GetFileName(filepath));
         return(null);
     }
 }
 public static List <CheatInfo> Load(Stream cheatFile, string gameName, string gameCrc)
 {
     try {
         XmlDocument xml = new XmlDocument();
         xml.Load(cheatFile);
         return(NestopiaCheatLoader.Load(xml, gameName, gameCrc, ""));
     } catch {
         //Invalid xml file
         MesenMsgBox.Show("InvalidXmlFile", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error, string.Empty);
         return(null);
     }
 }
Exemple #9
0
 private void btnImportCheatDB_Click(object sender, EventArgs e)
 {
     using (frmCheatImportFromDb frm = new frmCheatImportFromDb()) {
         if (frm.ShowDialog() == DialogResult.OK)
         {
             if (frm.ImportedCheats.Count > 0)
             {
                 this.AddCheats(frm.ImportedCheats);
                 MesenMsgBox.Show("CheatsImported", MessageBoxButtons.OK, MessageBoxIcon.Information, frm.ImportedCheats.Count.ToString(), frm.ImportedCheats[0].GameName);
             }
         }
     }
 }
Exemple #10
0
        protected override void OnDragDrop(DragEventArgs e)
        {
            base.OnDragDrop(e);

            try {
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                if (files != null && File.Exists(files[0]))
                {
                    ImportLabelFile(files[0]);
                }
            } catch (Exception ex) {
                MesenMsgBox.Show("UnexpectedError", MessageBoxButtons.OK, MessageBoxIcon.Error, ex.ToString());
            }
        }
Exemple #11
0
        public static void LoadPatchFile(string patchFile)
        {
            string           patchFolder   = Path.GetDirectoryName(patchFile);
            HashSet <string> romExtensions = new HashSet <string>()
            {
                ".sfc", ".smc", ".swc", ".fig"
            };
            List <string> romsInFolder = new List <string>();

            foreach (string filepath in Directory.EnumerateFiles(patchFolder))
            {
                if (romExtensions.Contains(Path.GetExtension(filepath).ToLowerInvariant()))
                {
                    romsInFolder.Add(filepath);
                }
            }

            if (romsInFolder.Count == 1)
            {
                //There is a single rom in the same folder as the IPS/BPS patch, use it automatically
                LoadRom(romsInFolder[0], patchFile);
            }
            else
            {
                if (!IsRunning() || !_romPath.HasValue)
                {
                    //Prompt the user for a rom to load
                    if (MesenMsgBox.Show("SelectRomIps", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                    {
                        using (OpenFileDialog ofd = new OpenFileDialog()) {
                            ofd.SetFilter(ResourceHelper.GetMessage("FilterRom"));
                            if (ConfigManager.Config.RecentFiles.Items.Count > 0)
                            {
                                ofd.InitialDirectory = ConfigManager.Config.RecentFiles.Items[0].RomFile.Folder;
                            }

                            if (ofd.ShowDialog(Application.OpenForms[0]) == DialogResult.OK)
                            {
                                LoadRom(ofd.FileName, patchFile);
                            }
                        }
                    }
                }
                else if (MesenMsgBox.Show("PatchAndReset", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    //Confirm that the user wants to patch the current rom and reset
                    LoadRom(_romPath.Value, patchFile);
                }
            }
        }
Exemple #12
0
        public static void LoadPatchFile(string patchFile)
        {
            string        patchFolder  = Path.GetDirectoryName(patchFile);
            List <string> romsInFolder = new List <string>();

            foreach (string filepath in Directory.EnumerateFiles(patchFolder))
            {
                if (FolderHelper.IsRomFile(filepath))
                {
                    romsInFolder.Add(filepath);
                }
            }

            if (romsInFolder.Count == 1)
            {
                //There is a single rom in the same folder as the IPS/BPS patch, use it automatically
                LoadRom(romsInFolder[0], patchFile);
            }
            else
            {
                if (!IsRunning())
                {
                    //Prompt the user for a rom to load
                    if (MesenMsgBox.Show("SelectRomIps", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                    {
                        using (OpenFileDialog ofd = new OpenFileDialog()) {
                            ofd.SetFilter(ResourceHelper.GetMessage("FilterRom"));
                            if (ConfigManager.Config.RecentFiles.Items.Count > 0)
                            {
                                ofd.InitialDirectory = ConfigManager.Config.RecentFiles.Items[0].RomFile.Folder;
                            }

                            if (ofd.ShowDialog(frmMain.Instance) == DialogResult.OK)
                            {
                                LoadRom(ofd.FileName, patchFile);
                            }
                        }
                    }
                }
                else if (MesenMsgBox.Show("PatchAndReset", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    //Confirm that the user wants to patch the current rom and reset
                    LoadRom(EmuApi.GetRomInfo().RomPath, patchFile);
                }
            }
        }
Exemple #13
0
        private bool ValidateFolderSettings()
        {
            bool          result         = true;
            List <string> invalidFolders = new List <string>();

            try {
                if (chkGameOverride.Checked && !CheckFolderPermissions(psGame.Text, false))
                {
                    invalidFolders.Add(chkGameOverride.Text.Replace(":", "").Trim());
                }
                if (chkAviOverride.Checked && !CheckFolderPermissions(psAvi.Text))
                {
                    invalidFolders.Add(chkAviOverride.Text.Replace(":", "").Trim());
                }
                if (chkMoviesOverride.Checked && !CheckFolderPermissions(psMovies.Text))
                {
                    invalidFolders.Add(chkMoviesOverride.Text.Replace(":", "").Trim());
                }
                if (chkSaveDataOverride.Checked && !CheckFolderPermissions(psSaveData.Text))
                {
                    invalidFolders.Add(chkSaveDataOverride.Text.Replace(":", "").Trim());
                }
                if (chkSaveStatesOverride.Checked && !CheckFolderPermissions(psSaveStates.Text))
                {
                    invalidFolders.Add(chkSaveStatesOverride.Text.Replace(":", "").Trim());
                }
                if (chkScreenshotsOverride.Checked && !CheckFolderPermissions(psScreenshots.Text))
                {
                    invalidFolders.Add(chkScreenshotsOverride.Text.Replace(":", "").Trim());
                }
                if (chkWaveOverride.Checked && !CheckFolderPermissions(psWave.Text))
                {
                    invalidFolders.Add(chkWaveOverride.Text.Replace(":", "").Trim());
                }

                result = invalidFolders.Count == 0;
            } catch {
                result = false;
            }
            if (!result)
            {
                MesenMsgBox.Show("InvalidPaths", MessageBoxButtons.OK, MessageBoxIcon.Error, string.Join(Environment.NewLine, invalidFolders));
            }
            return(result);
        }
Exemple #14
0
        private static bool DownloadRuntime()
        {
            string link = string.Empty;

            if (IntPtr.Size == 4)
            {
                //x86
                link = "http://download.microsoft.com/download/C/E/5/CE514EAE-78A8-4381-86E8-29108D78DBD4/VC_redist.x86.exe";
            }
            else
            {
                //x64
                link = "http://download.microsoft.com/download/C/E/5/CE514EAE-78A8-4381-86E8-29108D78DBD4/VC_redist.x64.exe";
            }

            string tempFilename = Path.GetTempPath() + "Mesen_VsRuntime2015.exe";

            try {
                frmDownloadProgress frm = new frmDownloadProgress(link, tempFilename);

                if (frm.ShowDialog() == DialogResult.OK)
                {
                    Process installer = Process.Start(tempFilename, "/passive /norestart");
                    installer.WaitForExit();
                    if (installer.ExitCode != 0)
                    {
                        MesenMsgBox.Show("UnexpectedError", MessageBoxButtons.OK, MessageBoxIcon.Error, installer.ExitCode.ToString());
                        return(false);
                    }
                    else
                    {
                        //Runtime should now be installed, try to launch Mesen again
                        return(true);
                    }
                }
            } catch (Exception e) {
                MesenMsgBox.Show("UnexpectedError", MessageBoxButtons.OK, MessageBoxIcon.Error, e.ToString());
            } finally {
                try {
                    File.Delete(tempFilename);
                } catch { }
            }

            return(false);
        }
Exemple #15
0
        private void btnUpdate_Click(object sender, EventArgs e)
        {
#if DISABLEAUTOUPDATE
            MesenMsgBox.Show("AutoUpdateDisabledMessage", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.DialogResult = DialogResult.Cancel;
            this.Close();
#else
            string destFilePath   = System.Reflection.Assembly.GetEntryAssembly().Location;
            string srcFilePath    = Path.Combine(ConfigManager.DownloadFolder, "Mesen-S." + lblLatestVersionString.Text + ".exe");
            string backupFilePath = Path.Combine(ConfigManager.BackupFolder, "Mesen-S." + lblCurrentVersionString.Text + ".exe");
            string updateHelper   = Path.Combine(ConfigManager.HomeFolder, "Resources", "MesenUpdater.exe");

            if (!File.Exists(updateHelper))
            {
                MesenMsgBox.Show("UpdaterNotFound", MessageBoxButtons.OK, MessageBoxIcon.Error);
                DialogResult = DialogResult.Cancel;
            }
            else if (!string.IsNullOrWhiteSpace(srcFilePath))
            {
                using (frmDownloadProgress frmDownload = new frmDownloadProgress("https://www.mesen.ca/snes/Services/GetLatestVersion.php?a=download&p=win&v=" + EmuApi.GetMesenVersion().ToString(3), srcFilePath)) {
                    if (frmDownload.ShowDialog() == DialogResult.OK)
                    {
                        FileInfo fileInfo = new FileInfo(srcFilePath);
                        if (fileInfo.Length > 0 && ResourceExtractor.GetSha1Hash(File.ReadAllBytes(srcFilePath)) == _fileHash)
                        {
                            if (Program.IsMono)
                            {
                                Process.Start("mono", string.Format("\"{0}\" \"{1}\" \"{2}\" \"{3}\"", updateHelper, srcFilePath, destFilePath, backupFilePath));
                            }
                            else
                            {
                                Process.Start(updateHelper, string.Format("\"{0}\" \"{1}\" \"{2}\"", srcFilePath, destFilePath, backupFilePath));
                            }
                        }
                        else
                        {
                            //Download failed, mismatching hashes
                            MesenMsgBox.Show("UpdateDownloadFailed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            DialogResult = DialogResult.Cancel;
                        }
                    }
                }
            }
#endif
        }
Exemple #16
0
        protected override void OnDragEnter(DragEventArgs e)
        {
            base.OnDragEnter(e);

            try {
                if (e.Data != null && e.Data.GetDataPresent(DataFormats.FileDrop))
                {
                    string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                    if (files != null && files.Length > 0)
                    {
                        string ext = Path.GetExtension(files[0]).ToLower();
                        if (ext == ".dbg" || ext == ".msl" || ext == ".sym")
                        {
                            e.Effect = DragDropEffects.Copy;
                        }
                    }
                }
            } catch (Exception ex) {
                MesenMsgBox.Show("UnexpectedError", MessageBoxButtons.OK, MessageBoxIcon.Error, ex.ToString());
            }
        }
Exemple #17
0
        public static void CheckForUpdates(bool silent)
        {
            Task.Run(() => {
                try {
                    using (var client = new WebClient()) {
                        XmlDocument xmlDoc = new XmlDocument();

                        string platform = Program.IsMono ? "linux" : "win";
                        xmlDoc.LoadXml(client.DownloadString("https://www.mesen.ca/snes/Services/GetLatestVersion.php?v=" + EmuApi.GetMesenVersion().ToString(3) + "&p=" + platform + "&l=" + ResourceHelper.GetLanguageCode()));
                        Version currentVersion = EmuApi.GetMesenVersion();
                        Version latestVersion  = new Version(xmlDoc.SelectSingleNode("VersionInfo/LatestVersion").InnerText);
                        string changeLog       = xmlDoc.SelectSingleNode("VersionInfo/ChangeLog").InnerText;
                        string fileHash        = xmlDoc.SelectSingleNode("VersionInfo/Sha1Hash").InnerText;
                        string donateText      = xmlDoc.SelectSingleNode("VersionInfo/DonateText")?.InnerText;

                        if (latestVersion > currentVersion)
                        {
                            Application.OpenForms[0].BeginInvoke((MethodInvoker)(() => {
                                using (frmUpdatePrompt frmUpdate = new frmUpdatePrompt(currentVersion, latestVersion, changeLog, fileHash, donateText)) {
                                    if (frmUpdate.ShowDialog(null, Application.OpenForms[0]) == DialogResult.OK)
                                    {
                                        Application.Exit();
                                    }
                                }
                            }));
                        }
                        else if (!silent)
                        {
                            MesenMsgBox.Show("MesenUpToDate", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                } catch (Exception ex) {
                    if (!silent)
                    {
                        MesenMsgBox.Show("ErrorWhileCheckingUpdates", MessageBoxButtons.OK, MessageBoxIcon.Error, ex.ToString());
                    }
                }
            });
        }
Exemple #18
0
        public static void RequestFirmwareFile(MissingFirmwareMessage msg)
        {
            string filename = Utf8Marshaler.GetStringFromIntPtr(msg.Filename);

            if (MesenMsgBox.Show("FirmwareNotFound", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, msg.FirmwareType.ToString(), filename, msg.Size.ToString()) == DialogResult.OK)
            {
                using (OpenFileDialog ofd = new OpenFileDialog()) {
                    ofd.SetFilter(ResourceHelper.GetMessage("FilterAll"));
                    if (ofd.ShowDialog(Application.OpenForms[0]) == DialogResult.OK)
                    {
                        if (GetFileHash(ofd.FileName) != GetExpectedHash(msg.FirmwareType))
                        {
                            if (MesenMsgBox.Show("FirmwareMismatch", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, msg.FirmwareType.ToString(), GetFileHash(ofd.FileName), GetExpectedHash(msg.FirmwareType)) != DialogResult.OK)
                            {
                                //Files don't match and user cancelled the action
                                return;
                            }
                        }
                        File.Copy(ofd.FileName, Path.Combine(ConfigManager.FirmwareFolder, filename));
                    }
                }
            }
        }
Exemple #19
0
        private static void Main(string[] args)
        {
            try {
                Task.Run(() => {
                    //Cache deserializers in another thread
                    new XmlSerializer(typeof(Configuration));
                    new XmlSerializer(typeof(DebugWorkspace));
                });

                if (Type.GetType("Mono.Runtime") != null)
                {
                    Program.IsMono = true;
                }

                Program.OriginalFolder = Directory.GetCurrentDirectory();

                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                Application.ThreadException += Application_ThreadException;
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

                //Enable TLS 1.0/1.1/1.2 support
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                if (ConfigManager.GetConfigFile() == null)
                {
                    //Show config wizard
                    ResourceHelper.LoadResources(Language.English);
                    Application.Run(new frmConfigWizard());

                    if (ConfigManager.GetConfigFile() == null)
                    {
                        Application.Exit();
                        return;
                    }
                }
                Directory.CreateDirectory(ConfigManager.HomeFolder);
                Directory.SetCurrentDirectory(ConfigManager.HomeFolder);
                try {
                    if (!ResourceExtractor.ExtractResources())
                    {
                        return;
                    }
                } catch (FileNotFoundException e) {
                    string message = "The Microsoft .NET Framework 4.5 could not be found. Please download and install the latest version of the .NET Framework from Microsoft's website and try again.";
                    switch (ResourceHelper.GetCurrentLanguage())
                    {
                    case Language.French: message = "Le .NET Framework 4.5 de Microsoft n'a pas été trouvé. Veuillez télécharger la plus récente version du .NET Framework à partir du site de Microsoft et essayer à nouveau."; break;

                    case Language.Japanese: message = "Microsoft .NET Framework 4.5はインストールされていないため、Mesenは起動できません。Microsoft .NET Frameworkの最新版をMicrosoftのサイトからダウンロードして、インストールしてください。"; break;

                    case Language.Russian: message = "Microsoft .NET Framework 4.5 не найден. Пожалуйста загрузите и установите последнюю версию .NET Framework с сайта Microsoft и попробуйте снова."; break;

                    case Language.Spanish: message = "Microsoft .NET Framework 4.5 no se ha encontrado. Por favor, descargue la versión más reciente de .NET Framework desde el sitio de Microsoft y vuelva a intentarlo."; break;

                    case Language.Ukrainian: message = "Microsoft .NET Framework 4.5 не знайдений. Будь ласка завантажте і встановіть останню версію .NET Framework з сайту Microsoft і спробуйте знову."; break;

                    case Language.Portuguese: message = "Microsoft .NET Framework 4.5 não foi encontrado. Por favor, baixe a versão mais recente de .NET Framework do site da Microsoft e tente novamente."; break;

                    case Language.Chinese: message = "找不到 Microsoft .NET Framework 4.5,请访问 Microsoft 官网下载安装之后再试。"; break;
                    }
                    MessageBox.Show(message + Environment.NewLine + Environment.NewLine + e.ToString(), "Mesen-S", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                } catch (Exception e) {
                    string message = "An unexpected error has occurred.\n\nError details:\n{0}";
                    switch (ResourceHelper.GetCurrentLanguage())
                    {
                    case Language.French: message = "Une erreur inattendue s'est produite.\n\nDétails de l'erreur :\n{0}"; break;

                    case Language.Japanese: message = "予期しないエラーが発生しました。\n\nエラーの詳細:\n{0}"; break;

                    case Language.Russian: message = "Неизвестная ошибка.&#xA;&#xA;Подробно:&#xA;{0}"; break;

                    case Language.Spanish: message = "Se ha producido un error inesperado.&#xA;&#xA;Detalles del error:&#xA;{0}"; break;

                    case Language.Ukrainian: message = "Невідома помилка.&#xA;&#xA;Детально:&#xA;{0}"; break;

                    case Language.Portuguese: message = "Houve um erro inesperado.&#xA;&#xA;Detalhes do erro:&#xA;{0}"; break;

                    case Language.Chinese: message = "发生意外错误。\n\n详情:\n{0}"; break;
                    }
                    MessageBox.Show(string.Format(message, e.ToString()), "Mesen-S", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                if (!RuntimeChecker.TestDll())
                {
                    return;
                }

                using (SingleInstance singleInstance = new SingleInstance()) {
                    if (singleInstance.FirstInstance || !ConfigManager.Config.Preferences.SingleInstance)
                    {
                        frmMain frmMain = new frmMain(args);

                        singleInstance.ListenForArgumentsFromSuccessiveInstances();
                        singleInstance.ArgumentsReceived += (object sender, ArgumentsReceivedEventArgs e) => {
                            if (frmMain.IsHandleCreated)
                            {
                                frmMain.BeginInvoke((MethodInvoker)(() => {
                                    new CommandLineHelper(e.Args).LoadGameFromCommandLine();
                                }));
                            }
                        };

                        Application.Run(frmMain);
                    }
                    else
                    {
                        if (singleInstance.PassArgumentsToFirstInstance(args))
                        {
                            Process current = Process.GetCurrentProcess();
                            foreach (Process process in Process.GetProcessesByName(current.ProcessName))
                            {
                                if (process.Id != current.Id)
                                {
                                    Program.SetForegroundWindow(process.MainWindowHandle);
                                    break;
                                }
                            }
                        }
                        else
                        {
                            Application.Run(new frmMain(args));
                        }
                    }
                }
            } catch (Exception e) {
                MesenMsgBox.Show("UnexpectedError", MessageBoxButtons.OK, MessageBoxIcon.Error, e.ToString());
            }
        }
Exemple #20
0
 private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
 {
     MesenMsgBox.Show("UnexpectedError", MessageBoxButtons.OK, MessageBoxIcon.Error, e.ExceptionObject.ToString());
 }
Exemple #21
0
 private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
 {
     MesenMsgBox.Show("UnexpectedError", MessageBoxButtons.OK, MessageBoxIcon.Error, e.Exception.ToString());
 }
        private static List <CheatInfo> Load(XmlDocument xml, string gameName, string gameCrc, string filepath)
        {
            try {
                List <CheatInfo> cheats = new List <CheatInfo>();

                bool validFile         = false;
                bool hasMatchingCheats = false;
                foreach (XmlNode node in xml.SelectNodes("/cheats/cheat"))
                {
                    try {
                        if (node.Attributes["game"] != null)
                        {
                            validFile = true;
                            var nodeGameName = node.Attributes["gameName"]?.Value;
                            if (nodeGameName != null && string.IsNullOrWhiteSpace(gameCrc) || node.Attributes["game"].Value.Contains(gameCrc))
                            {
                                hasMatchingCheats = true;
                                var  crc         = node.Attributes["game"].Value.Replace("0x", "").ToUpper();
                                var  genie       = node.SelectSingleNode("genie");
                                var  rocky       = node.SelectSingleNode("rocky");
                                var  description = node.SelectSingleNode("description");
                                var  address     = node.SelectSingleNode("address");
                                var  value       = node.SelectSingleNode("value");
                                var  compare     = node.SelectSingleNode("compare");
                                bool isPrgOffset = node.SelectSingleNode("isPrgOffset")?.InnerText == "true";

                                var cheat = new CheatInfo();
                                cheat.GameCrc   = crc;
                                cheat.GameName  = nodeGameName ?? gameName;
                                cheat.CheatName = description?.InnerXml;
                                cheat.Enabled   = node.Attributes["enabled"] != null && node.Attributes["enabled"].Value == "1" ? true : false;
                                if (genie != null)
                                {
                                    cheat.CheatType     = CheatType.GameGenie;
                                    cheat.GameGenieCode = genie.InnerText.ToUpper();
                                }
                                else if (rocky != null)
                                {
                                    cheat.CheatType          = CheatType.ProActionRocky;
                                    cheat.ProActionRockyCode = HexToInt(rocky.InnerText);
                                }
                                else
                                {
                                    cheat.CheatType         = CheatType.Custom;
                                    cheat.IsRelativeAddress = !isPrgOffset;
                                    cheat.Address           = HexToInt(address?.InnerText);
                                    cheat.Value             = (byte)HexToInt(value?.InnerText);
                                    if (compare != null)
                                    {
                                        cheat.CompareValue    = (byte)HexToInt(compare.InnerText);
                                        cheat.UseCompareValue = true;
                                    }
                                }

                                cheats.Add(cheat);
                            }
                        }
                    } catch { }
                }

                if (!validFile)
                {
                    //Valid xml file, but invalid content
                    MesenMsgBox.Show("InvalidCheatFile", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error, Path.GetFileName(filepath));
                    return(null);
                }
                else if (!hasMatchingCheats)
                {
                    //Valid cheat file, but no cheats match selected game
                    MesenMsgBox.Show("NoMatchingCheats", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error, Path.GetFileName(filepath));
                    return(null);
                }
                else
                {
                    return(cheats);
                }
            } catch {
                //Invalid xml file
                MesenMsgBox.Show("InvalidXmlFile", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error, Path.GetFileName(filepath));
                return(null);
            }
        }
Exemple #23
0
        public static void LoadRandomGame()
        {
            IEnumerable <string> gameFolders;
            SearchOption         searchOptions = SearchOption.TopDirectoryOnly;

            if (ConfigManager.Config.Preferences.OverrideGameFolder && Directory.Exists(ConfigManager.Config.Preferences.GameFolder))
            {
                gameFolders = new List <string>()
                {
                    ConfigManager.Config.Preferences.GameFolder
                };
                searchOptions = SearchOption.AllDirectories;
            }
            else
            {
                gameFolders = ConfigManager.Config.RecentFiles.Items.Select(recentFile => recentFile.RomFile.Folder).Distinct();
            }

            List <string> gameRoms = new List <string>();

            foreach (string folder in gameFolders)
            {
                if (Directory.Exists(folder))
                {
                    foreach (string file in Directory.EnumerateFiles(folder, "*.*", searchOptions))
                    {
                        if (FolderHelper.IsRomFile(file) || (searchOptions == SearchOption.AllDirectories && FolderHelper.IsArchiveFile(file)))
                        {
                            gameRoms.Add(file);
                        }
                    }
                }
            }

            if (gameRoms.Count == 0)
            {
                MesenMsgBox.Show("RandomGameNoGameFound", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                int    retryCount = 0;
                Random random     = new Random();
                do
                {
                    string randomGame = gameRoms[random.Next(gameRoms.Count)];
                    if (FolderHelper.IsArchiveFile(randomGame))
                    {
                        List <ArchiveRomEntry> archiveRomList = ArchiveHelper.GetArchiveRomList(randomGame);
                        if (archiveRomList.Count > 0)
                        {
                            ResourcePath res = new ResourcePath()
                            {
                                InnerFile = archiveRomList[0].Filename,
                                Path      = randomGame
                            };
                            if (!archiveRomList[0].IsUtf8)
                            {
                                res.InnerFileIndex = 1;
                            }
                            EmuRunner.LoadRom(res);
                            break;
                        }
                        else
                        {
                            retryCount++;
                        }
                    }
                    else
                    {
                        EmuRunner.LoadRom(randomGame);
                        break;
                    }
                } while(retryCount < 5);
            }
        }
        private void tmrStart_Tick(object sender, EventArgs e)
        {
            tmrStart.Stop();

            DialogResult result = DialogResult.None;

            Task.Run(() => {
                using (var client = new WebClient()) {
                    client.DownloadProgressChanged += (object s, DownloadProgressChangedEventArgs args) => {
                        this.BeginInvoke((Action)(() => {
                            lblFilename.Text = string.Format("{0} ({1:0.00}Mb)", _link, (double)args.TotalBytesToReceive / 1024 / 1024);
                            progressDownload.Value = args.ProgressPercentage;
                        }));
                    };
                    client.DownloadFileCompleted += (object s, AsyncCompletedEventArgs args) => {
                        if (!args.Cancelled && args.Error == null && File.Exists(_filename))
                        {
                            result = DialogResult.OK;
                        }
                        else if (args.Error != null)
                        {
                            MesenMsgBox.Show("UnableToDownload", MessageBoxButtons.OK, MessageBoxIcon.Error, args.Error.ToString());
                            result = DialogResult.Cancel;
                        }
                    };

                    Task downloadTask = null;
                    try {
                        downloadTask = client.DownloadFileTaskAsync(_link, _filename);
                    } catch (Exception ex) {
                        MesenMsgBox.Show("UnableToDownload", MessageBoxButtons.OK, MessageBoxIcon.Error, ex.ToString());
                        result = DialogResult.Cancel;
                    }

                    if (downloadTask == null)
                    {
                        result = DialogResult.Cancel;
                    }
                    else
                    {
                        while (!downloadTask.IsCompleted && !_cancel)
                        {
                            System.Threading.Thread.Sleep(200);
                        }

                        if (_cancel)
                        {
                            client.CancelAsync();
                        }
                        else if (result == DialogResult.None)
                        {
                            result = DialogResult.OK;
                        }
                    }
                }

                //Wait a bit for the progress bar to update to 100% (display updates are slower than the .Value updates)
                System.Threading.Thread.Sleep(500);
                this.BeginInvoke((Action)(() => {
                    DialogResult = result;
                    this.Close();
                }));
            });
        }
Exemple #25
0
        private static void Main(string[] args)
        {
            try {
                AppDomain.CurrentDomain.AssemblyResolve += LoadAssemblies;
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                Application.ThreadException += Application_ThreadException;
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

                Directory.CreateDirectory(ConfigManager.HomeFolder);
                Directory.SetCurrentDirectory(ConfigManager.HomeFolder);
                try {
                    ResourceHelper.LoadResources(ConfigManager.Config.PreferenceInfo.DisplayLanguage);
                    ResourceManager.ExtractResources();
                } catch (FileNotFoundException) {
                    string message = "The Microsoft .NET Framework 4.5 could not be found. Please download and install the latest version of the .NET Framework from Microsoft's website and try again.";
                    switch (ResourceHelper.GetCurrentLanguage())
                    {
                    case Language.French: message = "Le .NET Framework 4.5 de Microsoft n'a pas été trouvé. Veuillez télécharger la plus récente version du .NET Framework à partir du site de Microsoft et essayer à nouveau."; break;

                    case Language.Japanese: message = "Microsoft .NET Framework 4.5はインストールされていないため、Mesenは起動できません。Microsoft .NET Frameworkの最新版をMicrosoftのサイトからダウンロードして、インストールしてください。"; break;

                    case Language.Russian: message = "Microsoft .NET Framework 4.5 не найден. Пожалуйста загрузите и установите последнюю версию .NET Framework с сайта Microsoft и попробуйте снова."; break;

                    case Language.Spanish: message = "Microsoft .NET Framework 4.5 no se ha encontrado. Por favor, descargue la versión más reciente de .NET Framework desde el sitio de Microsoft y vuelva a intentarlo."; break;

                    case Language.Ukrainian: message = "Microsoft .NET Framework 4.5 не знайдений. Будь ласка завантажте і встановіть останню версію .NET Framework з сайту Microsoft і спробуйте знову."; break;
                    }
                    MessageBox.Show(message, "Mesen", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                } catch (Exception e) {
                    string message = "An unexpected error has occurred.\n\nError details:\n{0}";
                    switch (ResourceHelper.GetCurrentLanguage())
                    {
                    case Language.French: message = "Une erreur inattendue s'est produite.\n\nDétails de l'erreur :\n{0}"; break;

                    case Language.Japanese: message = "予期しないエラーが発生しました。\n\nエラーの詳細:\n{0}"; break;

                    case Language.Russian: message = "Неизвестная ошибка.&#xA;&#xA;Подробно:&#xA;{0}"; break;

                    case Language.Spanish: message = "Se ha producido un error inesperado.&#xA;&#xA;Detalles del error:&#xA;{0}"; break;

                    case Language.Ukrainian: message = "Невідома помилка.&#xA;&#xA;Детально:&#xA;{0}"; break;
                    }
                    MessageBox.Show(string.Format(message, e.ToString()), "Mesen", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                if (!RuntimeChecker.TestDll())
                {
                    return;
                }

                ResourceHelper.UpdateEmuLanguage();

                Guid guid = new Guid("{A46606B7-2D1C-4CC5-A52F-43BCAF094AED}");
                using (SingleInstance singleInstance = new SingleInstance(guid)) {
                    if (singleInstance.FirstInstance || !Config.ConfigManager.Config.PreferenceInfo.SingleInstance)
                    {
                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);

                        Mesen.GUI.Forms.frmMain frmMain = new Mesen.GUI.Forms.frmMain(args);

                        if (Config.ConfigManager.Config.PreferenceInfo.SingleInstance)
                        {
                            singleInstance.ListenForArgumentsFromSuccessiveInstances();
                            singleInstance.ArgumentsReceived += (object sender, ArgumentsReceivedEventArgs e) => {
                                frmMain.BeginInvoke((MethodInvoker)(() => {
                                    frmMain.ProcessCommandLineArguments(e.Args, false);
                                }));
                            };
                        }

                        Application.Run(frmMain);
                    }
                    else
                    {
                        if (singleInstance.PassArgumentsToFirstInstance(args))
                        {
                            Process current = Process.GetCurrentProcess();
                            foreach (Process process in Process.GetProcessesByName(current.ProcessName))
                            {
                                if (process.Id != current.Id)
                                {
                                    Program.SetForegroundWindow(process.MainWindowHandle);
                                    break;
                                }
                            }
                        }
                        else
                        {
                            Application.EnableVisualStyles();
                            Application.SetCompatibleTextRenderingDefault(false);
                            Application.Run(new Mesen.GUI.Forms.frmMain(args));
                        }
                    }
                }
            } catch (Exception e) {
                MesenMsgBox.Show("UnexpectedError", MessageBoxButtons.OK, MessageBoxIcon.Error, e.ToString());
            }
        }