private async void cmdSelectFile_Click(object sender, EventArgs e) { // Prompt the user to select a save file to possess. using (OpenFileDialog openFileDialog = new OpenFileDialog { Filter = await LanguageManager.GetStringAsync("DialogFilter_HeroLab") + '|' + await LanguageManager.GetStringAsync("DialogFilter_All"), Multiselect = false }) { if (openFileDialog.ShowDialog(this) != DialogResult.OK) { return; } using (CursorWait.New(this)) { string strSelectedFile = openFileDialog.FileName; TreeNode objNode = await CacheCharacters(strSelectedFile); if (objNode != null) { treCharacterList.Nodes.Clear(); treCharacterList.Nodes.Add(objNode); treCharacterList.SelectedNode = objNode.Nodes.Count > 0 ? objNode.Nodes[0] : objNode; } } } }
private async void tsAttachCharacter_Click(object sender, EventArgs e) { // Prompt the user to select a save file to associate with this Contact. using (OpenFileDialog openFileDialog = new OpenFileDialog { Filter = await LanguageManager.GetStringAsync("DialogFilter_Chum5") + '|' + await LanguageManager.GetStringAsync("DialogFilter_All") }) { if (!string.IsNullOrEmpty(_objContact.FileName) && File.Exists(_objContact.FileName)) { openFileDialog.InitialDirectory = Path.GetDirectoryName(_objContact.FileName); openFileDialog.FileName = Path.GetFileName(_objContact.FileName); } if (openFileDialog.ShowDialog(this) != DialogResult.OK) { return; } using (CursorWait.New(ParentForm)) { _objContact.FileName = openFileDialog.FileName; cmdLink.ToolTipText = await LanguageManager.GetStringAsync("Tip_Contact_OpenFile"); // Set the relative path. Uri uriApplication = new Uri(Utils.GetStartupPath); Uri uriFile = new Uri(_objContact.FileName); Uri uriRelative = uriApplication.MakeRelativeUri(uriFile); _objContact.RelativeFileName = "../" + uriRelative; ContactDetailChanged?.Invoke(this, new TextEventArgs("File")); } } }
/// <summary> /// Update the internal XML of the Viewer window. /// </summary> private async Task RefreshCharacterXml() { using (CursorWait.New(this, true)) { await Task.WhenAll(this.DoThreadSafeAsync(() => { tsPrintPreview.Enabled = false; tsSaveAsHtml.Enabled = false; }), cmdPrint.DoThreadSafeAsync(x => x.Enabled = false), cmdSaveAsPdf.DoThreadSafeAsync(x => x.Enabled = false)); Character[] aobjCharacters = await _lstCharacters.ToArrayAsync(); _objCharacterXml = aobjCharacters.Length > 0 ? await CommonFunctions.GenerateCharactersExportXml(_objPrintCulture, _strPrintLanguage, _objRefresherCancellationTokenSource.Token, aobjCharacters) : null; await this.DoThreadSafeAsync(() => tsSaveAsXml.Enabled = _objCharacterXml != null); if (_objRefresherCancellationTokenSource.IsCancellationRequested) { return; } await RefreshSheet(); } }
private async void OnSelectedSettingChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(CharacterSettings.Books) || e.PropertyName == nameof(CharacterSettings.EnabledCustomDataDirectoryPaths)) { using (CursorWait.New(this)) await LoadContent(); } }
private async void MasterIndex_Load(object sender, EventArgs e) { using (CursorWait.New(this)) { await PopulateCharacterSettings(); await LoadContent().AsTask().ContinueWith(x => IsFinishedLoading = true); _objSelectedSetting.PropertyChanged += OnSelectedSettingChanged; } }
private async void cmdEditCharacterSetting_Click(object sender, EventArgs e) { using (CursorWait.New(this)) { using (EditCharacterSettings frmOptions = new EditCharacterSettings(cboCharacterSetting.SelectedValue as CharacterSettings)) await frmOptions.ShowDialogSafeAsync(this); // Do not repopulate the character settings list because that will happen from frmCharacterSettings where appropriate } }
private async ValueTask RefreshSelectLifestyle() { _blnIsSelectLifestyleRefreshing = true; using (CursorWait.New(this)) { try { Lifestyle objPreferredLifestyle = null; ListItem objPreferredLifestyleItem = default; Lifestyle objCurrentlySelectedLifestyle = cboSelectLifestyle.SelectedIndex >= 0 ? ((ListItem)cboSelectLifestyle.SelectedItem).Value as Lifestyle : null; using (new FetchSafelyFromPool <List <ListItem> >(Utils.ListItemListPool, out List <ListItem> lstLifestyleItems)) { foreach (Lifestyle objLifestyle in _objCharacter.Lifestyles) { ListItem objLifestyleItem = new ListItem(objLifestyle, objLifestyle.CurrentDisplayName); lstLifestyleItems.Add(new ListItem(objLifestyle, objLifestyle.CurrentDisplayName)); // We already selected a lifestyle, so keep the selection if possible despite the refresh if (objCurrentlySelectedLifestyle != null) { if (objCurrentlySelectedLifestyle == objLifestyle) { objPreferredLifestyleItem = objLifestyleItem; } } else if (objPreferredLifestyle == null || objLifestyle.ExpectedValue > objPreferredLifestyle.ExpectedValue) { objPreferredLifestyleItem = objLifestyleItem; objPreferredLifestyle = objLifestyle; } } lstLifestyleItems.Sort(CompareListItems.CompareNames); await cboSelectLifestyle.PopulateWithListItemsAsync(lstLifestyleItems); cboSelectLifestyle.SelectedItem = objPreferredLifestyleItem; if (cboSelectLifestyle.SelectedIndex < 0 && lstLifestyleItems.Count > 0) { cboSelectLifestyle.SelectedIndex = 0; } cboSelectLifestyle.Enabled = lstLifestyleItems.Count > 1; } } finally { _blnIsSelectLifestyleRefreshing = false; } await RefreshBaseLifestyle(); } }
private async void tsContactOpen_Click(object sender, EventArgs e) { if (_objContact.LinkedCharacter != null) { Character objOpenCharacter = await Program.OpenCharacters.ContainsAsync(_objContact.LinkedCharacter) ? _objContact.LinkedCharacter : null; using (CursorWait.New(ParentForm)) { if (objOpenCharacter == null) { objOpenCharacter = await Program.LoadCharacterAsync(_objContact.LinkedCharacter.FileName); } if (!Program.SwitchToOpenCharacter(objOpenCharacter)) { await Program.OpenCharacter(objOpenCharacter); } } } else { bool blnUseRelative = false; // Make sure the file still exists before attempting to load it. if (!File.Exists(_objContact.FileName)) { bool blnError = false; // If the file doesn't exist, use the relative path if one is available. if (string.IsNullOrEmpty(_objContact.RelativeFileName)) { blnError = true; } else if (!File.Exists(Path.GetFullPath(_objContact.RelativeFileName))) { blnError = true; } else { blnUseRelative = true; } if (blnError) { Program.ShowMessageBox(string.Format(GlobalSettings.CultureInfo, await LanguageManager.GetStringAsync("Message_FileNotFound"), _objContact.FileName), await LanguageManager.GetStringAsync("MessageTitle_FileNotFound"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } string strFile = blnUseRelative ? Path.GetFullPath(_objContact.RelativeFileName) : _objContact.FileName; System.Diagnostics.Process.Start(strFile); } }
private async void cmdRoll_Click(object sender, EventArgs e) { using (CursorWait.New(this)) { int intResult = 0; for (int i = 0; i < Dice; ++i) { intResult += await GlobalSettings.RandomGenerator.NextD6ModuloBiasRemovedAsync(); } nudDiceResult.ValueAsInt = intResult; } }
private ValueTask RefreshCalculation() { using (CursorWait.New(this)) { nudDiceResult.SuspendLayout(); nudDiceResult.MinimumAsInt = int.MinValue; // Temporarily set this to avoid crashing if we shift from something with more than 6 dice to something with less. nudDiceResult.MaximumAsInt = SelectedLifestyle?.Dice * 6 ?? 0; nudDiceResult.MinimumAsInt = SelectedLifestyle?.Dice ?? 0; nudDiceResult.ResumeLayout(); return(RefreshResultLabel()); } }
private async void cmdEditCharacterOption_Click(object sender, EventArgs e) { using (CursorWait.New(this)) { using (EditCharacterSettings frmOptions = new EditCharacterSettings(cboCharacterSetting.SelectedValue as CharacterSettings)) await frmOptions.ShowDialogSafeAsync(this); SuspendLayout(); try { // Populate the Gameplay Settings list. object objOldSelected = cboCharacterSetting.SelectedValue; using (new FetchSafelyFromPool <List <ListItem> >( Utils.ListItemListPool, out List <ListItem> lstGameplayOptions)) { lstGameplayOptions.AddRange(SettingsManager.LoadedCharacterSettings.Values .Select(objLoopOptions => new ListItem( objLoopOptions, objLoopOptions.DisplayName))); lstGameplayOptions.Sort(CompareListItems.CompareNames); await cboCharacterSetting.PopulateWithListItemsAsync(lstGameplayOptions); cboCharacterSetting.SelectedValue = objOldSelected; if (cboCharacterSetting.SelectedIndex == -1 && lstGameplayOptions.Count > 0) { (bool blnSuccess, CharacterSettings objSetting) = await SettingsManager.LoadedCharacterSettings.TryGetValueAsync( GlobalSettings.DefaultCharacterSetting); if (blnSuccess) { cboCharacterSetting.SelectedValue = objSetting; } } if (cboCharacterSetting.SelectedIndex == -1 && lstGameplayOptions.Count > 0) { cboCharacterSetting.SelectedIndex = 0; } } } finally { ResumeLayout(); } } }
private async void cboGamePlay_SelectedIndexChanged(object sender, EventArgs e) { using (CursorWait.New(this)) { SuspendLayout(); try { await ProcessGameplayIndexChanged(); } finally { ResumeLayout(); } } }
private async ValueTask RefreshResultLabel() { using (CursorWait.New(this)) { string strSpace = await LanguageManager.GetStringAsync("String_Space"); lblResult.Text = strSpace + '+' + strSpace + Extra.ToString("#,0", GlobalSettings.CultureInfo) + ')' + strSpace + '×' + strSpace + (SelectedLifestyle?.Multiplier ?? 0).ToString( _objCharacter.Settings.NuyenFormat + '¥', GlobalSettings.CultureInfo) + strSpace + '=' + strSpace + StartingNuyen.ToString(_objCharacter.Settings.NuyenFormat + '¥', GlobalSettings.CultureInfo); } }
public async ValueTask ForceRepopulateCharacterSettings() { using (CursorWait.New(this)) { SuspendLayout(); try { await PopulateCharacterSettings(); } finally { ResumeLayout(); } } }
private async void cboCharacterSetting_SelectedIndexChanged(object sender, EventArgs e) { if (_blnSkipRefresh) { return; } using (CursorWait.New(this)) { string strSelectedSetting = (await cboCharacterSetting.DoThreadSafeFuncAsync(x => x.SelectedValue) as CharacterSettings)?.DictionaryKey; CharacterSettings objSettings = null; bool blnSuccess = false; if (!string.IsNullOrEmpty(strSelectedSetting)) { (blnSuccess, objSettings) = await SettingsManager.LoadedCharacterSettings.TryGetValueAsync(strSelectedSetting); } if (!blnSuccess) { (blnSuccess, objSettings) = await SettingsManager.LoadedCharacterSettings.TryGetValueAsync( GlobalSettings.DefaultMasterIndexSetting); if (!blnSuccess) { (blnSuccess, objSettings) = await SettingsManager.LoadedCharacterSettings.TryGetValueAsync( GlobalSettings.DefaultMasterIndexSettingDefaultValue); if (!blnSuccess) { objSettings = SettingsManager.LoadedCharacterSettings.Values.First(); } } } if (objSettings != _objSelectedSetting) { _objSelectedSetting.PropertyChanged -= OnSelectedSettingChanged; _objSelectedSetting = objSettings; _objSelectedSetting.PropertyChanged += OnSelectedSettingChanged; await LoadContent(); } } }
private async void cmdOK_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(_strXslt)) { return; } using (CursorWait.New(this)) { if (_strXslt == "JSON") { await ExportJson(); } else { await ExportNormal(); } } }
private async Task GenerateJson() { using (CursorWait.New(this)) { await cmdOK.DoThreadSafeAsync(x => x.Enabled = false); try { string strText = JsonConvert.SerializeXmlNode(_objCharacterXml, Formatting.Indented); if (_objXmlGeneratorCancellationTokenSource.IsCancellationRequested) { return; } SetTextToWorkerResult(strText); } finally { await cmdOK.DoThreadSafeAsync(x => x.Enabled = true); } } }
private async ValueTask RefreshBaseLifestyle() { if (_blnIsSelectLifestyleRefreshing) { return; } if (cboSelectLifestyle.SelectedIndex < 0) { return; } using (CursorWait.New(this)) { _objLifestyle = ((ListItem)cboSelectLifestyle.SelectedItem).Value as Lifestyle; lblDice.Text = string.Format(GlobalSettings.CultureInfo, await LanguageManager.GetStringAsync("Label_LifestyleNuyen_ResultOf"), SelectedLifestyle?.Dice ?? 0); await RefreshCalculation(); cmdRoll.Enabled = SelectedLifestyle?.Dice > 0; } }
private async Task GenerateCharacterXml() { using (CursorWait.New(this)) { await Task.WhenAll(cmdOK.DoThreadSafeAsync(x => x.Enabled = false), txtText.DoThreadSafeAsync( async x => x.Text = await LanguageManager.GetStringAsync("String_Generating_Data"))); _objCharacterXml = await _objCharacter.GenerateExportXml(_objExportCulture, _strExportLanguage, _objCharacterXmlGeneratorCancellationTokenSource .Token); if (_objCharacterXmlGeneratorCancellationTokenSource.IsCancellationRequested) { return; } if (_objCharacterXml != null) { await DoXsltUpdate(); } } }
/// <summary> /// Loads the character /// </summary> /// <param name="fileName"></param> private async ValueTask LoadCharacter(string fileName) { if (File.Exists(fileName) && fileName.EndsWith(".chum5", StringComparison.OrdinalIgnoreCase)) { Character objCharacter = new Character { FileName = fileName }; using (CursorWait.New(this)) { if (!await objCharacter.LoadAsync()) { // TODO edward setup error page await objCharacter.DisposeAsync(); return; // we obviously cannot init } nudInit.Value = objCharacter.InitiativeDice; txtName.Text = objCharacter.Name; if (int.TryParse( objCharacter.Initiative.SplitNoAlloc(' ', StringSplitOptions.RemoveEmptyEntries) .FirstOrDefault(), out int intTemp)) { nudInitStart.Value = intTemp; } if (_character != null) { await _character.DisposeAsync(); _blnCharacterAdded = false; } _character = objCharacter; } } }
private async void RefreshList(object sender, EventArgs e) { if (_blnSkipRefresh) { return; } using (CursorWait.New(this)) { bool blnCustomList = !(txtSearch.TextLength == 0 && string.IsNullOrEmpty(cboFile.SelectedValue?.ToString())); List <ListItem> lstFilteredItems = blnCustomList ? Utils.ListItemListPool.Get() : _lstItems; try { if (blnCustomList) { string strFileFilter = cboFile.SelectedValue?.ToString() ?? string.Empty; string strSearchFilter = txtSearch.Text; foreach (ListItem objItem in _lstItems) { if (!(objItem.Value is MasterIndexEntry objItemEntry)) { continue; } if (!string.IsNullOrEmpty(strFileFilter) && !objItemEntry.FileNames.Contains(strFileFilter)) { continue; } if (!string.IsNullOrEmpty(strSearchFilter)) { string strDisplayNameNoFile = objItemEntry.DisplayName; if (strDisplayNameNoFile.EndsWith(".xml]", StringComparison.OrdinalIgnoreCase)) { strDisplayNameNoFile = strDisplayNameNoFile .Substring(0, strDisplayNameNoFile.LastIndexOf('[')).Trim(); } if (strDisplayNameNoFile.IndexOf(strSearchFilter, StringComparison.OrdinalIgnoreCase) == -1) { continue; } } lstFilteredItems.Add(objItem); } } object objOldSelectedValue = lstItems.SelectedValue; _blnSkipRefresh = true; await lstItems.PopulateWithListItemsAsync(lstFilteredItems); _blnSkipRefresh = false; if (objOldSelectedValue is MasterIndexEntry objOldSelectedEntry) { lstItems.SelectedIndex = lstFilteredItems.FindIndex(x => objOldSelectedEntry.Equals(x.Value as MasterIndexEntry)); } else { lstItems.SelectedIndex = -1; } } finally { if (blnCustomList) { Utils.ListItemListPool.Return(lstFilteredItems); } } } }
private async void cmdSaveAsPdf_Click(object sender, EventArgs e) { using (CursorWait.New(this)) { // 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.ShowMessageBox(this, string.Format(GlobalSettings.CultureInfo, await LanguageManager.GetStringAsync("Message_Viewer_FoundPDFPrinter"), strPdfPrinter), await LanguageManager.GetStringAsync("MessageTitle_Viewer_FoundPDFPrinter"), MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information); switch (ePdfPrinterDialogResult) { case DialogResult.Cancel: case DialogResult.Yes when DoPdfPrinterShortcut(strPdfPrinter): return; case DialogResult.Yes: Program.ShowMessageBox(this, await LanguageManager.GetStringAsync( "Message_Viewer_PDFPrinterError")); break; } } // Save the generated output as PDF. SaveFileDialog1.Filter = await LanguageManager.GetStringAsync("DialogFilter_Pdf") + '|' + await LanguageManager.GetStringAsync("DialogFilter_All"); SaveFileDialog1.Title = await LanguageManager.GetStringAsync("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.ShowMessageBox(this, string.Format(GlobalSettings.CultureInfo, await LanguageManager.GetStringAsync( "Message_File_Cannot_Be_Accessed"), strSaveFile)); return; } if (!await Utils.SafeDeleteFileAsync(strSaveFile, true)) { Program.ShowMessageBox(this, string.Format(GlobalSettings.CultureInfo, await LanguageManager.GetStringAsync( "Message_File_Cannot_Be_Accessed"), strSaveFile)); return; } // No PDF printer found, let's use wkhtmltopdf try { PdfDocument objPdfDocument = new PdfDocument { Html = webViewer.DocumentText, ExtraParams = new Dictionary <string, string>(8) { { "encoding", "UTF-8" }, { "dpi", "300" }, { "margin-top", "13" }, { "margin-bottom", "19" }, { "margin-left", "13" }, { "margin-right", "13" }, { "image-quality", "100" }, { "print-media-type", string.Empty } } }; PdfConvertEnvironment objPdfConvertEnvironment = new PdfConvertEnvironment { WkHtmlToPdfPath = Path.Combine(Utils.GetStartupPath, "wkhtmltopdf.exe") }; PdfOutput objPdfOutput = new PdfOutput { OutputFilePath = strSaveFile }; await PdfConvert.ConvertHtmlToPdfAsync(objPdfDocument, objPdfConvertEnvironment, objPdfOutput); if (!string.IsNullOrWhiteSpace(GlobalSettings.PdfAppPath)) { Uri uriPath = new Uri(strSaveFile); string strParams = GlobalSettings.PdfParameters .Replace("{page}", "1") .Replace("{localpath}", uriPath.LocalPath) .Replace("{absolutepath}", uriPath.AbsolutePath); ProcessStartInfo objPdfProgramProcess = new ProcessStartInfo { FileName = GlobalSettings.PdfAppPath, Arguments = strParams, WindowStyle = ProcessWindowStyle.Hidden }; objPdfProgramProcess.Start(); } } catch (Exception ex) { Program.ShowMessageBox(this, ex.ToString()); } } }
private async Task DoImport() { TreeNode objSelectedNode = treCharacterList.SelectedNode; if (objSelectedNode == null || objSelectedNode.Level <= 0) { return; } int intIndex = Convert.ToInt32(objSelectedNode.Tag, GlobalSettings.InvariantCultureInfo); if (intIndex < 0 || intIndex >= _lstCharacterCache.Count) { return; } HeroLabCharacterCache objCache = _lstCharacterCache[intIndex]; if (objCache == null) { return; } string strFile = objCache.FilePath; string strCharacterId = objCache.CharacterId; if (string.IsNullOrEmpty(strFile) || string.IsNullOrEmpty(strCharacterId)) { return; } using (CursorWait.New(this)) { bool blnLoaded = false; Character objCharacter = new Character(); try { Program.OpenCharacters.Add(objCharacter); CharacterSettings objHeroLabSettings = SettingsManager.LoadedCharacterSettings.Values.FirstOrDefault( x => x.Name == objCache.SettingsName && x.BuildMethod == objCache.BuildMethod); if (objHeroLabSettings != null) { objCharacter.SettingsKey = objHeroLabSettings.DictionaryKey; } else { objHeroLabSettings = SettingsManager.LoadedCharacterSettings.Values.FirstOrDefault( x => x.Name.Contains(objCache.SettingsName) && x.BuildMethod == objCache.BuildMethod); if (objHeroLabSettings != null) { objCharacter.SettingsKey = objHeroLabSettings.DictionaryKey; } else { (bool blnSuccess, CharacterSettings objDefaultCharacterSettings) = await SettingsManager.LoadedCharacterSettings.TryGetValueAsync( GlobalSettings.DefaultCharacterSetting); if (blnSuccess && objCache.BuildMethod.UsesPriorityTables() == objDefaultCharacterSettings.BuildMethod.UsesPriorityTables()) { objCharacter.SettingsKey = objDefaultCharacterSettings.DictionaryKey; } else { objCharacter.SettingsKey = SettingsManager.LoadedCharacterSettings.Values .FirstOrDefault( x => x.BuiltInOption && x.BuildMethod == objCache.BuildMethod) ?.DictionaryKey ?? SettingsManager.LoadedCharacterSettings.Values .FirstOrDefault( x => x.BuiltInOption && x.BuildMethod.UsesPriorityTables() == objCache.BuildMethod .UsesPriorityTables()) ?.DictionaryKey ?? GlobalSettings.DefaultCharacterSetting; } } } DialogResult ePickBPResult = await this.DoThreadSafeFunc(ShowBPAsync); async ValueTask <DialogResult> ShowBPAsync() { using (SelectBuildMethod frmPickBP = new SelectBuildMethod(objCharacter, true)) { await frmPickBP.ShowDialogSafeAsync(this); return(frmPickBP.DialogResult); } } if (ePickBPResult != DialogResult.OK) { return; } //Timekeeper.Start("load_file"); if (!await objCharacter.LoadFromHeroLabFileAsync(strFile, strCharacterId, objCharacter.SettingsKey)) { return; } blnLoaded = true; //Timekeeper.Finish("load_file"); await Program.OpenCharacter(objCharacter); } finally { cmdImport.Enabled = true; cmdSelectFile.Enabled = true; if (!blnLoaded) { Program.OpenCharacters.Remove(objCharacter); } } } Close(); }
private async ValueTask DoXsltUpdate() { if (!_blnLoading) { if (_objCharacterXml != null) { _strXslt = cboXSLT.SelectedValue?.ToString(); if (!string.IsNullOrEmpty(_strXslt)) { using (CursorWait.New(this)) { await txtText.DoThreadSafeAsync( async x => x.Text = await LanguageManager.GetStringAsync("String_Generating_Data")); (bool blnSuccess, Tuple <string, string> strBoxText) = await _dicCache.TryGetValueAsync( new Tuple <string, string>(_strExportLanguage, _strXslt)); if (blnSuccess) { await txtText.DoThreadSafeAsync(x => x.Text = strBoxText.Item2); } else { if (_objXmlGeneratorCancellationTokenSource != null) { _objXmlGeneratorCancellationTokenSource.Cancel(false); _objXmlGeneratorCancellationTokenSource.Dispose(); } _objXmlGeneratorCancellationTokenSource = new CancellationTokenSource(); try { if (_tskXmlGenerator?.IsCompleted == false) { await _tskXmlGenerator; } } catch (TaskCanceledException) { // Swallow this } _tskXmlGenerator = _strXslt == "JSON" ? Task.Run(GenerateJson, _objXmlGeneratorCancellationTokenSource.Token) : Task.Run(GenerateXml, _objXmlGeneratorCancellationTokenSource.Token); } } } } else { if (_objCharacterXmlGeneratorCancellationTokenSource != null) { _objCharacterXmlGeneratorCancellationTokenSource.Cancel(false); _objCharacterXmlGeneratorCancellationTokenSource.Dispose(); } _objCharacterXmlGeneratorCancellationTokenSource = new CancellationTokenSource(); try { if (_tskCharacterXmlGenerator?.IsCompleted == false) { await _tskCharacterXmlGenerator; } } catch (TaskCanceledException) { // Swallow this } _tskCharacterXmlGenerator = Task.Run(GenerateCharacterXml, _objCharacterXmlGeneratorCancellationTokenSource.Token); } } }
private async Task DoPrint() { using (CursorWait.New(this, true)) { try { await Task.WhenAll(cmdPrint.DoThreadSafeAsync(x => x.Enabled = false), prgProgress.DoThreadSafeAsync(objBar => { objBar.Value = 0; objBar.Maximum = treCharacters.Nodes.Count; })); // Parallelized load because this is one major bottleneck. Character[] lstCharacters = new Character[treCharacters.Nodes.Count]; Task <Character>[] tskLoadingTasks = new Task <Character> [treCharacters.Nodes.Count]; for (int i = 0; i < tskLoadingTasks.Length; ++i) { string strLoopFile = treCharacters.Nodes[i].Tag.ToString(); tskLoadingTasks[i] = Task.Run(() => InnerLoad(strLoopFile), _objPrinterCancellationTokenSource.Token); } async Task <Character> InnerLoad(string strLoopFile) { if (_objPrinterCancellationTokenSource.IsCancellationRequested) { _objPrinterCancellationTokenSource?.Cancel(false); return(null); } Character objReturn = await Program.LoadCharacterAsync(strLoopFile, string.Empty, false, false, false); bool blnLoadSuccessful = objReturn != null; if (_objPrinterCancellationTokenSource.IsCancellationRequested) { _objPrinterCancellationTokenSource?.Cancel(false); return(null); } if (blnLoadSuccessful) { await prgProgress.DoThreadSafeAsync(() => ++ prgProgress.Value); } return(objReturn); } await Task.WhenAll(tskLoadingTasks); if (_objPrinterCancellationTokenSource.IsCancellationRequested) { return; } try { for (int i = 0; i < lstCharacters.Length; ++i) { lstCharacters[i] = await tskLoadingTasks[i]; } } catch (TaskCanceledException) { return; // We cancelled the task, so just exit } if (_objPrinterCancellationTokenSource.IsCancellationRequested) { return; } await CleanUpOldCharacters(); if (_objPrinterCancellationTokenSource.IsCancellationRequested) { return; } _aobjCharacters = lstCharacters; if (_frmPrintView == null) { await this.DoThreadSafeAsync(async() => { _frmPrintView = new CharacterSheetViewer(); await _frmPrintView.SetSelectedSheet("Game Master Summary"); await _frmPrintView.SetCharacters(_aobjCharacters); _frmPrintView.Show(); }); } else { await _frmPrintView.DoThreadSafeAsync(async objSheetViewer => { await objSheetViewer.SetCharacters(_aobjCharacters); objSheetViewer.Activate(); }); } } finally { await Task.WhenAll(cmdPrint.DoThreadSafeAsync(x => x.Enabled = true), prgProgress.DoThreadSafeAsync(x => x.Value = 0)); } } }
private async Task GenerateXml() { using (CursorWait.New(this)) { await cmdOK.DoThreadSafeAsync(x => x.Enabled = false); try { string exportSheetPath = Path.Combine(Utils.GetStartupPath, "export", _strXslt + ".xsl"); XslCompiledTransform objXslTransform; try { objXslTransform = await XslManager .GetTransformForFileAsync(exportSheetPath); // Use the path for the export sheet. } catch (ArgumentException) { string strReturn = "Last write time could not be fetched when attempting to load " + _strXslt + Environment.NewLine; Log.Debug(strReturn); SetTextToWorkerResult(strReturn); return; } catch (PathTooLongException) { string strReturn = "Last write time could not be fetched when attempting to load " + _strXslt + Environment.NewLine; Log.Debug(strReturn); SetTextToWorkerResult(strReturn); return; } catch (UnauthorizedAccessException) { string strReturn = "Last write time could not be fetched when attempting to load " + _strXslt + Environment.NewLine; Log.Debug(strReturn); SetTextToWorkerResult(strReturn); return; } catch (XsltException ex) { string strReturn = "Error attempting to load " + _strXslt + Environment.NewLine; Log.Debug(strReturn); Log.Error("ERROR Message = " + ex.Message); strReturn += ex.Message; SetTextToWorkerResult(strReturn); return; } if (_objXmlGeneratorCancellationTokenSource.IsCancellationRequested) { return; } XmlWriterSettings objSettings = objXslTransform.OutputSettings.Clone(); objSettings.CheckCharacters = false; objSettings.ConformanceLevel = ConformanceLevel.Fragment; string strText; using (MemoryStream objStream = new MemoryStream()) { using (XmlWriter objWriter = XmlWriter.Create(objStream, objSettings)) objXslTransform.Transform(_objCharacterXml, null, objWriter); if (_objXmlGeneratorCancellationTokenSource.IsCancellationRequested) { return; } objStream.Position = 0; // Read in the resulting code and pass it to the browser. using (StreamReader objReader = new StreamReader(objStream, Encoding.UTF8, true)) strText = await objReader.ReadToEndAsync(); } SetTextToWorkerResult(strText); } finally { await cmdOK.DoThreadSafeAsync(x => x.Enabled = true); } } }
/// <summary> /// Run the generated XML file through the XSL transformation engine to create the file output. /// </summary> private async Task AsyncGenerateOutput() { using (CursorWait.New(this)) { await Task.WhenAll(this.DoThreadSafeAsync(() => { tsPrintPreview.Enabled = false; tsSaveAsHtml.Enabled = false; }), cmdPrint.DoThreadSafeAsync(x => x.Enabled = false), cmdSaveAsPdf.DoThreadSafeAsync(x => x.Enabled = false)); await SetDocumentText(await LanguageManager.GetStringAsync("String_Generating_Sheet")); string strXslPath = Path.Combine(Utils.GetStartupPath, "sheets", _strSelectedSheet + ".xsl"); if (!File.Exists(strXslPath)) { string strReturn = "File not found when attempting to load " + _strSelectedSheet + Environment.NewLine; Log.Debug(strReturn); Program.ShowMessageBox(this, strReturn); return; } XslCompiledTransform objXslTransform; try { objXslTransform = await XslManager.GetTransformForFileAsync(strXslPath); } catch (ArgumentException) { string strReturn = "Last write time could not be fetched when attempting to load " + _strSelectedSheet + Environment.NewLine; Log.Debug(strReturn); Program.ShowMessageBox(this, strReturn); return; } catch (PathTooLongException) { string strReturn = "Last write time could not be fetched when attempting to load " + _strSelectedSheet + Environment.NewLine; Log.Debug(strReturn); Program.ShowMessageBox(this, strReturn); return; } catch (UnauthorizedAccessException) { string strReturn = "Last write time could not be fetched when attempting to load " + _strSelectedSheet + Environment.NewLine; Log.Debug(strReturn); Program.ShowMessageBox(this, strReturn); return; } catch (XsltException ex) { string strReturn = "Error attempting to load " + _strSelectedSheet + Environment.NewLine; Log.Debug(strReturn); Log.Error("ERROR Message = " + ex.Message); strReturn += ex.Message; Program.ShowMessageBox(this, strReturn); return; } if (_objOutputGeneratorCancellationTokenSource.IsCancellationRequested) { return; } using (MemoryStream objStream = new MemoryStream()) { using (XmlWriter objWriter = Utils.GetXslTransformXmlWriter(objStream)) { await Task.Run(() => objXslTransform.Transform(_objCharacterXml, objWriter)); if (_objOutputGeneratorCancellationTokenSource.IsCancellationRequested) { return; } } objStream.Position = 0; // This reads from a static file, outputs to an HTML file, then has the browser read from that file. For debugging purposes. //objXSLTransform.Transform("D:\\temp\\print.xml", "D:\\temp\\output.htm"); //webBrowser1.Navigate("D:\\temp\\output.htm"); if (GlobalSettings.PrintToFileFirst) { // The DocumentStream method fails when using Wine, so we'll instead dump everything out a temporary HTML file, have the WebBrowser load that, then delete the temporary file. // Delete any old versions of the file if (!await Utils.SafeDeleteFileAsync(_strTempSheetFilePath, true)) { return; } // Read in the resulting code and pass it to the browser. using (StreamReader objReader = new StreamReader(objStream, Encoding.UTF8, true)) { string strOutput = await objReader.ReadToEndAsync(); File.WriteAllText(_strTempSheetFilePath, strOutput); } await this.DoThreadSafeAsync(() => UseWaitCursor = true); await webViewer.DoThreadSafeAsync( x => x.Url = new Uri("file:///" + _strTempSheetFilePath)); } else { // Populate the browser using DocumentText (DocumentStream would cause issues due to stream disposal). using (StreamReader objReader = new StreamReader(objStream, Encoding.UTF8, true)) { string strOutput = await objReader.ReadToEndAsync(); await this.DoThreadSafeAsync(() => UseWaitCursor = true); await webViewer.DoThreadSafeAsync(x => x.DocumentText = strOutput); } } } } }
private async void lstItems_SelectedIndexChanged(object sender, EventArgs e) { if (_blnSkipRefresh) { return; } using (CursorWait.New(this)) { if (lstItems.DoThreadSafeFunc(x => x.SelectedValue) is MasterIndexEntry objEntry) { await lblSourceLabel.DoThreadSafeAsync(x => x.Visible = true); await lblSource.DoThreadSafeAsync(x => x.Visible = true); await lblSourceClickReminder.DoThreadSafeAsync(x => x.Visible = true); await lblSource.DoThreadSafeAsync(x => x.Text = objEntry.DisplaySource.ToString()); await lblSource.DoThreadSafeAsync(x => x.ToolTipText = objEntry.DisplaySource.LanguageBookTooltip); (bool blnSuccess, Task <string> tskNotes) = await _dicCachedNotes.TryGetValueAsync(objEntry); if (!blnSuccess) { if (!GlobalSettings.Language.Equals(GlobalSettings.DefaultLanguage, StringComparison.OrdinalIgnoreCase) && (objEntry.TranslatedNameOnPage != objEntry.EnglishNameOnPage || objEntry.Source.Page != objEntry.DisplaySource.Page)) { // don't check again it is not translated tskNotes = Task.Run(async() => { string strReturn = await CommonFunctions.GetTextFromPdfAsync(objEntry.Source.ToString(), objEntry.EnglishNameOnPage); if (string.IsNullOrEmpty(strReturn)) { strReturn = await CommonFunctions.GetTextFromPdfAsync( objEntry.DisplaySource.ToString(), objEntry.TranslatedNameOnPage); } return(strReturn); }); } else { tskNotes = Task.Run(() => CommonFunctions.GetTextFromPdfAsync(objEntry.Source.ToString(), objEntry.EnglishNameOnPage)); } await _dicCachedNotes.TryAddAsync(objEntry, tskNotes); } string strNotes = await tskNotes; await txtNotes.DoThreadSafeAsync(x => x.Text = strNotes); await txtNotes.DoThreadSafeAsync(x => x.Visible = true); } else { await lblSourceLabel.DoThreadSafeAsync(x => x.Visible = false); await lblSource.DoThreadSafeAsync(x => x.Visible = false); await lblSourceClickReminder.DoThreadSafeAsync(x => x.Visible = false); await txtNotes.DoThreadSafeAsync(x => x.Visible = false); } } }
/// <summary> /// Create a Critter, put them into Career Mode, link them, and open the newly-created Critter. /// </summary> /// <param name="strCritterName">Name of the Critter's Metatype.</param> /// <param name="intForce">Critter's Force.</param> private async ValueTask CreateCritter(string strCritterName, int intForce) { // Code from frmMetatype. XmlDocument objXmlDocument = await _objSpirit.CharacterObject.LoadDataAsync("critters.xml"); XmlNode objXmlMetatype = objXmlDocument.SelectSingleNode("/chummer/metatypes/metatype[name = " + strCritterName.CleanXPath() + ']'); // If the Critter could not be found, show an error and get out of here. if (objXmlMetatype == null) { Program.ShowMessageBox(string.Format(GlobalSettings.CultureInfo, await LanguageManager.GetStringAsync("Message_UnknownCritterType"), strCritterName), await LanguageManager.GetStringAsync("MessageTitle_SelectCritterType"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } using (CursorWait.New(ParentForm)) { // The Critter should use the same settings file as the character. Character objCharacter = new Character { SettingsKey = _objSpirit.CharacterObject.SettingsKey, // Override the defaults for the setting. IgnoreRules = true, IsCritter = true, Alias = strCritterName, Created = true }; try { if (!string.IsNullOrEmpty(txtCritterName.Text)) { objCharacter.Name = txtCritterName.Text; } string strSpace = await LanguageManager.GetStringAsync("String_Space"); using (SaveFileDialog saveFileDialog = new SaveFileDialog { Filter = await LanguageManager.GetStringAsync("DialogFilter_Chum5") + '|' + await LanguageManager.GetStringAsync("DialogFilter_All"), FileName = strCritterName + strSpace + '(' + await LanguageManager.GetStringAsync(_objSpirit.RatingLabel) + strSpace + _objSpirit.Force.ToString(GlobalSettings.InvariantCultureInfo) + ").chum5" }) { if (saveFileDialog.ShowDialog(this) != DialogResult.OK) { return; } string strFileName = saveFileDialog.FileName; objCharacter.FileName = strFileName; } objCharacter.Create(objXmlMetatype["category"]?.InnerText, objXmlMetatype["id"]?.InnerText, string.Empty, objXmlMetatype, intForce); objCharacter.MetatypeBP = 0; using (LoadingBar frmProgressBar = await Program.CreateAndShowProgressBarAsync()) { frmProgressBar.PerformStep(objCharacter.CharacterName, LoadingBar.ProgressBarTextPatterns.Saving); if (!await objCharacter.SaveAsync()) { return; } } // Link the newly-created Critter to the Spirit. cmdLink.ToolTipText = await LanguageManager.GetStringAsync( _objSpirit.EntityType == SpiritType.Spirit? "Tip_Spirit_OpenFile" : "Tip_Sprite_OpenFile"); ContactDetailChanged?.Invoke(this, EventArgs.Empty); await Program.OpenCharacter(objCharacter); } finally { await objCharacter .DisposeAsync(); // Fine here because Dispose()/DisposeAsync() code is skipped if the character is open in a form } } }
private async void SelectBuildMethod_Load(object sender, EventArgs e) { using (CursorWait.New(this)) { SuspendLayout(); try { // Populate the Character Settings list. using (new FetchSafelyFromPool <List <ListItem> >(Utils.ListItemListPool, out List <ListItem> lstCharacterSettings)) { foreach (CharacterSettings objLoopSetting in SettingsManager.LoadedCharacterSettings.Values) { lstCharacterSettings.Add(new ListItem(objLoopSetting, objLoopSetting.DisplayName)); } lstCharacterSettings.Sort(CompareListItems.CompareNames); await cboCharacterSetting.PopulateWithListItemsAsync(lstCharacterSettings); if (_blnForExistingCharacter) { (bool blnSuccess, CharacterSettings objSetting) = await SettingsManager.LoadedCharacterSettings.TryGetValueAsync( _objCharacter.SettingsKey); if (blnSuccess) { cboCharacterSetting.SelectedValue = objSetting; } if (cboCharacterSetting.SelectedIndex == -1) { (blnSuccess, objSetting) = await SettingsManager.LoadedCharacterSettings.TryGetValueAsync( GlobalSettings.DefaultCharacterSetting); if (blnSuccess) { cboCharacterSetting.SelectedValue = objSetting; } } chkIgnoreRules.Checked = _objCharacter.IgnoreRules; } else { (bool blnSuccess, CharacterSettings objSetting) = await SettingsManager.LoadedCharacterSettings.TryGetValueAsync( GlobalSettings.DefaultCharacterSetting); if (blnSuccess) { cboCharacterSetting.SelectedValue = objSetting; } } if (cboCharacterSetting.SelectedIndex == -1 && lstCharacterSettings.Count > 0) { cboCharacterSetting.SelectedIndex = 0; } } await chkIgnoreRules.SetToolTipAsync(await LanguageManager.GetStringAsync("Tip_SelectKarma_IgnoreRules")); await ProcessGameplayIndexChanged(); } finally { ResumeLayout(); } } }