MainWindow.xaml.cs 66 KB

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