/// <summary> /// Saves the level file to the currently selected file name. If none, or /// if forceDialog is true, a Save dialog is shown first. Returns true if /// saved successfully. /// </summary> public bool SaveWithDialog(bool forceDialog) { // Check if have a file name if (forceDialog || Program.Settings.LevelFilename == null) { SaveFileDialog dlg = new SaveFileDialog(); dlg.DefaultExt = "txt"; dlg.Filter = Program.Tr.Save_FileType_TextFiles + "|*.txt|" + Program.Tr.Save_FileType_AllFiles + "|*.*"; dlg.InitialDirectory = Program.Settings.LastOpenSaveDirectory; DialogResult result = dlg.ShowDialog(); // If the user cancelled the dialog, bail out if (result != DialogResult.OK) { return(false); } // Update the current filename Program.Settings.LastOpenSaveDirectory = Path.GetDirectoryName(dlg.FileName); Program.Settings.LevelFilename = dlg.FileName; } // Just save. try { SaveLevelPack(Program.Settings.LevelFilename); return(true); } catch (Exception e) { // If anything fails here, don't crash. Just tell the caller that save hasn't actually happened. DlgMessage.Show(Program.Tr.LevelList_Message_CannotSaveSettings + "\n" + e.Message, Program.Tr.LevelList_Message_CannotSaveSettings_Title, DlgType.Error); return(false); } }
public override bool AskForValue(string parameterName, ref object value) { var result = DlgMessage.Show(Prompt, parameterName, DlgType.Question, ReadableNames.Concat("Cancel").ToArray()); value = result == ReadableNames.Length ? null : Enum.ToObject(EnumType, result); return(value != null); }
/// <summary>Override; see base.</summary> protected override void EditCurrentLanguage() { if (_getCurrentLanguage() == _defaultLanguage) { DlgMessage.Show("The currently selected language is the native language of this application and cannot be edited.", "Edit current language", DlgType.Info); return; } if (_translationWindow == null) { #if !DEBUG try #endif { _translationWindow = new TranslationWindow(typeof(TTranslation), _settings, _icon, _programTitle, _moduleName, _getCurrentLanguage()); } #if !DEBUG catch (Exception ex) { DlgMessage.Show("Translation could not be loaded: " + ex.Message, "Edit current language", DlgType.Info); return; } #endif _translationWindow.TranslationChanged += tr => { FireTranslationChanged((TTranslation)tr); }; _translationWindow.Closed += delegate { _translationWindow = null; }; } _translationWindow.Show(); }
private void revert(object sender, EventArgs e) { if (_currentFilePath != null && DlgMessage.Show("Revert all changes made since last save?", "Revert", DlgType.Question, "&Revert", "&Cancel") == 0) { openCore(_currentFilePath); } }
public override bool AskForValue(string parameterName, ref object value) { var result = DlgMessage.Show(Prompt, parameterName, DlgType.Question, ReadableFalseName, ReadableTrueName, "Cancel"); value = result == 0 ? false : result == 1 ? true : (object)null; return(result < 2); }
private void deletePath(object sender, EventArgs e) { if (DlgMessage.Show("Are you sure you wish to delete this path?", "Confirmation", DlgType.Question, "&Delete path", "&Cancel") == 0) { _file.Paths.Remove((HCPath)lstPaths.SelectedItem); updateList(); rerender(); } }
/// <summary> /// Attempts to open the level at the specified index either for playing or editing. /// </summary> /// <param name="index">The index of the level to be opened, or null to deselect the current level.</param> /// <param name="state">Must be <see cref="LevelListBoxState.Playing"/> or <see cref="LevelListBoxState.Editing"/>. Ignored if index is null.</param> private void setActiveLevel(int?index, LevelListBoxState state) { if (LevelActivating != null) { // Confirm with the owner that the level can be changed ConfirmEventArgs args = new ConfirmEventArgs { ConfirmOK = true }; LevelActivating(this, args); if (!args.ConfirmOK) { return; } } if (index == null) { _activeLevelIndex = null; } else if (index.Value < 0 || index.Value >= Items.Count || !(Items[index.Value] is SokobanLevel)) { Ut.InternalError(); } else { SokobanLevelStatus status; if (state == LevelListBoxState.Playing && (status = ((SokobanLevel)Items[index.Value]).Validity) != SokobanLevelStatus.Valid) { string problem = status == SokobanLevelStatus.NotEnclosed ? Program.Tr.Mainform_Validity_NotEnclosed : Program.Tr.Mainform_Validity_WrongNumber; if (DlgMessage.Show(Program.Tr.Mainform_Validity_CannotOpen + "\n\n" + problem + "\n\n" + Program.Tr.Mainform_Validity_CannotOpen_Fix, Program.Tr.Mainform_MessageTitle_OpenLevel, DlgType.Error, Program.Tr.Mainform_Validity_CannotOpen_btnEdit, Program.Tr.Dialogs_btnCancel) == 0) { _state = LevelListBoxState.Editing; _activeLevelIndex = index.Value; } else { return; } } else { _state = state; _activeLevelIndex = index.Value; } } RefreshItems(); // Inform the owner that the level has changed LevelActivated(this, new EventArgs()); // Make the active level selected SelectActiveLevel(); }
static void enterMoveMode() { if (_selectedBox == null) { DlgMessage.Show("No item is selected.", "Error", DlgType.Error); return; } _mode = EditMode.Moving; Invalidate(_selectedBox); }
private bool compile(ExecutionState state) { removeRunToCursorBreakpoint(); _currentPosition = null; if (_env != null) { _env.State = state; return(true); } if (_saveWhenRun) { save(); } try { _env = _currentLanguage.Compile(txtSource.Text, _input ?? ""); _env.OriginalSource = txtSource.Text; _env.State = state; _env.DebuggerBreak += p => { this.BeginInvoke(new Action(() => debuggerBreak(p))); }; _env.ExecutionFinished += (c, e) => { this.BeginInvoke(new Action(() => executionFinished(c, e))); }; foreach (int bp in lstBreakpoints.Items) { _env.AddBreakpoint(bp); } _env.BreakpointsChanged += () => { this.BeginInvoke(new Action(() => breakpointsChanged())); }; tabWatch.Controls.Clear(); tabWatch.Controls.Add(_env.InitializeWatchWindow()); if (EsotericIDEProgram.Settings.WatchFont != null) { _env.SetWatchWindowFont(EsotericIDEProgram.Settings.WatchFont); } return(true); } catch (CompileException e) { if (e.Index != null) { txtSource.Focus(); txtSource.SelectionStart = e.Index.Value; txtSource.SelectionLength = e.Length ?? 0; txtSource.ScrollToCaret(); } DlgMessage.Show("Compilation failed:" + Environment.NewLine + e.Message, "Esoteric IDE", DlgType.Error, "&OK"); return(false); } catch (Exception e) { DlgMessage.Show("Compilation failed:" + Environment.NewLine + e.Message + " (" + e.GetType().FullName + ")", "Esoteric IDE", DlgType.Error, "&OK"); return(false); } }
private void openCore(string filePath) { if (!File.Exists(filePath)) { DlgMessage.Show("The specified file does not exist.", "Error", DlgType.Error); return; } _currentFilePath = filePath; _file = ClassifyJson.Deserialize <HCFile>(JsonValue.Parse(File.ReadAllText(_currentFilePath))); _anyChanges = false; // _lastFileTime = File.GetLastWriteTimeUtc(_currentFilePath); updateList(); rerender(); }
private void insertByteArray(IIde ide) { string @default, selected = ide.GetSelectedText(); try { @default = ScliptingUtil.DecodeByteArray(selected).ToHex(); } catch { @default = ""; } var line = InputBox.GetLine("Type a byte array to insert (in hexdump format; two hexadecimal digits per byte):", @default, "Esoteric IDE", "&OK", "&Cancel"); if (line != null) { try { ide.InsertText(ScliptingUtil.EncodeByteArray(line.FromHex())); } catch { DlgMessage.Show("The text you entered is not valid hexadecimal. Please ensure that you enter an even number of characters 0-9/a-f.", "Esoteric IDE", DlgType.Error, "&OK"); } } }
private void mouseDown(object sender, MouseEventArgs e) { if (_lastRendering != null) { _lastMouseDown = _file.FromScreen(e.X, e.Y); if (e.Button == MouseButtons.Right) { mnuContext.Show(ctImage, e.Location); } else { DlgMessage.Show("The position you clicked is: " + _lastMouseDown.ToString(), "Axial coordinates", DlgType.Info); } } }
private EventHandler checkDebugging(IIde ide, Action <HexagonyEnv> action) { return((_, __) => { var env = ide.GetEnvironment() as HexagonyEnv; if (env == null || env.State != ExecutionState.Debugging) { DlgMessage.Show("Program must be running but stopped in the debugger.", "Error", DlgType.Error); } else { action(env); } }); }
/// <summary> /// Activates the previous level for playing. Wraps around and starts from the /// last level if necessary. If no previous level is found, an appropriate /// message is displayed to the user. The function will trigger the /// LevelActivating event before activating the level. /// </summary> /// <param name="mustBeUnsolved">Specifies whether to activate the immediately /// previous level (false) or the previous unsolved level (true).</param> public void PlayPrev(bool mustBeUnsolved) { int?i = findPrevNext(mustBeUnsolved, false); if (i == null) { DlgMessage.Show( mustBeUnsolved ? Program.Tr.LevelList_Message_NoMoreUnsolved : Program.Tr.LevelList_Message_NoOtherLevel, mustBeUnsolved ? Program.Tr.LevelList_Message_PrevUnsolved_Title : Program.Tr.LevelList_Message_Prev_Title, DlgType.Info, Program.Tr.Dialogs_btnOK); } else { playingIndex = i.Value; } }
private void openCore(string filePath) { if (!File.Exists(filePath)) { DlgMessage.Show("The specified file does not exist.", "Error", DlgType.Error); return; } _currentFilePath = filePath; txtSource.Text = File.ReadAllText(_currentFilePath).UnifyLineEndings(); txtOutput.Text = ""; _timerPreviousSource = txtSource.Text; _timerPreviousCursorPosition = -1; sourceTextboxFixHack(); _anyChanges = false; _lastFileTime = File.GetLastWriteTimeUtc(_currentFilePath); }
/// <summary> /// Invoked by "Level => Show highscores". Displays the highscores for the /// currently selected level. /// </summary> private void showHighscores(object sender, EventArgs e) { if (lstLevels.SelectedLevel != null) { string level = lstLevels.SelectedLevel.ToString(); if (!Program.Settings.Highscores.ContainsKey(level)) { DlgMessage.Show(Program.Tr.Mainform_NoHighscores, Program.Tr.Mainform_NoHighscores_Title, DlgType.Info, Program.Tr.Dialogs_btnOK); } else { HighscoresForm hsf = new HighscoresForm(); hsf.SetContents(Program.Settings.Highscores[level], lstLevels.SelectedLevel); hsf.ShowDialog(); } } }
private void checkFileChanged() { // Make sure this is not called while it is already running, which would // happen because dismissing the DlgMessage triggers activated() if (!_checkFileChangedBusy) { _checkFileChangedBusy = true; if (_currentFilePath != null && File.Exists(_currentFilePath) && File.GetLastWriteTimeUtc(_currentFilePath) > _lastFileTime && DlgMessage.Show("The file has changed on disk. Reload?", "File has changed", DlgType.Question, "&Reload", "&Cancel") == 0) { openCore(_currentFilePath); } _checkFileChangedBusy = false; } }
public override ToolStripMenuItem[] CreateMenus(IIde ide) { var menuItems = new List <Tuple <ToolStripMenuItem, Func <bool> > >(); var ret = Ut.NewArray <ToolStripMenuItem>( new ToolStripMenuItem("&Insert", null, new ToolStripMenuItem("&Word from index", null, (_, __) => { var input = InputBox.GetLine("Index to look up?", caption: "Runic"); if (input == null || !int.TryParse(input, out var ix)) { return; } var word = WordDictionary.GetWord(ix); if (word == null) { DlgMessage.Show($"The specified index is out of range. Valid range is 0–{WordDictionary.List.Length - 1}.", "Runic", DlgType.Error); } else { ide.InsertText(word); } }), new ToolStripMenuItem("&Index from word", null, (_, __) => { var input = InputBox.GetLine("Word to look up?", caption: "Runic"); if (input == null) { return; } var index = WordDictionary.GetIndex(input.ToLowerInvariant().Trim()); if (index == -1) { DlgMessage.Show("The specified word is not in the dictionary.", "Runic", DlgType.Error); } else { ide.InsertText(index.ToString()); } }) ) ); return(ret); }
/// <summary>Returns a value indicating whether it is okay to close the application. The user is asked if there are any unsaved changes.</summary> public bool MayExitApplication() { if (TranslationDialog == null || !TranslationDialog.AnyChanges) { return(true); } var result = DlgMessage.Show("Would you like to save the changes to made to the translation you are currently editing?", "Exit Application", DlgType.Warning, "Save changes", "Discard changes", "Cancel"); if (result == 2) { return(false); } if (result == 0) { TranslationDialog.SaveChanges(false); } return(true); }
private void executionFinished(bool canceled, RuntimeError runtimeError) { removeRunToCursorBreakpoint(); tabWatch.Controls.Clear(); tabWatch.Controls.Add(notRunningLabel); var sel = txtSource.SelectionStart; var len = txtSource.SelectionLength; txtSource.Text = _env.OriginalSource; txtOutput.Text = _env.Output.UnifyLineEndings(); if (canceled && runtimeError == null) { txtOutput.Text += Environment.NewLine + Environment.NewLine + "Execution stopped."; } _env = null; _currentPosition = null; ctTabs.SelectedTab = tabOutput; txtSource.Focus(); txtSource.SelectionStart = sel; txtSource.SelectionLength = len; txtSource.ScrollToCaret(); // In case the file has changed since the last time we ran the program checkFileChanged(); if (runtimeError != null) { var msg = "A run-time error occurred:{0}{0}{1}".Fmt(Environment.NewLine, runtimeError.Message); txtOutput.Text += Environment.NewLine + Environment.NewLine + msg; txtSource.Focus(); if (runtimeError.Position != null) { txtSource.Focus(); txtSource.SelectionStart = runtimeError.Position.Index; txtSource.SelectionLength = runtimeError.Position.Length; txtSource.ScrollToCaret(); } DlgMessage.Show(msg, "Run-time error", DlgType.Error, "&OK"); } }
static void fileOpen(string filePath, bool doThrow) { try { _file = Parse(filePath); _filePath = filePath; _fileChanged = false; Invalidate(0, 0, Console.BufferWidth, Console.BufferHeight); Console.Title = Path.GetFileName(_filePath) + " — Editon"; updateAfterEdit(); } catch (Exception e) { if (doThrow) { throw; } DlgMessage.Show("{0} ({1})".Fmt(e.Message, e.GetType().Name), "Error", DlgType.Error); } }
public override bool AskForValue(string parameterName, ref object value) { tryAgain: var result = InputBox.GetLine(Prompt, @default: value?.ToString() ?? "", caption: "Parameter"); if (result == null) { return(false); } if (!tryParse(result, ref value)) { var result2 = DlgMessage.Show("The value is not valid. Do you want to try again?", "Error", DlgType.Error, "&Yes", "&No"); if (result2 == 0) { goto tryAgain; } return(false); } return(true); }
private bool canDestroy() { if (!_anyChanges) { return(true); } var result = DlgMessage.Show("Would you like to save your changes to this file?", "Hexagony Colorer", DlgType.Question, "&Save", "&Discard", "&Cancel"); if (result == 2) { return(false); } if (result == 1) { return(true); } return(save() == DialogResult.OK); }
/// <summary> /// Determines whether we are allowed to delete the selected item from the /// level list. If the user is currently playing the level, a confirmation /// message asks whether they want to give up. If they are currently editing it, /// a message asks whether they want to discard it. /// </summary> /// <param name="normalConfirmation">If true, a confirmation message will also /// appear if the user is not currently playing or editing the selected level. /// </param> /// <returns>True if allowed.</returns> public bool MayDeleteSelectedItem(bool normalConfirmation) { if (!Visible || SelectedIndex < 0) { return(false); } object item = Items[SelectedIndex]; // Confirmation message if user is currently editing the selected level if (item is SokobanLevel && SelectedIndex == editingIndex) { if (DlgMessage.Show(Program.Tr.LevelList_Message_DeleteLevel_CurrentlyEditing, Program.Tr.LevelList_Message_DeleteLevel_Title, DlgType.Warning, Program.Tr.Dialogs_btnDiscard, Program.Tr.Dialogs_btnCancel) == 1) { return(false); } } // Confirmation message if user is currently playing the selected level else if (item is SokobanLevel && SelectedIndex == playingIndex) { if (DlgMessage.Show(Program.Tr.LevelList_Message_DeleteLevel_CurrentlyPlaying, Program.Tr.LevelList_Message_DeleteLevel_Title, DlgType.Warning, Program.Tr.Dialogs_btnGiveUp, Program.Tr.Dialogs_btnCancel) == 1) { return(false); } } // Confirmation message if neither of the two cases apply else if (item is SokobanLevel) { if (normalConfirmation && DlgMessage.Show( Program.Tr.LevelList_Message_DeleteLevel_Sure, Program.Tr.LevelList_Message_DeleteLevel_Title, DlgType.Question, Program.Tr.LevelList_Message_DeleteLevel_btnDelete, Program.Tr.Dialogs_btnCancel) == 1) { return(false); } } return(true); }
private void insertInteger(IIde ide) { string @default, selected = ide.GetSelectedText(); try { if (selected.Length == 1 && selected[0] >= 0xbc00 && selected[0] <= 0xd7a3) { @default = (0xbbff - selected[0]).ToString(); } else { @default = new BigInteger(new byte[] { 0 }.Concat(ScliptingUtil.DecodeByteArray(selected)).Reverse().ToArray()).ToString(); } } catch { @default = "0"; } var line = InputBox.GetLine("Type an integer to insert (must be greater than −7077):", @default, "Esoteric IDE", "&OK", "&Cancel"); if (line != null) { BigInteger i; if (BigInteger.TryParse(line, out i) && (i >= -7076)) { if (i < 0) { ide.InsertText(((char)(0xbbff - i)).ToString()); } else { ide.InsertText(ScliptingUtil.EncodeByteArray(i.ToByteArray().Reverse().SkipWhile(b => b == 0).DefaultIfEmpty().ToArray())); } } else { DlgMessage.Show("The integer you typed is not a valid literal integer for Sclipting. Literal integers must be greater than −7077.", "Esoteric IDE", DlgType.Error, "&OK"); } } }
/// <summary>Override; see base.</summary> protected override void EditCurrentLanguage() { if (_getCurrentLanguage() == _defaultLanguage) { DlgMessage.Show("The currently selected language is the native language of this application and cannot be edited.", "Edit current language", DlgType.Info); return; } if (_translationForm == null) { try { _translationForm = new TranslationForm <TTranslation>(_settings, _icon, _programTitle, _moduleName, _getCurrentLanguage()); } catch (Exception ex) { DlgMessage.Show("Translation could not be loaded: " + ex.Message, "Edit current language", DlgType.Info); return; } _translationForm.TranslationChanged += tr => { FireTranslationChanged(tr); }; _translationForm.FormClosed += delegate { _translationForm = null; }; } _translationForm.Show(); }
private bool canDestroy() { int result; if (_env != null) { result = DlgMessage.Show("Cancel debugging?", "Esoteric IDE", DlgType.Question, "&Yes", "&No"); if (result == 1) { return(false); } // Tell the executing program to stop _env.State = ExecutionState.Stop; _env.Continue(true); // The stopped program will have triggered an executionFinished event, which needs to be processed before the form is disposed Application.DoEvents(); } if (!_anyChanges) { return(true); } result = DlgMessage.Show("Would you like to save your changes to this file?", "Esoteric IDE", DlgType.Question, "&Save", "&Discard", "&Cancel"); if (result == 2) { return(false); } if (result == 1) { return(true); } return(save() == DialogResult.OK); }
private void createAnnotationSet(bool copyFromCurrent, IIde ide) { string newName = copyFromCurrent ? _settings.LastMemoryAnnotationSet : null; while (true) { newName = InputBox.GetLine("Enter new name for this annotation set:", newName, "Create new annotation set", "&OK", "&Cancel"); if (newName == null) { break; } if (!_settings.MemoryAnnotations.ContainsKey(newName)) { _settings.MemoryAnnotations[newName] = copyFromCurrent ? _settings.MemoryAnnotations[_settings.LastMemoryAnnotationSet].ToDictionary(kvp => kvp.Key, kvp => new Dictionary <PointAxial, string>(kvp.Value)) : new Dictionary <Direction, Dictionary <PointAxial, string> >(); _settings.LastMemoryAnnotationSet = newName; updateAnnotationSets(ide); updateWatch(ide); return; } DlgMessage.Show("The specified annotation set name already exists. Annotation set names must be unique.", "Error", DlgType.Error); } }
/// <summary>Presents the user with a dialog to select a language from, and (if they click "OK") creates a new XML file for the new translation.</summary> /// <typeparam name="TTranslation">Class containing the translatable strings.</typeparam> /// <param name="moduleName">Name of the module being translated (forms part of the translation's XML file).</param> /// <param name="fontName">Specifies the name of the font to use in this dialog, or null for the default font.</param> /// <param name="fontSize">Specifies the size of the font to use in this dialog. Ignored if <paramref name="fontName"/> is null.</param> /// <returns>If the user clicked OK, creates a new XML file and returns the translation. If the user clicked Cancel, returns null.</returns> public static TTranslation CreateTranslation <TTranslation>(string moduleName, string fontName, float fontSize) where TTranslation : TranslationBase, new() { using (TranslationCreateForm tcf = new TranslationCreateForm()) { tcf.Font = fontName != null ? new Font(fontName, fontSize, FontStyle.Regular) : SystemFonts.MessageBoxFont; if (tcf.ShowDialog() != DialogResult.OK) { return(null); } if (tcf.SelectedLanguage == new TTranslation().Language) { DlgMessage.Show("This is the native language of the application. This translation cannot be edited, and you cannot create a new translation for this language.", "Error creating translation", DlgType.Error, "OK"); return(null); } var trans = new TTranslation { Language = tcf.SelectedLanguage }; string iso = trans.Language.GetIsoLanguageCode(); string xmlFile = PathUtil.AppPathCombine("Translations", moduleName + "." + iso + ".xml"); if (File.Exists(xmlFile)) { int result = DlgMessage.Show("A translation into the selected language already exists. If you wish to start this translation afresh, please delete the translation file first.\n\nThe translation file is: " + xmlFile, "Error creating translation", DlgType.Error, "&Go to containing folder", "Cancel"); if (result == 0) { Process.Start(Path.GetDirectoryName(xmlFile)); } return(null); } ClassifyXml.SerializeToFile(trans, xmlFile); return(trans); } }
private void insertString(IIde ide) { string @default, selected = ide.GetSelectedText(); try { if (selected.Length == 1 && selected[0] >= 0xbc00 && selected[0] <= 0xd7a3) { @default = (0xbbff - selected[0]).ToString(); } else { @default = ScliptingUtil.DecodeByteArray(selected).FromUtf8().CLiteralEscape(); } } catch { @default = "\\n"; } var line = InputBox.GetLine("Type a string to insert (in C-escaped format; backslashes must be escaped):", @default, "Esoteric IDE", "&OK", "&Cancel"); if (line != null) { try { ide.InsertText(ScliptingUtil.EncodeByteArray(line.CLiteralUnescape().ToUtf8())); } catch { DlgMessage.Show("The string you typed is not a valid C-escaped string. Please ensure that your backslashes are escaped.", "Esoteric IDE", DlgType.Error, "&OK"); } } }