MainWindow.xaml.cs 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846
  1. #pragma warning disable CA1822
  2. namespace OINA.Extender.WPF.Testharness
  3. {
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Collections.ObjectModel;
  7. using System.Collections.Specialized;
  8. using System.ComponentModel;
  9. using System.Drawing;
  10. using System.Drawing.Imaging;
  11. using System.Globalization;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Reflection;
  15. using System.Runtime.Serialization;
  16. using System.Text;
  17. using System.Threading;
  18. using System.Windows;
  19. using System.Windows.Controls;
  20. using System.Windows.Resources;
  21. using System.Windows.Threading;
  22. using Microsoft.Win32;
  23. using OINA.Extender.Acquisition;
  24. using OINA.Extender.Acquisition.Ed;
  25. using OINA.Extender.Controls;
  26. using OINA.Extender.Controls.Spectrum;
  27. using OINA.Extender.Data.Ed;
  28. using OINA.Extender.Data.Image;
  29. using OINA.Extender.MonitorControl;
  30. using OINA.Extender.Processing;
  31. using OINA.Extender.Processing.Quant;
  32. using WindowsMedia = System.Windows.Media;
  33. /// <summary>
  34. /// Interaction logic for MainWindow.xaml
  35. /// </summary>
  36. public partial class MainWindow : Window, INotifyPropertyChanged
  37. {
  38. /// <summary>
  39. /// List of ElectronImage objects
  40. /// </summary>
  41. private readonly List<IElectronImage> electronImageList = new List<IElectronImage>();
  42. /// <summary>
  43. /// StringBuilder object
  44. /// </summary>
  45. private StringBuilder sb = new StringBuilder();
  46. /// <summary>
  47. /// The element dictionary
  48. /// </summary>
  49. private Dictionary<int, string> elementDictionary;
  50. /// <summary>
  51. /// The current spectrum acquisitions
  52. /// </summary>
  53. private Dictionary<IEdSpectrum, AcquisitionItem> currentSpectrumAcquisitions;
  54. /// <summary>
  55. /// Acquisition status timer
  56. /// </summary>
  57. private DispatcherTimer acquisitionStatusTimer;
  58. /// <summary>
  59. /// Identify elements timer
  60. /// </summary>
  61. private DispatcherTimer identifyElementsTimer;
  62. /// <summary>
  63. /// The compare spectra ids
  64. /// </summary>
  65. private ObservableCollection<IEdSpectrum> compareSpectra;
  66. /// <summary>
  67. /// The comparison spectra
  68. /// </summary>
  69. private List<IEdSpectrum> comparisonSpectra;
  70. private int dataChangedCount;
  71. private List<DetectorEnableModel> enabledDetectors;
  72. private List<string> identifiedElements;
  73. private string selectedIdentifiedElement;
  74. private QuantAnalysisStatus status;
  75. private string statusMessage;
  76. /// <summary>
  77. /// MainWindow Constructor
  78. /// </summary>
  79. public MainWindow()
  80. {
  81. Application.Current.DispatcherUnhandledException += this.OnCurrentOnDispatcherUnhandledException;
  82. this.compareSpectra = new ObservableCollection<IEdSpectrum>();
  83. this.currentSpectrumAcquisitions = new Dictionary<IEdSpectrum, AcquisitionItem>();
  84. this.InitializeComponent();
  85. this.DataContext = this;
  86. this.LoadComparisonSpectra();
  87. // Binding spectrum acquisition controller events
  88. OIHelper.EdSpectrumAcquisitionController.ExperimentStarted += this.OnEdSpectrumExperimentStarted;
  89. OIHelper.EdSpectrumAcquisitionController.ExperimentFinished += this.OnEdSpectrumExperimentFinished;
  90. // Binding image acquisition controller events
  91. OIHelper.ImageAcquisitionController.ExperimentStarted += this.OnImageExperimentStarted;
  92. OIHelper.ImageAcquisitionController.ExperimentFinished += this.OnImageExperimentFinished;
  93. // Initial UI contents
  94. this.InitialSpectrumSettingsContent();
  95. this.InitialSpectrumViewer();
  96. this.InitialImageSettingsContent();
  97. this.InitialTimers();
  98. this.InitialProcessingSettingsContent();
  99. this.InitialiseElementDictionary();
  100. this.IncludedListBox.DataContext = this.PeriodicTable;
  101. this.UnsetListBox.DataContext = this.PeriodicTable;
  102. this.ExcludedListBox.DataContext = this.PeriodicTable;
  103. this.TableBackColorCombo.DataContext = this.PeriodicTable;
  104. var clearCompareSpectra = new MenuItem
  105. {
  106. Header = @"Clear Compare Spectra",
  107. Visibility = Visibility.Visible,
  108. };
  109. clearCompareSpectra.Click += this.OnClearCompareSpectra;
  110. this.spectrumViewer.ContextMenu.Items.Add(clearCompareSpectra);
  111. this.spectrumViewer.ContextMenu.UpdateLayout();
  112. this.compareSpectrumColor.SelectedColor = GetRandomColor();
  113. this.SortListBox();
  114. this.PeriodicTable.PropertyChanged += this.OnPropertyChanged;
  115. }
  116. /// <summary>
  117. /// Gets the comparison spectra.
  118. /// </summary>
  119. /// <value>
  120. /// The comparison spectra.
  121. /// </value>
  122. public IList<IEdSpectrum> ComparisonSpectra
  123. {
  124. get { return this.comparisonSpectra; }
  125. }
  126. /// <summary>
  127. /// Gets the compare spectra ids.
  128. /// </summary>
  129. /// <value>
  130. /// The compare spectra ids.
  131. /// </value>
  132. public ObservableCollection<IEdSpectrum> CompareSpectra
  133. {
  134. get { return this.compareSpectra; }
  135. }
  136. /// <summary>
  137. /// Gets the element dictionary.
  138. /// </summary>
  139. /// <value>
  140. /// The element dictionary.
  141. /// </value>
  142. public Dictionary<int, string> ElementDictionary
  143. {
  144. get { return this.elementDictionary; }
  145. }
  146. /// <summary>
  147. /// Gets a value indicating whether this instance is acquiring spectrum.
  148. /// </summary>
  149. /// <value>
  150. /// <c>true</c> if this instance is acquiring spectrum; otherwise, <c>false</c>.
  151. /// </value>
  152. public bool IsAcquiringSpectrum
  153. {
  154. get { return OIHelper.EdSpectrumAcquisitionController.IsAcquiring; }
  155. }
  156. /// <summary>
  157. /// The currently selected Exclusion element
  158. /// </summary>
  159. private int currentExclusionElement;
  160. /// <summary>
  161. /// Gets or sets currently selected Exclusion element
  162. /// </summary>
  163. public int CurrentExclusionElement
  164. {
  165. get
  166. {
  167. return this.currentExclusionElement;
  168. }
  169. set
  170. {
  171. if (value == this.currentExclusionElement)
  172. {
  173. return;
  174. }
  175. this.currentExclusionElement = value;
  176. this.RaisePropertyChanged(nameof(this.CurrentExclusionElement));
  177. }
  178. }
  179. /// <summary>
  180. /// Enable or disable Markers on Spectrum
  181. /// </summary>
  182. private bool showMarkers;
  183. public bool ShowMarkers
  184. {
  185. get
  186. {
  187. return this.showMarkers;
  188. }
  189. set
  190. {
  191. if (value == this.showMarkers)
  192. {
  193. return;
  194. }
  195. this.showMarkers = value;
  196. this.ShowHideMarker();
  197. this.RaisePropertyChanged(nameof(this.ShowMarkers));
  198. }
  199. }
  200. /// <summary>
  201. /// Gets or sets currently selected Deconvolution element
  202. /// </summary>
  203. private int currentDeconvolutionElement;
  204. /// <summary>
  205. /// Gets or sets currently selected Deconvolution element
  206. /// </summary>
  207. public int CurrentDeconvolutionElement
  208. {
  209. get
  210. {
  211. return this.currentDeconvolutionElement;
  212. }
  213. set
  214. {
  215. if (value == this.currentDeconvolutionElement)
  216. {
  217. return;
  218. }
  219. this.currentDeconvolutionElement = value;
  220. this.RaisePropertyChanged(nameof(this.CurrentDeconvolutionElement));
  221. }
  222. }
  223. public IEnumerable<IEdDeviceStatus> DeviceStatus
  224. {
  225. get
  226. {
  227. return OIHelper.MonitoringController.EdStatus.Values;
  228. }
  229. }
  230. /// <summary>
  231. /// Handles the DispatcherUnhandledException.
  232. /// Specifically, here it handles the LicenseCheckExceptions which are wrapped in the DispatcherUnhandledException.
  233. /// Shutdowns application when a invalid or missing licence has been found in LicenseCheck.cs.
  234. /// </summary>
  235. /// <param name="obj">Object</param>
  236. /// <param name="args">Event</param>
  237. private void OnCurrentOnDispatcherUnhandledException(object obj, DispatcherUnhandledExceptionEventArgs args)
  238. {
  239. LicenseCheckException ex = args.Exception.InnerException as LicenseCheckException;
  240. if (ex != null)
  241. {
  242. MessageBox.Show(@"This application will shutdown, as a valid license is not available." + Environment.NewLine + ex.Message, @"Error Message", MessageBoxButton.OK, MessageBoxImage.Error);
  243. args.Handled = true;
  244. Application.Current.Shutdown();
  245. }
  246. }
  247. /// <summary>
  248. /// Gets the random color.
  249. /// </summary>
  250. /// <returns>A random color</returns>
  251. private static WindowsMedia.Color GetRandomColor()
  252. {
  253. Random randomGen = new Random();
  254. byte[] values = new byte[3];
  255. randomGen.NextBytes(values);
  256. PropertyInfo[] info = typeof(WindowsMedia.Colors).GetProperties();
  257. PropertyInfo colorInfo = info[randomGen.Next(info.Length)];
  258. WindowsMedia.Color randomColor = (WindowsMedia.Color)WindowsMedia.ColorConverter.ConvertFromString(colorInfo.Name);
  259. return randomColor;
  260. }
  261. #region Event handlers
  262. /// <summary>
  263. /// Called when [clear compare spectra menu item is selected].
  264. /// </summary>
  265. /// <param name="sender">The sender.</param>
  266. /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
  267. private void OnClearCompareSpectra(object sender, RoutedEventArgs e)
  268. {
  269. this.spectrumViewer.ClearComparisonSpectra();
  270. this.compareSpectra.Clear();
  271. }
  272. /// <summary>
  273. /// Acquisition status timer event handler
  274. /// </summary>
  275. /// <param name="sender">sender object</param>
  276. /// <param name="e">EventArgs</param>
  277. private void OnAcquisitionStatusTimer_Tick(object sender, EventArgs e)
  278. {
  279. if (OIHelper.EdSpectrumAcquisitionController.IsAcquiring || OIHelper.ImageAcquisitionController.IsAcquiring)
  280. {
  281. this.lbAcquisitionStatus.Visibility = System.Windows.Visibility.Visible;
  282. }
  283. else
  284. {
  285. this.lbAcquisitionStatus.Visibility = System.Windows.Visibility.Hidden;
  286. }
  287. }
  288. /// <summary>
  289. /// Indentify elements timer event handler
  290. /// </summary>
  291. /// <param name="sender">sender object</param>
  292. /// <param name="e">EventArgs</param>
  293. private void OnIdentifyElementsTimer_Tick(object sender, EventArgs e)
  294. {
  295. this.DoAutoID();
  296. }
  297. /// <summary>
  298. /// Called when [ed spectrum experiment started].
  299. /// </summary>
  300. /// <param name="sender">The sender.</param>
  301. /// <param name="e">The <see cref="AcquisitionFinishedEventArgs{IEdSpectrum}"/> instance containing the event data.</param>
  302. private void OnEdSpectrumExperimentStarted(object sender, AcquisitionStartedEventArgs<IEdSpectrum> e)
  303. {
  304. var edSpectrum = e.Value;
  305. // execute on ui thread
  306. this.Dispatcher.BeginInvoke(() =>
  307. {
  308. this.spectrumViewer.Spectrum = edSpectrum;
  309. // Clear periodic table elements
  310. this.PeriodicTable.ClearAll();
  311. // Update Known Elements
  312. this.PeriodicTable.IncludeElements(OIHelper.AutoIdSettings.KnownElements.ToArray());
  313. });
  314. this.identifyElementsTimer.Tick += this.OnIdentifyElementsTimer_Tick;
  315. this.identifyElementsTimer.Start();
  316. edSpectrum.PropertyChanged += this.OnPropertyChanged;
  317. this.dataChangedCount = 0;
  318. edSpectrum.DataChanged += this.OnEdSpectrumDataChanged;
  319. }
  320. /// <summary>
  321. /// Called when [image experiment started].
  322. /// </summary>
  323. /// <param name="sender">The sender.</param>
  324. /// <param name="e">The instance containing the event data.</param>
  325. private void OnImageExperimentStarted(object sender, AcquisitionStartedEventArgs<IElectronImage[]> e)
  326. {
  327. // execute on UI thread
  328. this.Dispatcher.BeginInvoke(() =>
  329. {
  330. this.imageViewer.DisplayImage = e.Value[0];
  331. });
  332. }
  333. /// <summary>
  334. /// OnExperimentFinished
  335. /// </summary>
  336. /// <param name="sender">sender object</param>
  337. /// <param name="e">The <see cref="AcquisitionFinishedEventArgs{IEdSpectrum}"/> instance containing the event data.</param>
  338. private void OnEdSpectrumExperimentFinished(object sender, AcquisitionFinishedEventArgs<IEdSpectrum> e)
  339. {
  340. e.Value.PropertyChanged -= this.OnPropertyChanged;
  341. e.Value.DataChanged -= this.OnEdSpectrumDataChanged;
  342. this.identifyElementsTimer.Tick -= this.OnIdentifyElementsTimer_Tick;
  343. this.identifyElementsTimer.Stop();
  344. // execute on UI thread
  345. this.Dispatcher.BeginInvoke(() =>
  346. {
  347. this.DoAutoID();
  348. this.UpdatePeriodicTable();
  349. this.DoQuant();
  350. if (this.currentSpectrumAcquisitions.ContainsKey(e.Value))
  351. {
  352. this.AcquisitionQueueListBox.Items.Remove(this.currentSpectrumAcquisitions[e.Value]);
  353. this.currentSpectrumAcquisitions.Remove(e.Value);
  354. }
  355. // *** If this is the last experiment, call EndMultipleAcquisition on the Acquisition
  356. // *** controller, to re-enable external scan switching
  357. if (!this.currentSpectrumAcquisitions.Any())
  358. {
  359. OIHelper.EdSpectrumAcquisitionController.EndMultipleAcquisition();
  360. }
  361. });
  362. }
  363. /// <summary>
  364. /// Called when [image experiment finished].
  365. /// </summary>
  366. /// <param name="sender">The sender.</param>
  367. /// <param name="e">The instance containing the event data.</param>
  368. private void OnImageExperimentFinished(object sender, AcquisitionFinishedEventArgs<IElectronImage[]> e)
  369. {
  370. // execute on UI thread
  371. this.Dispatcher.BeginInvoke(() =>
  372. {
  373. e.Value.ToList().ForEach(i =>
  374. {
  375. this.electronImageList.Remove(i);
  376. this.ImageAcquisitionQueueListBox.Items.Remove(i.Label);
  377. });
  378. });
  379. }
  380. /// <summary>
  381. /// Show or Hide Markers base on Selected Element in Periodic Table
  382. /// </summary>
  383. public void ShowHideMarker()
  384. {
  385. if (this.ShowMarkers)
  386. {
  387. this.spectrumViewer.MarkersElement = this.PeriodicTable.SelectedElement;
  388. }
  389. else
  390. {
  391. this.spectrumViewer.MarkersElement = 0;
  392. }
  393. }
  394. /// <summary>
  395. /// OnPropertyChanged
  396. /// </summary>
  397. /// <param name="sender">Event source</param>
  398. /// <param name="e">Event arguments</param>
  399. private void OnPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
  400. {
  401. var edSpectrum = sender as IEdSpectrum;
  402. if (e.PropertyName == nameof(edSpectrum.RealTimeSeconds))
  403. {
  404. this.Dispatcher.Invoke(() =>
  405. {
  406. this.textRealTimeSeconds.Text = Math.Round(edSpectrum.RealTimeSeconds, 3).ToString(CultureInfo.InvariantCulture);
  407. });
  408. }
  409. else if (e.PropertyName == nameof(edSpectrum.LiveTimeSeconds))
  410. {
  411. this.Dispatcher.Invoke(() =>
  412. {
  413. this.textLiveTimeSeconds.Text = Math.Round(edSpectrum.LiveTimeSeconds, 3).ToString(CultureInfo.InvariantCulture);
  414. });
  415. }
  416. else if (e.PropertyName == nameof(this.PeriodicTable.SelectedElement))
  417. {
  418. this.ShowHideMarker();
  419. }
  420. }
  421. /// <summary>
  422. /// Handles the CollectionChanged event of the IncludedElements.
  423. /// </summary>
  424. /// <param name="sender">The source of the event.</param>
  425. /// <param name="e">The <see cref="NotifyCollectionChangedEventArgs"/> instance containing the event data.</param>
  426. private void IncludedElements_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
  427. {
  428. var spectrum = this.spectrumViewer.Spectrum;
  429. // Update peak labels for included elements
  430. if (spectrum != null)
  431. {
  432. switch (e.Action)
  433. {
  434. case NotifyCollectionChangedAction.Add:
  435. foreach (int i in e.NewItems.Cast<int>())
  436. {
  437. spectrum.SetIdentifiedElement(i, true);
  438. }
  439. break;
  440. case NotifyCollectionChangedAction.Remove:
  441. foreach (int i in e.OldItems.Cast<int>())
  442. {
  443. spectrum.SetIdentifiedElement(i, false);
  444. }
  445. break;
  446. default:
  447. break;
  448. }
  449. this.UpdateSpectrumPeakLabels();
  450. }
  451. }
  452. /// <summary>
  453. /// Update current spectrum peak labels
  454. /// </summary>
  455. private void UpdateSpectrumPeakLabels()
  456. {
  457. try
  458. {
  459. OIHelper.EdSpectrumProcessing.UpdatePeakLabels(this.spectrumViewer.Spectrum, null, Processing.Ed.PeakLabelFormat.Symbol);
  460. }
  461. catch (ArgumentNullException)
  462. {
  463. }
  464. catch (InvalidOperationException)
  465. {
  466. }
  467. }
  468. /// <summary>
  469. /// Sort Listbox
  470. /// </summary>
  471. private void SortListBox()
  472. {
  473. this.IncludedListBox.Items.SortDescriptions.Add(new SortDescription(string.Empty, ListSortDirection.Ascending));
  474. this.ExcludedListBox.Items.SortDescriptions.Add(new SortDescription(string.Empty, ListSortDirection.Ascending));
  475. }
  476. #endregion
  477. #region Update UI Status
  478. /// <summary>
  479. /// Initialise spectrum acquisition settings
  480. /// </summary>
  481. private void InitialSpectrumSettingsContent()
  482. {
  483. if (OIHelper.EdSpectrumSettings.EdCapabilities.HasHardwareConnection)
  484. {
  485. this.tbSpectrumLabel.Text = @"Spectrum 1";
  486. this.cbAcquisitionMode.Items.Add(EdAcquireMode.LiveTime);
  487. this.cbAcquisitionMode.Items.Add(EdAcquireMode.RealTime);
  488. this.cbAcquisitionMode.SelectedIndex = 0;
  489. this.tbAcquisitionTime.Text = @"10000";
  490. this.cbProcessTime.ItemsSource = OIHelper.EdSpectrumSettings.EdCapabilities.AllowedProcessTimes;
  491. this.cbProcessTime.SelectedIndex = 3;
  492. this.cbEnergyRange.ItemsSource = OIHelper.EdSpectrumSettings.EdCapabilities.AllowedEnergyRanges;
  493. this.cbEnergyRange.SelectedIndex = 1;
  494. this.cbNumOfChannels.ItemsSource = OIHelper.EdSpectrumSettings.EdCapabilities.AllowedNumberOfChannels;
  495. this.cbNumOfChannels.SelectedIndex = 1;
  496. this.enabledDetectors = new List<DetectorEnableModel>();
  497. foreach (var kvp in OIHelper.EdSpectrumSettings.EdSettings.IsHardwareEnabled)
  498. {
  499. this.enabledDetectors.Add(new DetectorEnableModel(kvp.Key, kvp.Value));
  500. }
  501. this.enabledDetectors = this.enabledDetectors.OrderBy(x => x.DisplayName).ToList();
  502. this.DetectorListBox.DataContext = this;
  503. this.cbPrimaryDetector.ItemsSource = this.enabledDetectors.Select(x => x.DisplayName).ToList();
  504. this.cbPrimaryDetector.SelectedIndex = 0;
  505. }
  506. }
  507. public IReadOnlyList<DetectorEnableModel> EnabledDetectors
  508. {
  509. get
  510. {
  511. return this.enabledDetectors;
  512. }
  513. }
  514. /// <summary>
  515. /// Initialise SpectrumViewer
  516. /// </summary>
  517. private void InitialSpectrumViewer()
  518. {
  519. this.spectrumViewer.IsXAxisAutoScaleEnabled = false;
  520. this.spectrumViewer.IsYAxisAutoScaleEnabled = true;
  521. }
  522. /// <summary>
  523. /// InitialImageSettingsContent
  524. /// </summary>
  525. private void InitialImageSettingsContent()
  526. {
  527. var settings = OIHelper.ImageSettings;
  528. if (settings.ImageCapabilities.HasHardwareConnection)
  529. {
  530. this.cbImageScanSize.ItemsSource = OIHelper.GetScanSizes(
  531. settings.ScanCapabilities.MinimumPixelSize,
  532. settings.ScanCapabilities.MaximumPixelSize);
  533. this.cbImageScanSize.SelectedIndex = this.cbImageScanSize.Items.Count > 4 ? 4 : this.cbImageScanSize.Items.Count - 1;
  534. this.cbInputSignal.ItemsSource = settings.ImageCapabilities.AllowedInputSources;
  535. this.cbInputSignal.SelectedIndex = 0;
  536. this.tbNumberOfFrames.Text = @"1";
  537. this.tbDwellTime.Text = @"40";
  538. }
  539. }
  540. /// <summary>
  541. /// Initialize Processing settings
  542. /// </summary>
  543. private void InitialProcessingSettingsContent()
  544. {
  545. this.ExcludedListBox.DataContext = this;
  546. ((INotifyCollectionChanged)this.PeriodicTable.IncludedElements).CollectionChanged += this.IncludedElements_CollectionChanged;
  547. this.AllElementsRadioButton.IsChecked = true;
  548. this.CombinedElementTextBox.IsEnabled = false;
  549. this.CombinedElementTextBox.Text = @"8";
  550. this.NumberOfIonsTextBox.IsEnabled = false;
  551. this.NumberOfIonsTextBox.Text = @"3.0";
  552. this.IsCoatedCheckBox.IsChecked = OIHelper.SEMQuantSettings.SampleCoating.IsCoated;
  553. this.CoatingElementTextBox.IsEnabled = OIHelper.SEMQuantSettings.SampleCoating.IsCoated;
  554. this.CoatingElementTextBox.Text = OIHelper.SEMQuantSettings.SampleCoating.CoatingElement.ToString(CultureInfo.InvariantCulture);
  555. this.DensityTextBox.IsEnabled = OIHelper.SEMQuantSettings.SampleCoating.IsCoated;
  556. this.DensityTextBox.Text = OIHelper.SEMQuantSettings.SampleCoating.Density.ToString(CultureInfo.InvariantCulture);
  557. this.ThicknessTextBox.IsEnabled = OIHelper.SEMQuantSettings.SampleCoating.IsCoated;
  558. this.ThicknessTextBox.Text = OIHelper.SEMQuantSettings.SampleCoating.Thickness.ToString(CultureInfo.InvariantCulture);
  559. foreach (int i in OIHelper.SEMQuantSettings.DeconvolutionElements)
  560. {
  561. this.DeconvolutionElementListTextBox.Text += i.ToString(CultureInfo.InvariantCulture) + System.Environment.NewLine;
  562. }
  563. this.ThresholdingCheckBox.IsChecked = false;
  564. this.SigmaLevelTextBox.IsEnabled = false;
  565. this.SigmaLevelTextBox.Text = @"3.0";
  566. }
  567. /// <summary>
  568. /// Initialises the element dictionary.
  569. /// </summary>
  570. private void InitialiseElementDictionary()
  571. {
  572. this.elementDictionary = new Dictionary<int, string>();
  573. for (int elementNo = 1; elementNo <= 103; elementNo++)
  574. {
  575. this.elementDictionary.Add(elementNo, this.PeriodicTable.LookupElementInfo(elementNo).ElementName);
  576. }
  577. this.EnableElementsList.DataContext = this;
  578. }
  579. /// <summary>
  580. /// Initialise acquisition timer
  581. /// </summary>
  582. private void InitialTimers()
  583. {
  584. this.acquisitionStatusTimer = new DispatcherTimer();
  585. this.acquisitionStatusTimer.Tick += new EventHandler(this.OnAcquisitionStatusTimer_Tick);
  586. this.acquisitionStatusTimer.Interval = TimeSpan.FromMilliseconds(100);
  587. this.acquisitionStatusTimer.Start();
  588. this.identifyElementsTimer = new DispatcherTimer();
  589. this.identifyElementsTimer.Interval = TimeSpan.FromMilliseconds(1000);
  590. }
  591. /// <summary>
  592. /// Update the Periodic Table content after acquisition finished
  593. /// </summary>
  594. private void UpdatePeriodicTable()
  595. {
  596. this.PeriodicTable.IncludeElements(this.spectrumViewer.Spectrum.IdentifiedElements.ToArray());
  597. }
  598. #endregion
  599. #region Menu items actions
  600. /// <summary>
  601. /// Exit application
  602. /// </summary>
  603. /// <param name="sender">sender object</param>
  604. /// <param name="e">RoutedEventArgs</param>
  605. private void AppExit(object sender, RoutedEventArgs e)
  606. {
  607. Application.Current.Shutdown();
  608. }
  609. /// <summary>
  610. /// Show detector control panel
  611. /// </summary>
  612. /// <param name="sender">sender object</param>
  613. /// <param name="e">RoutedEventArgs</param>
  614. private void DetectorControl_Click(object sender, RoutedEventArgs e)
  615. {
  616. new DetectorControlPanel(OIHelper.EDDetectorControl) { Owner = this }.Show();
  617. }
  618. /// <summary>
  619. /// Show microscope control panel
  620. /// </summary>
  621. /// <param name="sender">sender object</param>
  622. /// <param name="e">RoutedEventArgs</param>
  623. private void MicroscopeControl_Click(object sender, RoutedEventArgs e)
  624. {
  625. new MicroscopeControlPanel { Owner = this }.Show();
  626. }
  627. /// <summary>
  628. /// Calibrate Click event handler.
  629. /// </summary>
  630. /// <param name="sender">sender</param>
  631. /// <param name="e">RoutedEventArgs</param>
  632. private void Calibrate_Click(object sender, RoutedEventArgs e)
  633. {
  634. new Calibrate { Owner = this }.Show();
  635. }
  636. /// <summary>
  637. /// Auto ID settings Window
  638. /// </summary>
  639. /// <param name="sender">sender object</param>
  640. /// <param name="e">RoutedEventArgs</param>
  641. private void AutoIdSetting_Click(object sender, RoutedEventArgs e)
  642. {
  643. new AutoIdSettings { Owner = this }.Show();
  644. }
  645. /// <summary>
  646. /// Handles the Click event of the PeriodicTableSettings menu item.
  647. /// </summary>
  648. /// <param name="sender">The source of the event.</param>
  649. /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
  650. private void PeriodicTableSettings_Click(object sender, RoutedEventArgs e)
  651. {
  652. new PeriodicTableVisualSettings { Owner = this, ShowInTaskbar = false }.Show();
  653. }
  654. /// <summary>
  655. /// Handles the Click event of the SpectrumViewerSettings menu item.
  656. /// </summary>
  657. /// <param name="sender">The source of the event.</param>
  658. /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
  659. private void SpectrumViewerSettings_Click(object sender, RoutedEventArgs e)
  660. {
  661. new SpectrumViewerVisualSettings { Owner = this, ShowInTaskbar = false }.Show();
  662. }
  663. /// <summary>
  664. /// Handles the Click event of the ImageViewerSettings menu item.
  665. /// </summary>
  666. /// <param name="sender">The source of the event.</param>
  667. /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
  668. private void ImageViewerSettings_Click(object sender, RoutedEventArgs e)
  669. {
  670. new ImageViewerVisualSettings { Owner = this, ShowInTaskbar = false }.Show();
  671. }
  672. /// <summary>
  673. /// Handles the Click event of the ElementComboSettings menu item.
  674. /// </summary>
  675. /// <param name="sender">The source of the event.</param>
  676. /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
  677. private void ElementComboSettings_Click(object sender, RoutedEventArgs e)
  678. {
  679. new ElementComboVisualSettings { Owner = this, ShowInTaskbar = false }.Show();
  680. }
  681. /// <summary>
  682. /// Handles the Click event of the BC Dialog settings menu item.
  683. /// </summary>
  684. /// <param name="sender">The source of the event.</param>
  685. /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
  686. private void BCDialogSettings_Click(object sender, RoutedEventArgs e)
  687. {
  688. new BCDialogVisualSettings { Owner = this, ShowInTaskbar = false }.Show();
  689. }
  690. /// <summary>
  691. /// Handles the Click event of the DetailDialogsVisualStyles control.
  692. /// </summary>
  693. /// <param name="sender">The source of the event.</param>
  694. /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
  695. private void DetailsDialogVisualStyles_Click(object sender, RoutedEventArgs e)
  696. {
  697. new DetailDialogVisualSettings { Owner = this, ShowInTaskbar = false }.Show();
  698. }
  699. /// <summary>
  700. /// Handles the Click event of the elementComboVisualSettingsToolStripMenuItem control.
  701. /// </summary>
  702. /// <param name="sender">The source of the event.</param>
  703. /// <param name="e">instance containing the event data.</param>
  704. private void ExportSpectrumAs_Click(object sender, RoutedEventArgs e)
  705. {
  706. try
  707. {
  708. short width = (short)this.spectrumViewer.ActualWidth;
  709. short height = (short)this.spectrumViewer.ActualHeight;
  710. Bitmap bitmap = OIHelper.EdSpectrumProcessing.CreateBitmap(this.spectrumViewer.Spectrum, width, height);
  711. SaveFileDialog exportSpectrumDialog = new SaveFileDialog();
  712. exportSpectrumDialog.Filter = @"Bitmap (*.bmp)|*.bmp|PNG (*.png)|*.png|TIFF (*.tif)|*.tif|JPEG (*.jpg)|*.jpg";
  713. exportSpectrumDialog.Title = @"Export Spectrum As...";
  714. if (exportSpectrumDialog.ShowDialog() == true)
  715. {
  716. switch (exportSpectrumDialog.FilterIndex)
  717. {
  718. case 1:
  719. bitmap.Save(exportSpectrumDialog.FileName, ImageFormat.Bmp);
  720. break;
  721. case 2:
  722. bitmap.Save(exportSpectrumDialog.FileName, ImageFormat.Png);
  723. break;
  724. case 3:
  725. bitmap.Save(exportSpectrumDialog.FileName, ImageFormat.Tiff);
  726. break;
  727. case 4:
  728. bitmap.Save(exportSpectrumDialog.FileName, ImageFormat.Jpeg);
  729. break;
  730. default:
  731. bitmap.Save(exportSpectrumDialog.FileName, ImageFormat.Bmp);
  732. break;
  733. }
  734. }
  735. }
  736. catch (ArgumentException)
  737. {
  738. }
  739. }
  740. /// <summary>
  741. /// LoadSpectrumData menuitem click event
  742. /// </summary>
  743. /// <param name="sender">sender object</param>
  744. /// <param name="e">RoutedEventArgs</param>
  745. private void LoadSpectrumData_Click(object sender, RoutedEventArgs e)
  746. {
  747. var of_dlg = new OpenFileDialog();
  748. of_dlg.Title = @"Select a file";
  749. of_dlg.Filter = @"Esd(*.esd)|*.esd|Iex(*.iex)|*.iex";
  750. of_dlg.FilterIndex = 1;
  751. if (of_dlg.ShowDialog() == true)
  752. {
  753. if (!File.Exists(of_dlg.FileName))
  754. {
  755. throw new InvalidOperationException("File does not exists!");
  756. }
  757. this.spectrumViewer.ClearComparisonSpectra();
  758. switch (of_dlg.FilterIndex)
  759. {
  760. case 1:
  761. this.spectrumViewer.Spectrum = DataFactory.LoadEdSpectrum(OIHelper.FileToByteArray(of_dlg.FileName));
  762. break;
  763. case 2:
  764. this.spectrumViewer.Spectrum = DataFactory.LoadEdSpectrumFromIex(of_dlg.FileName);
  765. break;
  766. }
  767. // Initial Periodic table to show the element state
  768. this.PeriodicTable.ClearAll();
  769. this.PeriodicTable.IncludeElements(this.spectrumViewer.Spectrum.IdentifiedElements.ToArray());
  770. }
  771. }
  772. /// <summary>
  773. /// SaveSpectrumData menuitem click event
  774. /// </summary>
  775. /// <param name="sender">sender object</param>
  776. /// <param name="e">RoutedEventArgs</param>
  777. private void SaveSpectrumData_Click(object sender, RoutedEventArgs e)
  778. {
  779. var spectrum = this.spectrumViewer.Spectrum;
  780. if (spectrum != null)
  781. {
  782. try
  783. {
  784. var sf_dlg = new SaveFileDialog();
  785. sf_dlg.Title = @"Save spectrum as";
  786. sf_dlg.Filter = @"Esd(*.esd)|*.esd|Iex(*.iex)|*.iex";
  787. sf_dlg.FilterIndex = 1;
  788. if (sf_dlg.ShowDialog() == true)
  789. {
  790. switch (sf_dlg.FilterIndex)
  791. {
  792. case 1:
  793. byte[] spectrumData = spectrum.Save();
  794. OIHelper.ByteArrayToFile(sf_dlg.FileName, spectrumData);
  795. break;
  796. case 2:
  797. OIHelper.EdSpectrumProcessing.CreateIexSpectrum(sf_dlg.FileName, spectrum);
  798. break;
  799. }
  800. }
  801. }
  802. catch (ArgumentException)
  803. {
  804. }
  805. }
  806. }
  807. /// <summary>
  808. /// LoadImageData_Click
  809. /// </summary>
  810. /// <param name="sender">sender object</param>
  811. /// <param name="e">RoutedEventArgs</param>
  812. private void LoadImageData_Click(object sender, RoutedEventArgs e)
  813. {
  814. try
  815. {
  816. OpenFileDialog of_dlg = new OpenFileDialog();
  817. of_dlg.Title = @"Select a file";
  818. of_dlg.Filter = @"Img(*.img)|*.img";
  819. of_dlg.FilterIndex = 1;
  820. if (of_dlg.ShowDialog() == true)
  821. {
  822. if (!File.Exists(of_dlg.FileName))
  823. {
  824. throw new System.InvalidOperationException("File does not exists!");
  825. }
  826. this.imageViewer.DisplayImage = DataFactory.LoadElectronImage(OIHelper.FileToByteArray(of_dlg.FileName));
  827. }
  828. }
  829. catch (SerializationException)
  830. {
  831. }
  832. }
  833. /// <summary>
  834. /// SaveImageData_Click
  835. /// </summary>
  836. /// <param name="sender">sender object</param>
  837. /// <param name="e">RoutedEventArgs</param>
  838. private void SaveImageData_Click(object sender, RoutedEventArgs e)
  839. {
  840. string filter = @"Img(*.img)|*.img";
  841. string title = @"Save image as";
  842. if (this.imageViewer.DisplayImage != null)
  843. {
  844. try
  845. {
  846. var electronImage = this.imageViewer.DisplayImage;
  847. SaveFileDialog sf_dlg = new SaveFileDialog();
  848. sf_dlg.Filter = filter;
  849. sf_dlg.Title = title;
  850. sf_dlg.FilterIndex = 1;
  851. if (sf_dlg.ShowDialog() == true)
  852. {
  853. byte[] imageData = electronImage.Save();
  854. OIHelper.ByteArrayToFile(sf_dlg.FileName, imageData);
  855. }
  856. }
  857. catch (ArgumentException)
  858. {
  859. }
  860. }
  861. }
  862. /// <summary>
  863. /// ChordListAcquire_Click
  864. /// </summary>
  865. /// <param name="sender">sender object</param>
  866. /// <param name="e">RoutedEventArgs</param>
  867. private void ChordListAcquire_Click(object sender, RoutedEventArgs e)
  868. {
  869. try
  870. {
  871. Window edChordListAcquireWindow = new EdChordListAcquisition()
  872. {
  873. Owner = this,
  874. WindowStartupLocation = WindowStartupLocation.CenterOwner,
  875. };
  876. edChordListAcquireWindow.ShowDialog();
  877. }
  878. catch (LicenseCheckException)
  879. {
  880. MessageBox.Show(@"Not supported by the license");
  881. }
  882. }
  883. #endregion
  884. #region Control from UI
  885. /// <summary>
  886. /// Start spectrum acquisition
  887. /// </summary>
  888. /// <param name="sender">sender object</param>
  889. /// <param name="e">RoutedEventArgs</param>
  890. private void StartAcquisition(object sender, RoutedEventArgs e)
  891. {
  892. this.spectrumViewer.ClearComparisonSpectra();
  893. this.AcquireSpectrum(false);
  894. }
  895. /// <summary>
  896. /// Resume spectrum acquisition
  897. /// </summary>
  898. /// <param name="sender">sender object</param>
  899. /// <param name="e">RoutedEventArgs</param>
  900. private void ResumeAcquisitionButton_Click(object sender, RoutedEventArgs e)
  901. {
  902. if (this.spectrumViewer.Spectrum != null && !this.IsAcquiringSpectrum)
  903. {
  904. this.AcquireSpectrum(true);
  905. }
  906. }
  907. /// <summary>
  908. /// Adds a spectrum for comparison
  909. /// </summary>
  910. /// <param name="sender">The source of the event.</param>
  911. /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
  912. private void OnAddCompareSpectraButtonClick(object sender, RoutedEventArgs e)
  913. {
  914. var spectrum = this.cbCompareSpectra.SelectedItem as IEdSpectrum;
  915. if (spectrum != null)
  916. {
  917. ////add current spectrum to compare spectrum
  918. this.spectrumViewer.AddComparisonSpectrum(spectrum, this.compareSpectrumColor.SelectedColor);
  919. this.compareSpectra.Add(spectrum);
  920. this.compareSpectrumColor.SelectedColor = GetRandomColor();
  921. }
  922. }
  923. /// <summary>
  924. /// Acquires the spectrum.
  925. /// </summary>
  926. /// <param name="isResume">if set to <c>true</c> [is resume].</param>
  927. private void AcquireSpectrum(bool isResume)
  928. {
  929. IEdSpectrum edSpectrum = null;
  930. // Spectrum acquisition settings confirm
  931. var edSpectrumSettings = OIHelper.EdSpectrumSettings;
  932. var edSpectrumAcquisitionController = OIHelper.EdSpectrumAcquisitionController;
  933. edSpectrumSettings.EdSettings.AcquisitionMode = (EdAcquireMode)this.cbAcquisitionMode.SelectedItem;
  934. edSpectrumSettings.EdSettings.AcquisitionTime = TimeSpan.FromMilliseconds(int.Parse(this.tbAcquisitionTime.Text, CultureInfo.CurrentCulture));
  935. if (edSpectrumSettings.EdSettings.AcquisitionTime > edSpectrumSettings.EdCapabilities.MaximumAcquisitionTime)
  936. {
  937. edSpectrumSettings.EdSettings.AcquisitionTime = edSpectrumSettings.EdCapabilities.MaximumAcquisitionTime;
  938. this.tbAcquisitionTime.Text = edSpectrumSettings.EdSettings.AcquisitionTime.TotalMilliseconds.ToString(CultureInfo.CurrentCulture);
  939. }
  940. if (edSpectrumSettings.EdSettings.AcquisitionTime < edSpectrumSettings.EdCapabilities.MinimumAcquisitionTime)
  941. {
  942. edSpectrumSettings.EdSettings.AcquisitionTime = edSpectrumSettings.EdCapabilities.MinimumAcquisitionTime;
  943. this.tbAcquisitionTime.Text = edSpectrumSettings.EdSettings.AcquisitionTime.TotalSeconds.ToString(CultureInfo.CurrentCulture);
  944. }
  945. edSpectrumSettings.EdSettings.ProcessTime = (int)this.cbProcessTime.SelectedValue;
  946. edSpectrumSettings.EdSettings.EnergyRange = (int)this.cbEnergyRange.SelectedValue;
  947. edSpectrumSettings.EdSettings.NumberOfChannels = (int)this.cbNumOfChannels.SelectedValue;
  948. // Enable the appropriate detectors
  949. foreach (var item in this.EnabledDetectors)
  950. {
  951. edSpectrumSettings.EdSettings.EnableDevice(item.EdHardwareId, item.IsDetectorEnabled);
  952. }
  953. int selectedIndex = this.cbPrimaryDetector.SelectedIndex;
  954. if (selectedIndex >= 0 && selectedIndex < this.EnabledDetectors.Count)
  955. {
  956. DetectorEnableModel primaryDetectorModel = this.EnabledDetectors[selectedIndex];
  957. edSpectrumSettings.EdSettings.PrimaryHardwareId = primaryDetectorModel.EdHardwareId;
  958. edSpectrumSettings.EdSettings.EnableDevice(primaryDetectorModel.EdHardwareId, true);
  959. primaryDetectorModel.IsDetectorEnabled = true; // ensure the ui reflects settings
  960. }
  961. edSpectrumSettings.ScanSettings.AcquisitionRegion.CreateMicroscopeRegion();
  962. this.spectrumViewer.MaximumEnergy = edSpectrumSettings.EdSettings.EnergyRange;
  963. // If Ed hardware is not ready, the software will crash.
  964. if (edSpectrumAcquisitionController.IsEdHardwareReady(OIHelper.EdSpectrumSettings))
  965. {
  966. // *** If this is the first acquisition, call BeginMultipleAcquisition
  967. // *** on the AcquisitionController to suppress external scan switching
  968. if (!this.currentSpectrumAcquisitions.Any())
  969. {
  970. edSpectrumAcquisitionController.BeginMultipleAcquisition();
  971. }
  972. if (!isResume)
  973. {
  974. try
  975. {
  976. edSpectrum = edSpectrumAcquisitionController.StartAcquisition(edSpectrumSettings);
  977. edSpectrum.Label = string.Format(CultureInfo.CurrentCulture, @"{0} ({1:HH:mm:ss})", this.tbSpectrumLabel.Text, DateTime.Now);
  978. }
  979. catch (InvalidSettingsException invalidSettingsException)
  980. {
  981. MessageBox.Show(invalidSettingsException.Message);
  982. }
  983. catch (AcquisitionStartException acquisitionStartException)
  984. {
  985. MessageBox.Show(acquisitionStartException.Message);
  986. }
  987. }
  988. else
  989. {
  990. edSpectrumAcquisitionController.ResumeAcquisition(edSpectrumSettings, this.spectrumViewer.Spectrum);
  991. edSpectrum = this.spectrumViewer.Spectrum;
  992. }
  993. if (edSpectrum != null)
  994. {
  995. this.currentSpectrumAcquisitions.Add(edSpectrum, new AcquisitionItem(edSpectrum, OIHelper.EdSpectrumSettings.EdSettings.AcquisitionMode, OIHelper.EdSpectrumSettings.EdSettings.AcquisitionTime.TotalMilliseconds));
  996. this.AcquisitionQueueListBox.Items.Add(this.currentSpectrumAcquisitions[edSpectrum]);
  997. }
  998. }
  999. }
  1000. private void OnEdSpectrumDataChanged(object sender, EventArgs e)
  1001. {
  1002. // execute on ui thread
  1003. this.Dispatcher.BeginInvoke(() =>
  1004. {
  1005. this.dataChangedCount++;
  1006. this.lbDataChanged.Content = string.Format(CultureInfo.InvariantCulture, @"Data Changed: ({0})", this.dataChangedCount);
  1007. });
  1008. }
  1009. /// <summary>
  1010. /// StopAcquisition
  1011. /// </summary>
  1012. /// <param name="sender">sender object</param>
  1013. /// <param name="e">RoutedEventArgs</param>
  1014. private void StopAcquisition(object sender, RoutedEventArgs e)
  1015. {
  1016. if (OIHelper.EdSpectrumAcquisitionController.IsAcquiring == true)
  1017. {
  1018. OIHelper.EdSpectrumAcquisitionController.StopAcquisition();
  1019. }
  1020. }
  1021. /// <summary>
  1022. /// Handles the Click event of btStartImageScan button.
  1023. /// </summary>
  1024. /// <param name="sender">The source of the event.</param>
  1025. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  1026. private void StartImageScan_Click(object sender, EventArgs e)
  1027. {
  1028. // Image acquisition settings comfirm
  1029. var imageSettings = OIHelper.ImageSettings.ImageSettings;
  1030. var imageCapabilities = OIHelper.ImageSettings.ImageCapabilities;
  1031. var scanSettings = OIHelper.ImageSettings.ScanSettings;
  1032. var imageAcquisitionController = OIHelper.ImageAcquisitionController;
  1033. this.tbImageData.Text = string.Empty;
  1034. int value = int.Parse(this.tbDwellTime.Text, CultureInfo.InvariantCulture);
  1035. if (value > imageCapabilities.MaximumImageDwellMicroseconds)
  1036. {
  1037. imageSettings.DwellTimeMicroSeconds = imageCapabilities.MaximumImageDwellMicroseconds;
  1038. }
  1039. if (value < imageCapabilities.MinimumImageDwellMicroseconds)
  1040. {
  1041. imageSettings.DwellTimeMicroSeconds = imageCapabilities.MinimumImageDwellMicroseconds;
  1042. }
  1043. else
  1044. {
  1045. imageSettings.DwellTimeMicroSeconds = value;
  1046. }
  1047. // *** Disable all input sources before enabling the one that the user has chosen
  1048. imageSettings.InputSources.ToList().ForEach(i => imageSettings.EnableInputSource(i.Key, false));
  1049. imageSettings.EnableInputSource((ImageInputSources)this.cbInputSignal.SelectedItem, true);
  1050. scanSettings.FrameCount = int.Parse(this.tbNumberOfFrames.Text, CultureInfo.InvariantCulture);
  1051. var pixelSize = 1d / double.Parse(this.cbImageScanSize.Text, CultureInfo.InvariantCulture);
  1052. scanSettings.AcquisitionRegion.CreateFullFieldRegion(pixelSize);
  1053. var images = imageAcquisitionController.StartAcquisition(OIHelper.ImageSettings).ToList();
  1054. images.ForEach(i =>
  1055. {
  1056. i.Label = string.Format(CultureInfo.CurrentCulture, @"{0} ({1:HH:mm:ss})", @"ElectronImage", DateTime.Now);
  1057. this.electronImageList.Add(i);
  1058. this.ImageAcquisitionQueueListBox.Items.Add(i.Label);
  1059. });
  1060. }
  1061. /// <summary>
  1062. /// Handles the Click event of btStopImageScan button.
  1063. /// </summary>
  1064. /// <param name="sender">The source of the event.</param>
  1065. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  1066. private void StopImageScan_Click(object sender, EventArgs e)
  1067. {
  1068. if (OIHelper.ImageAcquisitionController.IsAcquiring)
  1069. {
  1070. OIHelper.ImageAcquisitionController.StopAcquisition();
  1071. }
  1072. }
  1073. /// <summary>
  1074. /// AutoID elements.
  1075. /// </summary>
  1076. /// <param name="sender">sender object</param>
  1077. /// <param name="e">RoutedEventArgs</param>
  1078. private void AutoIdButton_Click(object sender, RoutedEventArgs e)
  1079. {
  1080. this.DoAutoID();
  1081. }
  1082. /// <summary>
  1083. /// Do AutoID
  1084. /// </summary>
  1085. private void DoAutoID()
  1086. {
  1087. var elements = new List<string>();
  1088. var spectrum = this.spectrumViewer.Spectrum;
  1089. if (spectrum != null)
  1090. {
  1091. elements = OIHelper.EdSpectrumProcessing.IdentifyElements(spectrum, OIHelper.AutoIdSettings)
  1092. .Select(i => ElementProperties.GetElementSymbol(i))
  1093. .ToList();
  1094. // Update spectrum peak label
  1095. this.UpdateSpectrumPeakLabels();
  1096. }
  1097. this.IdentifiedElements = elements;
  1098. this.SelectedIdentifiedElement = elements.FirstOrDefault();
  1099. }
  1100. public IReadOnlyList<string> IdentifiedElements
  1101. {
  1102. get
  1103. {
  1104. return this.identifiedElements;
  1105. }
  1106. set
  1107. {
  1108. this.identifiedElements = value.ToList();
  1109. this.RaisePropertyChanged(nameof(this.IdentifiedElements));
  1110. }
  1111. }
  1112. public string SelectedIdentifiedElement
  1113. {
  1114. get
  1115. {
  1116. return this.selectedIdentifiedElement;
  1117. }
  1118. set
  1119. {
  1120. this.selectedIdentifiedElement = value;
  1121. this.RaisePropertyChanged(nameof(this.SelectedIdentifiedElement));
  1122. }
  1123. }
  1124. /// <summary>
  1125. /// Confirm excluded element
  1126. /// </summary>
  1127. /// <param name="sender">sender object</param>
  1128. /// <param name="e">EventArgs</param>
  1129. private void AddElementButton_Click(object sender, RoutedEventArgs e)
  1130. {
  1131. try
  1132. {
  1133. this.PeriodicTable.ExcludeElements(this.CurrentExclusionElement);
  1134. }
  1135. catch (FormatException fe)
  1136. {
  1137. MessageBox.Show(@"Please enter valid element!" + fe.Message);
  1138. }
  1139. }
  1140. /// <summary>
  1141. /// Detete Excluded Elements
  1142. /// </summary>
  1143. /// <param name="sender">sender object</param>
  1144. /// <param name="e">EventArgs</param>
  1145. private void RemoveElementButton_Click(object sender, RoutedEventArgs e)
  1146. {
  1147. try
  1148. {
  1149. this.PeriodicTable.Clear(this.CurrentExclusionElement);
  1150. }
  1151. catch (FormatException fe)
  1152. {
  1153. MessageBox.Show(@"Please enter valid element!" + fe.Message);
  1154. }
  1155. }
  1156. /// <summary>
  1157. /// Clear Excluded element list
  1158. /// </summary>
  1159. /// <param name="sender">sender object</param>
  1160. /// <param name="e">EventArgs</param>
  1161. private void ClearButton_Click(object sender, RoutedEventArgs e)
  1162. {
  1163. this.PeriodicTable.ClearAll();
  1164. }
  1165. /// <summary>
  1166. /// Do quant button click handler.
  1167. /// </summary>
  1168. /// <param name="sender">sender</param>
  1169. /// <param name="e">RoutedEventArgs</param>
  1170. private void QuantButton_Click(object sender, RoutedEventArgs e)
  1171. {
  1172. this.DoQuant();
  1173. }
  1174. /// <summary>
  1175. /// Do quantitative processing and display
  1176. /// </summary>
  1177. private void DoQuant()
  1178. {
  1179. switch (OIHelper.SEMQuantSettings.ProcessingOption)
  1180. {
  1181. case ProcessingOption.ElementByDifference:
  1182. OIHelper.SEMQuantSettings.CombinedElement = int.Parse(this.CombinedElementTextBox.Text, CultureInfo.InvariantCulture);
  1183. break;
  1184. case ProcessingOption.ElementByStoichiometry:
  1185. // While it is possible to choose other elements, Oxygen is the only supported element by stoichiometry.
  1186. OIHelper.SEMQuantSettings.CombinedElement = 8;
  1187. OIHelper.SEMQuantSettings.TypeOfIon = IonType.Anion;
  1188. OIHelper.SEMQuantSettings.NumberOfIons = double.Parse(this.NumberOfIonsTextBox.Text, CultureInfo.InvariantCulture);
  1189. break;
  1190. case ProcessingOption.AllElements:
  1191. default:
  1192. break;
  1193. }
  1194. if (this.IsCoatedCheckBox.IsChecked == true)
  1195. {
  1196. OIHelper.SEMQuantSettings.SampleCoating.IsCoated = true;
  1197. OIHelper.SEMQuantSettings.SampleCoating.Thickness = double.Parse(this.ThicknessTextBox.Text, CultureInfo.InvariantCulture);
  1198. OIHelper.SEMQuantSettings.SampleCoating.Density = double.Parse(this.DensityTextBox.Text, CultureInfo.InvariantCulture);
  1199. OIHelper.SEMQuantSettings.SampleCoating.CoatingElement = int.Parse(this.CoatingElementTextBox.Text, CultureInfo.InvariantCulture);
  1200. }
  1201. else
  1202. {
  1203. OIHelper.SEMQuantSettings.SampleCoating.IsCoated = false;
  1204. this.ThicknessTextBox.IsEnabled = false;
  1205. this.DensityTextBox.IsEnabled = false;
  1206. }
  1207. if (this.ThresholdingCheckBox.IsChecked == true)
  1208. {
  1209. OIHelper.SEMQuantSettings.Thresholding = true;
  1210. OIHelper.SEMQuantSettings.SigmaLevel = double.Parse(this.SigmaLevelTextBox.Text, CultureInfo.InvariantCulture);
  1211. }
  1212. else
  1213. {
  1214. OIHelper.SEMQuantSettings.Thresholding = false;
  1215. this.SigmaLevelTextBox.IsEnabled = false;
  1216. }
  1217. OIHelper.SEMQuantSettings.Normalised = this.NormalisedCheckBox.IsChecked.Value;
  1218. this.QuantResultDataGrid.Items.Clear();
  1219. try
  1220. {
  1221. ISEMQuantStatus status = OIHelper.EdSpectrumProcessing.SEMQuantifySpectrum(this.spectrumViewer.Spectrum, OIHelper.SEMQuantSettings);
  1222. this.Status = status.Status;
  1223. this.StatusMessage = status.StatusMessage;
  1224. double totalWeightPercent = 0;
  1225. double totalAtomicPercent = 0;
  1226. foreach (ISEMQuantResult result in status.Results)
  1227. {
  1228. if (result.IsQuantLine)
  1229. {
  1230. var elementRow = new DataGridRow();
  1231. elementRow.Item = new
  1232. {
  1233. Element = ElementProperties.GetElementSymbol(result.AtomicNumber),
  1234. Line = result.LineType,
  1235. WtPcent = Math.Round(result.WeightPercent, 2),
  1236. WtSigma = Math.Round(result.WeightPercentSigma, 6),
  1237. AtPcent = Math.Round(result.AtomicPercent, 2),
  1238. };
  1239. this.QuantResultDataGrid.Items.Add(elementRow);
  1240. }
  1241. totalWeightPercent += result.WeightPercent;
  1242. totalAtomicPercent += result.AtomicPercent;
  1243. }
  1244. var totalRow = new DataGridRow();
  1245. totalRow.Item = new
  1246. {
  1247. Element = @"Total",
  1248. WtPcent = Math.Round(totalWeightPercent, 2),
  1249. AtPcent = Math.Round(totalAtomicPercent, 2),
  1250. };
  1251. this.QuantResultDataGrid.Items.Add(totalRow);
  1252. this.spectrumViewer.SEMQuantify(OIHelper.SEMQuantSettings);
  1253. }
  1254. catch (QuantificationException ex)
  1255. {
  1256. MessageBox.Show(ex.Message, @"Quantification Error", MessageBoxButton.OK, MessageBoxImage.Warning);
  1257. }
  1258. catch (ArgumentNullException)
  1259. {
  1260. }
  1261. }
  1262. public QuantAnalysisStatus Status
  1263. {
  1264. get
  1265. {
  1266. return this.status;
  1267. }
  1268. set
  1269. {
  1270. this.status = value;
  1271. this.RaisePropertyChanged(nameof(this.Status));
  1272. }
  1273. }
  1274. public string StatusMessage
  1275. {
  1276. get
  1277. {
  1278. return this.statusMessage;
  1279. }
  1280. set
  1281. {
  1282. this.statusMessage = value;
  1283. this.RaisePropertyChanged(nameof(this.StatusMessage));
  1284. }
  1285. }
  1286. private void CurrentSpectrumRadioButton_Click(object sender, RoutedEventArgs e)
  1287. {
  1288. OIHelper.SEMQuantSettings.TypeOfElementList = ElementListType.CurrentSpectrum;
  1289. this.FixedListRadioButton.IsChecked = false;
  1290. this.CurrentAndFixed.IsChecked = false;
  1291. }
  1292. private void FixedList_Click(object sender, RoutedEventArgs e)
  1293. {
  1294. OIHelper.SEMQuantSettings.TypeOfElementList = ElementListType.Fixed;
  1295. // Set the element as an example of fixed list
  1296. OIHelper.SEMQuantSettings.SetElement(72, true);
  1297. this.CurrentAndFixed.IsChecked = false;
  1298. this.CurrentSpectrumRadioButton.IsChecked = false;
  1299. }
  1300. private void CurrentAndFixed_Click(object sender, RoutedEventArgs e)
  1301. {
  1302. OIHelper.SEMQuantSettings.TypeOfElementList = ElementListType.FixedAndCurrentSpectrum;
  1303. this.FixedListRadioButton.IsChecked = false;
  1304. this.CurrentSpectrumRadioButton.IsChecked = false;
  1305. }
  1306. /// <summary>
  1307. /// Used when processing spectra from specimens in which all elements yield X-rays which can be readily detected.
  1308. /// </summary>
  1309. /// <param name="sender">sender object</param>
  1310. /// <param name="e">EventArgs</param>
  1311. private void AllElementsRadioButton_Click(object sender, RoutedEventArgs e)
  1312. {
  1313. OIHelper.SEMQuantSettings.ProcessingOption = ProcessingOption.AllElements;
  1314. this.NormalisedCheckBox.IsEnabled = true;
  1315. this.CombinedElementTextBox.IsEnabled = false;
  1316. this.NumberOfIonsTextBox.IsEnabled = false;
  1317. }
  1318. /// <summary>
  1319. /// Calculated assuming that the difference between the analyzed total and 100%
  1320. /// </summary>
  1321. /// <param name="sender">sender object</param>
  1322. /// <param name="e">EventArgs</param>
  1323. private void ElementByDifferenceRadioButton_Click(object sender, RoutedEventArgs e)
  1324. {
  1325. OIHelper.SEMQuantSettings.ProcessingOption = ProcessingOption.ElementByDifference;
  1326. this.NormalisedCheckBox.IsChecked = false;
  1327. this.NormalisedCheckBox.IsEnabled = false;
  1328. this.CombinedElementTextBox.IsEnabled = true;
  1329. this.NumberOfIonsTextBox.IsEnabled = false;
  1330. }
  1331. /// <summary>
  1332. /// Concentration of oxygen to be calculated.
  1333. /// </summary>
  1334. /// <param name="sender">sender object</param>
  1335. /// <param name="e">EventArgs</param>
  1336. private void ElementByStoichiometryRadioButton_Click(object sender, RoutedEventArgs e)
  1337. {
  1338. OIHelper.SEMQuantSettings.ProcessingOption = ProcessingOption.ElementByStoichiometry;
  1339. this.NormalisedCheckBox.IsEnabled = true;
  1340. this.CombinedElementTextBox.IsEnabled = false;
  1341. this.NumberOfIonsTextBox.IsEnabled = true;
  1342. }
  1343. /// <summary>
  1344. /// Add deconvolution element to list
  1345. /// </summary>
  1346. /// <param name="sender">sender object</param>
  1347. /// <param name="e">EventArgs</param>
  1348. private void AddDeconvolutionButton_Click(object sender, RoutedEventArgs e)
  1349. {
  1350. this.DeconvolutionElementListTextBox.Clear();
  1351. try
  1352. {
  1353. OIHelper.SEMQuantSettings.SetDeconvolutionElement(this.CurrentDeconvolutionElement, true);
  1354. foreach (int i in OIHelper.SEMQuantSettings.DeconvolutionElements)
  1355. {
  1356. this.DeconvolutionElementListTextBox.Text += i.ToString(CultureInfo.InvariantCulture) + Environment.NewLine;
  1357. }
  1358. }
  1359. catch (FormatException fe)
  1360. {
  1361. this.DeconvolutionElementListTextBox.Text = fe.Message;
  1362. }
  1363. catch (ArgumentOutOfRangeException ae)
  1364. {
  1365. this.DeconvolutionElementListTextBox.Text = ae.Message;
  1366. }
  1367. }
  1368. /// <summary>
  1369. /// Remove 1 deconvolution element from elment list.
  1370. /// </summary>
  1371. /// <param name="sender">sender</param>
  1372. /// <param name="e">RoutedEventArgs</param>
  1373. private void DeconvolutionRemoveButton_Click(object sender, RoutedEventArgs e)
  1374. {
  1375. this.DeconvolutionElementListTextBox.Clear();
  1376. try
  1377. {
  1378. OIHelper.SEMQuantSettings.SetDeconvolutionElement(this.CurrentDeconvolutionElement, false);
  1379. foreach (int i in OIHelper.SEMQuantSettings.DeconvolutionElements)
  1380. {
  1381. this.DeconvolutionElementListTextBox.Text += i.ToString(CultureInfo.InvariantCulture) + Environment.NewLine;
  1382. }
  1383. }
  1384. catch (FormatException fe)
  1385. {
  1386. this.DeconvolutionElementListTextBox.Text = fe.Message;
  1387. }
  1388. }
  1389. /// <summary>
  1390. /// Clear DeconvolutionElementList
  1391. /// </summary>
  1392. /// <param name="sender">sender</param>
  1393. /// <param name="e">RoutedEventArgs</param>
  1394. private void DeconvolutionClearButton_Click(object sender, RoutedEventArgs e)
  1395. {
  1396. this.DeconvolutionElementListTextBox.Clear();
  1397. OIHelper.SEMQuantSettings.ClearDeconvolutionElements();
  1398. foreach (int i in OIHelper.SEMQuantSettings.DeconvolutionElements)
  1399. {
  1400. this.DeconvolutionElementListTextBox.Text += i.ToString(CultureInfo.InvariantCulture) + Environment.NewLine;
  1401. }
  1402. }
  1403. /// <summary>
  1404. /// ThicknessTextBox and DensityTextBox will be enabled when IsCoatedCheckBox_Checked
  1405. /// </summary>
  1406. /// <param name="sender">sender</param>
  1407. /// <param name="e">RoutedEventArgs</param>
  1408. private void IsCoatedCheckBox_Click(object sender, RoutedEventArgs e)
  1409. {
  1410. this.CoatingElementTextBox.IsEnabled = (bool)this.IsCoatedCheckBox.IsChecked;
  1411. this.DensityTextBox.IsEnabled = (bool)this.IsCoatedCheckBox.IsChecked;
  1412. this.ThicknessTextBox.IsEnabled = (bool)this.IsCoatedCheckBox.IsChecked;
  1413. }
  1414. /// <summary>
  1415. /// SigmaLevelTextBox will be enabled when ThresholdingCheckBox_Checked
  1416. /// </summary>
  1417. /// <param name="sender">sender</param>
  1418. /// <param name="e">RoutedEventArgs</param>
  1419. private void ThresholdingCheckBox_Click(object sender, RoutedEventArgs e)
  1420. {
  1421. this.SigmaLevelTextBox.IsEnabled = (bool)this.ThresholdingCheckBox.IsChecked;
  1422. }
  1423. /// <summary>
  1424. /// Handles the CheckedChanged event of the MultiselectCheckBox control.
  1425. /// </summary>
  1426. /// <param name="sender">The source of the event.</param>
  1427. /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
  1428. private void MultiselectCheckBox_CheckedChanged(object sender, RoutedEventArgs e)
  1429. {
  1430. this.PeriodicTable.SelectionMode = this.MultiselectCheckBox.IsChecked.Value ? SelectionMode.Multiple : SelectionMode.Single;
  1431. }
  1432. /// <summary>
  1433. /// Handles the Checked event of the ElementEnable control.
  1434. /// </summary>
  1435. /// <param name="sender">The source of the event.</param>
  1436. /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
  1437. private void ElementEnable_Checked(object sender, RoutedEventArgs e)
  1438. {
  1439. CheckBox check = sender as CheckBox;
  1440. this.PeriodicTable.EnableElements(true, (int)check.Tag);
  1441. }
  1442. /// <summary>
  1443. /// Handles the Unchecked event of the ElementEnable control.
  1444. /// </summary>
  1445. /// <param name="sender">The source of the event.</param>
  1446. /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
  1447. private void ElementEnable_Unchecked(object sender, RoutedEventArgs e)
  1448. {
  1449. CheckBox check = sender as CheckBox;
  1450. this.PeriodicTable.EnableElements(false, (int)check.Tag);
  1451. }
  1452. /// <summary>
  1453. /// Handles the click Calculate button event.
  1454. /// </summary>
  1455. /// <param name="sender">The source of the event.</param>
  1456. /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
  1457. private void CalculatePeakParameterButton_Click(object sender, RoutedEventArgs e)
  1458. {
  1459. try
  1460. {
  1461. int atomicNum = ElementProperties.GetAtomicNumberByElementSymbol(this.SelectedIdentifiedElement);
  1462. var peakParameters = OIHelper.EdSpectrumProcessing.CalculatePeakParameters(this.spectrumViewer.Spectrum, atomicNum);
  1463. this.tbEnergy.Text = string.Format(CultureInfo.InvariantCulture, @"{0:F4} keV", peakParameters.Centre);
  1464. this.tbFWHM.Text = string.Format(CultureInfo.InvariantCulture, @"{0:F2} eV", peakParameters.FWHM);
  1465. }
  1466. catch (NullReferenceException)
  1467. {
  1468. }
  1469. catch (FormatException)
  1470. {
  1471. }
  1472. catch (InvalidOperationException)
  1473. {
  1474. }
  1475. }
  1476. /// <summary>
  1477. /// Handles the Click event of the GetPixelData button.
  1478. /// </summary>
  1479. /// <param name="sender">The source of the event.</param>
  1480. /// <param name="e">instance containing the event data.</param>
  1481. private void GetPixelData_Click(object sender, RoutedEventArgs e)
  1482. {
  1483. if (OIHelper.ImageAcquisitionController.IsAcquiring != true && this.imageViewer.DisplayImage != null)
  1484. {
  1485. try
  1486. {
  1487. var electronImage = this.imageViewer.DisplayImage as IElectronImage;
  1488. int x = int.Parse(this.tbPointX.Text, CultureInfo.InvariantCulture);
  1489. int y = int.Parse(this.tbPointY.Text, CultureInfo.InvariantCulture);
  1490. this.sb.Append(string.Format(CultureInfo.CurrentCulture, @" Point({0},{1}), Value: {2}", x, y, electronImage.GetData(new System.Drawing.Point(x, y))));
  1491. this.sb.Append(System.Environment.NewLine);
  1492. this.tbImageData.Text = this.sb.ToString();
  1493. }
  1494. catch (ArgumentOutOfRangeException)
  1495. {
  1496. //// stringBuilder - The length of the expanded string would exceed MaxCapacity.
  1497. }
  1498. catch (FormatException)
  1499. {
  1500. //// int.Parse - The x or y coordinates are not in the correct format.
  1501. }
  1502. }
  1503. }
  1504. /// <summary>
  1505. /// The Window is closing. Cancel if acquiring a spectrum.
  1506. /// </summary>
  1507. /// <param name="sender">The sender.</param>
  1508. /// <param name="e">The <see cref="CancelEventArgs"/> instance containing the event data.</param>
  1509. private void WindowClosing(object sender, CancelEventArgs e)
  1510. {
  1511. e.Cancel = this.IsAcquiringSpectrum;
  1512. }
  1513. #endregion
  1514. /// <summary>
  1515. /// Loads the comparison spectra.
  1516. /// </summary>
  1517. private void LoadComparisonSpectra()
  1518. {
  1519. byte[] data;
  1520. Uri uri;
  1521. StreamResourceInfo info;
  1522. this.comparisonSpectra = new List<IEdSpectrum>();
  1523. uri = new Uri(@"/ComparisonSpectra/Nickel.spec", UriKind.Relative);
  1524. info = Application.GetResourceStream(uri);
  1525. data = new byte[info.Stream.Length];
  1526. info.Stream.Read(data, 0, (int)info.Stream.Length);
  1527. this.comparisonSpectra.Add(DataFactory.LoadEdSpectrum(data));
  1528. uri = new Uri(@"/ComparisonSpectra/Preview spectrum.spec", UriKind.Relative);
  1529. info = Application.GetResourceStream(uri);
  1530. data = new byte[info.Stream.Length];
  1531. info.Stream.Read(data, 0, (int)info.Stream.Length);
  1532. this.comparisonSpectra.Add(DataFactory.LoadEdSpectrum(data));
  1533. uri = new Uri(@"/ComparisonSpectra/Tungsten particle.spec", UriKind.Relative);
  1534. info = Application.GetResourceStream(uri);
  1535. data = new byte[info.Stream.Length];
  1536. info.Stream.Read(data, 0, (int)info.Stream.Length);
  1537. this.comparisonSpectra.Add(DataFactory.LoadEdSpectrum(data));
  1538. this.cbCompareSpectra.DataContext = this;
  1539. this.cbCompareSpectra.SelectedIndex = 0;
  1540. }
  1541. #region INotifyPropertyChanged Members
  1542. /// <summary>
  1543. /// PropertyChanged event
  1544. /// </summary>
  1545. public event PropertyChangedEventHandler PropertyChanged;
  1546. private void RaisePropertyChanged(string propertyName)
  1547. {
  1548. this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  1549. }
  1550. #endregion
  1551. /// <summary>
  1552. /// The last element set
  1553. /// </summary>
  1554. private int lastElementSet = -1;
  1555. /// <summary>
  1556. /// Handles the PropertyChanged event of the ExcludeElementCombo control.
  1557. /// </summary>
  1558. /// <param name="sender">The source of the event.</param>
  1559. /// <param name="e">The <see cref="PropertyChangedEventArgs"/> instance containing the event data.</param>
  1560. private void ExcludeElementCombo_PropertyChanged(object sender, PropertyChangedEventArgs e)
  1561. {
  1562. if (e.PropertyName == nameof(this.ExcludeElementCombo.CurrentElement))
  1563. {
  1564. this.UpdateHighlightedElementInTable();
  1565. }
  1566. }
  1567. /// <summary>
  1568. /// Updates the highlighted element in table.
  1569. /// </summary>
  1570. private void UpdateHighlightedElementInTable()
  1571. {
  1572. if (this.lastElementSet != -1)
  1573. {
  1574. this.PeriodicTable.SetElementColor(this.lastElementSet, System.Windows.Media.Colors.Transparent);
  1575. }
  1576. System.Windows.Media.Color currentElementColor = System.Windows.Media.Color.FromArgb(255, 200, 255, 0);
  1577. this.PeriodicTable.SetElementColor(this.ExcludeElementCombo.CurrentElement, currentElementColor);
  1578. this.PeriodicTable.ShowElementColors = true;
  1579. this.lastElementSet = this.ExcludeElementCombo.CurrentElement;
  1580. this.PeriodicTable.SelectedElement = this.lastElementSet;
  1581. }
  1582. /// <summary>
  1583. /// Handles the Click event of the exportTiffButton control.
  1584. /// </summary>
  1585. /// <param name="sender">The source of the event.</param>
  1586. /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
  1587. private void ExportTiffButton_Click(object sender, RoutedEventArgs e)
  1588. {
  1589. // Export a tiff synchronously on the calling thread.
  1590. var syncTiff = this.spectrumViewer.CreateImage(ExportImageType.Tiff);
  1591. File.WriteAllBytes(Path.Combine(Path.GetTempPath(), @"zSpectrumSync.tiff"), syncTiff);
  1592. // Export a tiff asynchronously on a background thread.
  1593. // The thread must be created with an apartment state set to STA.
  1594. // Calls to CreateImage() must be made on the same thread that created the viewer.
  1595. var spectrum = this.spectrumViewer.Spectrum;
  1596. var thread = new System.Threading.Thread(() =>
  1597. {
  1598. // For optimum performance, create a single spectrum viewer and change the spectrum
  1599. // and viewer settings where required for all spectra that you need images for.
  1600. var backgroundViewer = new SpectrumViewer();
  1601. // A height and width must be set to provide the image dimensions in pixels.
  1602. backgroundViewer.Width = 500;
  1603. backgroundViewer.Height = 500;
  1604. backgroundViewer.IsYAxisAutoScaleEnabled = true;
  1605. backgroundViewer.YAxisType = ScaleType.Logarithmic;
  1606. backgroundViewer.MaximumEnergy = 8;
  1607. backgroundViewer.Spectrum = spectrum;
  1608. var asyncTiff = backgroundViewer.CreateImage(ExportImageType.Tiff);
  1609. File.WriteAllBytes(Path.Combine(Path.GetTempPath(), @"zSpectrumAsync.tiff"), asyncTiff);
  1610. backgroundViewer.Dispatcher.InvokeShutdown();
  1611. });
  1612. thread.IsBackground = true;
  1613. thread.SetApartmentState(ApartmentState.STA);
  1614. thread.Start();
  1615. }
  1616. }
  1617. }