public frmSelectSkillGroup() { InitializeComponent(); LanguageManager.Load(GlobalOptions.Language, this); _objXmlDocument = XmlManager.Load("skills.xml"); }
/// <summary> /// Update the labels and images based on the selected treenode. /// </summary> /// <param name="objCache"></param> private void UpdateCharacter(HeroLabCharacterCache objCache) { if (objCache != null) { txtCharacterBio.Text = objCache.Description; string strUnknown = LanguageManager.GetString("String_Unknown"); string strNone = LanguageManager.GetString("String_None"); lblCharacterName.Text = objCache.CharacterName; if (string.IsNullOrEmpty(lblCharacterName.Text)) { lblCharacterName.Text = strUnknown; } lblCharacterNameLabel.Visible = !string.IsNullOrEmpty(lblCharacterName.Text); lblCharacterName.Visible = !string.IsNullOrEmpty(lblCharacterName.Text); lblCharacterAlias.Text = objCache.CharacterAlias; if (string.IsNullOrEmpty(lblCharacterAlias.Text)) { lblCharacterAlias.Text = strUnknown; } lblCharacterAliasLabel.Visible = !string.IsNullOrEmpty(lblCharacterAlias.Text); lblCharacterAlias.Visible = !string.IsNullOrEmpty(lblCharacterAlias.Text); lblPlayerName.Text = objCache.PlayerName; if (string.IsNullOrEmpty(lblPlayerName.Text)) { lblPlayerName.Text = strUnknown; } lblPlayerNameLabel.Visible = !string.IsNullOrEmpty(lblPlayerName.Text); lblPlayerName.Visible = !string.IsNullOrEmpty(lblPlayerName.Text); lblCareerKarma.Text = objCache.Karma; if (string.IsNullOrEmpty(lblCareerKarma.Text) || lblCareerKarma.Text == 0.ToString(GlobalOptions.CultureInfo)) { lblCareerKarma.Text = strNone; } lblCareerKarmaLabel.Visible = !string.IsNullOrEmpty(lblCareerKarma.Text); lblCareerKarma.Visible = !string.IsNullOrEmpty(lblCareerKarma.Text); lblEssence.Text = objCache.Essence; if (string.IsNullOrEmpty(lblEssence.Text)) { lblEssence.Text = strUnknown; } lblEssenceLabel.Visible = !string.IsNullOrEmpty(lblEssence.Text); lblEssence.Visible = !string.IsNullOrEmpty(lblEssence.Text); picMugshot.Image = objCache.Mugshot; // Populate character information fields. XmlDocument objMetatypeDoc = XmlManager.Load("metatypes.xml"); XmlNode objMetatypeNode = objMetatypeDoc.SelectSingleNode("/chummer/metatypes/metatype[name = \"" + objCache.Metatype + "\"]"); if (objMetatypeNode == null) { objMetatypeDoc = XmlManager.Load("critters.xml"); objMetatypeNode = objMetatypeDoc.SelectSingleNode("/chummer/metatypes/metatype[name = \"" + objCache.Metatype + "\"]"); } string strMetatype = objMetatypeNode?["translate"]?.InnerText ?? objCache.Metatype; if (!string.IsNullOrEmpty(objCache.Metavariant) && objCache.Metavariant != "None") { objMetatypeNode = objMetatypeNode?.SelectSingleNode("metavariants/metavariant[name = \"" + objCache.Metavariant + "\"]"); strMetatype += " (" + (objMetatypeNode?["translate"]?.InnerText ?? objCache.Metavariant) + ')'; } lblMetatype.Text = strMetatype; if (string.IsNullOrEmpty(lblMetatype.Text)) { lblMetatype.Text = strUnknown; } lblMetatypeLabel.Visible = !string.IsNullOrEmpty(lblMetatype.Text); lblMetatype.Visible = !string.IsNullOrEmpty(lblMetatype.Text); cmdImport.Enabled = true; } else { txtCharacterBio.Text = string.Empty; lblCharacterNameLabel.Visible = false; lblCharacterName.Visible = false; lblCharacterAliasLabel.Visible = false; lblCharacterAlias.Visible = false; lblPlayerNameLabel.Visible = false; lblPlayerName.Visible = false; lblMetatypeLabel.Visible = false; lblMetatype.Visible = false; lblCareerKarmaLabel.Visible = false; lblCareerKarma.Visible = false; lblEssenceLabel.Visible = false; lblEssence.Visible = false; picMugshot.Image = null; cmdImport.Enabled = false; } picMugshot_SizeChanged(null, EventArgs.Empty); }
/// <summary> /// Update the labels and images based on the selected treenode. /// </summary> /// <param name="objCache"></param> public void UpdateCharacter(CharacterCache objCache) { if (Disposing || IsDisposed) // Safety check for external calls { return; } tlpCharacterRoster.SuspendLayout(); if (objCache != null) { string strUnknown = LanguageManager.GetString("String_Unknown"); string strNone = LanguageManager.GetString("String_None"); txtCharacterBio.Text = objCache.Description.RtfToPlainText(); txtCharacterBackground.Text = objCache.Background.RtfToPlainText(); txtCharacterNotes.Text = objCache.CharacterNotes.RtfToPlainText(); txtGameNotes.Text = objCache.GameNotes.RtfToPlainText(); txtCharacterConcept.Text = objCache.Concept.RtfToPlainText(); lblCareerKarma.Text = objCache.Karma; if (string.IsNullOrEmpty(lblCareerKarma.Text) || lblCareerKarma.Text == 0.ToString(GlobalOptions.CultureInfo)) { lblCareerKarma.Text = strNone; } lblPlayerName.Text = objCache.PlayerName; if (string.IsNullOrEmpty(lblPlayerName.Text)) { lblPlayerName.Text = strUnknown; } lblCharacterName.Text = objCache.CharacterName; if (string.IsNullOrEmpty(lblCharacterName.Text)) { lblCharacterName.Text = strUnknown; } lblCharacterAlias.Text = objCache.CharacterAlias; if (string.IsNullOrEmpty(lblCharacterAlias.Text)) { lblCharacterAlias.Text = strUnknown; } lblEssence.Text = objCache.Essence; if (string.IsNullOrEmpty(lblEssence.Text)) { lblEssence.Text = strUnknown; } lblFilePath.Text = objCache.FileName; if (string.IsNullOrEmpty(lblFilePath.Text)) { lblFilePath.Text = LanguageManager.GetString("MessageTitle_FileNotFound"); } lblSettings.Text = objCache.SettingsFile; if (string.IsNullOrEmpty(lblSettings.Text)) { lblSettings.Text = strUnknown; } lblFilePath.SetToolTip(objCache.FilePath.CheapReplace(Utils.GetStartupPath, () => '<' + Application.ProductName + '>')); picMugshot.Image?.Dispose(); picMugshot.Image = objCache.Mugshot; // Populate character information fields. XPathNavigator objMetatypeDoc = XmlManager.LoadXPath("metatypes.xml"); if (objCache.Metatype != null) { XPathNavigator objMetatypeNode = objMetatypeDoc.SelectSingleNode("/chummer/metatypes/metatype[name = " + objCache.Metatype?.CleanXPath() + "]"); if (objMetatypeNode == null) { objMetatypeDoc = XmlManager.LoadXPath("critters.xml"); objMetatypeNode = objMetatypeDoc.SelectSingleNode("/chummer/metatypes/metatype[name = " + objCache.Metatype?.CleanXPath() + "]"); } string strMetatype = objMetatypeNode?.SelectSingleNode("translate")?.Value ?? objCache.Metatype; if (!string.IsNullOrEmpty(objCache.Metavariant) && objCache.Metavariant != "None") { objMetatypeNode = objMetatypeNode?.SelectSingleNode("metavariants/metavariant[name = " + objCache.Metavariant.CleanXPath() + "]"); strMetatype += LanguageManager.GetString("String_Space") + '(' + (objMetatypeNode?.SelectSingleNode("translate")?.Value ?? objCache.Metavariant) + ')'; } lblMetatype.Text = strMetatype; } else { lblMetatype.Text = LanguageManager.GetString("String_MetatypeLoadError"); } tabCharacterText.Visible = true; if (!string.IsNullOrEmpty(objCache.ErrorText)) { txtCharacterBio.Text = objCache.ErrorText; txtCharacterBio.ForeColor = ColorManager.ErrorColor; txtCharacterBio.BringToFront(); } else { txtCharacterBio.ForeColor = ColorManager.WindowText; } } else { tabCharacterText.Visible = false; txtCharacterBio.Clear(); txtCharacterBackground.Clear(); txtCharacterNotes.Clear(); txtGameNotes.Clear(); txtCharacterConcept.Clear(); lblCareerKarma.Text = string.Empty; lblMetatype.Text = string.Empty; lblPlayerName.Text = string.Empty; lblCharacterName.Text = string.Empty; lblCharacterAlias.Text = string.Empty; lblEssence.Text = string.Empty; lblFilePath.Text = string.Empty; lblFilePath.SetToolTip(string.Empty); lblSettings.Text = string.Empty; picMugshot.Image = null; } lblCareerKarmaLabel.Visible = !string.IsNullOrEmpty(lblCareerKarma.Text); lblMetatypeLabel.Visible = !string.IsNullOrEmpty(lblMetatype.Text); lblPlayerNameLabel.Visible = !string.IsNullOrEmpty(lblPlayerName.Text); lblCharacterNameLabel.Visible = !string.IsNullOrEmpty(lblCharacterName.Text); lblCharacterAliasLabel.Visible = !string.IsNullOrEmpty(lblCharacterAlias.Text); lblEssenceLabel.Visible = !string.IsNullOrEmpty(lblEssence.Text); lblFilePathLabel.Visible = !string.IsNullOrEmpty(lblFilePath.Text); lblSettingsLabel.Visible = !string.IsNullOrEmpty(lblSettings.Text); ProcessMugshotSizeMode(); tlpCharacterRoster.ResumeLayout(); }
/// <summary> /// Create a Critter, put them into Career Mode, link them, and open the newly-created Critter. /// </summary> /// <param name="strCritterName">Name of the Critter's Metatype.</param> /// <param name="intForce">Critter's Force.</param> private async void CreateCritter(string strCritterName, int intForce) { // Code from frmMetatype. XmlDocument objXmlDocument = XmlManager.Load("critters.xml"); XmlNode objXmlMetatype = objXmlDocument.SelectSingleNode("/chummer/metatypes/metatype[name = \"" + strCritterName + "\"]"); // If the Critter could not be found, show an error and get out of here. if (objXmlMetatype == null) { MessageBox.Show(string.Format(LanguageManager.GetString("Message_UnknownCritterType", GlobalOptions.Language), strCritterName), LanguageManager.GetString("MessageTitle_SelectCritterType", GlobalOptions.Language), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // The Critter should use the same settings file as the character. Character objCharacter = new Character { SettingsFile = _objSpirit.CharacterObject.SettingsFile, // Override the defaults for the setting. IgnoreRules = true, IsCritter = true, BuildMethod = CharacterBuildMethod.Karma }; if (!string.IsNullOrEmpty(txtCritterName.Text)) { objCharacter.Name = txtCritterName.Text; } // Ask the user to select a filename for the new character. string strForce = LanguageManager.GetString("String_Force", GlobalOptions.Language); if (_objSpirit.EntityType == SpiritType.Sprite) { strForce = LanguageManager.GetString("String_Rating", GlobalOptions.Language); } string strSpaceCharacter = LanguageManager.GetString("String_Space", GlobalOptions.Language); SaveFileDialog saveFileDialog = new SaveFileDialog { Filter = LanguageManager.GetString("DialogFilter_Chum5", GlobalOptions.Language) + '|' + LanguageManager.GetString("DialogFilter_All", GlobalOptions.Language), FileName = strCritterName + strSpaceCharacter + '(' + strForce + strSpaceCharacter + _objSpirit.Force.ToString() + ").chum5" }; if (saveFileDialog.ShowDialog(this) == DialogResult.OK) { string strFileName = saveFileDialog.FileName; objCharacter.FileName = strFileName; } else { objCharacter.DeleteCharacter(); return; } Cursor = Cursors.WaitCursor; // Set Metatype information. if (strCritterName == "Ally Spirit") { objCharacter.BOD.AssignLimits(ExpressionToString(objXmlMetatype["bodmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["bodmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["bodaug"]?.InnerText, intForce, 0)); objCharacter.AGI.AssignLimits(ExpressionToString(objXmlMetatype["agimin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["agimax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["agiaug"]?.InnerText, intForce, 0)); objCharacter.REA.AssignLimits(ExpressionToString(objXmlMetatype["reamin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["reamax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["reaaug"]?.InnerText, intForce, 0)); objCharacter.STR.AssignLimits(ExpressionToString(objXmlMetatype["strmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["strmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["straug"]?.InnerText, intForce, 0)); objCharacter.CHA.AssignLimits(ExpressionToString(objXmlMetatype["chamin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["chamax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["chaaug"]?.InnerText, intForce, 0)); objCharacter.INT.AssignLimits(ExpressionToString(objXmlMetatype["intmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["intmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["intaug"]?.InnerText, intForce, 0)); objCharacter.LOG.AssignLimits(ExpressionToString(objXmlMetatype["logmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["logmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["logaug"]?.InnerText, intForce, 0)); objCharacter.WIL.AssignLimits(ExpressionToString(objXmlMetatype["wilmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["wilmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["wilaug"]?.InnerText, intForce, 0)); objCharacter.MAG.AssignLimits(ExpressionToString(objXmlMetatype["magmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["magmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["magaug"]?.InnerText, intForce, 0)); objCharacter.RES.AssignLimits(ExpressionToString(objXmlMetatype["resmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["resmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["resaug"]?.InnerText, intForce, 0)); objCharacter.EDG.AssignLimits(ExpressionToString(objXmlMetatype["edgmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["edgmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["edgaug"]?.InnerText, intForce, 0)); objCharacter.ESS.AssignLimits(ExpressionToString(objXmlMetatype["essmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["essmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["essaug"]?.InnerText, intForce, 0)); } else { int intMinModifier = -3; objCharacter.BOD.AssignLimits(ExpressionToString(objXmlMetatype["bodmin"]?.InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["bodmin"]?.InnerText, intForce, 3), ExpressionToString(objXmlMetatype["bodmin"]?.InnerText, intForce, 3)); objCharacter.AGI.AssignLimits(ExpressionToString(objXmlMetatype["agimin"]?.InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["agimin"]?.InnerText, intForce, 3), ExpressionToString(objXmlMetatype["agimin"]?.InnerText, intForce, 3)); objCharacter.REA.AssignLimits(ExpressionToString(objXmlMetatype["reamin"]?.InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["reamin"]?.InnerText, intForce, 3), ExpressionToString(objXmlMetatype["reamin"]?.InnerText, intForce, 3)); objCharacter.STR.AssignLimits(ExpressionToString(objXmlMetatype["strmin"]?.InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["strmin"]?.InnerText, intForce, 3), ExpressionToString(objXmlMetatype["strmin"]?.InnerText, intForce, 3)); objCharacter.CHA.AssignLimits(ExpressionToString(objXmlMetatype["chamin"]?.InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["chamin"]?.InnerText, intForce, 3), ExpressionToString(objXmlMetatype["chamin"]?.InnerText, intForce, 3)); objCharacter.INT.AssignLimits(ExpressionToString(objXmlMetatype["intmin"]?.InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["intmin"]?.InnerText, intForce, 3), ExpressionToString(objXmlMetatype["intmin"]?.InnerText, intForce, 3)); objCharacter.LOG.AssignLimits(ExpressionToString(objXmlMetatype["logmin"]?.InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["logmin"]?.InnerText, intForce, 3), ExpressionToString(objXmlMetatype["logmin"]?.InnerText, intForce, 3)); objCharacter.WIL.AssignLimits(ExpressionToString(objXmlMetatype["wilmin"]?.InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["wilmin"]?.InnerText, intForce, 3), ExpressionToString(objXmlMetatype["wilmin"]?.InnerText, intForce, 3)); objCharacter.MAG.AssignLimits(ExpressionToString(objXmlMetatype["magmin"]?.InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["magmin"]?.InnerText, intForce, 3), ExpressionToString(objXmlMetatype["magmin"]?.InnerText, intForce, 3)); objCharacter.RES.AssignLimits(ExpressionToString(objXmlMetatype["resmin"]?.InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["resmin"]?.InnerText, intForce, 3), ExpressionToString(objXmlMetatype["resmin"]?.InnerText, intForce, 3)); objCharacter.EDG.AssignLimits(ExpressionToString(objXmlMetatype["edgmin"]?.InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["edgmin"]?.InnerText, intForce, 3), ExpressionToString(objXmlMetatype["edgmin"]?.InnerText, intForce, 3)); objCharacter.ESS.AssignLimits(ExpressionToString(objXmlMetatype["essmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["essmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["essaug"]?.InnerText, intForce, 0)); } // If we're working with a Critter, set the Attributes to their default values. objCharacter.BOD.MetatypeMinimum = ExpressionToInt(objXmlMetatype["bodmin"]?.InnerText, intForce, 0); objCharacter.AGI.MetatypeMinimum = ExpressionToInt(objXmlMetatype["agimin"]?.InnerText, intForce, 0); objCharacter.REA.MetatypeMinimum = ExpressionToInt(objXmlMetatype["reamin"]?.InnerText, intForce, 0); objCharacter.STR.MetatypeMinimum = ExpressionToInt(objXmlMetatype["strmin"]?.InnerText, intForce, 0); objCharacter.CHA.MetatypeMinimum = ExpressionToInt(objXmlMetatype["chamin"]?.InnerText, intForce, 0); objCharacter.INT.MetatypeMinimum = ExpressionToInt(objXmlMetatype["intmin"]?.InnerText, intForce, 0); objCharacter.LOG.MetatypeMinimum = ExpressionToInt(objXmlMetatype["logmin"]?.InnerText, intForce, 0); objCharacter.WIL.MetatypeMinimum = ExpressionToInt(objXmlMetatype["wilmin"]?.InnerText, intForce, 0); objCharacter.MAG.MetatypeMinimum = ExpressionToInt(objXmlMetatype["magmin"]?.InnerText, intForce, 0); objCharacter.RES.MetatypeMinimum = ExpressionToInt(objXmlMetatype["resmin"]?.InnerText, intForce, 0); objCharacter.EDG.MetatypeMinimum = ExpressionToInt(objXmlMetatype["edgmin"]?.InnerText, intForce, 0); objCharacter.ESS.MetatypeMinimum = ExpressionToInt(objXmlMetatype["essmax"]?.InnerText, intForce, 0); // Sprites can never have Physical Attributes. if (objXmlMetatype["category"].InnerText.EndsWith("Sprite")) { objCharacter.BOD.AssignLimits("0", "0", "0"); objCharacter.AGI.AssignLimits("0", "0", "0"); objCharacter.REA.AssignLimits("0", "0", "0"); objCharacter.STR.AssignLimits("0", "0", "0"); } objCharacter.Metatype = strCritterName; objCharacter.MetatypeCategory = objXmlMetatype["category"].InnerText; objCharacter.Metavariant = string.Empty; objCharacter.MetatypeBP = 0; if (objXmlMetatype["movement"] != null) { objCharacter.Movement = objXmlMetatype["movement"].InnerText; } // Load the Qualities file. XmlDocument objXmlQualityDocument = XmlManager.Load("qualities.xml"); // Determine if the Metatype has any bonuses. if (objXmlMetatype.InnerXml.Contains("bonus")) { ImprovementManager.CreateImprovements(objCharacter, Improvement.ImprovementSource.Metatype, strCritterName, objXmlMetatype.SelectSingleNode("bonus"), false, 1, strCritterName); } // Create the Qualities that come with the Metatype. foreach (XmlNode objXmlQualityItem in objXmlMetatype.SelectNodes("qualities/*/quality")) { XmlNode objXmlQuality = objXmlQualityDocument.SelectSingleNode("/chummer/qualities/quality[name = \"" + objXmlQualityItem.InnerText + "\"]"); List <Weapon> lstWeapons = new List <Weapon>(); Quality objQuality = new Quality(objCharacter); string strForceValue = objXmlQualityItem.Attributes?["select"]?.InnerText ?? string.Empty; QualitySource objSource = objXmlQualityItem.Attributes["removable"]?.InnerText == bool.TrueString ? QualitySource.MetatypeRemovable : QualitySource.Metatype; objQuality.Create(objXmlQuality, objSource, lstWeapons, strForceValue); objCharacter.Qualities.Add(objQuality); // Add any created Weapons to the character. foreach (Weapon objWeapon in lstWeapons) { objCharacter.Weapons.Add(objWeapon); } } // Add any Critter Powers the Metatype/Critter should have. XmlNode objXmlCritter = objXmlDocument.SelectSingleNode("/chummer/metatypes/metatype[name = \"" + objCharacter.Metatype + "\"]"); objXmlDocument = XmlManager.Load("critterpowers.xml"); foreach (XmlNode objXmlPower in objXmlCritter.SelectNodes("powers/power")) { XmlNode objXmlCritterPower = objXmlDocument.SelectSingleNode("/chummer/powers/power[name = \"" + objXmlPower.InnerText + "\"]"); CritterPower objPower = new CritterPower(objCharacter); string strForcedValue = objXmlPower.Attributes?["select"]?.InnerText ?? string.Empty; int intRating = Convert.ToInt32(objXmlPower.Attributes?["rating"]?.InnerText); objPower.Create(objXmlCritterPower, intRating, strForcedValue); objCharacter.CritterPowers.Add(objPower); } if (objXmlCritter["optionalpowers"] != null) { //For every 3 full points of Force a spirit has, it may gain one Optional Power. for (int i = intForce - 3; i >= 0; i -= 3) { XmlDocument objDummyDocument = new XmlDocument(); XmlNode bonusNode = objDummyDocument.CreateNode(XmlNodeType.Element, "bonus", null); objDummyDocument.AppendChild(bonusNode); XmlNode powerNode = objDummyDocument.ImportNode(objXmlMetatype["optionalpowers"].CloneNode(true), true); objDummyDocument.ImportNode(powerNode, true); bonusNode.AppendChild(powerNode); ImprovementManager.CreateImprovements(objCharacter, Improvement.ImprovementSource.Metatype, objCharacter.Metatype, bonusNode, false, 1, objCharacter.Metatype); } } // Add any Complex Forms the Critter comes with (typically Sprites) XmlDocument objXmlProgramDocument = XmlManager.Load("complexforms.xml"); foreach (XmlNode objXmlComplexForm in objXmlCritter.SelectNodes("complexforms/complexform")) { string strForceValue = objXmlComplexForm.Attributes?["select"]?.InnerText ?? string.Empty; XmlNode objXmlComplexFormData = objXmlProgramDocument.SelectSingleNode("/chummer/complexforms/complexform[name = \"" + objXmlComplexForm.InnerText + "\"]"); ComplexForm objComplexForm = new ComplexForm(objCharacter); objComplexForm.Create(objXmlComplexFormData, strForceValue); objCharacter.ComplexForms.Add(objComplexForm); } // Add any Gear the Critter comes with (typically Programs for A.I.s) XmlDocument objXmlGearDocument = XmlManager.Load("gear.xml"); foreach (XmlNode objXmlGear in objXmlCritter.SelectNodes("gears/gear")) { int intRating = 0; if (objXmlGear.Attributes["rating"] != null) { intRating = ExpressionToInt(objXmlGear.Attributes["rating"].InnerText, decimal.ToInt32(nudForce.Value), 0); } string strForceValue = objXmlGear.Attributes?["select"]?.InnerText ?? string.Empty; XmlNode objXmlGearItem = objXmlGearDocument.SelectSingleNode("/chummer/gears/gear[name = " + objXmlGear.InnerText.CleanXPath() + "]"); Gear objGear = new Gear(objCharacter); List <Weapon> lstWeapons = new List <Weapon>(); objGear.Create(objXmlGearItem, intRating, lstWeapons, strForceValue); objGear.Cost = "0"; objCharacter.Gear.Add(objGear); } // Add the Unarmed Attack Weapon to the character. objXmlDocument = XmlManager.Load("weapons.xml"); XmlNode objXmlWeapon = objXmlDocument.SelectSingleNode("/chummer/weapons/weapon[name = \"Unarmed Attack\"]"); if (objXmlWeapon != null) { List <Weapon> lstWeapons = new List <Weapon>(); Weapon objWeapon = new Weapon(objCharacter); objWeapon.Create(objXmlWeapon, lstWeapons); objWeapon.ParentID = Guid.NewGuid().ToString("D"); // Unarmed Attack can never be removed objCharacter.Weapons.Add(objWeapon); foreach (Weapon objLoopWeapon in lstWeapons) { objCharacter.Weapons.Add(objLoopWeapon); } } objCharacter.Alias = strCritterName; objCharacter.Created = true; if (!objCharacter.Save()) { Cursor = Cursors.Default; objCharacter.DeleteCharacter(); return; } string strOpenFile = objCharacter.FileName; objCharacter.DeleteCharacter(); // Link the newly-created Critter to the Spirit. _objSpirit.FileName = strOpenFile; imgLink.SetToolTip(LanguageManager.GetString(_objSpirit.EntityType == SpiritType.Spirit ? "Tip_Spirit_OpenFile" : "Tip_Sprite_OpenFile", GlobalOptions.Language)); ContactDetailChanged?.Invoke(this, null); Character objOpenCharacter = await Program.MainForm.LoadCharacter(strOpenFile); Cursor = Cursors.Default; Program.MainForm.OpenCharacter(objOpenCharacter); }
private void frmSelectProgram_Load(object sender, EventArgs e) { foreach (Label objLabel in Controls.OfType <Label>()) { if (objLabel.Text.StartsWith('[')) { objLabel.Text = string.Empty; } } // Populate the Program list. XmlNodeList objXmlNodeList = _objXmlDocument.SelectNodes("/chummer/complexforms/complexform[" + _objCharacter.Options.BookXPath() + "]"); bool blnCheckForOptional = false; XmlNode objXmlCritter = null; if (_objCharacter.IsCritter) { XmlDocument objXmlCritterDocument = XmlManager.Load("critters.xml"); objXmlCritter = objXmlCritterDocument.SelectSingleNode("/chummer/metatypes/metatype[name = \"" + _objCharacter.Metatype + "\"]"); if (objXmlCritter.InnerXml.Contains("<optionalcomplexforms>")) { blnCheckForOptional = true; } } /* * // Check to see if the character has the Biowire Echo. * foreach (Metamagic objMetamagic in _objCharacter.Metamagics) * { * if (objMetamagic.Name == "Biowire") * _blnBiowireEnabled = true; * } */ trePrograms.TreeViewNodeSorter = new SortByName(); foreach (XmlNode objXmlProgram in objXmlNodeList) { bool blnAdd = true; TreeNode nodProgram = new TreeNode(); nodProgram.Text = objXmlProgram["translate"]?.InnerText ?? objXmlProgram["name"].InnerText; nodProgram.Tag = objXmlProgram["id"].InnerText; // If this is a Sprite with Optional Complex Forms, see if this Complex Form is allowed. if (blnCheckForOptional) { blnAdd = false; foreach (XmlNode objXmlForm in objXmlCritter?.SelectNodes("optionalcomplexforms/complexform")) { if (objXmlForm.InnerText == objXmlProgram["name"].InnerText) { blnAdd = true; } } } // Add the Program to the Category node. if (blnAdd) { trePrograms.Nodes.Add(nodProgram); } } trePrograms.Nodes[0].Expand(); }
private void mnuNewCritter_Click(object sender, EventArgs e) { Character objCharacter = new Character(); string settingsPath = Path.Combine(Application.StartupPath, "settings"); string[] settingsFiles = Directory.GetFiles(settingsPath, "*.xml"); if (settingsFiles.Length > 1) { frmSelectSetting frmPickSetting = new frmSelectSetting(); frmPickSetting.ShowDialog(this); if (frmPickSetting.DialogResult == DialogResult.Cancel) { return; } objCharacter.SettingsFile = frmPickSetting.SettingsFile; } else { string strSettingsFile = settingsFiles[0]; objCharacter.SettingsFile = Path.GetFileName(strSettingsFile); } // Override the defaults for the setting. objCharacter.IgnoreRules = true; objCharacter.IsCritter = true; objCharacter.Created = true; objCharacter.BuildMethod = CharacterBuildMethod.Karma; objCharacter.BuildPoints = 0; // Show the Metatype selection window. frmKarmaMetatype frmSelectMetatype = new frmKarmaMetatype(objCharacter); frmSelectMetatype.XmlFile = "critters.xml"; frmSelectMetatype.ShowDialog(); if (frmSelectMetatype.DialogResult == DialogResult.Cancel) { return; } Cursor.Current = Cursors.WaitCursor; // Add the Unarmed Attack Weapon to the character. XmlDocument objXmlDocument = XmlManager.Load("weapons.xml"); XmlNode objXmlWeapon = objXmlDocument.SelectSingleNode("/chummer/weapons/weapon[name = \"Unarmed Attack\"]"); if (objXmlWeapon != null) { TreeNode objDummy = new TreeNode(); Weapon objWeapon = new Weapon(objCharacter); objWeapon.Create(objXmlWeapon, objDummy, null, null); objCharacter.Weapons.Add(objWeapon); } frmCareer frmNewCharacter = new frmCareer(objCharacter); frmNewCharacter.MdiParent = this; frmNewCharacter.WindowState = FormWindowState.Maximized; frmNewCharacter.Show(); objCharacter.CharacterNameChanged += objCharacter_CharacterNameChanged; Cursor.Current = Cursors.Default; }
/// <summary> /// Create a new character and show the Create Form. /// </summary> private void ShowNewForm(object sender, EventArgs e) { string strFilePath = Path.Combine(Application.StartupPath, "settings", "default.xml"); if (!File.Exists(strFilePath)) { if (MessageBox.Show(LanguageManager.GetString("Message_CharacterOptions_OpenOptions"), LanguageManager.GetString("MessageTitle_CharacterOptions_OpenOptions"), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { frmOptions frmOptions = new frmOptions(); frmOptions.ShowDialog(); } } Character objCharacter = new Character(); string settingsPath = Path.Combine(Application.StartupPath, "settings"); string[] settingsFiles = Directory.GetFiles(settingsPath, "*.xml"); if (settingsFiles.Length > 1) { frmSelectSetting frmPickSetting = new frmSelectSetting(); frmPickSetting.ShowDialog(this); if (frmPickSetting.DialogResult == DialogResult.Cancel) { return; } objCharacter.SettingsFile = frmPickSetting.SettingsFile; } else { string strSettingsFile = settingsFiles[0]; objCharacter.SettingsFile = Path.GetFileName(strSettingsFile); } // Show the BP selection window. frmSelectBuildMethod frmBP = new frmSelectBuildMethod(objCharacter); frmBP.ShowDialog(); if (frmBP.DialogResult == DialogResult.Cancel) { return; } if (objCharacter.BuildMethod == CharacterBuildMethod.Karma || objCharacter.BuildMethod == CharacterBuildMethod.LifeModule) { frmKarmaMetatype frmSelectMetatype = new frmKarmaMetatype(objCharacter); frmSelectMetatype.ShowDialog(); if (frmSelectMetatype.DialogResult == DialogResult.Cancel) { return; } } // Show the Metatype selection window. else if (objCharacter.BuildMethod == CharacterBuildMethod.Priority || objCharacter.BuildMethod == CharacterBuildMethod.SumtoTen) { frmPriorityMetatype frmSelectMetatype = new frmPriorityMetatype(objCharacter); frmSelectMetatype.ShowDialog(); if (frmSelectMetatype.DialogResult == DialogResult.Cancel) { return; } } Cursor.Current = Cursors.WaitCursor; // Add the Unarmed Attack Weapon to the character. XmlDocument objXmlDocument = XmlManager.Load("weapons.xml"); XmlNode objXmlWeapon = objXmlDocument.SelectSingleNode("/chummer/weapons/weapon[name = \"Unarmed Attack\"]"); if (objXmlWeapon != null) { TreeNode objDummy = new TreeNode(); Weapon objWeapon = new Weapon(objCharacter); objWeapon.Create(objXmlWeapon, objDummy, null, null); objCharacter.Weapons.Add(objWeapon); } frmCreate frmNewCharacter = new frmCreate(objCharacter); frmNewCharacter.MdiParent = this; frmNewCharacter.WindowState = FormWindowState.Maximized; frmNewCharacter.Show(); OpenCharacters.Add(objCharacter); objCharacter.CharacterNameChanged += objCharacter_CharacterNameChanged; Cursor.Current = Cursors.Default; }
/// <summary> /// Create a Quality from an XmlNode. /// </summary> /// <param name="objXmlQuality">XmlNode to create the object from.</param> /// <param name="objQualitySource">Source of the Quality.</param> /// <param name="lstWeapons">List of Weapons that should be added to the Character.</param> /// <param name="strForceValue">Force a value to be selected for the Quality.</param> /// <param name="strSourceName">Friendly name for the improvement that added this quality.</param> public void Create(XmlNode objXmlQuality, QualitySource objQualitySource, IList <Weapon> lstWeapons, string strForceValue = "", string strSourceName = "") { _strSourceName = strSourceName; objXmlQuality.TryGetStringFieldQuickly("name", ref _strName); objXmlQuality.TryGetBoolFieldQuickly("metagenetic", ref _blnMetagenetic); if (!objXmlQuality.TryGetStringFieldQuickly("altnotes", ref _strNotes)) { objXmlQuality.TryGetStringFieldQuickly("notes", ref _strNotes); } objXmlQuality.TryGetInt32FieldQuickly("karma", ref _intBP); _eQualityType = ConvertToQualityType(objXmlQuality["category"]?.InnerText); _eQualitySource = objQualitySource; objXmlQuality.TryGetBoolFieldQuickly("doublecareer", ref _blnDoubleCostCareer); objXmlQuality.TryGetBoolFieldQuickly("canbuywithspellpoints", ref _blnCanBuyWithSpellPoints); objXmlQuality.TryGetBoolFieldQuickly("print", ref _blnPrint); objXmlQuality.TryGetBoolFieldQuickly("implemented", ref _blnImplemented); objXmlQuality.TryGetBoolFieldQuickly("contributetolimit", ref _blnContributeToLimit); objXmlQuality.TryGetStringFieldQuickly("source", ref _strSource); objXmlQuality.TryGetStringFieldQuickly("page", ref _strPage); _blnMutant = objXmlQuality["mutant"] != null; if (_eQualityType == QualityType.LifeModule) { objXmlQuality.TryGetStringFieldQuickly("stage", ref _strStage); } if (objXmlQuality.TryGetField("id", Guid.TryParse, out Guid guiTemp)) { _guiQualityId = guiTemp; _objCachedMyXmlNode = null; } // Add Weapons if applicable. // More than one Weapon can be added, so loop through all occurrences. using (XmlNodeList xmlAddWeaponList = objXmlQuality.SelectNodes("addweapon")) if (xmlAddWeaponList?.Count > 0) { XmlDocument objXmlWeaponDocument = XmlManager.Load("weapons.xml"); foreach (XmlNode objXmlAddWeapon in xmlAddWeaponList) { string strLoopID = objXmlAddWeapon.InnerText; XmlNode objXmlWeapon = strLoopID.IsGuid() ? objXmlWeaponDocument.SelectSingleNode("/chummer/weapons/weapon[id = \"" + strLoopID + "\"]") : objXmlWeaponDocument.SelectSingleNode("/chummer/weapons/weapon[name = \"" + strLoopID + "\"]"); Weapon objGearWeapon = new Weapon(_objCharacter); objGearWeapon.Create(objXmlWeapon, lstWeapons); objGearWeapon.ParentID = InternalId; objGearWeapon.Cost = "0"; lstWeapons.Add(objGearWeapon); Guid.TryParse(objGearWeapon.InternalId, out _guiWeaponID); } } using (XmlNodeList xmlNaturalWeaponList = objXmlQuality.SelectNodes("naturalweapons/naturalweapon")) if (xmlNaturalWeaponList?.Count > 0) { foreach (XmlNode objXmlNaturalWeapon in xmlNaturalWeaponList) { Weapon objWeapon = new Weapon(_objCharacter); if (objXmlNaturalWeapon["name"] != null) { objWeapon.Name = objXmlNaturalWeapon["name"].InnerText; } objWeapon.Category = LanguageManager.GetString("Tab_Critter", GlobalOptions.Language); objWeapon.WeaponType = "Melee"; if (objXmlNaturalWeapon["reach"] != null) { objWeapon.Reach = Convert.ToInt32(objXmlNaturalWeapon["reach"].InnerText); } if (objXmlNaturalWeapon["accuracy"] != null) { objWeapon.Accuracy = objXmlNaturalWeapon["accuracy"].InnerText; } if (objXmlNaturalWeapon["damage"] != null) { objWeapon.Damage = objXmlNaturalWeapon["damage"].InnerText; } if (objXmlNaturalWeapon["ap"] != null) { objWeapon.AP = objXmlNaturalWeapon["ap"].InnerText; } objWeapon.Mode = "0"; objWeapon.RC = "0"; objWeapon.Concealability = 0; objWeapon.Avail = "0"; objWeapon.Cost = "0"; if (objXmlNaturalWeapon["useskill"] != null) { objWeapon.UseSkill = objXmlNaturalWeapon["useskill"].InnerText; } if (objXmlNaturalWeapon["source"] != null) { objWeapon.Source = objXmlNaturalWeapon["source"].InnerText; } if (objXmlNaturalWeapon["page"] != null) { objWeapon.Page = objXmlNaturalWeapon["page"].InnerText; } _objCharacter.Weapons.Add(objWeapon); } } _nodDiscounts = objXmlQuality["costdiscount"]; // If the item grants a bonus, pass the information to the Improvement Manager. _nodBonus = objXmlQuality["bonus"]; if (_nodBonus?.ChildNodes.Count > 0) { ImprovementManager.ForcedValue = strForceValue; if (!ImprovementManager.CreateImprovements(_objCharacter, Improvement.ImprovementSource.Quality, InternalId, _nodBonus, false, 1, DisplayNameShort(GlobalOptions.Language))) { _guiID = Guid.Empty; return; } if (!string.IsNullOrEmpty(ImprovementManager.SelectedValue)) { _strExtra = ImprovementManager.SelectedValue; } } else if (!string.IsNullOrEmpty(strForceValue)) { _strExtra = strForceValue; } _nodFirstLevelBonus = objXmlQuality["firstlevelbonus"]; if (_nodFirstLevelBonus?.ChildNodes.Count > 0 && Levels == 0) { ImprovementManager.ForcedValue = string.IsNullOrEmpty(strForceValue) ? Extra : strForceValue; if (!ImprovementManager.CreateImprovements(_objCharacter, Improvement.ImprovementSource.Quality, InternalId, _nodFirstLevelBonus, false, 1, DisplayNameShort(GlobalOptions.Language))) { _guiID = Guid.Empty; return; } } if (string.IsNullOrEmpty(Notes)) { string strEnglishNameOnPage = Name; string strNameOnPage = string.Empty; // make sure we have something and not just an empty tag if (objXmlQuality.TryGetStringFieldQuickly("nameonpage", ref strNameOnPage) && !string.IsNullOrEmpty(strNameOnPage)) { strEnglishNameOnPage = strNameOnPage; } string strQualityNotes = CommonFunctions.GetTextFromPDF($"{Source} {Page}", strEnglishNameOnPage); if (string.IsNullOrEmpty(strQualityNotes) && GlobalOptions.Language != GlobalOptions.DefaultLanguage) { string strTranslatedNameOnPage = DisplayName(GlobalOptions.CultureInfo, GlobalOptions.Language); // don't check again it is not translated if (strTranslatedNameOnPage != _strName) { // if we found <altnameonpage>, and is not empty and not the same as english we must use that instead if (objXmlQuality.TryGetStringFieldQuickly("altnameonpage", ref strNameOnPage) && !string.IsNullOrEmpty(strNameOnPage) && strNameOnPage != strEnglishNameOnPage) { strTranslatedNameOnPage = strNameOnPage; } Notes = CommonFunctions.GetTextFromPDF($"{Source} {DisplayPage(GlobalOptions.Language)}", strTranslatedNameOnPage); } } else { Notes = strQualityNotes; } } }
/// <summary> /// Build the list of Qualities. /// </summary> private void BuildQualityList() { if (_blnLoading) { return; } string strCategory = cboCategory.SelectedValue?.ToString(); string strFilter = "(" + _objCharacter.Options.BookXPath() + ")"; if (!string.IsNullOrEmpty(strCategory) && strCategory != "Show All" && (_objCharacter.Options.SearchInCategoryOnly || txtSearch.TextLength == 0)) { strFilter += " and category = \"" + strCategory + "\""; } else { StringBuilder objCategoryFilter = new StringBuilder(); foreach (string strItem in _lstCategory.Select(x => x.Value)) { if (!string.IsNullOrEmpty(strItem)) { objCategoryFilter.Append("category = \"" + strItem + "\" or "); } } if (objCategoryFilter.Length > 0) { strFilter += " and (" + objCategoryFilter.ToString().TrimEnd(" or ") + ")"; } } if (!string.IsNullOrWhiteSpace(txtSearch.Text)) { // Treat everything as being uppercase so the search is case-insensitive. string strSearchText = txtSearch.Text.ToUpper(); strFilter += " and ((contains(translate(name,'abcdefghijklmnopqrstuvwxyzàáâãäåçèéêëìíîïñòóôõöùúûüýß','ABCDEFGHIJKLMNOPQRSTUVWXYZÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝß'), \"" + strSearchText + "\") and not(translate)) or contains(translate(translate,'abcdefghijklmnopqrstuvwxyzàáâãäåçèéêëìíîïñòóôõöùúûüýß','ABCDEFGHIJKLMNOPQRSTUVWXYZÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝß'), \"" + strSearchText + "\"))"; } if (chkMetagenetic.Checked) { strFilter += " and (metagenetic = 'yes' or required/oneof[contains(., 'Changeling')])"; } else if (chkNotMetagenetic.Checked) { strFilter += " and not(metagenetic = 'yes') and not(required/oneof[contains(., 'Changeling')])"; } if (nudValueBP.Value != 0) { strFilter += "and karma = " + nudValueBP.Value; } else { if (nudMinimumBP.Value != 0) { strFilter += "and karma >= " + nudMinimumBP.Value; } if (nudMaximumBP.Value != 0) { strFilter += "and karma <= " + nudMaximumBP.Value; } } XmlDocument objXmlMetatypeDocument = XmlManager.Load("metatypes.xml"); XmlDocument objXmlCrittersDocument = XmlManager.Load("critters.xml"); bool blnNeedQualityWhitelist = false; XmlNode objXmlMetatype = objXmlMetatypeDocument.SelectSingleNode("/chummer/metatypes/metatype[name = \"" + _objCharacter.Metatype + "\"]"); if (objXmlMetatype?.SelectSingleNode("qualityrestriction") != null) { blnNeedQualityWhitelist = true; } else { objXmlMetatype = objXmlCrittersDocument.SelectSingleNode("/chummer/metatypes/metatype[name = \"" + _objCharacter.Metatype + "\"]"); if (objXmlMetatype?.SelectSingleNode("qualityrestriction") != null) { blnNeedQualityWhitelist = true; } } XmlNodeList objXmlQualityList = _objXmlDocument.SelectNodes("/chummer/qualities/quality[" + strFilter + "]"); List <ListItem> lstQuality = new List <ListItem>(); foreach (XmlNode objXmlQuality in objXmlQualityList) { if (objXmlQuality["name"] == null) { continue; } if (blnNeedQualityWhitelist) { if (strCategory == "Show All") { bool blnAllowed = false; foreach (ListItem objCategory in _lstCategory) { if (objXmlMetatype.SelectSingleNode("qualityrestriction/*/quality[. = \"" + objXmlQuality["name"].InnerText + "\"]") != null) { blnAllowed = true; break; } } if (!blnAllowed) { continue; } } else if (objXmlMetatype.SelectSingleNode("qualityrestriction/" + strCategory.ToLower() + "/quality[. = \"" + objXmlQuality["name"].InnerText + "\"]") == null) { continue; } } if (!chkLimitList.Checked || SelectionShared.RequirementsMet(objXmlQuality, false, _objCharacter, objXmlMetatypeDocument, objXmlCrittersDocument, _objXmlDocument, IgnoreQuality)) { string strName = objXmlQuality["name"].InnerText; lstQuality.Add(new ListItem(strName, objXmlQuality["translate"]?.InnerText ?? strName)); } } lstQuality.Sort(CompareListItems.CompareNames); lstQualities.BeginUpdate(); lstQualities.DataSource = null; lstQualities.ValueMember = "Value"; lstQualities.DisplayMember = "Name"; lstQualities.DataSource = lstQuality; lstQualities.EndUpdate(); }
private async void cmdOK_Click(object sender, EventArgs e) { // Make sure the kit and file name fields are populated. string strName = await txtName.DoThreadSafeFuncAsync(x => x.Text); if (string.IsNullOrEmpty(strName)) { Program.ShowMessageBox(this, await LanguageManager.GetStringAsync("Message_CreatePACKSKit_KitName"), await LanguageManager.GetStringAsync("MessageTitle_CreatePACKSKit_KitName"), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } string strFileName = await txtFileName.DoThreadSafeFuncAsync(x => x.Text); if (string.IsNullOrEmpty(strFileName)) { Program.ShowMessageBox(this, await LanguageManager.GetStringAsync("Message_CreatePACKSKit_FileName"), await LanguageManager.GetStringAsync("MessageTitle_CreatePACKSKit_FileName"), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } // Make sure the file name starts with custom and ends with _packs.xml. if (!strFileName.StartsWith("custom_", StringComparison.OrdinalIgnoreCase) || !strFileName.EndsWith("_packs.xml", StringComparison.OrdinalIgnoreCase)) { Program.ShowMessageBox(this, await LanguageManager.GetStringAsync("Message_CreatePACKSKit_InvalidFileName"), await LanguageManager.GetStringAsync("MessageTitle_CreatePACKSKit_InvalidFileName"), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } // See if a Kit with this name already exists for the Custom category. // This was originally done without the XmlManager, but because amends and overrides and toggling custom data directories can change names, we need to use it. if ((await XmlManager.LoadXPathAsync("packs.xml", _objCharacter.Settings.EnabledCustomDataDirectoryPaths)) .SelectSingleNode("/chummer/packs/pack[name = " + strName.CleanXPath() + " and category = \"Custom\"]") != null) { Program.ShowMessageBox(this, string.Format(GlobalSettings.CultureInfo, await LanguageManager.GetStringAsync("Message_CreatePACKSKit_DuplicateName"), strName), await LanguageManager.GetStringAsync("MessageTitle_CreatePACKSKit_DuplicateName"), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } string strPath = Path.Combine(Utils.GetStartupPath, "data", strFileName); // If this is not a new file, read in the existing contents. XmlDocument objXmlCurrentDocument = null; if (File.Exists(strPath)) { try { objXmlCurrentDocument = new XmlDocument { XmlResolver = null }; objXmlCurrentDocument.LoadStandard(strPath); } catch (IOException ex) { Program.ShowMessageBox(this, ex.ToString()); return; } catch (XmlException ex) { Program.ShowMessageBox(this, ex.ToString()); return; } } using (FileStream objStream = new FileStream(strPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)) { using (XmlWriter objWriter = Utils.GetStandardXmlWriter(objStream)) { await objWriter.WriteStartDocumentAsync(); // <chummer> await objWriter.WriteStartElementAsync("chummer"); // <packs> await objWriter.WriteStartElementAsync("packs"); // If this is not a new file, write out the current contents. if (objXmlCurrentDocument != null) { XmlNode xmlExistingPacksNode = objXmlCurrentDocument.SelectSingleNode("/chummer/packs"); xmlExistingPacksNode?.WriteContentTo(objWriter); } // <pack> await objWriter.WriteStartElementAsync("pack"); // <name /> await objWriter.WriteElementStringAsync("name", txtName.Text); // <category /> await objWriter.WriteElementStringAsync("category", "Custom"); // Export Attributes. if (await chkAttributes.DoThreadSafeFuncAsync(x => x.Checked)) { int intBOD = await _objCharacter.BOD.ValueAsync - (await _objCharacter.BOD.MetatypeMinimumAsync - 1); int intAGI = await _objCharacter.AGI.ValueAsync - (await _objCharacter.AGI.MetatypeMinimumAsync - 1); int intREA = await _objCharacter.REA.ValueAsync - (await _objCharacter.REA.MetatypeMinimumAsync - 1); int intSTR = await _objCharacter.STR.ValueAsync - (await _objCharacter.STR.MetatypeMinimumAsync - 1); int intCHA = await _objCharacter.CHA.ValueAsync - (await _objCharacter.CHA.MetatypeMinimumAsync - 1); int intINT = await _objCharacter.INT.ValueAsync - (await _objCharacter.INT.MetatypeMinimumAsync - 1); int intLOG = await _objCharacter.LOG.ValueAsync - (await _objCharacter.LOG.MetatypeMinimumAsync - 1); int intWIL = await _objCharacter.WIL.ValueAsync - (await _objCharacter.WIL.MetatypeMinimumAsync - 1); int intEDG = await _objCharacter.EDG.ValueAsync - (await _objCharacter.EDG.MetatypeMinimumAsync - 1); int intMAG = await _objCharacter.MAG.ValueAsync - (await _objCharacter.MAG.MetatypeMinimumAsync - 1); int intMAGAdept = await _objCharacter.MAGAdept.ValueAsync - (await _objCharacter.MAGAdept.MetatypeMinimumAsync - 1); int intDEP = await _objCharacter.DEP.ValueAsync - (await _objCharacter.DEP.MetatypeMinimumAsync - 1); int intRES = await _objCharacter.RES.ValueAsync - (await _objCharacter.RES.MetatypeMinimumAsync - 1); // <attributes> await objWriter.WriteStartElementAsync("attributes"); await objWriter.WriteElementStringAsync("bod", intBOD.ToString(GlobalSettings.InvariantCultureInfo)); await objWriter.WriteElementStringAsync("agi", intAGI.ToString(GlobalSettings.InvariantCultureInfo)); await objWriter.WriteElementStringAsync("rea", intREA.ToString(GlobalSettings.InvariantCultureInfo)); await objWriter.WriteElementStringAsync("str", intSTR.ToString(GlobalSettings.InvariantCultureInfo)); await objWriter.WriteElementStringAsync("cha", intCHA.ToString(GlobalSettings.InvariantCultureInfo)); await objWriter.WriteElementStringAsync("int", intINT.ToString(GlobalSettings.InvariantCultureInfo)); await objWriter.WriteElementStringAsync("log", intLOG.ToString(GlobalSettings.InvariantCultureInfo)); await objWriter.WriteElementStringAsync("wil", intWIL.ToString(GlobalSettings.InvariantCultureInfo)); await objWriter.WriteElementStringAsync("edg", intEDG.ToString(GlobalSettings.InvariantCultureInfo)); if (_objCharacter.MAGEnabled) { await objWriter.WriteElementStringAsync("mag", intMAG.ToString(GlobalSettings.InvariantCultureInfo)); if (_objCharacter.Settings.MysAdeptSecondMAGAttribute && _objCharacter.IsMysticAdept) { await objWriter.WriteElementStringAsync("magadept", intMAGAdept.ToString(GlobalSettings.InvariantCultureInfo)); } } if (_objCharacter.RESEnabled) { await objWriter.WriteElementStringAsync("res", intRES.ToString(GlobalSettings.InvariantCultureInfo)); } if (_objCharacter.DEPEnabled) { await objWriter.WriteElementStringAsync("dep", intDEP.ToString(GlobalSettings.InvariantCultureInfo)); } // </attributes> await objWriter.WriteEndElementAsync(); } // Export Qualities. if (await chkQualities.DoThreadSafeFuncAsync(x => x.Checked)) { bool blnPositive = false; bool blnNegative = false; // Determine if Positive or Negative Qualities exist. foreach (Quality objQuality in _objCharacter.Qualities) { switch (objQuality.Type) { case QualityType.Positive: blnPositive = true; break; case QualityType.Negative: blnNegative = true; break; } if (blnPositive && blnNegative) { break; } } // <qualities> await objWriter.WriteStartElementAsync("qualities"); // Positive Qualities. if (blnPositive) { // <positive> await objWriter.WriteStartElementAsync("positive"); foreach (Quality objQuality in _objCharacter.Qualities) { if (objQuality.Type == QualityType.Positive) { await objWriter.WriteStartElementAsync("quality"); if (!string.IsNullOrEmpty(objQuality.Extra)) { await objWriter.WriteAttributeStringAsync("select", objQuality.Extra); } objWriter.WriteValue(objQuality.Name); await objWriter.WriteEndElementAsync(); } } // </positive> await objWriter.WriteEndElementAsync(); } // Negative Qualities. if (blnPositive) { // <negative> await objWriter.WriteStartElementAsync("negative"); foreach (Quality objQuality in _objCharacter.Qualities) { if (objQuality.Type == QualityType.Negative) { await objWriter.WriteStartElementAsync("quality"); if (!string.IsNullOrEmpty(objQuality.Extra)) { await objWriter.WriteAttributeStringAsync("select", objQuality.Extra); } objWriter.WriteValue(objQuality.Name); await objWriter.WriteEndElementAsync(); } } // </negative> await objWriter.WriteEndElementAsync(); } // </qualities> await objWriter.WriteEndElementAsync(); } // Export Starting Nuyen. if (await chkStartingNuyen.DoThreadSafeFuncAsync(x => x.Checked)) { decimal decNuyenBP = _objCharacter.NuyenBP; if (!_objCharacter.EffectiveBuildMethodUsesPriorityTables) { decNuyenBP /= 2.0m; } await objWriter.WriteElementStringAsync("nuyenbp", decNuyenBP.ToString(GlobalSettings.InvariantCultureInfo)); } /* TODO: Add support for active and knowledge skills and skill groups * // Export Active Skills. * if (await chkActiveSkills.DoThreadSafeFuncAsync(x => x.Checked)) * { * // <skills> * await objWriter.WriteStartElementAsync("skills"); * * // Active Skills. * foreach (Skill objSkill in _objCharacter.SkillsSection.Skills) * { * if (!objSkill.IsKnowledgeSkill && objSkill.Rating > 0) * { * // <skill> * await objWriter.WriteStartElementAsync("skill"); * await objWriter.WriteElementStringAsync("name", objSkill.Name); * await objWriter.WriteElementStringAsync("rating", objSkill.Rating.ToString()); * if (!string.IsNullOrEmpty(objSkill.Specialization)) * await objWriter.WriteElementStringAsync("spec", objSkill.Specialization); * // </skill> * await objWriter.WriteEndElementAsync(); * } * } * * // Skill Groups. * foreach (SkillGroup objSkillGroup in _objCharacter.SkillsSection.SkillGroups) * { * if (objSkillGroup.BaseUnbroken && objSkillGroup.Rating > 0) * { * // <skillgroup> * await objWriter.WriteStartElementAsync("skillgroup"); * await objWriter.WriteElementStringAsync("name", objSkillGroup.Name); * await objWriter.WriteElementStringAsync("rating", objSkillGroup.Rating.ToString()); * // </skillgroup> * await objWriter.WriteEndElementAsync(); * } * } * // </skills> * await objWriter.WriteEndElementAsync(); * } * * // Export Knowledge Skills. * if (await chkKnowledgeSkills.DoThreadSafeFuncAsync(x => x.Checked)) * { * // <knowledgeskills> * await objWriter.WriteStartElementAsync("knowledgeskills"); * foreach (KnowledgeSkill objSkill in _objCharacter.SkillsSection.Skills.OfType<KnowledgeSkill>()) * { * // <skill> * await objWriter.WriteStartElementAsync("skill"); * await objWriter.WriteElementStringAsync("name", objSkill.Name); * await objWriter.WriteElementStringAsync("rating", objSkill.Rating.ToString(GlobalSettings.InvariantCultureInfo)); * if (!string.IsNullOrEmpty(objSkill.Specialization)) * await objWriter.WriteElementStringAsync("spec", objSkill.Specialization); * await objWriter.WriteElementStringAsync("category", objSkill.SkillCategory); * // </skill> * await objWriter.WriteEndElementAsync(); * } * * // </knowledgeskills> * await objWriter.WriteEndElementAsync(); * } */ // Export Martial Arts. if (await chkMartialArts.DoThreadSafeFuncAsync(x => x.Checked)) { // <martialarts> await objWriter.WriteStartElementAsync("martialarts"); foreach (MartialArt objArt in _objCharacter.MartialArts) { // <martialart> await objWriter.WriteStartElementAsync("martialart"); await objWriter.WriteElementStringAsync("name", objArt.Name); if (objArt.Techniques.Count > 0) { // <techniques> await objWriter.WriteStartElementAsync("techniques"); foreach (MartialArtTechnique objTechnique in objArt.Techniques) { await objWriter.WriteElementStringAsync("technique", objTechnique.Name); } // </techniques> await objWriter.WriteEndElementAsync(); } // </martialart> await objWriter.WriteEndElementAsync(); } // </martialarts> await objWriter.WriteEndElementAsync(); } // Export Spells. if (await chkSpells.DoThreadSafeFuncAsync(x => x.Checked)) { // <spells> await objWriter.WriteStartElementAsync("spells"); foreach (Spell objSpell in _objCharacter.Spells) { await objWriter.WriteStartElementAsync("spell"); await objWriter.WriteStartElementAsync("name"); if (!string.IsNullOrEmpty(objSpell.Extra)) { await objWriter.WriteAttributeStringAsync("select", objSpell.Extra); } objWriter.WriteValue(objSpell.Name); await objWriter.WriteEndElementAsync(); await objWriter.WriteElementStringAsync("category", objSpell.Category); await objWriter.WriteEndElementAsync(); } // </spells> await objWriter.WriteEndElementAsync(); } // Export Complex Forms. if (await chkComplexForms.DoThreadSafeFuncAsync(x => x.Checked)) { // <programs> await objWriter.WriteStartElementAsync("complexforms"); foreach (ComplexForm objComplexForm in _objCharacter.ComplexForms) { // <program> await objWriter.WriteStartElementAsync("complexform"); await objWriter.WriteStartElementAsync("name"); if (!string.IsNullOrEmpty(objComplexForm.Extra)) { await objWriter.WriteAttributeStringAsync("select", objComplexForm.Extra); } objWriter.WriteValue(objComplexForm.Name); await objWriter.WriteEndElementAsync(); await objWriter.WriteEndElementAsync(); // </program> await objWriter.WriteEndElementAsync(); } // </programs> await objWriter.WriteEndElementAsync(); } // Export Cyberware/Bioware. if (await chkCyberware.DoThreadSafeFuncAsync(x => x.Checked)) { bool blnCyberware = false; bool blnBioware = false; foreach (Cyberware objCharacterCyberware in _objCharacter.Cyberware) { switch (objCharacterCyberware.SourceType) { case Improvement.ImprovementSource.Bioware: blnBioware = true; break; case Improvement.ImprovementSource.Cyberware: blnCyberware = true; break; } if (blnCyberware && blnBioware) { break; } } if (blnCyberware) { // <cyberwares> await objWriter.WriteStartElementAsync("cyberwares"); foreach (Cyberware objCyberware in _objCharacter.Cyberware) { if (objCyberware.SourceType == Improvement.ImprovementSource.Cyberware) { // <cyberware> await objWriter.WriteStartElementAsync("cyberware"); await objWriter.WriteElementStringAsync("name", objCyberware.Name); if (objCyberware.Rating > 0) { await objWriter.WriteElementStringAsync("rating", objCyberware.Rating.ToString(GlobalSettings.InvariantCultureInfo)); } await objWriter.WriteElementStringAsync("grade", objCyberware.Grade.Name); if (objCyberware.Children.Count > 0) { // <cyberwares> await objWriter.WriteStartElementAsync("cyberwares"); foreach (Cyberware objChildCyberware in objCyberware.Children) { if (objChildCyberware.Capacity != "[*]") { // <cyberware> await objWriter.WriteStartElementAsync("cyberware"); await objWriter.WriteElementStringAsync("name", objChildCyberware.Name); if (objChildCyberware.Rating > 0) { await objWriter.WriteElementStringAsync("rating", objChildCyberware.Rating.ToString(GlobalSettings.InvariantCultureInfo)); } if (objChildCyberware.GearChildren.Count > 0) { await WriteGear(objWriter, objChildCyberware.GearChildren); } // </cyberware> await objWriter.WriteEndElementAsync(); } } // </cyberwares> await objWriter.WriteEndElementAsync(); } if (objCyberware.GearChildren.Count > 0) { await WriteGear(objWriter, objCyberware.GearChildren); } // </cyberware> await objWriter.WriteEndElementAsync(); } } // </cyberwares> await objWriter.WriteEndElementAsync(); } if (blnBioware) { // <biowares> await objWriter.WriteStartElementAsync("biowares"); foreach (Cyberware objCyberware in _objCharacter.Cyberware) { if (objCyberware.SourceType == Improvement.ImprovementSource.Bioware) { // <bioware> await objWriter.WriteStartElementAsync("bioware"); await objWriter.WriteElementStringAsync("name", objCyberware.Name); if (objCyberware.Rating > 0) { await objWriter.WriteElementStringAsync("rating", objCyberware.Rating.ToString(GlobalSettings.InvariantCultureInfo)); } await objWriter.WriteElementStringAsync("grade", objCyberware.Grade.ToString()); if (objCyberware.GearChildren.Count > 0) { await WriteGear(objWriter, objCyberware.GearChildren); } // </bioware> await objWriter.WriteEndElementAsync(); } } // </biowares> await objWriter.WriteEndElementAsync(); } } // Export Lifestyle. if (await chkLifestyle.DoThreadSafeFuncAsync(x => x.Checked)) { // <lifestyles> await objWriter.WriteStartElementAsync("lifestyles"); foreach (Lifestyle objLifestyle in _objCharacter.Lifestyles) { // <lifestyle> await objWriter.WriteStartElementAsync("lifestyle"); await objWriter.WriteElementStringAsync("name", objLifestyle.Name); await objWriter.WriteElementStringAsync("months", objLifestyle.Increments.ToString(GlobalSettings.InvariantCultureInfo)); if (!string.IsNullOrEmpty(objLifestyle.BaseLifestyle)) { // This is an Advanced Lifestyle, so write out its properties. await objWriter.WriteElementStringAsync("cost", objLifestyle.Cost.ToString(_objCharacter.Settings.NuyenFormat, GlobalSettings.CultureInfo)); await objWriter.WriteElementStringAsync("dice", objLifestyle.Dice.ToString(GlobalSettings.InvariantCultureInfo)); await objWriter.WriteElementStringAsync("multiplier", objLifestyle.Multiplier.ToString(_objCharacter.Settings.NuyenFormat, GlobalSettings.CultureInfo)); await objWriter.WriteElementStringAsync("baselifestyle", objLifestyle.BaseLifestyle); if (objLifestyle.LifestyleQualities.Count > 0) { // <qualities> await objWriter.WriteStartElementAsync("qualities"); foreach (LifestyleQuality objQuality in objLifestyle.LifestyleQualities) { await objWriter.WriteElementStringAsync("quality", objQuality.Name); } // </qualities> await objWriter.WriteEndElementAsync(); } } // </lifestyle> await objWriter.WriteEndElementAsync(); } // </lifestyles> await objWriter.WriteEndElementAsync(); } // Export Armor. if (await chkArmor.DoThreadSafeFuncAsync(x => x.Checked)) { // <armors> await objWriter.WriteStartElementAsync("armors"); foreach (Armor objArmor in _objCharacter.Armor) { // <armor> await objWriter.WriteStartElementAsync("armor"); await objWriter.WriteElementStringAsync("name", objArmor.Name); if (objArmor.ArmorMods.Count > 0) { // <mods> await objWriter.WriteStartElementAsync("mods"); foreach (ArmorMod objMod in objArmor.ArmorMods) { // <mod> await objWriter.WriteStartElementAsync("mod"); await objWriter.WriteElementStringAsync("name", objMod.Name); if (objMod.Rating > 0) { await objWriter.WriteElementStringAsync("rating", objMod.Rating.ToString(GlobalSettings.InvariantCultureInfo)); } // </mod> await objWriter.WriteEndElementAsync(); } // </mods> await objWriter.WriteEndElementAsync(); } if (objArmor.GearChildren.Count > 0) { await WriteGear(objWriter, objArmor.GearChildren); } // </armor> await objWriter.WriteEndElementAsync(); } // </armors> await objWriter.WriteEndElementAsync(); } // Export Weapons. if (await chkWeapons.DoThreadSafeFuncAsync(x => x.Checked)) { // <weapons> await objWriter.WriteStartElementAsync("weapons"); foreach (Weapon objWeapon in _objCharacter.Weapons) { // Don't attempt to export Cyberware and Gear Weapons since those are handled by those object types. The default Unarmed Attack Weapon should also not be exported. if (objWeapon.Category != "Cyberware" && objWeapon.Category != "Gear" && objWeapon.Name != "Unarmed Attack") { // <weapon> await objWriter.WriteStartElementAsync("weapon"); await objWriter.WriteElementStringAsync("name", objWeapon.Name); // Weapon Accessories. if (objWeapon.WeaponAccessories.Count > 0) { // <accessories> await objWriter.WriteStartElementAsync("accessories"); foreach (WeaponAccessory objAccessory in objWeapon.WeaponAccessories) { // Don't attempt to export items included in the Weapon. if (!objAccessory.IncludedInWeapon) { // <accessory> await objWriter.WriteStartElementAsync("accessory"); await objWriter.WriteElementStringAsync("name", objAccessory.Name); await objWriter.WriteElementStringAsync("mount", objAccessory.Mount); await objWriter.WriteElementStringAsync("extramount", objAccessory.ExtraMount); if (objAccessory.GearChildren.Count > 0) { await WriteGear(objWriter, objAccessory.GearChildren); } // </accessory> await objWriter.WriteEndElementAsync(); } } // </accessories> await objWriter.WriteEndElementAsync(); } // Underbarrel Weapon. if (objWeapon.UnderbarrelWeapons.Count > 0) { foreach (Weapon objUnderbarrelWeapon in objWeapon.UnderbarrelWeapons) { if (!objUnderbarrelWeapon.IncludedInWeapon) { await objWriter.WriteElementStringAsync("underbarrel", objUnderbarrelWeapon.Name); } } } // </weapon> await objWriter.WriteEndElementAsync(); } } // </weapons> await objWriter.WriteEndElementAsync(); } // Export Gear. if (await chkGear.DoThreadSafeFuncAsync(x => x.Checked)) { await WriteGear(objWriter, _objCharacter.Gear); } // Export Vehicles. if (await chkVehicles.DoThreadSafeFuncAsync(x => x.Checked)) { // <vehicles> await objWriter.WriteStartElementAsync("vehicles"); foreach (Vehicle objVehicle in _objCharacter.Vehicles) { bool blnWeapons = false; // <vehicle> await objWriter.WriteStartElementAsync("vehicle"); await objWriter.WriteElementStringAsync("name", objVehicle.Name); if (objVehicle.Mods.Count > 0) { // <mods> await objWriter.WriteStartElementAsync("mods"); foreach (VehicleMod objVehicleMod in objVehicle.Mods) { // Only write out the Mods that are not part of the base vehicle. if (!objVehicleMod.IncludedInVehicle) { // <mod> await objWriter.WriteStartElementAsync("mod"); await objWriter.WriteElementStringAsync("name", objVehicleMod.Name); if (objVehicleMod.Rating > 0) { await objWriter.WriteElementStringAsync("rating", objVehicleMod.Rating.ToString(GlobalSettings.InvariantCultureInfo)); } // </mod> await objWriter.WriteEndElementAsync(); // See if this is a Weapon Mount with Weapons. if (objVehicleMod.Weapons.Count > 0) { blnWeapons = true; } } else { // See if this is a Weapon Mount with Weapons. if (objVehicleMod.Weapons.Count > 0) { blnWeapons = true; } } } // </mods> await objWriter.WriteEndElementAsync(); } // If there are Weapons, add them. if (blnWeapons) { // <weapons> await objWriter.WriteStartElementAsync("weapons"); foreach (VehicleMod objVehicleMod in objVehicle.Mods) { foreach (Weapon objWeapon in objVehicleMod.Weapons) { // <weapon> await objWriter.WriteStartElementAsync("weapon"); await objWriter.WriteElementStringAsync("name", objWeapon.Name); // Weapon Accessories. if (objWeapon.WeaponAccessories.Count > 0) { // <accessories> await objWriter.WriteStartElementAsync("accessories"); foreach (WeaponAccessory objAccessory in objWeapon.WeaponAccessories) { // Don't attempt to export items included in the Weapon. if (!objAccessory.IncludedInWeapon) { // <accessory> await objWriter.WriteStartElementAsync("accessory"); await objWriter.WriteElementStringAsync("name", objAccessory.Name); await objWriter.WriteElementStringAsync("mount", objAccessory.Mount); await objWriter.WriteElementStringAsync("extramount", objAccessory.ExtraMount); // </accessory> await objWriter.WriteEndElementAsync(); } } // </accessories> await objWriter.WriteEndElementAsync(); } // Underbarrel Weapon. if (objWeapon.UnderbarrelWeapons.Count > 0) { foreach (Weapon objUnderbarrelWeapon in objWeapon.UnderbarrelWeapons) { await objWriter.WriteElementStringAsync("underbarrel", objUnderbarrelWeapon.Name); } } // </weapon> await objWriter.WriteEndElementAsync(); } } // </weapons> await objWriter.WriteEndElementAsync(); } // Gear. if (objVehicle.GearChildren.Count > 0) { await WriteGear(objWriter, objVehicle.GearChildren); } // </vehicle> await objWriter.WriteEndElementAsync(); } // </vehicles> await objWriter.WriteEndElementAsync(); } // </pack> await objWriter.WriteEndElementAsync(); // </packs> await objWriter.WriteEndElementAsync(); // </chummer> await objWriter.WriteEndElementAsync(); await objWriter.WriteEndDocumentAsync(); } } Program.ShowMessageBox(this, string.Format(GlobalSettings.CultureInfo, await LanguageManager.GetStringAsync("Message_CreatePACKSKit_SuiteCreated"), strName), await LanguageManager.GetStringAsync("MessageTitle_CreatePACKSKit_SuiteCreated"), MessageBoxButtons.OK, MessageBoxIcon.Information); await this.DoThreadSafeAsync(x => { x.DialogResult = DialogResult.OK; x.Close(); }); }
private void cboBaseLifestyle_SelectedIndexChanged(object sender, EventArgs e) { if (!_blnSkipRefresh) { string strBaseLifestyle = cboBaseLifestyle.SelectedValue.ToString(); _objLifestyle.BaseLifestyle = strBaseLifestyle; XmlDocument objXmlDocument = XmlManager.Load("lifestyles.xml"); XmlNode objXmlAspect = _objXmlDocument.SelectSingleNode("/chummer/lifestyles/lifestyle[name = \"" + strBaseLifestyle + "\"]"); XmlNodeList objGridNodes = null; if (objXmlAspect != null) { objGridNodes = objXmlAspect.SelectNodes("freegrids/freegrid"); if (objXmlAspect["source"] != null && objXmlAspect["page"] != null) { lblSource.Text = objXmlAspect["source"].InnerText + " " + objXmlAspect["page"].InnerText; } } objXmlAspect = _objXmlDocument.SelectSingleNode("/chummer/comforts/comfort[name = \"" + strBaseLifestyle + "\"]"); nudComforts.Minimum = objXmlAspect?["minimum"] != null?Convert.ToInt32(objXmlAspect["minimum"].InnerText) : 0; nudComforts.Value = nudComforts.Minimum; // Area. objXmlAspect = _objXmlDocument.SelectSingleNode("/chummer/neighborhoods/neighborhood[name = \"" + strBaseLifestyle + "\"]"); nudArea.Minimum = objXmlAspect?["minimum"] != null?Convert.ToInt32(objXmlAspect["minimum"].InnerText) : 0; nudArea.Value = nudArea.Minimum; // Security. objXmlAspect = _objXmlDocument.SelectSingleNode("/chummer/securities/security[name = \"" + strBaseLifestyle + "\"]"); nudSecurity.Minimum = objXmlAspect?["minimum"] != null?Convert.ToInt32(objXmlAspect["minimum"].InnerText) : 0; nudSecurity.Value = nudSecurity.Minimum; //This needs a handler for translations, will fix later. if (strBaseLifestyle == "Bolt Hole") { bool blnAddQuality = true; foreach (TreeNode objNode in treLifestyleQualities.Nodes[1].Nodes) { //Bolt Holes automatically come with the Not a Home quality. if (objNode.Name == "Not a Home") { blnAddQuality = false; break; } } if (blnAddQuality) { XmlNode objXmlQuality = objXmlDocument.SelectSingleNode("/chummer/qualities/quality[name = \"Not a Home\"]"); LifestyleQuality objQuality = new LifestyleQuality(_objCharacter); TreeNode objNode = new TreeNode(); objQuality.Create(objXmlQuality, _objLifestyle, _objCharacter, QualitySource.BuiltIn, objNode); treLifestyleQualities.Nodes[1].Nodes.Add(objNode); treLifestyleQualities.Nodes[1].Expand(); _objLifestyle.LifestyleQualities.Add(objQuality); } } else { //Characters with the Trust Fund Quality can have the lifestyle discounted. if (strBaseLifestyle == "Medium" && (_objCharacter.TrustFund == 1 || _objCharacter.TrustFund == 4)) { chkTrustFund.Visible = true; } else if (strBaseLifestyle == "Low" && _objCharacter.TrustFund == 2) { chkTrustFund.Visible = true; } else if (strBaseLifestyle == "High" && _objCharacter.TrustFund == 3) { chkTrustFund.Visible = true; } else { chkTrustFund.Checked = false; chkTrustFund.Visible = false; if (strBaseLifestyle == "Traveler") { Random rndTavelerLp = MersenneTwister.SfmtRandom.Create(); int intModuloTemp = 0; do { intModuloTemp = rndTavelerLp.Next(); }while (intModuloTemp >= int.MaxValue - 1); // Modulo bias removal for 1d6 _intTravelerRdmLP = 1 + intModuloTemp % 6; } } foreach (LifestyleQuality objQuality in _objLifestyle.LifestyleQualities.ToList()) { if (objQuality.Name == "Not a Home") { _objLifestyle.LifestyleQualities.Remove(objQuality); foreach (TreeNode objNode in treLifestyleQualities.Nodes[1].Nodes) { //Bolt Holes automatically come with the Not a Home quality. if (objNode.Text == "Not a Home") { treLifestyleQualities.Nodes[1].Nodes.Remove(objNode); } } } else if (objQuality.Name == "Dug a Hole") { _objLifestyle.LifestyleQualities.Remove(objQuality); foreach (TreeNode objNode in treLifestyleQualities.Nodes[0].Nodes) { //Bolt Holes automatically come with the Not a Home quality. if (objNode.Text == "Dug a Hole") { treLifestyleQualities.Nodes[1].Nodes.Remove(objNode); } } } } } if (objGridNodes != null) { _objLifestyle.FreeGrids.Clear(); treLifestyleQualities.Nodes[3].Nodes.Clear(); foreach (XmlNode objXmlNode in objGridNodes) { XmlNode objXmlQuality = objXmlDocument.SelectSingleNode("/chummer/qualities/quality[name = \"" + objXmlNode.InnerText + "\"]"); LifestyleQuality objQuality = new LifestyleQuality(_objCharacter); TreeNode objNode = new TreeNode(); string push = objXmlNode.Attributes?["select"]?.InnerText; if (!string.IsNullOrWhiteSpace(push)) { _objCharacter.Pushtext.Push(push); } objQuality.Create(objXmlQuality, _objLifestyle, _objCharacter, QualitySource.BuiltIn, objNode); objNode.Text = objQuality.DisplayName; treLifestyleQualities.Nodes[3].Nodes.Add(objNode); treLifestyleQualities.Nodes[3].Expand(); _objLifestyle.FreeGrids.Add(objQuality); } } } CalculateValues(); }
/// <summary> /// Attempt to translate any Extra text for an item. /// </summary> /// <param name="strExtra">Extra string to translate.</param> public static string TranslateExtra(string strExtra) { string strReturn = string.Empty; // Only attempt to translate if we're not using English. Don't attempt to translate an empty string either. if (_strLanguage != "en-us" && !string.IsNullOrWhiteSpace(strExtra)) { // Attempt to translate CharacterAttribute names. switch (strExtra) { case "BOD": strReturn = GetString("String_AttributeBODShort"); break; case "AGI": strReturn = GetString("String_AttributeAGIShort"); break; case "REA": strReturn = GetString("String_AttributeREAShort"); break; case "STR": strReturn = GetString("String_AttributeSTRShort"); break; case "CHA": strReturn = GetString("String_AttributeCHAShort"); break; case "INT": strReturn = GetString("String_AttributeINTShort"); break; case "LOG": strReturn = GetString("String_AttributeLOGShort"); break; case "WIL": strReturn = GetString("String_AttributeWILShort"); break; case "EDG": strReturn = GetString("String_AttributeEDGShort"); break; case "MAG": strReturn = GetString("String_AttributeMAGShort"); break; case "RES": strReturn = GetString("String_AttributeRESShort"); break; case "DEP": strReturn = GetString("String_AttributeDEPShort"); break; default: string strExtraNoQuotes = strExtra.FastEscape('\"'); XmlDocument objXmlDocument = XmlManager.Load("weapons.xml"); XmlNode objNode = objXmlDocument.SelectSingleNode("/chummer/categories/category[. = \"" + strExtraNoQuotes + "\"]"); if (objNode?.Attributes?["translate"] != null) { return(objNode.Attributes["translate"].InnerText); } // Look in Weapons. objNode = objXmlDocument.SelectSingleNode("/chummer/weapons/weapon[name = \"" + strExtraNoQuotes + "\"]"); if (objNode?["translate"] != null) { return(objNode["translate"].InnerText); } // Look in Skills. objXmlDocument = XmlManager.Load("skills.xml"); objNode = objXmlDocument.SelectSingleNode("/chummer/skills/skill[name = \"" + strExtraNoQuotes + "\"]"); if (objNode?["translate"] != null) { return(objNode["translate"].InnerText); } XmlNodeList objNodelist = objXmlDocument.SelectNodes("/chummer/skills/skill/specs/spec"); foreach (XmlNode objXmlNode in objNodelist) { if (objXmlNode.InnerText == strExtra) { if (objXmlNode.Attributes?["translate"] != null) { return(objXmlNode.Attributes["translate"].InnerText); } } } // Look in Skill Groups. objNode = objXmlDocument.SelectSingleNode("/chummer/skillgroups/name[. = \"" + strExtraNoQuotes + "\"]"); if (objNode?.Attributes?["translate"] != null) { return(objNode.Attributes["translate"].InnerText); } // Look in Licences. objXmlDocument = XmlManager.Load("licenses.xml"); objNode = objXmlDocument.SelectSingleNode("/chummer/licenses/license[. = \"" + strExtraNoQuotes + "\"]"); if (objNode?.Attributes?["translate"] != null) { return(objNode.Attributes["translate"].InnerText); } // Look in Mentors. objXmlDocument = XmlManager.Load("mentors.xml"); objNode = objXmlDocument.SelectSingleNode("/chummer/mentors/mentor[name = \"" + strExtraNoQuotes + "\"]"); if (objNode?["translate"] != null) { return(objNode["translate"].InnerText); } objNode = objXmlDocument.SelectSingleNode("/chummer/mentors/mentor/choices/choice[name = \"" + strExtraNoQuotes + "\"]"); if (objNode?["translate"] != null) { return(objNode["translate"].InnerText); } // Look in Paragons. objXmlDocument = XmlManager.Load("paragons.xml"); objNode = objXmlDocument.SelectSingleNode("/chummer/mentors/mentor[name = \"" + strExtraNoQuotes + "\"]"); if (objNode?["translate"] != null) { return(objNode["translate"].InnerText); } objNode = objXmlDocument.SelectSingleNode("/chummer/mentors/mentor/choices/choice[name = \"" + strExtraNoQuotes + "\"]"); if (objNode?["translate"] != null) { return(objNode["translate"].InnerText); } break; } } // If no translation could be found, just use whatever we were passed. if (string.IsNullOrEmpty(strReturn) || strReturn.Contains("Error finding string for key - ")) { strReturn = strExtra; } return(strReturn); }
/// <summary> /// Returns a current language translation given an improvement name. /// </summary> /// <param name="strImprovementType"> The selector for the target translation. Often just _strSelect. </param> /// <param name="strToTranslate"> The string which to translate. Usually name. Guid in the case of adept powers.</param> /// <returns></returns> private string TranslateField(string strImprovementType, string strToTranslate) { XmlNode objXmlNode; switch (strImprovementType) { case "SelectAttribute": case "SelectPhysicalAttribute": case "SelectMentalAttribute": case "SelectSpecialAttribute": return(strToTranslate == "MAGAdept" ? LanguageManager.GetString("String_AttributeMAGShort", GlobalOptions.Language) + LanguageManager.GetString("String_Space", GlobalOptions.Language) + '(' + LanguageManager.GetString("String_DescAdept", GlobalOptions.Language) + ')' : LanguageManager.GetString("String_Attribute" + strToTranslate + "Short", GlobalOptions.Language)); case "SelectSkill": if (strToTranslate.Contains("Exotic Melee Weapon") || strToTranslate.Contains("Exotic Ranged Weapon") || strToTranslate.Contains("Pilot Exotic Vehicle")) { string[] astrToTranslateParts = strToTranslate.Split('('); astrToTranslateParts[0] = astrToTranslateParts[0].Trim(); astrToTranslateParts[1] = astrToTranslateParts[1].Substring(0, astrToTranslateParts[1].Length - 1); objXmlNode = XmlManager.Load("skills.xml").SelectSingleNode("/chummer/skills/skill[name = \"" + astrToTranslateParts[0] + "\"]"); string strFirstPartTranslated = objXmlNode?.SelectSingleNode("translate")?.InnerText ?? objXmlNode?.SelectSingleNode("name")?.InnerText ?? astrToTranslateParts[0]; return($"{strFirstPartTranslated}{LanguageManager.GetString("String_Space", GlobalOptions.Language)}({LanguageManager.TranslateExtra(astrToTranslateParts[1], GlobalOptions.Language)})"); } else { objXmlNode = XmlManager.Load("skills.xml").SelectSingleNode("/chummer/skills/skill[name = \"" + strToTranslate + "\"]"); return(objXmlNode?.SelectSingleNode("translate")?.InnerText ?? objXmlNode?.SelectSingleNode("name")?.InnerText ?? strToTranslate); } case "SelectKnowSkill": objXmlNode = XmlManager.Load("skills.xml").SelectSingleNode("/chummer/knowledgeskills/skill[name = \"" + strToTranslate + "\"]"); return(objXmlNode?.SelectSingleNode("translate")?.InnerText ?? objXmlNode?.SelectSingleNode("name")?.InnerText ?? strToTranslate); case "SelectSkillCategory": objXmlNode = XmlManager.Load("skills.xml").SelectSingleNode("/chummer/categories/category[. = \"" + strToTranslate + "\"]"); return(objXmlNode?.Attributes?["translate"]?.InnerText ?? objXmlNode?.SelectSingleNode(".")?.InnerText ?? strToTranslate); case "SelectSkillGroup": objXmlNode = XmlManager.Load("skills.xml").SelectSingleNode("/chummer/skillgroups/name[. = \"" + strToTranslate + "\"]"); return(objXmlNode?.Attributes?["translate"]?.InnerText ?? objXmlNode?.SelectSingleNode(".")?.InnerText ?? strToTranslate); case "SelectWeaponCategory": objXmlNode = XmlManager.Load("weapons.xml").SelectSingleNode("/chummer/categories/category[. = \"" + strToTranslate + "\"]"); return(objXmlNode?.Attributes?["translate"]?.InnerText ?? objXmlNode?.SelectSingleNode(".")?.InnerText ?? strToTranslate); case "SelectSpellCategory": objXmlNode = XmlManager.Load("spells.xml").SelectSingleNode("/chummer/categories/category[. = \"" + strToTranslate + "\"]"); return(objXmlNode?.Attributes?["translate"]?.InnerText ?? objXmlNode?.SelectSingleNode(".")?.InnerText ?? strToTranslate); case "SelectAdeptPower": objXmlNode = XmlManager.Load("powers.xml").SelectSingleNode("/chummer/powers/power[id = \"" + strToTranslate + "\" or name = \"" + strToTranslate + "\"]"); return(objXmlNode?.SelectSingleNode("translate")?.InnerText ?? objXmlNode?.SelectSingleNode("name")?.InnerText ?? strToTranslate); default: return(strToTranslate); } }
private void BuildComplexFormList() { bool blnCheckForOptional = false; XmlNode objXmlCritter = null; if (_objCharacter.IsCritter) { XmlDocument objXmlCritterDocument = XmlManager.Load("critters.xml"); objXmlCritter = objXmlCritterDocument.SelectSingleNode("/chummer/metatypes/metatype[name = \"" + _objCharacter.Metatype + "\"]"); if (objXmlCritter.InnerXml.Contains("<optionalcomplexforms>")) { blnCheckForOptional = true; } } string strFilter = "(" + _objCharacter.Options.BookXPath() + ")"; if (txtSearch.TextLength != 0) { // Treat everything as being uppercase so the search is case-insensitive. string strSearchText = txtSearch.Text.ToUpper(); strFilter += " and ((contains(translate(name,'abcdefghijklmnopqrstuvwxyzàáâãäåçèéêëìíîïñòóôõöùúûüýß','ABCDEFGHIJKLMNOPQRSTUVWXYZÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝß'), \"" + strSearchText + "\") and not(translate)) or contains(translate(translate,'abcdefghijklmnopqrstuvwxyzàáâãäåçèéêëìíîïñòóôõöùúûüýß','ABCDEFGHIJKLMNOPQRSTUVWXYZÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝß'), \"" + strSearchText + "\"))"; } // Populate the Program list. XmlNodeList objXmlNodeList = _objXmlDocument.SelectNodes("/chummer/complexforms/complexform[" + strFilter + "]"); List <ListItem> lstComplexFormItems = new List <ListItem>(); foreach (XmlNode objXmlProgram in objXmlNodeList) { string strName = objXmlProgram["name"]?.InnerText ?? string.Empty; // If this is a Sprite with Optional Complex Forms, see if this Complex Form is allowed. if (blnCheckForOptional) { bool blnAdd = false; foreach (XmlNode objXmlForm in objXmlCritter?.SelectNodes("optionalcomplexforms/complexform")) { if (objXmlForm.InnerText == strName) { blnAdd = true; break; } } if (!blnAdd) { continue; } } lstComplexFormItems.Add(new ListItem(objXmlProgram["id"].InnerText, objXmlProgram["translate"]?.InnerText ?? strName)); } lstComplexFormItems.Sort(CompareListItems.CompareNames); lstPrograms.BeginUpdate(); lstPrograms.DataSource = null; lstPrograms.ValueMember = "Value"; lstPrograms.DisplayMember = "Name"; lstPrograms.DataSource = lstComplexFormItems; lstPrograms.EndUpdate(); }
private void frmMasterIndex_Load(object sender, EventArgs e) { using (var op_load_frm_masterindex = Timekeeper.StartSyncron("op_load_frm_masterindex", null, CustomActivity.OperationType.RequestOperation, null)) { ConcurrentBag <ListItem> lstItemsForLoading = new ConcurrentBag <ListItem>(); ConcurrentBag <ListItem> lstFileNamesWithItemsForLoading = new ConcurrentBag <ListItem>(); using (_ = Timekeeper.StartSyncron("load_frm_masterindex_load_entries", op_load_frm_masterindex)) { Parallel.ForEach(_lstFileNames, strFileName => { XPathNavigator xmlBaseNode = XmlManager.Load(strFileName).GetFastNavigator().SelectSingleNode("/chummer"); if (xmlBaseNode != null) { bool blnLoopFileNameHasItems = false; foreach (XPathNavigator xmlItemNode in xmlBaseNode.Select(".//*[source and page]")) { blnLoopFileNameHasItems = true; string strName = xmlItemNode.SelectSingleNode("name")?.Value; string strDisplayName = xmlItemNode.SelectSingleNode("translate")?.Value ?? strName ?? xmlItemNode.SelectSingleNode("id")?.Value ?? LanguageManager.GetString("String_Unknown"); string strSource = xmlItemNode.SelectSingleNode("source")?.Value; string strPage = xmlItemNode.SelectSingleNode("page")?.Value; string strDisplayPage = xmlItemNode.SelectSingleNode("altpage")?.Value ?? strPage; string strEnglishNameOnPage = xmlItemNode.SelectSingleNode("nameonpage")?.Value ?? strName; string strTranslatedNameOnPage = xmlItemNode.SelectSingleNode("altnameonpage")?.Value ?? strDisplayName; string strNotes = xmlItemNode.SelectSingleNode("altnotes")?.Value ?? xmlItemNode.SelectSingleNode("notes")?.Value; MasterIndexEntry objEntry = new MasterIndexEntry( strDisplayName, strFileName, new SourceString(strSource, strPage, GlobalOptions.DefaultLanguage, GlobalOptions.InvariantCultureInfo), new SourceString(strSource, strDisplayPage, GlobalOptions.Language, GlobalOptions.CultureInfo), strEnglishNameOnPage, strTranslatedNameOnPage); lstItemsForLoading.Add(new ListItem(objEntry, strDisplayName)); if (!string.IsNullOrEmpty(strNotes)) { _dicCachedNotes.TryAdd(objEntry, strNotes); } } if (blnLoopFileNameHasItems) { lstFileNamesWithItemsForLoading.Add(new ListItem(strFileName, strFileName)); } } }); } using (_ = Timekeeper.StartSyncron("load_frm_masterindex_populate_entries", op_load_frm_masterindex)) { Dictionary <Tuple <string, SourceString>, HashSet <string> > dicHelper = new Dictionary <Tuple <string, SourceString>, HashSet <string> >(lstItemsForLoading.Count); foreach (ListItem objItem in lstItemsForLoading) { MasterIndexEntry objEntry = (MasterIndexEntry)objItem.Value; Tuple <string, SourceString> objKey = new Tuple <string, SourceString>(objEntry.DisplayName.ToUpperInvariant(), objEntry.DisplaySource); if (dicHelper.TryGetValue(objKey, out HashSet <string> setFileNames)) { setFileNames.UnionWith(objEntry.FileNames); } else { _lstItems.Add(objItem); // Not using AddRange because of potential memory issues dicHelper.Add(objKey, objEntry.FileNames); } } _lstFileNamesWithItems.AddRange(lstFileNamesWithItemsForLoading); } using (_ = Timekeeper.StartSyncron("load_frm_masterindex_sort_entries", op_load_frm_masterindex)) { _lstItems.Sort(CompareListItems.CompareNames); _lstFileNamesWithItems.Sort(CompareListItems.CompareNames); } using (_ = Timekeeper.StartSyncron("load_frm_masterindex_populate_controls", op_load_frm_masterindex)) { _lstFileNamesWithItems.Insert(0, new ListItem(string.Empty, LanguageManager.GetString("String_All"))); cboFile.BeginUpdate(); cboFile.ValueMember = nameof(ListItem.Value); cboFile.DisplayMember = nameof(ListItem.Name); cboFile.DataSource = _lstFileNamesWithItems; cboFile.SelectedIndex = 0; cboFile.EndUpdate(); lstItems.BeginUpdate(); lstItems.ValueMember = nameof(ListItem.Value); lstItems.DisplayMember = nameof(ListItem.Name); lstItems.DataSource = _lstItems; lstItems.SelectedIndex = -1; lstItems.EndUpdate(); _blnSkipRefresh = false; } } }
private void frmMasterIndex_Load(object sender, EventArgs e) { using (var op_load_frm_masterindex = Timekeeper.StartSyncron("op_load_frm_masterindex", null, CustomActivity.OperationType.RequestOperation, null)) { HashSet <string> setValidCodes = new HashSet <string>(); XmlNodeList lstBookNodes = XmlManager.Load("books.xml").SelectNodes("/chummer/books/book/code"); if (lstBookNodes?.Count > 0) { foreach (XmlNode xmlBookNode in lstBookNodes) { setValidCodes.Add(xmlBookNode.InnerText); } } string strSourceFilter = setValidCodes.Count > 0 ? new StringBuilder("(") .AppendJoin(" or ", setValidCodes.Select(x => "source = \'" + x + "\'")) .Append(')').ToString() : "source"; ConcurrentBag <ListItem> lstItemsForLoading = new ConcurrentBag <ListItem>(); ConcurrentBag <ListItem> lstFileNamesWithItemsForLoading = new ConcurrentBag <ListItem>(); using (_ = Timekeeper.StartSyncron("load_frm_masterindex_load_entries", op_load_frm_masterindex)) { Parallel.ForEach(_lstFileNames, strFileName => { XPathNavigator xmlBaseNode = XmlManager.Load(strFileName).GetFastNavigator().SelectSingleNode("/chummer"); if (xmlBaseNode != null) { bool blnLoopFileNameHasItems = false; foreach (XPathNavigator xmlItemNode in xmlBaseNode.Select(".//*[page and " + strSourceFilter + ']')) { blnLoopFileNameHasItems = true; string strName = xmlItemNode.SelectSingleNode("name")?.Value; string strDisplayName = xmlItemNode.SelectSingleNode("translate")?.Value ?? strName ?? xmlItemNode.SelectSingleNode("id")?.Value ?? LanguageManager.GetString("String_Unknown"); string strSource = xmlItemNode.SelectSingleNode("source")?.Value; string strPage = xmlItemNode.SelectSingleNode("page")?.Value; string strDisplayPage = xmlItemNode.SelectSingleNode("altpage")?.Value ?? strPage; string strEnglishNameOnPage = xmlItemNode.SelectSingleNode("nameonpage")?.Value ?? strName; string strTranslatedNameOnPage = xmlItemNode.SelectSingleNode("altnameonpage")?.Value ?? strDisplayName; string strNotes = xmlItemNode.SelectSingleNode("altnotes")?.Value ?? xmlItemNode.SelectSingleNode("notes")?.Value; MasterIndexEntry objEntry = new MasterIndexEntry( strDisplayName, strFileName, new SourceString(strSource, strPage, GlobalOptions.DefaultLanguage, GlobalOptions.InvariantCultureInfo), new SourceString(strSource, strDisplayPage, GlobalOptions.Language, GlobalOptions.CultureInfo), strEnglishNameOnPage, strTranslatedNameOnPage); lstItemsForLoading.Add(new ListItem(objEntry, strDisplayName)); if (!string.IsNullOrEmpty(strNotes)) { _dicCachedNotes.TryAdd(objEntry, strNotes); } } if (blnLoopFileNameHasItems) { lstFileNamesWithItemsForLoading.Add(new ListItem(strFileName, strFileName)); } } }); } using (_ = Timekeeper.StartSyncron("load_frm_masterindex_populate_entries", op_load_frm_masterindex)) { string strSpace = LanguageManager.GetString("String_Space"); Dictionary <string, List <ListItem> > dicHelper = new Dictionary <string, List <ListItem> >(lstItemsForLoading.Count); foreach (ListItem objItem in lstItemsForLoading) { MasterIndexEntry objEntry = (MasterIndexEntry)objItem.Value; string strKey = objEntry.DisplayName.ToUpperInvariant(); if (dicHelper.TryGetValue(strKey, out List <ListItem> lstExistingItems)) { ListItem objExistingItem = lstExistingItems.FirstOrDefault(x => objEntry.DisplaySource.Equals(((MasterIndexEntry)x.Value).DisplaySource)); if (objExistingItem.Value != null) { ((MasterIndexEntry)objExistingItem.Value).FileNames.UnionWith(objEntry.FileNames); } else { List <ListItem> lstItemsNeedingNameChanges = lstExistingItems.Where(x => !objEntry.FileNames.IsSubsetOf(((MasterIndexEntry)x.Value).FileNames)).ToList(); if (lstItemsNeedingNameChanges.Count == 0) { _lstItems.Add(objItem); // Not using AddRange because of potential memory issues lstExistingItems.Add(objItem); } else { ListItem objItemToAdd = new ListItem(objItem.Value, new StringBuilder(objItem.Name) .Append(strSpace).Append('[').AppendJoin(',' + strSpace, objEntry.FileNames).Append(']').ToString()); _lstItems.Add(objItemToAdd); // Not using AddRange because of potential memory issues lstExistingItems.Add(objItemToAdd); foreach (ListItem objToRename in lstItemsNeedingNameChanges) { _lstItems.Remove(objToRename); lstExistingItems.Remove(objToRename); MasterIndexEntry objExistingEntry = (MasterIndexEntry)objToRename.Value; objItemToAdd = new ListItem(objToRename.Value, new StringBuilder(objExistingEntry.DisplayName) .Append(strSpace).Append('[').AppendJoin(',' + strSpace, objExistingEntry.FileNames).Append(']').ToString()); _lstItems.Add(objItemToAdd); // Not using AddRange because of potential memory issues lstExistingItems.Add(objItemToAdd); } } } } else { _lstItems.Add(objItem); // Not using AddRange because of potential memory issues dicHelper.Add(strKey, new List <ListItem>(objItem.Yield())); } } _lstFileNamesWithItems.AddRange(lstFileNamesWithItemsForLoading); } using (_ = Timekeeper.StartSyncron("load_frm_masterindex_sort_entries", op_load_frm_masterindex)) { _lstItems.Sort(CompareListItems.CompareNames); _lstFileNamesWithItems.Sort(CompareListItems.CompareNames); } using (_ = Timekeeper.StartSyncron("load_frm_masterindex_populate_controls", op_load_frm_masterindex)) { _lstFileNamesWithItems.Insert(0, new ListItem(string.Empty, LanguageManager.GetString("String_All"))); cboFile.BeginUpdate(); cboFile.ValueMember = nameof(ListItem.Value); cboFile.DisplayMember = nameof(ListItem.Name); cboFile.DataSource = _lstFileNamesWithItems; cboFile.SelectedIndex = 0; cboFile.EndUpdate(); lstItems.BeginUpdate(); lstItems.ValueMember = nameof(ListItem.Value); lstItems.DisplayMember = nameof(ListItem.Name); lstItems.DataSource = _lstItems; lstItems.SelectedIndex = -1; lstItems.EndUpdate(); _blnSkipRefresh = false; } } }
/// <summary> /// Print the object's XML to the XmlWriter. /// </summary> /// <param name="objWriter">XmlTextWriter to write with.</param> /// <param name="objCulture">Culture in which to print numbers.</param> /// <param name="strLanguageToPrint">Language in which to print.</param> public void Print(XmlTextWriter objWriter, CultureInfo objCulture, string strLanguageToPrint) { // Translate the Critter name if applicable. string strName = Name; XmlNode objXmlCritterNode = GetNode(strLanguageToPrint); if (strLanguageToPrint != GlobalOptions.DefaultLanguage) { strName = objXmlCritterNode?["translate"]?.InnerText ?? Name; } objWriter.WriteStartElement("spirit"); objWriter.WriteElementString("name", strName); objWriter.WriteElementString("name_english", Name); objWriter.WriteElementString("crittername", CritterName); objWriter.WriteElementString("fettered", Fettered.ToString(GlobalOptions.InvariantCultureInfo)); objWriter.WriteElementString("bound", Bound.ToString(GlobalOptions.InvariantCultureInfo)); objWriter.WriteElementString("services", ServicesOwed.ToString(objCulture)); objWriter.WriteElementString("force", Force.ToString(objCulture)); objWriter.WriteElementString("ratinglabel", LanguageManager.GetString(RatingLabel, strLanguageToPrint)); if (objXmlCritterNode != null) { //Attributes for spirits, named differently as to not confuse <attribtue> Dictionary <string, int> dicAttributes = new Dictionary <string, int>(); objWriter.WriteStartElement("spiritattributes"); foreach (string strAttribute in new[] { "bod", "agi", "rea", "str", "cha", "int", "wil", "log", "ini" }) { string strInner = string.Empty; if (objXmlCritterNode.TryGetStringFieldQuickly(strAttribute, ref strInner)) { object objProcess = CommonFunctions.EvaluateInvariantXPath(strInner.Replace("F", _intForce.ToString()), out bool blnIsSuccess); int intValue = Math.Max(blnIsSuccess ? Convert.ToInt32(objProcess) : _intForce, 1); objWriter.WriteElementString(strAttribute, intValue.ToString(objCulture)); dicAttributes[strAttribute] = intValue; } } objWriter.WriteEndElement(); //Dump skills, (optional)powers if present to output XPathNavigator xmlSpiritPowersBaseChummerNode = XmlManager.Load("spiritpowers.xml", strLanguageToPrint).GetFastNavigator().SelectSingleNode("/chummer"); XPathNavigator xmlCritterPowersBaseChummerNode = XmlManager.Load("critterpowers.xml", strLanguageToPrint).GetFastNavigator().SelectSingleNode("/chummer"); XmlNode xmlPowersNode = objXmlCritterNode["powers"]; if (xmlPowersNode != null) { objWriter.WriteStartElement("powers"); foreach (XmlNode objXmlPowerNode in xmlPowersNode.ChildNodes) { PrintPowerInfo(objWriter, xmlSpiritPowersBaseChummerNode, xmlCritterPowersBaseChummerNode, objXmlPowerNode, GlobalOptions.Language); } objWriter.WriteEndElement(); } xmlPowersNode = objXmlCritterNode["optionalpowers"]; if (xmlPowersNode != null) { objWriter.WriteStartElement("optionalpowers"); foreach (XmlNode objXmlPowerNode in xmlPowersNode.ChildNodes) { PrintPowerInfo(objWriter, xmlSpiritPowersBaseChummerNode, xmlCritterPowersBaseChummerNode, objXmlPowerNode, GlobalOptions.Language); } objWriter.WriteEndElement(); } xmlPowersNode = objXmlCritterNode["skills"]; if (xmlPowersNode != null) { XmlDocument xmlSkillsDocument = XmlManager.Load("skills.xml", strLanguageToPrint); objWriter.WriteStartElement("skills"); foreach (XmlNode xmlSkillNode in xmlPowersNode.ChildNodes) { string strAttrName = xmlSkillNode.Attributes?["attr"]?.Value ?? string.Empty; if (!dicAttributes.TryGetValue(strAttrName, out int intAttrValue)) { intAttrValue = _intForce; } int intDicepool = intAttrValue + _intForce; string strEnglishName = xmlSkillNode.InnerText; string strTranslatedName = xmlSkillsDocument.SelectSingleNode("/chummer/skills/skill[name = \"" + strEnglishName + "\"]/translate")?.InnerText ?? xmlSkillsDocument.SelectSingleNode("/chummer/knowledgeskills/skill[name = \"" + strEnglishName + "\"]/translate")?.InnerText ?? strEnglishName; objWriter.WriteStartElement("skill"); objWriter.WriteElementString("name", strTranslatedName); objWriter.WriteElementString("name_english", strEnglishName); objWriter.WriteElementString("attr", strAttrName); objWriter.WriteElementString("pool", intDicepool.ToString(objCulture)); objWriter.WriteEndElement(); } objWriter.WriteEndElement(); } xmlPowersNode = objXmlCritterNode["weaknesses"]; if (xmlPowersNode != null) { objWriter.WriteStartElement("weaknesses"); foreach (XmlNode objXmlPowerNode in xmlPowersNode.ChildNodes) { PrintPowerInfo(objWriter, xmlSpiritPowersBaseChummerNode, xmlCritterPowersBaseChummerNode, objXmlPowerNode, GlobalOptions.Language); } objWriter.WriteEndElement(); } //Page in book for reference string strSource = string.Empty; string strPage = string.Empty; if (objXmlCritterNode.TryGetStringFieldQuickly("source", ref strSource)) { objWriter.WriteElementString("source", CommonFunctions.LanguageBookShort(strSource, strLanguageToPrint)); } if (objXmlCritterNode.TryGetStringFieldQuickly("altpage", ref strPage) || objXmlCritterNode.TryGetStringFieldQuickly("page", ref strPage)) { objWriter.WriteElementString("page", strPage); } } objWriter.WriteElementString("bound", Bound.ToString()); objWriter.WriteElementString("type", EntityType.ToString()); if (CharacterObject.Options.PrintNotes) { objWriter.WriteElementString("notes", Notes); } PrintMugshots(objWriter); objWriter.WriteEndElement(); }
private void cmdOK_Click(object sender, EventArgs e) { // Make sure the suite and file name fields are populated. if (string.IsNullOrEmpty(txtName.Text)) { Program.MainForm.ShowMessageBox(LanguageManager.GetString("Message_CyberwareSuite_SuiteName"), LanguageManager.GetString("MessageTitle_CyberwareSuite_SuiteName"), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (string.IsNullOrEmpty(txtFileName.Text)) { Program.MainForm.ShowMessageBox(LanguageManager.GetString("Message_CyberwareSuite_FileName"), LanguageManager.GetString("MessageTitle_CyberwareSuite_FileName"), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } // Make sure the file name starts with custom and ends with _cyberware.xml. if (!txtFileName.Text.StartsWith("custom_", StringComparison.OrdinalIgnoreCase) || !txtFileName.Text.EndsWith('_' + _strType + ".xml", StringComparison.OrdinalIgnoreCase)) { Program.MainForm.ShowMessageBox(string.Format(GlobalOptions.CultureInfo, LanguageManager.GetString("Message_CyberwareSuite_InvalidFileName"), _strType), LanguageManager.GetString("MessageTitle_CyberwareSuite_InvalidFileName"), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } // See if a Suite with this name already exists for the Custom category. // This was originally done without the XmlManager, but because amends and overrides and toggling custom data directories can change names, we need to use it. string strName = txtName.Text; if (XmlManager.Load(_strType + ".xml").SelectSingleNode("/chummer/suites/suite[name = \"" + strName + "\"]") != null) { Program.MainForm.ShowMessageBox(string.Format(GlobalOptions.CultureInfo, LanguageManager.GetString("Message_CyberwareSuite_DuplicateName"), strName), LanguageManager.GetString("MessageTitle_CyberwareSuite_DuplicateName"), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } string strPath = Path.Combine(Utils.GetStartupPath, "data", txtFileName.Text); bool blnNewFile = !File.Exists(strPath); // If this is not a new file, read in the existing contents. XmlDocument objXmlCurrentDocument = new XmlDocument { XmlResolver = null }; if (!blnNewFile) { try { using (StreamReader objStreamReader = new StreamReader(strPath, Encoding.UTF8, true)) using (XmlReader objXmlReader = XmlReader.Create(objStreamReader, new XmlReaderSettings { XmlResolver = null })) objXmlCurrentDocument.Load(objXmlReader); } catch (IOException ex) { Program.MainForm.ShowMessageBox(ex.ToString()); return; } catch (XmlException ex) { Program.MainForm.ShowMessageBox(ex.ToString()); return; } } using (FileStream objStream = new FileStream(strPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)) { using (XmlTextWriter objWriter = new XmlTextWriter(objStream, Encoding.UTF8) { Formatting = Formatting.Indented, Indentation = 1, IndentChar = '\t' }) { objWriter.WriteStartDocument(); // <chummer> objWriter.WriteStartElement("chummer"); if (!blnNewFile) { // <cyberwares> objWriter.WriteStartElement(_strType + "s"); using (XmlNodeList xmlCyberwareList = objXmlCurrentDocument.SelectNodes("/chummer/" + _strType + "s")) if (xmlCyberwareList?.Count > 0) { foreach (XmlNode xmlCyberware in xmlCyberwareList) { xmlCyberware.WriteContentTo(objWriter); } } // </cyberwares> objWriter.WriteEndElement(); } // <suites> objWriter.WriteStartElement("suites"); // If this is not a new file, write out the current contents. if (!blnNewFile) { using (XmlNodeList xmlCyberwareList = objXmlCurrentDocument.SelectNodes("/chummer/suites")) if (xmlCyberwareList?.Count > 0) { foreach (XmlNode xmlCyberware in xmlCyberwareList) { xmlCyberware.WriteContentTo(objWriter); } } } string strGrade = string.Empty; // Determine the Grade of Cyberware. foreach (Cyberware objCyberware in _objCharacter.Cyberware) { if (objCyberware.SourceType == _objSource) { strGrade = objCyberware.Grade.Name; break; } } // <suite> objWriter.WriteStartElement("suite"); // <name /> objWriter.WriteElementString("id", Guid.NewGuid().ToString()); // <name /> objWriter.WriteElementString("name", txtName.Text); // <grade /> objWriter.WriteElementString("grade", strGrade); // <cyberwares> objWriter.WriteStartElement(_strType + "s"); // Write out the Cyberware. foreach (Cyberware objCyberware in _objCharacter.Cyberware) { if (objCyberware.SourceType == _objSource) { // <cyberware> objWriter.WriteStartElement(_strType); objWriter.WriteElementString("name", objCyberware.Name); if (objCyberware.Rating > 0) { objWriter.WriteElementString("rating", objCyberware.Rating.ToString(GlobalOptions.InvariantCultureInfo)); } // Write out child items. if (objCyberware.Children.Count > 0) { // <cyberwares> objWriter.WriteStartElement(_strType + "s"); foreach (Cyberware objChild in objCyberware.Children) { // Do not include items that come with the base item by default. if (objChild.Capacity != "[*]") { objWriter.WriteStartElement(_strType); objWriter.WriteElementString("name", objChild.Name); if (objChild.Rating > 0) { objWriter.WriteElementString("rating", objChild.Rating.ToString(GlobalOptions.InvariantCultureInfo)); } // </cyberware> objWriter.WriteEndElement(); } } // </cyberwares> objWriter.WriteEndElement(); } // </cyberware> objWriter.WriteEndElement(); } } // </cyberwares> objWriter.WriteEndElement(); // </suite> objWriter.WriteEndElement(); // </chummer> objWriter.WriteEndElement(); objWriter.WriteEndDocument(); } } Program.MainForm.ShowMessageBox(string.Format(GlobalOptions.CultureInfo, LanguageManager.GetString("Message_CyberwareSuite_SuiteCreated"), txtName.Text), LanguageManager.GetString("MessageTitle_CyberwareSuite_SuiteCreated"), MessageBoxButtons.OK, MessageBoxIcon.Information); DialogResult = DialogResult.OK; }
public frmMain() { InitializeComponent(); Version version = Assembly.GetExecutingAssembly().GetName().Version; string strCurrentVersion = $"{version.Major}.{version.Minor}.{version.Build}"; Text = string.Format("Chummer 5a - Version " + strCurrentVersion); #if DEBUG Text += " DEBUG BUILD"; #endif LanguageManager.Load(GlobalOptions.Language, this); /** Dashboard **/ //this.toolsMenu.DropDownItems.Add("GM Dashboard").Click += this.dashboardToolStripMenuItem_Click; /** End Dashboard **/ // If Automatic Updates are enabled, check for updates immediately. #if RELEASE if (Utils.GitUpdateAvailable() > 0) { if (GlobalOptions.AutomaticUpdate) { frmUpdate frmAutoUpdate = new frmUpdate(); frmAutoUpdate.SilentMode = true; frmAutoUpdate.Visible = false; frmAutoUpdate.ShowDialog(this); } else { this.Text += String.Format(" - Update {0} now available!", Utils.GitVersion()); } } #endif GlobalOptions.MRUChanged += PopulateMRU; // Delete the old executable if it exists (created by the update process). foreach (string strLoopOldFilePath in Directory.GetFiles(Application.StartupPath, "*.old")) { if (File.Exists(strLoopOldFilePath)) { File.Delete(strLoopOldFilePath); } } // Populate the MRU list. PopulateMRU(); GlobalOptions.MainForm = this; // Set the Tag for each ToolStrip item so it can be translated. foreach (ToolStripMenuItem objItem in menuStrip.Items.OfType <ToolStripMenuItem>()) { if (objItem.Tag != null) { objItem.Text = LanguageManager.GetString(objItem.Tag.ToString()); } } // ToolStrip Items. foreach (ToolStrip objToolStrip in Controls.OfType <ToolStrip>()) { foreach (ToolStripButton objButton in objToolStrip.Items.OfType <ToolStripButton>()) { if (objButton.Tag != null) { objButton.Text = LanguageManager.GetString(objButton.Tag.ToString()); } } } // Attempt to cache all XML files that are used the most. Timekeeper.Start("cache_load"); XmlManager.Load("armor.xml"); XmlManager.Load("bioware.xml"); XmlManager.Load("books.xml"); XmlManager.Load("complexforms.xml"); XmlManager.Load("contacts.xml"); XmlManager.Load("critters.xml"); XmlManager.Load("critterpowers.xml"); XmlManager.Load("cyberware.xml"); // XmlManager.Load("drugcomponents.xml"); TODO: Re-enable when Custom Drugs branch is merged XmlManager.Load("echoes.xml"); XmlManager.Load("gameplayoptions.xml"); XmlManager.Load("gear.xml"); XmlManager.Load("improvements.xml"); XmlManager.Load("licenses.xml"); XmlManager.Load("lifemodules.xml"); XmlManager.Load("lifestyles.xml"); XmlManager.Load("martialarts.xml"); XmlManager.Load("mentors.xml"); XmlManager.Load("metamagic.xml"); XmlManager.Load("metatypes.xml"); XmlManager.Load("options.xml"); XmlManager.Load("packs.xml"); XmlManager.Load("powers.xml"); XmlManager.Load("priorities.xml"); XmlManager.Load("programs.xml"); XmlManager.Load("qualities.xml"); XmlManager.Load("ranges.xml"); XmlManager.Load("skills.xml"); XmlManager.Load("spells.xml"); XmlManager.Load("spiritpowers.xml"); XmlManager.Load("traditions.xml"); XmlManager.Load("vehicles.xml"); XmlManager.Load("weapons.xml"); Timekeeper.Finish("cache_load"); frmCharacterRoster frmCharacter = new frmCharacterRoster(); frmCharacter.MdiParent = this; // Retrieve the arguments passed to the application. If more than 1 is passed, we're being given the name of a file to open. string[] strArgs = Environment.GetCommandLineArgs(); if (strArgs.GetUpperBound(0) > 0) { if (strArgs[1] != "/debug") { LoadCharacter(strArgs[1]); } if (strArgs.Length > 2) { if (strArgs[2] == "/test") { frmTest frmTestData = new frmTest(); frmTestData.Show(); } } } frmCharacter.WindowState = FormWindowState.Maximized; frmCharacter.Show(); }
public frmSelectSpellCategory() { InitializeComponent(); LanguageManager.TranslateWinForm(GlobalOptions.Language, this); _objXmlDocument = XmlManager.Load("spells.xml"); }
// Rebuild the list of Spirits/Sprites based on the character's selected Tradition/Stream. public void RebuildSpiritList(Tradition objTradition) { if (objTradition == null) { return; } string strCurrentValue = cboSpiritName.SelectedValue?.ToString() ?? _objSpirit.Name; XmlDocument objXmlDocument = _objSpirit.EntityType == SpiritType.Spirit ? XmlManager.Load("traditions.xml") : XmlManager.Load("streams.xml"); XmlDocument objXmlCritterDocument = XmlManager.Load("critters.xml"); HashSet <string> lstLimitCategories = new HashSet <string>(); foreach (Improvement improvement in _objSpirit.CharacterObject.Improvements.Where(x => x.ImproveType == Improvement.ImprovementType.LimitSpiritCategory && x.Enabled)) { lstLimitCategories.Add(improvement.ImprovedName); } List <ListItem> lstCritters = new List <ListItem>(); if (objTradition.IsCustomTradition) { string strSpiritCombat = objTradition.SpiritCombat; string strSpiritDetection = objTradition.SpiritDetection; string strSpiritHealth = objTradition.SpiritHealth; string strSpiritIllusion = objTradition.SpiritIllusion; string strSpiritManipulation = objTradition.SpiritManipulation; if ((lstLimitCategories.Count == 0 || lstLimitCategories.Contains(strSpiritCombat)) && !string.IsNullOrWhiteSpace(strSpiritCombat)) { XmlNode objXmlCritterNode = objXmlDocument.SelectSingleNode("/chummer/spirits/spirit[name = \"" + strSpiritCombat + "\"]"); lstCritters.Add(new ListItem(strSpiritCombat, objXmlCritterNode?["translate"]?.InnerText ?? strSpiritCombat)); } if ((lstLimitCategories.Count == 0 || lstLimitCategories.Contains(strSpiritDetection)) && !string.IsNullOrWhiteSpace(strSpiritDetection)) { XmlNode objXmlCritterNode = objXmlDocument.SelectSingleNode("/chummer/spirits/spirit[name = \"" + strSpiritDetection + "\"]"); lstCritters.Add(new ListItem(strSpiritDetection, objXmlCritterNode?["translate"]?.InnerText ?? strSpiritDetection)); } if ((lstLimitCategories.Count == 0 || lstLimitCategories.Contains(strSpiritHealth)) && !string.IsNullOrWhiteSpace(strSpiritHealth)) { XmlNode objXmlCritterNode = objXmlDocument.SelectSingleNode("/chummer/spirits/spirit[name = \"" + strSpiritHealth + "\"]"); lstCritters.Add(new ListItem(strSpiritHealth, objXmlCritterNode?["translate"]?.InnerText ?? strSpiritHealth)); } if ((lstLimitCategories.Count == 0 || lstLimitCategories.Contains(strSpiritIllusion)) && !string.IsNullOrWhiteSpace(strSpiritIllusion)) { XmlNode objXmlCritterNode = objXmlDocument.SelectSingleNode("/chummer/spirits/spirit[name = \"" + strSpiritIllusion + "\"]"); lstCritters.Add(new ListItem(strSpiritIllusion, objXmlCritterNode?["translate"]?.InnerText ?? strSpiritIllusion)); } if ((lstLimitCategories.Count == 0 || lstLimitCategories.Contains(strSpiritManipulation)) && !string.IsNullOrWhiteSpace(strSpiritManipulation)) { XmlNode objXmlCritterNode = objXmlDocument.SelectSingleNode("/chummer/spirits/spirit[name = \"" + strSpiritManipulation + "\"]"); lstCritters.Add(new ListItem(strSpiritManipulation, objXmlCritterNode?["translate"]?.InnerText ?? strSpiritManipulation)); } } else { if (objTradition.GetNode()?.SelectSingleNode("spirits/spirit[. = \"All\"]") != null) { if (lstLimitCategories.Count == 0) { using (XmlNodeList xmlSpiritList = objXmlDocument.SelectNodes("/chummer/spirits/spirit")) if (xmlSpiritList != null) { foreach (XmlNode objXmlCritterNode in xmlSpiritList) { string strSpiritName = objXmlCritterNode["name"]?.InnerText; lstCritters.Add(new ListItem(strSpiritName, objXmlCritterNode["translate"]?.InnerText ?? strSpiritName)); } } } else { foreach (string strSpiritName in lstLimitCategories) { XmlNode objXmlCritterNode = objXmlDocument.SelectSingleNode("/chummer/spirits/spirit[name = \"" + strSpiritName + "\"]"); lstCritters.Add(new ListItem(strSpiritName, objXmlCritterNode?["translate"]?.InnerText ?? strSpiritName)); } } } else { using (XmlNodeList xmlSpiritList = objTradition.GetNode()?.SelectSingleNode("spirits")?.ChildNodes) if (xmlSpiritList != null) { foreach (XmlNode objXmlSpirit in xmlSpiritList) { string strSpiritName = objXmlSpirit.InnerText; if (lstLimitCategories.Count == 0 || lstLimitCategories.Contains(strSpiritName)) { XmlNode objXmlCritterNode = objXmlDocument.SelectSingleNode("/chummer/spirits/spirit[name = \"" + strSpiritName + "\"]"); lstCritters.Add(new ListItem(strSpiritName, objXmlCritterNode?["translate"]?.InnerText ?? strSpiritName)); } } } } } if (_objSpirit.CharacterObject.RESEnabled) { // Add any additional Sprites the character has Access to through improvements. lstCritters.AddRange(from objImprovement in _objSpirit.CharacterObject.Improvements .Where(imp => imp.ImproveType == Improvement.ImprovementType.AddSprite && imp.Enabled) let objXmlCritterNode = objXmlDocument.SelectSingleNode("/chummer/spirits/spirit[name = \"" + objImprovement.ImprovedName + "\"]") select new ListItem(objImprovement.ImprovedName, objXmlCritterNode?["translate"]?.InnerText ?? objImprovement.ImprovedName)); } if (_objSpirit.CharacterObject.MAGEnabled) { // Add any additional Spirits the character has Access to through improvements. lstCritters.AddRange(from objImprovement in _objSpirit.CharacterObject.Improvements .Where(imp => imp.ImproveType == Improvement.ImprovementType.AddSpirit && imp.Enabled) let objXmlCritterNode = objXmlDocument.SelectSingleNode("/chummer/spirits/spirit[name = \"" + objImprovement.ImprovedName + "\"]") select new ListItem(objImprovement.ImprovedName, objXmlCritterNode?["translate"]?.InnerText ?? objImprovement.ImprovedName)); } cboSpiritName.BeginUpdate(); cboSpiritName.DisplayMember = "Name"; cboSpiritName.ValueMember = "Value"; cboSpiritName.DataSource = lstCritters; // Set the control back to its original value. cboSpiritName.SelectedValue = strCurrentValue; cboSpiritName.EndUpdate(); }
/// <summary> /// Load the Power from the XmlNode. /// </summary> /// <param name="objNode">XmlNode to load.</param> public void Load(XmlNode objNode) { _guiID = Guid.Parse(objNode["guid"].InnerText); Name = objNode["name"].InnerText; if (objNode["id"] != null) { _sourceID = Guid.Parse(objNode["id"].InnerText); } else { string strPowerName = Name; if (strPowerName.Contains('(')) { strPowerName = strPowerName.Substring(0, strPowerName.IndexOf('(') - 1); } XmlDocument objXmlDocument = XmlManager.Load("powers.xml"); XmlNode objXmlPower = objXmlDocument.SelectSingleNode("/chummer/powers/power[starts-with(./name,\"" + strPowerName + "\")]"); if (objXmlPower != null) { _sourceID = Guid.Parse(objXmlPower["id"].InnerText); } } Extra = objNode["extra"].InnerText ?? string.Empty; _strPointsPerLevel = objNode["pointsperlevel"]?.InnerText; objNode.TryGetField("action", out _strAction); if (objNode["adeptway"] != null) { _strAdeptWayDiscount = objNode["adeptway"].InnerText; } else { string strPowerName = Name; if (strPowerName.Contains('(')) { strPowerName = strPowerName.Substring(0, strPowerName.IndexOf('(') - 1); } XmlDocument objXmlDocument = XmlManager.Load("powers.xml"); XmlNode objXmlPower = objXmlDocument.SelectSingleNode("/chummer/powers/power[starts-with(./name,\"" + strPowerName + "\")]"); if (objXmlPower?["adeptway"] != null) { _strAdeptWayDiscount = objXmlPower["adeptway"].InnerText; } } Rating = Convert.ToInt32(objNode["rating"]?.InnerText); LevelsEnabled = Convert.ToBoolean(objNode["levels"]?.InnerText); objNode.TryGetBoolFieldQuickly("free", ref _blnFree); objNode.TryGetInt32FieldQuickly("maxlevel", ref _intMaxLevel); objNode.TryGetInt32FieldQuickly("freelevels", ref _intFreeLevels); objNode.TryGetBoolFieldQuickly("discounted", ref _blnDiscountedAdeptWay); objNode.TryGetBoolFieldQuickly("discountedgeas", ref _blnDiscountedGeas); objNode.TryGetStringFieldQuickly("bonussource", ref _strBonusSource); objNode.TryGetDecFieldQuickly("freepoints", ref _decFreePoints); objNode.TryGetDecFieldQuickly("extrapointcost", ref _decExtraPointCost); objNode.TryGetStringFieldQuickly("source", ref _strSource); objNode.TryGetStringFieldQuickly("page", ref _strPage); objNode.TryGetStringFieldQuickly("notes", ref _strNotes); Bonus = objNode["bonus"]; if (objNode["adeptway"] != null) { if (objNode["adeptwayrequires"] == null) { XmlNode objXmlPower = MyXmlNode; if (objXmlPower != null) { _nodAdeptWayRequirements = objXmlPower["adeptwayrequires"]; } } else { _nodAdeptWayRequirements = objNode["adeptwayrequires"]; } } if (Name != "Improved Reflexes" && Name.StartsWith("Improved Reflexes")) { XmlDocument objXmlDocument = XmlManager.Load("powers.xml"); XmlNode objXmlPower = objXmlDocument.SelectSingleNode("/chummer/powers/power[starts-with(./name,\"Improved Reflexes\")]"); if (objXmlPower != null) { int intTemp; if (int.TryParse(Name.TrimStart("Improved Reflexes", true).Trim(), out intTemp)) { Create(objXmlPower, intTemp, null, false); objNode.TryGetStringFieldQuickly("notes", ref _strNotes); } } } else { if (!objNode.InnerXml.Contains("enhancements")) { return; } XmlNodeList nodEnhancements = objNode.SelectNodes("enhancements/enhancement"); if (nodEnhancements == null) { return; } foreach (XmlNode nodEnhancement in nodEnhancements) { Enhancement objEnhancement = new Enhancement(CharacterObject); objEnhancement.Load(nodEnhancement); objEnhancement.Parent = this; Enhancements.Add(objEnhancement); } } }
private void cmdChangeSelection_Click(object sender, EventArgs e) { switch (_strSelect) { case "SelectActionDicePool": List <ListItem> lstActions = new List <ListItem>(); using (XmlNodeList xmlActionList = XmlManager.Load("actions.xml").SelectNodes("/chummer/actions/action")) if (xmlActionList != null) { foreach (XmlNode xmlAction in xmlActionList) { lstActions.Add(new ListItem(xmlAction["name"].InnerText, xmlAction["translate"]?.InnerText ?? xmlAction["name"]?.InnerText)); } } frmSelectItem select = new frmSelectItem { Description = LanguageManager.GetString("Title_SelectAction", GlobalOptions.Language), DropdownItems = lstActions }; select.ShowDialog(this); if (select.DialogResult == DialogResult.OK) { txtSelect.Text = select.SelectedName; txtTranslateSelection.Text = TranslateField(_strSelect, select.SelectedName); } break; case "SelectAttribute": { List <string> lstAbbrevs = new List <string>(Backend.Attributes.AttributeSection.AttributeStrings); lstAbbrevs.Remove("ESS"); if (!_objCharacter.MAGEnabled) { lstAbbrevs.Remove("MAG"); lstAbbrevs.Remove("MAGAdept"); } else if (!_objCharacter.IsMysticAdept || !_objCharacter.Options.MysAdeptSecondMAGAttribute) { lstAbbrevs.Remove("MAGAdept"); } if (!_objCharacter.RESEnabled) { lstAbbrevs.Remove("RES"); } if (!_objCharacter.DEPEnabled) { lstAbbrevs.Remove("DEP"); } frmSelectAttribute frmPickAttribute = new frmSelectAttribute(lstAbbrevs.ToArray()) { Description = LanguageManager.GetString("Title_SelectAttribute", GlobalOptions.Language) }; frmPickAttribute.ShowDialog(this); if (frmPickAttribute.DialogResult == DialogResult.OK) { txtSelect.Text = frmPickAttribute.SelectedAttribute; txtTranslateSelection.Text = TranslateField(_strSelect, frmPickAttribute.SelectedAttribute); } } break; case "SelectMentalAttribute": { frmSelectAttribute frmPickAttribute = new frmSelectAttribute(Backend.Attributes.AttributeSection.MentalAttributes.ToArray()) { Description = LanguageManager.GetString("Title_SelectAttribute", GlobalOptions.Language) }; frmPickAttribute.ShowDialog(this); if (frmPickAttribute.DialogResult == DialogResult.OK) { txtSelect.Text = frmPickAttribute.SelectedAttribute; txtTranslateSelection.Text = TranslateField(_strSelect, frmPickAttribute.SelectedAttribute); } } break; case "SelectPhysicalAttribute": { frmSelectAttribute frmPickAttribute = new frmSelectAttribute(Backend.Attributes.AttributeSection.PhysicalAttributes.ToArray()) { Description = LanguageManager.GetString("Title_SelectAttribute", GlobalOptions.Language) }; frmPickAttribute.ShowDialog(this); if (frmPickAttribute.DialogResult == DialogResult.OK) { txtSelect.Text = frmPickAttribute.SelectedAttribute; txtTranslateSelection.Text = TranslateField(_strSelect, frmPickAttribute.SelectedAttribute); } } break; case "SelectSpecialAttribute": { List <string> lstAbbrevs = new List <string>(Backend.Attributes.AttributeSection.AttributeStrings); lstAbbrevs.RemoveAll(x => Backend.Attributes.AttributeSection.PhysicalAttributes.Contains(x) || Backend.Attributes.AttributeSection.MentalAttributes.Contains(x)); lstAbbrevs.Remove("ESS"); /* * if (!_objCharacter.MAGEnabled) * { * lstAbbrevs.Remove("MAG"); * lstAbbrevs.Remove("MAGAdept"); * } * else if (!_objCharacter.IsMysticAdept || !_objCharacter.Options.MysAdeptSecondMAGAttribute) * lstAbbrevs.Remove("MAGAdept"); * * if (!_objCharacter.RESEnabled) * lstAbbrevs.Remove("RES"); * if (!_objCharacter.DEPEnabled) * lstAbbrevs.Remove("DEP"); */ frmSelectAttribute frmPickAttribute = new frmSelectAttribute(lstAbbrevs.ToArray()) { Description = LanguageManager.GetString("Title_SelectAttribute", GlobalOptions.Language) }; frmPickAttribute.ShowDialog(this); if (frmPickAttribute.DialogResult == DialogResult.OK) { txtSelect.Text = frmPickAttribute.SelectedAttribute; txtTranslateSelection.Text = TranslateField(_strSelect, frmPickAttribute.SelectedAttribute); } } break; case "SelectSkill": { frmSelectSkill frmPickSkill = new frmSelectSkill(_objCharacter) { Description = LanguageManager.GetString("Title_SelectSkill", GlobalOptions.Language) }; frmPickSkill.ShowDialog(this); if (frmPickSkill.DialogResult == DialogResult.OK) { txtSelect.Text = frmPickSkill.SelectedSkill; txtTranslateSelection.Text = TranslateField(_strSelect, frmPickSkill.SelectedSkill); } } break; case "SelectKnowSkill": { List <ListItem> lstDropdownItems = new List <ListItem>(); HashSet <string> setProcessedSkillNames = new HashSet <string>(); foreach (KnowledgeSkill objKnowledgeSkill in _objCharacter.SkillsSection.KnowledgeSkills) { lstDropdownItems.Add(new ListItem(objKnowledgeSkill.Name, objKnowledgeSkill.DisplayNameMethod(GlobalOptions.Language))); setProcessedSkillNames.Add(objKnowledgeSkill.Name); } StringBuilder objFilter = new StringBuilder(); if (setProcessedSkillNames.Count > 0) { objFilter.Append("not("); foreach (string strName in setProcessedSkillNames) { objFilter.Append("name = \"" + strName + "\" or "); } objFilter.Length -= 4; objFilter.Append(')'); } string strFilter = objFilter.Length > 0 ? '[' + objFilter.ToString() + ']' : string.Empty; using (XmlNodeList xmlSkillList = XmlManager.Load("skills.xml", GlobalOptions.Language).SelectNodes("/chummer/knowledgeskills/skill" + strFilter)) { if (xmlSkillList?.Count > 0) { foreach (XmlNode xmlSkill in xmlSkillList) { string strName = xmlSkill["name"]?.InnerText; if (!string.IsNullOrEmpty(strName)) { lstDropdownItems.Add(new ListItem(strName, xmlSkill["translate"]?.InnerText ?? strName)); } } } } lstDropdownItems.Sort(CompareListItems.CompareNames); frmSelectItem frmPickSkill = new frmSelectItem { DropdownItems = lstDropdownItems, Description = LanguageManager.GetString("Title_SelectSkill", GlobalOptions.Language) }; frmPickSkill.ShowDialog(this); if (frmPickSkill.DialogResult == DialogResult.OK) { txtSelect.Text = frmPickSkill.SelectedItem; txtTranslateSelection.Text = TranslateField(_strSelect, frmPickSkill.SelectedItem); } } break; case "SelectSkillCategory": frmSelectSkillCategory frmPickSkillCategory = new frmSelectSkillCategory { Description = LanguageManager.GetString("Title_SelectSkillCategory", GlobalOptions.Language) }; frmPickSkillCategory.ShowDialog(this); if (frmPickSkillCategory.DialogResult == DialogResult.OK) { txtSelect.Text = frmPickSkillCategory.SelectedCategory; txtTranslateSelection.Text = TranslateField(_strSelect, frmPickSkillCategory.SelectedCategory); } break; case "SelectSkillGroup": frmSelectSkillGroup frmPickSkillGroup = new frmSelectSkillGroup { Description = LanguageManager.GetString("Title_SelectSkillGroup", GlobalOptions.Language) }; frmPickSkillGroup.ShowDialog(this); if (frmPickSkillGroup.DialogResult == DialogResult.OK) { txtSelect.Text = frmPickSkillGroup.SelectedSkillGroup; txtTranslateSelection.Text = TranslateField(_strSelect, frmPickSkillGroup.SelectedSkillGroup); } break; case "SelectSpell": List <ListItem> lstSpells = new List <ListItem>(); using (XmlNodeList xmlSpellList = XmlManager.Load("spells.xml").SelectNodes("/chummer/spells/spell")) if (xmlSpellList != null) { foreach (XmlNode xmlSpell in xmlSpellList) { lstSpells.Add(new ListItem(xmlSpell["name"].InnerText, xmlSpell["translate"]?.InnerText ?? xmlSpell["name"]?.InnerText)); } } frmSelectItem selectSpell = new frmSelectItem { Description = LanguageManager.GetString("Title_SelectSpell", GlobalOptions.Language), DropdownItems = lstSpells }; selectSpell.ShowDialog(this); if (selectSpell.DialogResult == DialogResult.OK) { txtSelect.Text = selectSpell.SelectedName; txtTranslateSelection.Text = TranslateField(_strSelect, selectSpell.SelectedName); } break; case "SelectWeaponCategory": frmSelectWeaponCategory frmPickWeaponCategory = new frmSelectWeaponCategory { Description = LanguageManager.GetString("Title_SelectWeaponCategory", GlobalOptions.Language) }; frmPickWeaponCategory.ShowDialog(this); if (frmPickWeaponCategory.DialogResult == DialogResult.OK) { txtSelect.Text = frmPickWeaponCategory.SelectedCategory; txtTranslateSelection.Text = TranslateField(_strSelect, frmPickWeaponCategory.SelectedCategory); } break; case "SelectSpellCategory": frmSelectSpellCategory frmPickSpellCategory = new frmSelectSpellCategory { Description = LanguageManager.GetString("Title_SelectSpellCategory", GlobalOptions.Language) }; frmPickSpellCategory.ShowDialog(this); if (frmPickSpellCategory.DialogResult == DialogResult.OK) { txtSelect.Text = frmPickSpellCategory.SelectedCategory; txtTranslateSelection.Text = TranslateField(_strSelect, frmPickSpellCategory.SelectedCategory); } break; case "SelectAdeptPower": frmSelectPower frmPickPower = new frmSelectPower(_objCharacter); frmPickPower.ShowDialog(this); if (frmPickPower.DialogResult == DialogResult.OK) { txtSelect.Text = XmlManager.Load("powers.xml").SelectSingleNode("/chummer/powers/power[id = \"" + frmPickPower.SelectedPower + "\"]/name")?.InnerText; txtTranslateSelection.Text = TranslateField(_strSelect, frmPickPower.SelectedPower); } break; } }
private void frmSelectItem_Load(object sender, EventArgs e) { List <ListItem> lstItems = new List <ListItem>(); if (_strMode == "Gear") { string strSpace = LanguageManager.GetString("String_Space"); cboAmmo.DropDownStyle = ComboBoxStyle.DropDownList; // Add each of the items to a new List since we need to also grab their plugin information. foreach (Gear objGear in _lstGear) { string strAmmoName = objGear.DisplayNameShort(GlobalOptions.Language); // Retrieve the plugin information if it has any. if (objGear.Children.Count > 0) { string strPlugins = string.Empty; foreach (Gear objChild in objGear.Children) { strPlugins += objChild.DisplayNameShort(GlobalOptions.Language) + ',' + strSpace; } // Remove the trailing comma. strPlugins = strPlugins.Substring(0, strPlugins.Length - 1 - strSpace.Length); // Append the plugin information to the name. strAmmoName += strSpace + '[' + strPlugins + ']'; } if (objGear.Rating > 0) { strAmmoName += strSpace + '(' + LanguageManager.GetString(objGear.RatingLabel) + strSpace + objGear.Rating.ToString(GlobalOptions.CultureInfo) + ')'; } strAmmoName += strSpace + 'x' + objGear.Quantity.ToString(GlobalOptions.InvariantCultureInfo); lstItems.Add(new ListItem(objGear.InternalId, strAmmoName)); } } else if (_strMode == "Vehicles") { cboAmmo.DropDownStyle = ComboBoxStyle.DropDownList; // Add each of the items to a new List. foreach (Vehicle objVehicle in _lstVehicles) { lstItems.Add(new ListItem(objVehicle.InternalId, objVehicle.CurrentDisplayName)); } } else if (_strMode == "General") { cboAmmo.DropDownStyle = ComboBoxStyle.DropDownList; lstItems = _lstGeneralItems; } else if (_strMode == "Dropdown") { cboAmmo.DropDownStyle = ComboBoxStyle.DropDown; lstItems = _lstGeneralItems; } else if (_strMode == "Restricted") { cboAmmo.DropDownStyle = ComboBoxStyle.DropDown; if (!_objCharacter.Options.LicenseRestricted) { using (XmlNodeList objXmlList = XmlManager.Load("licenses.xml").SelectNodes("/chummer/licenses/license")) { if (objXmlList != null) { foreach (XmlNode objNode in objXmlList) { string strInnerText = objNode.InnerText; lstItems.Add(new ListItem(strInnerText, objNode.Attributes?["translate"]?.InnerText ?? strInnerText)); } } } } else { // Cyberware/Bioware. foreach (Cyberware objCyberware in _objCharacter.Cyberware.GetAllDescendants(x => x.Children)) { if (objCyberware.TotalAvailTuple(false).Suffix == 'R') { lstItems.Add(new ListItem(objCyberware.InternalId, objCyberware.CurrentDisplayName)); } foreach (Gear objGear in objCyberware.Gear.DeepWhere(x => x.Children, x => x.TotalAvailTuple(false).Suffix == 'R')) { lstItems.Add(new ListItem(objGear.InternalId, objGear.CurrentDisplayName)); } } // Armor. foreach (Armor objArmor in _objCharacter.Armor) { if (objArmor.TotalAvailTuple(false).Suffix == 'R') { lstItems.Add(new ListItem(objArmor.InternalId, objArmor.CurrentDisplayName)); } foreach (ArmorMod objMod in objArmor.ArmorMods) { if (objMod.TotalAvailTuple(false).Suffix == 'R') { lstItems.Add(new ListItem(objMod.InternalId, objMod.CurrentDisplayName)); } foreach (Gear objGear in objMod.Gear.DeepWhere(x => x.Children, x => x.TotalAvailTuple(false).Suffix == 'R')) { lstItems.Add(new ListItem(objGear.InternalId, objGear.CurrentDisplayName)); } } foreach (Gear objGear in objArmor.Gear.DeepWhere(x => x.Children, x => x.TotalAvailTuple(false).Suffix == 'R')) { lstItems.Add(new ListItem(objGear.InternalId, objGear.CurrentDisplayName)); } } // Weapons. foreach (Weapon objWeapon in _objCharacter.Weapons.GetAllDescendants(x => x.Children)) { if (objWeapon.TotalAvailTuple(false).Suffix == 'R') { lstItems.Add(new ListItem(objWeapon.InternalId, objWeapon.CurrentDisplayName)); } foreach (WeaponAccessory objAccessory in objWeapon.WeaponAccessories) { if (!objAccessory.IncludedInWeapon && objAccessory.TotalAvailTuple(false).Suffix == 'R') { lstItems.Add(new ListItem(objAccessory.InternalId, objAccessory.CurrentDisplayName)); } foreach (Gear objGear in objAccessory.Gear.DeepWhere(x => x.Children, x => x.TotalAvailTuple(false).Suffix == 'R')) { lstItems.Add(new ListItem(objGear.InternalId, objGear.CurrentDisplayName)); } } } // Gear. foreach (Gear objGear in _objCharacter.Gear.DeepWhere(x => x.Children, x => x.TotalAvailTuple(false).Suffix == 'R')) { lstItems.Add(new ListItem(objGear.InternalId, objGear.CurrentDisplayName)); } // Vehicles. foreach (Vehicle objVehicle in _objCharacter.Vehicles) { if (objVehicle.TotalAvailTuple(false).Suffix == 'R') { lstItems.Add(new ListItem(objVehicle.InternalId, objVehicle.CurrentDisplayName)); } foreach (VehicleMod objMod in objVehicle.Mods) { if (!objMod.IncludedInVehicle && objMod.TotalAvailTuple(false).Suffix == 'R') { lstItems.Add(new ListItem(objMod.InternalId, objMod.CurrentDisplayName)); } foreach (Weapon objWeapon in objMod.Weapons.GetAllDescendants(x => x.Children)) { if (objWeapon.TotalAvailTuple(false).Suffix == 'R') { lstItems.Add(new ListItem(objWeapon.InternalId, objWeapon.CurrentDisplayName)); } foreach (WeaponAccessory objAccessory in objWeapon.WeaponAccessories) { if (!objAccessory.IncludedInWeapon && objAccessory.TotalAvailTuple(false).Suffix == 'R') { lstItems.Add(new ListItem(objAccessory.InternalId, objAccessory.CurrentDisplayName)); } foreach (Gear objGear in objAccessory.Gear.DeepWhere(x => x.Children, x => x.TotalAvailTuple(false).Suffix == 'R')) { lstItems.Add(new ListItem(objGear.InternalId, objGear.CurrentDisplayName)); } } } } foreach (WeaponMount objWeaponMount in objVehicle.WeaponMounts) { if (!objWeaponMount.IncludedInVehicle && objWeaponMount.TotalAvailTuple(false).Suffix == 'R') { lstItems.Add(new ListItem(objWeaponMount.InternalId, objWeaponMount.CurrentDisplayName)); } foreach (Weapon objWeapon in objWeaponMount.Weapons.GetAllDescendants(x => x.Children)) { if (objWeapon.TotalAvailTuple(false).Suffix == 'R') { lstItems.Add(new ListItem(objWeapon.InternalId, objWeapon.CurrentDisplayName)); } foreach (WeaponAccessory objAccessory in objWeapon.WeaponAccessories) { if (!objAccessory.IncludedInWeapon && objAccessory.TotalAvailTuple(false).Suffix == 'R') { lstItems.Add(new ListItem(objAccessory.InternalId, objAccessory.CurrentDisplayName)); } foreach (Gear objGear in objAccessory.Gear.DeepWhere(x => x.Children, x => x.TotalAvailTuple(false).Suffix == 'R')) { lstItems.Add(new ListItem(objGear.InternalId, objGear.CurrentDisplayName)); } } } } foreach (Gear objGear in objVehicle.Gear.DeepWhere(x => x.Children, x => x.TotalAvailTuple(false).Suffix == 'R')) { lstItems.Add(new ListItem(objGear.InternalId, objGear.CurrentDisplayName)); } } } } // Populate the lists. cboAmmo.BeginUpdate(); cboAmmo.ValueMember = nameof(ListItem.Value); cboAmmo.DisplayMember = nameof(ListItem.Name); cboAmmo.DataSource = lstItems; // If there's only 1 value in the list, the character doesn't have a choice, so just accept it. if (cboAmmo.Items.Count == 1 && _blnAllowAutoSelect) { AcceptForm(); } if (!string.IsNullOrEmpty(_strForceItem)) { cboAmmo.SelectedIndex = cboAmmo.FindStringExact(_strForceItem); if (cboAmmo.SelectedIndex != -1) { AcceptForm(); } } if (!string.IsNullOrEmpty(_strSelectItemOnLoad)) { if (cboAmmo.DropDownStyle == ComboBoxStyle.DropDownList) { string strOldSelected = cboAmmo.SelectedValue?.ToString(); cboAmmo.SelectedValue = _strSelectItemOnLoad; if (cboAmmo.SelectedIndex == -1 && !string.IsNullOrEmpty(strOldSelected)) { cboAmmo.SelectedValue = strOldSelected; } } else { cboAmmo.Text = _strSelectItemOnLoad; } } cboAmmo.EndUpdate(); if (cboAmmo.Items.Count < 0) { cmdOK.Enabled = false; } }
public frmSelectBuildMethod(Character objCharacter, bool blnUseCurrentValues = false) { _objCharacter = objCharacter ?? throw new ArgumentNullException(nameof(objCharacter)); InitializeComponent(); this.UpdateLightDarkMode(); this.TranslateWinForm(); _xmlGameplayOptionsDataGameplayOptionsNode = XmlManager.Load("gameplayoptions.xml").GetFastNavigator().SelectSingleNode("/chummer/gameplayoptions"); // Populate the Build Method list. List <ListItem> lstBuildMethod = new List <ListItem>(4) { new ListItem("Karma", LanguageManager.GetString("String_Karma")), new ListItem("Priority", LanguageManager.GetString("String_Priority")), new ListItem("SumtoTen", LanguageManager.GetString("String_SumtoTen")), }; if (GlobalOptions.LifeModuleEnabled) { lstBuildMethod.Add(new ListItem("LifeModule", LanguageManager.GetString("String_LifeModule"))); } cboBuildMethod.BeginUpdate(); cboBuildMethod.ValueMember = nameof(ListItem.Value); cboBuildMethod.DisplayMember = nameof(ListItem.Name); cboBuildMethod.DataSource = lstBuildMethod; cboBuildMethod.SelectedValue = GlobalOptions.DefaultBuildMethod; cboBuildMethod.EndUpdate(); string strSpace = LanguageManager.GetString("String_Space"); // Populate the Gameplay Options list. List <ListItem> lstGameplayOptions = new List <ListItem>(10); if (_xmlGameplayOptionsDataGameplayOptionsNode != null) { foreach (XPathNavigator objXmlGameplayOption in _xmlGameplayOptionsDataGameplayOptionsNode.Select("gameplayoption")) { string strName = objXmlGameplayOption.SelectSingleNode("name")?.Value; if (!string.IsNullOrEmpty(strName)) { if (objXmlGameplayOption.SelectSingleNode("default")?.Value == bool.TrueString) { objXmlGameplayOption.TryGetInt32FieldQuickly("maxavailability", ref _intDefaultMaxAvail); objXmlGameplayOption.TryGetInt32FieldQuickly("sumtoten", ref _intDefaultSumToTen); objXmlGameplayOption.TryGetInt32FieldQuickly("pointbuykarma", ref _intDefaultPointBuyKarma); objXmlGameplayOption.TryGetInt32FieldQuickly("lifemoduleskarma", ref _intDefaultLifeModulesKarma); } if (objXmlGameplayOption.SelectSingleNode("priorityarrays") != null) { XPathNodeIterator iterator = objXmlGameplayOption.Select("priorityarrays/priorityarray"); lstGameplayOptions.AddRange(iterator.Cast <XPathNavigator>() .Select(node => new ListItem(strName + '|' + node.Value, (objXmlGameplayOption.SelectSingleNode("translate")?.Value ?? strName) + strSpace + '(' + node.Value + ')'))); } else { lstGameplayOptions.Add(new ListItem(strName, objXmlGameplayOption.SelectSingleNode("translate")?.Value ?? strName)); } } } } cboGamePlay.BeginUpdate(); cboGamePlay.ValueMember = nameof(ListItem.Value); cboGamePlay.DisplayMember = nameof(ListItem.Name); cboGamePlay.DataSource = lstGameplayOptions; cboGamePlay.SelectedValue = _strDefaultOption; cboGamePlay.EndUpdate(); chkIgnoreRules.SetToolTip(LanguageManager.GetString("Tip_SelectKarma_IgnoreRules")); if (blnUseCurrentValues) { string strGameplayOption = _objCharacter.GameplayOption; if (!string.IsNullOrEmpty(_objCharacter.PriorityArray)) { strGameplayOption += '|' + _objCharacter.PriorityArray; } cboGamePlay.SelectedValue = strGameplayOption; if (cboGamePlay.SelectedIndex == -1) { cboGamePlay.SelectedValue = _strDefaultOption; } cboBuildMethod.Enabled = false; cboBuildMethod.SelectedValue = _objCharacter.BuildMethod.ToString(); nudKarma.Value = objCharacter.BuildKarma; nudMaxNuyen.Value = _decNuyenBP = _objCharacter.NuyenMaximumBP; _intQualityLimits = _objCharacter.GameplayOptionQualityLimit; chkIgnoreRules.Checked = _objCharacter.IgnoreRules; nudMaxAvail.Value = Math.Min(objCharacter.MaximumAvailability, nudMaxAvail.Maximum); nudSumtoTen.Value = objCharacter.SumtoTen; } else if (_xmlGameplayOptionsDataGameplayOptionsNode != null) { string strSelectedGameplayOption = cboGamePlay.SelectedValue?.ToString(); if (strSelectedGameplayOption != null && strSelectedGameplayOption.IndexOf('|') != -1) { strSelectedGameplayOption = strSelectedGameplayOption.SplitNoAlloc('|').FirstOrDefault(); } XPathNavigator objXmlSelectedGameplayOption = _xmlGameplayOptionsDataGameplayOptionsNode.SelectSingleNode("gameplayoption[name = \"" + (strSelectedGameplayOption ?? string.Empty) + "\"]"); objXmlSelectedGameplayOption.TryGetInt32FieldQuickly("karma", ref _intQualityLimits); objXmlSelectedGameplayOption.TryGetDecFieldQuickly("maxnuyen", ref _decNuyenBP); nudMaxNuyen.Value = _decNuyenBP; nudKarma.Value = _intQualityLimits; int intTemp = _intDefaultMaxAvail; objXmlSelectedGameplayOption.TryGetInt32FieldQuickly("maxavailability", ref intTemp); nudMaxAvail.Value = intTemp; intTemp = _intDefaultSumToTen; objXmlSelectedGameplayOption.TryGetInt32FieldQuickly("sumtoten", ref intTemp); nudSumtoTen.Value = intTemp; } }
public Story(Character objCharacter) { _objCharacter = objCharacter; _xmlStoryDocumentBaseNode = XmlManager.Load("stories.xml").GetFastNavigator().SelectSingleNode("/chummer"); _lstStoryModules.CollectionChanged += LstStoryModulesOnCollectionChanged; }
/// <summary> /// Generates a character cache, which prevents us from repeatedly loading XmlNodes or caching a full character. /// </summary> /// <param name="strFile"></param> private TreeNode CacheCharacters(string strFile) { if (!File.Exists(strFile)) { Program.MainForm.ShowMessageBox(this, LanguageManager.GetString("Message_File_Cannot_Be_Accessed") + Environment.NewLine + Environment.NewLine + strFile); return(null); } List <XmlDocument> lstCharacterXmlStatblocks = new List <XmlDocument>(3); try { using (ZipArchive zipArchive = ZipFile.Open(strFile, ZipArchiveMode.Read, Encoding.GetEncoding(850))) { foreach (ZipArchiveEntry entry in zipArchive.Entries) { string strEntryFullName = entry.FullName; if (strEntryFullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) && strEntryFullName.StartsWith("statblocks_xml", StringComparison.Ordinal)) { XmlDocument xmlSourceDoc = new XmlDocument { XmlResolver = null }; // If we run into any problems loading the character cache, fail out early. try { using (StreamReader sr = new StreamReader(entry.Open(), true)) using (XmlReader objXmlReader = XmlReader.Create(sr, GlobalOptions.SafeXmlReaderSettings)) xmlSourceDoc.Load(objXmlReader); lstCharacterXmlStatblocks.Add(xmlSourceDoc); } // If we run into any problems loading the character cache, fail out early. catch (IOException) { Utils.BreakIfDebug(); } catch (XmlException) { Utils.BreakIfDebug(); } } else if (strEntryFullName.StartsWith("images", StringComparison.Ordinal) && strEntryFullName.Contains('.')) { string strKey = Path.GetFileName(strEntryFullName); Bitmap bmpMugshot = new Bitmap(entry.Open(), true); if (bmpMugshot.PixelFormat == PixelFormat.Format32bppPArgb) { if (_dicImages.ContainsKey(strKey)) { _dicImages[strKey].Dispose(); _dicImages[strKey] = bmpMugshot; } else { _dicImages.Add(strKey, bmpMugshot); } } else { try { Bitmap bmpMugshotCorrected = bmpMugshot.ConvertPixelFormat(PixelFormat.Format32bppPArgb); if (_dicImages.ContainsKey(strKey)) { _dicImages[strKey].Dispose(); _dicImages[strKey] = bmpMugshotCorrected; } else { _dicImages.Add(strKey, bmpMugshotCorrected); } } finally { bmpMugshot.Dispose(); } } } } } } catch (IOException) { Program.MainForm.ShowMessageBox(this, LanguageManager.GetString("Message_File_Cannot_Be_Accessed") + Environment.NewLine + Environment.NewLine + strFile); return(null); } catch (NotSupportedException) { Program.MainForm.ShowMessageBox(this, LanguageManager.GetString("Message_File_Cannot_Be_Accessed") + Environment.NewLine + Environment.NewLine + strFile); return(null); } catch (UnauthorizedAccessException) { Program.MainForm.ShowMessageBox(this, LanguageManager.GetString("Message_Insufficient_Permissions_Warning")); return(null); } string strFileText = strFile.CheapReplace(Application.StartupPath, () => "<" + Application.ProductName + ">"); TreeNode nodRootNode = new TreeNode { Text = strFileText, ToolTipText = strFileText }; XmlDocument xmlMetatypesDocument = XmlManager.Load("metatypes.xml"); foreach (XmlDocument xmlCharacterDocument in lstCharacterXmlStatblocks) { XmlNode xmlBaseCharacterNode = xmlCharacterDocument.SelectSingleNode("/document/public/character"); if (xmlBaseCharacterNode != null) { HeroLabCharacterCache objCache = new HeroLabCharacterCache { PlayerName = xmlBaseCharacterNode.Attributes?["playername"]?.InnerText }; string strNameString = xmlBaseCharacterNode.Attributes?["name"]?.InnerText ?? string.Empty; objCache.CharacterId = strNameString; if (!string.IsNullOrEmpty(strNameString)) { int intAsIndex = strNameString.IndexOf(" as ", StringComparison.Ordinal); if (intAsIndex != -1) { objCache.CharacterName = strNameString.Substring(0, intAsIndex); objCache.CharacterAlias = strNameString.Substring(intAsIndex).TrimStart(" as ").Trim('\''); } else { objCache.CharacterName = strNameString; } } string strRaceString = xmlBaseCharacterNode.SelectSingleNode("race/@name")?.InnerText; if (strRaceString == "Metasapient") { strRaceString = "A.I."; } if (!string.IsNullOrEmpty(strRaceString)) { using (XmlNodeList xmlMetatypeList = xmlMetatypesDocument.SelectNodes("/chummer/metatypes/metatype")) { if (xmlMetatypeList?.Count > 0) { foreach (XmlNode xmlMetatype in xmlMetatypeList) { string strMetatypeName = xmlMetatype["name"]?.InnerText ?? string.Empty; if (strMetatypeName == strRaceString) { objCache.Metatype = strMetatypeName; objCache.Metavariant = "None"; break; } using (XmlNodeList xmlMetavariantList = xmlMetatype.SelectNodes("metavariants/metavariant")) { if (xmlMetavariantList?.Count > 0) { foreach (XmlNode xmlMetavariant in xmlMetavariantList) { string strMetavariantName = xmlMetavariant["name"]?.InnerText ?? string.Empty; if (strMetavariantName == strRaceString) { objCache.Metatype = strMetatypeName; objCache.Metavariant = strMetavariantName; break; } } } } } } } } objCache.Description = xmlBaseCharacterNode.SelectSingleNode("personal/description")?.InnerText; objCache.Karma = xmlBaseCharacterNode.SelectSingleNode("karma/@total")?.InnerText ?? "0"; objCache.Essence = xmlBaseCharacterNode.SelectSingleNode("attributes/attribute[@name = \"Essence\"]/@text")?.InnerText; objCache.BuildMethod = xmlBaseCharacterNode.SelectSingleNode("creation/bp/@total")?.InnerText == "25" ? CharacterBuildMethod.Priority.ToString() : CharacterBuildMethod.Karma.ToString(); objCache.Created = objCache.Karma != "0"; if (!objCache.Created) { XmlNodeList xmlJournalEntries = xmlBaseCharacterNode.SelectNodes("journals/journal"); if (xmlJournalEntries?.Count > 1) { objCache.Created = true; } else if (xmlJournalEntries?.Count == 1 && xmlJournalEntries[0]?.Attributes?["name"]?.InnerText != "Title") { objCache.Created = true; } } string strImageString = xmlBaseCharacterNode.SelectSingleNode("images/image/@filename")?.InnerText; if (!string.IsNullOrEmpty(strImageString) && _dicImages.TryGetValue(strImageString, out Bitmap objTemp)) { objCache.Mugshot = objTemp; } objCache.FilePath = strFile; TreeNode objNode = new TreeNode { Text = CalculatedName(objCache), ToolTipText = strFile.CheapReplace(Application.StartupPath, () => "<" + Application.ProductName + ">") }; nodRootNode.Nodes.Add(objNode); lock (_lstCharacterCacheLock) { _lstCharacterCache.Add(objCache); objNode.Tag = _lstCharacterCache.IndexOf(objCache); } } } nodRootNode.Expand(); return(nodRootNode); }
public frmSelectBuildMethod(Character objCharacter, bool blnUseCurrentValues = false) { _objCharacter = objCharacter; InitializeComponent(); LanguageManager.TranslateWinForm(GlobalOptions.Language, this); _xmlGameplayOptionsDataGameplayOptionsNode = XmlManager.Load("gameplayoptions.xml").GetFastNavigator().SelectSingleNode("/chummer/gameplayoptions"); // Populate the Build Method list. List <ListItem> lstBuildMethod = new List <ListItem> { new ListItem("Karma", LanguageManager.GetString("String_Karma", GlobalOptions.Language)), new ListItem("Priority", LanguageManager.GetString("String_Priority", GlobalOptions.Language)), new ListItem("SumtoTen", LanguageManager.GetString("String_SumtoTen", GlobalOptions.Language)), }; if (GlobalOptions.LifeModuleEnabled) { lstBuildMethod.Add(new ListItem("LifeModule", LanguageManager.GetString("String_LifeModule", GlobalOptions.Language))); } cboBuildMethod.BeginUpdate(); cboBuildMethod.ValueMember = nameof(ListItem.Value); cboBuildMethod.DisplayMember = nameof(ListItem.Name); cboBuildMethod.DataSource = lstBuildMethod; cboBuildMethod.SelectedValue = GlobalOptions.DefaultBuildMethod; cboBuildMethod.EndUpdate(); // Populate the Gameplay Options list. List <ListItem> lstGameplayOptions = new List <ListItem>(); if (_xmlGameplayOptionsDataGameplayOptionsNode != null) { foreach (XPathNavigator objXmlGameplayOption in _xmlGameplayOptionsDataGameplayOptionsNode.Select("gameplayoption")) { string strName = objXmlGameplayOption.SelectSingleNode("name")?.Value; if (!string.IsNullOrEmpty(strName)) { if (objXmlGameplayOption.SelectSingleNode("default")?.Value == bool.TrueString) { objXmlGameplayOption.TryGetInt32FieldQuickly("maxavailability", ref _intDefaultMaxAvail); objXmlGameplayOption.TryGetInt32FieldQuickly("sumtoten", ref _intDefaultSumToTen); objXmlGameplayOption.TryGetInt32FieldQuickly("pointbuykarma", ref _intDefaultPointBuyKarma); objXmlGameplayOption.TryGetInt32FieldQuickly("lifemoduleskarma", ref _intDefaultLifeModulesKarma); } lstGameplayOptions.Add(new ListItem(strName, objXmlGameplayOption.SelectSingleNode("translate")?.Value ?? strName)); } } } cboGamePlay.BeginUpdate(); cboGamePlay.ValueMember = "Value"; cboGamePlay.DisplayMember = "Name"; cboGamePlay.DataSource = lstGameplayOptions; cboGamePlay.SelectedValue = _strDefaultOption; cboGamePlay.EndUpdate(); chkIgnoreRules.SetToolTip(LanguageManager.GetString("Tip_SelectKarma_IgnoreRules", GlobalOptions.Language)); if (blnUseCurrentValues) { cboGamePlay.SelectedValue = _objCharacter.GameplayOption; if (cboGamePlay.SelectedIndex == -1) { cboGamePlay.SelectedValue = _strDefaultOption; } cboBuildMethod.Enabled = false; cboBuildMethod.SelectedValue = _objCharacter.BuildMethod.ToString(); nudKarma.Value = objCharacter.BuildKarma; nudMaxNuyen.Value = _decNuyenBP = _objCharacter.NuyenMaximumBP; _intQualityLimits = _objCharacter.GameplayOptionQualityLimit; chkIgnoreRules.Checked = _objCharacter.IgnoreRules; nudMaxAvail.Value = objCharacter.MaximumAvailability; nudSumtoTen.Value = objCharacter.SumtoTen; } else if (_xmlGameplayOptionsDataGameplayOptionsNode != null) { XPathNavigator objXmlSelectedGameplayOption = _xmlGameplayOptionsDataGameplayOptionsNode.SelectSingleNode("gameplayoption[name = \"" + (cboGamePlay.SelectedValue?.ToString() ?? string.Empty) + "\"]"); objXmlSelectedGameplayOption.TryGetInt32FieldQuickly("karma", ref _intQualityLimits); objXmlSelectedGameplayOption.TryGetDecFieldQuickly("maxnuyen", ref _decNuyenBP); nudMaxNuyen.Value = _decNuyenBP; nudKarma.Value = _intQualityLimits; int intTemp = _intDefaultMaxAvail; objXmlSelectedGameplayOption.TryGetInt32FieldQuickly("maxavailability", ref intTemp); nudMaxAvail.Value = intTemp; intTemp = _intDefaultSumToTen; objXmlSelectedGameplayOption.TryGetInt32FieldQuickly("sumtoten", ref intTemp); nudSumtoTen.Value = intTemp; } }
private void cmdAddMod_Click(object sender, EventArgs e) { bool blnAddAgain; XmlNode xmlSelectedMount = null; string strSelectedMount = cboSize.SelectedValue?.ToString(); if (!string.IsNullOrEmpty(strSelectedMount)) { xmlSelectedMount = _xmlDoc.SelectSingleNode("/chummer/weaponmounts/weaponmount[id = \"" + strSelectedMount + "\"]"); } int intSlots = Convert.ToInt32(xmlSelectedMount?["slots"]?.InnerText); string[] astrSelectedValues = { cboVisibility.SelectedValue?.ToString(), cboFlexibility.SelectedValue?.ToString(), cboControl.SelectedValue?.ToString() }; for (int i = 0; i < astrSelectedValues.Length; ++i) { string strSelectedId = astrSelectedValues[i]; if (!string.IsNullOrEmpty(strSelectedId)) { XmlNode xmlLoopNode = _xmlDoc.SelectSingleNode("/chummer/weaponmounts/weaponmount[id = \"" + strSelectedId + "\"]"); if (xmlLoopNode != null) { intSlots += Convert.ToInt32(xmlLoopNode["slots"]?.InnerText); } } } foreach (VehicleMod objMod in _lstMods) { intSlots += objMod.CalculatedSlots; } string strSpaceCharacter = LanguageManager.GetString("String_Space", GlobalOptions.Language); TreeNode objModsParentNode = treMods.FindNode("Node_AdditionalMods"); do { frmSelectVehicleMod frmPickVehicleMod = new frmSelectVehicleMod(_objCharacter, _objMount?.Mods) { // Pass the selected vehicle on to the form. SelectedVehicle = _objVehicle, VehicleMountMods = true, WeaponMountSlots = intSlots }; frmPickVehicleMod.ShowDialog(this); // Make sure the dialogue window was not canceled. if (frmPickVehicleMod.DialogResult == DialogResult.Cancel) { frmPickVehicleMod.Dispose(); break; } blnAddAgain = frmPickVehicleMod.AddAgain; XmlDocument objXmlDocument = XmlManager.Load("vehicles.xml"); XmlNode objXmlMod = objXmlDocument.SelectSingleNode("/chummer/weaponmountmods/mod[id = \"" + frmPickVehicleMod.SelectedMod + "\"]"); VehicleMod objMod = new VehicleMod(_objCharacter) { DiscountCost = frmPickVehicleMod.BlackMarketDiscount }; objMod.Create(objXmlMod, frmPickVehicleMod.SelectedRating, _objVehicle, frmPickVehicleMod.Markup); // Check the item's Cost and make sure the character can afford it. decimal decOriginalCost = _objVehicle.TotalCost; if (frmPickVehicleMod.FreeCost) { objMod.Cost = "0"; } frmPickVehicleMod.Dispose(); // Do not allow the user to add a new Vehicle Mod if the Vehicle's Capacity has been reached. if (_objCharacter.Options.EnforceCapacity) { bool blnOverCapacity = false; if (_objCharacter.Options.BookEnabled("R5")) { if (_objVehicle.IsDrone && GlobalOptions.Dronemods) { if (_objVehicle.DroneModSlotsUsed > _objVehicle.DroneModSlots) { blnOverCapacity = true; } } else { int intUsed = _objVehicle.CalcCategoryUsed(objMod.Category); int intAvail = _objVehicle.CalcCategoryAvail(objMod.Category); if (intUsed > intAvail) { blnOverCapacity = true; } } } else if (_objVehicle.Slots < _objVehicle.SlotsUsed) { blnOverCapacity = true; } if (blnOverCapacity) { Program.MainForm.ShowMessageBox(LanguageManager.GetString("Message_CapacityReached", GlobalOptions.Language), LanguageManager.GetString("MessageTitle_CapacityReached", GlobalOptions.Language), MessageBoxButtons.OK, MessageBoxIcon.Information); continue; } } if (_objCharacter.Created) { decimal decCost = _objVehicle.TotalCost - decOriginalCost; // Multiply the cost if applicable. char chrAvail = objMod.TotalAvailTuple().Suffix; if (chrAvail == 'R' && _objCharacter.Options.MultiplyRestrictedCost) { decCost *= _objCharacter.Options.RestrictedCostMultiplier; } if (chrAvail == 'F' && _objCharacter.Options.MultiplyForbiddenCost) { decCost *= _objCharacter.Options.ForbiddenCostMultiplier; } if (decCost > _objCharacter.Nuyen) { Program.MainForm.ShowMessageBox(LanguageManager.GetString("Message_NotEnoughNuyen", GlobalOptions.Language), LanguageManager.GetString("MessageTitle_NotEnoughNuyen", GlobalOptions.Language), MessageBoxButtons.OK, MessageBoxIcon.Information); continue; } // Create the Expense Log Entry. ExpenseLogEntry objExpense = new ExpenseLogEntry(_objCharacter); objExpense.Create(decCost * -1, LanguageManager.GetString("String_ExpensePurchaseVehicleMod", GlobalOptions.Language) + strSpaceCharacter + objMod.DisplayNameShort(GlobalOptions.Language), ExpenseType.Nuyen, DateTime.Now); _objCharacter.ExpenseEntries.AddWithSort(objExpense); _objCharacter.Nuyen -= decCost; ExpenseUndo objUndo = new ExpenseUndo(); objUndo.CreateNuyen(NuyenExpenseType.AddVehicleWeaponMountMod, objMod.InternalId); objExpense.Undo = objUndo; } _lstMods.Add(objMod); intSlots += objMod.CalculatedSlots; TreeNode objNewNode = objMod.CreateTreeNode(null, null, null, null, null, null); if (objModsParentNode == null) { objModsParentNode = new TreeNode { Tag = "Node_AdditionalMods", Text = LanguageManager.GetString("Node_AdditionalMods", GlobalOptions.Language) }; treMods.Nodes.Add(objModsParentNode); objModsParentNode.Expand(); } objModsParentNode.Nodes.Add(objNewNode); treMods.SelectedNode = objNewNode; }while (blnAddAgain); }
private void cmdOK_Click(object sender, EventArgs e) { // Make sure the kit and file name fields are populated. if (string.IsNullOrEmpty(txtName.Text)) { MessageBox.Show(LanguageManager.GetString("Message_CreatePACKSKit_KitName", GlobalOptions.Language), LanguageManager.GetString("MessageTitle_CreatePACKSKit_KitName", GlobalOptions.Language), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (string.IsNullOrEmpty(txtFileName.Text)) { MessageBox.Show(LanguageManager.GetString("Message_CreatePACKSKit_FileName", GlobalOptions.Language), LanguageManager.GetString("MessageTitle_CreatePACKSKit_FileName", GlobalOptions.Language), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } // Make sure the file name starts with custom and ends with _packs.xml. if (!txtFileName.Text.StartsWith("custom") || !txtFileName.Text.EndsWith("_packs.xml")) { MessageBox.Show(LanguageManager.GetString("Message_CreatePACKSKit_InvalidFileName", GlobalOptions.Language), LanguageManager.GetString("MessageTitle_CreatePACKSKit_InvalidFileName", GlobalOptions.Language), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } // See if a Kit with this name already exists for the Custom category. // This was originally done without the XmlManager, but because amends and overrides and toggling custom data directories can change names, we need to use it. string strName = txtName.Text; if (XmlManager.Load("packs.xml", GlobalOptions.Language).SelectSingleNode("/chummer/packs/pack[name = " + strName.CleanXPath() + " and category = \"Custom\"]") != null) { MessageBox.Show(string.Format(LanguageManager.GetString("Message_CreatePACKSKit_DuplicateName", GlobalOptions.Language), strName), LanguageManager.GetString("MessageTitle_CreatePACKSKit_DuplicateName", GlobalOptions.Language), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } string strPath = Path.Combine(Application.StartupPath, "data", txtFileName.Text); // If this is not a new file, read in the existing contents. XmlDocument objXmlCurrentDocument = null; if (File.Exists(strPath)) { try { objXmlCurrentDocument = new XmlDocument(); using (StreamReader objStreamReader = new StreamReader(strPath, Encoding.UTF8, true)) { objXmlCurrentDocument.Load(objStreamReader); } } catch (IOException ex) { MessageBox.Show(ex.ToString()); return; } catch (XmlException ex) { MessageBox.Show(ex.ToString()); return; } } FileStream objStream = new FileStream(strPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); XmlTextWriter objWriter = new XmlTextWriter(objStream, Encoding.UTF8) { Formatting = Formatting.Indented, Indentation = 1, IndentChar = '\t' }; objWriter.WriteStartDocument(); // <chummer> objWriter.WriteStartElement("chummer"); // <packs> objWriter.WriteStartElement("packs"); // If this is not a new file, write out the current contents. if (objXmlCurrentDocument != null) { using (XmlNodeList objXmlNodeList = objXmlCurrentDocument.SelectNodes("/chummer/*")) if (objXmlNodeList?.Count > 0) { foreach (XmlNode objXmlNode in objXmlNodeList) { objXmlNode.WriteContentTo(objWriter); } } } // <pack> objWriter.WriteStartElement("pack"); // <name /> objWriter.WriteElementString("name", txtName.Text); // <category /> objWriter.WriteElementString("category", "Custom"); // Export Attributes. if (chkAttributes.Checked) { int intBOD = _objCharacter.BOD.Value - (_objCharacter.BOD.MetatypeMinimum - 1); int intAGI = _objCharacter.AGI.Value - (_objCharacter.AGI.MetatypeMinimum - 1); int intREA = _objCharacter.REA.Value - (_objCharacter.REA.MetatypeMinimum - 1); int intSTR = _objCharacter.STR.Value - (_objCharacter.STR.MetatypeMinimum - 1); int intCHA = _objCharacter.CHA.Value - (_objCharacter.CHA.MetatypeMinimum - 1); int intINT = _objCharacter.INT.Value - (_objCharacter.INT.MetatypeMinimum - 1); int intLOG = _objCharacter.LOG.Value - (_objCharacter.LOG.MetatypeMinimum - 1); int intWIL = _objCharacter.WIL.Value - (_objCharacter.WIL.MetatypeMinimum - 1); int intEDG = _objCharacter.EDG.Value - (_objCharacter.EDG.MetatypeMinimum - 1); int intMAG = _objCharacter.MAG.Value - (_objCharacter.MAG.MetatypeMinimum - 1); int intMAGAdept = _objCharacter.MAGAdept.Value - (_objCharacter.MAGAdept.MetatypeMinimum - 1); int intDEP = _objCharacter.DEP.Value - (_objCharacter.DEP.MetatypeMinimum - 1); int intRES = _objCharacter.RES.Value - (_objCharacter.RES.MetatypeMinimum - 1); // <attributes> objWriter.WriteStartElement("attributes"); objWriter.WriteElementString("bod", intBOD.ToString()); objWriter.WriteElementString("agi", intAGI.ToString()); objWriter.WriteElementString("rea", intREA.ToString()); objWriter.WriteElementString("str", intSTR.ToString()); objWriter.WriteElementString("cha", intCHA.ToString()); objWriter.WriteElementString("int", intINT.ToString()); objWriter.WriteElementString("log", intLOG.ToString()); objWriter.WriteElementString("wil", intWIL.ToString()); objWriter.WriteElementString("edg", intEDG.ToString()); if (_objCharacter.MAGEnabled) { objWriter.WriteElementString("mag", intMAG.ToString()); if (_objCharacter.Options.MysAdeptSecondMAGAttribute && _objCharacter.IsMysticAdept) { objWriter.WriteElementString("magadept", intMAGAdept.ToString()); } } if (_objCharacter.RESEnabled) { objWriter.WriteElementString("res", intRES.ToString()); } if (_objCharacter.DEPEnabled) { objWriter.WriteElementString("dep", intDEP.ToString()); } // </attributes> objWriter.WriteEndElement(); } // Export Qualities. if (chkQualities.Checked) { bool blnPositive = false; bool blnNegative = false; // Determine if Positive or Negative Qualities exist. foreach (Quality objQuality in _objCharacter.Qualities) { if (objQuality.Type == QualityType.Positive) { blnPositive = true; } if (objQuality.Type == QualityType.Negative) { blnNegative = true; } if (blnPositive && blnNegative) { break; } } // <qualities> objWriter.WriteStartElement("qualities"); // Positive Qualities. if (blnPositive) { // <positive> objWriter.WriteStartElement("positive"); foreach (Quality objQuality in _objCharacter.Qualities) { if (objQuality.Type == QualityType.Positive) { objWriter.WriteStartElement("quality"); if (!string.IsNullOrEmpty(objQuality.Extra)) { objWriter.WriteAttributeString("select", objQuality.Extra); } objWriter.WriteValue(objQuality.Name); objWriter.WriteEndElement(); } } // </positive> objWriter.WriteEndElement(); } // Negative Qualities. if (blnPositive) { // <negative> objWriter.WriteStartElement("negative"); foreach (Quality objQuality in _objCharacter.Qualities) { if (objQuality.Type == QualityType.Negative) { objWriter.WriteStartElement("quality"); if (!string.IsNullOrEmpty(objQuality.Extra)) { objWriter.WriteAttributeString("select", objQuality.Extra); } objWriter.WriteValue(objQuality.Name); objWriter.WriteEndElement(); } } // </negative> objWriter.WriteEndElement(); } // </qualities> objWriter.WriteEndElement(); } // Export Starting Nuyen. if (chkStartingNuyen.Checked) { decimal decNuyenBP = _objCharacter.NuyenBP; if (_objCharacter.BuildMethod == CharacterBuildMethod.Karma) { decNuyenBP /= 2.0m; } objWriter.WriteElementString("nuyenbp", decNuyenBP.ToString(GlobalOptions.InvariantCultureInfo)); } // Export Active Skills. if (chkActiveSkills.Checked) { // <skills> objWriter.WriteStartElement("skills"); //TODO: Figure out what this did? // Active Skills. //foreach (Skill objSkill in _objCharacter.Skills) //{ // if (!objSkill.KnowledgeSkill && !objSkill.IsGrouped && objSkill.Rating > 0) // { // // <skill> // objWriter.WriteStartElement("skill"); // objWriter.WriteElementString("name", objSkill.Name); // objWriter.WriteElementString("rating", objSkill.Rating.ToString()); // if (!string.IsNullOrEmpty(objSkill.Specialization)) // objWriter.WriteElementString("spec", objSkill.Specialization); // // </skill> // objWriter.WriteEndElement(); // } //} // Skill Groups. //foreach (SkillGroup objSkillGroup in _objCharacter.SkillGroups) //{ // if (!objSkillGroup.Broken && objSkillGroup.Rating > 0) // { // // <skillgroup> // objWriter.WriteStartElement("skillgroup"); // objWriter.WriteElementString("name", objSkillGroup.Name); // objWriter.WriteElementString("rating", objSkillGroup.Rating.ToString()); // // </skillgroup> // objWriter.WriteEndElement(); // } //} // </skills> objWriter.WriteEndElement(); } // Export Knowledge Skills. if (chkKnowledgeSkills.Checked) { // <knowledgeskills> objWriter.WriteStartElement("knowledgeskills"); foreach (KnowledgeSkill objSkill in _objCharacter.SkillsSection.Skills.OfType <KnowledgeSkill>()) { // <skill> objWriter.WriteStartElement("skill"); objWriter.WriteElementString("name", objSkill.Name); objWriter.WriteElementString("rating", objSkill.Rating.ToString()); if (!string.IsNullOrEmpty(objSkill.Specialization)) { objWriter.WriteElementString("spec", objSkill.Specialization); } objWriter.WriteElementString("category", objSkill.SkillCategory); // </skill> objWriter.WriteEndElement(); } // </knowledgeskills> objWriter.WriteEndElement(); } // Export Martial Arts. if (chkMartialArts.Checked) { // <martialarts> objWriter.WriteStartElement("martialarts"); foreach (MartialArt objArt in _objCharacter.MartialArts) { // <martialart> objWriter.WriteStartElement("martialart"); objWriter.WriteElementString("name", objArt.Name); objWriter.WriteElementString("rating", objArt.Rating.ToString()); if (objArt.Techniques.Count > 0) { // <advantages> objWriter.WriteStartElement("advantages"); foreach (MartialArtTechnique objAdvantage in objArt.Techniques) { objWriter.WriteElementString("advantage", objAdvantage.Name); } // </advantages> objWriter.WriteEndElement(); } // </martialart> objWriter.WriteEndElement(); } #if LEGACY foreach (MartialArtManeuver objManeuver in _objCharacter.MartialArtManeuvers) { objWriter.WriteElementString("maneuver", objManeuver.Name); } #endif // </martialarts> objWriter.WriteEndElement(); } // Export Spells. if (chkSpells.Checked) { // <spells> objWriter.WriteStartElement("spells"); foreach (Spell objSpell in _objCharacter.Spells) { objWriter.WriteStartElement("spell"); if (!string.IsNullOrEmpty(objSpell.Extra)) { objWriter.WriteAttributeString("select", objSpell.Extra); } objWriter.WriteValue(objSpell.Name); objWriter.WriteEndElement(); } // </spells> objWriter.WriteEndElement(); } // Export Complex Forms. if (chkComplexForms.Checked) { // <programs> objWriter.WriteStartElement("complexforms"); foreach (ComplexForm objComplexForm in _objCharacter.ComplexForms) { // <program> objWriter.WriteStartElement("complexform"); objWriter.WriteStartElement("name"); objWriter.WriteValue(objComplexForm.Name); objWriter.WriteEndElement(); // </program> objWriter.WriteEndElement(); } // </programs> objWriter.WriteEndElement(); } // Export Cyberware/Bioware. if (chkCyberware.Checked) { bool blnCyberware = false; bool blnBioware = false; foreach (Cyberware objCharacterCyberware in _objCharacter.Cyberware) { if (objCharacterCyberware.SourceType == Improvement.ImprovementSource.Bioware) { blnBioware = true; } if (objCharacterCyberware.SourceType == Improvement.ImprovementSource.Cyberware) { blnCyberware = true; } if (blnCyberware && blnBioware) { break; } } if (blnCyberware) { // <cyberwares> objWriter.WriteStartElement("cyberwares"); foreach (Cyberware objCyberware in _objCharacter.Cyberware) { if (objCyberware.SourceType == Improvement.ImprovementSource.Cyberware) { // <cyberware> objWriter.WriteStartElement("cyberware"); objWriter.WriteElementString("name", objCyberware.Name); if (objCyberware.Rating > 0) { objWriter.WriteElementString("rating", objCyberware.Rating.ToString()); } objWriter.WriteElementString("grade", objCyberware.Grade.Name); if (objCyberware.Children.Count > 0) { // <cyberwares> objWriter.WriteStartElement("cyberwares"); foreach (Cyberware objChildCyberware in objCyberware.Children) { if (objChildCyberware.Capacity != "[*]") { // <cyberware> objWriter.WriteStartElement("cyberware"); objWriter.WriteElementString("name", objChildCyberware.Name); if (objChildCyberware.Rating > 0) { objWriter.WriteElementString("rating", objChildCyberware.Rating.ToString()); } if (objChildCyberware.Gear.Count > 0) { WriteGear(objWriter, objChildCyberware.Gear); } // </cyberware> objWriter.WriteEndElement(); } } // </cyberwares> objWriter.WriteEndElement(); } if (objCyberware.Gear.Count > 0) { WriteGear(objWriter, objCyberware.Gear); } // </cyberware> objWriter.WriteEndElement(); } } // </cyberwares> objWriter.WriteEndElement(); } if (blnBioware) { // <biowares> objWriter.WriteStartElement("biowares"); foreach (Cyberware objCyberware in _objCharacter.Cyberware) { if (objCyberware.SourceType == Improvement.ImprovementSource.Bioware) { // <bioware> objWriter.WriteStartElement("bioware"); objWriter.WriteElementString("name", objCyberware.Name); if (objCyberware.Rating > 0) { objWriter.WriteElementString("rating", objCyberware.Rating.ToString()); } objWriter.WriteElementString("grade", objCyberware.Grade.ToString()); if (objCyberware.Gear.Count > 0) { WriteGear(objWriter, objCyberware.Gear); } // </bioware> objWriter.WriteEndElement(); } } // </biowares> objWriter.WriteEndElement(); } } // Export Lifestyle. if (chkLifestyle.Checked) { // <lifestyles> objWriter.WriteStartElement("lifestyles"); foreach (Lifestyle objLifestyle in _objCharacter.Lifestyles) { // <lifestyle> objWriter.WriteStartElement("lifestyle"); objWriter.WriteElementString("name", objLifestyle.Name); objWriter.WriteElementString("months", objLifestyle.Increments.ToString()); if (!string.IsNullOrEmpty(objLifestyle.BaseLifestyle)) { // This is an Advanced Lifestyle, so write out its properties. objWriter.WriteElementString("cost", objLifestyle.Cost.ToString(_objCharacter.Options.NuyenFormat, GlobalOptions.CultureInfo)); objWriter.WriteElementString("dice", objLifestyle.Dice.ToString()); objWriter.WriteElementString("multiplier", objLifestyle.Multiplier.ToString(_objCharacter.Options.NuyenFormat, GlobalOptions.CultureInfo)); objWriter.WriteElementString("baselifestyle", objLifestyle.BaseLifestyle); if (objLifestyle.LifestyleQualities.Count > 0) { // <qualities> objWriter.WriteStartElement("qualities"); foreach (LifestyleQuality objQuality in objLifestyle.LifestyleQualities) { objWriter.WriteElementString("quality", objQuality.Name); } // </qualities> objWriter.WriteEndElement(); } } // </lifestyle> objWriter.WriteEndElement(); } // </lifestyles> objWriter.WriteEndElement(); } // Export Armor. if (chkArmor.Checked) { // <armors> objWriter.WriteStartElement("armors"); foreach (Armor objArmor in _objCharacter.Armor) { // <armor> objWriter.WriteStartElement("armor"); objWriter.WriteElementString("name", objArmor.Name); if (objArmor.ArmorMods.Count > 0) { // <mods> objWriter.WriteStartElement("mods"); foreach (ArmorMod objMod in objArmor.ArmorMods) { // <mod> objWriter.WriteStartElement("mod"); objWriter.WriteElementString("name", objMod.Name); if (objMod.Rating > 0) { objWriter.WriteElementString("rating", objMod.Rating.ToString()); } // </mod> objWriter.WriteEndElement(); } // </mods> objWriter.WriteEndElement(); } if (objArmor.Gear.Count > 0) { WriteGear(objWriter, objArmor.Gear); } // </armor> objWriter.WriteEndElement(); } // </armors> objWriter.WriteEndElement(); } // Export Weapons. if (chkWeapons.Checked) { // <weapons> objWriter.WriteStartElement("weapons"); foreach (Weapon objWeapon in _objCharacter.Weapons) { // Don't attempt to export Cyberware and Gear Weapons since those are handled by those object types. The default Unarmed Attack Weapon should also not be exported. if (objWeapon.Category != "Cyberware" && objWeapon.Category != "Gear" && objWeapon.Name != "Unarmed Attack") { // <weapon> objWriter.WriteStartElement("weapon"); objWriter.WriteElementString("name", objWeapon.Name); // Weapon Accessories. if (objWeapon.WeaponAccessories.Count > 0) { // <accessories> objWriter.WriteStartElement("accessories"); foreach (WeaponAccessory objAccessory in objWeapon.WeaponAccessories) { // Don't attempt to export items included in the Weapon. if (!objAccessory.IncludedInWeapon) { // <accessory> objWriter.WriteStartElement("accessory"); objWriter.WriteElementString("name", objAccessory.Name); objWriter.WriteElementString("mount", objAccessory.Mount); objWriter.WriteElementString("extramount", objAccessory.ExtraMount); if (objAccessory.Gear.Count > 0) { WriteGear(objWriter, objAccessory.Gear); } // </accessory> objWriter.WriteEndElement(); } } // </accessories> objWriter.WriteEndElement(); } // Underbarrel Weapon. if (objWeapon.UnderbarrelWeapons.Count > 0) { foreach (Weapon objUnderbarrelWeapon in objWeapon.UnderbarrelWeapons) { if (!objUnderbarrelWeapon.IncludedInWeapon) { objWriter.WriteElementString("underbarrel", objUnderbarrelWeapon.Name); } } } // </weapon> objWriter.WriteEndElement(); } } // </weapons> objWriter.WriteEndElement(); } // Export Gear. if (chkGear.Checked) { WriteGear(objWriter, _objCharacter.Gear); } // Export Vehicles. if (chkVehicles.Checked) { // <vehicles> objWriter.WriteStartElement("vehicles"); foreach (Vehicle objVehicle in _objCharacter.Vehicles) { bool blnWeapons = false; // <vehicle> objWriter.WriteStartElement("vehicle"); objWriter.WriteElementString("name", objVehicle.Name); if (objVehicle.Mods.Count > 0) { // <mods> objWriter.WriteStartElement("mods"); foreach (VehicleMod objVehicleMod in objVehicle.Mods) { // Only write out the Mods that are not part of the base vehicle. if (!objVehicleMod.IncludedInVehicle) { // <mod> objWriter.WriteStartElement("mod"); objWriter.WriteElementString("name", objVehicleMod.Name); if (objVehicleMod.Rating > 0) { objWriter.WriteElementString("rating", objVehicleMod.Rating.ToString()); } // </mod> objWriter.WriteEndElement(); // See if this is a Weapon Mount with Weapons. if (objVehicleMod.Weapons.Count > 0) { blnWeapons = true; } } else { // See if this is a Weapon Mount with Weapons. if (objVehicleMod.Weapons.Count > 0) { blnWeapons = true; } } } // </mods> objWriter.WriteEndElement(); } // If there are Weapons, add them. if (blnWeapons) { // <weapons> objWriter.WriteStartElement("weapons"); foreach (VehicleMod objVehicleMod in objVehicle.Mods) { foreach (Weapon objWeapon in objVehicleMod.Weapons) { // <weapon> objWriter.WriteStartElement("weapon"); objWriter.WriteElementString("name", objWeapon.Name); // Weapon Accessories. if (objWeapon.WeaponAccessories.Count > 0) { // <accessories> objWriter.WriteStartElement("accessories"); foreach (WeaponAccessory objAccessory in objWeapon.WeaponAccessories) { // Don't attempt to export items included in the Weapon. if (!objAccessory.IncludedInWeapon) { // <accessory> objWriter.WriteStartElement("accessory"); objWriter.WriteElementString("name", objAccessory.Name); objWriter.WriteElementString("mount", objAccessory.Mount); objWriter.WriteElementString("extramount", objAccessory.ExtraMount); // </accessory> objWriter.WriteEndElement(); } } // </accessories> objWriter.WriteEndElement(); } // Underbarrel Weapon. if (objWeapon.UnderbarrelWeapons.Count > 0) { foreach (Weapon objUnderbarrelWeapon in objWeapon.UnderbarrelWeapons) { objWriter.WriteElementString("underbarrel", objUnderbarrelWeapon.Name); } } // </weapon> objWriter.WriteEndElement(); } } // </weapons> objWriter.WriteEndElement(); } // Gear. if (objVehicle.Gear.Count > 0) { WriteGear(objWriter, objVehicle.Gear); } // </vehicle> objWriter.WriteEndElement(); } // </vehicles> objWriter.WriteEndElement(); } // </pack> objWriter.WriteEndElement(); // </packs> objWriter.WriteEndElement(); // </chummer> objWriter.WriteEndElement(); objWriter.WriteEndDocument(); objWriter.Close(); MessageBox.Show(string.Format(LanguageManager.GetString("Message_CreatePACKSKit_SuiteCreated", GlobalOptions.Language), txtName.Text), LanguageManager.GetString("MessageTitle_CreatePACKSKit_SuiteCreated", GlobalOptions.Language), MessageBoxButtons.OK, MessageBoxIcon.Information); DialogResult = DialogResult.OK; }