/// <summary>
 /// Gets the content of the site of the passed URL and parses it for ModInfos.
 /// </summary>
 /// <param name="url">The URL of the site to parse the ModInfos from.</param>
 /// <returns>The ModInfos parsed from the site of the passed URL.</returns>
 public static ModInfo GetModInfo(string forumURL)
 {
     ModInfo modInfo = new ModInfo();
     modInfo.ForumURL = forumURL;
     modInfo.VersionControl = VersionControl.KSPForum;
     if (ParseSite(www.Load(forumURL), ref modInfo))
         return modInfo;
     else
         return null;
 }
Esempio n. 2
0
        /// <summary>
        /// Constructs a new <see cref="LoaderError"/>.
        /// </summary>
        /// <param name="modPath">The path to the mod associated with this error</param>
        /// <param name="message">The message associated with this error</param>
        /// <param name="data">The data associated with this error</param>
        /// <param name="info">The <see cref="ModInfo"/> of the mod associated with this error</param>
        public LoaderError(string modPath, string message = null, object data = null, ModInfo? info = null)
        {
            if (String.IsNullOrEmpty(modPath))
                throw new ArgumentNullException("modPath");

            ModPath = modPath;
            Message = message;

            Mod = info;
            Data = data;
        }
Esempio n. 3
0
        private void ModList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ModInfo mod = ModList.SelectedItem as ModInfo;

            NameBox.Text        = mod?.Name;
            DescriptionBox.Text = mod?.Description;

            if (string.IsNullOrEmpty(mod?.Url))
            {
                NameBox.IsEnabled       = false;
                NameBox.TextDecorations = null;
                NameBox.Foreground      = System.Windows.Media.Brushes.White;
            }
            else
            {
                NameBox.IsEnabled       = true;
                NameBox.TextDecorations = TextDecorations.Underline;
                NameBox.Foreground      = System.Windows.Media.Brushes.DodgerBlue;
            }
        }
Esempio n. 4
0
        private void LoadModInfo()
        {
            string content = null;

            if (!File.Exists(this.file.Path + "/modinfo.lua"))
            {
                Logger.Error("[WorkshopItem] ModInfo not exists: " + this.file.Path);
                return;
            }

            try {
                using (StreamReader reader = new StreamReader(this.file.Path + "/modinfo.lua")) {
                    content = reader.ReadToEnd();
                }
            } catch (IOException) {
                /* Do Nothing */
            }

            if (content == null)
            {
                Logger.Error("[WorkshopItem] ModInfo is empty or had errors: " + this.file.Path);
                return;
            }

            Logger.Info("[WorkshopItem] OK: " + this.file.Name);
            ModInfo info = Boot.Core.LUA.GetModInfo(content, this.file.Path + "/modinfo.lua", delegate(ParserException e) {
                Logger.Error("[WorkshopItem] ModInfo is broken: " + e);
            });

            info.SetID(UInt64.Parse(this.file.Name.Replace("workshop-", "")));

            if (info.IsBroken() && !info.HasName())
            {
                //this.Header = this.file.GetName(); //set at base constructs
            }
            else
            {
                this.Header = info.GetName();
            }
            // @ToDo Add ID(?)
        }
Esempio n. 5
0
        public ModInfo GenerateModFromInput()
        {
            decimal.TryParse(VersionInput, System.Globalization.NumberStyles.AllowDecimalPoint, new System.Globalization.CultureInfo(""), out decimal parsedVersion);
            Guid.TryParse(IDInput, out Guid parsedId);

            string translatedCategory = ResourceHelper.ModCategoryTranslations[CategoryInput];

            if (LoadedMod == null)
            {
                LoadedMod = new ModInfo()
                {
                    ID           = parsedId,
                    Name         = NameInput,
                    Author       = AuthorInput,
                    Version      = parsedVersion,
                    Category     = translatedCategory,
                    Description  = DescriptionInput,
                    Link         = InfoLinkInput,
                    PreviewFile  = PreviewImageInput,
                    ReleaseDate  = DateTime.Now,
                    ReleaseNotes = ReleaseNotesInput
                };
            }
            else
            {
                LoadedMod.ID           = parsedId;
                LoadedMod.Name         = NameInput;
                LoadedMod.Author       = AuthorInput;
                LoadedMod.Version      = parsedVersion;
                LoadedMod.Category     = translatedCategory;
                LoadedMod.Description  = DescriptionInput;
                LoadedMod.Link         = InfoLinkInput;
                LoadedMod.PreviewFile  = PreviewImageInput;
                LoadedMod.ReleaseDate  = DateTime.Now;
                LoadedMod.ReleaseNotes = ReleaseNotesInput;
            }

            NullifyEmptyLists();

            return(LoadedMod);
        }
Esempio n. 6
0
        void LoadMods()
        {
            if (!Directory.Exists(modFolderPath))
            {
                return;
            }

            FileStream stream = new FileInfo(modFolderPath + "ModLoadConfig.xml").OpenRead();

            modLoadConfig = (ModLoadConfig) new XmlSerializer(typeof(ModLoadConfig)).Deserialize(stream);
            stream.Close();

            FileInfo[] files = GetFilesByType(modFolderPath, "ModInfo.xml");
            foreach (FileInfo file in files)
            {
                ModInfo modInfo = new ModInfo();
                modInfo = (ModInfo) new XmlSerializer(typeof(ModInfo)).Deserialize((Stream)file.OpenRead());
                modInfos.Add(modInfo);
            }

            //Fill list with mods already in load config and in modinfos
            foreach (ModLoadConfig.ModEntry entry in modLoadConfig.ModLoadOrder)
            {
                foreach (ModInfo modInfo in modInfos)
                {
                    if (modInfo.Name == entry.Name)
                    {
                        ModList.Items.Add(entry.Name, entry.Load);
                    }
                }
            }

            //Fill list with mods not in load config
            foreach (ModInfo modInfo in modInfos)
            {
                if (!modLoadConfig.hasMod(modInfo.Name))
                {
                    ModList.Items.Add(modInfo.Name, false);
                }
            }
        }
        /// <summary>
        /// Downloads the mod.
        /// </summary>
        /// <param name="modInfo">The infos of the mod. Must have at least ModURL and LocalPath</param>
        /// <param name="downloadProgressCallback">Callback function for download progress.</param>
        /// <returns>True if the mod was downloaded.</returns>
        public bool DownloadMod(ref ModInfo modInfo, DownloadProgressCallback downloadProgressCallback = null)
        {
            if (modInfo == null)
            {
                return(false);
            }

            HtmlWeb      web     = new HtmlWeb();
            HtmlDocument htmlDoc = web.Load(modInfo.ModURL);

            htmlDoc.OptionFixNestedTags = true;

            // get filename from hover text
            HtmlNode fileNode  = htmlDoc.DocumentNode.SelectSingleNode("//*[@id='content']/section[2]/div[4]/div[2]/ul/li[1]/div[2]/p/a");
            HtmlNode fileNode2 = htmlDoc.DocumentNode.SelectSingleNode("//*[@id='content']/section[2]/div[4]/div[2]/ul/li/div[2]/p/a/span");

            string downloadURL = GetDownloadURL(modInfo.ModURL);

            if (fileNode == null || (fileNode.InnerHtml.Contains("...") && fileNode2 == null))
            {
                modInfo.LocalPath = Www.DownloadFile2(downloadURL, OptionsController.DownloadPath, downloadProgressCallback);
                return(!string.IsNullOrEmpty(modInfo.LocalPath) && File.Exists(modInfo.LocalPath));
            }

            string filename = string.Empty;

            if (fileNode.InnerHtml.Contains("..."))
            {
                filename = fileNode2.Attributes["title"].Value; // Long filename was truncated
            }
            else
            {
                filename = fileNode.InnerHtml;
            }

            modInfo.LocalPath = Path.Combine(OptionsController.DownloadPath, filename);

            Www.DownloadFile(downloadURL, modInfo.LocalPath, downloadProgressCallback);

            return(File.Exists(modInfo.LocalPath));
        }
Esempio n. 8
0
        public override JsonOperationResponseBase OnOperation(Arguments arguments, Authentication authentication)
        {
            string modId = arguments["modId"];

            ModInfo modInfo = UploadedModsManager.Instance.GetModInfoFromId(modId);

            if (modInfo == null)
            {
                return(new RemoveModResponse()
                {
                    Error = "Mod not found"
                });
            }

            UploadedModsManager.Instance.DeleteMod(modId);

            return(new RemoveModResponse()
            {
                Message = "Removed mod."
            });
        }
        internal static ModInfo GetModInfo(this Assembly assembly)
        {
            ModInfo modInfo = default;

            Type[] types = assembly.GetExportedTypes();

            foreach (var item in types)
            {
                BepInPlugin bepInPlugin = item.GetCustomAttribute <BepInPlugin>();

                if (bepInPlugin == null)
                {
                    continue;
                }

                modInfo.ModGuid = bepInPlugin.GUID;
                modInfo.ModName = bepInPlugin.Name;
            }

            return(modInfo);
        }
 /// <summary>
 /// Commits the current values to the <see cref="IModInfo"/>
 /// being edited.
 /// </summary>
 /// <returns>The <see cref="IModInfo"/> being edited with the new
 /// values, if they pass validation. If the current values are invalid, the
 /// original <see cref="IModInfo"/> is returned.</returns>
 public IModInfo Commit()
 {
     if (Validate() && (ModInfo != null))
     {
         ModInfo midInfo = new ModInfo(ModInfo);
         midInfo.DownloadId           = DownloadId;
         midInfo.Author               = Author;
         midInfo.Description          = Description;
         midInfo.HumanReadableVersion = HumanReadableVersion;
         midInfo.LastKnownVersion     = LastKnownVersion;
         midInfo.MachineVersion       = String.IsNullOrEmpty(MachineVersion) ? null : new Version(MachineVersion);
         midInfo.ModName              = ModName;
         midInfo.InstallDate          = InstallDate;
         midInfo.Website              = String.IsNullOrEmpty(Website) ? null : new Uri(Website);
         midInfo.Screenshot           = Screenshot;
         midInfo.CategoryId           = CategoryId;
         midInfo.IsEndorsed           = IsEndorsed;
         ModInfo.UpdateInfo(midInfo, true);
     }
     return(ModInfo);
 }
Esempio n. 11
0
    public ValueTask ExecuteAsync(IConsole console)
    {
        ModInfo modInfo = _modManager.Create(RomPath, ModName, ModVersion, ModAuthor);

        if (SetAsCurrent)
        {
            var mods = _modManager.GetAllModInfo();
            for (int i = 0; i < mods.Count; i++)
            {
                if (mods[i].FolderPath == modInfo.FolderPath)
                {
                    _settingService.Get <CurrentConsoleModSlotSetting>().Value = i;
                    _settingService.Save();
                    break;
                }
            }
        }
        console.Output.WriteLine("Mod created successfully");
        console.Render(modInfo);

        return(default);
Esempio n. 12
0
        public ModInfo GetModInfo()
        {
            ModInfo info;
            string  pathToModFileOrFolder = Path.Combine(Sys.Settings.LibraryLocation, LatestInstalled.InstalledLocation);

            try
            {
                if (!_infoCache.TryGetValue(pathToModFileOrFolder, out info))
                {
                    if (pathToModFileOrFolder.EndsWith(".iro", StringComparison.InvariantCultureIgnoreCase))
                    {
                        using (IrosArc arc = new IrosArc(pathToModFileOrFolder))
                        {
                            if (arc.HasFile("mod.xml"))
                            {
                                var doc = new System.Xml.XmlDocument();
                                doc.Load(arc.GetData("mod.xml"));
                                info = new ModInfo(doc, Sys._context);
                            }
                        }
                    }
                    else
                    {
                        string file = Path.Combine(pathToModFileOrFolder, "mod.xml");
                        if (File.Exists(file))
                        {
                            info = new ModInfo(file, Sys._context);
                        }
                    }
                    _infoCache.Add(pathToModFileOrFolder, info);
                }
            }
            catch (Exception ex)
            {
                Sys.Message(new WMessage($"WARNING: failed to get mod info due to unknown exception (commonly caused by incorrect xml): {ex.Message}", WMessageLogLevel.LogOnly, ex));
                return(null);
            }

            return(info);
        }
Esempio n. 13
0
        private void btnGotoSpaceport_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(ModURL))
            {
                MessageBox.Show(this, Messages.MSG_ENTER_VALID_URL_FIRST);
            }
            else
            {
                try
                {
                    ISiteHandler siteHandler = SiteHandlerManager.GetSiteHandlerByURL(ModURL); ////ByName(cbVersionControl.SelectedItem as string);
                    if (siteHandler == null)
                    {
                        // set selected sitehandler to none.
                        cbVersionControl.SelectedItem = cbVersionControl.Items[0];
                        string msg = string.Format(Messages.MSG_NO_SITEHANDLER_FOUND_FOR_URL_0, ModURL);
                        MessageBox.Show(this, msg, Messages.MSG_TITLE_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    ModInfo newModInfo = null;
                    if (siteHandler.IsValidURL(ModURL))
                    {
                        newModInfo = siteHandler.GetModInfo(ModURL);
                    }

                    if (newModInfo != null)
                    {
                        newModInfo.AdditionalURL = ModInfo.AdditionalURL;
                        ModInfo = newModInfo;
                    }
                }
                catch (Exception ex)
                {
                    string msg = string.Format(Messages.MSG_ERROR_DURING_MODINFO_UPDATE, ModURL, Environment.NewLine, ex.Message);
                    MessageBox.Show(this, msg, Messages.MSG_TITLE_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Log.AddErrorS(msg, ex);
                }
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Downloads the mod.
        /// </summary>
        /// <param name="modInfo">The infos of the mod. Must have at least ModURL and LocalPath</param>
        /// <param name="downloadProgressCallback">Callback function for download progress.</param>
        /// <returns>True if the mod was downloaded.</returns>
        public bool DownloadMod(ref ModInfo modInfo, DownloadProgressCallback downloadProgressCallback = null)
        {
            if (modInfo == null)
            {
                return(false);
            }

            var          downloadInfos = GetDownloadInfo(modInfo);
            DownloadInfo selected      = null;

            if (downloadInfos.Count > 1)
            {
                // create new selection form if more than one download option found
                var dlg = new frmSelectDownload(downloadInfos);
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    selected = dlg.SelectedLink;
                }
            }
            else if (downloadInfos.Count == 1)
            {
                selected = downloadInfos.First();
            }
            else
            {
                string msg = string.Format(Messages.MSG_NO_BINARY_DOWNLOAD_FOUND_AT_0, modInfo.SiteHandlerName);
                MessageBox.Show(msg, Messages.MSG_TITLE_ERROR);
                Messenger.AddDebug(msg);
                return(false);
            }

            if (selected != null)
            {
                string downloadUrl = selected.DownloadURL;
                modInfo.LocalPath = Path.Combine(OptionsController.DownloadPath, selected.Filename);
                Www.DownloadFile(downloadUrl, modInfo.LocalPath, downloadProgressCallback);
            }

            return(File.Exists(modInfo.LocalPath));
        }
Esempio n. 15
0
        public static FullGameState Read(NetIncomingMessage message)
        {
            var state = new FullGameState();

            state.MapInfo = ModAssetInfo.Decode(message.ReadBytes(message.ReadUInt16()));
            state.GamemodeReflectionName = message.ReadString();
            state.FriendlyFireEnabled    = message.ReadBoolean();
            state.HasStarted             = message.ReadBoolean();
            message.ReadPadBits();
            state.GamemodeState               = message.ReadBytes(message.ReadInt32());
            state.Status                      = (GameCore.CurrentGameStatus)message.ReadByte();
            state.TimescaleString             = message.ReadString();
            state.TimescaleValue              = message.ReadDouble();
            state.CurrentGameTimeMilliseconds = message.ReadDouble();
            state.NextObjectId                = message.ReadUInt16();
            state.GameEndedTime               = message.ReadDouble();

            var objCount = message.ReadInt32();

            for (var i = 0; i < objCount; i++)
            {
                state.ObjectStates.Add(new FullObjectState(message.ReadBytes(message.ReadInt32())));
            }

            var playersCount = message.ReadInt32();

            for (var i = 0; i < playersCount; i++)
            {
                state.Players.Add(FullStatePlayer.Read(message));
            }

            var loadedModCount = message.ReadInt32();

            for (var i = 0; i < loadedModCount; i++)
            {
                state.GameLoadedMods.Add(ModInfo.Decode(message.ReadBytes(message.ReadUInt16())));
            }

            return(state);
        }
Esempio n. 16
0
        private async Task LoadExtendedModInfoAsync(ModInfo mod, int operationIndex)
        {
            ExtendedModInfo extendedInfo;

            try
            {
                extendedInfo = await ModWebsite.GetExtendedInfoAsync(mod);
            }
            catch (WebException)
            {
                MessageBox.Show(Window,
                                App.Instance.GetLocalizedMessage("InternetConnection", MessageType.Error),
                                App.Instance.GetLocalizedMessageTitle("InternetConnection", MessageType.Error),
                                MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            if (operationIndex == asyncFetchExtendedInfoIndex)
            {
                ExtendedInfo = extendedInfo;
            }
        }
Esempio n. 17
0
        // Returns an array of ModInfo records, in the 'correct'
        // order for the mod.

        private ModInfo[] BuildModInfo(string[] plugins)
        {
            var mi       = new ModInfo[plugins.Length];
            var addcount = 1;
            var lastPos  = -1;
            var maxPos   = 0;

            for (var i = 0; i < mi.Length; i++)
            {
                var lplugin = plugins[i].ToLowerInvariant();
                if (m_dicMasterList.ContainsKey(lplugin))
                {
                    lastPos = m_dicMasterList[lplugin].id;
                    if (lastPos > maxPos)
                    {
                        maxPos = lastPos;
                    }
                    mi[i]    = new ModInfo(plugins[i], lastPos, true);
                    addcount = 1;
                }
                else
                {
                    mi[i] = new ModInfo(plugins[i], lastPos + addcount * 0.001, false);
                    addcount++;
                }
            }
            addcount = 1;
            maxPos++;
            for (var i = mi.Length - 1; i >= 0; i--)
            {
                if (mi[i].hadEntry)
                {
                    break;
                }
                mi[i].id = maxPos - addcount * 0.001;
                addcount++;
            }
            return(mi);
        }
        public ModViewModel(string Id, string dir, ModType type)
        {
            var info = new ModInfo(Path.Combine(dir, "About"));

            if (!info.Loaded)
            {
                return;
            }

            this.Directory = dir;

            this.Id = Id;

            this.Name        = info.Name;
            this.Author      = info.Author;
            this.Description = info.Description;

            this.SupportedVersions = info.SupportedVersions;
            this.Version           = info.Version;

            this.Type = type;
        }
Esempio n. 19
0
        private void SteamWorkshop_OnItemDownloaded(object sender, Workshop.DownloadItemEventArgs e)
        {
            if (e.Result.m_eResult != EResult.k_EResultOK)
            {
                MessageBox.Show($"{e.Result.m_nPublishedFileId}: {e.Result.m_eResult}");
                return;
            }

            var m = Downloads.SingleOrDefault(x => x.WorkshopID == (long)e.Result.m_nPublishedFileId.m_PublishedFileId);

            if (m != null)
            {
                // look for .XComMod file
                var infoFile = Directory.GetFiles(m.Path, "*.XComMod", SearchOption.TopDirectoryOnly).SingleOrDefault();
                if (infoFile == null)
                {
                    throw new Exception("Invalid Download");
                }

                // Fill fields
                m.State &= ~ModState.NotInstalled;
                m.ID     = Path.GetFileNameWithoutExtension(infoFile);
                m.Image  = null; // Use default image again

                // load info
                var info = new ModInfo(m.GetModInfoFile());

                // Move mod
                Downloads.Remove(m);
                Mods.AddMod(info.Category, m);

                // update listitem
                //var item = modlist_listview.Items.Cast<ListViewItem>().Single(i => (i.Tag as ModEntry).SourceID == m.SourceID);
                //UpdateModListItem(item, info.Category);
            }
            m = Mods.All.Single(x => x.WorkshopID == (long)e.Result.m_nPublishedFileId.m_PublishedFileId);

            MessageBox.Show($"{m.Name} finished download.");
        }
Esempio n. 20
0
        /// <summary>
        /// Checks if updates are available for the passed mod.
        /// </summary>
        /// <param name="modInfo">The ModInfos of the mod to check for updates.</param>
        /// <param name="newModInfo">A reference to an empty ModInfo to write the updated ModInfos to.</param>
        /// <returns>True if there is an update, otherwise false.</returns>
        public bool CheckForUpdates(ModInfo modInfo, ref ModInfo newModInfo)
        {
            newModInfo = GetModInfo(modInfo.ModURL);
            if (string.IsNullOrEmpty(modInfo.Version) && !string.IsNullOrEmpty(newModInfo.Version))
            {
                return(true);
            }
            else if (!string.IsNullOrEmpty(modInfo.Version) && !string.IsNullOrEmpty(newModInfo.Version))
            {
                return(VersionComparer.CompareVersions(modInfo.Version, newModInfo.Version) == VersionComparer.Result.AisSmallerB);
            }
            else if (string.IsNullOrEmpty(modInfo.CreationDate) && !string.IsNullOrEmpty(newModInfo.CreationDate))
            {
                return(true);
            }
            else if (!string.IsNullOrEmpty(modInfo.CreationDate) && !string.IsNullOrEmpty(newModInfo.CreationDate))
            {
                return(modInfo.CreationDateAsDateTime < newModInfo.CreationDateAsDateTime);
            }

            return(false);
        }
Esempio n. 21
0
        public BeatSaverLookupResult(Beatmap map)
        {
            ResultId = map.Hash;
            var info = new ModInfo {
                GameId      = "beatsaber",
                FileVersion = map.Hash,
                // SourceUrl = new Uri($"https://beatmods.com/api/v1/mod/{entry.DocumentId}"),
                SourceUrl       = new Uri($"https://beatmods.com{map.DownloadURL}"),
                Source          = "beatsaver",
                FileName        = System.IO.Path.GetFileName(map.DownloadURL),
                LogicalFileName = map.Key,
                Expires         = DateTime.UtcNow.AddHours(24).Ticks,
                Details         = new ModDetails {
                    Author      = map.Metadata.LevelAuthorName ?? map.Uploader.Username,
                    Description = map.Description,
                    FileId      = map.Key,
                    HomePage    = $"https://beatsaver.com/beatmap/{map.Key}",
                }
            };

            ModInfo = info;
        }
        /// <summary>
        /// Export as an asynchronous operation.
        /// </summary>
        /// <param name="params">The parameters.</param>
        /// <returns>A Task&lt;System.Boolean&gt; representing the asynchronous operation.</returns>
        public async Task <bool> ExportAsync(ModCollectionExporterParams @params)
        {
            // Paradox launcher only exports pdx or steam mods, local mods are not exported
            var validMods = @params.ExportMods.Where(p => p.Source != ModSource.Local).ToList();
            var modInfo   = new ModInfo()
            {
                Game = @params.Game.ParadoxGameId,
                Name = @params.Mod.Name,
                Mods = validMods.Select(p => new Models.Paradox.Json.v3.Mods()
                {
                    DisplayName = p.Name,
                    Enabled     = true,
                    Position    = validMods.IndexOf(p),
                    SteamId     = p.Source == ModSource.Steam ? p.RemoteId.ToString() : null,
                    PdxId       = p.Source == ModSource.Paradox ? p.RemoteId.ToString() : null
                }).ToList()
            };
            var json = JsonDISerializer.Serialize(modInfo);
            await File.WriteAllTextAsync(@params.File, json);

            return(true);
        }
Esempio n. 23
0
        public bool DeleteMod(string key)
        {
            Logging.Assert(m_modStates.ContainsKey(key));
            ModInfo mod = m_modStates[key];

            if (mod.ModState != ModState.Miss)
            {
                if (mod.Mod.Image != null)
                {
                    mod.Mod.Image.Dispose();
                }
                //the image file can not be realsed right now
                new System.Threading.Thread(new System.Threading.ThreadStart(() =>
                {
                    Logging.Log("delete mod " + mod.Key);
                    int trycount = 0;
                    while (trycount++ < 10)  //try 10 times
                    {
                        try
                        {
                            foreach (var v in new DirectoryInfo(m_path + (mod.Source == ModSource.Player ? m_dirAddons : m_dirWorkshop))
                                     .GetFiles(mod.Mod.FileName.Substring(0, mod.Mod.FileName.LastIndexOf('.')) + ".*"))
                            {
                                v.Attributes = FileAttributes.Normal;
                                v.Delete();
                            }
                            return;
                        }
                        catch
                        {
                            System.Threading.Thread.Sleep(100);
                        }
                    }
                })).Start();
            }
            m_modStates.Remove(key);
            return(true);
        }
Esempio n. 24
0
        public void ReorderMod(ModInfo info, bool up)
        {
            // todo: certified f****d tier

            var prio     = info.Priority;
            var swapPrio = up ? prio + 1 : prio - 1;
            var swapMeta = ModSettings.FirstOrDefault(x => x.Priority == swapPrio);

            if (swapMeta == null)
            {
                return;
            }

            info.Priority     = swapPrio;
            swapMeta.Priority = prio;

            // reorder mods list
            ModSettings = ModSettings.OrderBy(x => x.Priority).ToList();
            EnabledMods = GetOrderedAndEnabledModList().ToArray();

            // save new prios
            Save();
        }
Esempio n. 25
0
        private void CleanMod(ModInfo toClean)
        {
            DirectoryInfo downloadDir = toClean.DownloadDir;

            foreach (FileSystemInfo fileSystemInfo in downloadDir.EnumerateFileSystemInfos())
            {
                if (IsKeyFile(fileSystemInfo))
                {
                    continue;
                }

                var folder = fileSystemInfo as DirectoryInfo;

                if (folder != null)
                {
                    folder.Delete(true);
                }
                else
                {
                    fileSystemInfo.Delete();
                }
            }
        }
Esempio n. 26
0
        internal static bool IsModInstalled(string assemblyName)
        {
            ModInfo info = GetInfo(assemblyName);

            if (info.alreadyChecked)
            {
                return(info.installed);
            }

            try
            {
                Assembly assembly = (from a in assemblies
                                     where a.FullName.Split(',')[0] == assemblyName
                                     select a).First();
                info.alreadyChecked = true;
                info.installed      = assembly != null;
                return(info.installed);
            }
            catch
            {
                return(false);
            }
        }
Esempio n. 27
0
        public void ChangeModState(string key, ModState state)
        {
            Logging.Assert(state == ModState.On || state == ModState.Off || state == ModState.Unsubscribed);
            Logging.Assert(m_modStates.ContainsKey(key));
            ModInfo  mod      = m_modStates[key];
            ModState oldState = mod.ModState;

            if (oldState != state)
            {
                Logging.Log("change mod " + key + " state from " + oldState.ToString() + " to " + state.ToString());
                if (oldState == ModState.Unsubscribed)
                {
                    m_steam.Workshop.GetItem(mod.Mod.PublishedId).Subscribe();
                }
                if (state == ModState.Unsubscribed)
                {
                    Logging.Assert(m_steam != null);
                    Logging.Assert(mod.Mod.PublishedId > 0);
                    m_steam.Workshop.GetItem(mod.Mod.PublishedId).UnSubscribe();
                }
                mod.ModState = state;
            }
        }
Esempio n. 28
0
    static void RestoreModState(ModInfo loadMod)
    {
        //a file being "installed" in this context means that it was installed when the loadout was saved
        //so we need to make sure files that werent installed, get uninstalled now when restoring the loadout
        foreach (var file in loadMod.archiveFiles)
        {
            file.belongingNode = new TreeNode()
            {
                Checked = !file.GetInstalledStatus()
            }
        }
        ;
        ArchiveManager.UninstallSelected(loadMod, false, true);


        //Check the ones that actually should be installed and install them
        foreach (var file in loadMod.archiveFiles)
        {
            file.belongingNode.Checked = file.GetInstalledStatus();
        }
        ArchiveManager.InstallSelected(loadMod, false);
    }
}
Esempio n. 29
0
    public bool CreateModBasedOn(ModInfo baseMod, out ModInfo newModInfo)
    {
        var vm = new ModCreateBasedOnViewModel(baseMod);

        var dialog = new Dialogs.ModCreateBasedOnDialog
        {
            Owner       = Application.Current.MainWindow,
            DataContext = vm
        };

        bool?proceed = dialog.ShowDialog();

        if (proceed == true)
        {
            newModInfo = vm.ModInfo;
            return(true);
        }
        else
        {
            newModInfo = null;
            return(false);
        }
    }
Esempio n. 30
0
        protected void InitMod<T>(Assembly assembly) where T : GameShared
        {
            var mod = new ModInfo(assembly);

            _reflectionManager.LoadAssemblies(mod.GameAssembly);

            var entryPoints = mod.GameAssembly.GetTypes().Where(t => typeof(T).IsAssignableFrom(t)).ToArray();

            if (entryPoints.Length == 0)
                Logger.WarningS("res", $"Assembly has no entry points: {mod.GameAssembly.FullName}");

            foreach (var entryPoint in entryPoints)
            {
                var entryPointInstance = (T) Activator.CreateInstance(entryPoint)!;
                if (_testingCallbacks != null)
                {
                    entryPointInstance.SetTestingCallbacks(_testingCallbacks);
                }
                mod.EntryPoints.Add(entryPointInstance);
            }

            _mods.Add(mod);
        }
Esempio n. 31
0
        public ModInfo Import(string modPath)
        {
            ModInfo modInfo;

            using (ZipArchive zip = ZipFile.OpenRead(modPath))
            {
                ZipArchiveEntry entry = zip.GetEntry(ModInfoFileName);
                if (entry == null)
                {
                    throw new Exception("Failed to load mod because ModInfoFile not found.");
                }
                using (Stream modInfoStream = entry.Open())
                {
                    if (!ModInfo.TryLoadFrom(XDocument.Load(modInfoStream), out modInfo))
                    {
                        throw new Exception("Failed to load mod because failed to load ModInfo from ModInfoFile.");
                    }
                }
            }
            modInfo.FolderPath = GetNewModDirectory();
            ZipFile.ExtractToDirectory(modPath, modInfo.FolderPath);
            return(modInfo);
        }
Esempio n. 32
0
        /// <summary>
        /// Handles a mod add via URL.
        /// Validates the URL, gets ModInfos, downloads mod archive, adds it to the ModSelection and installs the mod if selected.
        /// </summary>
        /// <param name="url">The URL to the mod.</param>
        /// <param name="modName">The name for the mod.</param>
        /// <param name="install">Flag to determine if the mod should be installed after adding.</param>
        /// <param name="downloadProgressCallback">Callback function for download progress.</param>
        /// <returns>The root node of the added mod, or null.</returns>
        public ModNode HandleAdd(string url, string modName, bool install, DownloadProgressCallback downloadProgressCallback = null)
        {
            ModInfo modInfo = GetModInfo(url);

            if (modInfo == null)
            {
                return(null);
            }

            if (!string.IsNullOrEmpty(modName))
            {
                modInfo.Name = modName;
            }

            ModNode newMod = null;

            if (DownloadMod(ref modInfo, downloadProgressCallback))
            {
                newMod = ModSelectionController.HandleModAddViaModInfo(modInfo, install);
            }

            return(newMod);
        }
Esempio n. 33
0
 public LoaderError(string modPath, Exception e, ModInfo? info = null)
     : this(modPath, e == null ? null : e.Message, e, info)
 {
 }
Esempio n. 34
0
        public CrpReader(Stream stream)
            : base(stream)
        {
            singlarObjParser["System.DateTime"] = () =>
            {
                return DateTime.Parse(this.ReadString(), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
            };
            singlarObjParser["UnityEngine.Vector2"] = () =>
            {
                return new Vector2(this.ReadSingle(), this.ReadSingle());
            };
            singlarObjParser["UnityEngine.Vector3"] = () =>
            {
                return new Vector3(this.ReadSingle(), this.ReadSingle(), this.ReadSingle());
            };
            singlarObjParser["UnityEngine.Vector4"] = () =>
            {
                return new Vector4(this.ReadSingle(), this.ReadSingle(), this.ReadSingle(), this.ReadSingle());
            };
            singlarObjParser["System.String"] = () =>
            {
                return this.ReadString();
            };
            singlarObjParser["System.Single"] = () =>
            {
                return this.ReadSingle();
            };
            singlarObjParser["System.Int32"] = () =>
            {
                return this.ReadInt32();
            };
            singlarObjParser["System.Boolean"] = () =>
            {
                return this.ReadBoolean();
            };
            singlarObjParser["CustomAssetMetaData"] = () =>
            {
                return (CustomAssetMetaData.Type)(this.ReadInt32());
            };
            singlarObjParser["ModInfo"] = () =>
            {
                ModInfo info = new ModInfo();
                info.modName = this.ReadString();
                info.modWorkshopID = this.ReadUInt64();
                return info;
            };
            singlarObjParser["UnityEngine.Color"] = () =>
            {
                return new Color(this.ReadSingle(), this.ReadSingle(), this.ReadSingle(), this.ReadSingle());
            };
            singlarObjParser["UnityEngine.BoneWeight"] = () =>
            {
                Boneweight boneWeight = new Boneweight();
                for (int i = 0; i < 4; i++)
                {
                    boneWeight.indicies[i] = this.ReadInt32();
                    boneWeight.weights[i] = this.ReadSingle();
                }
                return boneWeight;
            };
            singlarObjParser["UnityEngine.Matrix4x4"] = () =>
            {
                Matrix4x4 matrix = new Matrix4x4();
                for (int i = 0; i < 16; i++)
                {
                    matrix.entries[i] = this.ReadSingle();
                }
                return matrix;
            };
            singlarObjParser["ItemClass"] = () =>
            {
                string retval = this.ReadString();
                this.ReadBoolean();
                return (retval);
            };
            singlarObjParser["ItemClass+Placement"] = () =>
            {
                return (ItemClass.Placement)(this.ReadInt32());
            };
            singlarObjParser["ItemClass+Availability"] = () =>
            {
                return (ItemClass.Availability)(this.ReadInt32());
            };
            singlarObjParser["ItemClass+Level"] = () =>
            {
                return (ItemClass.Level)(this.ReadInt32());
            };
            singlarObjParser["ItemClass+Service"] = () =>
            {
                return (ItemClass.Service)(this.ReadInt32());
            };
            singlarObjParser["ItemClass+SubService"] = () =>
            {
                return (ItemClass.SubService)(this.ReadInt32());
            };

            singlarObjParser["BuildingInfo+PlacementMode"] = () =>
            {
                return (BuildingInfo.PlacementMode)(this.ReadInt32());
            };
            singlarObjParser["BuildingInfo+ZoningMode"] = () =>
            {
                return (BuildingInfo.ZoningMode)(this.ReadInt32());
            };

            singlarObjParser["TerrainModify+Surface"] = () =>
            {
                return (TerrainModify.Surface)(this.ReadInt32());
            };
            singlarObjParser["VehicleInfo+MeshInfo"] = () =>
            {

                Dictionary<string, dynamic> retVal = new Dictionary<string, dynamic>();
                retVal["checksum"] = this.ReadString();
                retVal["m_parkedFlagsForbidden"] = (VehicleParked.Flags)this.ReadInt32();
                retVal["m_parkedFlagsRequired"] = (VehicleParked.Flags)this.ReadInt32();
                retVal["m_vehicleFlagsForbidden"] = (Vehicle.Flags)this.ReadInt32();
                retVal["m_vehicleFlagsRequired"] = (Vehicle.Flags)this.ReadInt32();
                return retVal;
            };
            singlarObjParser["BuildingInfo+Prop"] = () =>
            {
                Dictionary<string, dynamic> retVal = new Dictionary<string, dynamic>();
                retVal["m_prop"] = this.ReadString();
                retVal["m_tree"] = this.ReadString();
                retVal["m_position"] = singlarObjParser["UnityEngine.Vector3"]();
                retVal["m_angle"] = this.ReadSingle();
                retVal["m_probability"] = this.ReadInt32();
                retVal["m_fixedHeight"] = this.ReadBoolean();
                return retVal;
            };
            singlarObjParser["BuildingInfo+MeshInfo"] = () =>
            {

                Dictionary<string, dynamic> retVal = new Dictionary<string, dynamic>();
                retVal["m_subInfo"] = this.ReadString();
                retVal["m_flagsForbidden"] = (Building.Flags)(this.ReadInt32());
                retVal["m_flagsRequired"] = (Building.Flags)(this.ReadInt32());
                retVal["m_position"] = singlarObjParser["UnityEngine.Vector3"]();
                retVal["m_angle"] = this.ReadSingle();
                return retVal;
            };
            singlarObjParser["BuildingInfo+PathInfo"] = () =>
            {
                Dictionary<string, dynamic> retVal = new Dictionary<string, dynamic>();
                retVal["m_netInfo"] = this.ReadString();
                retVal["m_nodes"] = readUnityArray("UnityEngine.Vector3[]");
                retVal["m_curveTargets"] = readUnityArray("UnityEngine.Vector3[]");
                retVal["m_invertSegments"] = this.ReadBoolean();
                retVal["m_maxSnapDistance"] = this.ReadSingle();
                return retVal;
            };
            singlarObjParser["BuildingInfo+SubInfo"] = () =>
            {
                Dictionary<string, dynamic> retVal = new Dictionary<string, dynamic>();
                retVal["m_buildingInfo"] = this.ReadString();
                retVal["m_position"] = singlarObjParser["UnityEngine.Vector3"]();
                retVal["m_angle"] = this.ReadSingle();
                retVal["m_fixedHeight"] = this.ReadBoolean();
                return retVal;
            };
            singlarObjParser["PropInfo+DoorType"] = () =>
            {
                return (PropInfo.DoorType)this.ReadInt32();
            };
            singlarObjParser["PropInfo+Variation"] = () =>
            {
                Dictionary<string, dynamic> retVal = new Dictionary<string, dynamic>();
                retVal["m_prop"] = this.ReadString();
                retVal["m_probability"] = this.ReadInt32();
                return retVal;
            };
            singlarObjParser["PropInfo+ParkingSpace"] = () =>
            {
                Dictionary<string, dynamic> retVal = new Dictionary<string, dynamic>();
                retVal["m_position"] = singlarObjParser["UnityEngine.Vector3"]();
                retVal["m_angle"] = singlarObjParser["UnityEngine.Vector3"]();
                retVal["m_size"] = singlarObjParser["UnityEngine.Vector3"]();
                return retVal;
            };
            singlarObjParser["PropInfo+Effect"] = () =>
            {
                Dictionary<string, dynamic> retVal = new Dictionary<string, dynamic>();
                retVal["m_effect"] = this.ReadString();
                retVal["m_position"] = singlarObjParser["UnityEngine.Vector3"]();
                retVal["m_direction"] = singlarObjParser["UnityEngine.Vector3"]();
                return retVal;
            };
            singlarObjParser["DepotAI+SpawnPoint"] = () =>
            {
                Dictionary<string, dynamic> retVal = new Dictionary<string, dynamic>();
                retVal["m_position"] = singlarObjParser["UnityEngine.Vector3"]();
                retVal["m_target"] = singlarObjParser["UnityEngine.Vector3"]();
                return retVal;
            };
            singlarObjParser["PropInfo+SpecialPlace"] = () =>
            {
                Dictionary<string, dynamic> retVal = new Dictionary<string, dynamic>();
                retVal["m_specialFlags"] = this.ReadInt32();
                retVal["m_position"] = singlarObjParser["UnityEngine.Vector3"]();
                retVal["m_direction"] = singlarObjParser["UnityEngine.Vector3"]();
                return retVal;
            };

            singlarObjParser["TransportInfo"] = () =>
            {
                Dictionary<string, dynamic> retVal = new Dictionary<string, dynamic>();
                retVal["m_transportInfo"] = this.ReadString();
                return retVal;
            };
            singlarObjParser["ItemClass"] = () =>
            {
                Dictionary<string, dynamic> retVal = new Dictionary<string, dynamic>();
                retVal["m_itemClass"] = this.ReadString();
                return retVal;
            };
            singlarObjParser["MessageInfo"] = () =>
            {
                Dictionary<string, dynamic> retVal = new Dictionary<string, dynamic>();
                retVal["firstId1"] = this.ReadString();
                retVal["firstId2"] = this.ReadString();
                retVal["repeatId1"] = this.ReadString();
                retVal["repeatId2"] = this.ReadString();
                return retVal;
            };
            singlarObjParser["VehicleParked+Flags"] = () =>
            {
                return (VehicleParked.Flags)(this.ReadInt32());
            };
            singlarObjParser["Vehicle+Flags"] = () =>
            {
                return (Vehicle.Flags)(this.ReadInt32());
            };
            singlarObjParser["Building+Flags"] = () =>
            {
                return (Building.Flags)(this.ReadInt32());
            };
            singlarObjParser["VehicleInfo+VehicleType"] = () =>
            {
                return (VehicleInfo.VehicleType)(this.ReadInt32());
            };

            singlarObjParser["VehicleInfo+Effect"] = () =>
            {
                Dictionary<string, dynamic> retVal = new Dictionary<string, dynamic>();
                retVal["m_effect"] = this.ReadString();
                retVal["m_parkedFlagsForbidden"] = (VehicleParked.Flags)this.ReadInt32();
                retVal["m_parkedFlagsRequired"] = (VehicleParked.Flags)this.ReadInt32();
                retVal["m_vehicleFlagsForbidden"] = (Vehicle.Flags)this.ReadInt32();
                retVal["m_vehicleFlagsRequired"] = (Vehicle.Flags)this.ReadInt32();
                return retVal;
            };
            singlarObjParser["VehicleInfo+VehicleDoor"] = () =>
            {
                Dictionary<string, dynamic> retVal = new Dictionary<string, dynamic>();
                retVal["m_name"] = this.ReadString();
                retVal["m_position"] = singlarObjParser["UnityEngine.Vector3"]();
                return retVal;
            };
            singlarObjParser["VehicleInfo+VehicleTrailer"] = () =>
            {
                Dictionary<string, dynamic> retVal = new Dictionary<string, dynamic>();
                retVal["m_type"] = this.ReadInt32();
                retVal["m_probability"] = this.ReadInt32();
                retVal["m_invertprobability"] = this.ReadInt32();
                return retVal;
            };
            singlarObjParser["SteamHelper+DLC_BitMask"] = () =>
            {
                return (SteamHelper.DLC_BitMask)(this.ReadInt32());
            };
            singlarObjParser["ColossalFramework.Packaging.Package+Asset"] = () =>
            {
                return this.ReadString();
            };
            singlarObjParser["CustomAssetMetaData+Type"] = () =>
            {
                return (CustomAssetMetaData.Type)(this.ReadInt32());
            };
            singlarObjParser["UnityEngine.Transform"] = () =>
            {
                Transform transform = new Transform();
                transform.position = new Vector3(this.ReadSingle(), this.ReadSingle(), this.ReadSingle());
                transform.rotation = new Vector4(this.ReadSingle(), this.ReadSingle(), this.ReadSingle(), this.ReadSingle());
                transform.scale = new Vector3(this.ReadSingle(), this.ReadSingle(), this.ReadSingle());
                return transform;
            };
            singlarObjParser["UnityEngine.MeshFilter"] = () =>
            {
                return this.ReadString();
            };
            singlarObjParser["UnityEngine.MeshRenderer"] = () =>
            {
                int numEntries = this.ReadInt32();
                string[] retVal = new string[numEntries];
                for (int i = 0; i < numEntries; i++)
                {
                    retVal[i] = this.ReadString();
                }
                return retVal;
            };

            singlarObjParser["VehicleInfo"] = readGameInfo;
            singlarObjParser["BuildingInfo"] = readGameInfo;
            singlarObjParser["PropInfo"] = readGameInfo;
            singlarObjParser["BuildingInfoGen"] = () =>
            {
                return this.ReadString();
            };
            singlarObjParser["PropInfoGen"] = () =>
            {
                return this.ReadString();
            };
            singlarObjParser["VehicleInfoGen"] = () =>
            {
                return this.ReadString();
            };
            singlarObjParser["UnityEngine.GameObject"] = () =>
            {
                Dictionary<string, dynamic> retVal = new Dictionary<string, dynamic>();

                retVal["tag"] = this.ReadString();
                retVal["enabled"] = this.ReadBoolean();

                return retVal;
            };
            singlarObjParser["ResidentialBuildingAI"] = readGameInfo;
            singlarObjParser["CommercialBuildingAI"] = readGameInfo;
            singlarObjParser["OfficeBuildingAI"] = readGameInfo;
            singlarObjParser["IndustrialBuildingAI"] = readGameInfo;
            singlarObjParser["IndustrialExtractorAI"] = readGameInfo;
            singlarObjParser["IndustrialBuildingAI"] = readGameInfo;
            singlarObjParser["LivestockExtractorAI"] = readGameInfo;
        }
Esempio n. 35
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                if (ofd.ShowDialog() == DialogResult.OK)
                {

                    lblLoad.Text = "Loading: ";
                    String fName = ofd.FileName;
                    String sFName = ofd.FileName;
                    SBCFile = new XPathDocument(fName);
                    nav = SBCFile.CreateNavigator();
                    modListIt = nav.Select("//ModItem/PublishedFileId");

                    /*
                    txtOutRAW.Clear();

                    while (modListIt.MoveNext())
                    {

                        txtOutRAW.AppendText(modListIt.Current.InnerXml + "\r\n");

                    }
                    */

                    ModList.Clear();

                    while (modListIt.MoveNext())
                    {
                        ModInfo modInfo = new ModInfo();
                        modInfo.ID = modListIt.Current.InnerXml;
                        modInfo.URL = "http://steamcommunity.com/sharedfiles/filedetails/?id=" + modInfo.ID;
                        int failcount = 0;
                        do{
                        try
                        {

                            string workshopPage = web.DownloadString(modInfo.URL);
                            System.Threading.Thread.Sleep(500);
                            modInfo.title = Regex.Match(workshopPage, @"\<title\b[^>]*\>\s*(?<Title>[\s\S]*?)\</title\>", RegexOptions.IgnoreCase).Groups["Title"].Value;
                            modInfo.title = modInfo.title.Replace("Steam Workshop :: ", "");
                            if (failcount > 0) failcount = 0;

                        }
                        catch (Exception)
                        {
                            modInfo.title = "URL Timed Out";
                            failcount++;
                        }
                        }while(failcount>0&&failcount<4);
                        ModList.Add(modInfo);
                        lblLoad.Text += "|";
                        if(lblLoad.Text.TakeWhile(c => c == '|').Count()>10)
                        {
                            lblLoad.Text = "Loading: ";
                        }

                        lblLoad.Refresh();
                        Application.DoEvents();
                        System.Threading.Thread.Sleep(500);

                    }

                    ModList = ModList.OrderBy(m => m.ID).ToList();

                    txtOutRAW.Clear();
                    txtOut.Clear();
                    foreach (ModInfo MI in ModList)
                    {
                        txtOutRAW.AppendText(MI.ID + "\r\n");
                        StringBuilder tOut = new StringBuilder();
                        tOut.Append("ModID: " + MI.ID + "       ");
                        tOut.Append("ModName: " + MI.title + "      ");
                        tOut.Append("Workshop URL: " + MI.URL + "\r\n");
                        txtOut.AppendText(tOut.ToString());
                    }
                    lblLoad.Text = "File Loaded";

                    //old code deprecated
                    /*
                    while (modListIt.MoveNext())
                    {
                        StringBuilder outputStr = new StringBuilder();
                        string ID = modListIt.Current.InnerXml;
                        outputStr.Append("ModID>>   " + ID);
                        string URL =  "http://steamcommunity.com/sharedfiles/filedetails/?id=" + ID;
                        try{
                            string workshopPage = web.DownloadString(URL);
                        string title = Regex.Match(workshopPage, @"\<title\b[^>]*\>\s*(?<Title>[\s\S]*?)\</title\>", RegexOptions.IgnoreCase).Groups["Title"].Value;
                        title = title.Replace("Steam Workshop :: ", "");
                        outputStr.Append("  >>NAME>>    " + title);
                        }
                        catch(Exception)
                        {
                            outputStr.Append("      >>NAME>>         BadURL");
                        }
                        outputStr.Append("  >>LINK>>    " + URL);
                        outputStr.Append("\r\n");
                        txtOut.AppendText(outputStr.ToString());

                    }

                    */

                }

                else { txtOutRAW.Text = "Unable To Read File"; }

            }
            catch (Exception)
            {
                txtOutRAW.Text = "An Unknown Error Has Occurred";
            }
        }
Esempio n. 36
0
    // Returns an array of ModInfo records, in the 'correct'
    // order for the mod.

    private ModInfo[] BuildModInfo(string[] plugins)
    {
      var mi = new ModInfo[plugins.Length];
      var addcount = 1;
      var lastPos = -1;
      var maxPos = 0;
      for (var i = 0; i < mi.Length; i++)
      {
        var lplugin = plugins[i].ToLowerInvariant();
        if (m_dicMasterList.ContainsKey(lplugin))
        {
          lastPos = m_dicMasterList[lplugin].id;
          if (lastPos > maxPos)
          {
            maxPos = lastPos;
          }
          mi[i] = new ModInfo(plugins[i], lastPos, true);
          addcount = 1;
        }
        else
        {
          mi[i] = new ModInfo(plugins[i], lastPos + addcount*0.001, false);
          addcount++;
        }
      }
      addcount = 1;
      maxPos++;
      for (var i = mi.Length - 1; i >= 0; i--)
      {
        if (mi[i].hadEntry)
        {
          break;
        }
        mi[i].id = maxPos - addcount*0.001;
        addcount++;
      }
      return mi;
    }
Esempio n. 37
0
 public LoaderError(ModInfo info, string message = null, object data = null)
     : this(info.ModPath, message, data, info)
 {
 }
Esempio n. 38
0
        /// <summary>
        /// Loads a mod from an <see cref="System.Reflection.Assembly"/> and returns its <see cref="ModDef"/>.
        /// </summary>
        /// <param name="asm">The mod's <see cref="System.Reflection.Assembly"/></param>
        /// <param name="info">The mod's <see cref="ModInfo"/></param>
        /// <returns>The <see cref="ModDef"/> of the mod</returns>
        static ModDef LoadModFromAssembly(Assembly asm, ModInfo info)
        {
            var mdType = asm.GetType(info.ModDefTypeName, false);

            if (mdType == null)
            {
                errors.Add(new LoaderError(info, "ModDef type not found", info.ModDefTypeName));
                return null;
            }

            var mod = Activator.CreateInstance(mdType) as ModDef;

            if (mod == null)
            {
                errors.Add(new LoaderError(info, "Could not instantiate ModDef implementation", mdType));
                return null;
            }

            mod.Assembly = asm ;
            mod.Info     = info;

            // required by the entity def loader
            ModData.mods                .Add(mod.Info             , mod);
            ModData.modsFromInternalName.Add(mod.Info.InternalName, mod);

            mod.ContentHandler = mod.CreateContentHandlerInternally();
            mod.ContentHandler.Adopt(mod.Info);

            errors.AddRange(ResourceLoader .Load(mod));
            errors.AddRange(ContentLoader  .Load(mod));
            errors.AddRange(EntityDefLoader.Load(mod));

            return mod;
        }
        void OnGUI()
        {
            EditorGUI.indentLevel++;

            GUILayoutHelper.Horizontal(() =>
            {
                if (GUILayout.Button("Create New Mod"))
                {
                    fileOpen = true;
                    if(modInfo != null)
                    {
                        modInfo.DFUnity_Verion = VersionInfo.DaggerfallUnityVersion;
                    }
                }

                else if (GUILayout.Button("Open Existing Mod Settings File"))
                {
                    try
                    {
                        currentFilePath = EditorUtility.OpenFilePanelWithFilters("", Application.dataPath, new string[] { "JSON", "dfmod.json"});

                        if (!File.Exists(currentFilePath))
                        {
                            Debug.Log("Invalid file selection");
                            currentFilePath = null;
                            fileOpen = false;
                            return;
                        }

                        string inPut = File.ReadAllText(currentFilePath);
                        modInfo = (ModInfo)JsonUtility.FromJson(inPut, typeof(ModInfo));

                        Debug.Log(string.Format("opened mod file for: {0}", modInfo.ModTitle));

                    }
                    catch (Exception ex)
                    {
                        Debug.Log(string.Format("Error while trying to open mod file at: {0} \n {1}", currentFilePath, ex.Message));
                        currentFilePath = null;
                        fileOpen = false;
                        return;
                    }

                    fileOpen = true;
                }
            });

            if(modInfo == null)
            {
                fileOpen = false;
                modInfo = new ModInfo();
            }
            if (!fileOpen) // if no fileopen, hide rest of UI
                return;

            GUILayoutHelper.Vertical(() =>
            {
                EditorGUILayout.LabelField(new GUIContent("Mod File Path:" + currentFilePath));
                EditorGUI.indentLevel++;

                GUILayoutHelper.Vertical(() =>
                {
                    EditorGUILayout.Space();

                    GUILayoutHelper.Horizontal(() =>
                    {
                        EditorGUILayout.LabelField(new GUIContent("Mod File Name:"));
                        modInfo.ModFileName = EditorGUILayout.TextField(modInfo.ModFileName.ToLower(), GUILayout.MinWidth(600));
                    });

                    EditorGUILayout.Space();

                    GUILayoutHelper.Horizontal(() =>
                    {
                        EditorGUILayout.LabelField(new GUIContent("Mod Title:"));
                        modInfo.ModTitle = EditorGUILayout.TextField(modInfo.ModTitle, GUILayout.MinWidth(600));
                    });

                    EditorGUILayout.Space();

                    GUILayoutHelper.Horizontal(() =>
                    {

                        EditorGUILayout.LabelField(new GUIContent("Mod Version:"));
                        modInfo.ModVersion = EditorGUILayout.TextField(modInfo.ModVersion, GUILayout.MinWidth(600));
                    });

                    EditorGUILayout.Space();

                    GUILayoutHelper.Horizontal(() =>
                    {
                        EditorGUILayout.LabelField(new GUIContent("Mod Creator:"));
                        modInfo.ModAuthor = EditorGUILayout.TextField(modInfo.ModAuthor, GUILayout.MinWidth(600));
                    });

                    EditorGUILayout.Space();

                    GUILayoutHelper.Horizontal(() =>
                    {
                        EditorGUILayout.LabelField(new GUIContent("Contact Info:"));
                        modInfo.ContactInfo = EditorGUILayout.TextField(modInfo.ContactInfo, GUILayout.MinWidth(600));
                    });

                    EditorGUILayout.Space();

                    GUILayoutHelper.Horizontal(() =>
                    {
                        EditorGUILayout.LabelField(new GUIContent("DFUnity Version:"));
                        modInfo.DFUnity_Verion = EditorGUILayout.TextField(modInfo.DFUnity_Verion, GUILayout.MinWidth(600));
                    });

                    EditorGUILayout.Space();

                    GUILayoutHelper.Horizontal(() =>
                    {
                        EditorGUILayout.LabelField(new GUIContent("Mod Description:"));
                        modInfo.ModDescription = EditorGUILayout.TextArea(modInfo.ModDescription, GUILayout.MinWidth(600));
                    });

                });

                EditorGUILayout.Space();
                EditorGUI.indentLevel--;

                GUILayoutHelper.Horizontal(() =>
                {
                    if (GUILayout.Button("Add Selected Asset(s)"))
                        AddAssetToMod();

                    else if (GUILayout.Button("Remove Selected Asset(s)"))
                    {
                        if (Assets == null || Assets.Count < 1)
                            return;
                        else if (assetSelection < 0 || assetSelection > Assets.Count)
                            return;
                        else
                            Assets.RemoveAt(assetSelection);
                    }
                    else if (GUILayout.Button("Clear ALL Asset(s)"))
                    {
                        if (Assets != null)
                            Assets = new List<string>();
                    }

                });

            });

            EditorGUILayout.Space();

            ShowFileFoldOut = GUILayoutHelper.Foldout(ShowFileFoldOut, new GUIContent("Files"), () =>
            {
                scrollPos = GUILayoutHelper.ScrollView(scrollPos, () =>
                {
                    assetSelection = GUILayout.SelectionGrid(assetSelection, modInfo.Files.ToArray(), 1);
                });
            });

            EditorGUILayout.Space();
            EditorGUILayout.Space();

            GUILayoutHelper.Horizontal(() =>
            {

                if (GUILayout.Button("Save Mod Settings to File"))
                {
                    SaveModFile();
                    Debug.Log("got path: " + currentFilePath);
                }
                else if (GUILayout.Button("Build Mod"))
                {
                    SaveModFile();
                    BuildMod();
                }

            });
        }
Esempio n. 40
0
        /// <summary>
        /// Recursively checks and returns whether a mod has a circular mod reference and outputs the name of the circular reference if applicable.
        /// </summary>
        /// <param name="info">The <see cref="ModInfo"/> of the mod to check</param>
        /// <param name="evilMod">Outputs the <see cref="ModReference.Name"/> causing the circular references if applicable.</param>
        /// <returns>True if circular referencing is found. False if not.</returns>
        static bool CheckForCircularReferences(ModInfo info, out string evilMod)
        {
            evilMod = String.Empty;

            foreach (string refIName in info.References.OfType<ModReference>().Select(mr => mr.Name))
            {
                if (circRefList.Contains(refIName))
                {
                    evilMod = refIName;
                    return true;
                }

                List<string> temp = new List<string>(circRefList);

                circRefList.Add(refIName);

                var info_ = ModInfoFromInternalName(refIName);
                if (!info_.HasValue)
                {
                    errors.Add(new LoaderError(info, "Mod reference could not be found", refIName));
                    return false;
                }

                if (CheckForCircularReferences(info_.Value, out evilMod))
                    return true;

                circRefList = temp;
            }

            return false;
        }
Esempio n. 41
0
        /// <summary>
        /// Loads a mod from an <see cref="System.Reflection.Assembly"/> and returns its <see cref="ModDef"/>.
        /// </summary>
        /// <param name="asm">The mod's <see cref="System.Reflection.Assembly"/></param>
        /// <param name="info">The mod's <see cref="ModInfo"/></param>
        /// <returns>The <see cref="ModDef"/> of the mod</returns>
        static ModDef LoadModFromAssembly(Assembly asm, ModInfo info)
        {
            var mdType = asm.GetType(info.ModDefTypeName, false);

            if (mdType == null)
            {
                errors.Add(new LoaderError(info, "ModDef type not found", info.ModDefTypeName));
                return null;
            }

            ModDef mod = Activator.CreateInstance(mdType) as ModDef;

            if (mod == null)
            {
                errors.Add(new LoaderError(info, "Could not instantiate ModDef implementation", mdType));
                return null;
            }

            mod.Assembly = asm;
            mod.Info = info;

            errors.AddRange(ResourceLoader .Load(mod));
            errors.AddRange(EntityDefLoader.Load(mod));

            return mod;
        }
Esempio n. 42
0
 public LoaderError(ModInfo info, Exception e)
     : this(info.ModPath, e, info)
 {
 }
		/// <summary>
		/// Converts the native Nexus repository mod info data structure into an <see cref="IModInfo"/>
		/// structure.
		/// </summary>
		/// <param name="p_nmiNexusModInfo">The structure to convert.</param>
		/// <returns>The converted structure.</returns>
		private IModInfo Convert(NexusModInfo p_nmiNexusModInfo)
		{
			Uri uriWebsite = (String.IsNullOrEmpty(p_nmiNexusModInfo.Website) ? null : new Uri(p_nmiNexusModInfo.Website));
			ModInfo mifInfo = new ModInfo(p_nmiNexusModInfo.Id, p_nmiNexusModInfo.Name, p_nmiNexusModInfo.HumanReadableVersion, p_nmiNexusModInfo.HumanReadableVersion, p_nmiNexusModInfo.IsEndorsed, null, p_nmiNexusModInfo.Author, p_nmiNexusModInfo.CategoryId, -1, p_nmiNexusModInfo.Description, null, uriWebsite, null);
			return mifInfo;
		}
        /// <summary>
        /// Downloads a mod from KSP Spaceport.
        /// </summary>
        /// <param name="modInfo"></param>
        /// <returns></returns>
        public static bool DownloadMod(string downloadURL, ref ModInfo modInfo, DownloadProgressChangedEventHandler downloadProgressHandler = null)
        {
            if (modInfo == null || string.IsNullOrEmpty(downloadURL))
                return false;

            // get save path 
            string filename = downloadURL;
            int start = filename.LastIndexOf("?");
            if (start > -1)
            {
                string filenameA = filename.Substring(0, start);
                string filenameB = filename.Substring(start + 1);
                Regex regEx = new Regex("[.](zip)|(rar)|(7zip)");
                if (regEx.IsMatch(filenameA))
                    filename = filenameA;
                else if (regEx.IsMatch(filenameB))
                    filename = filenameB;
                else
                    return false;
            }
            start = filename.LastIndexOf("/") + 1;
            filename = filename.Substring(start, filename.Length - start);
            modInfo.LocalPath = Path.Combine(OptionsController.DownloadPath, filename);
            www.DownloadFile(downloadURL, modInfo.LocalPath, downloadProgressHandler);

            return true;
        }
        /// <summary>
        /// Starts a async download of a mod from KSP Spaceport.
        /// </summary>
        /// <param name="modInfo"></param>
        /// <param name="finished"></param>
        /// <param name="progressChanged"></param>
        public static void DownloadModAsync(string downloadURL, ref ModInfo modInfo, AsyncResultHandler<bool> finished = null, AsyncProgressChangedHandler progressChanged = null)
        {
            // get save path 
            int start = downloadURL.LastIndexOf("/") + 1;
            string filename = downloadURL.Substring(start, downloadURL.Length - start);
            modInfo.LocalPath = Path.Combine(downloadURL, filename);

            AsyncTask<bool> asyncJob = new AsyncTask<bool>();
            asyncJob.SetDownloadCallbackFunctions(modInfo.SpaceportURL, modInfo.LocalPath, finished, progressChanged);
            asyncJob.RunDownload(); ;
        }
        /// <summary>
        /// Parses the siteContent for ModInfo data.
        /// </summary>
        /// <param name="siteContent">The KSP Forum sites content for a mod.</param>
        /// <param name="modInfo">The ModInfo to fill with the data of the site.</param>
        private static bool ParseSite(string siteContent, ref ModInfo modInfo)
        {
            // get threadID
            int index = siteContent.IndexOf("var RELPATH = \"threads/");
            if (index < 0) return false;
            siteContent = siteContent.Substring(index + 23);
            index = siteContent.IndexOf("-");
            if (index < 0) return false;
            modInfo.ProductID = siteContent.Substring(0, index).Trim();

            //get mod title
            index = siteContent.IndexOf("<title>");
            if (index < 0) return false;
            siteContent = siteContent.Substring(index + 7);
            index = siteContent.IndexOf("</title>");
            if (index < 0) return false;
            modInfo.Name = siteContent.Substring(0, index).Trim();

            // get rating
            index = siteContent.IndexOf("<li id=\"threadrating_current\" title=\"Thread Rating: ");
            if (index >= 0)
            {
                siteContent = siteContent.Substring(index + 52);
                index = siteContent.IndexOf(" votes,");
                string votes = siteContent.Substring(0, index).Trim();
                siteContent = siteContent.Substring(index + 7);
                index = siteContent.IndexOf(" average.");
                string rating = siteContent.Substring(0, index).Trim();
                modInfo.Rating = string.Format("{0}({1})", rating, votes);
            }

            // get author
            index = siteContent.IndexOf("Last edited by ");
            if (index < 0) return false;
            siteContent = siteContent.Substring(index + 15);
            index = siteContent.IndexOf(";");
            if (index < 0) return false;
            modInfo.Author = siteContent.Substring(0, index).Trim();
            modInfo.Author = modInfo.Author.Replace("</a>", "").Trim();
            siteContent = siteContent.Substring(index);

            // get edit date
            index = siteContent.IndexOf("</span>") - 1;
            if (index < 0) return false;
            string temp = siteContent.Substring(1, index);
            temp = temp.Replace(" at", "");
            temp = temp.Replace("<span class=\"time\">", "");
            if (temp.Contains("Yesterday"))
                temp = temp.Replace("Yesterday", DateTime.Now.AddDays(-1).ToString("dd.MM.yyyy"));
            else if (temp.Contains("Today"))
                temp = temp.Replace("Today", DateTime.Now.ToString("dd.MM.yyyy"));
            else
            {
                temp = temp.Replace("st ", " ");
                temp = temp.Replace("nd ", " ");
                temp = temp.Replace("rd ", " ");
                temp = temp.Replace("th ", " ");
            }

            DateTime dtCreationDate = DateTime.Now;
            modInfo.CreationDate = (DateTime.TryParse(temp, out dtCreationDate)) ? dtCreationDate.ToString() : DateTime.Now.ToString();

            // more infos could be parsed here (like: short description, Tab content (overview, installation, ...), comments, ...)
            return true;
        }
Esempio n. 47
0
        public static ModInfo readInfo(String modInfo)
        {
            String activeMod;
            ModInfo info = new ModInfo();
            String xmlInput = new System.IO.StreamReader(modInfo).ReadToEnd();
            try
            {
                using (XmlReader reader = XmlReader.Create(new StringReader(xmlInput)))
                {
                    reader.ReadToFollowing("ActiveMod");//Skips to first element
                    reader.MoveToAttribute("Name");
                    activeMod = reader.Value;
                    while (reader.ReadToFollowing("ActiveAddon"))
                    {
                        reader.MoveToAttribute("Name");
                        info.addAddon(reader.Value);
                    }
                }
            }
            catch (Exception)
            {
                throw new System.FormatException("Error in XML file, are you sure it's formatted right?");
            }

            info.activeMod = activeMod;
            return info;
        }
 void OnEnable()
 {
     if (!fileOpen)
         modInfo = new ModInfo();
 }