ScriptEditor.xaml.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Drawing;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Threading.Tasks;
  8. using System.Windows;
  9. using System.Windows.Controls;
  10. using System.Windows.Input;
  11. using System.Windows.Threading;
  12. using ICSharpCode.AvalonEdit.Highlighting;
  13. using InABox.Core;
  14. using InABox.Scripting;
  15. using InABox.WPF;
  16. using InABox.Wpf;
  17. using InABox.WPF.Themes;
  18. using Microsoft.CodeAnalysis;
  19. using RoslynPad.Editor;
  20. using RoslynPad.Roslyn;
  21. using Syncfusion.Data.Extensions;
  22. using Image = System.Windows.Controls.Image;
  23. namespace InABox.DynamicGrid
  24. {
  25. /// <summary>
  26. /// Interaction logic for ScriptEditor.xaml
  27. /// </summary>
  28. public partial class ScriptEditorWindow : ThemableWindow
  29. {
  30. public static RoutedCommand SaveCommand = new();
  31. private bool _bChanged;
  32. private string _editorTitle = "ScriptEditor";
  33. public string EditorTitle
  34. {
  35. get => _editorTitle;
  36. set {
  37. _editorTitle = value;
  38. UpdateTitle();
  39. }
  40. }
  41. private RoslynHost _host;
  42. private ManualOnlyCompletionProvider? _manual;
  43. private readonly SyntaxLanguage _language = SyntaxLanguage.CSharp;
  44. private readonly string _script = "";
  45. private Dictionary<string, string[]> _snippets = new();
  46. private bool bCompiled;
  47. private readonly Dictionary<bool, Image> compile = SetupImage(Wpf.Resources.tick);
  48. private readonly Dictionary<bool, Image> copy = SetupImage(Wpf.Resources.copy);
  49. private readonly Dictionary<bool, Image> cut = SetupImage(Wpf.Resources.cut);
  50. private readonly Dictionary<bool, Image> paste = SetupImage(Wpf.Resources.paste);
  51. private readonly Dictionary<bool, Image> print = SetupImage(Wpf.Resources.print);
  52. private readonly Dictionary<bool, Image> redo = SetupImage(Wpf.Resources.redo);
  53. private readonly Dictionary<bool, Image> run = SetupImage(Wpf.Resources.run);
  54. private readonly Dictionary<bool, Image> save = SetupImage(Wpf.Resources.disk);
  55. private readonly Dictionary<bool, Image> undo = SetupImage(Wpf.Resources.undo);
  56. private readonly Dictionary<bool, Image> errors = SetupImage(Wpf.Resources.delete);
  57. private readonly Dictionary<bool, Image> warnings = SetupImage(Wpf.Resources.warning);
  58. private bool _showErrors;
  59. public bool ShowErrors
  60. {
  61. get => _showErrors;
  62. set
  63. {
  64. _showErrors = value;
  65. UpdateDiagnosticButton(ShowErrorsButton, errors, value);
  66. RefreshDiagnostics();
  67. }
  68. }
  69. private bool _showWarnings;
  70. public bool ShowWarnings
  71. {
  72. get => _showWarnings;
  73. set
  74. {
  75. _showWarnings = value;
  76. UpdateDiagnosticButton(ShowWarningsButton, warnings, value);
  77. RefreshDiagnostics();
  78. }
  79. }
  80. private void UpdateDiagnosticButton(Button button, Dictionary<bool, Image> image, bool enabled)
  81. {
  82. button.Content = image[enabled];
  83. }
  84. static ScriptEditorWindow()
  85. {
  86. SaveCommand.InputGestures.Add(new KeyGesture(Key.S, ModifierKeys.Control));
  87. }
  88. public ScriptEditorWindow(string script, SyntaxLanguage language = SyntaxLanguage.CSharp, string scriptTitle = "ScriptEditor")
  89. {
  90. _language = language;
  91. _script = script;
  92. EditorTitle = scriptTitle;
  93. InitializeComponent();
  94. // Not Sure if we need Roslyn for XAML - need to research this
  95. if (language == SyntaxLanguage.CSharp || language == SyntaxLanguage.XAML)
  96. {
  97. try
  98. {
  99. if (ScriptDocument.Host == null)
  100. ScriptDocument.Initialize();
  101. }
  102. catch (Exception e)
  103. {
  104. MessageBox.Show("Unable to initialize Script Editor!\nPlease try again.\n\n" + e.Message);
  105. }
  106. }
  107. Editor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition(
  108. language == SyntaxLanguage.HTML
  109. ? "HTML"
  110. : language == SyntaxLanguage.XAML
  111. ? "XML"
  112. : language == SyntaxLanguage.CSS
  113. ? "CSS"
  114. : "C#"
  115. );
  116. // Arm on Ctrl+Space, but don't handle the key so the editor's command still runs.
  117. Editor.PreviewKeyDown += (s, e) =>
  118. {
  119. if (e.Key == System.Windows.Input.Key.Space &&
  120. (System.Windows.Input.Keyboard.Modifiers & System.Windows.Input.ModifierKeys.Control) != 0)
  121. {
  122. _manual?.AllowNextCompletionOnce();
  123. // IMPORTANT: do not set e.Handled = true
  124. }
  125. };
  126. Editor.TextArea.TextEntering += TextArea_TextEntering;
  127. CheckButton(SaveButton, true, save);
  128. CheckButton(CopyButton, false, copy);
  129. CheckButton(CutButton, false, cut);
  130. CheckButton(PasteButton, false, paste);
  131. CheckButton(UndoButton, false, undo);
  132. CheckButton(RedoButton, false, redo);
  133. CheckButton(PrintButton, true, print);
  134. CheckButton(CompileButton, language == SyntaxLanguage.CSharp || language == SyntaxLanguage.XAML, compile);
  135. CheckButton(RunButton, false, run);
  136. ShowErrors = true;
  137. ShowWarnings = false;
  138. var timer = new DispatcherTimer();
  139. timer.Interval = TimeSpan.FromMilliseconds(500);
  140. timer.Tick += Timer_Tick;
  141. timer.Start();
  142. bChanged = false;
  143. }
  144. public string Script
  145. {
  146. get => new String(Editor.Text);
  147. }
  148. public Dictionary<string, string[]> Snippets
  149. {
  150. get => _snippets;
  151. set
  152. {
  153. _snippets = value;
  154. if (_snippets != null && _snippets.Any())
  155. {
  156. SnippetPanel.Visibility = Visibility.Visible;
  157. SnippetSection.ItemsSource = _snippets.Keys;
  158. SnippetSection.SelectedValue = _snippets.Keys.First();
  159. }
  160. else
  161. {
  162. SnippetPanel.Visibility = Visibility.Collapsed;
  163. }
  164. }
  165. }
  166. private bool bChanged
  167. {
  168. get => _bChanged;
  169. set
  170. {
  171. _bChanged = value;
  172. UpdateTitle();
  173. }
  174. }
  175. private static Dictionary<bool, Image> SetupImage(Bitmap bitmap)
  176. {
  177. return new Dictionary<bool, Image>
  178. {
  179. { true, new Image { Source = bitmap.AsBitmapImage(), MaxHeight = 32, MaxWidth = 32 } },
  180. { false, new Image { Source = bitmap.AsGrayScale().AsBitmapImage(), MaxHeight = 32, MaxWidth = 32 } }
  181. };
  182. }
  183. private event EventHandler _onSave;
  184. public event EventHandler OnSave
  185. {
  186. add
  187. {
  188. _onSave += value;
  189. SaveButton.ToolTip = "Save";
  190. }
  191. remove
  192. {
  193. _onSave -= value;
  194. if (_onSave == null) SaveButton.ToolTip = "Save & Close";
  195. }
  196. }
  197. private event EventHandler _onCompile;
  198. public event EventHandler OnCompile
  199. {
  200. add
  201. {
  202. _onCompile += value;
  203. CheckButton(CompileButton, true, compile);
  204. }
  205. remove => _onCompile -= value;
  206. }
  207. private void CheckButton(Button button, bool condition, Dictionary<bool, Image> images)
  208. {
  209. if (button.Visibility != Visibility.Visible)
  210. button.Visibility = Visibility.Visible;
  211. if (condition != button.IsEnabled)
  212. {
  213. button.IsEnabled = condition;
  214. button.Content = images[condition];
  215. }
  216. }
  217. private void UpdateTitle()
  218. {
  219. if (bChanged)
  220. {
  221. Title = _editorTitle + "*";
  222. }
  223. else
  224. {
  225. Title = _editorTitle;
  226. }
  227. }
  228. #region Public Interface
  229. public ScriptEditorWindow ClearErrors()
  230. {
  231. Errors.Items.Clear();
  232. return this;
  233. }
  234. public ScriptEditorWindow AddError(string error)
  235. {
  236. Errors.Items.Add(error);
  237. return this;
  238. }
  239. public void Save()
  240. {
  241. bChanged = false;
  242. if (_onSave != null)
  243. {
  244. _onSave?.Invoke(this, EventArgs.Empty);
  245. }
  246. else
  247. {
  248. DialogResult = true;
  249. Close();
  250. }
  251. }
  252. #endregion
  253. #region Event Handlers
  254. private void TextArea_TextEntering(object sender, TextCompositionEventArgs e)
  255. {
  256. if (string.Equals(e.Text, "\r"))
  257. e.Handled = true;
  258. }
  259. private void OnLoaded(object sender, RoutedEventArgs e)
  260. {
  261. if (_language == SyntaxLanguage.CSharp || _language == SyntaxLanguage.XAML)
  262. {
  263. Editor.DataContext = new ScriptDocument(_script);
  264. }
  265. else
  266. {
  267. Editor.Text = _script;
  268. bChanged = false;
  269. }
  270. //Roslyn.Text = _script;
  271. //Changed = DateTime.MinValue;
  272. }
  273. private void Roslyn_Loaded(object sender, RoutedEventArgs e)
  274. {
  275. var editor = (RoslynCodeEditor)sender;
  276. editor.Focus();
  277. if (_language == SyntaxLanguage.CSharp || _language == SyntaxLanguage.XAML)
  278. {
  279. var changed = bChanged;
  280. var script = (ScriptDocument)editor.DataContext;
  281. script.Id = editor.InitializeAsync(
  282. ScriptDocument.Host,
  283. new ClassificationHighlightColors(),
  284. Directory.GetCurrentDirectory(),
  285. _script,
  286. SourceCodeKind.Regular
  287. ).Result;
  288. bChanged = changed;
  289. }
  290. }
  291. private void Roslyn_PreviewKeyDown(object sender, KeyEventArgs e)
  292. {
  293. if (bCompiled)
  294. {
  295. bCompiled = false;
  296. CheckButton(RunButton, false, run);
  297. }
  298. }
  299. private void Roslyn_TextChanged(object sender, EventArgs e)
  300. {
  301. bChanged = true;
  302. if (bCompiled)
  303. {
  304. bCompiled = false;
  305. CheckButton(RunButton, false, run);
  306. }
  307. }
  308. private void Timer_Tick(object sender, EventArgs e)
  309. {
  310. if ((_manual == null) && (Editor.CompletionProvider != null))
  311. {
  312. _manual = new ManualOnlyCompletionProvider(Editor.CompletionProvider)
  313. {
  314. AllowSignatureHelp = false,
  315. TreatNullTriggerAsManualInvoke = true,
  316. AllowDotTrigger = false
  317. };
  318. Editor.CompletionProvider = _manual;
  319. }
  320. CheckButton(CopyButton, !string.IsNullOrEmpty(Editor.SelectedText), copy);
  321. CheckButton(CutButton, !string.IsNullOrEmpty(Editor.SelectedText), cut);
  322. CheckButton(PasteButton, Clipboard.ContainsText(), paste);
  323. CheckButton(UndoButton, Editor.CanUndo, undo);
  324. CheckButton(RedoButton, Editor.CanRedo, redo);
  325. }
  326. private void OKButton_Click(object sender, RoutedEventArgs e)
  327. {
  328. DialogResult = true;
  329. Close();
  330. }
  331. private void CancelButton_Click(object sender, RoutedEventArgs e)
  332. {
  333. DialogResult = false;
  334. Close();
  335. }
  336. private List<ScriptDocument.Diagnostic> Diagnostics = new();
  337. private void RefreshDiagnostics()
  338. {
  339. var diagnostics = Diagnostics.Where(x => x.Severity switch
  340. {
  341. DiagnosticSeverity.Error => ShowErrors,
  342. DiagnosticSeverity.Warning => ShowWarnings,
  343. _ => false
  344. }).ToList();
  345. Errors.Items.Clear();
  346. if (bCompiled && diagnostics.Count == 0)
  347. {
  348. Errors.Items.Add("Script Compiled Successfully!");
  349. }
  350. else
  351. {
  352. foreach(var diagnostic in diagnostics)
  353. {
  354. Errors.Items.Add(diagnostic.Contents);
  355. }
  356. }
  357. }
  358. private void CompileButton_Click(object sender, RoutedEventArgs e)
  359. {
  360. CheckButton(RunButton, false, run);
  361. if (_onCompile != null)
  362. {
  363. _onCompile.Invoke(this, EventArgs.Empty);
  364. }
  365. else
  366. {
  367. var viewModel = (ScriptDocument)Editor.DataContext;
  368. viewModel.Text = Editor.Text;
  369. Errors.Items.Clear();
  370. Errors.Items.Add("Compiling Script... ");
  371. Task.Run(() =>
  372. {
  373. bCompiled = viewModel.Compile();
  374. Diagnostics = viewModel.Diagnostics;
  375. Dispatcher.Invoke(() =>
  376. {
  377. RefreshDiagnostics();
  378. CheckButton(RunButton, bCompiled, run);
  379. });
  380. });
  381. }
  382. }
  383. private void RunButton_Click(object sender, RoutedEventArgs e)
  384. {
  385. var viewModel = (ScriptDocument)Editor.DataContext;
  386. try
  387. {
  388. var result = viewModel.Execute();
  389. }
  390. catch (Exception err)
  391. {
  392. MessageBox.Show(CoreUtils.FormatException(err));
  393. }
  394. }
  395. private void GotoLine(string line)
  396. {
  397. if (line.StartsWith("("))
  398. {
  399. var sLine = line.Substring(1).Split(',')[0];
  400. var iLine = int.Parse(sLine);
  401. Editor.ScrollToLine(iLine);
  402. }
  403. }
  404. private void Errors_SelectionChanged(object sender, SelectionChangedEventArgs e)
  405. {
  406. if (e.AddedItems.Count == 1) GotoLine(e.AddedItems[0].ToString());
  407. }
  408. private void Errors_PreviewMouseDown(object sender, MouseButtonEventArgs e)
  409. {
  410. if (Errors.SelectedItems.Count == 1) GotoLine(Errors.SelectedItems[0].ToString());
  411. }
  412. private void Window_Closing(object sender, CancelEventArgs e)
  413. {
  414. if (bChanged)
  415. {
  416. var bRes = MessageBox.Show("Script has changed. Do you wish to save this script before closing?", "Save Changes",
  417. MessageBoxButton.YesNoCancel);
  418. if (bRes == MessageBoxResult.Cancel)
  419. {
  420. e.Cancel = true;
  421. return;
  422. }
  423. if (bRes == MessageBoxResult.Yes) _onSave?.Invoke(this, EventArgs.Empty);
  424. try
  425. {
  426. DialogResult = bRes == MessageBoxResult.Yes;
  427. }
  428. catch (InvalidOperationException)
  429. {
  430. // Do nothing, just avoids a crash when closing a script editor which was opened by Show();
  431. }
  432. }
  433. }
  434. private void SaveButton_Click(object sender, RoutedEventArgs e)
  435. {
  436. Save();
  437. }
  438. private void CopyButton_Click(object sender, RoutedEventArgs e)
  439. {
  440. Editor.Copy();
  441. }
  442. private void CutButton_Click(object sender, RoutedEventArgs e)
  443. {
  444. Editor.Cut();
  445. }
  446. private void PasteButton_Click(object sender, RoutedEventArgs e)
  447. {
  448. Editor.Paste();
  449. }
  450. private void UndoButton_Click(object sender, RoutedEventArgs e)
  451. {
  452. Editor.Undo();
  453. }
  454. private void RedoButton_Click(object sender, RoutedEventArgs e)
  455. {
  456. Editor.Redo();
  457. }
  458. private void PrintButton_Click(object sender, RoutedEventArgs e)
  459. {
  460. //Syncfusion.Windows.Edit.EditCommands.PrintPreview.Execute(null, Edit1);
  461. }
  462. private void Snippets_MouseDoubleClick(object sender, MouseButtonEventArgs e)
  463. {
  464. Editor.SelectedText = SnippetList.SelectedValue.ToString();
  465. }
  466. private void SnippetSection_SelectionChanged(object sender, SelectionChangedEventArgs e)
  467. {
  468. if (e.AddedItems.Count == 1)
  469. SnippetList.ItemsSource = _snippets[e.AddedItems[0].ToString()];
  470. else
  471. SnippetList.ItemsSource = null;
  472. }
  473. private void SaveCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
  474. {
  475. if (_onSave != null)
  476. {
  477. bChanged = false;
  478. _onSave?.Invoke(this, EventArgs.Empty);
  479. }
  480. }
  481. private void SaveCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
  482. {
  483. e.CanExecute = _onSave != null;
  484. }
  485. private void ShowErrors_Click(object sender, RoutedEventArgs e)
  486. {
  487. ShowErrors = !ShowErrors;
  488. }
  489. private void ShowWarnings_Click(object sender, RoutedEventArgs e)
  490. {
  491. ShowWarnings = !ShowWarnings;
  492. }
  493. #endregion
  494. }
  495. }