Ejemplo n.º 1
0
        public static string[] GetImageUrls(NesApplication app)
        {
            string query = app.Name ?? "";

            query += " " + app.Metadata.AppInfo.GoogleSuffix + " (box|cover) art";
            return(ImageGoogler.GetImageUrls(query));
        }
Ejemplo n.º 2
0
 public GameGenieCodeForm(NesApplication AGame)
 {
     InitializeComponent();
     FGame = AGame;
     FGameGenieDataBase = new GameGenieDataBase(FGame);
     this.Text         += string.Format(": {0}", FGame.Name);
     LoadGameGenieCodes();
 }
Ejemplo n.º 3
0
 public ImageGooglerForm(NesApplication app)
 {
     InitializeComponent();
     if (!string.IsNullOrEmpty(app.Name))
     {
         Text += " - " + app.Name;
     }
     searchThread = new Thread(SearchThread);
     searchThread.Start(app);
 }
Ejemplo n.º 4
0
 private void textBox1_TextChanged(object sender, EventArgs e)
 {
     if (checkBox1.Checked)
     {
         if (textBox1.Text.Length > 0)
         {
             uint crc32 = Shared.CRC32(Encoding.UTF8.GetBytes(textBox1.Text.ToCharArray()));
             maskedTextBox1.Text = NesApplication.GenerateCode(crc32, AppTypeCollection.GetAvailablePrefix(textBox1.Text));
         }
         else
         {
             maskedTextBox1.Text = string.Empty;
         }
     }
 }
Ejemplo n.º 5
0
        // --- scan files and create internal list
        public Tasker.Conclusion LoadGamesFromFiles(Tasker tasker, Object syncObject = null)
        {
            var sync = (LoadGamesSyncObject)syncObject;

            // list original game directories
            var originalGameDirs = new List <string>();

            foreach (var defaultGame in NesApplication.CurrentDefaultGames)
            {
                string gameDir   = Path.Combine(NesApplication.OriginalGamesDirectory, defaultGame);
                string cachedDir = Path.Combine(NesApplication.OriginalGamesCacheDirectory, defaultGame);
                if (Directory.Exists(gameDir) && (!ConfigIni.Instance.AlwaysCopyOriginalGames || Directory.Exists(cachedDir)))
                {
                    originalGameDirs.Add(gameDir);
                }
            }

            // add custom games
            Directory.CreateDirectory(NesApplication.GamesDirectory);
            var gameDirs = Shared.ConcatArrays(Directory.GetDirectories(NesApplication.GamesDirectory), originalGameDirs.ToArray());

            var items = new List <ListViewItem>();
            int i     = 0;

            foreach (var gameDir in gameDirs)
            {
                try
                {
                    var game = NesApplication.FromDirectory(gameDir);
                    items.Add(new ListViewItem(game.Name)
                    {
                        Tag = game
                    });
                }
                catch // remove bad directories if any, no throw
                {
                    Trace.WriteLine($"Game directory \"{gameDir}\" is invalid, deleting");
                    Directory.Delete(gameDir, true);
                }
                tasker.SetProgress(++i, gameDirs.Length);
            }
            sync.items = ConfigIni.Instance.OriginalGamesPosition == MainForm.OriginalGamesPosition.Hidden ?
                         items.Where(item => !(item.Tag as NesApplication).IsOriginalGame).ToArray() :
                         items.ToArray();

            return(Tasker.Conclusion.Success);
        }
Ejemplo n.º 6
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 = NesApplication.FromDirectory(tmpPath);
                    (lGame as NesApplication).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;
        }
Ejemplo n.º 7
0
 public GameGenieDataBase(NesApplication 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"));
     }
 }
Ejemplo n.º 8
0
        public static string[] GetImageUrls(NesApplication app)
        {
            string query = app.Name ?? "";

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

            Trace.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();
            //Trace.WriteLine("Web response: " + responseFromServer);

            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());
        }
Ejemplo n.º 9
0
 private void button1_Click(object sender, EventArgs e)
 {
     if (maskedTextBox1.MaskCompleted && textBox1.Text.Length > 0)
     {
         var code = maskedTextBox1.Text;
         var path = Path.Combine(NesApplication.GamesDirectory, code);
         if (!Directory.Exists(path))
         {
             NewApp       = NesApplication.CreateEmptyApp(path, textBox1.Text);
             DialogResult = DialogResult.OK;
             Close();
         }
         else
         {
             Tasks.MessageForm.Show(Resources.NewCustomGame, Resources.CustomGameCodeAlreadyExists, Resources.sign_warning);
         }
     }
     else
     {
         Tasks.MessageForm.Show(Resources.NewCustomGame, Resources.CustomGameNeedValidData, Resources.sign_warning);
     }
 }
Ejemplo n.º 10
0
 private void button1_Click(object sender, EventArgs e)
 {
     if (maskedTextBox1.MaskCompleted && textBox1.Text.Length > 0)
     {
         var code = maskedTextBox1.Text;
         var path = Path.Combine(NesApplication.GamesDirectory, code);
         if (!Directory.Exists(path))
         {
             NewApp       = NesApplication.CreateEmptyApp(path, textBox1.Text);
             DialogResult = DialogResult.OK;
             Close();
         }
         else
         {
             MessageBox.Show(this, Resources.CustomGameCodeAlreadyExists, Resources.NewCustomGame, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
         }
     }
     else
     {
         MessageBox.Show(this, Resources.CustomGameNeedValidData, Resources.NewCustomGame, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
     }
 }
Ejemplo n.º 11
0
        private void AddMenu(NesMenuCollection menuCollection, NesApplication.CopyMode copyMode, HashSet <ApplicationFileInfo> localGameSet = null, GamesTreeStats stats = null)
        {
            if (stats == null)
            {
                stats = new GamesTreeStats();
            }
            if (!stats.allMenus.Contains(menuCollection))
            {
                stats.allMenus.Add(menuCollection);
            }
            int    menuIndex       = stats.allMenus.IndexOf(menuCollection);
            string targetDirectory = string.Format("{0:D3}", menuIndex);

            foreach (var element in menuCollection)
            {
                if (element is NesApplication)
                {
                    var game = element as NesApplication;

                    // still use temp directory for game genie games
                    try
                    {
                        if (game is ISupportsGameGenie && File.Exists(game.GameGeniePath))
                        {
                            string tempPath = Path.Combine(tempDirectory, game.Desktop.Code);
                            Shared.EnsureEmptyDirectory(tempPath);
                            NesApplication gameCopy = game.CopyTo(tempDirectory);
                            (gameCopy as ISupportsGameGenie).ApplyGameGenie();
                            game = gameCopy;
                        }
                    }
                    catch (GameGenieFormatException ex)
                    {
                        Trace.WriteLine(string.Format(Resources.GameGenieFormatError, ex.Code, game.Name));
                    }
                    catch (GameGenieNotFoundException ex)
                    {
                        Trace.WriteLine(string.Format(Resources.GameGenieNotFound, ex.Code, game.Name));
                    }

                    long gameSize = game.Size();
                    Trace.WriteLine(string.Format("Processing {0} ('{1}'), size: {2}KB", game.Code, game.Name, gameSize / 1024));
                    gameSize            = game.CopyTo(targetDirectory, localGameSet, copyMode);
                    stats.TotalSize    += gameSize;
                    stats.TransferSize += gameSize;
                    stats.TotalGames++;
                }
                if (element is NesMenuFolder)
                {
                    var folder = element as NesMenuFolder;
                    if (folder.Name == Resources.FolderNameTrashBin)
                    {
                        continue; // skip recycle bin!
                    }
                    if (folder.ChildMenuCollection.Count == 1 && folder.ChildMenuCollection[0].Name == Resources.FolderNameBack)
                    {
                        continue; // skip empty folders
                    }
                    if (!stats.allMenus.Contains(folder.ChildMenuCollection))
                    {
                        stats.allMenus.Add(folder.ChildMenuCollection);
                        AddMenu(folder.ChildMenuCollection, copyMode, localGameSet, stats);
                    }
                    folder.ChildIndex = stats.allMenus.IndexOf(folder.ChildMenuCollection);

                    long folderSize = folder.CopyTo(targetDirectory, localGameSet);
                    stats.TotalSize    += folderSize;
                    stats.TransferSize += folderSize;
                    Trace.WriteLine(string.Format("Processed folder {0} ('{1}'), size: {2}KB", folder.Code, folder.Name, folderSize / 1024));
                }
            }
        }
Ejemplo n.º 12
0
        // internal methods

        private void AddSymLinks(NesMenuCollection menuCollection, MemoryStream commandBuilder)
        {
            int    menuIndex       = stats.allMenus.IndexOf(menuCollection);
            string targetDirectory = string.Format("{0:D3}", menuIndex);

            foreach (var menuElement in menuCollection)
            {
                if (menuElement is NesApplication)
                {
                    NesApplication app = menuElement as NesApplication;

                    bool   hasAutoplayPixelArt = Directory.Exists(Path.Combine(app.BasePath, "autoplay")) || Directory.Exists(Path.Combine(app.BasePath, "autoplay"));
                    string src = $"{uploadPath}/.storage/{app.Code}";
                    string dst = $"{uploadPath}/{targetDirectory}/{app.Code}";

                    bool needLink = false;
                    if (ConfigIni.Instance.SyncLinked)
                    {
                        if (app.IsOriginalGame)
                        {
                            if (ConfigIni.Instance.AlwaysCopyOriginalGames)
                            {
                                if (hasAutoplayPixelArt)
                                {
                                    needLink = true;
                                }
                                else
                                {
                                    needLink = true;
                                }
                            }
                            else
                            {
                                if (hasAutoplayPixelArt)
                                {
                                    needLink = true;
                                }
                                else
                                {
                                    needLink = true;
                                    src      = $"{hakchi.SquashFsPath}{hakchi.GamesSquashFsPath}/{app.Code}";
                                }
                            }
                        }
                        else
                        {
                            if (hasAutoplayPixelArt)
                            {
                                needLink = true;
                            }
                            else
                            {
                                // needLink = false;
                            }
                        }
                    }
                    else
                    {
                        if (app.IsOriginalGame)
                        {
                            if (ConfigIni.Instance.AlwaysCopyOriginalGames)
                            {
                                if (hasAutoplayPixelArt)
                                {
                                    // needLink = false;
                                }
                                else
                                {
                                    // needLink = false;
                                }
                            }
                            else
                            {
                                if (hasAutoplayPixelArt)
                                {
                                    // needLink = false;
                                }
                                else
                                {
                                    needLink = true;
                                    src      = $"{hakchi.SquashFsPath}{hakchi.GamesSquashFsPath}/{app.Code}";
                                }
                            }
                        }
                        else
                        {
                            if (hasAutoplayPixelArt)
                            {
                                // needLink = false;
                            }
                            else
                            {
                                // needLink = false;
                            }
                        }
                    }

                    if (needLink)
                    {
                        string linkCode =
                            $"src=\"{src}\" && " +
                            $"dst=\"{dst}\" && " +
                            $"mkdir -p \"$dst\" && " +
                            $"rm -rf \"$dst/autoplay\" && " +
                            $"ln -s \"$src/autoplay\" \"$dst/\" ";
                        if (hakchi.HasPixelArt(ConfigIni.Instance.ConsoleType))
                        {
                            linkCode +=
                                $"&& rm -rf \"$dst/pixelart\" && " +
                                $"ln -s \"$src/pixelart\" \"$dst/\" ";
                        }
                        linkCode += "\n";
#if VERY_DEBUG
                        Trace.WriteLine(linkCode);
#endif
                        commandBuilder.Write(Encoding.UTF8.GetBytes(linkCode), 0, linkCode.Length);
                    }
                }
            }
        }
Ejemplo n.º 13
0
        public void Split(SplitStyle style, int maxElements = 35)
        {
            bool originalToRoot = false;
            int  originalCount  = 0;

            switch (style)
            {
            case SplitStyle.Original_NoSplit:
            case SplitStyle.Original_Auto:
            case SplitStyle.Original_FoldersAlphabetic_FoldersEqual:
            case SplitStyle.Original_FoldersAlphabetic_PagesEqual:
            case SplitStyle.Original_FoldersEqual:
            case SplitStyle.Original_PagesEqual:
                style--;
                originalCount = this.Where(o => (o is NesApplication) && (o as NesApplication).IsOriginalGame).Count();
                if (originalCount > 0)
                {
                    originalToRoot = true;
                }
                break;
            }
            if (style == SplitStyle.NoSplit && !originalToRoot)
            {
                return;
            }
            if (((style == SplitStyle.Auto && !originalToRoot) ||
                 (style == SplitStyle.FoldersEqual && !originalToRoot) ||
                 (style == SplitStyle.PagesEqual) && !originalToRoot) &&
                (Count <= maxElements))
            {
                return;
            }
            var total      = Count - originalCount;
            var partsCount = (int)Math.Ceiling((float)total / (float)maxElements);
            var perPart    = (int)Math.Ceiling((float)total / (float)partsCount);
            var alphaNum   = new Regex(@"[^\p{L}\p{Nd}0-9]", RegexOptions.Compiled); //var alphaNum = new Regex("[^a-zA-Z0-9]");

            NesMenuCollection root;

            if (!originalToRoot)
            {
                root = this;
            }
            else
            {
                root = new NesMenuCollection();
                root.AddRange(this.Where(o => (o is NesApplication) && !(o as NesApplication).IsOriginalGame));
                if (root.Count == 0)
                {
                    return;
                }
                this.RemoveAll(o => root.Contains(o));
                this.Add(new NesMenuFolder()
                {
                    Name                = Resources.FolderNameMoreGames,
                    Position            = NesMenuFolder.Priority.Rightmost,
                    ChildMenuCollection = root
                });
            }

            var sorted      = root.OrderBy(o => o.SortName);
            var collections = new List <NesMenuCollection>();
            int i           = 0;

            if (style == SplitStyle.Auto || style == SplitStyle.FoldersEqual || style == SplitStyle.PagesEqual)
            {
                var collection = new NesMenuCollection();
                foreach (var game in sorted)
                {
                    collection.Add(game);
                    i++;
                    if (((i % perPart) == 0) || (i == sorted.Count()))
                    {
                        collections.Add(collection);
                        collection = new NesMenuCollection();
                    }
                }
            }

            if (style == SplitStyle.Auto)
            {
                if (collections.Count >= 12)
                {
                    style = SplitStyle.FoldersEqual;
                }
                else
                {
                    style = SplitStyle.PagesEqual;
                }
            }

            // Folders, equal
            if (style == SplitStyle.FoldersEqual) // minimum amount of games/folders on screen without glitches
            {
                root.Clear();
                foreach (var coll in collections)
                {
                    var fname = alphaNum.Replace(coll.Where(o => o is NesApplication).First().SortName.ToUpper(), "");
                    var lname = alphaNum.Replace(coll.Where(o => o is NesApplication).Last().SortName.ToUpper(), "");

                    System.Diagnostics.Debug.WriteLine($"fname:\"{fname}\", lname:\"{lname}\"");

                    var folder = new NesMenuFolder()
                    {
                        ChildMenuCollection = coll, NameParts = new string[] { fname, lname }, Position = NesMenuFolder.Priority.Right
                    };
                    coll.Add(new NesMenuFolder()
                    {
                        Name = Resources.FolderNameBack, ImageId = "folder_back", Position = ConfigIni.Instance.BackFolderPosition, ChildMenuCollection = root
                    });
                    root.Add(folder);
                }
                TrimFolderNames(root);
            }
            else if (style == SplitStyle.PagesEqual)
            // Pages, equal
            {
                root.Clear();
                root.AddRange(collections[0]);
                collections[0] = root;
                for (i = 0; i < collections.Count; i++)
                {
                    for (int j = i - 1; j >= 0; j--)
                    {
                        var fname  = alphaNum.Replace(collections[j].Where(o => o is NesApplication).First().SortName.ToUpper(), "");
                        var lname  = alphaNum.Replace(collections[j].Where(o => o is NesApplication).Last().SortName.ToUpper(), "");
                        var folder = new NesMenuFolder()
                        {
                            ChildMenuCollection = collections[j],
                            NameParts           = new string[] { fname, lname },
                            Position            = NesMenuFolder.Priority.Left
                        };
                        collections[i].Insert(0, folder);
                    }
                    for (int j = i + 1; j < collections.Count; j++)
                    {
                        var fname  = alphaNum.Replace(collections[j].Where(o => o is NesApplication).First().SortName.ToUpper(), "");
                        var lname  = alphaNum.Replace(collections[j].Where(o => o is NesApplication).Last().SortName.ToUpper(), "");
                        var folder = new NesMenuFolder()
                        {
                            ChildMenuCollection = collections[j],
                            NameParts           = new string[] { fname, lname },
                            Position            = NesMenuFolder.Priority.Right
                        };
                        collections[i].Insert(collections[i].Count, folder);
                    }
                    TrimFolderNames(collections[i]);
                }
            }
            else if (style == SplitStyle.FoldersAlphabetic_PagesEqual || style == SplitStyle.FoldersAlphabetic_FoldersEqual)
            {
                var letters = new Dictionary <char, NesMenuCollection>();
                for (char ch = 'A'; ch <= 'Z'; ch++)
                {
                    letters[ch] = new NesMenuCollection();
                }
                letters['#'] = new NesMenuCollection();
                foreach (var game in root)
                {
                    if (!(game is NesApplication))
                    {
                        continue;
                    }
                    var letter = game.SortName.Substring(0, 1).ToUpper()[0];
                    if (letter < 'A' || letter > 'Z')
                    {
                        letter = '#';
                    }
                    letters[letter].Add(game);
                }

                root.Clear();
                foreach (var letter in letters.Keys)
                {
                    if (letters[letter].Count > 0)
                    {
                        string folderImageId = "folder_" + letter.ToString().ToLower();
                        if (letter < 'A' || letter > 'Z')
                        {
                            folderImageId = "folder_number";
                        }
                        var folder = new NesMenuFolder()
                        {
                            ChildMenuCollection = letters[letter], Name = letter.ToString(), Position = NesMenuFolder.Priority.Right, ImageId = folderImageId
                        };
                        if (style == SplitStyle.FoldersAlphabetic_PagesEqual)
                        {
                            folder.ChildMenuCollection.Split(SplitStyle.PagesEqual, maxElements);
                            folder.ChildMenuCollection.Add(new NesMenuFolder()
                            {
                                Name = Resources.FolderNameBack, ImageId = "folder_back", Position = ConfigIni.Instance.BackFolderPosition, ChildMenuCollection = root
                            });
                            foreach (NesMenuFolder f in folder.ChildMenuCollection.Where(o => o is NesMenuFolder))
                            {
                                if (f.ChildMenuCollection != root)
                                {
                                    f.ChildMenuCollection.Add(new NesMenuFolder()
                                    {
                                        Name = Resources.FolderNameBack, ImageId = "folder_back", Position = ConfigIni.Instance.BackFolderPosition, ChildMenuCollection = root
                                    });
                                }
                            }
                        }
                        else if (style == SplitStyle.FoldersAlphabetic_FoldersEqual)
                        {
                            folder.ChildMenuCollection.Split(SplitStyle.FoldersEqual, maxElements);
                            folder.ChildMenuCollection.Add(new NesMenuFolder()
                            {
                                Name = Resources.FolderNameBack, ImageId = "folder_back", Position = ConfigIni.Instance.BackFolderPosition, ChildMenuCollection = root
                            });
                        }
                        root.Add(folder);
                    }
                }
            }
            else if (style == SplitStyle.FoldersGroupByApp)
            {
                var apps       = new SortedDictionary <string, NesMenuCollection>();
                var customApps = new Dictionary <string, NesMenuCollection>();
                foreach (var system in CoreCollection.Systems)
                {
                    apps[system] = new NesMenuCollection();
                }
                foreach (var ai in AppTypeCollection.Apps)
                {
                    if (!apps.ContainsKey(ai.Name))
                    {
                        apps[ai.Name] = new NesMenuCollection();
                    }
                }
                apps[AppTypeCollection.UnknownApp.Name] = new NesMenuCollection();

                foreach (var game in root)
                {
                    if (!(game is NesApplication))
                    {
                        continue;
                    }
                    NesApplication app = game as NesApplication;

                    AppTypeCollection.AppInfo ai = app.Metadata.AppInfo;
                    if (!ai.Unknown && apps.ContainsKey(ai.Name))
                    {
                        apps[ai.Name].Add(game);
                    }
                    else if (!string.IsNullOrEmpty(app.Metadata.System) && apps.ContainsKey(app.Metadata.System))
                    {
                        apps[app.Metadata.System].Add(game);
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(app.Desktop.Bin))
                        {
                            if (!customApps.ContainsKey(app.Desktop.Bin))
                            {
                                customApps.Add(app.Desktop.Bin, new NesMenuCollection());
                            }
                            customApps[app.Desktop.Bin].Add(game);
                        }
                        else
                        {
                            apps[AppTypeCollection.UnknownApp.Name].Add(game);
                        }
                    }
                }

                root.Clear();
                foreach (var app in apps)
                {
                    if (app.Value.Count > 0)
                    {
                        string folderImageId = "folder";
                        var    folder        = new NesMenuFolder()
                        {
                            ChildMenuCollection = app.Value, Name = app.Key, Position = NesMenuFolder.Priority.Right, ImageId = folderImageId
                        };
                        //folder.ChildMenuCollection.Split(SplitStyle.FoldersEqual, maxElements);
                        folder.ChildMenuCollection.Add(new NesMenuFolder()
                        {
                            Name = Resources.FolderNameBack, ImageId = "folder_back", Position = ConfigIni.Instance.BackFolderPosition, ChildMenuCollection = root
                        });
                        root.Add(folder);
                    }
                }
                foreach (var app in customApps)
                {
                    if (app.Value.Count > 0)
                    {
                        string folderImageId = "folder";
                        var    folder        = new NesMenuFolder()
                        {
                            ChildMenuCollection = app.Value, Name = app.Key, Position = NesMenuFolder.Priority.Right, ImageId = folderImageId
                        };
                        //folder.ChildMenuCollection.Split(SplitStyle.FoldersEqual, maxElements);
                        folder.ChildMenuCollection.Add(new NesMenuFolder()
                        {
                            Name = Resources.FolderNameBack, ImageId = "folder_back", Position = ConfigIni.Instance.BackFolderPosition, ChildMenuCollection = root
                        });
                        root.Add(folder);
                    }
                }
            }
            if (originalToRoot)
            {
                if (style != SplitStyle.PagesEqual)
                {
                    root.Add(new NesMenuFolder()
                    {
                        Name = Resources.FolderNameOriginalGames, ImageId = "folder_back", Position = ConfigIni.Instance.BackFolderPosition, ChildMenuCollection = this
                    });
                }
                else
                {
                    foreach (var collection in collections)
                    {
                        collection.Add(new NesMenuFolder()
                        {
                            Name = Resources.FolderNameOriginalGames, ImageId = "folder_back", Position = ConfigIni.Instance.BackFolderPosition, ChildMenuCollection = this
                        });
                    }
                }
            }
        }
Ejemplo n.º 14
0
        public Tasker.Conclusion AddGames(Tasker tasker, Object syncObject = null)
        {
            tasker.SetProgress(-1, -1, Tasker.State.Running, Resources.AddingGames);
            tasker.SetTitle(Resources.AddingGames);
            tasker.SetStatusImage(Resources.sign_cogs);

            // static presets
            NesApplication.ParentForm           = tasker.HostForm;
            NesApplication.NeedPatch            = null;
            NesApplication.Need3rdPartyEmulator = null;
            NesApplication.CachedCoverFiles     = null;
            NesGame.IgnoreMapper           = null;
            SnesGame.NeedAutoDownloadCover = null;

            int total = files.Count();
            int count = 0;
            var gamesWithMultipleArt = new List <NesApplication>();

            foreach (var sourceFileName in files)
            {
                NesApplication app = null;
                try
                {
                    tasker.SetStatus(string.Format(Resources.AddingGame, Path.GetFileName(sourceFileName)));
                    var    fileName = sourceFileName;
                    var    ext      = Path.GetExtension(sourceFileName).ToLower();
                    byte[] rawData  = null;
                    string tmp      = null;
                    if (!asIs && (ext == ".7z" || ext == ".zip" || ext == ".rar" || ext == ".clvg"))
                    {
                        if (ext == ".clvg")
                        {
                            tmp = TempHelpers.getUniqueTempPath();
                            Directory.CreateDirectory(tmp);

                            using (var file = File.OpenRead(sourceFileName))
                                using (var reader = ReaderFactory.Open(file))
                                {
                                    reader.WriteAllToDirectory(tmp, new ExtractionOptions()
                                    {
                                        ExtractFullPath = true, PreserveFileTime = true
                                    });
                                }

                            var gameFilesInArchive = Directory.GetFiles(tmp, "*.desktop").Select(o => new DirectoryInfo(o)).Cast <DirectoryInfo>().ToArray();

                            switch (gameFilesInArchive.LongLength)
                            {
                            case 0:
                                // no files found
                                break;

                            case 1:
                                // one file found
                                fileName = gameFilesInArchive[0].FullName;
                                break;

                            default:
                                // multiple files found
                                var r = SelectFile(tasker, gameFilesInArchive.Select(o => o.FullName).ToArray());
                                if (r == DialogResult.OK)
                                {
                                    fileName = selectedFile;
                                }
                                else if (r == DialogResult.Ignore)
                                {
                                    fileName = sourceFileName;
                                }
                                else
                                {
                                    continue;
                                }
                                break;
                            }
                        }
                        else
                        {
                            using (var extractor = ArchiveFactory.Open(sourceFileName))
                            {
                                var filesInArchive     = extractor.Entries;
                                var gameFilesInArchive = new List <string>();
                                foreach (var f in extractor.Entries)
                                {
                                    if (!f.IsDirectory)
                                    {
                                        var e = Path.GetExtension(f.Key).ToLower();
                                        if (e == ".desktop")
                                        {
                                            gameFilesInArchive.Clear();
                                            gameFilesInArchive.Add(f.Key);
                                            break;
                                        }
                                        else if (CoreCollection.Extensions.Contains(e))
                                        {
                                            gameFilesInArchive.Add(f.Key);
                                        }
                                    }
                                }
                                if (gameFilesInArchive.Count == 1) // Only one known file (or app)
                                {
                                    fileName = gameFilesInArchive[0];
                                }
                                else if (gameFilesInArchive.Count > 1) // Many known files, need to select
                                {
                                    var r = SelectFile(tasker, gameFilesInArchive.ToArray());
                                    if (r == DialogResult.OK)
                                    {
                                        fileName = selectedFile;
                                    }
                                    else if (r == DialogResult.Ignore)
                                    {
                                        fileName = sourceFileName;
                                    }
                                    else
                                    {
                                        continue;
                                    }
                                }
                                else if (filesInArchive.Count() == 1) // No known files but only one another file
                                {
                                    fileName = filesInArchive.First().Key;
                                }
                                else // Need to select
                                {
                                    var r = SelectFile(tasker, filesInArchive.Select(f => f.Key).ToArray());
                                    if (r == DialogResult.OK)
                                    {
                                        fileName = selectedFile;
                                    }
                                    else if (r == DialogResult.Ignore)
                                    {
                                        fileName = sourceFileName;
                                    }
                                    else
                                    {
                                        continue;
                                    }
                                }
                                if (fileName != sourceFileName)
                                {
                                    var o = new MemoryStream();
                                    if (Path.GetExtension(fileName).ToLower() == ".desktop" || // App in archive, need the whole directory
                                        filesInArchive.Select(f => f.Key).Contains(Path.GetFileNameWithoutExtension(fileName) + ".jpg") || // Or it has cover in archive
                                        filesInArchive.Select(f => f.Key).Contains(Path.GetFileNameWithoutExtension(fileName) + ".png") ||
                                        filesInArchive.Select(f => f.Key).Contains(Path.GetFileNameWithoutExtension(fileName) + ".ips")    // Or IPS file
                                        )
                                    {
                                        tmp = Path.Combine(tempDirectory, fileName);
                                        Directory.CreateDirectory(tmp);
                                        extractor.WriteToDirectory(tmp, new ExtractionOptions()
                                        {
                                            ExtractFullPath = true, Overwrite = true
                                        });
                                        fileName = Path.Combine(tmp, fileName);
                                    }
                                    else
                                    {
                                        extractor.Entries.Where(f => f.Key == fileName).First().WriteTo(o);
                                        rawData = new byte[o.Length];
                                        o.Seek(0, SeekOrigin.Begin);
                                        o.Read(rawData, 0, (int)o.Length);
                                    }
                                }
                            }
                        }
                    }
                    app = NesApplication.Import(fileName, sourceFileName, rawData, asIs);

                    if (ext == ".clvg")
                    {
                        app.SkipCoreSelect = true;
                    }
                    else
                    {
                        if (app.CoverArtMatches != null && app.CoverArtMatches.Count() > 1)
                        {
                            gamesWithMultipleArt.Add(app);
                        }
                        if (ConfigIni.Instance.EnableImportScraper && Program.TheGamesDBAPI != null &&
                            app.Metadata.OriginalCrc32 != 0 &&
                            data.GamesDB.HashLookup.ContainsKey(app.Metadata.OriginalCrc32) &&
                            data.GamesDB.HashLookup[app.Metadata.OriginalCrc32].Length > 0)
                        {
                            var api  = Program.TheGamesDBAPI;
                            var task = api.GetInfoByID(data.GamesDB.HashLookup[app.Metadata.OriginalCrc32]);
                            try
                            {
                                task.Wait();
                                var result = task.Result;

                                if (result.Items.Count() > 0)
                                {
                                    var first = result.Items.First();

                                    if (first.Name != null)
                                    {
                                        app.Desktop.Name     = first.Name;
                                        app.Desktop.SortName = Shared.GetSortName(first.Name);
                                    }

                                    if (first.Publishers != null && first.Publishers.Length > 0)
                                    {
                                        app.Desktop.Publisher = String.Join(", ", first.Publishers).ToUpper();
                                    }
                                    else if (first.Developers != null && first.Developers.Length > 0)
                                    {
                                        if (first.ReleaseDate != null)
                                        {
                                            app.Desktop.Copyright = $"© {first.ReleaseDate.Year} {String.Join(", ", first.Developers)}";
                                        }
                                        else
                                        {
                                            app.Desktop.Copyright = $"© {String.Join(", ", first.Developers)}";
                                        }
                                    }

                                    if (first.Description != null)
                                    {
                                        app.Desktop.Description = first.Description;
                                    }

                                    if (first.ReleaseDate != null)
                                    {
                                        app.Desktop.ReleaseDate = first.ReleaseDate.ToString("yyyy-MM-dd");
                                    }

                                    if (first.PlayerCount > 0)
                                    {
                                        app.Desktop.Players      = Convert.ToByte(first.PlayerCount);
                                        app.Desktop.Simultaneous = first.PlayerCount == 2;
                                    }

                                    if (first.Genres != null && first.Genres.Length > 0)
                                    {
                                        foreach (var genre in first.Genres)
                                        {
                                            var match = ScraperForm.TheGamesDBGenreLookup.Where(g => g.Value.Contains(genre.ID)).Select(g => g.Key);

                                            if (match.Count() > 0)
                                            {
                                                var firstGenre = match.First();

                                                app.Desktop.Genre = firstGenre;
                                                break;
                                            }
                                        }
                                    }

                                    using (var wc = new HakchiWebClient())
                                    {
                                        try
                                        {
                                            var front = first.Images.Where(i => i.Type == TeamShinkansen.Scrapers.Enums.ArtType.Front).ToArray();

                                            if (front.Length > 0 && !app.CoverArtMatchSuccess)
                                            {
                                                var data = wc.DownloadData(front[0].Url);
                                                using (var ms = new MemoryStream(data))
                                                    using (var bm = new Bitmap(ms))
                                                    {
                                                        app.SetImage(bm);
                                                    }
                                            }
                                        }
                                        catch (WebException ex) { }

                                        try
                                        {
                                            var imageData = wc.DownloadData($"https://cdn.thegamesdb.net/images/original/clearlogo/{first.ID}.png");

                                            using (var ms = new MemoryStream(imageData))
                                                using (var clearLogo = File.OpenWrite(Path.Combine(app.BasePath, $"{app.Code}_logo.png")))
                                                {
                                                    ms.Seek(0, SeekOrigin.Begin);
                                                    ms.CopyTo(clearLogo);
                                                }
                                        }
                                        catch (WebException ex) { }
                                    }
                                }
                            }
                            catch (Exception) { }
                        }
                    }

                    if (app is ISupportsGameGenie && Path.GetExtension(fileName).ToLower() == ".nes")
                    {
                        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();
                        }
                    }

                    if (!string.IsNullOrEmpty(tmp) && Directory.Exists(tmp))
                    {
                        Directory.Delete(tmp, true);
                    }
                }
                catch (Exception ex)
                {
                    if (ex is ThreadAbortException)
                    {
                        return(Tasker.Conclusion.Abort);
                    }
                    if (ex.InnerException != null && !string.IsNullOrEmpty(ex.InnerException.Message))
                    {
                        Trace.WriteLine(ex.InnerException.Message + ex.InnerException.StackTrace);
                        tasker.ShowError(ex.InnerException, Path.GetFileName(sourceFileName));
                    }
                    else
                    {
                        Trace.WriteLine(ex.Message + ex.StackTrace, Path.GetFileName(sourceFileName));
                        tasker.ShowError(ex);
                    }
                    return(Tasker.Conclusion.Error);
                }
                if (app != null)
                {
                    addedApps.Add(app);
                }
                tasker.SetProgress(++count, total);
            }
            if (gamesWithMultipleArt.Count > 0)
            {
                tasker.HostForm.Invoke(new Action(() => {
                    using (SelectCoverDialog selectCoverDialog = new SelectCoverDialog())
                    {
                        selectCoverDialog.Games.AddRange(gamesWithMultipleArt);
                        selectCoverDialog.ShowDialog(tasker.HostForm);
                    }
                }));
            }
            return(Tasker.Conclusion.Success);
        }
Ejemplo n.º 15
0
        public Tasker.Conclusion AddGames(Tasker tasker, Object syncObject = null)
        {
            tasker.SetProgress(-1, -1, Tasker.State.Running, Resources.AddingGames);
            tasker.SetTitle(Resources.AddingGames);
            tasker.SetStatusImage(Resources.sign_cogs);

            // static presets
            NesApplication.ParentForm           = tasker.HostForm;
            NesApplication.NeedPatch            = null;
            NesApplication.Need3rdPartyEmulator = null;
            NesApplication.CachedCoverFiles     = null;
            NesGame.IgnoreMapper           = null;
            SnesGame.NeedAutoDownloadCover = null;

            int total = files.Count();
            int count = 0;

            foreach (var sourceFileName in files)
            {
                NesApplication app = null;
                try
                {
                    tasker.SetStatus(string.Format(Resources.AddingGame, Path.GetFileName(sourceFileName)));
                    var    fileName = sourceFileName;
                    var    ext      = Path.GetExtension(sourceFileName).ToLower();
                    byte[] rawData  = null;
                    string tmp      = null;
                    if (ext == ".7z" || ext == ".zip" || ext == ".rar")
                    {
                        using (var szExtractor = new SevenZipExtractor(sourceFileName))
                        {
                            var filesInArchive     = szExtractor.ArchiveFileNames;
                            var gameFilesInArchive = new List <string>();
                            foreach (var f in szExtractor.ArchiveFileNames)
                            {
                                var e = Path.GetExtension(f).ToLower();
                                if (e == ".desktop")
                                {
                                    gameFilesInArchive.Clear();
                                    gameFilesInArchive.Add(f);
                                    break;
                                }
                                else if (CoreCollection.Extensions.Contains(e))
                                {
                                    gameFilesInArchive.Add(f);
                                }
                            }
                            if (gameFilesInArchive.Count == 1) // Only one known file (or app)
                            {
                                fileName = gameFilesInArchive[0];
                            }
                            else if (gameFilesInArchive.Count > 1) // Many known files, need to select
                            {
                                var r = SelectFile(tasker, gameFilesInArchive.ToArray());
                                if (r == DialogResult.OK)
                                {
                                    fileName = selectedFile;
                                }
                                else if (r == DialogResult.Ignore)
                                {
                                    fileName = sourceFileName;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            else if (filesInArchive.Count == 1) // No known files but only one another file
                            {
                                fileName = filesInArchive[0];
                            }
                            else // Need to select
                            {
                                var r = SelectFile(tasker, filesInArchive.ToArray());
                                if (r == DialogResult.OK)
                                {
                                    fileName = selectedFile;
                                }
                                else if (r == DialogResult.Ignore)
                                {
                                    fileName = sourceFileName;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            if (fileName != sourceFileName)
                            {
                                var o = new MemoryStream();
                                if (Path.GetExtension(fileName).ToLower() == ".desktop" || // App in archive, need the whole directory
                                    szExtractor.ArchiveFileNames.Contains(Path.GetFileNameWithoutExtension(fileName) + ".jpg") || // Or it has cover in archive
                                    szExtractor.ArchiveFileNames.Contains(Path.GetFileNameWithoutExtension(fileName) + ".png") ||
                                    szExtractor.ArchiveFileNames.Contains(Path.GetFileNameWithoutExtension(fileName) + ".ips")    // Or IPS file
                                    )
                                {
                                    tmp = Path.Combine(tempDirectory, fileName);
                                    Directory.CreateDirectory(tmp);
                                    szExtractor.ExtractArchive(tmp);
                                    fileName = Path.Combine(tmp, fileName);
                                }
                                else
                                {
                                    szExtractor.ExtractFile(fileName, o);
                                    rawData = new byte[o.Length];
                                    o.Seek(0, SeekOrigin.Begin);
                                    o.Read(rawData, 0, (int)o.Length);
                                }
                            }
                        }
                    }
                    app = NesApplication.Import(fileName, sourceFileName, rawData);

                    if (app is ISupportsGameGenie && Path.GetExtension(fileName).ToLower() == ".nes")
                    {
                        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();
                        }
                    }

                    if (!string.IsNullOrEmpty(tmp) && Directory.Exists(tmp))
                    {
                        Directory.Delete(tmp, true);
                    }
                }
                catch (Exception ex)
                {
                    if (ex is ThreadAbortException)
                    {
                        return(Tasker.Conclusion.Abort);
                    }
                    if (ex.InnerException != null && !string.IsNullOrEmpty(ex.InnerException.Message))
                    {
                        Debug.WriteLine(ex.InnerException.Message + ex.InnerException.StackTrace);
                        tasker.ShowError(ex.InnerException, Path.GetFileName(sourceFileName));
                    }
                    else
                    {
                        Debug.WriteLine(ex.Message + ex.StackTrace, Path.GetFileName(sourceFileName));
                        tasker.ShowError(ex);
                    }
                    return(Tasker.Conclusion.Error);
                }
                if (app != null)
                {
                    addedApps.Add(app);
                }
                tasker.SetProgress(++count, total);
            }
            return(Tasker.Conclusion.Success);
        }
Ejemplo n.º 16
0
        public Tasker.Conclusion SyncOriginalGames(Tasker tasker, Object SyncObject = null)
        {
            tasker.SetTitle(Resources.ResettingOriginalGames);
            tasker.SetStatusImage(Resources.sign_sync);
            tasker.SetProgress(-1, -1, Tasker.State.Running, Resources.ResettingOriginalGames);

            string desktopEntriesArchiveFile = Path.Combine(Path.Combine(Program.BaseDirectoryInternal, "data"), "desktop_entries.7z");
            string originalGamesPath         = Path.Combine(Program.BaseDirectoryExternal, "games_originals");
            var    selectedGames             = ConfigIni.Instance.SelectedGames;

            if (!Directory.Exists(originalGamesPath))
            {
                Directory.CreateDirectory(originalGamesPath);
            }

            if (!File.Exists(desktopEntriesArchiveFile))
            {
                throw new FileLoadException("desktop_entries.7z data file was deleted, cannot sync original games.");
            }

            try
            {
                var defaultGames = ResetAllOriginalGames ? NesApplication.AllDefaultGames : NesApplication.DefaultGames;

                using (var szExtractor = new SevenZipExtractor(desktopEntriesArchiveFile))
                {
                    int i = 0;
                    foreach (var f in szExtractor.ArchiveFileNames)
                    {
                        var code  = Path.GetFileNameWithoutExtension(f);
                        var query = defaultGames.Where(g => g.Code == code);

                        if (query.Count() != 1)
                        {
                            continue;
                        }

                        var ext = Path.GetExtension(f).ToLower();
                        if (ext != ".desktop") // sanity check
                        {
                            throw new FileLoadException($"invalid file \"{f}\" found in desktop_entries.7z data file.");
                        }

                        string path       = Path.Combine(originalGamesPath, code);
                        string outputFile = Path.Combine(path, code + ".desktop");
                        bool   exists     = File.Exists(outputFile);

                        if (exists && !NonDestructiveSync)
                        {
                            Shared.EnsureEmptyDirectory(path);
                            Thread.Sleep(0);
                        }

                        if (!exists || !NonDestructiveSync)
                        {
                            Directory.CreateDirectory(path);

                            // extract .desktop file from archive
                            using (var o = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
                            {
                                szExtractor.ExtractFile(f, o);
                                o.Flush();
                                if (!this.ResetAllOriginalGames && !selectedGames.Contains(code))
                                {
                                    selectedGames.Add(code);
                                }
                            }

                            // create game temporarily to perform cover search
                            Debug.WriteLine(string.Format("Resetting game \"{0}\".", query.Single().Name));
                            var game = NesApplication.FromDirectory(path);
                            game.FindCover(code + ".desktop");
                            game.Save();
                        }

                        tasker.SetProgress(++i, defaultGames.Length);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error synchronizing original games " + ex.Message + ex.StackTrace);
                tasker.ShowError(ex, Resources.ErrorRestoringAllOriginalGames);
                return(Tasker.Conclusion.Error);
            }

            return(Tasker.Conclusion.Success);
        }
Ejemplo n.º 17
0
        public Tasker.Conclusion SyncOriginalGames(Tasker tasker, Object SyncObject = null)
        {
            tasker.SetTitle(Resources.ResettingOriginalGames);
            tasker.SetStatusImage(Resources.sign_sync);
            tasker.SetProgress(-1, -1, Tasker.State.Running, Resources.ResettingOriginalGames);

            string desktopEntriesArchiveFile = Path.Combine(Path.Combine(Program.BaseDirectoryInternal, "data"), "desktop_entries.tar");
            string originalGamesPath         = Path.Combine(Program.BaseDirectoryExternal, "games_originals");

            if (!Directory.Exists(originalGamesPath))
            {
                Directory.CreateDirectory(originalGamesPath);
            }

            if (!File.Exists(desktopEntriesArchiveFile))
            {
                throw new FileLoadException("desktop_entries.tar data file was deleted, cannot sync original games.");
            }

            try
            {
                var defaultGames = ResetAllOriginalGames ? NesApplication.AllDefaultGames.Select(g => g.Key) : NesApplication.CurrentDefaultGames;
                using (var extractor = ArchiveFactory.Open(desktopEntriesArchiveFile))
                    using (var reader = extractor.ExtractAllEntries())
                    {
                        int i = 0;
                        while (reader.MoveToNextEntry())
                        {
                            if (reader.Entry.IsDirectory)
                            {
                                continue;
                            }

                            var code = Path.GetFileNameWithoutExtension(reader.Entry.Key);
                            if (!defaultGames.Contains(code))
                            {
                                continue;
                            }

                            var ext = Path.GetExtension(reader.Entry.Key).ToLower();
                            if (ext != ".desktop") // sanity check
                            {
                                throw new FileLoadException($"invalid file \"{reader.Entry.Key}\" found in desktop_entries.tar data file.");
                            }

                            string path       = Path.Combine(originalGamesPath, code);
                            string outputFile = Path.Combine(path, code + ".desktop");
                            bool   exists     = File.Exists(outputFile);

                            if (exists && !NonDestructiveSync)
                            {
                                Shared.EnsureEmptyDirectory(path);
                                Thread.Sleep(0);
                            }

                            if (!exists || !NonDestructiveSync)
                            {
                                Directory.CreateDirectory(path);

                                // extract .desktop file from archive
                                using (var o = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
                                {
                                    reader.WriteEntryTo(o);
                                    o.Flush();
                                    if (!this.ResetAllOriginalGames && !ConfigIni.Instance.OriginalGames.Contains(code))
                                    {
                                        ConfigIni.Instance.OriginalGames.Add(code);
                                    }
                                }

                                // create game temporarily to perform cover search
                                Trace.WriteLine(string.Format($"Resetting game \"{NesApplication.AllDefaultGames[code].Name}\"."));
                                var game = NesApplication.FromDirectory(path);
                                game.FindCover(code + ".desktop");
                                game.Save();
                            }

                            tasker.SetProgress(++i, defaultGames.Count());
                        }
                    }
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Error synchronizing original games " + ex.Message + ex.StackTrace);
                tasker.ShowError(ex, Resources.ErrorRestoringAllOriginalGames);
                return(Tasker.Conclusion.Error);
            }

            return(Tasker.Conclusion.Success);
        }
Ejemplo n.º 18
0
        public Tasker.Conclusion AddGames(Tasker tasker, Object syncObject = null)
        {
            tasker.SetProgress(-1, -1, Tasker.State.Running, Resources.AddingGames);
            tasker.SetTitle(Resources.AddingGames);
            tasker.SetStatusImage(Resources.sign_cogs);

            // static presets
            NesApplication.ParentForm           = tasker.HostForm;
            NesApplication.NeedPatch            = null;
            NesApplication.Need3rdPartyEmulator = null;
            NesApplication.CachedCoverFiles     = null;
            NesGame.IgnoreMapper           = null;
            SnesGame.NeedAutoDownloadCover = null;

            int total = files.Count();
            int count = 0;
            var gamesWithMultipleArt = new List <NesApplication>();

            foreach (var sourceFileName in files)
            {
                NesApplication app = null;
                try
                {
                    tasker.SetStatus(string.Format(Resources.AddingGame, Path.GetFileName(sourceFileName)));
                    var    fileName = sourceFileName;
                    var    ext      = Path.GetExtension(sourceFileName).ToLower();
                    byte[] rawData  = null;
                    string tmp      = null;
                    if (!asIs && (ext == ".7z" || ext == ".zip" || ext == ".rar" || ext == ".clvg"))
                    {
                        if (ext == ".clvg")
                        {
                            tmp = TempHelpers.getUniqueTempPath();
                            Directory.CreateDirectory(tmp);

                            using (var file = File.OpenRead(sourceFileName))
                                using (var reader = ReaderFactory.Open(file))
                                {
                                    reader.WriteAllToDirectory(tmp, new ExtractionOptions()
                                    {
                                        ExtractFullPath = true, PreserveFileTime = true
                                    });
                                }

                            var gameFilesInArchive = Directory.GetFiles(tmp, "*.desktop").Select(o => new DirectoryInfo(o)).Cast <DirectoryInfo>().ToArray();

                            switch (gameFilesInArchive.LongLength)
                            {
                            case 0:
                                // no files found
                                break;

                            case 1:
                                // one file found
                                fileName = gameFilesInArchive[0].FullName;
                                break;

                            default:
                                // multiple files found
                                var r = SelectFile(tasker, gameFilesInArchive.Select(o => o.FullName).ToArray());
                                if (r == DialogResult.OK)
                                {
                                    fileName = selectedFile;
                                }
                                else if (r == DialogResult.Ignore)
                                {
                                    fileName = sourceFileName;
                                }
                                else
                                {
                                    continue;
                                }
                                break;
                            }
                        }
                        else
                        {
                            using (var extractor = ArchiveFactory.Open(sourceFileName))
                            {
                                var filesInArchive     = extractor.Entries;
                                var gameFilesInArchive = new List <string>();
                                foreach (var f in extractor.Entries)
                                {
                                    if (!f.IsDirectory)
                                    {
                                        var e = Path.GetExtension(f.Key).ToLower();
                                        if (e == ".desktop")
                                        {
                                            gameFilesInArchive.Clear();
                                            gameFilesInArchive.Add(f.Key);
                                            break;
                                        }
                                        else if (CoreCollection.Extensions.Contains(e))
                                        {
                                            gameFilesInArchive.Add(f.Key);
                                        }
                                    }
                                }
                                if (gameFilesInArchive.Count == 1) // Only one known file (or app)
                                {
                                    fileName = gameFilesInArchive[0];
                                }
                                else if (gameFilesInArchive.Count > 1) // Many known files, need to select
                                {
                                    var r = SelectFile(tasker, gameFilesInArchive.ToArray());
                                    if (r == DialogResult.OK)
                                    {
                                        fileName = selectedFile;
                                    }
                                    else if (r == DialogResult.Ignore)
                                    {
                                        fileName = sourceFileName;
                                    }
                                    else
                                    {
                                        continue;
                                    }
                                }
                                else if (filesInArchive.Count() == 1) // No known files but only one another file
                                {
                                    fileName = filesInArchive.First().Key;
                                }
                                else // Need to select
                                {
                                    var r = SelectFile(tasker, filesInArchive.Select(f => f.Key).ToArray());
                                    if (r == DialogResult.OK)
                                    {
                                        fileName = selectedFile;
                                    }
                                    else if (r == DialogResult.Ignore)
                                    {
                                        fileName = sourceFileName;
                                    }
                                    else
                                    {
                                        continue;
                                    }
                                }
                                if (fileName != sourceFileName)
                                {
                                    var o = new MemoryStream();
                                    if (Path.GetExtension(fileName).ToLower() == ".desktop" || // App in archive, need the whole directory
                                        filesInArchive.Select(f => f.Key).Contains(Path.GetFileNameWithoutExtension(fileName) + ".jpg") || // Or it has cover in archive
                                        filesInArchive.Select(f => f.Key).Contains(Path.GetFileNameWithoutExtension(fileName) + ".png") ||
                                        filesInArchive.Select(f => f.Key).Contains(Path.GetFileNameWithoutExtension(fileName) + ".ips")    // Or IPS file
                                        )
                                    {
                                        tmp = Path.Combine(tempDirectory, fileName);
                                        Directory.CreateDirectory(tmp);
                                        extractor.WriteToDirectory(tmp, new ExtractionOptions()
                                        {
                                            ExtractFullPath = true, Overwrite = true
                                        });
                                        fileName = Path.Combine(tmp, fileName);
                                    }
                                    else
                                    {
                                        extractor.Entries.Where(f => f.Key == fileName).First().WriteTo(o);
                                        rawData = new byte[o.Length];
                                        o.Seek(0, SeekOrigin.Begin);
                                        o.Read(rawData, 0, (int)o.Length);
                                    }
                                }
                            }
                        }
                    }
                    app = NesApplication.Import(fileName, sourceFileName, rawData, asIs);

                    if (ext == ".clvg")
                    {
                        app.SkipCoreSelect = true;
                    }
                    else
                    {
                        if (app != null && app.CoverArtMatches != null && app.CoverArtMatches.Count() > 1)
                        {
                            gamesWithMultipleArt.Add(app);
                        }
                        NewGames.Add(app);
                    }

                    if (app is ISupportsGameGenie && Path.GetExtension(fileName).ToLower() == ".nes")
                    {
                        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();
                        }
                    }

                    if (!string.IsNullOrEmpty(tmp) && Directory.Exists(tmp))
                    {
                        Directory.Delete(tmp, true);
                    }
                }
                catch (Exception ex)
                {
                    if (ex is ThreadAbortException)
                    {
                        return(Tasker.Conclusion.Abort);
                    }
                    if (ex.InnerException != null && !string.IsNullOrEmpty(ex.InnerException.Message))
                    {
                        Trace.WriteLine(ex.InnerException.Message + ex.InnerException.StackTrace);
                        tasker.ShowError(ex.InnerException, Path.GetFileName(sourceFileName));
                    }
                    else
                    {
                        Trace.WriteLine(ex.Message + ex.StackTrace, Path.GetFileName(sourceFileName));
                        tasker.ShowError(ex);
                    }
                    return(Tasker.Conclusion.Error);
                }
                if (app != null)
                {
                    addedApps.Add(app);
                }
                tasker.SetProgress(++count, total);
            }
            if (gamesWithMultipleArt.Count > 0)
            {
                tasker.HostForm.Invoke(new Action(() => {
                    using (SelectCoverDialog selectCoverDialog = new SelectCoverDialog())
                    {
                        selectCoverDialog.Games.AddRange(gamesWithMultipleArt);
                        selectCoverDialog.ShowDialog(tasker.HostForm);
                    }
                }));
            }
            return(Tasker.Conclusion.Success);
        }
Ejemplo n.º 19
0
        private void ShowSelected()
        {
            var items = listViewGames.SelectedItems;

            if (items.Count != 1)
            {
                listViewImages.Items.Clear();
                listViewImages.Enabled = false;
            }
            else
            {
                listViewImages.BeginUpdate();
                listViewImages.Items.Clear();

                NesApplication game          = items[0].Tag as NesApplication;
                var            matchedCovers = game.CoverArtMatches.ToArray();
                int            i             = imageList.Images.Count;

                listViewImages.View = matchedCovers.Length < 100 ? View.LargeIcon : View.List;

                if (imageIndexes.ContainsKey(game.Metadata.AppInfo.Name))
                {
                    var item = new ListViewItem(Resources.DefaultNoChange);
                    item.ImageIndex = imageIndexes[game.Metadata.AppInfo.Name];
                    listViewImages.Items.Add(item);
                }
                else
                {
                    var image = Shared.ResizeImage(game.Metadata.AppInfo.DefaultCover, null, listViewImages.BackColor, 114, 102, false, true, true, true);
                    imageList.Images.Add(image);

                    var item = new ListViewItem(Resources.DefaultNoChange);
                    imageIndexes.Add(game.Metadata.AppInfo.Name, item.ImageIndex = i++);
                    listViewImages.Items.Add(item);
                }

                foreach (var match in matchedCovers)
                {
                    var item = new ListViewItem(Path.GetFileName(match));
                    if (imageIndexes.ContainsKey(match))
                    {
                        item.ImageIndex = imageIndexes[match];
                    }
                    else
                    {
                        if (matchedCovers.Length < 100)
                        {
                            var image = Shared.ResizeImage(Image.FromFile(match), null, null, 114, 102, false, true, true, true);
                            imageList.Images.Add(image);
                            imageIndexes.Add(match, item.ImageIndex = i++);
                        }
                    }
                    listViewImages.Items.Add(item);
                }

                for (int j = 0; j < listViewImages.Items.Count; ++j)
                {
                    if (listViewImages.Items[j].Text == items[0].SubItems[4].Text)
                    {
                        listViewImages.Items[j].Selected = true;
                        break;
                    }
                }

                listViewImages.Enabled = true;
                listViewImages.EndUpdate();
            }
        }
Ejemplo n.º 20
0
 public ImageGooglerForm(NesApplication app)
 {
     InitializeComponent();
     query  = app.Name ?? "";
     query += " " + app.Metadata.AppInfo.GoogleSuffix + " (box|cover) art";
 }
Ejemplo n.º 21
0
 public GameGenieCodeAddModForm(NesApplication game)
 {
     InitializeComponent();
     FGame = game;
 }