Example #1
0
        public static NesMiniApplication Import(string fileName, string sourceFile = null, byte[] rawRomData = null)
        {
            var extension = Path.GetExtension(fileName).ToLower();

            if (extension == ".desktop")
            {
                return(ImportApp(fileName));
            }
            if (rawRomData == null)
            {
                rawRomData = File.ReadAllBytes(fileName);
            }
            List <Manager.EmulatorManager.Emulator> availableEmus = Manager.EmulatorManager.getInstance().ListByFileType(System.IO.Path.GetFileName(fileName));

            Manager.EmulatorManager.Emulator toUse = null;
            if (availableEmus.Count > 0)
            {
                toUse = availableEmus[0];
                NesMiniApplication app = (NesMiniApplication)UnknowSystem.Import(fileName, sourceFile, rawRomData, toUse.Prefix[0], toUse.Executable, Manager.BitmapManager.getInstance().GetBitmap(".\\images\\" + toUse.DefaultImage), toUse.SupportZip);
                // app.theRom = Manager.RomManager.getInstance().AddRom(fileName);
                return(app);
            }
            else
            {
                return(null);
            }



            //string application = extension.Length > 2 ? ("/bin/" + extension.Substring(1)) : DefaultApp;
            //return Import(fileName, sourceFile, rawRomData, DefaultPrefix, application, DefaultCover);
        }
Example #2
0
        public static NesMiniApplication CreateEmptyApp()
        {
            char   prefix = 'X';
            uint   crc32;
            string code;
            string gamePath;

            do
            {
                crc32    = (uint)new Random().Next();
                code     = GenerateCode(crc32, prefix);
                gamePath = Path.Combine(GamesDirectory, code);
            } while (Directory.Exists(gamePath));
            Directory.CreateDirectory(gamePath);
            var game = new NesMiniApplication(gamePath, true);

            game.Name      = "New app";
            game.Image     = DefaultCover;
            game.Command   = "enter some command here";
            game.SaveCount = 0;
            game.Save();

            var app = FromDirectory(gamePath);

            return(app);
        }
Example #3
0
        public static string[] GetImageUrls(NesMiniApplication app)
        {
            string query = app.Name ?? "";

            query += " " + app.GoogleSuffix + " (box|cover) art";
            var url = string.Format("https://www.google.com/search?q={0}&source=lnms&tbm=isch", HttpUtility.UrlEncode(query));

            Debug.WriteLine("Web request: " + url);
            var request = WebRequest.Create(url);

            request.Credentials = CredentialCache.DefaultCredentials;
            (request as HttpWebRequest).UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36";
            request.Timeout = 10000;
            var          response           = request.GetResponse();
            Stream       dataStream         = response.GetResponseStream();
            StreamReader reader             = new StreamReader(dataStream);
            string       responseFromServer = reader.ReadToEnd();

            reader.Close();
            response.Close();
            //Debug.WriteLine("Web response: " + responseFromServer);

            var             urls    = new List <string>();
            string          search  = @"\[""(?<url>https?:\/\/.*?\.(jpg|jpeg|png))\"",\d+,\d+\]";
            MatchCollection matches = Regex.Matches(responseFromServer, search);

            foreach (Match match in matches)
            {
                urls.Add(match.Groups["url"].Value);
            }
            return(urls.ToArray());
        }
Example #4
0
 public ImageGooglerForm(NesMiniApplication app)
 {
     InitializeComponent();
     Text         = "Google Images - " + app.Name ?? "";
     searchThread = new Thread(SearchThread);
     searchThread.Start(app);
 }
 public GameGenieCodeForm(NesMiniApplication AGame)
 {
     InitializeComponent();
     FGame = AGame;
     FGameGenieDataBase = new GameGenieDataBase(FGame);
     this.Text         += string.Format(": {0}", FGame.Name);
     LoadGameGenieCodes();
 }
Example #6
0
        private static NesMiniApplication Import(string fileName, string zFileName, byte[] rawRomData, char prefixCode, string application, Image defaultCover, bool compress = false)
        {
            var  crc32       = CRC32(rawRomData);
            var  code        = GenerateCode(crc32, prefixCode);
            var  gamePath    = Path.Combine(GamesDirectory, code);
            bool sevenZipped = false;

            if (compress)
            {
                string temp = null;
                try
                {
                    if (!File.Exists(fileName))
                    {
                        temp = Path.Combine(Path.GetTempPath(), Path.GetFileName(fileName));
                        File.WriteAllBytes(temp, rawRomData);
                        rawRomData  = Compress(temp);
                        sevenZipped = true;
                    }
                    else
                    {
                        rawRomData  = Compress(fileName);
                        sevenZipped = true;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Compression error: " + ex.Message + ex.Source);
                }
                finally
                {
                    if (!string.IsNullOrEmpty(temp) && File.Exists(temp))
                    {
                        File.Delete(temp);
                    }
                }
            }
            var romName = Regex.Replace(Path.GetFileName(fileName), @"[^A-Za-z0-9.-]", "_").Trim() + (sevenZipped ? ".7z" : "");
            var romPath = Path.Combine(gamePath, romName);

            if (Directory.Exists(gamePath))
            {
                Directory.Delete(gamePath, true);
            }
            Directory.CreateDirectory(gamePath);
            File.WriteAllBytes(romPath, rawRomData);
            var game = new NesMiniApplication(gamePath, true);

            game.Name = Path.GetFileNameWithoutExtension(fileName);
            game.Name = Regex.Replace(game.Name, @" ?\(.*?\)", string.Empty).Trim();
            game.Name = Regex.Replace(game.Name, @" ?\[.*?\]", string.Empty).Trim();
            game.Name = game.Name.Replace("_", " ").Replace("  ", " ").Trim();
            game.FindCover(fileName, zFileName, defaultCover, crc32);
            game.Command = string.Format("{0} /usr/share/games/nes/kachikachi/{1}/{2}", application, code, romName);
            game.Save();
            return(NesMiniApplication.FromDirectory(gamePath));
        }
Example #7
0
 public ImageGooglerForm(NesMiniApplication app)
 {
     InitializeComponent();
     if (!string.IsNullOrEmpty(app.Name))
     {
         Text += " - " + app.Name;
     }
     searchThread = new Thread(SearchThread);
     searchThread.Start(app);
 }
Example #8
0
        public static string[] GetImageUrls(NesMiniApplication app)
        {
            string query = app.Name ?? "";

            if (app is NesGame)
            {
                query += " nes|famicom box art";
            }
            else if (app is FdsGame)
            {
                query += " fds box art";
            }
            else
            {
                query += " game (box|cover) art";
            }
            var url = string.Format("https://www.google.com/search?q={0}&source=lnms&tbm=isch", HttpUtility.UrlEncode(query));

            Debug.WriteLine("Web request: " + url);
            var request = WebRequest.Create(url);

            request.Credentials = CredentialCache.DefaultCredentials;
            (request as HttpWebRequest).UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36";
            request.Timeout = 10000;
            var          response           = request.GetResponse();
            Stream       dataStream         = response.GetResponseStream();
            StreamReader reader             = new StreamReader(dataStream);
            string       responseFromServer = reader.ReadToEnd();

            reader.Close();
            response.Close();
            Debug.WriteLine("Web response: " + url);

            var             urls    = new List <string>();
            string          search  = @"\""ou\""\:\""(?<url>.+?)\""";
            MatchCollection matches = Regex.Matches(responseFromServer, search);

            foreach (Match match in matches)
            {
                urls.Add(HttpUtility.UrlDecode(match.Groups[1].Value.Replace("\\u00", "%")));
            }

            // For some reason Google returns different data for dirrefent users (IPs?)
            // There is alternative method
            search  = @"imgurl=(.*?)&";
            matches = Regex.Matches(responseFromServer, search);
            foreach (Match match in matches)
            {
                // Not sure about it.
                urls.Add(HttpUtility.UrlDecode(match.Groups[1].Value.Replace("\\u00", "%")));
            }

            return(urls.ToArray());
        }
Example #9
0
        private void ShowSelected()
        {
            var node = treeView.SelectedNode;

            listViewContent.Clear();
            if (node != null && (node.Nodes.Count > 0 || node.Tag is NesMenuFolder)) // Folder or root
            {
                pictureBoxArt.Image        = (node.Tag is NesMenuFolder) ? (node.Tag as NesMenuFolder).Image : null;
                groupBoxArt.Enabled        = (node.Tag is NesMenuFolder);
                groupBoxSplitModes.Enabled = true;
                pictureBoxArt.Cursor       = Cursors.Hand;
                listViewContent.Enabled    = true;
                foreach (TreeNode n in node.Nodes)
                {
                    var element = (INesMenuElement)n.Tag;
                    var item    = new ListViewItem();
                    item.Text = element.Name;
                    var transparency = cuttedNodes.Contains(n) ? 1 : 0;
                    if (element is NesMenuFolder)
                    {
                        item.ImageIndex = 0 + transparency;
                    }
                    else if (element is NesMiniApplication)
                    {
                        item.ImageIndex = 2 + transparency;
                    }
                    else if (element is NesDefaultGame)
                    {
                        item.ImageIndex = 4 + transparency;
                    }
                    item.Tag = n;
                    listViewContent.Items.Add(item);
                }
            }
            else
            {
                if (node != null && node.Tag is NesMiniApplication)
                {
                    var game = node.Tag as NesMiniApplication;
                    pictureBoxArt.Image     = NesMiniApplication.LoadBitmap(game.IconPath);
                    groupBoxArt.Enabled     = true;
                    listViewContent.Enabled = false;
                }
                else //if (e.Node.Tag is NesDefaultGame)
                {
                    pictureBoxArt.Image = null;
                    groupBoxArt.Enabled = false;
                }
                listViewContent.Enabled    = false;
                groupBoxSplitModes.Enabled = false;
                pictureBoxArt.Cursor       = Cursors.Default;
            }
            ShowFolderStats();
        }
Example #10
0
 public GameGenieDataBase(NesMiniApplication AGame)
 {
     DataBasePath = Path.Combine(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "data"), "GameGenieDB.xml");
     FGame        = AGame;
     FDBName      = DataBasePath;
     if (File.Exists(FDBName))
     {
         FXml.Load(FDBName);
     }
     else
     {
         FXml.AppendChild(FXml.CreateElement("database"));
     }
 }
Example #11
0
        private void buttonOk_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBoxCode.Text.Trim()))
            {
                MessageBox.Show(this, Resources.GGCodeEmpty, Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (FGame != null)
            {
                var tmpPath = Path.Combine(Path.GetTempPath(), FGame.Code);
                try
                {
                    FGame.CopyTo(tmpPath);
                    var lGame = NesMiniApplication.FromDirectory(tmpPath);
                    (lGame as NesMiniApplication).GameGenie = textBoxCode.Text;
                    lGame.Save();
                    (lGame as ISupportsGameGenie).ApplyGameGenie();
                }
                catch (GameGenieFormatException)
                {
                    MessageBox.Show(this, string.Format(Resources.GameGenieFormatError, textBoxCode.Text, FGame.Name), Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                catch (GameGenieNotFoundException)
                {
                    MessageBox.Show(this, string.Format(Resources.GameGenieNotFound, textBoxCode.Text, FGame.Name), Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                finally
                {
                    if (Directory.Exists(tmpPath))
                    {
                        Directory.Delete(tmpPath, true);
                    }
                }
            }

            if (string.IsNullOrEmpty(textBoxDescription.Text.Trim()))
            {
                MessageBox.Show(this, Resources.GGDescriptionEmpty, Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            textBoxCode.Text = textBoxCode.Text.ToUpper().Trim();
            DialogResult     = System.Windows.Forms.DialogResult.OK;
        }
Example #12
0
 public GameGenieDataBase(NesMiniApplication AGame)
 {
     //DataBasePath = Path.Combine(Path.Combine(Program.BaseDirectoryInternal, "data"), "GameGenieDB.xml");
     FGame = AGame;
     //FDBName = DataBasePath;
     if (File.Exists(userDatabasePath))
     {
         FXml.Load(userDatabasePath);
     }
     else if (File.Exists(originalDatabasePath))
     {
         FXml.Load(originalDatabasePath);
     }
     else
     {
         FXml.AppendChild(FXml.CreateElement("database"));
     }
 }
Example #13
0
        public static NesMiniApplication Import(string inputFileName, string originalFileName = null, byte[] rawRomData = null)
        {
            var extension = System.IO.Path.GetExtension(inputFileName).ToLower();

            if (extension == ".desktop")
            {
                return(ImportApp(inputFileName));
            }
            if (rawRomData == null)                            // Maybe it's already extracted data?
            {
                rawRomData = File.ReadAllBytes(inputFileName); // If not, reading file
            }
            if (originalFileName == null)                      // Original file name from archive
            {
                originalFileName = System.IO.Path.GetFileName(inputFileName);
            }
            char   prefix         = DefaultPrefix;
            string application    = extension.Length > 2 ? ("/bin/" + extension.Substring(1)) : DefaultApp;
            string args           = null;
            Image  cover          = DefaultCover;
            uint   crc32          = CRC32(rawRomData);
            string outputFileName = Regex.Replace(System.IO.Path.GetFileName(inputFileName), @"[^A-Za-z0-9()!\[\]\.\-]", "_").Trim();

            // Trying to determine file type
            var  appinfo = AppTypeCollection.GetAppByExtension(extension);
            bool patched = false;

            if (appinfo != null)
            {
                if (appinfo.DefaultApps.Length > 0)
                {
                    application = appinfo.DefaultApps[0];
                }
                prefix = appinfo.Prefix;
                cover  = appinfo.DefaultCover;
                var patch = appinfo.Class.GetMethod("Patch");
                if (patch != null)
                {
                    object[] values = new object[] { inputFileName, rawRomData, prefix, application, outputFileName, args, cover, crc32 };
                    var      result = (bool)patch.Invoke(null, values);
                    if (!result)
                    {
                        return(null);
                    }
                    rawRomData     = (byte[])values[1];
                    prefix         = (char)values[2];
                    application    = (string)values[3];
                    outputFileName = (string)values[4];
                    args           = (string)values[5];
                    cover          = (Image)values[6];
                    crc32          = (uint)values[7];
                    patched        = true;
                }
            }

            if (!patched)
            {
                FindPatch(ref rawRomData, inputFileName, crc32);
            }

            var code     = GenerateCode(crc32, prefix);
            var gamePath = Path.Combine(GamesDirectory, code);
            var romPath  = Path.Combine(gamePath, outputFileName);

            if (Directory.Exists(gamePath))
            {
                var files = Directory.GetFiles(gamePath, "*.*", SearchOption.AllDirectories);
                foreach (var f in files)
                {
                    try
                    {
                        File.Delete(f);
                    }
                    catch { }
                }
            }
            Directory.CreateDirectory(gamePath);
            File.WriteAllBytes(romPath, rawRomData);
            var game = new NesMiniApplication(gamePath, true);

            game.Name    = System.IO.Path.GetFileNameWithoutExtension(inputFileName);
            game.Name    = Regex.Replace(game.Name, @" ?\(.*?\)", string.Empty).Trim();
            game.Name    = Regex.Replace(game.Name, @" ?\[.*?\]", string.Empty).Trim();
            game.Name    = game.Name.Replace("_", " ").Replace("  ", " ").Trim();
            game.Command = $"{application} {GamesCloverPath}/{code}/{outputFileName}";
            if (!string.IsNullOrEmpty(args))
            {
                game.Command += " " + args;
            }
            game.FindCover(inputFileName, cover, crc32);
            game.Save();

            var app = NesMiniApplication.FromDirectory(gamePath);

            if (app is ICloverAutofill)
            {
                (app as ICloverAutofill).TryAutofill(crc32);
            }

            if (ConfigIni.Compress)
            {
                app.Compress();
            }

            return(app);
        }
Example #14
0
        private byte[] CreatePatchedKernel(GamesTreeStats stats = null)
        {
            if (stats == null)
            {
                stats = new GamesTreeStats();
            }
            bool first   = stats.GamesProceed == 0;
            bool partial = stats.GamesProceed > 0;

            SetStatus(Resources.BuildingCustom);
            if (first)
            {
                if (Directory.Exists(tempDirectory))
                {
                    Directory.Delete(tempDirectory, true);
                }
                Directory.CreateDirectory(tempDirectory);
                Directory.CreateDirectory(kernelDirectory);
                Directory.CreateDirectory(ramfsDirectory);
                if (!ExecuteTool("unpackbootimg.exe", string.Format("-i \"{0}\" -o \"{1}\"", KernelDump, kernelDirectory)))
                {
                    throw new Exception("Can't unpack kernel image");
                }
                if (!ExecuteTool("lzop.exe", string.Format("-d \"{0}\" -o \"{1}\"",
                                                           Path.Combine(kernelDirectory, "kernel.img-ramdisk.gz"), initramfs_cpio)))
                {
                    throw new Exception("Can't unpack ramdisk");
                }
                ExecuteTool("cpio.exe", string.Format("-imd --no-preserve-owner --quiet -I \"{0}\"",
                                                      @"..\initramfs.cpio"), ramfsDirectory);
                if (!File.Exists(Path.Combine(ramfsDirectory, "init"))) // cpio.exe fails on Windows XP for some reason. But working!
                {
                    throw new Exception("Can't unpack ramdisk 2");
                }
                if (Directory.Exists(hakchiDirectory))
                {
                    Directory.Delete(hakchiDirectory, true);
                }
                NesMiniApplication.DirectoryCopy(Path.Combine(modsDirectory, Mod), ramfsDirectory, true);
                var ramfsFiles = Directory.GetFiles(ramfsDirectory, "*.*", SearchOption.AllDirectories);
                foreach (var file in ramfsFiles)
                {
                    var fInfo = new FileInfo(file);
                    if (fInfo.Length > 10 && fInfo.Length < 100 && ((fInfo.Attributes & FileAttributes.System) == 0) &&
                        (Encoding.ASCII.GetString(File.ReadAllBytes(file), 0, 10)) == "!<symlink>")
                    {
                        fInfo.Attributes |= FileAttributes.System;
                    }
                }
            }

            if (!first && Directory.Exists(transferDirectory))
            {
                Debug.WriteLine("Clearing transfer directory");
                Directory.Delete(transferDirectory, true);
            }

            // Games!
            if (Games != null)
            {
                Directory.CreateDirectory(tempGamesDirectory);
                if (first)
                {
                    File.WriteAllBytes(Path.Combine(tempGamesDirectory, "clear"), new byte[0]);
                    Directory.CreateDirectory(originalGamesConfigDirectory);
                    if (HiddenGames != null && HiddenGames.Length > 0)
                    {
                        StringBuilder h = new StringBuilder();
                        foreach (var game in HiddenGames)
                        {
                            h.Append(game + "\n");
                        }
                        File.WriteAllText(hiddenPath, h.ToString());
                    }
                }

                stats.Next();
                AddMenu(Games, stats);
                Debug.WriteLine(string.Format("Games copied: {0}/{1}, part size: {2}", stats.GamesProceed, stats.GamesTotal, stats.Size));
            }

            bool last = stats.GamesProceed >= stats.GamesTotal;

            if (last && hmodsInstall != null && hmodsInstall.Count > 0)
            {
                Directory.CreateDirectory(tempHmodsDirectory);
                foreach (var hmod in hmodsInstall)
                {
                    var modName = hmod + ".hmod";
                    foreach (var dir in hmodDirectories)
                    {
                        if (Directory.Exists(Path.Combine(dir, modName)))
                        {
                            NesMiniApplication.DirectoryCopy(Path.Combine(dir, modName), Path.Combine(tempHmodsDirectory, modName), true);
                            break;
                        }
                        if (File.Exists(Path.Combine(dir, modName)))
                        {
                            File.Copy(Path.Combine(dir, modName), Path.Combine(tempHmodsDirectory, modName));
                            break;
                        }
                    }
                }
            }
            if (last && hmodsUninstall != null && hmodsUninstall.Count > 0)
            {
                Directory.CreateDirectory(tempHmodsDirectory);
                var mods = new StringBuilder();
                foreach (var hmod in hmodsUninstall)
                {
                    mods.AppendFormat("{0}.hmod\n", hmod);
                }
                File.WriteAllText(Path.Combine(tempHmodsDirectory, "uninstall"), mods.ToString());
            }

            // Writing config
            if (Config != null && Config.Count > 0)
            {
                Directory.CreateDirectory(transferDirectory);
                var config = new StringBuilder();
                foreach (var key in Config.Keys)
                {
                    config.AppendFormat("cfg_{0}='{1}'\n", key, Config[key].Replace(@"'", @"\'"));
                }
                File.WriteAllText(configPath, config.ToString());
            }

            // Building image
            if (first && Games != null && Games.Count > 0) // There is no reason to compress cryptsetup when we do not uploading games
            {
                ExecuteTool("upx.exe", "--best sbin\\cryptsetup", ramfsDirectory);
            }
            byte[] ramdisk;
            if (!ExecuteTool("mkbootfs.exe", string.Format("\"{0}\"", ramfsDirectory), out ramdisk))
            {
                throw new Exception("Can't repack ramdisk");
            }
            File.WriteAllBytes(initramfs_cpioPatched, ramdisk);
            var argCmdline    = File.ReadAllText(Path.Combine(kernelDirectory, "kernel.img-cmdline")).Trim();
            var argBoard      = File.ReadAllText(Path.Combine(kernelDirectory, "kernel.img-board")).Trim();
            var argBase       = File.ReadAllText(Path.Combine(kernelDirectory, "kernel.img-base")).Trim();
            var argPagesize   = File.ReadAllText(Path.Combine(kernelDirectory, "kernel.img-pagesize")).Trim();
            var argKerneloff  = File.ReadAllText(Path.Combine(kernelDirectory, "kernel.img-kerneloff")).Trim();
            var argRamdiscoff = File.ReadAllText(Path.Combine(kernelDirectory, "kernel.img-ramdiskoff")).Trim();
            var argTagsoff    = File.ReadAllText(Path.Combine(kernelDirectory, "kernel.img-tagsoff")).Trim();

            if (!ExecuteTool("lzop.exe", string.Format("--best -f -o \"{0}\" \"{1}\"",
                                                       ramdiskPatched, initramfs_cpioPatched)))
            {
                throw new Exception("Can't repack ramdisk 2");
            }
            if (!ExecuteTool("mkbootimg.exe", string.Format("--kernel \"{0}\" --ramdisk \"{1}\" --cmdline \"{2}\" --board \"{3}\" --base \"{4}\" --pagesize \"{5}\" --kernel_offset \"{6}\" --ramdisk_offset \"{7}\" --tags_offset \"{8}\" -o \"{9}\"",
                                                            Path.Combine(kernelDirectory, "kernel.img-zImage"), ramdiskPatched, argCmdline, argBoard, argBase, argPagesize, argKerneloff, argRamdiscoff, argTagsoff, kernelPatched)))
            {
                throw new Exception("Can't rebuild kernel");
            }

            var result = File.ReadAllBytes(kernelPatched);

#if !DEBUG
            if (last)
            {
                Directory.Delete(tempDirectory, true);
            }
#endif
            if (result.Length > Fel.kernel_max_size)
            {
                throw new Exception("Kernel is too big");
            }
            GC.Collect();
            return(result);
        }
Example #15
0
        private byte[] CreatePatchedKernel()
        {
            SetStatus(Resources.BuildingCustom);
            if (Directory.Exists(tempDirectory))
            {
                Directory.Delete(tempDirectory, true);
            }
            Directory.CreateDirectory(tempDirectory);
            Directory.CreateDirectory(kernelDirectory);
            Directory.CreateDirectory(ramfsDirectory);
            if (!ExecuteTool("unpackbootimg.exe", string.Format("-i \"{0}\" -o \"{1}\"", KernelDump, kernelDirectory)))
            {
                throw new Exception("Can't unpack kernel image");
            }
            if (!ExecuteTool("lzop.exe", string.Format("-d \"{0}\" -o \"{1}\"",
                                                       Path.Combine(kernelDirectory, "kernel.img-ramdisk.gz"), initramfs_cpio)))
            {
                throw new Exception("Can't unpack ramdisk");
            }
            ExecuteTool("cpio.exe", string.Format("-imd --no-preserve-owner --quiet -I \"{0}\"",
                                                  @"..\initramfs.cpio"), ramfsDirectory);
            if (!File.Exists(Path.Combine(ramfsDirectory, "init"))) // cpio.exe fails on Windows XP for some reason. But working!
            {
                throw new Exception("Can't unpack ramdisk 2");
            }
            if (Directory.Exists(hakchiDirectory))
            {
                Directory.Delete(hakchiDirectory, true);
            }
            NesMiniApplication.DirectoryCopy(Path.Combine(modsDirectory, Mod), ramfsDirectory, true);
            var ramfsFiles = Directory.GetFiles(ramfsDirectory, "*.*", SearchOption.AllDirectories);

            foreach (var file in ramfsFiles)
            {
                var fInfo = new FileInfo(file);
                if (fInfo.Length > 10 && fInfo.Length < 100 && ((fInfo.Attributes & FileAttributes.System) == 0) &&
                    (Encoding.ASCII.GetString(File.ReadAllBytes(file), 0, 10)) == "!<symlink>")
                {
                    fInfo.Attributes |= FileAttributes.System;
                }
            }

            if (hmodsInstall != null && hmodsInstall.Count() > 0)
            {
                Directory.CreateDirectory(tempHmodsDirectory);
                foreach (var hmod in hmodsInstall)
                {
                    var modName = hmod + ".hmod";
                    foreach (var dir in hmodDirectories)
                    {
                        if (Directory.Exists(Path.Combine(dir, modName)))
                        {
                            NesMiniApplication.DirectoryCopy(Path.Combine(dir, modName), Path.Combine(tempHmodsDirectory, modName), true);
                            break;
                        }
                        if (File.Exists(Path.Combine(dir, modName)))
                        {
                            File.Copy(Path.Combine(dir, modName), Path.Combine(tempHmodsDirectory, modName));
                            break;
                        }
                    }
                }
            }
            if (hmodsUninstall != null && hmodsUninstall.Count() > 0)
            {
                Directory.CreateDirectory(tempHmodsDirectory);
                var mods = new StringBuilder();
                foreach (var hmod in hmodsUninstall)
                {
                    mods.AppendFormat("{0}.hmod\n", hmod);
                }
                File.WriteAllText(Path.Combine(tempHmodsDirectory, "uninstall"), mods.ToString());
            }

            // Building image
            byte[] ramdisk;
            if (!ExecuteTool("mkbootfs.exe", string.Format("\"{0}\"", ramfsDirectory), out ramdisk))
            {
                throw new Exception("Can't repack ramdisk");
            }
            File.WriteAllBytes(initramfs_cpioPatched, ramdisk);
            var argCmdline    = File.ReadAllText(Path.Combine(kernelDirectory, "kernel.img-cmdline")).Trim();
            var argBoard      = File.ReadAllText(Path.Combine(kernelDirectory, "kernel.img-board")).Trim();
            var argBase       = File.ReadAllText(Path.Combine(kernelDirectory, "kernel.img-base")).Trim();
            var argPagesize   = File.ReadAllText(Path.Combine(kernelDirectory, "kernel.img-pagesize")).Trim();
            var argKerneloff  = File.ReadAllText(Path.Combine(kernelDirectory, "kernel.img-kerneloff")).Trim();
            var argRamdiscoff = File.ReadAllText(Path.Combine(kernelDirectory, "kernel.img-ramdiskoff")).Trim();
            var argTagsoff    = File.ReadAllText(Path.Combine(kernelDirectory, "kernel.img-tagsoff")).Trim();

            if (!ExecuteTool("lzop.exe", string.Format("--best -f -o \"{0}\" \"{1}\"",
                                                       ramdiskPatched, initramfs_cpioPatched)))
            {
                throw new Exception("Can't repack ramdisk 2");
            }
            if (!ExecuteTool("mkbootimg.exe", string.Format("--kernel \"{0}\" --ramdisk \"{1}\" --cmdline \"{2}\" --board \"{3}\" --base \"{4}\" --pagesize \"{5}\" --kernel_offset \"{6}\" --ramdisk_offset \"{7}\" --tags_offset \"{8}\" -o \"{9}\"",
                                                            Path.Combine(kernelDirectory, "kernel.img-zImage"), ramdiskPatched, argCmdline, argBoard, argBase, argPagesize, argKerneloff, argRamdiscoff, argTagsoff, kernelPatched)))
            {
                throw new Exception("Can't rebuild kernel");
            }

            var result = File.ReadAllBytes(kernelPatched);

#if !DEBUG
            Directory.Delete(tempDirectory, true);
#endif
            return(result);
        }
Example #16
0
        public static NesMiniApplication Import(string fileName, byte[] rawRomData = null)
        {
            var    extension = Path.GetExtension(fileName).ToLower();
            char   prefixCode;
            string application;
            Image  defaultCover = Resources.blank_app;

            switch (extension)
            {
            // For some unusual NES ROM formats
            case ".fds":
                return(FdsGame.ImportFds(fileName, rawRomData));

            case ".nes":
            case ".unf":
            case ".unif":
                prefixCode   = NesUGame.Prefix;
                application  = NesUGame.DefaultApp;
                defaultCover = NesUGame.DefaultCover;     // Most of UNIF roms are pirated Famicom games
                break;

            case ".desktop":
                return(ImportApp(fileName));

            case ".gb":
                prefixCode   = GbGame.Prefix;
                application  = GbGame.DefaultApp;
                defaultCover = GbGame.DefaultCover;
                break;

            case ".gbc":
                prefixCode   = GbcGame.Prefix;
                application  = GbcGame.DefaultApp;
                defaultCover = GbcGame.DefaultCover;
                break;

            case ".gba":
                prefixCode   = GbaGame.Prefix;
                application  = GbaGame.DefaultApp;
                defaultCover = GbaGame.DefaultCover;
                break;

            case ".n64":
            case ".z64":
            case ".v64":
                prefixCode   = N64Game.Prefix;
                application  = N64Game.DefaultApp;
                defaultCover = N64Game.DefaultCover;
                break;

            case ".sfc":
            case ".smc":
                prefixCode   = SnesGame.Prefix;
                application  = SnesGame.DefaultApp;
                defaultCover = SnesGame.DefaultCover;
                break;

            case ".gen":
            case ".md":
            case ".smd":
                prefixCode   = GenesisGame.Prefix;
                application  = GenesisGame.DefaultApp;
                defaultCover = GenesisGame.DefaultCover;
                break;

            case ".sms":
                prefixCode   = SmsGame.Prefix;
                application  = SmsGame.DefaultApp;
                defaultCover = SmsGame.DefaultCover;
                break;

            case ".pce":
                prefixCode   = PceGame.Prefix;
                application  = PceGame.DefaultApp;
                defaultCover = PceGame.DefaultCover;
                break;

            default:
                prefixCode = Prefix;
                if (extension.Length > 1)
                {
                    application = string.Format("/bin/{0}", extension.Substring(1));
                }
                else
                {
                    application = DefaultApp;
                }
                defaultCover = DefaultCover;
                break;
            }
            if (rawRomData == null)
            {
                rawRomData = File.ReadAllBytes(fileName);
            }
            var crc32    = CRC32(rawRomData);
            var code     = GenerateCode(crc32, prefixCode);
            var gamePath = Path.Combine(GamesDirectory, code);
            var romName  = Regex.Replace(Path.GetFileName(fileName), @"[^A-Za-z0-9.-]", "_").Trim();
            var romPath  = Path.Combine(gamePath, romName);

            Directory.CreateDirectory(gamePath);
            File.WriteAllBytes(romPath, rawRomData);
            var game = new NesMiniApplication(gamePath, true);

            game.Name = Path.GetFileNameWithoutExtension(fileName);
            game.Name = Regex.Replace(game.Name, @" ?\(.*?\)", string.Empty).Trim();
            game.Name = Regex.Replace(game.Name, @" ?\[.*?\]", string.Empty).Trim();
            game.Name = game.Name.Replace("_", " ").Replace("  ", " ").Trim();
            game.FindCover(fileName, defaultCover, crc32);
            game.Command = string.Format("{0} /usr/share/games/nes/kachikachi/{1}/{2}", application, code, romName);
            game.Save();
            return(NesMiniApplication.FromDirectory(gamePath));
        }
Example #17
0
        public static NesMiniApplication Import(string fileName, byte[] rawRomData = null)
        {
            var    extension = Path.GetExtension(fileName).ToLower();
            char   prefixCode;
            string application;

            switch (extension)
            {
            // For some unusual NES ROM formats
            case ".fds":
                return(FdsGame.Import(fileName, rawRomData));

            case ".nes":
            case ".unf":
            case ".unif":
                prefixCode  = 'U';
                application = "/bin/nes";
                break;

            case ".desktop":
                return(ImportApp(fileName));

            case ".gb":
            case ".gbc":
                prefixCode  = 'C';
                application = "/bin/gb";
                break;

            case ".gba":
                prefixCode  = 'A';
                application = "/bin/gba";
                break;

            case ".n64":
            case ".z64":
            case ".v64":
                prefixCode  = 'F';
                application = "/bin/n64";
                break;

            case ".smc":
                prefixCode  = 'E';
                application = "/bin/snes";
                break;

            case ".gen":
            case ".smd":
                prefixCode  = 'G';
                application = "/bin/md";
                break;

            case ".sms":
                prefixCode  = 'M';
                application = "/bin/sms";
                break;

            default:
                prefixCode  = 'Z';
                application = "/bin/path-to-your-app";
                break;
            }
            if (rawRomData == null)
            {
                rawRomData = File.ReadAllBytes(fileName);
            }
            var crc32    = CRC32(rawRomData);
            var code     = GenerateCode(crc32, prefixCode);
            var gamePath = Path.Combine(GamesDirectory, code);
            var romName  = Path.GetFileName(fileName).Replace(" ", "_");
            var romPath  = Path.Combine(gamePath, romName);

            Directory.CreateDirectory(gamePath);
            File.WriteAllBytes(romPath, rawRomData);
            var game = new NesMiniApplication(gamePath, true);

            game.Name = Path.GetFileNameWithoutExtension(fileName);
            game.Name = Regex.Replace(game.Name, @" ?\(.*?\)", string.Empty).Trim();
            game.Name = Regex.Replace(game.Name, @" ?\[.*?\]", string.Empty).Trim();
            game.Name = game.Name.Replace("_", " ").Replace("  ", " ").Trim();
            game.FindCover(fileName, Resources.blank, crc32);
            game.Command = string.Format("{0} /usr/share/games/nes/kachikachi/{1}/{2}", application, code, romName);
            game.Save();
            return(game);
        }
Example #18
0
 public GameGenieCodeAddModForm(NesMiniApplication game)
 {
     InitializeComponent();
     FGame = game;
 }
Example #19
0
        public static NesMiniApplication ImportNes(string nesFileName, bool?ignoreMapper, ref bool?needPatch, NeedPatchDelegate needPatchCallback = null, Form parentForm = null, byte[] rawRomData = null)
        {
            NesFile nesFile;

            try
            {
                if (rawRomData != null)
                {
                    nesFile = new NesFile(rawRomData);
                }
                else
                {
                    nesFile = new NesFile(nesFileName);
                }
            }
            catch
            {
                return(NesMiniApplication.Import(nesFileName, rawRomData));
            }
            nesFile.CorrectRom();
            var crc32            = nesFile.CRC32;
            var code             = GenerateCode(crc32, Prefix);
            var gamePath         = Path.Combine(GamesDirectory, code);
            var nesPath          = Path.Combine(gamePath, code + ".nes");
            var patchesDirectory = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "patches");

            Directory.CreateDirectory(patchesDirectory);
            Directory.CreateDirectory(gamePath);
            var patches = Directory.GetFiles(patchesDirectory, string.Format("{0:X8}*.ips", crc32), SearchOption.AllDirectories);

            if (patches.Length > 0 && needPatch != false)
            {
                if (needPatch == true || ((needPatchCallback != null) && needPatchCallback(parentForm, Path.GetFileName(nesFileName))))
                {
                    needPatch = true;
                    var patch = patches[0];
                    if (rawRomData == null)
                    {
                        rawRomData = File.ReadAllBytes(nesFileName);
                    }
                    Debug.WriteLine(string.Format("Patching {0}", nesFileName));
                    IpsPatcher.Patch(patch, ref rawRomData);
                    nesFile = new NesFile(rawRomData);
                }
                else
                {
                    needPatch = false;
                }
            }

            if (nesFile.Mapper == 71)
            {
                nesFile.Mapper = 2;                       // games by Codemasters/Camerica - this is UNROM clone. One exception - Fire Hawk
            }
            if (nesFile.Mapper == 88)
            {
                nesFile.Mapper = 4;                       // Compatible with MMC3... sometimes
            }
            if (nesFile.Mapper == 95)
            {
                nesFile.Mapper = 4;                       // Compatible with MMC3
            }
            if (nesFile.Mapper == 206)
            {
                nesFile.Mapper = 4;                        // Compatible with MMC3
            }
            if (!supportedMappers.Contains(nesFile.Mapper) && (ignoreMapper != true))
            {
                Directory.Delete(gamePath, true);
                if (ignoreMapper != false)
                {
                    throw new UnsupportedMapperException(nesFile);
                }
                else
                {
                    Debug.WriteLine(string.Format("Game {0} has mapper #{1}, skipped", nesFileName, nesFile.Mapper));
                    return(null);
                }
            }
            if ((nesFile.Mirroring == NesFile.MirroringType.FourScreenVram) && (ignoreMapper != true))
            {
                Directory.Delete(gamePath, true);
                if (ignoreMapper != false)
                {
                    throw new UnsupportedFourScreenException(nesFile);
                }
                else
                {
                    Debug.WriteLine(string.Format("Game {0} has four-screen mirroring, skipped", nesFileName, nesFile.Mapper));
                    return(null);
                }
            }
            // TODO: Make trainer check. I think that the NES Mini doesn't support it.

            nesFile.Save(nesPath);
            var game = new NesGame(gamePath, true);

            game.Name = Path.GetFileNameWithoutExtension(nesFileName);
            if (game.Name.Contains("(J)"))
            {
                game.region = "Japan";
            }
            game.TryAutofill(crc32);
            game.Name = Regex.Replace(game.Name, @" ?\(.*?\)", string.Empty).Trim();
            game.Name = Regex.Replace(game.Name, @" ?\[.*?\]", string.Empty).Trim();
            game.Name = game.Name.Replace("_", " ").Replace("  ", " ");
            game.FindCover(nesFileName, (game.region == "Japan") ? Resources.blank_jp : Resources.blank_nes, crc32);
            game.Args = DefaultArgs;
            game.Save();
            return(game);
        }
Example #20
0
        public ICollection <NesMiniApplication> AddGames(string[] files, Form parentForm = null)
        {
            var apps = new List <NesMiniApplication>();

            addedApplications = null;
            //bool NoForAllUnsupportedMappers = false;
            bool YesForAllUnsupportedMappers = false;

            YesForAllPatches = false;
            int count = 0;

            SetStatus(Resources.AddingGames);
            foreach (var file in files)
            {
                NesMiniApplication app = null;
                try
                {
                    var    fileName  = file;
                    var    ext       = Path.GetExtension(file).ToLower();
                    bool?  needPatch = YesForAllPatches ? (bool?)true : null;
                    byte[] rawData   = null;
                    if (ext == ".7z" || ext == ".zip" || ext == ".rar")
                    {
                        SevenZipExtractor.SetLibraryPath(Path.Combine(baseDirectory, IntPtr.Size == 8 ? @"tools\7z64.dll" : @"tools\7z.dll"));
                        using (var szExtractor = new SevenZipExtractor(file))
                        {
                            var filesInArchive    = new List <string>();
                            var nesFilesInArchive = new List <string>();
                            foreach (var f in szExtractor.ArchiveFileNames)
                            {
                                var e = Path.GetExtension(f).ToLower();
                                if (e == ".nes" || e == ".fds" || e == ".unf" || e == ".unif")
                                {
                                    nesFilesInArchive.Add(f);
                                }
                                filesInArchive.Add(f);
                            }
                            if (nesFilesInArchive.Count == 1) // Only one NES file
                            {
                                fileName = nesFilesInArchive[0];
                            }
                            else if (nesFilesInArchive.Count > 1) // Many NES files, need to select
                            {
                                if (SelectFileFromThread(nesFilesInArchive.ToArray()) == DialogResult.OK)
                                {
                                    fileName = selectedFile;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            else if (filesInArchive.Count == 1) // No NES files but only one another file
                            {
                                fileName = filesInArchive[0];
                            }
                            else // Need to select
                            {
                                if (SelectFileFromThread(filesInArchive.ToArray()) == DialogResult.OK)
                                {
                                    fileName = selectedFile;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            var o = new MemoryStream();
                            szExtractor.ExtractFile(fileName, o);
                            rawData = new byte[o.Length];
                            o.Seek(0, SeekOrigin.Begin);
                            o.Read(rawData, 0, (int)o.Length);
                        }
                    }
                    if (Path.GetExtension(fileName).ToLower() == ".nes")
                    {
                        try
                        {
                            app = NesGame.Import(fileName, YesForAllUnsupportedMappers ? (bool?)true : null, ref needPatch, needPatchCallback, this, rawData);

                            // Trying to import Game Genie codes
                            var lGameGeniePath = Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName) + ".xml");
                            if (File.Exists(lGameGeniePath))
                            {
                                GameGenieDataBase lGameGenieDataBase = new GameGenieDataBase(app);
                                lGameGenieDataBase.ImportCodes(lGameGeniePath, true);
                                lGameGenieDataBase.Save();
                            }
                        }
                        catch (Exception ex)
                        {
                            if (ex is UnsupportedMapperException || ex is UnsupportedFourScreenException)
                            {
                                var r = MessageBoxFromThread(this,
                                                             (ex is UnsupportedMapperException)
                                       ? string.Format(Resources.MapperNotSupported, Path.GetFileName(fileName), (ex as UnsupportedMapperException).ROM.Mapper)
                                       : string.Format(Resources.FourScreenNotSupported, Path.GetFileName(fileName)),
                                                             Resources.AreYouSure,
                                                             files.Length <= 1 ? MessageBoxButtons.YesNo : MessageBoxButtons.AbortRetryIgnore,
                                                             MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2, true);
                                while (r == DialogResult.None)
                                {
                                    Thread.Sleep(100);
                                }
                                if (r == DialogResult.Yes || r == DialogResult.Abort || r == DialogResult.Retry)
                                {
                                    app = NesGame.Import(fileName, true, ref needPatch, needPatchCallback, this, rawData);
                                }
                                if (r == DialogResult.Abort)
                                {
                                    YesForAllUnsupportedMappers = true;
                                }
                            }
                            else
                            {
                                throw ex;
                            }
                        }
                    }
                    else
                    {
                        app = NesMiniApplication.Import(fileName, rawData);
                    }
                    ConfigIni.SelectedGames += ";" + app.Code;
                }
                catch (Exception ex)
                {
                    if (ex is ThreadAbortException)
                    {
                        return(null);
                    }
                    Debug.WriteLine(ex.Message + ex.StackTrace);
                    ShowError(ex, true);
                }
                if (app != null)
                {
                    apps.Add(app);
                }
                SetProgress(++count, files.Length);
            }
            return(apps); // Added games/apps
        }