private void frmCreateWeaponMount_Load(object sender, EventArgs e) { XmlNode xmlVehicleNode = _objVehicle.GetNode(); List <ListItem> lstSize; // Populate the Weapon Mount Category list. string strSizeFilter = "category = \"Size\" and " + _objCharacter.Options.BookXPath(); if (!_objVehicle.IsDrone && GlobalOptions.Dronemods) { strSizeFilter += " and not(optionaldrone)"; } using (XmlNodeList xmlSizeNodeList = _xmlDoc.SelectNodes("/chummer/weaponmounts/weaponmount[" + strSizeFilter + "]")) { lstSize = new List <ListItem>(xmlSizeNodeList?.Count ?? 0); if (xmlSizeNodeList?.Count > 0) { foreach (XmlNode xmlSizeNode in xmlSizeNodeList) { string strId = xmlSizeNode["id"]?.InnerText; if (string.IsNullOrEmpty(strId)) { continue; } XmlNode xmlTestNode = xmlSizeNode.SelectSingleNode("forbidden/vehicledetails"); if (xmlTestNode != null) { // Assumes topmost parent is an AND node if (xmlVehicleNode.ProcessFilterOperationNode(xmlTestNode, false)) { continue; } } xmlTestNode = xmlSizeNode.SelectSingleNode("required/vehicledetails"); if (xmlTestNode != null) { // Assumes topmost parent is an AND node if (!xmlVehicleNode.ProcessFilterOperationNode(xmlTestNode, false)) { continue; } } lstSize.Add(new ListItem(strId, xmlSizeNode["translate"]?.InnerText ?? xmlSizeNode["name"]?.InnerText ?? LanguageManager.GetString("String_Unknown"))); } } } cboSize.BeginUpdate(); cboSize.ValueMember = nameof(ListItem.Value); cboSize.DisplayMember = nameof(ListItem.Name); cboSize.DataSource = lstSize; cboSize.Enabled = lstSize.Count > 1; cboSize.EndUpdate(); if (_objMount != null) { TreeNode objModsParentNode = new TreeNode { Tag = "Node_AdditionalMods", Text = LanguageManager.GetString("Node_AdditionalMods") }; treMods.Nodes.Add(objModsParentNode); objModsParentNode.Expand(); foreach (VehicleMod objMod in _objMount.Mods) { TreeNode objLoopNode = objMod.CreateTreeNode(null, null, null, null, null, null); if (objLoopNode != null) { objModsParentNode.Nodes.Add(objLoopNode); } } _lstMods.AddRange(_objMount.Mods); cboSize.SelectedValue = _objMount.SourceIDString; } if (cboSize.SelectedIndex == -1) { if (lstSize.Count > 0) { cboSize.SelectedIndex = 0; } } else { RefreshCBOs(); } nudMarkup.Visible = AllowDiscounts; lblMarkupLabel.Visible = AllowDiscounts; lblMarkupPercentLabel.Visible = AllowDiscounts; if (_objMount != null) { List <ListItem> lstVisibility = cboVisibility.Items.Cast <ListItem>().ToList(); List <ListItem> lstFlexibility = cboFlexibility.Items.Cast <ListItem>().ToList(); List <ListItem> lstControl = cboControl.Items.Cast <ListItem>().ToList(); foreach (WeaponMountOption objExistingOption in _objMount.WeaponMountOptions) { string strLoopId = objExistingOption.SourceIDString; if (lstVisibility.Any(x => x.Value.ToString() == strLoopId)) { cboVisibility.SelectedValue = strLoopId; } else if (lstFlexibility.Any(x => x.Value.ToString() == strLoopId)) { cboFlexibility.SelectedValue = strLoopId; } else if (lstControl.Any(x => x.Value.ToString() == strLoopId)) { cboControl.SelectedValue = strLoopId; } } } _blnLoading = false; UpdateInfo(); this.UpdateLightDarkMode(); this.TranslateWinForm(); }
private void UpdateGearInfo() { // Retrieve the information for the selected Accessory. XmlNode objXmlAccessory = _objXmlDocument.SelectSingleNode("/chummer/accessories/accessory[name = \"" + lstAccessory.SelectedValue + "\"]"); if (objXmlAccessory == null) { return; } if (objXmlAccessory.InnerXml.Contains("<rc>")) { lblRC.Visible = true; lblRCLabel.Visible = true; lblRC.Text = objXmlAccessory["rc"]?.InnerText; } else { lblRC.Visible = false; lblRCLabel.Visible = false; } if (int.TryParse(objXmlAccessory["rating"]?.InnerText, out int intMaxRating) && intMaxRating > 1) { nudRating.Enabled = true; nudRating.Visible = true; lblRatingLabel.Visible = true; nudRating.Maximum = intMaxRating; while (nudRating.Maximum > nudRating.Minimum && !Backend.SelectionShared.CheckAvailRestriction(objXmlAccessory, _objCharacter, chkHideOverAvailLimit.Checked, decimal.ToInt32(nudRating.Maximum))) { nudRating.Maximum -= 1; } } else { nudRating.Enabled = false; nudRating.Visible = false; lblRatingLabel.Visible = false; } List <string> strMounts = new List <string>(); foreach (string strItem in objXmlAccessory["mount"]?.InnerText?.Split('/')) { strMounts.Add(strItem); } strMounts.Add("None"); List <string> strAllowed = new List <string>(); foreach (string strItem in _strAllowedMounts.Split('/')) { strAllowed.Add(strItem); } strAllowed.Add("None"); cboMount.Items.Clear(); foreach (string strCurrentMount in strMounts) { if (!string.IsNullOrEmpty(strCurrentMount)) { foreach (string strAllowedMount in strAllowed) { if (strCurrentMount == strAllowedMount) { cboMount.Items.Add(strCurrentMount); } } } } if (cboMount.Items.Count <= 1) { cboMount.Enabled = false; } else { cboMount.Enabled = true; } cboMount.SelectedIndex = 0; List <string> strExtraMounts = new List <string>(); if (objXmlAccessory.InnerXml.Contains("<extramount>")) { foreach (string strItem in objXmlAccessory["extramount"]?.InnerText?.Split('/')) { strExtraMounts.Add(strItem); } } strExtraMounts.Add("None"); cboExtraMount.Items.Clear(); foreach (string strCurrentMount in strExtraMounts) { if (!string.IsNullOrEmpty(strCurrentMount)) { foreach (string strAllowedMount in strAllowed) { if (strCurrentMount == strAllowedMount) { cboExtraMount.Items.Add(strCurrentMount); } } } } if (cboExtraMount.Items.Count <= 1) { cboExtraMount.Enabled = false; } else { cboExtraMount.Enabled = true; } cboExtraMount.SelectedIndex = 0; if (cboMount.SelectedItem.ToString() != "None" && cboExtraMount.SelectedItem.ToString() != "None" && cboMount.SelectedItem.ToString() == cboExtraMount.SelectedItem.ToString()) { cboExtraMount.SelectedIndex += 1; } // Avail. // If avail contains "F" or "R", remove it from the string so we can use the expression. string strAvail = string.Empty; string strAvailExpr = objXmlAccessory["avail"]?.InnerText; if (!string.IsNullOrWhiteSpace(strAvailExpr)) { lblAvail.Text = strAvailExpr; if (strAvailExpr.Substring(strAvailExpr.Length - 1, 1) == "F" || strAvailExpr.Substring(strAvailExpr.Length - 1, 1) == "R") { strAvail = strAvailExpr.Substring(strAvailExpr.Length - 1, 1); if (strAvail == "R") { strAvail = LanguageManager.GetString("String_AvailRestricted"); } else if (strAvail == "F") { strAvail = LanguageManager.GetString("String_AvailForbidden"); } // Remove the trailing character if it is "F" or "R". strAvailExpr = strAvailExpr.Substring(0, strAvailExpr.Length - 1); } try { lblAvail.Text = Convert.ToInt32(CommonFunctions.EvaluateInvariantXPath(strAvailExpr.Replace("Rating", nudRating.Value.ToString(GlobalOptions.CultureInfo)))).ToString() + strAvail; } catch (XPathException) { lblAvail.Text = strAvailExpr + strAvail; } } else { lblAvail.Text = string.Empty; } if (!chkFreeItem.Checked) { string strCost = "0"; if (objXmlAccessory.TryGetStringFieldQuickly("cost", ref strCost)) { strCost = strCost.Replace("Weapon Cost", _decWeaponCost.ToString(GlobalOptions.InvariantCultureInfo)) .Replace("Rating", nudRating.Value.ToString(GlobalOptions.CultureInfo)); } if (strCost.StartsWith("Variable")) { decimal decMin = 0; decimal decMax = decimal.MaxValue; strCost = strCost.TrimStart("Variable", true).Trim("()".ToCharArray()); if (strCost.Contains('-')) { string[] strValues = strCost.Split('-'); decimal.TryParse(strValues[0], NumberStyles.Any, GlobalOptions.InvariantCultureInfo, out decMin); decimal.TryParse(strValues[1], NumberStyles.Any, GlobalOptions.InvariantCultureInfo, out decMax); } else { decimal.TryParse(strCost.FastEscape('+'), NumberStyles.Any, GlobalOptions.InvariantCultureInfo, out decMin); } if (decMax == decimal.MaxValue) { lblCost.Text = decMin.ToString(_objCharacter.Options.NuyenFormat, GlobalOptions.CultureInfo) + "¥+"; } else { lblCost.Text = decMin.ToString(_objCharacter.Options.NuyenFormat, GlobalOptions.CultureInfo) + " - " + decMax.ToString(_objCharacter.Options.NuyenFormat, GlobalOptions.CultureInfo) + '¥'; } lblTest.Text = _objCharacter.AvailTest(decMax, lblAvail.Text); } else { decimal decCost = 0.0m; try { decCost = Convert.ToDecimal(CommonFunctions.EvaluateInvariantXPath(strCost), GlobalOptions.InvariantCultureInfo); } catch (XPathException) { } // Apply any markup. decCost *= 1 + (nudMarkup.Value / 100.0m); lblCost.Text = decCost.ToString(_objCharacter.Options.NuyenFormat, GlobalOptions.CultureInfo) + '¥'; lblTest.Text = _objCharacter.AvailTest(decCost, lblAvail.Text); } } else { lblCost.Text = 0.ToString(_objCharacter.Options.NuyenFormat, GlobalOptions.CultureInfo) + '¥'; lblTest.Text = _objCharacter.AvailTest(0, lblAvail.Text); } string strBookCode = objXmlAccessory["source"]?.InnerText; string strBook = _objCharacter.Options.LanguageBookShort(strBookCode); string strPage = objXmlAccessory["page"]?.InnerText; objXmlAccessory.TryGetStringFieldQuickly("altpage", ref strPage); lblSource.Text = strBook + " " + strPage; tipTooltip.SetToolTip(lblSource, _objCharacter.Options.LanguageBookLong(strBookCode) + " " + LanguageManager.GetString("String_Page") + " " + strPage); }
private void treQualities_AfterSelect(object sender, TreeViewEventArgs e) { string strSource = string.Empty; string strPage = string.Empty; string strQualityId = treQualities.SelectedNode?.Tag.ToString(); if (!string.IsNullOrEmpty(strQualityId)) { XmlNode objXmlQuality = _objXmlDocument.SelectSingleNode("/chummer/qualities/quality[id = \"" + strQualityId + "\"]"); if (objXmlQuality != null) { strSource = objXmlQuality["source"]?.InnerText ?? string.Empty; strPage = objXmlQuality["altpage"]?.InnerText ?? objXmlQuality["page"]?.InnerText ?? string.Empty; } } if (!string.IsNullOrEmpty(strSource) && !string.IsNullOrEmpty(strPage)) { lblSource.Text = CommonFunctions.LanguageBookShort(strSource, GlobalOptions.Language) + ' ' + strPage; tipTooltip.SetToolTip(lblSource, CommonFunctions.LanguageBookLong(strSource, GlobalOptions.Language) + ' ' + LanguageManager.GetString("String_Page", GlobalOptions.Language) + ' ' + strPage); } else { lblSource.Text = string.Empty; tipTooltip.SetToolTip(lblSource, string.Empty); } }
private void LoadCharacters(bool blnRefreshFavorites = true, bool blnRefreshRecents = true, bool blnRefreshWatch = true) { ReadOnlyObservableCollection <string> lstFavorites = new ReadOnlyObservableCollection <string>(GlobalOptions.FavoritedCharacters); bool blnAddFavouriteNode = false; TreeNode objFavouriteNode = null; TreeNode[] lstFavoritesNodes = null; if (blnRefreshFavorites) { objFavouriteNode = treCharacterList.FindNode("Favourite", false); if (objFavouriteNode == null) { objFavouriteNode = new TreeNode(LanguageManager.GetString("Treenode_Roster_FavouriteCharacters", GlobalOptions.Language)) { Tag = "Favourite" }; blnAddFavouriteNode = true; } lstFavoritesNodes = new TreeNode[lstFavorites.Count]; } IList <string> lstRecents = new List <string>(GlobalOptions.MostRecentlyUsedCharacters); List <string> lstWatch = new List <string>(); if (!string.IsNullOrEmpty(GlobalOptions.CharacterRosterPath) && Directory.Exists(GlobalOptions.CharacterRosterPath)) { string[] objFiles = Directory.GetFiles(GlobalOptions.CharacterRosterPath, "*.chum5"); for (int i = 0; i < objFiles.Length; ++i) { string strFile = objFiles[i]; // Make sure we're not loading a character that was already loaded by the MRU list. if (lstFavorites.Contains(strFile) || lstRecents.Contains(strFile)) { continue; } lstWatch.Add(strFile); } } bool blnAddWatchNode = false; TreeNode objWatchNode = null; TreeNode[] lstWatchNodes = null; if (blnRefreshWatch) { objWatchNode = treCharacterList.FindNode("Watch", false); if (objWatchNode == null && lstWatch.Count > 0) { objWatchNode = new TreeNode(LanguageManager.GetString("Treenode_Roster_WatchFolder", GlobalOptions.Language)) { Tag = "Watch" }; blnAddWatchNode = true; } lstWatchNodes = new TreeNode[lstWatch.Count]; } bool blnAddRecentNode = false; TreeNode objRecentNode = null; TreeNode[] lstRecentsNodes = null; if (blnRefreshRecents) { // Add any characters that are open to the displayed list so we can have more than 10 characters listed foreach (CharacterShared objCharacterForm in Program.MainForm.OpenCharacterForms) { string strFile = objCharacterForm.CharacterObject.FileName; // Make sure we're not loading a character that was already loaded by the MRU list. if (lstFavorites.Contains(strFile) || lstRecents.Contains(strFile) || lstWatch.Contains(strFile)) { continue; } lstRecents.Add(strFile); } foreach (string strFavorite in lstFavorites) { lstRecents.Remove(strFavorite); } objRecentNode = treCharacterList.FindNode("Recent", false); if (objRecentNode == null && lstRecents.Count > 0) { objRecentNode = new TreeNode(LanguageManager.GetString("Treenode_Roster_RecentCharacters", GlobalOptions.Language)) { Tag = "Recent" }; blnAddRecentNode = true; } lstRecentsNodes = new TreeNode[lstRecents.Count]; } Parallel.Invoke( () => { if (objFavouriteNode != null && lstFavoritesNodes != null) { object lstFavoritesNodesLock = new object(); Parallel.For(0, lstFavorites.Count, i => { string strFile = lstFavorites[i]; TreeNode objNode = CacheCharacter(strFile); lock (lstFavoritesNodesLock) lstFavoritesNodes[i] = objNode; }); if (blnAddFavouriteNode) { for (int i = 0; i < lstFavoritesNodes.Length; i++) { TreeNode objNode = lstFavoritesNodes[i]; if (objNode != null) { objFavouriteNode.Nodes.Add(objNode); } } } } }, () => { if (objRecentNode != null && lstRecentsNodes != null) { object lstRecentsNodesLock = new object(); Parallel.For(0, lstRecents.Count, i => { string strFile = lstRecents[i]; TreeNode objNode = CacheCharacter(strFile); lock (lstRecentsNodesLock) lstRecentsNodes[i] = objNode; }); if (blnAddRecentNode) { for (int i = 0; i < lstRecentsNodes.Length; i++) { TreeNode objNode = lstRecentsNodes[i]; if (objNode != null) { objRecentNode.Nodes.Add(objNode); } } } } }, () => { if (objWatchNode != null && lstWatchNodes != null) { object lstWatchNodesLock = new object(); Parallel.For(0, lstWatch.Count, i => { string strFile = lstWatch[i]; TreeNode objNode = CacheCharacter(strFile); lock (lstWatchNodesLock) lstWatchNodes[i] = objNode; }); if (blnAddWatchNode) { for (int i = 0; i < lstWatchNodes.Length; i++) { TreeNode objNode = lstWatchNodes[i]; if (objNode != null) { objWatchNode.Nodes.Add(objNode); } } } } }); if (objFavouriteNode != null) { if (blnAddFavouriteNode) { treCharacterList.Nodes.Add(objFavouriteNode); objFavouriteNode.Expand(); } else { objFavouriteNode.Nodes.Clear(); for (int i = 0; i < lstFavoritesNodes.Length; i++) { TreeNode objNode = lstFavoritesNodes[i]; if (objNode != null) { objFavouriteNode.Nodes.Add(objNode); } } } } if (objRecentNode != null) { if (blnAddRecentNode) { treCharacterList.Nodes.Add(objRecentNode); objRecentNode.Expand(); } else { objRecentNode.Nodes.Clear(); for (int i = 0; i < lstRecentsNodes.Length; i++) { TreeNode objNode = lstRecentsNodes[i]; if (objNode != null) { objRecentNode.Nodes.Add(objNode); } } } } if (objWatchNode != null) { if (blnAddWatchNode) { treCharacterList.Nodes.Add(objWatchNode); objWatchNode.Expand(); } else { objWatchNode.Nodes.Clear(); for (int i = 0; i < lstWatchNodes.Length; i++) { TreeNode objNode = lstWatchNodes[i]; if (objNode != null) { objWatchNode.Nodes.Add(objNode); } } } } treCharacterList.ExpandAll(); }
/// <summary> /// Generates a name for the treenode based on values contained in the CharacterCache object. /// </summary> /// <param name="objCache">Cache from which to generate name.</param> /// <param name="blnAddMarkerIfOpen">Whether to add an asterisk to the beginning of the name if the character is open.</param> /// <returns></returns> private static string CalculatedName(CharacterCache objCache, bool blnAddMarkerIfOpen = true) { string strReturn; if (!string.IsNullOrEmpty(objCache.ErrorText)) { strReturn = Path.GetFileNameWithoutExtension(objCache.FileName) + " (" + LanguageManager.GetString("String_Error", GlobalOptions.Language) + ')'; } else { strReturn = objCache.CharacterAlias; if (string.IsNullOrEmpty(strReturn)) { strReturn = objCache.CharacterName; if (string.IsNullOrEmpty(strReturn)) { strReturn = LanguageManager.GetString("String_UnnamedCharacter", GlobalOptions.Language); } } string strBuildMethod = LanguageManager.GetString("String_" + objCache.BuildMethod, GlobalOptions.Language, false); if (string.IsNullOrEmpty(strBuildMethod)) { strBuildMethod = LanguageManager.GetString("String_Unknown", GlobalOptions.Language); } string strCreated = LanguageManager.GetString(objCache.Created ? "Title_CareerMode" : "Title_CreateMode", GlobalOptions.Language); strReturn += $" ({strBuildMethod} - {strCreated})"; } if (blnAddMarkerIfOpen && Program.MainForm.OpenCharacterForms.Any(x => x.CharacterObject.FileName == objCache.FilePath)) { strReturn = "* " + strReturn; } return(strReturn); }
private void cmdOK_Click(object sender, EventArgs e) { // Make sure the suite and file name fields are populated. if (string.IsNullOrEmpty(txtName.Text)) { MessageBox.Show(LanguageManager.GetString("Message_CyberwareSuite_SuiteName"), LanguageManager.GetString("MessageTitle_CyberwareSuite_SuiteName"), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (string.IsNullOrEmpty(txtFileName.Text)) { MessageBox.Show(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") || !txtFileName.Text.EndsWith("_" + _strType + ".xml")) { MessageBox.Show(LanguageManager.GetString("Message_CyberwareSuite_InvalidFileName").Replace("{0}", _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 is done without the XmlManager since we need to check each file individually. XmlDocument objXmlDocument = new XmlDocument(); XmlNodeList objXmlSuiteList; string strCustomPath = Path.Combine(Application.StartupPath, "data"); foreach (string strFile in Directory.GetFiles(strCustomPath, "custom*_" + _strType + ".xml")) { objXmlDocument.Load(strFile); objXmlSuiteList = objXmlDocument.SelectNodes("/chummer/suites/suite[name = \"" + txtName.Text + "\"]"); if (objXmlSuiteList.Count > 0) { MessageBox.Show(LanguageManager.GetString("Message_CyberwareSuite_DuplicateName").Replace("{0}", txtName.Text).Replace("{1}", strFile.Replace(strCustomPath + Path.DirectorySeparatorChar, string.Empty)), LanguageManager.GetString("MessageTitle_CyberwareSuite_DuplicateName"), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } } string strPath = Path.Combine(strCustomPath, txtFileName.Text); bool blnNewFile = !File.Exists(strPath); // If this is not a new file, read in the existing contents. XmlDocument objXmlCurrentDocument = new XmlDocument(); if (!blnNewFile) { objXmlCurrentDocument.Load(strPath); } FileStream objStream = new FileStream(strPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); XmlTextWriter objWriter = new XmlTextWriter(objStream, Encoding.Unicode) { Formatting = Formatting.Indented, Indentation = 1, IndentChar = '\t' }; objWriter.WriteStartDocument(); // <chummer> objWriter.WriteStartElement("chummer"); if (!blnNewFile) { // <cyberwares> objWriter.WriteStartElement(_strType + "s"); XmlNodeList objXmlCyberwareList = objXmlCurrentDocument.SelectNodes("/chummer/" + _strType + "s"); foreach (XmlNode objXmlCyberware in objXmlCyberwareList) { objXmlCyberware.WriteContentTo(objWriter); } // </cyberwares> objWriter.WriteEndElement(); } // <suites> objWriter.WriteStartElement("suites"); // If this is not a new file, write out the current contents. if (!blnNewFile) { XmlNodeList objXmlCyberwareList = objXmlCurrentDocument.SelectNodes("/chummer/suites"); foreach (XmlNode objXmlCyberware in objXmlCyberwareList) { objXmlCyberware.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("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()); } // 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()); } // </cyberware> objWriter.WriteEndElement(); } } // </cyberwares> objWriter.WriteEndElement(); } // </cyberware> objWriter.WriteEndElement(); } } // </cyberwares> objWriter.WriteEndElement(); // </suite> objWriter.WriteEndElement(); // </chummer> objWriter.WriteEndElement(); objWriter.WriteEndDocument(); objWriter.Close(); MessageBox.Show(LanguageManager.GetString("Message_CyberwareSuite_SuiteCreated").Replace("{0}", txtName.Text), LanguageManager.GetString("MessageTitle_CyberwareSuite_SuiteCreated"), MessageBoxButtons.OK, MessageBoxIcon.Information); DialogResult = DialogResult.OK; }
/// <summary> /// Populate the Martial Arts Techniques list. /// </summary> private void RefreshTechniquesList() { string strFilter = '(' + _objCharacter.Options.BookXPath() + ')'; if (!string.IsNullOrEmpty(txtSearch.Text)) { strFilter += " and " + CommonFunctions.GenerateSearchXPath(txtSearch.Text); } XPathNodeIterator objTechniquesList = _xmlBaseChummerNode.Select("techniques/technique[" + strFilter + "]"); List <ListItem> lstTechniqueItems = new List <ListItem>(); foreach (XPathNavigator xmlTechnique in objTechniquesList) { string strId = xmlTechnique.SelectSingleNode("id")?.Value; if (!string.IsNullOrEmpty(strId)) { string strTechniqueName = xmlTechnique.SelectSingleNode("name")?.Value ?? LanguageManager.GetString("String_Unknown"); if (_setAllowedTechniques?.Contains(strTechniqueName) == false) { continue; } if (xmlTechnique.RequirementsMet(_objCharacter, _objMartialArt)) { lstTechniqueItems.Add(new ListItem(strId, xmlTechnique.SelectSingleNode("translate")?.Value ?? strTechniqueName)); } } } lstTechniqueItems.Sort(CompareListItems.CompareNames); string strOldSelected = lstTechniques.SelectedValue?.ToString(); _blnLoading = true; lstTechniques.BeginUpdate(); lstTechniques.ValueMember = nameof(ListItem.Value); lstTechniques.DisplayMember = nameof(ListItem.Name); lstTechniques.DataSource = lstTechniqueItems; _blnLoading = false; if (!string.IsNullOrEmpty(strOldSelected)) { lstTechniques.SelectedValue = strOldSelected; } else { lstTechniques.SelectedIndex = -1; } lstTechniques.EndUpdate(); }
/// <summary> /// Accept the selected item and close the form. /// </summary> private void AcceptForm() { string strSelectedId = lstVehicle.SelectedValue?.ToString(); XPathNavigator xmlVehicle = null; if (!string.IsNullOrEmpty(strSelectedId)) { xmlVehicle = _xmlBaseVehicleDataNode.SelectSingleNode("vehicles/vehicle[id = \"" + strSelectedId + "\"]"); } if (xmlVehicle == null) { return; } if (chkUsedVehicle.Checked) { decimal decCost = Convert.ToDecimal(xmlVehicle.SelectSingleNode("cost")?.Value, GlobalOptions.InvariantCultureInfo); decCost *= 1 - (nudUsedVehicleDiscount.Value / 100.0m); _blnUsedVehicle = true; _strUsedAvail = lblVehicleAvail.Text.Replace(LanguageManager.GetString("String_AvailRestricted", GlobalOptions.Language), "R").Replace(LanguageManager.GetString("String_AvailForbidden", GlobalOptions.Language), "F"); _decUsedCost = decCost; } _blnBlackMarketDiscount = chkBlackMarketDiscount.Checked; s_StrSelectCategory = (_objCharacter.Options.SearchInCategoryOnly || txtSearch.TextLength == 0) ? cboCategory.SelectedValue?.ToString() : xmlVehicle.SelectSingleNode("category")?.Value; _strSelectedVehicle = strSelectedId; _decMarkup = nudMarkup.Value; DialogResult = DialogResult.OK; }
private void trePowers_AfterSelect(object sender, TreeViewEventArgs e) { lblPowerPoints.Visible = false; lblPowerPointsLabel.Visible = false; string strSelectedPower = trePowers.SelectedNode.Tag?.ToString(); if (!string.IsNullOrEmpty(strSelectedPower)) { XPathNavigator objXmlPower = _xmlBaseCritterPowerDataNode.SelectSingleNode("powers/power[id = \"" + strSelectedPower + "\"]"); if (objXmlPower != null) { lblCritterPowerCategory.Text = objXmlPower.SelectSingleNode("category")?.Value ?? string.Empty; switch (objXmlPower.SelectSingleNode("type")?.Value) { case "M": lblCritterPowerType.Text = LanguageManager.GetString("String_SpellTypeMana", GlobalOptions.Language); break; case "P": lblCritterPowerType.Text = LanguageManager.GetString("String_SpellTypePhysical", GlobalOptions.Language); break; default: lblCritterPowerType.Text = string.Empty; break; } switch (objXmlPower.SelectSingleNode("action")?.Value) { case "Auto": lblCritterPowerAction.Text = LanguageManager.GetString("String_ActionAutomatic", GlobalOptions.Language); break; case "Free": lblCritterPowerAction.Text = LanguageManager.GetString("String_ActionFree", GlobalOptions.Language); break; case "Simple": lblCritterPowerAction.Text = LanguageManager.GetString("String_ActionSimple", GlobalOptions.Language); break; case "Complex": lblCritterPowerAction.Text = LanguageManager.GetString("String_ActionComplex", GlobalOptions.Language); break; case "Special": lblCritterPowerAction.Text = LanguageManager.GetString("String_SpellDurationSpecial", GlobalOptions.Language); break; default: lblCritterPowerAction.Text = string.Empty; break; } string strRange = objXmlPower.SelectSingleNode("range")?.Value ?? string.Empty; if (!string.IsNullOrEmpty(strRange)) { strRange = strRange.CheapReplace("Self", () => LanguageManager.GetString("String_SpellRangeSelf", GlobalOptions.Language)) .CheapReplace("Special", () => LanguageManager.GetString("String_SpellDurationSpecial", GlobalOptions.Language)) .CheapReplace("LOS", () => LanguageManager.GetString("String_SpellRangeLineOfSight", GlobalOptions.Language)) .CheapReplace("LOI", () => LanguageManager.GetString("String_SpellRangeLineOfInfluence", GlobalOptions.Language)) .CheapReplace("T", () => LanguageManager.GetString("String_SpellRangeTouch", GlobalOptions.Language)) .CheapReplace("(A)", () => "(" + LanguageManager.GetString("String_SpellRangeArea", GlobalOptions.Language) + ')') .CheapReplace("MAG", () => LanguageManager.GetString("String_AttributeMAGShort", GlobalOptions.Language)); } lblCritterPowerRange.Text = strRange; string strDuration = objXmlPower.SelectSingleNode("duration")?.Value ?? string.Empty; switch (strDuration) { case "Instant": lblCritterPowerDuration.Text = LanguageManager.GetString("String_SpellDurationInstantLong", GlobalOptions.Language); break; case "Sustained": lblCritterPowerDuration.Text = LanguageManager.GetString("String_SpellDurationSustained", GlobalOptions.Language); break; case "Always": lblCritterPowerDuration.Text = LanguageManager.GetString("String_SpellDurationAlways", GlobalOptions.Language); break; case "Special": lblCritterPowerDuration.Text = LanguageManager.GetString("String_SpellDurationSpecial", GlobalOptions.Language); break; default: lblCritterPowerDuration.Text = strDuration; break; } string strSource = objXmlPower.SelectSingleNode("source")?.Value ?? LanguageManager.GetString("String_Unknown", GlobalOptions.Language); string strPage = objXmlPower.SelectSingleNode("altpage")?.Value ?? objXmlPower.SelectSingleNode("page")?.Value ?? LanguageManager.GetString("String_Unknown", GlobalOptions.Language); string strSpaceCharacter = LanguageManager.GetString("String_Space", GlobalOptions.Language); lblCritterPowerSource.Text = CommonFunctions.LanguageBookShort(strSource, GlobalOptions.Language) + strSpaceCharacter + strPage; lblCritterPowerSource.SetToolTip(CommonFunctions.LanguageBookLong(strSource, GlobalOptions.Language) + strSpaceCharacter + LanguageManager.GetString("String_Page", GlobalOptions.Language) + ' ' + strPage); nudCritterPowerRating.Visible = objXmlPower.SelectSingleNode("rating") != null; lblKarma.Text = objXmlPower.SelectSingleNode("karma")?.Value ?? "0"; // If the character is a Free Spirit, populate the Power Points Cost as well. if (_objCharacter.Metatype == "Free Spirit") { XPathNavigator xmlOptionalPowerCostNode = _xmlMetatypeDataNode.SelectSingleNode("optionalpowers/power[. = \"" + objXmlPower.SelectSingleNode("name")?.Value + "\"]/@cost"); if (xmlOptionalPowerCostNode != null) { lblPowerPoints.Text = xmlOptionalPowerCostNode.Value; lblPowerPoints.Visible = true; lblPowerPointsLabel.Visible = true; } } } } lblCritterPowerTypeLabel.Visible = !string.IsNullOrEmpty(lblCritterPowerType.Text); lblCritterPowerActionLabel.Visible = !string.IsNullOrEmpty(lblCritterPowerAction.Text); lblCritterPowerRangeLabel.Visible = !string.IsNullOrEmpty(lblCritterPowerRange.Text); lblCritterPowerDurationLabel.Visible = !string.IsNullOrEmpty(lblCritterPowerDuration.Text); lblCritterPowerSourceLabel.Visible = !string.IsNullOrEmpty(lblCritterPowerSource.Text); lblKarmaLabel.Visible = !string.IsNullOrEmpty(lblKarma.Text); }
/// <summary> /// Refresh the information for the selected Vehicle. /// </summary> private void UpdateSelectedVehicle() { string strSelectedId = lstVehicle.SelectedValue?.ToString(); XPathNavigator objXmlVehicle = null; if (!string.IsNullOrEmpty(strSelectedId)) { // Retireve the information for the selected Vehicle. objXmlVehicle = _xmlBaseVehicleDataNode.SelectSingleNode("vehicles/vehicle[id = \"" + strSelectedId + "\"]"); } if (objXmlVehicle == null) { lblVehicleHandling.Text = string.Empty; lblVehicleAccel.Text = string.Empty; lblVehicleSpeed.Text = string.Empty; lblVehiclePilot.Text = string.Empty; lblVehicleBody.Text = string.Empty; lblVehicleArmor.Text = string.Empty; lblVehicleSeats.Text = string.Empty; lblVehicleSensor.Text = string.Empty; lblVehicleAvail.Text = string.Empty; lblSource.Text = string.Empty; lblVehicleCost.Text = string.Empty; lblTest.Text = string.Empty; GlobalOptions.ToolTipProcessor.SetToolTip(lblSource, string.Empty); return; } decimal decCostModifier = 1.0m; if (chkUsedVehicle.Checked) { decCostModifier -= (nudUsedVehicleDiscount.Value / 100.0m); } lblVehicleHandling.Text = objXmlVehicle.SelectSingleNode("handling")?.Value; lblVehicleAccel.Text = objXmlVehicle.SelectSingleNode("accel")?.Value; lblVehicleSpeed.Text = objXmlVehicle.SelectSingleNode("speed")?.Value; lblVehiclePilot.Text = objXmlVehicle.SelectSingleNode("pilot")?.Value; lblVehicleBody.Text = objXmlVehicle.SelectSingleNode("body")?.Value; lblVehicleArmor.Text = objXmlVehicle.SelectSingleNode("armor")?.Value; lblVehicleSeats.Text = objXmlVehicle.SelectSingleNode("seats")?.Value; lblVehicleSensor.Text = objXmlVehicle.SelectSingleNode("sensor")?.Value; string strAvail = objXmlVehicle.SelectSingleNode("avail")?.Value ?? string.Empty; if (!string.IsNullOrEmpty(strAvail)) { string strSuffix = string.Empty; char chrLastChar = strAvail.Length > 0 ? strAvail[strAvail.Length - 1] : ' '; if (chrLastChar == 'F') { strSuffix = LanguageManager.GetString("String_AvailForbidden", GlobalOptions.Language); strAvail = strAvail.Substring(0, strAvail.Length - 1); } else if (chrLastChar == 'R') { strSuffix = LanguageManager.GetString("String_AvailRestricted", GlobalOptions.Language); strAvail = strAvail.Substring(0, strAvail.Length - 1); } if (chkUsedVehicle.Checked) { if (int.TryParse(strAvail, out int intTmp)) { strAvail = intTmp + 4.ToString(); } } strAvail += strSuffix; } lblVehicleAvail.Text = strAvail; chkBlackMarketDiscount.Checked = _setBlackMarketMaps.Contains(objXmlVehicle.SelectSingleNode("category")?.Value); // Apply the cost multiplier to the Vehicle (will be 1 unless Used Vehicle is selected) string strCost = objXmlVehicle.SelectSingleNode("cost")?.Value ?? string.Empty; if (strCost.StartsWith("Variable")) { lblVehicleCost.Text = strCost.TrimStartOnce("Variable(", true).TrimEndOnce(')'); lblTest.Text = string.Empty; } else { decimal decCost = 0.0m; if (!chkFreeItem.Checked) { if (decimal.TryParse(strCost, NumberStyles.Any, GlobalOptions.InvariantCultureInfo, out decimal decTmp)) { decCost = decTmp; } // Apply the markup if applicable. decCost *= decCostModifier; decCost *= 1 + (nudMarkup.Value / 100.0m); if (chkBlackMarketDiscount.Checked) { decCost *= 0.9m; } if (_setDealerConnectionMaps != null) { if (_setDealerConnectionMaps.Any(set => objXmlVehicle.SelectSingleNode("category").Value.StartsWith(set))) { decCost *= 0.9m; } } } lblVehicleCost.Text = decCost.ToString(_objCharacter.Options.NuyenFormat, GlobalOptions.CultureInfo) + '¥'; lblTest.Text = _objCharacter.AvailTest(decCost, lblVehicleAvail.Text); } string strSource = objXmlVehicle.SelectSingleNode("source")?.Value ?? LanguageManager.GetString("String_Unknown", GlobalOptions.Language); string strPage = objXmlVehicle.SelectSingleNode("altpage")?.Value ?? objXmlVehicle.SelectSingleNode("page")?.Value ?? LanguageManager.GetString("String_Unknown", GlobalOptions.Language); string strSpaceCharacter = LanguageManager.GetString("String_Space", GlobalOptions.Language); lblSource.Text = CommonFunctions.LanguageBookShort(strSource, GlobalOptions.Language) + strSpaceCharacter + strPage; GlobalOptions.ToolTipProcessor.SetToolTip(lblSource, CommonFunctions.LanguageBookLong(strSource, GlobalOptions.Language) + strSpaceCharacter + LanguageManager.GetString("String_Page", GlobalOptions.Language) + strSpaceCharacter + strPage); }
private void BuildVehicleList(XPathNodeIterator objXmlVehicleList) { List <ListItem> lstVehicles = new List <ListItem>(); foreach (XPathNavigator objXmlVehicle in objXmlVehicleList) { if (!chkHideOverAvailLimit.Checked || SelectionShared.CheckAvailRestriction(objXmlVehicle, _objCharacter)) { string strDisplayname = objXmlVehicle.SelectSingleNode("translate")?.Value ?? objXmlVehicle.SelectSingleNode("name")?.Value ?? LanguageManager.GetString("String_Unknown", GlobalOptions.Language); if (!_objCharacter.Options.SearchInCategoryOnly && txtSearch.TextLength != 0) { string strCategory = objXmlVehicle.SelectSingleNode("category")?.Value; if (!string.IsNullOrEmpty(strCategory)) { ListItem objFoundItem = _lstCategory.Find(objFind => objFind.Value.ToString() == strCategory); if (!string.IsNullOrEmpty(objFoundItem.Name)) { strDisplayname += " [" + objFoundItem.Name + ']'; } } } lstVehicles.Add(new ListItem(objXmlVehicle.SelectSingleNode("id")?.Value ?? string.Empty, strDisplayname)); } } lstVehicles.Sort(CompareListItems.CompareNames); lstVehicle.BeginUpdate(); lstVehicle.DataSource = null; lstVehicle.ValueMember = "Value"; lstVehicle.DisplayMember = "Name"; lstVehicle.DataSource = lstVehicles; lstVehicle.EndUpdate(); }
private void frmSelectSpell_Load(object sender, EventArgs e) { // If a value is forced, set the name of the spell and accept the form. if (!string.IsNullOrEmpty(_strForceSpell)) { _strSelectedSpell = _strForceSpell; DialogResult = DialogResult.OK; } _blnCanGenericSpellBeFree = _objCharacter.AllowFreeSpells.Item2; _blnCanTouchOnlySpellBeFree = _objCharacter.AllowFreeSpells.Item1; txtSearch.Text = string.Empty; // Populate the Category list. HashSet <string> limit = new HashSet <string>(); foreach (Improvement improvement in _objCharacter.Improvements.Where(x => (x.ImproveType == Improvement.ImprovementType.LimitSpellCategory || x.ImproveType == Improvement.ImprovementType.AllowSpellCategory) && x.Enabled)) { limit.Add(improvement.ImprovedName); } string strFilterPrefix = "spells/spell[(" + _objCharacter.Options.BookXPath() + ") and category = "; foreach (XPathNavigator objXmlCategory in _xmlBaseSpellDataNode.Select("categories/category")) { string strCategory = objXmlCategory.Value; if (!_blnIgnoreRequirements) { foreach (Improvement improvement in _objCharacter.Improvements.Where(x => (x.ImproveType == Improvement.ImprovementType.AllowSpellRange || x.ImproveType == Improvement.ImprovementType.LimitSpellRange) && x.Enabled)) { if (_xmlBaseSpellDataNode.SelectSingleNode(strFilterPrefix + strCategory.CleanXPath() + " and range = " + improvement.ImprovedName.CleanXPath() + "]") != null) { limit.Add(strCategory); } } if (limit.Count != 0 && !limit.Contains(strCategory)) { continue; } if (!string.IsNullOrEmpty(_strLimitCategory) && _strLimitCategory != strCategory) { continue; } } if (_xmlBaseSpellDataNode.SelectSingleNode(strFilterPrefix + strCategory.CleanXPath() + "]") == null) { continue; } _lstCategory.Add(new ListItem(strCategory, objXmlCategory.SelectSingleNode("@translate")?.Value ?? strCategory)); } _lstCategory.Sort(CompareListItems.CompareNames); if (_lstCategory.Count != 1) { _lstCategory.Insert(0, new ListItem("Show All", LanguageManager.GetString("String_ShowAll"))); } cboCategory.BeginUpdate(); cboCategory.DataSource = null; cboCategory.DataSource = _lstCategory; cboCategory.ValueMember = nameof(ListItem.Value); cboCategory.DisplayMember = nameof(ListItem.Name); // Select the first Category in the list. if (string.IsNullOrEmpty(s_StrSelectCategory)) { cboCategory.SelectedIndex = 0; } else { cboCategory.SelectedValue = s_StrSelectCategory; } if (cboCategory.SelectedIndex == -1) { cboCategory.SelectedIndex = 0; } cboCategory.EndUpdate(); // Don't show the Extended Spell checkbox if the option to Extend any Detection Spell is disabled. chkExtended.Visible = _objCharacter.Options.ExtendAnyDetectionSpell; _blnLoading = false; BuildSpellList(); }
private void RefreshCBOs() { XmlNode xmlRequiredNode = null; XmlNode xmlForbiddenNode = null; string strSelectedMount = cboSize.SelectedValue?.ToString(); if (!string.IsNullOrEmpty(strSelectedMount)) { XmlNode xmlSelectedMount = _xmlDoc.SelectSingleNode("/chummer/weaponmounts/weaponmount[id = \"" + strSelectedMount + "\"]"); if (xmlSelectedMount != null) { xmlForbiddenNode = xmlSelectedMount.SelectSingleNode("forbidden/weaponmountdetails"); xmlRequiredNode = xmlSelectedMount.SelectSingleNode("required/weaponmountdetails"); } } XmlNode xmlVehicleNode = _objVehicle.GetNode(); List <ListItem> lstVisibility; List <ListItem> lstFlexibility; List <ListItem> lstControl; // Populate the Weapon Mount Category list. string strFilter = "category != \"Size\" and not(hide)"; if (!_objVehicle.IsDrone || !GlobalOptions.Dronemods) { strFilter += " and not(optionaldrone)"; } using (XmlNodeList xmlWeaponMountOptionNodeList = _xmlDoc.SelectNodes("/chummer/weaponmounts/weaponmount[" + strFilter + "]")) { lstVisibility = new List <ListItem>(xmlWeaponMountOptionNodeList?.Count ?? 0); lstFlexibility = new List <ListItem>(xmlWeaponMountOptionNodeList?.Count ?? 0); lstControl = new List <ListItem>(xmlWeaponMountOptionNodeList?.Count ?? 0); if (xmlWeaponMountOptionNodeList?.Count > 0) { foreach (XmlNode xmlWeaponMountOptionNode in xmlWeaponMountOptionNodeList) { string strId = xmlWeaponMountOptionNode["id"]?.InnerText; if (string.IsNullOrEmpty(strId)) { continue; } XmlNode xmlTestNode = xmlWeaponMountOptionNode.SelectSingleNode("forbidden/vehicledetails"); if (xmlTestNode != null && xmlVehicleNode.ProcessFilterOperationNode(xmlTestNode, false)) { // Assumes topmost parent is an AND node continue; } xmlTestNode = xmlWeaponMountOptionNode.SelectSingleNode("required/vehicledetails"); if (xmlTestNode != null && !xmlVehicleNode.ProcessFilterOperationNode(xmlTestNode, false)) { // Assumes topmost parent is an AND node continue; } string strName = xmlWeaponMountOptionNode["name"]?.InnerText ?? LanguageManager.GetString("String_Unknown"); bool blnAddItem = true; switch (xmlWeaponMountOptionNode["category"]?.InnerText) { case "Visibility": { XmlNodeList xmlNodeList = xmlForbiddenNode?.SelectNodes("visibility"); if (xmlNodeList?.Count > 0) { foreach (XmlNode xmlLoopNode in xmlNodeList) { if (xmlLoopNode.InnerText == strName) { blnAddItem = false; break; } } } if (xmlRequiredNode != null) { blnAddItem = false; xmlNodeList = xmlRequiredNode.SelectNodes("visibility"); if (xmlNodeList?.Count > 0) { foreach (XmlNode xmlLoopNode in xmlNodeList) { if (xmlLoopNode.InnerText == strName) { blnAddItem = true; break; } } } } if (blnAddItem) { lstVisibility.Add(new ListItem(strId, xmlWeaponMountOptionNode["translate"]?.InnerText ?? strName)); } } break; case "Flexibility": { XmlNodeList xmlNodeList = xmlForbiddenNode?.SelectNodes("flexibility"); if (xmlNodeList?.Count > 0) { foreach (XmlNode xmlLoopNode in xmlNodeList) { if (xmlLoopNode.InnerText == strName) { blnAddItem = false; break; } } } if (xmlRequiredNode != null) { blnAddItem = false; xmlNodeList = xmlRequiredNode.SelectNodes("flexibility"); if (xmlNodeList?.Count > 0) { foreach (XmlNode xmlLoopNode in xmlNodeList) { if (xmlLoopNode.InnerText == strName) { blnAddItem = true; break; } } } } if (blnAddItem) { lstFlexibility.Add(new ListItem(strId, xmlWeaponMountOptionNode["translate"]?.InnerText ?? strName)); } } break; case "Control": { XmlNodeList xmlNodeList = xmlForbiddenNode?.SelectNodes("control"); if (xmlNodeList?.Count > 0) { foreach (XmlNode xmlLoopNode in xmlNodeList) { if (xmlLoopNode.InnerText == strName) { blnAddItem = false; break; } } } if (xmlRequiredNode != null) { blnAddItem = false; xmlNodeList = xmlRequiredNode.SelectNodes("control"); if (xmlNodeList?.Count > 0) { foreach (XmlNode xmlLoopNode in xmlNodeList) { if (xmlLoopNode.InnerText == strName) { blnAddItem = true; break; } } } } if (blnAddItem) { lstControl.Add(new ListItem(strId, xmlWeaponMountOptionNode["translate"]?.InnerText ?? strName)); } } break; default: Utils.BreakIfDebug(); break; } } } } bool blnOldLoading = _blnLoading; _blnLoading = true; string strOldVisibility = cboVisibility.SelectedValue?.ToString(); string strOldFlexibility = cboFlexibility.SelectedValue?.ToString(); string strOldControl = cboControl.SelectedValue?.ToString(); cboVisibility.BeginUpdate(); cboVisibility.ValueMember = nameof(ListItem.Value); cboVisibility.DisplayMember = nameof(ListItem.Name); cboVisibility.DataSource = lstVisibility; cboVisibility.Enabled = lstVisibility.Count > 1; if (!string.IsNullOrEmpty(strOldVisibility)) { cboVisibility.SelectedValue = strOldVisibility; } if (cboVisibility.SelectedIndex == -1 && lstVisibility.Count > 0) { cboVisibility.SelectedIndex = 0; } cboVisibility.EndUpdate(); cboFlexibility.BeginUpdate(); cboFlexibility.ValueMember = nameof(ListItem.Value); cboFlexibility.DisplayMember = nameof(ListItem.Name); cboFlexibility.DataSource = lstFlexibility; cboFlexibility.Enabled = lstFlexibility.Count > 1; if (!string.IsNullOrEmpty(strOldFlexibility)) { cboFlexibility.SelectedValue = strOldFlexibility; } if (cboFlexibility.SelectedIndex == -1 && lstFlexibility.Count > 0) { cboFlexibility.SelectedIndex = 0; } cboFlexibility.EndUpdate(); cboControl.BeginUpdate(); cboControl.ValueMember = nameof(ListItem.Value); cboControl.DisplayMember = nameof(ListItem.Name); cboControl.DataSource = lstControl; cboControl.Enabled = lstControl.Count > 1; if (!string.IsNullOrEmpty(strOldControl)) { cboControl.SelectedValue = strOldControl; } if (cboControl.SelectedIndex == -1 && lstControl.Count > 0) { cboControl.SelectedIndex = 0; } cboControl.EndUpdate(); _blnLoading = blnOldLoading; }
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, GlobalOptions.InvariantCultureInfo); string[] astrSelectedValues = { cboVisibility.SelectedValue?.ToString(), cboFlexibility.SelectedValue?.ToString(), cboControl.SelectedValue?.ToString() }; foreach (string strSelectedId in astrSelectedValues) { if (!string.IsNullOrEmpty(strSelectedId)) { XmlNode xmlLoopNode = _xmlDoc.SelectSingleNode("/chummer/weaponmounts/weaponmount[id = \"" + strSelectedId + "\"]"); if (xmlLoopNode != null) { intSlots += Convert.ToInt32(xmlLoopNode["slots"]?.InnerText, GlobalOptions.InvariantCultureInfo); } } } foreach (VehicleMod objMod in _lstMods) { intSlots += objMod.CalculatedSlots; } string strSpace = LanguageManager.GetString("String_Space"); TreeNode objModsParentNode = treMods.FindNode("Node_AdditionalMods"); do { using (frmSelectVehicleMod frmPickVehicleMod = new frmSelectVehicleMod(_objCharacter, _objVehicle, _objMount?.Mods) { // Pass the selected vehicle on to the form. VehicleMountMods = true, WeaponMountSlots = intSlots }) { frmPickVehicleMod.ShowDialog(this); // Make sure the dialogue window was not canceled. if (frmPickVehicleMod.DialogResult == DialogResult.Cancel) { 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"; } // 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(this, LanguageManager.GetString("Message_CapacityReached"), LanguageManager.GetString("MessageTitle_CapacityReached"), 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(this, LanguageManager.GetString("Message_NotEnoughNuyen"), LanguageManager.GetString("MessageTitle_NotEnoughNuyen"), MessageBoxButtons.OK, MessageBoxIcon.Information); continue; } // Create the Expense Log Entry. ExpenseLogEntry objExpense = new ExpenseLogEntry(_objCharacter); objExpense.Create(decCost * -1, LanguageManager.GetString("String_ExpensePurchaseVehicleMod") + strSpace + 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") }; treMods.Nodes.Add(objModsParentNode); objModsParentNode.Expand(); } objModsParentNode.Nodes.Add(objNewNode); treMods.SelectedNode = objNewNode; } }while (blnAddAgain); }
/// <summary> /// Calculate the LP value for the selected items. /// </summary> private void CalculateValues() { if (_blnSkipRefresh) { return; } int intLP = 0; decimal decBaseNuyen = 0; decimal decNuyen = 0; int intMultiplier = 0; int intMultiplierBaseOnly = 0; decimal decExtraCostAssets = 0; decimal decExtraCostServicesOutings = 0; decimal decExtraCostContracts = 0; int intMinComfort = 0; int intMaxComfort = 0; int intMinArea = 0; int intMaxArea = 0; int intMinSec = 0; int intMaxSec = 0; string strBaseLifestyle = cboBaseLifestyle.SelectedValue.ToString(); // Calculate the limits of the 3 aspects. // Comforts. XmlNode objXmlNode = _objXmlDocument.SelectSingleNode("/chummer/comforts/comfort[name = \"" + strBaseLifestyle + "\"]"); objXmlNode.TryGetInt32FieldQuickly("minimum", ref intMinComfort); objXmlNode.TryGetInt32FieldQuickly("limit", ref intMaxComfort); if (intMaxComfort < intMinComfort) { intMaxComfort = intMinComfort; } // Area. objXmlNode = _objXmlDocument.SelectSingleNode("/chummer/neighborhoods/neighborhood[name = \"" + strBaseLifestyle + "\"]"); objXmlNode.TryGetInt32FieldQuickly("minimum", ref intMinArea); objXmlNode.TryGetInt32FieldQuickly("limit", ref intMaxArea); if (intMaxArea < intMinArea) { intMaxArea = intMinArea; } // Security. objXmlNode = _objXmlDocument.SelectSingleNode("/chummer/securities/security[name = \"" + strBaseLifestyle + "\"]"); objXmlNode.TryGetInt32FieldQuickly("minimum", ref intMinSec); objXmlNode.TryGetInt32FieldQuickly("limit", ref intMaxSec); if (intMaxSec < intMinSec) { intMaxSec = intMinSec; } // Calculate the cost of Positive Qualities. foreach (LifestyleQuality objQuality in _objLifestyle.LifestyleQualities) { intLP -= objQuality.LP; intMultiplier += objQuality.Multiplier; intMultiplierBaseOnly += objQuality.BaseMultiplier; intMaxArea += objQuality.AreaMaximum; intMaxComfort += objQuality.ComfortMaximum; intMaxSec += objQuality.SecurityMaximum; intMinArea += objQuality.Area; intMinComfort += objQuality.Comfort; intMinSec += objQuality.Security; decimal decCost = objQuality.Cost; // Calculate the cost of Entertainments. if (decCost != 0 && (objQuality.Type == QualityType.Entertainment || objQuality.Type == QualityType.Contracts)) { objXmlNode = _objXmlDocument.SelectSingleNode("/chummer/qualities/quality[name = \"" + objQuality.Name + "\"]"); if (objQuality.Type == QualityType.Contracts) { decExtraCostContracts += decCost; } else if (objXmlNode?["category"] != null && (objXmlNode["category"].InnerText.Equals("Entertainment - Outing") || objXmlNode["category"].InnerText.Equals("Entertainment - Service"))) { decExtraCostServicesOutings += decCost; } else { decExtraCostAssets += decCost; } } else { decBaseNuyen += decCost; } } _blnSkipRefresh = true; nudComforts.Maximum = Math.Max(intMaxComfort - intMinComfort, 0); nudArea.Maximum = Math.Max(intMaxArea - intMinArea, 0); nudSecurity.Maximum = Math.Max(intMaxSec - intMinSec, 0); int intComfortsValue = decimal.ToInt32(nudComforts.Value); int intAreaValue = decimal.ToInt32(nudArea.Value); int intSecurityValue = decimal.ToInt32(nudSecurity.Value); int intRoommatesValue = decimal.ToInt32(nudRoommates.Value); _blnSkipRefresh = false; //set the Labels for current/maximum Label_SelectAdvancedLifestyle_Base_Comforts.Text = LanguageManager.GetString("Label_SelectAdvancedLifestyle_Base_Comforts", GlobalOptions.Language).Replace("{0}", (nudComforts.Value + intMinComfort).ToString(GlobalOptions.CultureInfo)).Replace("{1}", (nudComforts.Maximum + intMinComfort).ToString(GlobalOptions.CultureInfo)); Label_SelectAdvancedLifestyle_Base_Securities.Text = LanguageManager.GetString("Label_SelectAdvancedLifestyle_Base_Security", GlobalOptions.Language).Replace("{0}", (nudSecurity.Value + intMinSec).ToString(GlobalOptions.CultureInfo)).Replace("{1}", (nudSecurity.Maximum + intMinSec).ToString(GlobalOptions.CultureInfo)); Label_SelectAdvancedLifestyle_Base_Area.Text = LanguageManager.GetString("Label_SelectAdvancedLifestyle_Base_Area", GlobalOptions.Language).Replace("{0}", (nudArea.Value + intMinArea).ToString(GlobalOptions.CultureInfo)).Replace("{1}", (nudArea.Maximum + intMinArea).ToString(GlobalOptions.CultureInfo)); //calculate the total LP objXmlNode = _objXmlDocument.SelectSingleNode("/chummer/lifestyles/lifestyle[name = \"" + strBaseLifestyle + "\"]"); intLP += Convert.ToInt32(objXmlNode?["lp"]?.InnerText); intLP -= intComfortsValue; intLP -= intAreaValue; intLP -= intSecurityValue; intLP += intRoommatesValue; if (strBaseLifestyle == "Street") { decNuyen += intComfortsValue * 50; decNuyen += intAreaValue * 50; decNuyen += intSecurityValue * 50; } else if (strBaseLifestyle == "Traveler") { intLP += _intTravelerRdmLP; } if (!chkTrustFund.Checked) { // Determine the base Nuyen cost. XmlNode objXmlLifestyle = _objXmlDocument.SelectSingleNode("chummer/lifestyles/lifestyle[name = \"" + strBaseLifestyle + "\"]"); if (objXmlLifestyle?["cost"] != null) { decBaseNuyen += Convert.ToDecimal(objXmlLifestyle["cost"].InnerText, GlobalOptions.InvariantCultureInfo); } decBaseNuyen += decBaseNuyen * ((intMultiplier + intMultiplierBaseOnly) / 100.0m); decNuyen += decBaseNuyen; } decNuyen += decExtraCostAssets + (decExtraCostAssets * (intMultiplier / 100.0m)); decNuyen *= nudPercentage.Value / 100.0m; if (!chkPrimaryTenant.Checked) { decNuyen /= intRoommatesValue + 1.0m; } decNuyen += decExtraCostServicesOutings + (decExtraCostServicesOutings * (intMultiplier / 100.0m));; decNuyen += decExtraCostContracts; lblTotalLP.Text = intLP.ToString(); lblCost.Text = decNuyen.ToString(_objCharacter.Options.NuyenFormat, GlobalOptions.CultureInfo) + '¥'; }
private void cboCategory_SelectedIndexChanged(object sender, EventArgs e) { trePowers.Nodes.Clear(); string strCategory = cboCategory.SelectedValue?.ToString(); List <string> lstPowerWhitelist = new List <string>(); // If the Critter is only allowed certain Powers, display only those. XPathNavigator xmlOptionalPowers = _xmlMetatypeDataNode.SelectSingleNode("optionalpowers"); if (xmlOptionalPowers != null) { foreach (XPathNavigator xmlNode in xmlOptionalPowers.Select("power")) { lstPowerWhitelist.Add(xmlNode.Value); } // Determine if the Critter has a physical presence Power (Materialization, Possession, or Inhabitation). bool blnPhysicalPresence = _objCharacter.CritterPowers.Any(x => x.Name == "Materialization" || x.Name == "Possession" || x.Name == "Inhabitation"); // Add any Critter Powers the Critter comes with that have been manually deleted so they can be re-added. foreach (XPathNavigator objXmlCritterPower in _xmlMetatypeDataNode.Select("powers/power")) { bool blnAddPower = true; // Make sure the Critter doesn't already have the Power. foreach (CritterPower objCheckPower in _objCharacter.CritterPowers) { if (objCheckPower.Name == objXmlCritterPower.Value) { blnAddPower = false; break; } if ((objCheckPower.Name == "Materialization" || objCheckPower.Name == "Possession" || objCheckPower.Name == "Inhabitation") && blnPhysicalPresence) { blnAddPower = false; break; } } if (blnAddPower) { lstPowerWhitelist.Add(objXmlCritterPower.Value); // If Manifestation is one of the Powers, also include Inhabitation and Possess if they're not already in the list. if (!blnPhysicalPresence) { if (objXmlCritterPower.Value == "Materialization") { bool blnFoundPossession = false; bool blnFoundInhabitation = false; foreach (string strCheckPower in lstPowerWhitelist) { if (strCheckPower == "Possession") { blnFoundPossession = true; } else if (strCheckPower == "Inhabitation") { blnFoundInhabitation = true; } if (blnFoundInhabitation && blnFoundPossession) { break; } } if (!blnFoundPossession) { lstPowerWhitelist.Add("Possession"); } if (!blnFoundInhabitation) { lstPowerWhitelist.Add("Inhabitation"); } } } } } } string strFilter = "(" + _objCharacter.Options.BookXPath() + ')'; if (!string.IsNullOrEmpty(strCategory) && strCategory != "Show All") { strFilter += " and (contains(category,\"" + strCategory + "\"))"; } else { bool blnHasToxic = false; StringBuilder objCategoryFilter = new StringBuilder(); foreach (string strItem in _lstCategory.Select(x => x.Value)) { if (!string.IsNullOrEmpty(strItem)) { objCategoryFilter.Append("(contains(category,\"" + strItem + "\")) or "); if (strItem == "Toxic Critter Powers") { objCategoryFilter.Append("toxic = \"True\" or "); blnHasToxic = true; } } } if (objCategoryFilter.Length > 0) { strFilter += " and (" + objCategoryFilter.ToString().TrimEndOnce(" or ") + ')'; } if (!blnHasToxic) { strFilter += " and (not(toxic) or toxic != \"True\")"; } } strFilter += CommonFunctions.GenerateSearchXPath(txtSearch.Text); foreach (XPathNavigator objXmlPower in _xmlBaseCritterPowerDataNode.Select("powers/power[" + strFilter + "]")) { string strPowerName = objXmlPower.SelectSingleNode("name")?.Value ?? LanguageManager.GetString("String_Unknown", GlobalOptions.Language); if (!lstPowerWhitelist.Contains(strPowerName) && lstPowerWhitelist.Count != 0) { continue; } if (!objXmlPower.RequirementsMet(_objCharacter, string.Empty, string.Empty)) { continue; } TreeNode objNode = new TreeNode { Tag = objXmlPower.SelectSingleNode("id")?.Value ?? string.Empty, Text = objXmlPower.SelectSingleNode("translate")?.Value ?? strPowerName }; trePowers.Nodes.Add(objNode); } trePowers.Sort(); }
public frmSelectSkillGroup() { InitializeComponent(); LanguageManager.Load(GlobalOptions.Language, this); _objXmlDocument = XmlManager.Load("skills.xml"); }
private void cmdRollDice_Click(object sender, EventArgs e) { // TODO roll the dice List <int> results = new List <int>(); int val = 0; for (int i = 0; i < NumberOfDice; i++) { do { _intModuloTemp = s_ObjRandom.Next(); }while (_intModuloTemp >= int.MaxValue - 1); // Modulo bias removal for 1d6 val = 1 + _intModuloTemp % 6; results.Add(val); // check for pushing the limit if (EdgeUse == EdgeUses.PushTheLimit || chkRuleOf6.Checked) { while (val == 6) { do { _intModuloTemp = s_ObjRandom.Next(); }while (_intModuloTemp >= int.MaxValue - 1); // Modulo bias removal for 1d6 val = 1 + _intModuloTemp % 6; results.Add(val); } } } // populate the text box StringBuilder sb = new StringBuilder(); // show the number of hits int hits = 0; // calculate the 1 (and 2's) int glitches = 0; foreach (int intResult in results) { if (intResult == 5 || intResult == 6) { hits += 1; } else if (intResult == 1 || (chkRushJob.Checked && intResult == 2)) { glitches += 1; } sb.Append(intResult.ToString()); sb.Append(", "); } if (sb.Length > 0) { sb.Length -= 2; // remove trailing comma } if (chkBubbleDie.Checked && results.Count % 2 == 0 && results.Count / 2 == glitches + Gremlins) { do { _intModuloTemp = s_ObjRandom.Next(); }while (_intModuloTemp >= int.MaxValue - 1); // Modulo bias removal for 1d6 int intBubbleDieResult = 1 + _intModuloTemp % 6; sb.Append(", " + LanguageManager.GetString("String_BubbleDie") + " (" + intBubbleDieResult.ToString() + ")"); if (intBubbleDieResult == 1 || (chkRushJob.Checked && intBubbleDieResult == 2)) { glitches++; } } txtResults.Text = sb.ToString(); // calculate if we glitched or critically glitched (using gremlins) bool glitch = false, criticalGlitch = false; glitch = glitches + Gremlins > 0 && results.Count / (glitches + Gremlins) < 2; if (glitch && hits == 0) { criticalGlitch = true; } int limitAppliedHits = hits; if (limitAppliedHits > Limit && EdgeUse != EdgeUses.PushTheLimit) { limitAppliedHits = Limit; } // show the results // we have not gone over our limit sb = new StringBuilder(); if (hits > 0 && limitAppliedHits == hits) { sb.Append("Results: " + hits + " Hits!"); } if (limitAppliedHits < hits) { sb.Append("Results: " + limitAppliedHits + " Hits by Limit!"); } if (glitch && !criticalGlitch) { sb.Append(" Glitch!"); // we glitched though... } if (criticalGlitch) { sb.Append("Results: Critical Glitch!"); // we crited! } if (hits == 0 && !glitch) { sb.Append("Results: 0 Hits."); // we have no hits and no glitches } if (Threshold > 0) { if (hits >= Threshold || limitAppliedHits >= Threshold) { lblThreshold.Text = "Success! Threshold:"; // we succeded on the threshold test... } } lblResults.Text = sb.ToString(); }
private void lstTechniques_SelectedIndexChanged(object sender, EventArgs e) { if (_blnLoading) { return; } string strSelectedId = lstTechniques.SelectedValue?.ToString(); if (!string.IsNullOrEmpty(strSelectedId)) { XPathNavigator xmlTechnique = _xmlBaseChummerNode.SelectSingleNode("/chummer/techniques/technique[id = \"" + strSelectedId + "\"]"); if (xmlTechnique != null) { string strSource = xmlTechnique.SelectSingleNode("source")?.Value ?? LanguageManager.GetString("String_Unknown"); string strPage = xmlTechnique.SelectSingleNode("altpage")?.Value ?? xmlTechnique.SelectSingleNode("page")?.Value ?? LanguageManager.GetString("String_Unknown"); SourceString objSourceString = new SourceString(strSource, strPage, GlobalOptions.Language); objSourceString.SetControl(lblSource); lblSourceLabel.Visible = !string.IsNullOrEmpty(lblSource.Text); } else { lblSource.Text = string.Empty; lblSource.SetToolTip(string.Empty); lblSourceLabel.Visible = false; } } else { lblSource.Text = string.Empty; lblSource.SetToolTip(string.Empty); lblSourceLabel.Visible = 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) { objWriter.WriteStartElement("spell"); if (Limited) { objWriter.WriteElementString("name", DisplayNameShort(strLanguageToPrint) + LanguageManager.GetString("String_Space", strLanguageToPrint) + '(' + LanguageManager.GetString("String_SpellLimited", strLanguageToPrint) + ')'); } else if (Alchemical) { objWriter.WriteElementString("name", DisplayNameShort(strLanguageToPrint) + LanguageManager.GetString("String_Space", strLanguageToPrint) + '(' + LanguageManager.GetString("String_SpellAlchemical", strLanguageToPrint) + ')'); } else { objWriter.WriteElementString("name", DisplayNameShort(strLanguageToPrint)); } objWriter.WriteElementString("name_english", Name); objWriter.WriteElementString("descriptors", DisplayDescriptors(strLanguageToPrint)); objWriter.WriteElementString("category", DisplayCategory(strLanguageToPrint)); objWriter.WriteElementString("category_english", Category); objWriter.WriteElementString("type", DisplayType(strLanguageToPrint)); objWriter.WriteElementString("range", DisplayRange(strLanguageToPrint)); objWriter.WriteElementString("damage", DisplayDamage(strLanguageToPrint)); objWriter.WriteElementString("duration", DisplayDuration(strLanguageToPrint)); objWriter.WriteElementString("dv", DisplayDV(strLanguageToPrint)); objWriter.WriteElementString("alchemy", Alchemical.ToString()); objWriter.WriteElementString("dicepool", DicePool.ToString(objCulture)); objWriter.WriteElementString("source", CommonFunctions.LanguageBookShort(Source, strLanguageToPrint)); objWriter.WriteElementString("page", DisplayPage(strLanguageToPrint)); objWriter.WriteElementString("extra", LanguageManager.TranslateExtra(Extra, strLanguageToPrint)); if (_objCharacter.Options.PrintNotes) { objWriter.WriteElementString("notes", Notes); } objWriter.WriteEndElement(); }
public void RefreshNodes() { foreach (TreeNode objTypeNode in treCharacterList.Nodes) { foreach (TreeNode objCharacterNode in objTypeNode.Nodes) { string strFile = objCharacterNode.Tag.ToString(); if (_lstCharacterCache.TryGetValue(strFile, out CharacterCache objCache) && objCache != null) { objCharacterNode.Text = CalculatedName(objCache); objCharacterNode.ToolTipText = objCache.FilePath.CheapReplace(Application.StartupPath, () => '<' + Application.ProductName + '>'); if (!string.IsNullOrEmpty(objCache.ErrorText)) { objCharacterNode.ForeColor = Color.Red; objCharacterNode.ToolTipText += Environment.NewLine + Environment.NewLine + LanguageManager.GetString("String_Error", GlobalOptions.Language) + ":" + Environment.NewLine + objCache.ErrorText; } else { objCharacterNode.ForeColor = SystemColors.WindowText; } } else { objCharacterNode.Text = Path.GetFileNameWithoutExtension(strFile) + " (" + LanguageManager.GetString("String_Error", GlobalOptions.Language) + ')'; objCharacterNode.ToolTipText = strFile.CheapReplace(Application.StartupPath, () => '<' + Application.ProductName + '>') + Environment.NewLine + Environment.NewLine + LanguageManager.GetString("String_Error", GlobalOptions.Language) + ":" + Environment.NewLine + LanguageManager.GetString("MessageTitle_FileNotFound", GlobalOptions.Language); objCharacterNode.ForeColor = Color.Red; } } } }
private void tsSaveAsHTML_Click(object sender, EventArgs e) { // Save the generated output as HTML. SaveFileDialog1.Filter = LanguageManager.GetString("DialogFilter_Html") + '|' + LanguageManager.GetString("DialogFilter_All"); SaveFileDialog1.Title = LanguageManager.GetString("Button_Viewer_SaveAsHtml"); SaveFileDialog1.ShowDialog(); string strSaveFile = SaveFileDialog1.FileName; if (string.IsNullOrEmpty(strSaveFile)) { return; } if (!strSaveFile.EndsWith(".html", StringComparison.OrdinalIgnoreCase) && !strSaveFile.EndsWith(".htm", StringComparison.OrdinalIgnoreCase)) { strSaveFile += ".htm"; } using (TextWriter objWriter = new StreamWriter(strSaveFile, false, Encoding.UTF8)) objWriter.Write(webViewer.DocumentText); }
/// <summary> /// Generates a character cache, which prevents us from repeatedly loading XmlNodes or caching a full character. /// </summary> /// <param name="strFile"></param> private TreeNode CacheCharacter(string strFile) { CharacterCache objCache = new CharacterCache(); string strErrorText = string.Empty; XPathNavigator xmlSourceNode; if (!File.Exists(strFile)) { xmlSourceNode = null; strErrorText = LanguageManager.GetString("MessageTitle_FileNotFound", GlobalOptions.Language); } else { // If we run into any problems loading the character cache, fail out early. try { using (StreamReader objStreamReader = new StreamReader(strFile, Encoding.UTF8, true)) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(objStreamReader); xmlSourceNode = xmlDoc.CreateNavigator().SelectSingleNode("/character"); } } catch (Exception ex) { xmlSourceNode = null; strErrorText = ex.ToString(); } } if (xmlSourceNode != null) { objCache.Description = xmlSourceNode.SelectSingleNode("description")?.Value; objCache.BuildMethod = xmlSourceNode.SelectSingleNode("buildmethod")?.Value; objCache.Background = xmlSourceNode.SelectSingleNode("background")?.Value; objCache.CharacterNotes = xmlSourceNode.SelectSingleNode("notes")?.Value; objCache.GameNotes = xmlSourceNode.SelectSingleNode("gamenotes")?.Value; objCache.Concept = xmlSourceNode.SelectSingleNode("concept")?.Value; objCache.Karma = xmlSourceNode.SelectSingleNode("totalkarma")?.Value; objCache.Metatype = xmlSourceNode.SelectSingleNode("metatype")?.Value; objCache.Metavariant = xmlSourceNode.SelectSingleNode("metavariant")?.Value; objCache.PlayerName = xmlSourceNode.SelectSingleNode("playername")?.Value; objCache.CharacterName = xmlSourceNode.SelectSingleNode("name")?.Value; objCache.CharacterAlias = xmlSourceNode.SelectSingleNode("alias")?.Value; objCache.Created = xmlSourceNode.SelectSingleNode("created")?.Value == bool.TrueString; objCache.Essence = xmlSourceNode.SelectSingleNode("totaless")?.Value; string strSettings = xmlSourceNode.SelectSingleNode("settings")?.Value ?? string.Empty; objCache.SettingsFile = !File.Exists(Path.Combine(Application.StartupPath, "settings", strSettings)) ? LanguageManager.GetString("MessageTitle_FileNotFound", GlobalOptions.Language) : strSettings; string strMugshotBase64 = xmlSourceNode.SelectSingleNode("mugshot")?.Value; if (!string.IsNullOrEmpty(strMugshotBase64)) { objCache.Mugshot = strMugshotBase64.ToImage(); } else { XPathNavigator xmlMainMugshotIndex = xmlSourceNode.SelectSingleNode("mainmugshotindex"); if (xmlMainMugshotIndex != null && int.TryParse(xmlMainMugshotIndex.Value, out int intMainMugshotIndex) && intMainMugshotIndex >= 0) { XPathNodeIterator xmlMugshotList = xmlSourceNode.Select("mugshots/mugshot"); if (xmlMugshotList.Count > intMainMugshotIndex) { int intIndex = 0; foreach (XPathNavigator xmlMugshot in xmlMugshotList) { if (intMainMugshotIndex == intIndex) { objCache.Mugshot = xmlMugshot.Value.ToImage(); break; } intIndex += 1; } } } } } else { objCache.ErrorText = strErrorText; } objCache.FilePath = strFile; objCache.FileName = strFile.Substring(strFile.LastIndexOf(Path.DirectorySeparatorChar) + 1); if (!_lstCharacterCache.TryAdd(strFile, objCache)) { _lstCharacterCache[strFile] = objCache; } TreeNode objNode = new TreeNode { ContextMenuStrip = cmsRoster, Text = CalculatedName(objCache), ToolTipText = objCache.FilePath.CheapReplace(Application.StartupPath, () => '<' + Application.ProductName + '>'), Tag = strFile }; if (!string.IsNullOrEmpty(objCache.ErrorText)) { objNode.ForeColor = Color.Red; objNode.ToolTipText += Environment.NewLine + Environment.NewLine + LanguageManager.GetString("String_Error", GlobalOptions.Language) + ":" + Environment.NewLine + objCache.ErrorText; } return(objNode); }
private void tsSaveAsXml_Click(object sender, EventArgs e) { // Save the printout XML generated by the character. SaveFileDialog1.Filter = LanguageManager.GetString("DialogFilter_Xml") + '|' + LanguageManager.GetString("DialogFilter_All"); SaveFileDialog1.Title = LanguageManager.GetString("Button_Viewer_SaveAsXml"); SaveFileDialog1.ShowDialog(); string strSaveFile = SaveFileDialog1.FileName; if (string.IsNullOrEmpty(strSaveFile)) { return; } if (!strSaveFile.EndsWith(".xml", StringComparison.OrdinalIgnoreCase)) { strSaveFile += ".xml"; } try { _objCharacterXml.Save(strSaveFile); } catch (XmlException) { Program.MainForm.ShowMessageBox(this, LanguageManager.GetString("Message_Save_Error_Warning")); } catch (UnauthorizedAccessException) { Program.MainForm.ShowMessageBox(this, LanguageManager.GetString("Message_Save_Error_Warning")); } }
private void lstDrug_SelectedIndexChanged(object sender, EventArgs e) { if (_blnLoading) { return; } _blnLoading = true; XPathNavigator xmlDrug = null; string strSelectedId = lstDrug.SelectedValue?.ToString(); if (!string.IsNullOrEmpty(strSelectedId)) { // Retrieve the information for the selected piece of Drug. xmlDrug = _xmlBaseDrugDataNode.SelectSingleNode(_strNodeXPath + "[id = " + strSelectedId.CleanXPath() + "]"); } string strForceGrade; if (xmlDrug != null) { strForceGrade = xmlDrug.SelectSingleNode("forcegrade")?.Value; // If the piece has a Rating value, enable the Rating control, otherwise, disable it and set its value to 0. XPathNavigator xmlRatingNode = xmlDrug.SelectSingleNode("rating"); if (xmlRatingNode != null) { string strMinRating = xmlDrug.SelectSingleNode("minrating")?.Value; int intMinRating = 1; // Not a simple integer, so we need to start mucking around with strings if (!string.IsNullOrEmpty(strMinRating) && !int.TryParse(strMinRating, out intMinRating)) { strMinRating = strMinRating.CheapReplace("MaximumSTR", () => (ParentVehicle != null ? Math.Max(1, ParentVehicle.TotalBody * 2) : _objCharacter.STR.TotalMaximum).ToString(GlobalOptions.InvariantCultureInfo)) .CheapReplace("MaximumAGI", () => (ParentVehicle != null ? Math.Max(1, ParentVehicle.Pilot * 2) : _objCharacter.AGI.TotalMaximum).ToString(GlobalOptions.InvariantCultureInfo)) .CheapReplace("MinimumSTR", () => (ParentVehicle?.TotalBody ?? 3).ToString(GlobalOptions.InvariantCultureInfo)) .CheapReplace("MinimumAGI", () => (ParentVehicle?.Pilot ?? 3).ToString(GlobalOptions.InvariantCultureInfo)); object objProcess = CommonFunctions.EvaluateInvariantXPath(strMinRating, out bool blnIsSuccess); intMinRating = blnIsSuccess ? ((double)objProcess).StandardRound() : 1; } nudRating.Minimum = intMinRating; string strMaxRating = xmlRatingNode.Value; int intMaxRating = 0; // Not a simple integer, so we need to start mucking around with strings if (!string.IsNullOrEmpty(strMaxRating) && !int.TryParse(strMaxRating, out intMaxRating)) { strMaxRating = strMaxRating.CheapReplace("MaximumSTR", () => (ParentVehicle != null ? Math.Max(1, ParentVehicle.TotalBody * 2) : _objCharacter.STR.TotalMaximum).ToString(GlobalOptions.InvariantCultureInfo)) .CheapReplace("MaximumAGI", () => (ParentVehicle != null ? Math.Max(1, ParentVehicle.Pilot * 2) : _objCharacter.AGI.TotalMaximum).ToString(GlobalOptions.InvariantCultureInfo)) .CheapReplace("MinimumSTR", () => (ParentVehicle?.TotalBody ?? 3).ToString(GlobalOptions.InvariantCultureInfo)) .CheapReplace("MinimumAGI", () => (ParentVehicle?.Pilot ?? 3).ToString(GlobalOptions.InvariantCultureInfo)); object objProcess = CommonFunctions.EvaluateInvariantXPath(strMaxRating, out bool blnIsSuccess); intMaxRating = blnIsSuccess ? ((double)objProcess).StandardRound() : 1; } nudRating.Maximum = intMaxRating; if (chkHideOverAvailLimit.Checked) { int intAvailModifier = strForceGrade == "None" ? 0 : _intAvailModifier; while (nudRating.Maximum > intMinRating && !xmlDrug.CheckAvailRestriction(_objCharacter, nudRating.MaximumAsInt, intAvailModifier)) { nudRating.Maximum -= 1; } } if (chkShowOnlyAffordItems.Checked && !chkFree.Checked) { decimal decCostMultiplier = 1 + nudMarkup.Value / 100.0m; if (chkBlackMarketDiscount.Checked) { decCostMultiplier *= 0.9m; } while (nudRating.Maximum > intMinRating && !xmlDrug.CheckNuyenRestriction(_objCharacter.Nuyen, decCostMultiplier, nudRating.MaximumAsInt)) { nudRating.Maximum -= 1; } } nudRating.Value = nudRating.Minimum; nudRating.Enabled = nudRating.Minimum != nudRating.Maximum; nudRating.Visible = true; lblRatingNALabel.Visible = false; lblRatingLabel.Visible = true; } else { lblRatingLabel.Visible = true; lblRatingNALabel.Visible = true; nudRating.Minimum = 0; nudRating.Value = 0; nudRating.Visible = false; } string strSource = xmlDrug.SelectSingleNode("source")?.Value ?? LanguageManager.GetString("String_Unknown"); string strPage = xmlDrug.SelectSingleNode("altpage")?.Value ?? xmlDrug.SelectSingleNode("page")?.Value ?? LanguageManager.GetString("String_Unknown"); string strSpace = LanguageManager.GetString("String_Space"); lblSource.Text = _objCharacter.LanguageBookShort(strSource) + strSpace + strPage; lblSource.SetToolTip(_objCharacter.LanguageBookLong(strSource) + strSpace + LanguageManager.GetString("String_Page") + ' ' + strPage); lblSourceLabel.Visible = !string.IsNullOrEmpty(lblSource.Text); Grade objForcedGrade = null; if (!string.IsNullOrEmpty(strForceGrade)) { // Force the Drug to be a particular Grade. if (cboGrade.Enabled) { cboGrade.Enabled = false; } objForcedGrade = _lstGrades.FirstOrDefault(x => x.Name == strForceGrade); strForceGrade = objForcedGrade?.SourceId.ToString("D", GlobalOptions.InvariantCultureInfo); } else { cboGrade.Enabled = !_blnLockGrade; if (_blnLockGrade) { strForceGrade = _objForcedGrade?.SourceId.ToString("D", GlobalOptions.InvariantCultureInfo) ?? cboGrade.SelectedValue?.ToString(); objForcedGrade = _objForcedGrade ?? _lstGrades.FirstOrDefault(x => x.SourceId.ToString("D", GlobalOptions.InvariantCultureInfo) == strForceGrade); } } chkBlackMarketDiscount.Enabled = _objCharacter.BlackMarketDiscount; if (!chkBlackMarketDiscount.Checked) { chkBlackMarketDiscount.Checked = GlobalOptions.AssumeBlackMarket && _setBlackMarketMaps.Contains(xmlDrug.SelectSingleNode("category") ?.Value); } else if (!_setBlackMarketMaps.Contains(xmlDrug.SelectSingleNode("category")?.Value)) { //Prevent chkBlackMarketDiscount from being checked if the gear category doesn't match. chkBlackMarketDiscount.Checked = false; } // We may need to rebuild the Grade list since Cultured Bioware is not allowed to select Standard (Second-Hand) as Grade and ForceGrades can change. PopulateGrades(xmlDrug.SelectSingleNode("nosecondhand") != null || !cboGrade.Enabled && objForcedGrade?.SecondHand != true, false, strForceGrade); /* * string strNotes = xmlDrug.SelectSingleNode("altnotes")?.Value ?? xmlDrug.SelectSingleNode("notes")?.Value; * if (!string.IsNullOrEmpty(strNotes)) * { * lblDrugNotes.Visible = true; * lblDrugNotesLabel.Visible = true; * lblDrugNotes.Text = strNotes; * } * else * { * lblDrugNotes.Visible = false; * lblDrugNotesLabel.Visible = false; * }*/ } else { lblRatingLabel.Visible = false; lblRatingNALabel.Visible = false; nudRating.Minimum = 0; nudRating.Value = 0; nudRating.Visible = false; cboGrade.Enabled = !_blnLockGrade; strForceGrade = string.Empty; Grade objForcedGrade = null; if (_blnLockGrade) { strForceGrade = _objForcedGrade?.SourceId.ToString("D", GlobalOptions.InvariantCultureInfo) ?? cboGrade.SelectedValue?.ToString(); objForcedGrade = _objForcedGrade ?? _lstGrades.FirstOrDefault(x => x.SourceId.ToString("D", GlobalOptions.InvariantCultureInfo) == strForceGrade); } PopulateGrades(_blnLockGrade && objForcedGrade?.SecondHand != true, false, strForceGrade); chkBlackMarketDiscount.Checked = false; lblSourceLabel.Visible = false; lblSource.Text = string.Empty; lblSource.SetToolTip(string.Empty); } _blnLoading = false; UpdateDrugInfo(); }
private void cmdSaveAsPdf_Click(object sender, EventArgs e) { // Check to see if we have any "Print to PDF" printers, as they will be a lot more reliable than wkhtmltopdf string strPdfPrinter = string.Empty; foreach (string strPrinter in PrinterSettings.InstalledPrinters) { if (strPrinter == "Microsoft Print to PDF" || strPrinter == "Foxit Reader PDF Printer" || strPrinter == "Adobe PDF") { strPdfPrinter = strPrinter; break; } } if (!string.IsNullOrEmpty(strPdfPrinter)) { DialogResult ePdfPrinterDialogResult = Program.MainForm.ShowMessageBox(this, string.Format(GlobalOptions.CultureInfo, LanguageManager.GetString("Message_Viewer_FoundPDFPrinter"), strPdfPrinter), LanguageManager.GetString("MessageTitle_Viewer_FoundPDFPrinter"), MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information); if (ePdfPrinterDialogResult == DialogResult.Cancel) { return; } if (ePdfPrinterDialogResult == DialogResult.Yes) { if (DoPdfPrinterShortcut(strPdfPrinter)) { return; } Program.MainForm.ShowMessageBox(this, LanguageManager.GetString("Message_Viewer_PDFPrinterError")); } } // Save the generated output as PDF. SaveFileDialog1.Filter = LanguageManager.GetString("DialogFilter_Pdf") + '|' + LanguageManager.GetString("DialogFilter_All"); SaveFileDialog1.Title = LanguageManager.GetString("Button_Viewer_SaveAsPdf"); SaveFileDialog1.ShowDialog(); string strSaveFile = SaveFileDialog1.FileName; if (string.IsNullOrEmpty(strSaveFile)) { return; } if (!strSaveFile.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase)) { strSaveFile += ".pdf"; } if (!Directory.Exists(Path.GetDirectoryName(strSaveFile)) || !Utils.CanWriteToPath(strSaveFile)) { Program.MainForm.ShowMessageBox(this, LanguageManager.GetString("Message_File_Cannot_Be_Accessed")); return; } if (File.Exists(strSaveFile)) { try { File.Delete(strSaveFile); } catch (IOException) { Program.MainForm.ShowMessageBox(this, LanguageManager.GetString("Message_File_Cannot_Be_Accessed")); return; } catch (UnauthorizedAccessException) { Program.MainForm.ShowMessageBox(this, LanguageManager.GetString("Message_File_Cannot_Be_Accessed")); return; } } // No PDF printer found, let's use wkhtmltopdf PdfDocument objPdfDocument = new PdfDocument { Html = webViewer.DocumentText }; objPdfDocument.ExtraParams.Add("encoding", "UTF-8"); objPdfDocument.ExtraParams.Add("dpi", "300"); objPdfDocument.ExtraParams.Add("margin-top", "13"); objPdfDocument.ExtraParams.Add("margin-bottom", "19"); objPdfDocument.ExtraParams.Add("margin-left", "13"); objPdfDocument.ExtraParams.Add("margin-right", "13"); objPdfDocument.ExtraParams.Add("image-quality", "100"); objPdfDocument.ExtraParams.Add("print-media-type", string.Empty); try { PdfConvert.ConvertHtmlToPdf(objPdfDocument, new PdfConvertEnvironment { WkHtmlToPdfPath = Path.Combine(Utils.GetStartupPath, "wkhtmltopdf.exe"), Timeout = 60000, TempFolderPath = Path.GetTempPath() }, new PdfOutput { OutputFilePath = strSaveFile }); if (!string.IsNullOrWhiteSpace(GlobalOptions.PDFAppPath)) { Uri uriPath = new Uri(strSaveFile); string strParams = GlobalOptions.PDFParameters .Replace("{page}", "1") .Replace("{localpath}", uriPath.LocalPath) .Replace("{absolutepath}", uriPath.AbsolutePath); ProcessStartInfo objPdfProgramProcess = new ProcessStartInfo { FileName = GlobalOptions.PDFAppPath, Arguments = strParams, WindowStyle = ProcessWindowStyle.Hidden }; Process.Start(objPdfProgramProcess); } } catch (Exception ex) { Program.MainForm.ShowMessageBox(this, ex.ToString()); } }
private void cmdOK_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtLifestyleName.Text)) { MessageBox.Show(LanguageManager.GetString("Message_SelectAdvancedLifestyle_LifestyleName", GlobalOptions.Language), LanguageManager.GetString("MessageTitle_SelectAdvancedLifestyle_LifestyleName", GlobalOptions.Language), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } _blnAddAgain = false; AcceptForm(); }
private void frmSelectAdvancedLifestyle_Load(object sender, EventArgs e) { _blnSkipRefresh = true; foreach (Label objLabel in Controls.OfType <Label>()) { if (objLabel.Text.StartsWith('[')) { objLabel.Text = string.Empty; } } foreach (TreeNode objNode in treLifestyleQualities.Nodes) { if (objNode.Tag != null) { objNode.Text = LanguageManager.GetString(objNode.Tag.ToString(), GlobalOptions.Language); } } // Populate the Advanced Lifestyle ComboBoxes. // Lifestyles. List <ListItem> lstLifestyles = new List <ListItem>(); foreach (XmlNode objXmlLifestyle in _objXmlDocument.SelectNodes("/chummer/lifestyles/lifestyle[" + _objCharacter.Options.BookXPath() + "]")) { string strLifestyleName = objXmlLifestyle["name"]?.InnerText; if (!string.IsNullOrEmpty(strLifestyleName) && strLifestyleName != "ID ERROR. Re-add life style to fix" && (_objType == LifestyleType.Advanced || objXmlLifestyle["slp"]?.InnerText == "remove") && !strLifestyleName.Contains("Hospitalized") && _objCharacter.Options.Books.Contains(objXmlLifestyle["source"]?.InnerText)) { lstLifestyles.Add(new ListItem(strLifestyleName, objXmlLifestyle["translate"]?.InnerText ?? strLifestyleName)); } } //Populate the Qualities list. if (_objSourceLifestyle != null) { foreach (LifestyleQuality objQuality in _objSourceLifestyle.LifestyleQualities) { TreeNode objNode = new TreeNode { Name = objQuality.Name, Text = objQuality.FormattedDisplayName(GlobalOptions.CultureInfo, GlobalOptions.Language), Tag = objQuality.InternalId, ToolTipText = objQuality.Notes }; if (objQuality.OriginSource == QualitySource.BuiltIn) { objNode.ForeColor = SystemColors.GrayText; } if (objQuality.Type == QualityType.Positive) { treLifestyleQualities.Nodes[0].Nodes.Add(objNode); treLifestyleQualities.Nodes[0].Expand(); } else if (objQuality.Type == QualityType.Negative) { treLifestyleQualities.Nodes[1].Nodes.Add(objNode); treLifestyleQualities.Nodes[1].Expand(); } else { treLifestyleQualities.Nodes[2].Nodes.Add(objNode); treLifestyleQualities.Nodes[2].Expand(); } _objLifestyle.LifestyleQualities.Add(objQuality); } foreach (LifestyleQuality objQuality in _objSourceLifestyle.FreeGrids) { TreeNode objNode = new TreeNode { Name = objQuality.Name, Text = objQuality.FormattedDisplayName(GlobalOptions.CultureInfo, GlobalOptions.Language), Tag = objQuality.InternalId, ToolTipText = objQuality.Notes, ForeColor = SystemColors.GrayText }; treLifestyleQualities.Nodes[3].Nodes.Add(objNode); treLifestyleQualities.Nodes[3].Expand(); _objLifestyle.FreeGrids.Add(objQuality); } } cboBaseLifestyle.BeginUpdate(); cboBaseLifestyle.ValueMember = "Value"; cboBaseLifestyle.DisplayMember = "Name"; cboBaseLifestyle.DataSource = lstLifestyles; cboBaseLifestyle.SelectedValue = _objLifestyle.BaseLifestyle; if (cboBaseLifestyle.SelectedIndex == -1) { cboBaseLifestyle.SelectedIndex = 0; } if (_objSourceLifestyle != null) { txtLifestyleName.Text = _objSourceLifestyle.Name; nudRoommates.Value = _objSourceLifestyle.Roommates; nudPercentage.Value = _objSourceLifestyle.Percentage; nudArea.Value = _objSourceLifestyle.Area; nudComforts.Value = _objSourceLifestyle.Comforts; nudSecurity.Value = _objSourceLifestyle.Security; cboBaseLifestyle.SelectedValue = _objSourceLifestyle.BaseLifestyle; chkTrustFund.Checked = _objSourceLifestyle.TrustFund; } string strBaseLifestyle = cboBaseLifestyle.SelectedValue.ToString(); XmlNode objXmlAspect = _objXmlDocument.SelectSingleNode("/chummer/comforts/comfort[name = \"" + strBaseLifestyle + "\"]"); Label_SelectAdvancedLifestyle_Base_Comforts.Text = LanguageManager.GetString("Label_SelectAdvancedLifestyle_Base_Comforts", GlobalOptions.Language).Replace("{0}", (nudComforts.Value).ToString(GlobalOptions.CultureInfo)).Replace("{1}", objXmlAspect["limit"].InnerText); Label_SelectAdvancedLifestyle_Base_Area.Text = LanguageManager.GetString("Label_SelectAdvancedLifestyle_Base_Area", GlobalOptions.Language).Replace("{0}", (nudArea.Value).ToString(GlobalOptions.CultureInfo)).Replace("{1}", objXmlAspect["limit"].InnerText); Label_SelectAdvancedLifestyle_Base_Securities.Text = LanguageManager.GetString("Label_SelectAdvancedLifestyle_Base_Security", GlobalOptions.Language).Replace("{0}", (nudSecurity.Value).ToString(GlobalOptions.CultureInfo)).Replace("{1}", objXmlAspect["limit"].InnerText); objXmlAspect = _objXmlDocument.SelectSingleNode("/chummer/lifestyles/lifestyle[name = \"" + strBaseLifestyle + "\"]"); if (objXmlAspect?["source"] != null && objXmlAspect["page"] != null) { lblSource.Text = objXmlAspect["source"].InnerText + " " + objXmlAspect["page"].InnerText; } cboBaseLifestyle.EndUpdate(); _blnSkipRefresh = false; CalculateValues(); }
/// <summary> /// Calculate the LP value for the selected items. /// </summary> private void CalculateValues(bool blnIncludePercentage = true) { if (_blnSkipRefresh) { return; } decimal decBaseCost = 0; decimal decCost = 0; decimal decMod = 0; // Get the base cost of the lifestyle string strSelectedId = cboLifestyle.SelectedValue?.ToString(); if (strSelectedId != null) { XmlNode objXmlAspect = _objXmlDocument.SelectSingleNode("/chummer/lifestyles/lifestyle[id = \"" + strSelectedId + "\"]"); if (objXmlAspect != null) { decBaseCost += Convert.ToDecimal(objXmlAspect["cost"]?.InnerText, GlobalOptions.InvariantCultureInfo); string strSource = objXmlAspect["source"]?.InnerText; string strPage = objXmlAspect["altpage"]?.InnerText ?? objXmlAspect["page"]?.InnerText; if (!string.IsNullOrEmpty(strSource) && !string.IsNullOrEmpty(strPage)) { lblSource.Text = CommonFunctions.LanguageBookShort(strSource, GlobalOptions.Language) + ' ' + strPage; tipTooltip.SetToolTip(lblSource, CommonFunctions.LanguageBookLong(strSource, GlobalOptions.Language) + ' ' + LanguageManager.GetString("String_Page", GlobalOptions.Language) + ' ' + strPage); } else { lblSource.Text = LanguageManager.GetString("String_Unknown", GlobalOptions.Language); tipTooltip.SetToolTip(lblSource, LanguageManager.GetString("String_Unknown", GlobalOptions.Language)); } // Add the flat costs from qualities foreach (TreeNode objNode in treQualities.Nodes) { if (objNode.Checked) { string strCost = _objXmlDocument.SelectSingleNode($"/chummer/qualities/quality[id = \"{objNode.Tag}\"]/cost")?.InnerText; if (!string.IsNullOrEmpty(strCost)) { object objProcess = CommonFunctions.EvaluateInvariantXPath(strCost, out bool blnIsSuccess); if (blnIsSuccess) { decCost += Convert.ToDecimal(objProcess, GlobalOptions.InvariantCultureInfo); } } } } decimal decBaseMultiplier = 0; if (blnIncludePercentage) { // Add the modifiers from qualities foreach (TreeNode objNode in treQualities.Nodes) { if (!objNode.Checked) { continue; } objXmlAspect = _objXmlDocument.SelectSingleNode($"/chummer/qualities/quality[id = \"{objNode.Tag}\"]"); if (objXmlAspect == null) { continue; } string strMultiplier = objXmlAspect["multiplier"]?.InnerText; if (!string.IsNullOrEmpty(strMultiplier)) { decMod += Convert.ToDecimal(strMultiplier, GlobalOptions.InvariantCultureInfo) / 100.0m; } strMultiplier = objXmlAspect["multiplierbaseonly"]?.InnerText; if (!string.IsNullOrEmpty(strMultiplier)) { decBaseMultiplier += Convert.ToDecimal(strMultiplier, GlobalOptions.InvariantCultureInfo) / 100.0m; } } // Check for modifiers in the improvements decimal decModifier = Convert.ToDecimal(ImprovementManager.ValueOf(_objCharacter, Improvement.ImprovementType.LifestyleCost), GlobalOptions.InvariantCultureInfo); decMod += decModifier / 100.0m; } decBaseCost += decBaseCost * decBaseMultiplier; } } decimal decNuyen = decBaseCost + decBaseCost * decMod + decCost; lblCost.Text = decNuyen.ToString(_objCharacter.Options.NuyenFormat, GlobalOptions.CultureInfo) + '¥'; if (nudPercentage.Value != 100) { decimal decDiscount = decNuyen; decDiscount = decDiscount * (nudPercentage.Value / 100); lblCost.Text += " (" + decDiscount.ToString(_objCharacter.Options.NuyenFormat, GlobalOptions.CultureInfo) + "¥)"; } }
private void UpdateInfo() { if (_blnLoading) { return; } XmlNode xmlSelectedMount = null; string strSelectedMount = cboSize.SelectedValue?.ToString(); if (string.IsNullOrEmpty(strSelectedMount)) { cmdOK.Enabled = false; } else { xmlSelectedMount = _xmlDoc.SelectSingleNode("/chummer/weaponmounts/weaponmount[id = \"" + strSelectedMount + "\"]"); if (xmlSelectedMount == null) { cmdOK.Enabled = false; } else { string strSelectedControl = cboControl.SelectedValue?.ToString(); if (string.IsNullOrEmpty(strSelectedControl)) { cmdOK.Enabled = false; } else if (_xmlDoc.SelectSingleNode("/chummer/weaponmounts/weaponmount[id = \"" + strSelectedControl + "\"]") == null) { cmdOK.Enabled = false; } else { string strSelectedFlexibility = cboFlexibility.SelectedValue?.ToString(); if (string.IsNullOrEmpty(strSelectedFlexibility)) { cmdOK.Enabled = false; } else if (_xmlDoc.SelectSingleNode("/chummer/weaponmounts/weaponmount[id = \"" + strSelectedFlexibility + "\"]") == null) { cmdOK.Enabled = false; } else { string strSelectedVisibility = cboVisibility.SelectedValue?.ToString(); if (string.IsNullOrEmpty(strSelectedVisibility)) { cmdOK.Enabled = false; } else if (_xmlDoc.SelectSingleNode("/chummer/weaponmounts/weaponmount[id = \"" + strSelectedVisibility + "\"]") == null) { cmdOK.Enabled = false; } else { cmdOK.Enabled = true; } } } } } string[] astrSelectedValues = { cboVisibility.SelectedValue?.ToString(), cboFlexibility.SelectedValue?.ToString(), cboControl.SelectedValue?.ToString() }; cmdDeleteMod.Enabled = false; string strSelectedModId = treMods.SelectedNode?.Tag.ToString(); if (!string.IsNullOrEmpty(strSelectedModId) && strSelectedModId.IsGuid()) { VehicleMod objMod = _lstMods.FirstOrDefault(x => x.InternalId == strSelectedModId); if (objMod != null) { cmdDeleteMod.Enabled = !objMod.IncludedInVehicle; lblSlots.Text = objMod.CalculatedSlots.ToString(GlobalOptions.InvariantCultureInfo); lblAvailability.Text = objMod.DisplayTotalAvail; if (chkFreeItem.Checked) { lblCost.Text = (0.0m).ToString(_objCharacter.Options.NuyenFormat, GlobalOptions.CultureInfo) + '¥'; } else { int intTotalSlots = Convert.ToInt32(xmlSelectedMount?["slots"]?.InnerText, GlobalOptions.InvariantCultureInfo); foreach (string strSelectedId in astrSelectedValues) { if (!string.IsNullOrEmpty(strSelectedId)) { XmlNode xmlLoopNode = _xmlDoc.SelectSingleNode("/chummer/weaponmounts/weaponmount[id = \"" + strSelectedId + "\"]"); if (xmlLoopNode != null) { intTotalSlots += Convert.ToInt32(xmlLoopNode["slots"]?.InnerText, GlobalOptions.InvariantCultureInfo); } } } foreach (VehicleMod objLoopMod in _lstMods) { intTotalSlots += objLoopMod.CalculatedSlots; } lblCost.Text = (objMod.TotalCostInMountCreation(intTotalSlots) * (1 + (nudMarkup.Value / 100.0m))).ToString(_objCharacter.Options.NuyenFormat, GlobalOptions.CultureInfo) + '¥'; } objMod.SetSourceDetail(lblSource); lblCostLabel.Visible = !string.IsNullOrEmpty(lblCost.Text); lblSlotsLabel.Visible = !string.IsNullOrEmpty(lblSlots.Text); lblAvailabilityLabel.Visible = !string.IsNullOrEmpty(lblAvailability.Text); lblSourceLabel.Visible = !string.IsNullOrEmpty(lblSource.Text); return; } } if (xmlSelectedMount == null) { lblCost.Text = string.Empty; lblSlots.Text = string.Empty; lblAvailability.Text = string.Empty; lblCostLabel.Visible = false; lblSlotsLabel.Visible = false; lblAvailabilityLabel.Visible = false; return; } decimal decCost = !chkFreeItem.Checked ? Convert.ToDecimal(xmlSelectedMount["cost"]?.InnerText, GlobalOptions.InvariantCultureInfo) : 0; int intSlots = Convert.ToInt32(xmlSelectedMount["slots"]?.InnerText, GlobalOptions.InvariantCultureInfo); string strAvail = xmlSelectedMount["avail"]?.InnerText ?? string.Empty; char chrAvailSuffix = strAvail.Length > 0 ? strAvail[strAvail.Length - 1] : ' '; if (chrAvailSuffix == 'F' || chrAvailSuffix == 'R') { strAvail = strAvail.Substring(0, strAvail.Length - 1); } else { chrAvailSuffix = ' '; } int intAvail = Convert.ToInt32(strAvail, GlobalOptions.InvariantCultureInfo); foreach (string strSelectedId in astrSelectedValues) { if (!string.IsNullOrEmpty(strSelectedId)) { XmlNode xmlLoopNode = _xmlDoc.SelectSingleNode("/chummer/weaponmounts/weaponmount[id = \"" + strSelectedId + "\"]"); if (xmlLoopNode != null) { if (!chkFreeItem.Checked) { decCost += Convert.ToInt32(xmlLoopNode["cost"]?.InnerText, GlobalOptions.InvariantCultureInfo); } intSlots += Convert.ToInt32(xmlLoopNode["slots"]?.InnerText, GlobalOptions.InvariantCultureInfo); string strLoopAvail = xmlLoopNode["avail"]?.InnerText ?? string.Empty; char chrLoopAvailSuffix = strLoopAvail.Length > 0 ? strLoopAvail[strLoopAvail.Length - 1] : ' '; if (chrLoopAvailSuffix == 'F') { strLoopAvail = strLoopAvail.Substring(0, strLoopAvail.Length - 1); chrAvailSuffix = 'F'; } else if (chrLoopAvailSuffix == 'R') { strLoopAvail = strLoopAvail.Substring(0, strLoopAvail.Length - 1); if (chrAvailSuffix == ' ') { chrAvailSuffix = 'R'; } } intAvail += Convert.ToInt32(strLoopAvail, GlobalOptions.InvariantCultureInfo); } } } foreach (VehicleMod objMod in _lstMods) { intSlots += objMod.CalculatedSlots; AvailabilityValue objLoopAvail = objMod.TotalAvailTuple(); char chrLoopAvailSuffix = objLoopAvail.Suffix; if (chrLoopAvailSuffix == 'F') { chrAvailSuffix = 'F'; } else if (chrAvailSuffix != 'F' && chrLoopAvailSuffix == 'R') { chrAvailSuffix = 'R'; } intAvail += objLoopAvail.Value; } if (!chkFreeItem.Checked) { foreach (VehicleMod objMod in _lstMods) { decCost += objMod.TotalCostInMountCreation(intSlots); } } string strAvailText = intAvail.ToString(GlobalOptions.CultureInfo); if (chrAvailSuffix == 'F') { strAvailText += LanguageManager.GetString("String_AvailForbidden"); } else if (chrAvailSuffix == 'R') { strAvailText += LanguageManager.GetString("String_AvailRestricted"); } decCost *= 1 + (nudMarkup.Value / 100.0m); lblCost.Text = decCost.ToString(_objCharacter.Options.NuyenFormat, GlobalOptions.CultureInfo) + '¥'; lblSlots.Text = intSlots.ToString(GlobalOptions.CultureInfo); lblAvailability.Text = strAvailText; lblCostLabel.Visible = !string.IsNullOrEmpty(lblCost.Text); lblSlotsLabel.Visible = !string.IsNullOrEmpty(lblSlots.Text); lblAvailabilityLabel.Visible = !string.IsNullOrEmpty(lblAvailability.Text); string strSource = xmlSelectedMount["source"]?.InnerText ?? LanguageManager.GetString("String_Unknown"); string strPage = xmlSelectedMount["altpage"]?.InnerText ?? xmlSelectedMount["page"]?.InnerText ?? LanguageManager.GetString("String_Unknown"); SourceString objSourceString = new SourceString(strSource, strPage, GlobalOptions.Language); objSourceString.SetControl(lblSource); lblSourceLabel.Visible = !string.IsNullOrEmpty(lblSource.Text); }