using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Threading;
using System.Xml.Serialization;
using QC.GlobalVariableManager;
using QC.QsprShared.Config;
using QC.QsprShared.Dialogs;
using QC.QsprShared.GlobalData;
using QC.QsprShared.Trace;
using QC.QsprShared.Utilities;
using QC.QsprTestObjects;
using QC.QsprTestObjects.Loops;
using QC.QsprTestObjects.Registry;
using QC.QsprTestObjects.Tests.Base;
using QC.QTMApplication.Dialogs;
using QC.QTMApplication.Utilities;
using QC.QTMDotNetKernelInterface;
using QC.QTMInterface;
using QC.QTMSecurity;
using QsprMiscShared.Utilities;

namespace QC.QTMApplication;

public partial class QSPRMainWindow : Window, INotifyPropertyChanged, IComponentConnector
{
	private const string CHARTING_KEY = "Charting";

	private const string CTS_DVT_TREE_KEY = "CTS-DVT Tree";

	private const string LOOPING_KEY = "Looping";

	private const string PARAMETER_KEY = "Parameter";

	private const string PROPERTIES_KEY = "Properties";

	private const string TESTER_CONFIGURATION_KEY = "Tester Configuration";

	private const string TEST_RESULTS_KEY = "Test Results";

	private const string IMPORTING_LINKING_KEY = "Importing - Linking Trees";

	private const string ADDING_REMOTE_TARGET_KEY = "Adding Remote Targets";

	private const string ADDING_SCRIPTS_KEY = "Adding Scripts";

	public const string ENABLE_ALL_LOGGING = "Enable All Logging";

	public const string DISABLE_ALL_LOGGING = "Disable All Logging";

	private const string CHARTING_FILENAME_KEY = "Tutorial\\ChartMantraTutorial.exe";

	private const string CTS_DVT_TREE_FILENAME_KEY = "Tutorial\\CTS-DVTConversionTutorial.exe";

	private const string LOOPING_FILENAME_KEY = "Tutorial\\Looping.exe";

	private const string PARAMETER_FILENAME_KEY = "Tutorial\\ParametersTutorial.exe";

	private const string PROPERTIES_FILENAME_KEY = "Tutorial\\PropertiesBranchOnErrorTutorial.exe";

	private const string TESTER_CONFIGURATION_FILENAME_KEY = "Tutorial\\TesterConfigTutorial.exe";

	private const string TEST_RESULTS_FILENAME_KEY = "Tutorial\\TestResultsTutorial.exe";

	private const string IMPORTING_LINKING_FILENAME_KEY = "Tutorial\\TreeImportingLinkingTutorial.exe";

	private const string ADDING_REMOTE_TARGET_FILENAME_KEY = "Tutorial\\AddTarget.exe";

	private const string ADDING_SCRIPT_FILENAME_KEY = "Tutorial\\Script.exe";

	private const string XMLDB_PLUGIN = "XmlForDB";

	private const int MAX_TIME_OUT = 60000;

	private bool checkState;

	private static MenuToolBarManager ultraToolbarsManager1;

	private static string currentTreeName = "";

	private System.Windows.Forms.Timer timerStartMiniQTM;

	private static System.Windows.Controls.MenuItem RecentMenuItemBar;

	private ArrayList tempList = new ArrayList();

	private Window window;

	private static int exitCode = 1;

	private static Stack<ArrayList> retryMsgStack = new Stack<ArrayList>();

	private QTMArguments qArguments = new QTMArguments();

	private static QTMStatusBar statusBar;

	internal static WPFDebugWindowColl SDebugWindowCollection;

	internal static TestResultsColl STestResultsCollection;

	internal static WPFTestTreeWindowColl SWPFTestTreeWindowCollection;

	private static StopSignal sSignal = new StopSignal();

	private static Mutex messageMutex = new Mutex(initiallyOwned: false);

	private KeyActionCommand keyCommand;

	private static KeyActionCommand sKeyCommand;

	private WPFTestTreeWindowColl wpfTestTreeWindowColl;

	private TestResultsColl testResultsCollection;

	private UserWindowColl userWindowCollection;

	private WPFDebugWindowColl debugWindowCollection;

	private QSPRMainWindowUISettings customizedUISettings;

	private QSPRMainWindowUISettings defaultWindowUISettings = new QSPRMainWindowUISettings();

	private QSPRMainWindowUISettings mainWindowSettings = new QSPRMainWindowUISettings();

	public static MenuToolBarManager UltraToolbarsManager => ultraToolbarsManager1;

	public static string CurrentTreeName
	{
		get
		{
			return currentTreeName;
		}
		set
		{
			currentTreeName = value;
		}
	}

	public static QTMStatusBar StatusBar
	{
		get
		{
			return statusBar;
		}
		set
		{
			statusBar = value;
		}
	}

	public static PluginConfig AllPlugInConfig
	{
		get
		{
			PluginConfig pluginConfig = new PluginConfig();
			pluginConfig.AllConfig = SWPFTestTreeWindowCollection.AllPluginConfigInfo;
			pluginConfig.TestResultsConfig = STestResultsCollection.AllPluginConfigInfo;
			return pluginConfig;
		}
		set
		{
			SWPFTestTreeWindowCollection.AllPluginConfigInfo = value.AllConfig;
			STestResultsCollection.AllPluginConfigInfo = value.TestResultsConfig;
		}
	}

	public static List<DockConfig> DebugConfig
	{
		get
		{
			return WPFDebugWindowColl.DockedWindowCollection;
		}
		set
		{
			WPFDebugWindowColl.DockedWindowCollection = value;
		}
	}

	public WorkspaceConfig WConfig
	{
		get
		{
			return _scheduler.QTMData.WConfig;
		}
		set
		{
			_scheduler.QTMData.WConfig = value;
			try
			{
				if (STestResultsCollection != null)
				{
					STestResultsCollection.OnConfigInfo(_scheduler.QTMData.WConfig.ExportToStruct());
				}
				if (SWPFTestTreeWindowCollection != null)
				{
					SWPFTestTreeWindowCollection.OnConfigInfo(_scheduler.QTMData.WConfig.ExportToStruct());
				}
			}
			catch
			{
			}
		}
	}

	public Window Window
	{
		get
		{
			return window;
		}
		set
		{
			window = value;
		}
	}

	public static FeatureConfig FeatureConfigInfo
	{
		get
		{
			return QTMData.FeatureConfigInfo;
		}
		set
		{
			QTMData.FeatureConfigInfo = value;
		}
	}

	public static int ExitCode
	{
		get
		{
			return exitCode;
		}
		set
		{
			exitCode = value;
		}
	}

	internal Scheduler _scheduler => TreeView._scheduler;

	private TTDWpfTreeView TreeView => wpfTestTreeWindowColl.ttdWpfTreeView;

	private ArrayList messageQueue
	{
		get
		{
			if (_scheduler.QTMData.messageQueue == null)
			{
				_scheduler.QTMData.messageQueue = new ArrayList();
			}
			return _scheduler.QTMData.messageQueue;
		}
		set
		{
			_scheduler.QTMData.messageQueue = value;
		}
	}

	public QTMArguments QArguments
	{
		get
		{
			return qArguments;
		}
		set
		{
			qArguments = value;
		}
	}

	public ArrayList TesterConfigurationList
	{
		get
		{
			return TreeView.TesterConfigurationList;
		}
		set
		{
			TreeView.TesterConfigurationList = value;
		}
	}

	internal ScenarioHandler scenarioHandler
	{
		get
		{
			if (_scheduler.QTMData.scenarioHandler == null)
			{
				_scheduler.QTMData.scenarioHandler = new ScenarioHandler();
			}
			return (ScenarioHandler)_scheduler.QTMData.scenarioHandler;
		}
		set
		{
			_scheduler.QTMData.scenarioHandler = value;
		}
	}

	private QTMRegistry theRegistry
	{
		get
		{
			if (_scheduler.QTMData.theRegistry == null)
			{
				_scheduler.QTMData.theRegistry = new QTMRegistry();
			}
			return (QTMRegistry)_scheduler.QTMData.theRegistry;
		}
		set
		{
			_scheduler.QTMData.theRegistry = value;
		}
	}

	public KeyActionCommand KeyCommand => keyCommand;

	public WPFTestTreeWindowColl WPFTestTreeWindowCollection
	{
		get
		{
			return wpfTestTreeWindowColl;
		}
		set
		{
			wpfTestTreeWindowColl = value;
			QTMUtility.LoadPluginContainer(TestTreePluginsContenControl, wpfTestTreeWindowColl);
		}
	}

	public TestResultsColl TestResultsCollection
	{
		get
		{
			return testResultsCollection;
		}
		set
		{
			testResultsCollection = value;
			QTMUtility.LoadPluginContainer(TestResultsPluginsContentControl, testResultsCollection);
		}
	}

	public UserWindowColl UserWindowCollection
	{
		get
		{
			return userWindowCollection;
		}
		set
		{
			userWindowCollection = value;
			QTMUtility.LoadPluginContainer(UserCollectionPluginsContentControl, userWindowCollection);
		}
	}

	public WPFDebugWindowColl DebugWindowCollection
	{
		get
		{
			return debugWindowCollection;
		}
		set
		{
			debugWindowCollection = value;
			QTMUtility.LoadPluginContainer(DebugCollectionPluginsContentControl, debugWindowCollection);
		}
	}

	public static bool PasteEnabled
	{
		set
		{
			UltraToolbarsManager.SetEnabled("Paste", value);
		}
	}

	public event PropertyChangedEventHandler PropertyChanged;

	public void AddRecentFile(string fileName)
	{
		tempList = new ArrayList();
		if (_scheduler.QTMData.WConfig.RecentFileListSize <= 0)
		{
			return;
		}
		if (_scheduler.QTMData.WConfig.RecentFileList.Contains(fileName))
		{
			_scheduler.QTMData.WConfig.RecentFileList.Remove(fileName);
			tempList.Add(fileName);
		}
		else
		{
			tempList.Add(fileName);
		}
		foreach (string recentFile in _scheduler.QTMData.WConfig.RecentFileList)
		{
			tempList.Add(recentFile);
		}
		_scheduler.QTMData.WConfig.RecentFileList = tempList;
		UpdateRecentFile();
	}

	public void UpdateRecentFile()
	{
		RecentMenuItemBar.Items.Clear();
		tempList = new ArrayList();
		for (int i = 0; i < _scheduler.QTMData.WConfig.RecentFileListSize; i++)
		{
			try
			{
				tempList.Add(_scheduler.QTMData.WConfig.RecentFileList[i]);
			}
			catch
			{
			}
		}
		_scheduler.QTMData.WConfig.RecentFileList = tempList;
		foreach (string recentFile in _scheduler.QTMData.WConfig.RecentFileList)
		{
			AddMenuItem(recentFile);
		}
	}

	public void ShowWindow()
	{
		try
		{
			if (Window != null)
			{
				Window.ShowInTaskbar = true;
				Window.Show();
				Window.WindowState = WindowState.Maximized;
				Window.Activate();
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write("QC.QTMApplication.QTM", "ShowWindow " + ex.Message, TraceMessageType.Exception);
			throw new Exception("QC.QTMApplication.QTM, ShowWindow " + ex.Message, ex.InnerException);
		}
	}

	public void HideWindow()
	{
		try
		{
			if (Window != null)
			{
				Window.ShowInTaskbar = false;
				Window.Hide();
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write("QC.QTMApplication.QTM", "HideWindow " + ex.Message, TraceMessageType.Exception);
			throw new Exception("QC.QTMApplication.QTM, HideWindow " + ex.Message, ex.InnerException);
		}
	}

	public QSPRMainWindow()
	{
		InitializeComponent();
		PopulateDefaultGridSettings();
		LoadDockingConfiguration("QSPRDocking.config", loadDefault: true);
		base.DataContext = this;
		keyCommand = new KeyActionCommand(KeyCommand_Execute, KeyCommand_CanExecute);
		sKeyCommand = keyCommand;
		QTMData.UpdateToolBar = (QTMData.OnUpdateToolBar)Delegate.Combine(QTMData.UpdateToolBar, new QTMData.OnUpdateToolBar(UpdateMainToolbar));
	}

	private void UpdateMainToolbar(object value)
	{
		if (value is RegistrySelectedNode)
		{
			UpdateToolBar((RegistrySelectedNode)value);
		}
		else if (value is TestTreeSelectedNode)
		{
			UpdateToolBar((TestTreeSelectedNode)value);
		}
	}

	private void SendLoadLayoutMsg(string key)
	{
		TestResultsCollection.HandleToolsClick(key);
		DebugWindowCollection.HandleToolsClick(key);
		WPFTestTreeWindowCollection.HandleToolsClick(key);
	}

	private void TestResultsLayout()
	{
	}

	private void RestoreAppWindowSettings()
	{
		try
		{
			if (WConfig.MinimizeAtStartup)
			{
				base.WindowState = WindowState.Minimized;
				_ = QTMUserSettings.Default.WindowLocation;
				_ = QTMUserSettings.Default.WindowSize;
			}
			else if (QTMUserSettings.Default.Maximized)
			{
				base.WindowState = WindowState.Maximized;
			}
			else if (QTMUserSettings.Default.Minimized)
			{
				base.WindowState = WindowState.Maximized;
			}
			else
			{
				base.WindowState = WindowState.Normal;
				_ = QTMUserSettings.Default.WindowLocation;
				_ = QTMUserSettings.Default.WindowSize;
			}
		}
		catch (ConfigurationErrorsException ex)
		{
			string filename = ((ConfigurationException)ex.InnerException).Filename;
			File.Delete(filename);
		}
	}

	private void LaunchStartupEvents(object eventsObj)
	{
		string text = eventsObj.ToString();
		string[] array = text.Split(new string[1] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
		if (array.Length > 0)
		{
			string[] array2 = array;
			foreach (string text2 in array2)
			{
				Process process = new Process();
				process.StartInfo.CreateNoWindow = true;
				process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
				process.StartInfo.FileName = "cmd.exe";
				process.StartInfo.Arguments = "/C " + text2;
				process.Start();
			}
		}
	}

	private void ConfigureHiveKernel()
	{
		if (QTMData.Kernels.HiveKernel && GlobalStatus.AutomationMode)
		{
			_scheduler.KernelMgr.IsInAutomation(isInAutomation: true);
		}
		if (QTMData.Kernels.HiveKernel && WConfig.EnableHiveTracing)
		{
			_scheduler.KernelMgr.SetTracingForHiveKernel(enableTracing: true);
		}
		if (QTMData.Kernels.HiveKernel && WConfig.EnableSUITEOutParam)
		{
			_scheduler.KernelMgr.EnableSUITEOutParams(enable: true);
		}
	}

	private void SetSecurity()
	{
		try
		{
			if (!QSecurity.LoggedInWithPassword() && QSecurity.IsPasswordMode)
			{
				PasswordLoginScreen passwordLoginScreen = new PasswordLoginScreen(changingPassword: false);
				if (passwordLoginScreen.ShowDialog(WpfToWin32Window.GetCurrentWin32Window()) == System.Windows.Forms.DialogResult.OK)
				{
					UltraToolbarsManager.SetToolTipText("Login", "Logout");
					UltraToolbarsManager.SetImage("Login", "pack://application:,,,/QSPR;component/Icons/Logout.png");
				}
				return;
			}
			if (!QSecurity.Impersonating && !QSecurity.IsPasswordMode)
			{
				if (WPFTestTreeWindowCollection.TreeChanged && QSecurity.IsEngineer)
				{
					DialogResult dialogResult = AppMessageDialog.Show("Do you want to save the Test Tree?", "QSPR - Message Center", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, System.Windows.Forms.DialogResult.Yes, MessageDialogType.UIWarning);
					if (dialogResult == System.Windows.Forms.DialogResult.Yes)
					{
						WPFTestTreeWindowCollection.HandleToolsClick("Save");
					}
				}
				LoginScreen loginScreen = new LoginScreen();
				if (loginScreen.ShowDialog(WpfToWin32Window.GetCurrentWin32Window()) == System.Windows.Forms.DialogResult.OK)
				{
					UltraToolbarsManager.SetToolTipText("Login", "Logout");
					UltraToolbarsManager.SetImage("Login", "pack://application:,,,/QSPR;component/Icons/Logout.png");
				}
				return;
			}
			DialogResult dialogResult2 = AppMessageDialog.Show("Do you really want to Logout?", "QSPR - Message Center", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, System.Windows.Forms.DialogResult.Yes, MessageDialogType.Warning);
			if (dialogResult2 == System.Windows.Forms.DialogResult.No)
			{
				return;
			}
			if (WPFTestTreeWindowCollection.TreeChanged && QSecurity.IsEngineer)
			{
				DialogResult dialogResult3 = AppMessageDialog.Show("Do you want to save the Test Tree?", "QSPR - Message Center", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, System.Windows.Forms.DialogResult.Yes, MessageDialogType.UIWarning);
				if (dialogResult3 == System.Windows.Forms.DialogResult.Yes)
				{
					WPFTestTreeWindowCollection.HandleToolsClick("Save");
				}
			}
			if (QSecurity.IsPasswordMode)
			{
				QSecurity.PasswordLogout();
			}
			else
			{
				QSecurity.Logout();
			}
			UltraToolbarsManager.SetToolTipText("Login", "Login");
			UltraToolbarsManager.SetImage("Login", "pack://application:,,,/QSPR;component/Icons/Login.png");
		}
		catch
		{
		}
	}

	private void RunTutorial(string key)
	{
		try
		{
			string text = "";
			switch (key)
			{
			case "Charting":
				text = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), Path.Combine(FeatureConfigInfo.HelpDirectory, "Tutorial\\ChartMantraTutorial.exe"));
				break;
			case "CTS-DVT Tree":
				text = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), Path.Combine(FeatureConfigInfo.HelpDirectory, "Tutorial\\CTS-DVTConversionTutorial.exe"));
				break;
			case "Looping":
				text = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), Path.Combine(FeatureConfigInfo.HelpDirectory, "Tutorial\\Looping.exe"));
				break;
			case "Parameter":
				text = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), Path.Combine(FeatureConfigInfo.HelpDirectory, "Tutorial\\ParametersTutorial.exe"));
				break;
			case "Properties":
				text = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), Path.Combine(FeatureConfigInfo.HelpDirectory, "Tutorial\\PropertiesBranchOnErrorTutorial.exe"));
				break;
			case "Tester Configuration":
				text = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), Path.Combine(FeatureConfigInfo.HelpDirectory, "Tutorial\\TesterConfigTutorial.exe"));
				break;
			case "Test Results":
				text = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), Path.Combine(FeatureConfigInfo.HelpDirectory, "Tutorial\\TestResultsTutorial.exe"));
				break;
			case "Importing - Linking Trees":
				text = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), Path.Combine(FeatureConfigInfo.HelpDirectory, "Tutorial\\TreeImportingLinkingTutorial.exe"));
				break;
			case "Adding Remote Targets":
				text = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), Path.Combine(FeatureConfigInfo.HelpDirectory, "Tutorial\\AddTarget.exe"));
				break;
			case "Adding Scripts":
				text = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), Path.Combine(FeatureConfigInfo.HelpDirectory, "Tutorial\\Script.exe"));
				break;
			}
			if (text != "")
			{
				Process process = new Process();
				process.StartInfo.FileName = text;
				process.Start();
			}
		}
		catch
		{
		}
	}

	private void SaveCustomizedDocking(string key)
	{
		SaveWindowsDocking("CustomQSPRDocking.config");
		WPFTestTreeWindowCollection.HandleToolsClick(key);
		DebugWindowCollection.HandleToolsClick(key);
		AppMessageDialog.Show("Customized Layout saved.", System.Windows.Forms.DialogResult.OK, MessageDialogType.Information);
	}

	public void Load()
	{
		bool hideWindow = qArguments.HideWindow;
		if (!Directory.Exists(Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), FeatureConfigInfo.TraceMsgDirectory)))
		{
			Directory.CreateDirectory(Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), FeatureConfigInfo.TraceMsgDirectory));
		}
		if (!Directory.Exists(Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), FeatureConfigInfo.TempDirectory)))
		{
			Directory.CreateDirectory(Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), FeatureConfigInfo.TempDirectory));
		}
		_scheduler.GlobalStatus.Reset();
		_scheduler.QTMData.UpdateGVForLinkTree = WPFTestTreeWindowCollection.UpdateGlobalVbleForLinkedTree;
		_scheduler.GlobalStatus.RunningStatusChangedEvent += GlobalStatus_RunningStatusChangedEvent;
		if (hideWindow)
		{
			Hide();
			base.ShowInTaskbar = false;
		}
		RecentMenuItemBar = RecentFilesMenuItem;
		statusBar = new QTMStatusBar(ultraStatusBar1, this);
		ultraToolbarsManager1 = new MenuToolBarManager(QsprMainMenu, QsprMainToolBar, this);
		STestResultsCollection = TestResultsCollection;
		SDebugWindowCollection = DebugWindowCollection;
		SWPFTestTreeWindowCollection = WPFTestTreeWindowCollection;
		DebugWindowCollection.CreatingNewWindowEvent += DebugWindowCollection_CreatingNewWindowEvent;
		DebugWindowCollection.CreatedNewWindowEvent += DebugWindowCollection_CreatedNewWindowEvent;
		DebugWindowCollection.OnDebugCollEvent += DebugWindowCollection_OnDebugCollEvent;
		QC.QTMDotNetKernelInterface.GlobalVariable.OnTesterConfigChange += OnTesterConfigChange;
		_scheduler.TestMsgBroadCaster.SetMessageDelegate(OnTestMessages);
		_scheduler.TestMsgBroadCaster.SetTextOutDelegate(OnTextOut);
		_scheduler.TestMsgBroadCaster.SetPrintDebugDelegate(OnPrintDebugMsg);
		_scheduler.TestMsgBroadCaster.SetOnGenericMessageDelegate(OnGenericMsg);
		_scheduler.TestMsgBroadCaster.SetOnGenericParamMessageDelegate(OnGenericParamMsg);
		_scheduler.TestMsgBroadCaster.SetOnCustomMessageDelegate(OnCustomMsg);
		_scheduler.TestMsgBroadCaster.SetOnTpl2WindowDelegate(OnTPL2WindowMsg);
		_scheduler.TestMsgBroadCaster.SetOnHTMLWindowDelegate(OnHTMLWindowMsg);
		_scheduler.TestMsgBroadCaster.SetClearDebugMessageDelegate(OnClearDebugMsg);
		_scheduler.TestMsgBroadCaster.SetSaveDebugMessageDelegate(OnSaveDebugMsg);
		_scheduler.TestMsgBroadCaster.SetClearAllDebugDelegate(OnClearAllDebugMsg);
		_scheduler.TestMsgBroadCaster.SetSaveAllDebugDelegate(OnSaveAllDebugMsg);
		_scheduler.TestMsgBroadCaster.SetDebugWindowInFocusDelegate(OnSetDebugWindowInFocus);
		_scheduler.SetMessageDelegate(OnTestMessages);
		try
		{
			_scheduler.KernelMgr.InitializeHiveKernel(_scheduler.TestMsgBroadCaster);
			QTMData.Kernels.HiveKernel = true;
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "QTM_Load HiveKernel" + ex.Message, TraceMessageType.Exception);
		}
		try
		{
			_scheduler.KernelMgr.InitializeScriptKernel(_scheduler.TestMsgBroadCaster);
			QTMData.Kernels.ScriptKernel = true;
		}
		catch (Exception ex2)
		{
			TraceMessage.Write(ToString(), "QTM_Load Script Kernel" + ex2.Message, TraceMessageType.Exception);
		}
		try
		{
			if (!FeatureConfigInfo.DisableLabView)
			{
				_scheduler.KernelMgr.InitializeLabVIEWKernel(_scheduler.TestMsgBroadCaster);
				QTMData.Kernels.LabViewKernel = true;
			}
		}
		catch (Exception ex3)
		{
			TraceMessage.Write(ToString(), "QTM_Load LabView Kernel" + ex3.Message, TraceMessageType.Exception);
		}
		try
		{
			_scheduler.KernelMgr.InitializeDotNetKernel(_scheduler.TestMsgBroadCaster);
			QTMData.Kernels.DotNetKernel = true;
		}
		catch (Exception ex4)
		{
			TraceMessage.Write(ToString(), "QTM_Load Dot Net Kernel" + ex4.Message, TraceMessageType.Exception);
		}
		base.Topmost = true;
		UltraToolbarsManager.SetVisible("Tutorials", visiblilty: false);
		UltraToolbarsManager.SetVisible("Tools", visiblilty: false);
		wpfTestTreeWindowColl.OnTTDPluginMenu += testTreeWindowCollection_OnTTDPluginMenu;
		wpfTestTreeWindowColl.UpdateWindowBG = UpdateWindowBG;
	}

	private void testTreeWindowCollection_OnTTDPluginMenu(object sender, PluginMenuEventsArgs e)
	{
		MenuMessage(e.Key);
	}

	public void OnSaveAllDebugMsg(bool appendText)
	{
		TraceMessage.Write(ToString(), "OnSaveAllDebugMsg ", TraceMessageType.Trace);
		try
		{
			DebugWindowCollection.OnSaveAllMessages(appendText);
			WPFTestTreeWindowCollection.OnDebugMsg(DebugMsgType.OnSaveAllMsg, "");
			TestResultsCollection.OnDebugMsg(DebugMsgType.OnSaveAllMsg, "");
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "OnSaveAllDebugMsg " + ex.Message, TraceMessageType.Exception);
		}
	}

	public void OnSetDebugWindowInFocus(string debugWindowName)
	{
		TraceMessage.Write(ToString(), "OnSetDebugWindowInFocus ", TraceMessageType.Trace);
		try
		{
			DebugWindowCollection.OnSetDebugWindowInFocus(debugWindowName);
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "OnSetDebugWindowInFocus " + ex.Message, TraceMessageType.Exception);
		}
	}

	public static void UpdateLoginButton(bool loggedIn)
	{
		if (loggedIn)
		{
			UltraToolbarsManager.SetToolTipText("Login", "Logout");
			UltraToolbarsManager.SetImage("Login", "pack://application:,,,/QSPR;component/Icons/Logout.png");
		}
		else
		{
			UltraToolbarsManager.SetToolTipText("Login", "Login");
			UltraToolbarsManager.SetImage("Login", "pack://application:,,,/QSPR;component/Icons/Login.png");
		}
	}

	internal void SendLogDoneMessage(BasePlugin plugin)
	{
		if (plugin is TestResultPlugin trPlugin)
		{
			_scheduler.SendLogDoneMessage(trPlugin);
		}
	}

	public void UpdateGlobalVble(bool GetFromTesterConfig)
	{
		_scheduler.QTMData.UpdateGlobalVble(GetFromTesterConfig, wpfTestTreeWindowColl.GetTesterConfiguration());
	}

	public void OnClearAllDebugMsg()
	{
		if (this.InvokeRequired())
		{
			this.BeginInvoke(delegate
			{
				OnClearAllDebugMsg();
			});
			return;
		}
		TraceMessage.Write(ToString(), "OnClearAllDebugMsg ", TraceMessageType.Trace);
		try
		{
			DebugWindowCollection.OnClearAllMessage();
			WPFTestTreeWindowCollection.OnDebugMsg(DebugMsgType.OnClearAllMsg, "");
			TestResultsCollection.OnDebugMsg(DebugMsgType.OnClearAllMsg, "");
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "OnClearAllDebugMsg " + ex.Message, TraceMessageType.Exception);
		}
	}

	public void OnSaveDebugMsg(string strWindowName, bool appendText)
	{
		TraceMessage.Write(ToString(), "OnSaveDebugMsg " + strWindowName, TraceMessageType.Trace);
		try
		{
			DebugWindowCollection.OnSaveMessage(strWindowName, appendText);
			WPFTestTreeWindowCollection.OnDebugMsg(DebugMsgType.OnSaveMsg, strWindowName);
			TestResultsCollection.OnDebugMsg(DebugMsgType.OnSaveMsg, strWindowName);
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "OnSaveDebugMsg " + ex.Message, TraceMessageType.Exception);
		}
	}

	public void OnClearDebugMsg(string strWindowName)
	{
		if (this.InvokeRequired())
		{
			this.BeginInvoke(delegate
			{
				OnClearDebugMsg(strWindowName);
			});
			return;
		}
		TraceMessage.Write(ToString(), "OnClearDebugMsg " + strWindowName, TraceMessageType.Trace);
		try
		{
			DebugWindowCollection.OnClearMessage(strWindowName);
			WPFTestTreeWindowCollection.OnDebugMsg(DebugMsgType.OnClearMsg, strWindowName);
			TestResultsCollection.OnDebugMsg(DebugMsgType.OnClearMsg, strWindowName);
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "OnClearDebugMsg " + ex.Message, TraceMessageType.Exception);
		}
	}

	public void OnHTMLWindowMsg(string windowName, HTMLCommand command, string TextStr)
	{
		if (this.InvokeRequired())
		{
			this.BeginInvoke(delegate
			{
				OnHTMLWindowMsg(windowName, command, TextStr);
			});
			return;
		}
		TraceMessage.Write(ToString(), "OnHTMLWindowMsg " + command, TraceMessageType.Trace);
		try
		{
			DebugWindowCollection.OnHTMLWindowMessage(windowName, command, TextStr);
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "OnHTMLWindowMsg " + ex.Message, TraceMessageType.Exception);
		}
	}

	public void OnTPL2WindowMsg(string windowName, Tpl2Command command, Tpl2Info commandInfo)
	{
		if (this.InvokeRequired())
		{
			this.BeginInvoke(delegate
			{
				OnTPL2WindowMsg(windowName, command, commandInfo);
			});
			return;
		}
		TraceMessage.Write(ToString(), "OnTPL2WindowMsg " + command, TraceMessageType.Trace);
		try
		{
			DebugWindowCollection.OnTPL2WindowMessage(windowName, command, commandInfo);
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "OnTPL2WindowMsg " + ex.Message, TraceMessageType.Exception);
		}
	}

	public void OnCustomMsg(object customData, byte pluginTypes, string pluginNames)
	{
		if (this.InvokeRequired())
		{
			this.BeginInvoke(delegate
			{
				OnCustomMsg(customData, pluginTypes, pluginNames);
			});
			return;
		}
		TraceMessage.Write(ToString(), "OnCustomMsg ", TraceMessageType.Trace);
		try
		{
			if ((pluginTypes & 1) == 1)
			{
				WPFTestTreeWindowCollection.OnCustomMessage(customData, pluginNames);
			}
			if ((pluginTypes & 2) == 2)
			{
				TestResultsCollection.OnCustomMessage(customData, pluginNames);
			}
			if ((pluginTypes & 4) == 4)
			{
				DebugWindowCollection.OnCustomMessage(customData, pluginNames);
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "OnCustomMsg " + ex.Message, TraceMessageType.Exception);
		}
	}

	public void OnGenericParamMsg(string messageType, string id, string name, string value, string units, string lowerLimit, string upperLimit, byte pluginTypes, string pluginNames)
	{
		if (this.InvokeRequired())
		{
			this.BeginInvoke(delegate
			{
				OnGenericParamMsg(messageType, id, name, value, units, lowerLimit, upperLimit, pluginTypes, pluginNames);
			});
			return;
		}
		TraceMessage.Write(ToString(), "OnGenericParamMsg " + messageType, TraceMessageType.Trace);
		try
		{
			if ((pluginTypes & 1) == 1)
			{
				WPFTestTreeWindowCollection.OnGenericParamMessage(messageType, id, name, value, units, lowerLimit, upperLimit, pluginNames);
			}
			if ((pluginTypes & 2) == 2)
			{
				TestResultsCollection.OnGenericParamMessage(messageType, id, name, value, units, lowerLimit, upperLimit, pluginNames);
			}
			if ((pluginTypes & 4) == 4)
			{
				DebugWindowCollection.OnGenericParamMessage(messageType, id, name, value, units, lowerLimit, upperLimit, pluginNames);
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "OnGenericMsg " + ex.Message, TraceMessageType.Exception);
		}
	}

	public void OnGenericMsg(string messageType, GenericTestData data, byte pluginTypes, string pluginNames)
	{
		if (this.InvokeRequired())
		{
			this.BeginInvoke(delegate
			{
				OnGenericMsg(messageType, data, pluginTypes, pluginNames);
			});
			return;
		}
		TraceMessage.Write(ToString(), "OnGenericMsg " + messageType, TraceMessageType.Trace);
		try
		{
			if (messageType == "OnEndLog" || messageType == "OnStartLog")
			{
				if (_scheduler.GlobalStatus.IsDebugMode)
				{
					return;
				}
				data = new GenericTestData();
				data.TestResult = ((_scheduler.GlobalStatus.GlobalTestResult != TestResult.Passed) ? TestResult.Failed.ToString() : TestResult.Passed.ToString());
			}
			if (messageType == "ClearGlobalTreeResult")
			{
				_scheduler.GlobalStatus.GlobalTestResult = TestResult.Passed;
			}
			if ((pluginTypes & 1) == 1)
			{
				WPFTestTreeWindowCollection.OnGenericMessage(messageType, data, pluginNames);
			}
			if ((pluginTypes & 2) == 2)
			{
				TestResultsCollection.OnGenericMessage(messageType, data, pluginNames);
			}
			if ((pluginTypes & 4) == 4)
			{
				DebugWindowCollection.OnGenericMessage(messageType, data, pluginNames);
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "OnGenericMsg " + ex.Message, TraceMessageType.Exception);
		}
	}

	public void OnPrintDebugMsg(string strWindowName, PrintMsgOptions IsHeader, params string[] Values)
	{
		TraceMessage.Write(ToString(), "OnPrintDebugMsg " + strWindowName, TraceMessageType.Trace);
		try
		{
			DebugWindowCollection.OnPrintMessage(strWindowName, IsHeader, Values);
			PrintMsgInfo msgInfo = new PrintMsgInfo(strWindowName, Values, IsHeader);
			WPFTestTreeWindowCollection.OnDebugMsg(DebugMsgType.OnPrintMsg, msgInfo);
			TestResultsCollection.OnDebugMsg(DebugMsgType.OnPrintMsg, msgInfo);
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "OnTextOut " + ex.Message, TraceMessageType.Exception);
		}
	}

	public void OnTextOut(string strWindowName, string strWindowText, TraceLevel traceLevel, bool NoEndOfLine)
	{
		if (this.InvokeRequired())
		{
			this.BeginInvoke(delegate
			{
				OnTextOut(strWindowName, strWindowText, traceLevel, NoEndOfLine);
			});
			return;
		}
		TraceMessage.Write(ToString(), "OnTextOut " + strWindowText, TraceMessageType.Trace);
		try
		{
			if (string.Compare(strWindowName, "Telemetrics", ignoreCase: true) == 0)
			{
				Analytics.WriteAnalytics("DebugMessage", strWindowText);
				return;
			}
			DebugWindowCollection.OnTextOut(strWindowName, strWindowText, traceLevel, NoEndOfLine);
			DebugInfo msgInfo = new DebugInfo(strWindowName, strWindowText, traceLevel);
			WPFTestTreeWindowCollection.OnDebugMsg(DebugMsgType.OnTextMsg, msgInfo);
			TestResultsCollection.OnDebugMsg(DebugMsgType.OnTextMsg, msgInfo);
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "OnTextOut " + ex.Message, TraceMessageType.Exception);
		}
	}

	public void OnTestMessages(TestMsgType msgType, TestMessage message)
	{
		TraceMessage.Write(ToString(), "OnTestMessages " + msgType, TraceMessageType.Trace);
		scenarioHandler.ProcessMessage(msgType, message, _scheduler.RootFolder);
		UpdateStatusBar(msgType, message.Message, message.TestIndex, message.Result, message.Object, message.SerialNumber);
		theRegistry.OnTestMessage(msgType, message.Message, message.Result);
		QTMInfo.OnMsgFromQTM(msgType, GetMsgDataFromTestMsg(message));
		switch (msgType)
		{
		case TestMsgType.OnEnqueueTest:
		case TestMsgType.OnDequeueTest:
			WPFTestTreeWindowCollection.OnMsg((ArrayList)message.Object);
			break;
		case TestMsgType.OnAbort:
			if (_scheduler.GlobalStatus.GlobalTestResult != TestResult.IgnoreSession)
			{
				_scheduler.GlobalStatus.GlobalTestResult = TestResult.Exception;
			}
			HandleTestMessages(msgType, message);
			break;
		default:
			_scheduler.GlobalStatus.ProcessTestResultsPlugIns = true;
			HandleTestMessages(msgType, message);
			break;
		}
		if (msgType == TestMsgType.OnUnitEnd)
		{
			if (message.Result == TestResult.Passed)
			{
				exitCode = 1;
			}
			else if (message.Result == TestResult.Failed)
			{
				exitCode = -2;
			}
			else if (message.Result == TestResult.Exception)
			{
				exitCode = -1;
			}
			else
			{
				exitCode = -3;
			}
		}
		if (msgType == TestMsgType.OnTreeDone && qArguments.CloseAfterRunning)
		{
			while (_scheduler.GlobalStatus.ProcessTestResultsPlugIns)
			{
				Thread.Sleep(1000);
			}
			Close();
		}
	}

	private void HandleTestMessages(TestMsgType msgType, TestMessage testMsg)
	{
		try
		{
			messageMutex.WaitOne();
			TraceMessage.Write(ToString(), "HandleTestMessage " + msgType, TraceMessageType.Trace);
			bool flag = false;
			bool flag2 = false;
			MsgData msgDataFromTestMsg = GetMsgDataFromTestMsg(testMsg);
			msgDataFromTestMsg.msgType = msgType;
			switch (msgType)
			{
			case TestMsgType.OnStartOfDebugTesting:
				messageQueue.Clear();
				messageQueue.Add(msgDataFromTestMsg);
				break;
			case TestMsgType.OnTestMsgHold:
				flag2 = true;
				if (_scheduler.GlobalStatus.TestMsgHold)
				{
					retryMsgStack.Push((ArrayList)messageQueue.Clone());
				}
				else
				{
					flag = true;
				}
				_scheduler.GlobalStatus.TestMsgHold = true;
				break;
			case TestMsgType.OnTestMsgClear:
				messageQueue.Clear();
				break;
			case TestMsgType.OnTestMsgRetryDone:
				if (retryMsgStack.Count > 0)
				{
					messageQueue.InsertRange(0, retryMsgStack.Pop());
				}
				break;
			case TestMsgType.OnTestMsgSend:
				flag = true;
				flag2 = true;
				_scheduler.GlobalStatus.TestMsgHold = false;
				if (_scheduler.GlobalStatus.GlobalTestResult != 0)
				{
					for (int num = messageQueue.Count - 1; num >= 0; num--)
					{
						MsgData msgData = (MsgData)messageQueue[num];
						if (msgData.msgType == TestMsgType.OnTestResult && msgData.Result != TestResult.Passed)
						{
							_scheduler.GlobalStatus.GlobalTestResult = msgData.Result;
							break;
						}
					}
				}
				if (retryMsgStack.Count > 0)
				{
					messageQueue.InsertRange(0, retryMsgStack.Pop());
				}
				break;
			case TestMsgType.OnTestStart:
			case TestMsgType.OnTestResult:
			case TestMsgType.OnUnitStart:
			case TestMsgType.OnUnitEnd:
			case TestMsgType.OnEndOfDebugTesting:
			case TestMsgType.OnSessionStop:
			case TestMsgType.OnTreeDone:
				msgDataFromTestMsg.LoopDetails = _scheduler.GlobalStatus.LoopDetails;
				msgDataFromTestMsg.TesterConfiguration = _scheduler.GetTesterConfig();
				messageQueue.Add(msgDataFromTestMsg);
				flag2 = true;
				if (msgType == TestMsgType.OnTestStart || msgType == TestMsgType.OnTestResult)
				{
					if (!_scheduler.GlobalStatus.TestMsgHold)
					{
						flag = true;
					}
				}
				else
				{
					flag = true;
				}
				break;
			case TestMsgType.OnDLLLoaded:
			case TestMsgType.OnTargetConnected:
			case TestMsgType.OnTargetDisConnected:
				msgDataFromTestMsg.LoopDetails = _scheduler.GlobalStatus.LoopDetails;
				msgDataFromTestMsg.TesterConfiguration = _scheduler.GetTesterConfig();
				messageQueue.Add(msgDataFromTestMsg);
				flag2 = true;
				break;
			case TestMsgType.OnLinkedTreeStart:
			case TestMsgType.OnLinkedTreeEnd:
				msgDataFromTestMsg.TesterConfiguration = _scheduler.GetTesterConfig();
				if (!string.IsNullOrEmpty(_scheduler.LinkedLoopName) || !string.IsNullOrEmpty(_scheduler.LinkedLoopValue))
				{
					if (string.IsNullOrEmpty(_scheduler.GlobalStatus.LoopDetails))
					{
						msgDataFromTestMsg.LoopDetails = _scheduler.LinkedLoopName + "__" + _scheduler.LinkedLoopValue;
					}
					else
					{
						msgDataFromTestMsg.LoopDetails = _scheduler.GlobalStatus.LoopDetails + "_._" + _scheduler.LinkedLoopName + "__" + _scheduler.LinkedLoopValue;
					}
				}
				else
				{
					msgDataFromTestMsg.LoopDetails = _scheduler.GlobalStatus.LoopDetails;
				}
				messageQueue.Add(msgDataFromTestMsg);
				flag2 = true;
				if (!_scheduler.GlobalStatus.TestMsgHold)
				{
					flag = true;
				}
				break;
			case TestMsgType.OnTestSkipped:
			case TestMsgType.OnBreak:
			{
				if (_scheduler.Env.GlobalVariable.GetGlobalVariable("TestCaseExecutionMode", out var gvValue) && string.Compare(gvValue, "SkipAllManual", ignoreCase: true) == 0)
				{
					msgDataFromTestMsg.LoopDetails = _scheduler.GlobalStatus.LoopDetails;
					msgDataFromTestMsg.TesterConfiguration = _scheduler.GetTesterConfig();
				}
				messageQueue.Add(msgDataFromTestMsg);
				flag2 = true;
				break;
			}
			case TestMsgType.OnLoopStart:
			{
				structLoopValues loopData = (structLoopValues)msgDataFromTestMsg.ParamResult;
				QTMGlobalVariable.SetGlobalVariable("LOOPDETAILS_" + loopData.sLoopName, loopData.sLoopValue);
				_scheduler.Env.GlobalVariable.SetGlobalVariable("LOOPDETAILS", _scheduler.GlobalStatus.LoopDetails);
				msgDataFromTestMsg.LoopDetails = _scheduler.GlobalStatus.LoopDetails;
				msgDataFromTestMsg.LoopData = loopData;
				messageQueue.Add(msgDataFromTestMsg);
				break;
			}
			case TestMsgType.OnLoopEnd:
				_scheduler.Env.GlobalVariable.SetGlobalVariable("LOOPDETAILS", _scheduler.GlobalStatus.LoopDetails);
				msgDataFromTestMsg.LoopDetails = _scheduler.GlobalStatus.LoopDetails;
				messageQueue.Add(msgDataFromTestMsg);
				break;
			case TestMsgType.OnGoNoGoDidNotStart:
				flag = true;
				flag2 = true;
				messageQueue.Add(msgDataFromTestMsg);
				break;
			case TestMsgType.OnTestNodeSelected:
				flag2 = true;
				messageQueue.Add(msgDataFromTestMsg);
				break;
			case TestMsgType.OnLoggingDone:
				flag = true;
				flag2 = true;
				messageQueue.Add(msgDataFromTestMsg);
				break;
			case TestMsgType.OnTreePause:
			case TestMsgType.OnTreeResume:
				flag2 = true;
				messageQueue.Add(msgDataFromTestMsg);
				break;
			case TestMsgType.TMSPluginInitialized:
				flag2 = true;
				messageQueue.Add(msgDataFromTestMsg);
				if (SWPFTestTreeWindowCollection.AutomationOnTestMessageRecieved != null)
				{
					SWPFTestTreeWindowCollection.AutomationOnTestMessageRecieved(TestMsgType.TMSPluginInitialized);
				}
				break;
			default:
				messageQueue.Add(msgDataFromTestMsg);
				break;
			case TestMsgType.OnDebugMsg:
				break;
			}
			if (flag2)
			{
				try
				{
					wpfTestTreeWindowColl.OnMsg((ArrayList)messageQueue.Clone());
					TraceMessage.Write(ToString(), "HandleTestMessage Processing for test trees only - Done ", TraceMessageType.Trace);
				}
				catch (Exception ex)
				{
					TraceMessage.Write(ToString(), $"HandleTestMessage Processing for test trees only {ex.ToString()}", TraceMessageType.Exception);
				}
			}
			if (flag && !msgDataFromTestMsg.DoNotSendToPlugins)
			{
				try
				{
					_scheduler.GlobalStatus.ProcessTestResultsPlugIns = true;
					TestResultsCollection.OnMsg(GetMessagesForPlugins(messageQueue), msgDataFromTestMsg);
					DebugWindowCollection.OnMsg(GetMessagesForPlugins(messageQueue));
					messageQueue.Clear();
					TraceMessage.Write(ToString(), "HandleTestMessage Processing- Done ", TraceMessageType.Trace);
					return;
				}
				catch (Exception ex2)
				{
					TraceMessage.Write(ToString(), "HandleTestMessage Processing" + ex2.Message, TraceMessageType.Exception);
					return;
				}
			}
		}
		catch (Exception ex3)
		{
			TraceMessage.Write(ToString(), "HandleTestMessage Outermost " + msgType.ToString() + " " + ex3, TraceMessageType.Exception);
		}
		finally
		{
			messageMutex.ReleaseMutex();
		}
	}

	private void QTM_HandleCreated(object sender, EventArgs e)
	{
		try
		{
			QTMUtility.WriteLogMsg("In QTM_HandleCreated event", QTMUtility.IssueType.ThreadIssue);
			QTMUtility.WriteLogMsg("Current Thread ID: " + Thread.CurrentThread.ManagedThreadId, QTMUtility.IssueType.ThreadIssue);
			QTMUtility.WriteLogMsg("Current Thread aparment state: " + Thread.CurrentThread.GetApartmentState(), QTMUtility.IssueType.ThreadIssue);
			QTMUtility.WriteLogMsg("Current stackTrace: " + Environment.StackTrace, QTMUtility.IssueType.ThreadIssue);
		}
		catch (Exception ex)
		{
			QTMUtility.WriteLogMsg("Exception in QTM_HandleCreated event, Error:" + ex.Message, QTMUtility.IssueType.ThreadIssue);
		}
	}

	private ArrayList GetMessagesForPlugins(ArrayList messageQueue)
	{
		ArrayList arrayList = new ArrayList();
		foreach (MsgData item in messageQueue)
		{
			if (!item.DoNotSendToPlugins)
			{
				arrayList.Add(item);
			}
		}
		return arrayList;
	}

	private MsgData GetMsgDataFromTestMsg(TestMessage testMsg)
	{
		MsgData result = default(MsgData);
		result.ParamResult = testMsg.Object;
		result.TestFullPath = testMsg.Message;
		result.Result = testMsg.Result;
		result.time = DateTime.Now;
		result.TestIndex = testMsg.TestIndex;
		result.NodeRID = testMsg.NodeRID;
		result.UnitIndex = testMsg.UnitIndex;
		result.SerialNumber = testMsg.SerialNumber;
		result.ErrorCode = testMsg.ErrorCode;
		result.IsLinkedRoot = testMsg.IsLinkedRoot;
		result.TestName = testMsg.RealName;
		result.TestCaseInfo.TestCaseID = testMsg.TestCaseID;
		result.TestCaseInfo.DisplayId = testMsg.DisplayID;
		result.TestCaseInfo.TestCaseRefID = testMsg.TestCaseRefID;
		result.TestCaseInfo.TestCaseName = testMsg.TestCaseName;
		result.BlockedCRNumber = testMsg.BlockedCRNumber;
		result.DoNotSendToPlugins = testMsg.DoNotSendToPlugins;
		result.TestPathInTree = testMsg.TestPathInTree;
		result.ResultDetails = testMsg.ResultDetails;
		result.TestCaseInfo.IsApprovedTestPlan = testMsg.IsApprovedTestPlan;
		result.TestCaseInfo.TestPlanVersion = testMsg.TestPlanVersion;
		result.RealName = testMsg.RealName;
		result.ContainerInfo = testMsg.ContainerInfo;
		result.TestStartTime = testMsg.TestStartTime;
		result.TestStopTime = testMsg.TestStopTime;
		result.LimitsEnforced = testMsg.LimitsEnforced;
		result.CurrentLoopIteration = testMsg.CurrentLoopIteration;
		result.MaxLoopIteration = testMsg.MaxLoopIteration;
		return result;
	}

	public void UpdateStatusBar(TestMsgType msgType, string strMsg, string testIndex, TestResult Result, object Param, string serialNumber)
	{
		if (this.InvokeRequired())
		{
			this.BeginInvoke(delegate
			{
				statusBar.HandleTestMessage(msgType, strMsg, testIndex, Result, Param, serialNumber);
			});
		}
		else
		{
			statusBar.HandleTestMessage(msgType, strMsg, testIndex, Result, Param, serialNumber);
		}
	}

	private void OnTesterConfigChange(object sender, TesterConfigEventArgs e)
	{
		List<TesterConfigurationInfo> changedItems = e.ChangedItems;
		Hashtable testerConfig = _scheduler.GetTesterConfig();
		foreach (TesterConfigurationInfo item in changedItems)
		{
			if (!testerConfig.ContainsKey(item.Name))
			{
				TesterConfigurationList.Add(item);
				QTMGlobalVariable.SetGlobalVariable(item.Name, item.Value);
			}
			else
			{
				int index = TesterConfigurationList.IndexOf(testerConfig[item.Name]);
				TesterConfigurationList[index] = item;
				QTMGlobalVariable.SetGlobalVariable(item.Name, item.Value);
			}
		}
	}

	private void DebugWindowCollection_CreatingNewWindowEvent(object sender, EventArgs e)
	{
	}

	private void DebugWindowCollection_CreatedNewWindowEvent(object sender, EventArgs e)
	{
	}

	private void DebugWindowCollection_OnDebugCollEvent(object sender, PluginMenuEventsArgs e)
	{
		try
		{
			if (e.Key == "Restore")
			{
				DebugWindowCollection.HideDebugLayout();
				RestoreCurrDocking();
			}
			else
			{
				SaveCurrDocking();
				DebugLayout();
				DebugWindowCollection.ShowDebugLayout((int)base.Width, (int)base.Height, e.Message.ToString());
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "OnDebugCollEvent failed, " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void DebugLayout()
	{
	}

	private void SaveCurrDocking()
	{
		SaveWindowsDocking("QSPRDocking.config");
		WPFTestTreeWindowCollection.HandleToolsClick("Save Current Docking");
		TestResultsCollection.HandleToolsClick("Save Current Docking");
		DebugWindowCollection.HandleToolsClick("Save Current Docking");
	}

	protected virtual void OnPropertyChanged(string propertyName)
	{
		PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
		if (propertyChanged != null)
		{
			PropertyChangedEventArgs e = new PropertyChangedEventArgs(propertyName);
			propertyChanged(this, e);
		}
	}

	private void ChangeToQSPR2Layout()
	{
		LoadDefaultGridSettings();
		int num = (int)TestTreeContainerDockPanel.GetValue(Grid.RowProperty);
		int num2 = (int)DebugWindowsContainerDockPanel.GetValue(Grid.RowProperty);
		for (int i = 0; i < testPluginsGrid.RowDefinitions.Count; i++)
		{
			if (i != num)
			{
				testPluginsGrid.RowDefinitions[i].Height = new GridLength(0.0, GridUnitType.Pixel);
			}
		}
		for (int j = 0; j < debugUserPluginsGrid.RowDefinitions.Count; j++)
		{
			if (j != num2)
			{
				debugUserPluginsGrid.RowDefinitions[j].Height = new GridLength(0.0, GridUnitType.Pixel);
			}
		}
		mainWindowGrid.ColumnDefinitions[0].Width = new GridLength(1.0, GridUnitType.Star);
		mainWindowGrid.ColumnDefinitions[2].Width = new GridLength(2.0, GridUnitType.Star);
		TestTreeContainerRestoreButton.Visibility = Visibility.Visible;
		DebugWindowContainerRestoreButton.Visibility = Visibility.Visible;
		WPFTestTreeWindowCollection.CollpaseTestTreeProperties();
	}

	private void ChangePluginsLayout(Grid affectedGrid, int affectedGridRowIndexToMaximize, int mainWindowColumnIndexToMinimize)
	{
		LoadDefaultGridSettings();
		for (int i = 0; i < affectedGrid.RowDefinitions.Count; i++)
		{
			if (i != affectedGridRowIndexToMaximize)
			{
				affectedGrid.RowDefinitions[i].Height = new GridLength(0.0, GridUnitType.Pixel);
			}
		}
		mainWindowGrid.ColumnDefinitions[1].Width = new GridLength(0.0, GridUnitType.Pixel);
		mainWindowGrid.ColumnDefinitions[mainWindowColumnIndexToMinimize].Width = new GridLength(0.0, GridUnitType.Pixel);
	}

	private void TestTreeControlMax_Click(object sender, RoutedEventArgs e)
	{
		int affectedGridRowIndexToMaximize = (int)TestTreeContainerDockPanel.GetValue(Grid.RowProperty);
		int mainWindowColumnIndexToMinimize = (int)debugUserPluginsGrid.GetValue(Grid.ColumnProperty);
		ChangePluginsLayout(testPluginsGrid, affectedGridRowIndexToMaximize, mainWindowColumnIndexToMinimize);
		TestTreeContainerMaxButton.Visibility = Visibility.Collapsed;
		TestTreeContainerRestoreButton.Visibility = Visibility.Visible;
		WPFTestTreeWindowCollection.ExpandTestTreeProperties();
	}

	private void UserCollectionMin_Click(object sender, RoutedEventArgs e)
	{
		debugUserPluginsGrid.RowDefinitions[0].Height = new GridLength(22.0, GridUnitType.Pixel);
		UserCollectionPluginsContentControl.Visibility = Visibility.Collapsed;
		DebugGridSplitter.IsEnabled = false;
		UserCollectionMinButton.Visibility = Visibility.Collapsed;
		UserCollectionRestoreButton.Visibility = Visibility.Visible;
	}

	private void UserCollectionRestore_Click(object sender, RoutedEventArgs e)
	{
		UserCollectionPluginsContentControl.Visibility = Visibility.Visible;
		DebugGridSplitter.IsEnabled = true;
		LoadDefaultGridSettings();
		UserCollectionMinButton.Visibility = Visibility.Visible;
		UserCollectionRestoreButton.Visibility = Visibility.Collapsed;
	}

	private void TestTreeControlRestore_Click(object sender, RoutedEventArgs e)
	{
		LoadDefaultGridSettings();
		TestTreeContainerMaxButton.Visibility = Visibility.Visible;
		TestTreeContainerRestoreButton.Visibility = Visibility.Collapsed;
		DebugWindowContainerRestoreButton.Visibility = Visibility.Collapsed;
	}

	private void TestResultsControlMax_Click(object sender, RoutedEventArgs e)
	{
		int affectedGridRowIndexToMaximize = (int)TestResultsContainerDockPanel.GetValue(Grid.RowProperty);
		int mainWindowColumnIndexToMinimize = (int)debugUserPluginsGrid.GetValue(Grid.ColumnProperty);
		ChangePluginsLayout(testPluginsGrid, affectedGridRowIndexToMaximize, mainWindowColumnIndexToMinimize);
		TestResultsContainerMaxButton.Visibility = Visibility.Collapsed;
		TestResultsContainerRestoreButton.Visibility = Visibility.Visible;
	}

	private void TestResultsControlRestore_Click(object sender, RoutedEventArgs e)
	{
		LoadDefaultGridSettings();
		TestResultsContainerRestoreButton.Visibility = Visibility.Collapsed;
		TestResultsContainerMaxButton.Visibility = Visibility.Visible;
	}

	private void DebugWindowsControlMax_Click(object sender, RoutedEventArgs e)
	{
		int affectedGridRowIndexToMaximize = (int)DebugWindowsContainerDockPanel.GetValue(Grid.RowProperty);
		int mainWindowColumnIndexToMinimize = (int)testPluginsGrid.GetValue(Grid.ColumnProperty);
		ChangePluginsLayout(debugUserPluginsGrid, affectedGridRowIndexToMaximize, mainWindowColumnIndexToMinimize);
		DebugWindowContainerMaxButton.Visibility = Visibility.Collapsed;
		DebugWindowContainerRestoreButton.Visibility = Visibility.Visible;
	}

	private void DebugWindowsControlRestore_Click(object sender, RoutedEventArgs e)
	{
		LoadDefaultGridSettings();
		DebugWindowContainerMaxButton.Visibility = Visibility.Visible;
		DebugWindowContainerRestoreButton.Visibility = Visibility.Collapsed;
		TestTreeContainerRestoreButton.Visibility = Visibility.Collapsed;
	}

	private void LoadConfigurationItems()
	{
		DisableSlidingWindows();
		LoadPluginToolbars();
		window = this;
		LoadWorkspaceConfiguration();
		QSecurity.UserAccessLevelChanged += QSecurity_UserAccessLevelChanged;
		if (FeatureConfigInfo.SecurityAccessLevel == AccessLevel.Engineer.ToString() || FeatureConfigInfo.SecurityAccessLevel == AccessLevel.Technician.ToString() || FeatureConfigInfo.SecurityAccessLevel == AccessLevel.Operator.ToString())
		{
			AccessLevel accessLevel = (AccessLevel)Enum.Parse(typeof(AccessLevel), FeatureConfigInfo.SecurityAccessLevel);
			QSecurity.SetAccessLevel(accessLevel);
			QSecurity.SwitchToWindowsGroupMode();
			if (accessLevel == AccessLevel.Operator)
			{
				QSecurity_UserAccessLevelChanged(this, new UserAccessLevelChangedEventArgs(accessLevel));
			}
		}
		else
		{
			QSecurity.SetAccessLevel();
			QSecurity_UserAccessLevelChanged(this, new UserAccessLevelChangedEventArgs(QSecurity.UserAccessLevel));
		}
		WPFTestTreeWindowCollection.HandleToolsClick("QTM Loaded");
		TestResultsCollection.HandleToolsClick("QTM Loaded");
		DebugWindowCollection.HandleToolsClick("QTM Loaded");
		base.Topmost = false;
		if (qArguments.GlobalVariables != null && qArguments.GlobalVariables.Count > 0)
		{
			SetGlobalVariablesFromArg();
		}
		if (!string.IsNullOrEmpty(qArguments.BGColor))
		{
			try
			{
				System.Windows.Media.Color bgColor = (System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString(qArguments.BGColor);
				UpdateWindowBG(bgColor);
			}
			catch
			{
			}
		}
		if (qArguments.HideWindow)
		{
			Hide();
			base.ShowInTaskbar = false;
		}
		else
		{
			Show();
			base.ShowInTaskbar = true;
			Activate();
		}
		ConfigureHiveKernel();
		if (qArguments.RunTree)
		{
			MenuMessage("Run Tree");
		}
		if (!string.IsNullOrWhiteSpace(WConfig.CustomStartupEvents))
		{
			try
			{
				TraceMessage.Write(ToString(), "Launching custom start events", TraceMessageType.Trace);
				ThreadPool.QueueUserWorkItem(LaunchStartupEvents, WConfig.CustomStartupEvents.Trim());
			}
			catch (Exception ex)
			{
				TraceMessage.Write(ToString(), "QTM_Load " + ex.Message, TraceMessageType.Exception);
			}
		}
	}

	private void QSPRMainWindow_Loaded(object sender, RoutedEventArgs e)
	{
		TraceMessage.Write(ToString(), "QTM_Load", TraceMessageType.Trace);
		QTMUtility.WriteLogMsg(QTMUtility.SystemInformation(), QTMUtility.IssueType.ParameterView);
		try
		{
			base.Dispatcher.BeginInvoke((Action)delegate
			{
				LoadConfigurationItems();
			}, DispatcherPriority.ContextIdle, null);
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "QTM_Load " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void PopulateDefaultGridSettings()
	{
		defaultWindowUISettings = new QSPRMainWindowUISettings();
		defaultWindowUISettings.MainGridSetting.SaveGridSettings(mainWindowGrid);
		defaultWindowUISettings.TestPluginGridSettings.SaveGridSettings(testPluginsGrid);
		defaultWindowUISettings.DebugPluginGridSettings.SaveGridSettings(debugUserPluginsGrid);
	}

	private void LoadDefaultGridSettings()
	{
		defaultWindowUISettings.MainGridSetting.LoadGridSettings(mainWindowGrid);
		defaultWindowUISettings.TestPluginGridSettings.LoadGridSettings(testPluginsGrid);
		defaultWindowUISettings.DebugPluginGridSettings.LoadGridSettings(debugUserPluginsGrid);
	}

	private void KeyCommand_Execute(object parameter)
	{
		string key = parameter as string;
		MenuMessage(key);
	}

	private bool KeyCommand_CanExecute(object parameter)
	{
		return true;
	}

	private void MenuMessage(string key)
	{
		if (this.InvokeRequired())
		{
			this.BeginInvoke(delegate
			{
				MenuMessage(key);
			});
			return;
		}
		TraceMessage.Write(ToString(), "MenuMessage " + key, TraceMessageType.Trace);
		try
		{
			switch (key)
			{
			case "Enable All Breakpoints":
			case "Disable All Breakpoints":
			case "DeleteAllBreakpoints":
			case "Enable All Logging":
			case "Disable All Logging":
				WPFTestTreeWindowCollection.HandleToolsClick(key);
				break;
			case "Compare Test Trees":
			{
				Process process2 = new Process();
				process2.StartInfo.FileName = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), Path.Combine(FeatureConfigInfo.ToolsDirectory, "QTMTreeCompare\\QTMTreeCompare.exe"));
				process2.StartInfo.WorkingDirectory = Path.Combine(FeatureConfigInfo.ToolsDirectory, "QTMTreeCompare\\");
				process2.Start();
				break;
			}
			case "ShowStatusBar":
				if (!ShowStatusBarMenuItem.IsChecked)
				{
					ultraStatusBar1.Visibility = Visibility.Collapsed;
				}
				else
				{
					ultraStatusBar1.Visibility = Visibility.Visible;
				}
				break;
			case "Simulation Mode":
				_scheduler.GlobalStatus.SimulatorMode = !_scheduler.GlobalStatus.SimulatorMode;
				TestResultsCollection.HandleToolsClick(key);
				DebugWindowCollection.HandleToolsClick(key);
				WPFTestTreeWindowCollection.HandleToolsClick(key);
				break;
			case "Edit Work Space Configuration":
			{
				Configuration configuration = new Configuration(this);
				bool showDebugMessages = WConfig.ShowDebugMessages;
				if (configuration.ShowDialog() != System.Windows.Forms.DialogResult.OK)
				{
					break;
				}
				if (configuration.TreeChanged)
				{
					WPFTestTreeWindowCollection.TreeChanged = true;
					UltraToolbarsManager.SetToolTipText("CustomLink", WConfig.CustomAppToolTip);
				}
				TestResultsCollection.OnConfigInfo(WConfig.ExportToStruct());
				DebugWindowCollection.OnConfigInfo(WConfig.ExportToStruct());
				WPFTestTreeWindowCollection.OnConfigInfo(WConfig.ExportToStruct());
				if (showDebugMessages != WConfig.ShowDebugMessages)
				{
					if (WConfig.ShowDebugMessages)
					{
						MenuMessage("Enable All Logging");
					}
					else
					{
						MenuMessage("Disable All Logging");
					}
				}
				break;
			}
			case "Exit":
				Close();
				break;
			case "DebugCut":
			case "DebugCopy":
			case "DebugPaste":
				DebugWindowCollection.HandleToolsClick(key);
				break;
			case "TestResultsCut":
			case "TestResultsCopy":
			case "TestResultsPaste":
				WPFTestTreeWindowCollection.HandleToolsClick(key);
				break;
			case "Reset Tree Icons":
				WPFTestTreeWindowCollection.HandleToolsClick(key);
				break;
			case "Clear Debug Windows":
				DebugWindowCollection.HandleToolsClick(key);
				break;
			case "Clear Test Results":
				TestResultsCollection.HandleToolsClick(key);
				break;
			case "Clear Status Bar":
				statusBar.Clear();
				break;
			case "Reset All":
				TestResultsCollection.HandleToolsClick(key);
				DebugWindowCollection.HandleToolsClick(key);
				WPFTestTreeWindowCollection.HandleToolsClick(key);
				statusBar.Clear();
				break;
			case "Run Tree":
				_scheduler.GlobalStatus.DVTMode = false;
				RunGoNoGo(key);
				break;
			case "ReRun":
				_scheduler.GlobalStatus.DVTMode = false;
				RunGoNoGo(key);
				break;
			case "Open":
			{
				string text2 = CurrentTreeName;
				WPFTestTreeWindowCollection.HandleToolsClick(key);
				if (text2 != CurrentTreeName)
				{
					TestResultsCollection.HandleToolsClick(key);
					DebugWindowCollection.HandleToolsClick(key);
				}
				break;
			}
			case "Save":
				DebugWindowCollection.HandleToolsClick(key);
				WPFTestTreeWindowCollection.HandleToolsClick(key);
				TestResultsCollection.HandleToolsClick(key);
				break;
			case "DVTTest":
				_scheduler.GlobalStatus.DVTMode = true;
				RunGoNoGo("Run Tree");
				break;
			case "QSPR Help":
				try
				{
					string text = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "..\\help\\QSPR.chm");
					if (!File.Exists(text))
					{
						text = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "..\\help\\QDART_Help.chm");
					}
					Help.ShowHelp(null, text, HelpNavigator.TopicId, HelpUtility.GetHelpTopicId(this));
					break;
				}
				catch (Exception ex6)
				{
					AppMessageDialog.Show("Failed to launch QSPR help. " + ex6.Message, System.Windows.Forms.DialogResult.OK, MessageDialogType.Exception);
					break;
				}
			case "About QSPR":
			{
				About about = new About();
				about.ShowDialog();
				break;
			}
			case "Tree Icon Legend":
			{
				TreeIconLegenDialog treeIconLegenDialog = new TreeIconLegenDialog();
				treeIconLegenDialog.Owner = this;
				treeIconLegenDialog.ShowDialog();
				break;
			}
			case "Restore Window Layout":
				try
				{
					LoadDefaultGridSettings();
					TestTreeContainerRestoreButton.Visibility = Visibility.Collapsed;
					DebugWindowContainerRestoreButton.Visibility = Visibility.Collapsed;
					TestResultsContainerRestoreButton.Visibility = Visibility.Collapsed;
					TestTreeContainerMaxButton.Visibility = Visibility.Visible;
					DebugWindowContainerMaxButton.Visibility = Visibility.Visible;
					TestResultsContainerMaxButton.Visibility = Visibility.Visible;
					break;
				}
				catch (Exception ex5)
				{
					throw ex5;
				}
			case "Tree Edit Mode Layout":
				try
				{
					TestTreeControlMax_Click(null, null);
					break;
				}
				catch (Exception ex4)
				{
					throw ex4;
				}
			case "QSPR2.0 Window Layout":
				try
				{
					ChangeToQSPR2Layout();
					break;
				}
				catch (Exception ex3)
				{
					throw ex3;
				}
			case "Restore Customized Layout":
				LoadCustomizedUISettings();
				break;
			case "Save As Customized Layout":
				SaveCustomizedUISettings();
				AppMessageDialog.Show("Customized Layout saved.", System.Windows.Forms.DialogResult.OK, MessageDialogType.Information);
				break;
			case "Debug Layout":
				try
				{
					DebugWindowsControlMax_Click(null, null);
					break;
				}
				catch (Exception ex2)
				{
					throw ex2;
				}
			case "Test Results Layout":
				try
				{
					TestResultsControlMax_Click(null, null);
					break;
				}
				catch (Exception ex)
				{
					throw ex;
				}
			case "Abort":
				WPFTestTreeWindowCollection.HandleToolsClick(key);
				break;
			case "Charting":
				RunTutorial(key);
				break;
			case "CTS-DVT Tree":
				RunTutorial(key);
				break;
			case "Looping":
				RunTutorial(key);
				break;
			case "Parameter":
				RunTutorial(key);
				break;
			case "Properties":
				RunTutorial(key);
				break;
			case "Tester Configuration":
				RunTutorial(key);
				break;
			case "Test Results":
				RunTutorial(key);
				break;
			case "Importing - Linking Trees":
				RunTutorial(key);
				break;
			case "Adding Remote Targets":
			case "Adding Scripts":
				RunTutorial(key);
				break;
			case "Login":
				SetSecurity();
				break;
			case "CustomLink":
				if (WConfig.CustomLinkAppName != "")
				{
					Process process = new Process();
					process.StartInfo.FileName = WConfig.CustomLinkAppName;
					process.StartInfo.Arguments = WConfig.CustomLinkAppArgs;
					process.Start();
				}
				break;
			default:
				WPFTestTreeWindowCollection.HandleToolsClick(key);
				TestResultsCollection.HandleToolsClick(key);
				DebugWindowCollection.HandleToolsClick(key);
				break;
			case "Submit Bug":
				break;
			}
		}
		catch (Exception ex7)
		{
			TraceMessage.Write(ToString(), "MenuMessage " + ex7.Message, TraceMessageType.Exception);
		}
		finally
		{
			QSecurity_UserAccessLevelChanged(this, new UserAccessLevelChangedEventArgs(QSecurity.UserAccessLevel));
		}
	}

	private void SaveCustomizedUISettings()
	{
		customizedUISettings = new QSPRMainWindowUISettings();
		customizedUISettings.MainWindowSettings.SaveSettings(this);
		customizedUISettings.MainGridSetting.SaveGridSettings(mainWindowGrid);
		customizedUISettings.TestPluginGridSettings.SaveGridSettings(testPluginsGrid);
		customizedUISettings.DebugPluginGridSettings.SaveGridSettings(debugUserPluginsGrid);
		QTMUtility.Serialize(getCustomUiSettingsFileName(), customizedUISettings);
	}

	private string getCustomUiSettingsFileName()
	{
		return Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), Path.Combine(FeatureConfigInfo.ConfigDirectory, "CustomQSPRDocking.config"));
	}

	private void LoadCustomizedUISettings()
	{
		string customUiSettingsFileName = getCustomUiSettingsFileName();
		if (File.Exists(customUiSettingsFileName))
		{
			customizedUISettings = QTMUtility.Deserialize<QSPRMainWindowUISettings>(customUiSettingsFileName);
			if (customizedUISettings != null)
			{
				customizedUISettings.MainWindowSettings.LoadSettings(this);
				customizedUISettings.MainGridSetting.LoadGridSettings(mainWindowGrid);
				customizedUISettings.TestPluginGridSettings.LoadGridSettings(testPluginsGrid);
				customizedUISettings.DebugPluginGridSettings.LoadGridSettings(debugUserPluginsGrid);
			}
		}
	}

	private void RunGoNoGo(string key)
	{
		if (UnitTestingBegins())
		{
			WPFTestTreeWindowCollection.HandleToolsClick(key);
		}
	}

	public bool UnitTestingBegins()
	{
		TraceMessage.Write(ToString(), "RunUnitTree", TraceMessageType.Trace);
		try
		{
			QTMGlobalVariable.GetGlobalVariable("GONOGO_RUNNING", out var gvValue);
			if (!string.IsNullOrEmpty(gvValue) && Convert.ToBoolean(gvValue))
			{
				AppMessageDialog.Show("Invalid request, QSPR is already running another tree.", "QSPR - Error", System.Windows.Forms.DialogResult.OK, MessageDialogType.Error);
				QTMGlobalVariable.SetGlobalVariable("SetupTest Message", "Invalid request, QSPR is already running another tree.");
				_scheduler.SendGoNoGoDidNotStartMsg();
				return false;
			}
			if (WPFTestTreeWindowColl.TTDView.RegistrationRequired)
			{
				DialogResult dialogResult = AppMessageDialog.Show("                      Registered tree has changed.\nData will not be stored in database. Tree will lose registration information. \n                         Do you want to Continue?", "QSPR - Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, System.Windows.Forms.DialogResult.Yes, MessageDialogType.CriticalWarning);
				if (dialogResult == System.Windows.Forms.DialogResult.No)
				{
					QTMGlobalVariable.SetGlobalVariable("SetupTest Message", "Registered tree has changed.\nUser selected not to continue.");
					_scheduler.SendGoNoGoDidNotStartMsg();
					return false;
				}
				WPFTestTreeWindowColl.TTDView.Root.RemoveRegistrationInformation();
				WPFTestTreeWindowColl.TTDView.ApplyLeftIcons(null);
			}
			if (!WPFTestTreeWindowColl.TTDView.TreeRegistered && !QSecurity.IsTechnician && !WConfig.AllowOperatorRunUnregisteredTrees)
			{
				AppMessageDialog.Show("Tree not registered. Tests will not run.", "QSPR - Error", MessageBoxButtons.OK, MessageBoxIcon.Hand, System.Windows.Forms.DialogResult.OK, MessageDialogType.CritialError);
				QTMGlobalVariable.SetGlobalVariable("SetupTest Message", "The tree is not registered.\nSettings specify operators are not allowed to run unregistered trees.");
				_scheduler.SendGoNoGoDidNotStartMsg();
				return false;
			}
			if (!QSecurity.IsTechnician)
			{
				_ = _scheduler.GlobalStatus.SimulatorMode;
			}
			if (!WPFTestTreeWindowColl.TTDView.TreeRegistered && WPFTestTreeWindowColl.TTDView.DatabaseEnabled && WPFTestTreeWindowColl.TTDView.Root.RootProperties.TreeType != QC.QsprTestObjects.Tests.Base.TreeTypes.TestPlan)
			{
				DialogResult dialogResult2 = AppMessageDialog.Show("Tree not registered. Data will not be stored in the database.\n                      Do you want to Continue?\n\nNote: If registration is not required, set EnableDatabase property of \nthe Root node to False to not show this message again.", "QSPR - Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, System.Windows.Forms.DialogResult.Yes, MessageDialogType.Warning);
				if (dialogResult2 == System.Windows.Forms.DialogResult.No)
				{
					QTMGlobalVariable.SetGlobalVariable("SetupTest Message", "Tree not registered.\nUser selected not to continue.");
					_scheduler.SendGoNoGoDidNotStartMsg();
					return false;
				}
			}
			if (WPFTestTreeWindowColl.TTDView.TreeRegistered && !_scheduler.GlobalStatus.PluginList.Contains("XmlForDB") && WConfig.WarnXmlForDbMissing)
			{
				DialogResult dialogResult3 = AppMessageDialog.Show("Data will NOT be written to the database.\nXML DB Plugin missing. Do you want to Continue?\n\nNOTE: This warning can be disabled in Options > Workspace configuration tab by unchecking the 'Warn when XmlForDB plugin missing' checkbox.", "QSPR - Fatal Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Hand, System.Windows.Forms.DialogResult.Yes, MessageDialogType.Error);
				if (dialogResult3 == System.Windows.Forms.DialogResult.No)
				{
					QTMGlobalVariable.SetGlobalVariable("SetupTest Message", "XmlForDB plugin is missing.\nUser selected not to continue.");
					_scheduler.SendGoNoGoDidNotStartMsg();
					return false;
				}
			}
			_scheduler.GlobalStatus.SetupTestMode = true;
			WPFTestTreeWindowCollection.HandleToolsClick("Run Setup Tests");
			_scheduler.GlobalStatus.SetupTestMode = false;
			if (_scheduler.GlobalStatus.SetupTestStatus == TestResult.Passed)
			{
				TesterConfigurationList = WPFTestTreeWindowCollection.GetTesterConfiguration();
				if (TesterConfigurationList.Count == 0 && WPFTestTreeWindowColl.TTDView.Root.RootProperties.TreeType == QC.QsprTestObjects.Tests.Base.TreeTypes.GoNoGo)
				{
					DialogResult dialogResult4 = AppMessageDialog.Show("No Tester Configuration Present. \n   Do you want to Continue?\n\nNote: If tester config file is not required, \nset TreeType property of the Root node to DVT \nto not show this message again.", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, System.Windows.Forms.DialogResult.Yes, MessageDialogType.Warning);
					if (dialogResult4 == System.Windows.Forms.DialogResult.No)
					{
						QTMGlobalVariable.SetGlobalVariable("SetupTest Message", "No Tester Configuration Present.\nUser selected not to continue.");
						_scheduler.SendGoNoGoDidNotStartMsg();
						return false;
					}
				}
				_scheduler.GlobalStatus.ShowFailedTests = WConfig.ShowFailedTests;
				if (!WConfig.SuppressSerialNumberDialog && !GlobalStatus.AutomationMode)
				{
					if (WConfig.ClearSerialNumber)
					{
						WConfig.LastUsedSerialNumber = "";
					}
					using GetSerialNo getSerialNo = new GetSerialNo(TesterConfigurationList, WConfig.LastUsedSerialNumber, _scheduler.GlobalStatus.SimulatorMode);
					if (getSerialNo.ShowDialog() == System.Windows.Forms.DialogResult.OK)
					{
						WConfig.LastUsedSerialNumber = getSerialNo.SerialNo;
						return true;
					}
					QTMGlobalVariable.SetGlobalVariable("SetupTest Message", "GetSerialNo dialog was cancelled by user.");
					_scheduler.SendGoNoGoDidNotStartMsg();
					return false;
				}
				string gvValue2 = "";
				QTMGlobalVariable.GetGlobalVariable("SN", out gvValue2);
				WConfig.LastUsedSerialNumber = gvValue2;
				if (WConfig.ClearSerialNumber)
				{
					WConfig.LastUsedSerialNumber = "NA";
				}
				if (qArguments.SerialNumber.Length > 0)
				{
					WConfig.LastUsedSerialNumber = qArguments.SerialNumber;
				}
				return true;
			}
			AppMessageDialog.Show("Setup Tests failed. GoNoGo will not continue", System.Windows.Forms.DialogResult.OK, MessageDialogType.Error);
			_scheduler.SendGoNoGoDidNotStartMsg();
			return false;
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "RunUnitTree " + ex.Message, TraceMessageType.Exception);
		}
		return false;
	}

	public void UpdateWindowName(string name)
	{
		try
		{
			if (Window == null)
			{
				return;
			}
			if (Window.InvokeRequired())
			{
				Window.Invoke(delegate
				{
					UpdateWindowName(name);
				});
			}
			else
			{
				Window.Title = "QSPR - " + name;
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write("QC.QTMApplication.QTM", "UpdateWindowName " + ex.Message, TraceMessageType.Exception);
		}
	}

	public void LoadWorkspaceConfiguration()
	{
		TraceMessage.Write(ToString(), "LoadWorkspaceConfiguration", TraceMessageType.Trace);
		try
		{
			if (WConfig == null)
			{
				return;
			}
			try
			{
				WPFTestTreeWindowCollection.OnConfigInfo(WConfig.ExportToStruct());
				DebugWindowCollection.OnConfigInfo(WConfig.ExportToStruct());
				TestResultsCollection.OnConfigInfo(WConfig.ExportToStruct());
			}
			catch
			{
			}
			try
			{
				ArrayList recentFileList = WConfig.RecentFileList;
				foreach (string item in recentFileList)
				{
					AddMenuItem(item);
				}
			}
			catch
			{
			}
			if (qArguments.Filename != "")
			{
				if (File.Exists(qArguments.Filename))
				{
					WPFTestTreeWindowCollection.OpenFile(qArguments.Filename);
				}
				else
				{
					AppMessageDialog.Show(qArguments.Filename + " not found.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, System.Windows.Forms.DialogResult.OK, MessageDialogType.Error);
				}
			}
			else if (WConfig.OpenPreviousFile)
			{
				if (WConfig.RecentFileList.Count > 0 && File.Exists(WConfig.RecentFileList[0].ToString()))
				{
					WPFTestTreeWindowCollection.OpenFile(WConfig.RecentFileList[0].ToString());
				}
			}
			else if (File.Exists(WConfig.AlwaysOpenFile))
			{
				WPFTestTreeWindowCollection.OpenFile(WConfig.AlwaysOpenFile);
			}
			if (qArguments.DebugArg != "")
			{
				if (File.Exists(qArguments.DebugArg))
				{
					DebugWindowCollection.OpenFile(qArguments.DebugArg);
				}
				else
				{
					AppMessageDialog.Show(qArguments.DebugArg + " not found.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, System.Windows.Forms.DialogResult.OK, MessageDialogType.Error);
				}
			}
			if (!WConfig.EnableTracing)
			{
				return;
			}
			try
			{
				DialogResult dialogResult = AppMessageDialog.Show("Trace Logs are Enabled! \nDo you want to disable trace logging?\n\nWarning:\n    *Tracing may SLOW the application.", "QSPR - Message Center", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, System.Windows.Forms.DialogResult.No, MessageDialogType.Warning);
				if (dialogResult == System.Windows.Forms.DialogResult.Yes)
				{
					WConfig.EnableTracing = false;
					TestResultsCollection.OnConfigInfo(WConfig.ExportToStruct());
					WPFTestTreeWindowCollection.OnConfigInfo(WConfig.ExportToStruct());
					DebugWindowCollection.OnConfigInfo(WConfig.ExportToStruct());
					Directory.Delete(FeatureConfigInfo.TraceMsgDirectory, recursive: true);
					Directory.CreateDirectory(Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), FeatureConfigInfo.TraceMsgDirectory));
				}
			}
			catch
			{
			}
		}
		catch (Exception ex)
		{
			SplashScreen.CloseForm();
			TraceMessage.Write(ToString(), "LoadWorkspaceConfiguration failed, " + ex.Message, TraceMessageType.Exception);
			AppMessageDialog.Show("Error loading workspace configuration.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, System.Windows.Forms.DialogResult.OK, MessageDialogType.Exception);
		}
	}

	private void QSecurity_UserAccessLevelChanged(object sender, UserAccessLevelChangedEventArgs e)
	{
		try
		{
			switch (e.UserAccessLevel)
			{
			case AccessLevel.Operator:
				UltraToolbarsManager.SetEnabled("Edit", enabledValue: false);
				UltraToolbarsManager.SetEnabled("Cut", enabledValue: false);
				UltraToolbarsManager.SetEnabled("Copy", enabledValue: false);
				UltraToolbarsManager.SetEnabled("Paste", enabledValue: false);
				UltraToolbarsManager.SetEnabled("New", enabledValue: false);
				UltraToolbarsManager.SetEnabled("Save", enabledValue: false);
				UltraToolbarsManager.SetEnabled("SaveAs", enabledValue: false);
				UltraToolbarsManager.SetEnabled("Synchronize", enabledValue: false);
				UltraToolbarsManager.SetEnabled("Show Parameters", enabledValue: false);
				UltraToolbarsManager.SetEnabled("Options", enabledValue: false);
				UltraToolbarsManager.SetEnabled("View", enabledValue: false);
				UltraToolbarsManager.SetEnabled("Simulation Mode", enabledValue: false);
				UltraToolbarsManager.SetEnabled("Tools", enabledValue: false);
				UltraToolbarsManager.SetEnabled("DVTTest", enabledValue: false);
				UltraToolbarsManager.SetEnabled("Debug", enabledValue: false);
				UpdateWindowBG(System.Windows.SystemColors.ControlColor);
				UltraToolbarsManager.SetEnabled("Login", enabledValue: true);
				UpdateLoginButton(loggedIn: false);
				break;
			case AccessLevel.Technician:
				UltraToolbarsManager.SetEnabled("Edit", enabledValue: true);
				UltraToolbarsManager.SetEnabled("New", enabledValue: true);
				UltraToolbarsManager.SetEnabled("Save", enabledValue: false);
				UltraToolbarsManager.SetEnabled("SaveAs", enabledValue: false);
				UltraToolbarsManager.SetEnabled("Synchronize", enabledValue: true);
				UltraToolbarsManager.SetEnabled("Show Parameters", enabledValue: true);
				UltraToolbarsManager.SetEnabled("Options", enabledValue: true);
				UltraToolbarsManager.SetEnabled("View", enabledValue: true);
				UltraToolbarsManager.SetEnabled("Simulation Mode", enabledValue: true);
				UltraToolbarsManager.SetEnabled("Tools", enabledValue: true);
				UltraToolbarsManager.SetEnabled("DVTTest", enabledValue: true);
				UltraToolbarsManager.SetEnabled("Debug", enabledValue: true);
				UpdateWindowBG(System.Windows.SystemColors.ControlColor);
				UltraToolbarsManager.SetEnabled("Login", enabledValue: true);
				UpdateLoginButton(loggedIn: true);
				break;
			case AccessLevel.Engineer:
				UltraToolbarsManager.SetEnabled("Edit", enabledValue: true);
				UltraToolbarsManager.SetEnabled("New", enabledValue: true);
				UltraToolbarsManager.SetEnabled("Save", !QSecurity.LockedQGroup);
				UltraToolbarsManager.SetEnabled("SaveAs", enabledValue: true);
				UltraToolbarsManager.SetEnabled("Synchronize", enabledValue: true);
				UltraToolbarsManager.SetEnabled("Show Parameters", enabledValue: true);
				UltraToolbarsManager.SetEnabled("Options", enabledValue: true);
				UltraToolbarsManager.SetEnabled("View", enabledValue: true);
				UltraToolbarsManager.SetEnabled("Simulation Mode", enabledValue: true);
				UltraToolbarsManager.SetEnabled("Tools", enabledValue: true);
				UltraToolbarsManager.SetEnabled("DVTTest", enabledValue: true);
				UltraToolbarsManager.SetEnabled("Debug", enabledValue: true);
				if (QSecurity.IsSecurityDisabled)
				{
					UpdateWindowBG(System.Windows.SystemColors.ControlColor);
					UpdateLoginButton(loggedIn: false);
					UltraToolbarsManager.SetEnabled("Login", enabledValue: false);
					break;
				}
				UltraToolbarsManager.SetEnabled("Login", enabledValue: true);
				if (QSecurity.IsPasswordMode)
				{
					UpdateLoginButton(loggedIn: true);
					UpdateWindowBG(Colors.Orange);
					break;
				}
				if (QSecurity.Impersonating)
				{
					UpdateLoginButton(loggedIn: true);
				}
				else
				{
					UpdateLoginButton(loggedIn: false);
				}
				UpdateWindowBG(System.Windows.SystemColors.ControlColor);
				break;
			}
		}
		catch
		{
		}
	}

	private void SetGlobalVariablesFromArg()
	{
		foreach (string key in qArguments.GlobalVariables.Keys)
		{
			QTMGlobalVariable.SetGlobalVariable(key, qArguments.GlobalVariables[key]);
		}
	}

	public void UpdateWindowBG(System.Drawing.Color bgColor)
	{
		System.Windows.Media.Color bgColor2 = default(System.Windows.Media.Color);
		bgColor2.A = bgColor.A;
		bgColor2.B = bgColor.B;
		bgColor2.R = bgColor.R;
		bgColor2.G = bgColor.G;
		UpdateWindowBG(bgColor2);
	}

	public void UpdateWindowBG(System.Windows.Media.Color bgColor)
	{
		try
		{
			if (Window != null)
			{
				Window.Background = new SolidColorBrush(bgColor);
			}
			if (wpfTestTreeWindowColl != null)
			{
				wpfTestTreeWindowColl.Background = new SolidColorBrush(bgColor);
			}
			if (debugWindowCollection != null)
			{
				debugWindowCollection.Background = new SolidColorBrush(bgColor);
			}
			if (testResultsCollection != null)
			{
				testResultsCollection.BackColor = System.Drawing.Color.FromArgb(bgColor.A, bgColor.R, bgColor.G, bgColor.B);
			}
			if (userWindowCollection != null)
			{
				userWindowCollection.BackColor = System.Drawing.Color.FromArgb(bgColor.A, bgColor.R, bgColor.G, bgColor.B);
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write("QC.QTMApplication.QTM", "UpdateWindowBG " + ex.Message, TraceMessageType.Exception);
		}
	}

	private static void AddMenuItem(string fileName)
	{
		try
		{
			System.Windows.Controls.MenuItem menuItem = new System.Windows.Controls.MenuItem();
			menuItem.Tag = fileName + "Menu##Item";
			menuItem.Header = fileName;
			menuItem.CommandParameter = fileName + "Menu##Item";
			menuItem.Command = sKeyCommand;
			RecentMenuItemBar.Items.Add(menuItem);
		}
		catch
		{
		}
	}

	public static void UpdateToolBar(TestTreeSelectedNode nodeStatus)
	{
		if (UltraToolbarsManager != null)
		{
			ResetToolbarTestTree();
			switch (nodeStatus)
			{
			case TestTreeSelectedNode.Empty:
				SetEmptyNodeState();
				break;
			case TestTreeSelectedNode.LoopDisabledFolderNode:
				SetLoopDisabledFolderNodeState();
				break;
			case TestTreeSelectedNode.LoopEnabledFolderNode:
				SetLoopEnabledFolderNodeState();
				break;
			case TestTreeSelectedNode.RootNode:
				SetRootNodeState();
				break;
			}
		}
	}

	private static void SetRootNodeState()
	{
		UltraToolbarsManager.SetEnabled("Copy", enabledValue: false);
		UltraToolbarsManager.SetEnabled("Cut", enabledValue: false);
		UltraToolbarsManager.SetEnabled("Delete", enabledValue: false);
		UltraToolbarsManager.SetEnabled("Loop Setup", enabledValue: false);
	}

	private static void SetLoopDisabledFolderNodeState()
	{
		UltraToolbarsManager.SetEnabled("Loop Setup", enabledValue: false);
	}

	private static void SetLoopEnabledFolderNodeState()
	{
		UltraToolbarsManager.SetEnabled("Loop Setup", enabledValue: true);
	}

	private static void SetEmptyNodeState()
	{
		UltraToolbarsManager.SetEnabled("Copy", enabledValue: false);
		UltraToolbarsManager.SetEnabled("Cut", !QSecurity.LockedQGroup);
		UltraToolbarsManager.SetEnabled("Delete", !QSecurity.LockedQGroup);
		UltraToolbarsManager.SetEnabled("Loop Setup", !QSecurity.LockedQGroup);
		UltraToolbarsManager.SetEnabled("New Folder", !QSecurity.LockedQGroup);
		UltraToolbarsManager.SetEnabled("Show Static View of Parameters", enabledValue: false);
		UltraToolbarsManager.SetEnabled("Show Parameters", enabledValue: false);
		UltraToolbarsManager.SetEnabled("Synchronize", enabledValue: false);
	}

	private static void ResetToolbarTestTree()
	{
		UltraToolbarsManager.SetEnabled("Copy", enabledValue: true);
		UltraToolbarsManager.SetEnabled("Cut", !QSecurity.LockedQGroup);
		UltraToolbarsManager.SetEnabled("Delete", !QSecurity.LockedQGroup);
		UltraToolbarsManager.SetEnabled("Loop Setup", !QSecurity.LockedQGroup);
		UltraToolbarsManager.SetEnabled("New Folder", !QSecurity.LockedQGroup);
		UltraToolbarsManager.SetEnabled("Show Static View of Parameters", enabledValue: true);
		UltraToolbarsManager.SetEnabled("Show Parameters", enabledValue: true);
		UltraToolbarsManager.SetEnabled("Synchronize", enabledValue: true);
	}

	public static void UpdateToolBar(RegistrySelectedNode nodeStatus)
	{
		if (UltraToolbarsManager != null)
		{
			switch (nodeStatus)
			{
			case RegistrySelectedNode.Empty:
				SetRegistryEmptyNodeState();
				break;
			case RegistrySelectedNode.DllLoadedNode:
				SetDllLoadedState();
				break;
			case RegistrySelectedNode.DllUnLoadedNode:
				SetDllUnLoadedState();
				break;
			case RegistrySelectedNode.ThisPCNode:
				SetThisPCNodeState();
				break;
			case RegistrySelectedNode.EntersRegistryTree:
				SetRegistryEnterState();
				break;
			case RegistrySelectedNode.LeavesRegistryTree:
				SetRegistryLeaveState();
				break;
			case RegistrySelectedNode.EntersTreePanel:
				SetTreeViewEnterStatus();
				break;
			case RegistrySelectedNode.LeavesTreePanel:
				SetTreeViewLeaveStatus();
				break;
			case RegistrySelectedNode.RemoteTargetConnected:
			case RegistrySelectedNode.RemoteTargetDisConnected:
			case RegistrySelectedNode.DllNodeDisconnectedTarget:
			case RegistrySelectedNode.ScriptNode:
			case RegistrySelectedNode.TestNode:
				break;
			}
		}
	}

	private static void SetDllLoadedState()
	{
		UltraToolbarsManager.SetEnabled("Add DLL", enabledValue: false);
		UltraToolbarsManager.SetEnabled("UnLoad DLL", enabledValue: true);
		UltraToolbarsManager.SetEnabled("Load DLL", enabledValue: false);
		UltraToolbarsManager.SetEnabled("Delete DLL", enabledValue: false);
	}

	private static void SetDllUnLoadedState()
	{
		UltraToolbarsManager.SetEnabled("Add DLL", enabledValue: false);
		UltraToolbarsManager.SetEnabled("UnLoad DLL", enabledValue: false);
		UltraToolbarsManager.SetEnabled("Load DLL", enabledValue: true);
		UltraToolbarsManager.SetEnabled("Delete DLL", enabledValue: true);
	}

	private static void SetThisPCNodeState()
	{
		UltraToolbarsManager.SetEnabled("Add DLL", enabledValue: true);
		UltraToolbarsManager.SetEnabled("UnLoad DLL", enabledValue: false);
		UltraToolbarsManager.SetEnabled("Load DLL", enabledValue: false);
		UltraToolbarsManager.SetEnabled("Delete DLL", enabledValue: false);
	}

	private static void SetRegistryEmptyNodeState()
	{
		UltraToolbarsManager.SetEnabled("Add DLL", enabledValue: false);
		UltraToolbarsManager.SetEnabled("UnLoad DLL", enabledValue: false);
		UltraToolbarsManager.SetEnabled("Load DLL", enabledValue: false);
		UltraToolbarsManager.SetEnabled("Delete DLL", enabledValue: false);
	}

	private static void SetRegistryEnterState()
	{
		UltraToolbarsManager.SetEnabled("Targets", enabledValue: false);
	}

	private static void SetRegistryLeaveState()
	{
		UltraToolbarsManager.SetEnabled("Targets", enabledValue: false);
	}

	private static void SetTreeViewLeaveStatus()
	{
		UltraToolbarsManager.SetEnabled("Edit", enabledValue: false);
		UltraToolbarsManager.SetEnabled("Cut", enabledValue: false);
		UltraToolbarsManager.SetEnabled("Copy", enabledValue: false);
		UltraToolbarsManager.SetEnabled("Paste", enabledValue: false);
		UltraToolbarsManager.SetEnabled("Show Static View of Parameters", enabledValue: false);
		UltraToolbarsManager.SetEnabled("Show Parameters", enabledValue: false);
		UltraToolbarsManager.SetEnabled("Synchronize", enabledValue: false);
		UltraToolbarsManager.SetEnabled("Edit", enabledValue: false);
		UltraToolbarsManager.SetEnabled("Loop Setup", enabledValue: false);
		UltraToolbarsManager.SetEnabled("Delete", enabledValue: false);
		UltraToolbarsManager.SetEnabled("Cut", enabledValue: false);
		UltraToolbarsManager.SetEnabled("Copy", enabledValue: false);
		UltraToolbarsManager.SetEnabled("Paste", enabledValue: false);
		UltraToolbarsManager.SetEnabled("Show Static View of Parameters", enabledValue: false);
		UltraToolbarsManager.SetEnabled("Show Parameters", enabledValue: false);
		UltraToolbarsManager.SetEnabled("Synchronize", enabledValue: false);
	}

	private static void SetTreeViewEnterStatus()
	{
		UltraToolbarsManager.SetEnabled("Edit", enabledValue: true);
		UltraToolbarsManager.SetEnabled("Cut", !QSecurity.LockedQGroup);
		UltraToolbarsManager.SetEnabled("Copy", enabledValue: true);
		UltraToolbarsManager.SetEnabled("Paste", !QSecurity.LockedQGroup);
		UltraToolbarsManager.SetEnabled("Synchronize", enabledValue: true);
		UltraToolbarsManager.SetEnabled("Show Static View of Parameters", enabledValue: true);
		UltraToolbarsManager.SetEnabled("Show Parameters", enabledValue: true);
		UltraToolbarsManager.SetEnabled("Edit", enabledValue: true);
		UltraToolbarsManager.SetEnabled("Loop Setup", !QSecurity.LockedQGroup);
		UltraToolbarsManager.SetEnabled("Delete", !QSecurity.LockedQGroup);
		UltraToolbarsManager.SetEnabled("Cut", !QSecurity.LockedQGroup);
		UltraToolbarsManager.SetEnabled("Copy", !QSecurity.LockedQGroup);
		UltraToolbarsManager.SetEnabled("Synchronize", enabledValue: true);
		UltraToolbarsManager.SetEnabled("Show Static View of Parameters", enabledValue: true);
		UltraToolbarsManager.SetEnabled("Show Parameters", enabledValue: true);
	}

	private void LoadPluginToolbars()
	{
		try
		{
			WPFTestTreeWindowCollection.LoadPluginToolbars();
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "LoadPluginToolbars " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void QSPRMainWindow_Closing(object sender, CancelEventArgs e)
	{
		TraceMessage.WriteAlways(ToString(), "QTM_Closing", TraceMessageType.Trace);
		if (SWPFTestTreeWindowCollection.CloseHidesUI)
		{
			e.Cancel = true;
			MsgData msgData = default(MsgData);
			msgData.msgType = TestMsgType.QsprHidden;
			msgData.ParamResult = "";
			ArrayList arrayList = new ArrayList();
			arrayList.Add(msgData);
			SWPFTestTreeWindowCollection.OnMsg(arrayList);
			return;
		}
		try
		{
			DialogResult dialogResult = System.Windows.Forms.DialogResult.Yes;
			if (!qArguments.CloseAfterRunning)
			{
				dialogResult = AppMessageDialog.Show("Do you want to close?", "QSPR - Closing", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2, System.Windows.Forms.DialogResult.Yes, MessageDialogType.Warning);
			}
			if (dialogResult == System.Windows.Forms.DialogResult.Yes)
			{
				if (WPFTestTreeWindowCollection.Closing() && TestResultsCollection.Closing() && DebugWindowCollection.Closing())
				{
					TraceMessage.WriteAlways(ToString(), "QTM_Closing - No plugins cancelled the close event", TraceMessageType.Trace);
					_scheduler.GlobalStatus.Abort = true;
					File.Delete(WPFTestTreeWindowColl.TTDView.TEMP_FOLDER + "\\qtmTemp_" + Process.GetCurrentProcess().Id + ".xtt");
					if (DebugWindowCollection.IsDebugWindowsMaximized)
					{
						DebugWindowCollection.HideDebugLayout();
						RestoreCurrDocking();
					}
					SaveSettings();
					WPFTestTreeWindowCollection.HandleToolsClick("Exit");
					TestResultsCollection.HandleToolsClick("Exit");
					DebugWindowCollection.HandleToolsClick("Exit");
					_scheduler.KernelMgr.HandleHiveTestToolsClick("Exit");
					messageMutex.Close();
					_scheduler.mutTest.Close();
					_scheduler.KernelMgr.ShutdownHiveKernel();
					_scheduler.KernelMgr.ShutdownScriptKernel();
					_scheduler.KernelMgr.ShutdownLabVIEWKernel();
					_scheduler.KernelMgr.ShutdownDotNetKernel();
					e.Cancel = false;
					if (qArguments.CloseAfterRunning || GlobalStatus.AutomationMode)
					{
						IsSafeToExit();
						TraceMessage.WriteAlways(ToString(), "IsSafeToExit has returned", TraceMessageType.Trace);
					}
					_scheduler.GlobalStatus.RunningStatusChangedEvent -= GlobalStatus_RunningStatusChangedEvent;
					theRegistry.ClearTargets();
				}
				else
				{
					e.Cancel = true;
				}
			}
			else
			{
				e.Cancel = true;
			}
		}
		catch (Exception ex)
		{
			DialogResult dialogResult2 = AppMessageDialog.Show("Error cleaning up before closing due to " + ex.Message + " Continue Closing?", "QSPR - Closing", MessageBoxButtons.YesNo, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button2, System.Windows.Forms.DialogResult.Yes, MessageDialogType.Exception);
			if (dialogResult2 == System.Windows.Forms.DialogResult.Yes)
			{
				e.Cancel = false;
			}
			else
			{
				e.Cancel = true;
			}
		}
		TraceMessage.EndXMLLogging();
	}

	private bool IsSafeToExit()
	{
		TraceMessage.WriteAlways(ToString(), "IsSafeToExit", TraceMessageType.Trace);
		try
		{
			int num = 0;
			while (!WPFTestTreeWindowCollection.IsSafeToExit() || !TestResultsCollection.IsSafeToExit() || !DebugWindowCollection.IsSafeToExit() || !_scheduler.KernelMgr.IsSafeToExit)
			{
				if (num == 60000)
				{
					TraceMessage.Write(ToString(), "Waited too long, forced to exit", TraceMessageType.Error);
					Process.GetCurrentProcess().Kill();
					return false;
				}
				Thread.Sleep(500);
				num += 500;
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "Failed to check if it's safe to exit on all plugins, " + ex.Message + ex.InnerException, TraceMessageType.Exception);
		}
		return true;
	}

	private void RestoreCurrDocking()
	{
		LoadDockingConfiguration("QSPRDocking.config", loadDefault: true);
		WPFTestTreeWindowCollection.HandleToolsClick("Restore Current Docking");
		TestResultsCollection.HandleToolsClick("Restore Current Docking");
		DebugWindowCollection.HandleToolsClick("Restore Current Docking");
	}

	internal static bool SetSecurityLevelFromAutomation(int securityLevel)
	{
		if (securityLevel < 0 || securityLevel > 3)
		{
			return false;
		}
		AccessLevel userAccessLevel = QSecurity.UserAccessLevel;
		AccessLevel accessLevel = userAccessLevel;
		switch (securityLevel)
		{
		case 0:
			QSecurity.SetAccessLevel();
			break;
		case 1:
			accessLevel = AccessLevel.Operator;
			goto default;
		case 2:
			accessLevel = AccessLevel.Technician;
			goto default;
		case 3:
			accessLevel = AccessLevel.Engineer;
			goto default;
		default:
			if (accessLevel != userAccessLevel)
			{
				QSecurity.SetAccessLevel(accessLevel);
			}
			break;
		}
		return true;
	}

	private void LoadDockingConfiguration(string resourceFileName, bool loadDefault)
	{
		TraceMessage.Write(ToString(), "LoadDockingConfiguration", TraceMessageType.Trace);
		try
		{
			string filePath = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), Path.Combine(FeatureConfigInfo.ConfigDirectory, resourceFileName));
			mainWindowSettings = QTMUtility.Deserialize<QSPRMainWindowUISettings>(filePath);
			if (mainWindowSettings == null)
			{
				mainWindowSettings = new QSPRMainWindowUISettings();
			}
			else
			{
				mainWindowSettings.MainWindowSettings.LoadSettings(this);
				mainWindowSettings.MainGridSetting.LoadGridSettings(mainWindowGrid);
				mainWindowSettings.TestPluginGridSettings.LoadGridSettings(testPluginsGrid);
				mainWindowSettings.DebugPluginGridSettings.LoadGridSettings(debugUserPluginsGrid);
				if (testPluginsGrid.RowDefinitions[0].Height.Value > 0.0 && testPluginsGrid.RowDefinitions[1].Height.Value == 0.0 && testPluginsGrid.RowDefinitions[2].Height.Value == 0.0)
				{
					TestTreeContainerMaxButton.Visibility = Visibility.Collapsed;
					TestTreeContainerRestoreButton.Visibility = Visibility.Visible;
				}
				else if (testPluginsGrid.RowDefinitions[0].Height.Value == 0.0 && testPluginsGrid.RowDefinitions[1].Height.Value == 0.0 && testPluginsGrid.RowDefinitions[2].Height.Value > 0.0)
				{
					TestResultsContainerMaxButton.Visibility = Visibility.Collapsed;
					TestResultsContainerRestoreButton.Visibility = Visibility.Visible;
				}
				else if (mainWindowGrid.ColumnDefinitions[0].Width.Value == 0.0)
				{
					DebugWindowContainerMaxButton.Visibility = Visibility.Collapsed;
					DebugWindowContainerRestoreButton.Visibility = Visibility.Visible;
				}
			}
			DisableSlidingWindows();
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "LoadDockingConfiguration " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void DisableSlidingWindows()
	{
	}

	private void LoadPredefinedDockingConfiguration(string resourceFile)
	{
		try
		{
			using Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceFile);
			if (stream != null)
			{
				DisableSlidingWindows();
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "LoadDefaultConfiguration for file " + resourceFile + " Error: " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void SaveSettings()
	{
		TraceMessage.Write(ToString(), "SaveSettings", TraceMessageType.Trace);
		TextWriter textWriter = null;
		try
		{
			SaveWindowsDocking("QSPRDocking.config");
			string path = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), Path.Combine(FeatureConfigInfo.ConfigDirectory, "Workspace.config"));
			textWriter = new StreamWriter(path);
			XmlSerializer xmlSerializer = new XmlSerializer(typeof(WorkspaceConfig));
			xmlSerializer.Serialize(textWriter, WConfig);
			textWriter.Close();
			TraceMessage.EndXMLLogging();
			TraceMessage.EndSuppressedMsgLogging();
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "SaveSettings " + ex.Message, TraceMessageType.Exception);
		}
		finally
		{
			textWriter?.Close();
		}
	}

	private void SaveWindowsDocking(string configFileName)
	{
		try
		{
			string filePath = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), Path.Combine(FeatureConfigInfo.ConfigDirectory, configFileName));
			mainWindowSettings.MainWindowSettings.SaveSettings(this);
			mainWindowSettings.MainGridSetting.SaveGridSettings(mainWindowGrid);
			mainWindowSettings.TestPluginGridSettings.SaveGridSettings(testPluginsGrid);
			mainWindowSettings.DebugPluginGridSettings.SaveGridSettings(debugUserPluginsGrid);
			QTMUtility.Serialize(filePath, mainWindowSettings);
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "SaveWindowsDocking for file " + configFileName + " Error: " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void StoreAppWindowSettings()
	{
		if (WConfig.MinimizeAtStartup)
		{
			QTMUserSettings.Default.Minimized = true;
			QTMUserSettings.Default.Maximized = false;
		}
		else if (base.WindowState == WindowState.Maximized)
		{
			QTMUserSettings.Default.Maximized = true;
		}
		else if (base.WindowState == WindowState.Minimized)
		{
			QTMUserSettings.Default.Minimized = true;
			QTMUserSettings.Default.Maximized = false;
		}
		else
		{
			QTMUserSettings.Default.Maximized = false;
			QTMUserSettings.Default.Minimized = false;
		}
		QTMUserSettings.Default.Save();
	}

	private void GlobalStatus_RunningStatusChangedEvent(GlobalStatus.RunningStateChanged state)
	{
		if (this.InvokeRequired())
		{
			this.Invoke(delegate
			{
				GlobalStatus_RunningStatusChangedEvent(state);
			});
			return;
		}
		bool enabledValue = true;
		if (QSecurity.IsOperator)
		{
			enabledValue = _scheduler.QTMData.WConfig.AllowOperatorAbortTestRun;
		}
		switch (state)
		{
		case GlobalStatus.RunningStateChanged.TestRunning:
			if (_scheduler.GlobalStatus.SecondaryQueueRunning)
			{
				break;
			}
			if (_scheduler.GlobalStatus.TestRunning)
			{
				UltraToolbarsManager.SetEnabled("Run Tree", enabledValue: false);
				UltraToolbarsManager.SetEnabled("DVTTest", enabledValue: false);
				UltraToolbarsManager.SetEnabled("Pause", enabledValue: true);
				UltraToolbarsManager.SetToolTipText("Pause", "Pause Tree");
				UltraToolbarsManager.SetEnabled("Resume", enabledValue: false);
				UltraToolbarsManager.SetEnabled("Stop Tree", enabledValue: true);
				UltraToolbarsManager.SetEnabled("Abort", enabledValue);
				UltraToolbarsManager.SetEnabled("Rerun", enabledValue: false);
				break;
			}
			UltraToolbarsManager.SetEnabled("Run Tree", enabledValue: true);
			UltraToolbarsManager.SetEnabled("DVTTest", enabledValue: true);
			UltraToolbarsManager.SetEnabled("Pause", enabledValue: false);
			UltraToolbarsManager.SetEnabled("Resume", enabledValue: false);
			UltraToolbarsManager.SetEnabled("Stop Tree", enabledValue: false);
			UltraToolbarsManager.SetEnabled("Abort", enabledValue: false);
			if (_scheduler.GlobalStatus.GlobalTestResult == TestResult.Failed)
			{
				UltraToolbarsManager.SetEnabled("Rerun", enabledValue: true);
			}
			else
			{
				UltraToolbarsManager.SetEnabled("Rerun", enabledValue: false);
			}
			break;
		case GlobalStatus.RunningStateChanged.SecondaryQueueRunning:
			if (_scheduler.GlobalStatus.SecondaryQueueRunning)
			{
				UltraToolbarsManager.SetEnabled("Pause", enabledValue: false);
				UltraToolbarsManager.SetEnabled("Stop Tree", enabledValue: true);
				UltraToolbarsManager.SetEnabled("Abort", enabledValue);
			}
			else
			{
				UltraToolbarsManager.SetEnabled("Pause", enabledValue: true);
				UltraToolbarsManager.SetToolTipText("Pause", "Resume Tree");
				UltraToolbarsManager.SetEnabled("Stop Tree", enabledValue: true);
				UltraToolbarsManager.SetEnabled("Abort", enabledValue: false);
			}
			break;
		case GlobalStatus.RunningStateChanged.Pause:
			if (_scheduler.GlobalStatus.Pause)
			{
				UltraToolbarsManager.SetToolTipText("Pause", "Resume Tree");
				UltraToolbarsManager.SetImage("Pause", "pack://application:,,,/QSPR;component/Icons/Resume.png");
				UltraToolbarsManager.SetEnabled("Stop Tree", enabledValue: true);
				UltraToolbarsManager.SetEnabled("Abort", enabledValue: false);
				_scheduler.SendTreePauseResumeMsg(true);
			}
			else
			{
				UltraToolbarsManager.SetToolTipText("Pause", "Pause Tree");
				UltraToolbarsManager.SetImage("Pause", "pack://application:,,,/QSPR;component/Icons/Pause.png");
				UltraToolbarsManager.SetEnabled("Stop Tree", enabledValue: true);
				UltraToolbarsManager.SetEnabled("Abort", enabledValue);
				_scheduler.SendTreePauseResumeMsg(false);
			}
			break;
		case GlobalStatus.RunningStateChanged.Stop:
			if (_scheduler.GlobalStatus.Stop)
			{
				sSignal.Dispose();
				if (!_scheduler.GlobalStatus.Abort && _scheduler.GlobalStatus.TestRunning)
				{
					sSignal = new StopSignal();
					sSignal.Show();
				}
			}
			else
			{
				CloseStopDialog();
			}
			break;
		}
	}

	public static void CloseStopDialog()
	{
		if (sSignal.InvokeRequired)
		{
			sSignal.BeginInvoke((MethodInvoker)delegate
			{
				CloseStopDialog();
			});
		}
		else
		{
			sSignal.Close();
		}
	}

	private void StatusBarMouseEnter_Click(object sender, System.Windows.Input.MouseEventArgs e)
	{
		try
		{
			System.Windows.Controls.ToolTip toolTip = new System.Windows.Controls.ToolTip();
			if (WConfig.ShowToolTips)
			{
				string text = "";
				text = text + "Test Running : " + statusBar.TestMessage;
				text = text + "\nMessage : " + statusBar.DebugMessage;
				text = text + "\nLoop Details : " + statusBar.LoopMessage;
				text = text + "\nCurrent Unit : " + statusBar.UnitMessage;
				text = text + "\nPlugin Message : " + statusBar.PluginMessage;
				text = text + "\nTest Elapsed Time : " + statusBar.CurrentTestElapsedTime;
				text = text + "\nTotal Elapsed Time : " + statusBar.ElapsedTime;
				toolTip.IsEnabled = true;
				toolTip.Content = text;
			}
			else
			{
				toolTip.IsEnabled = false;
			}
			ultraStatusBar1.ToolTip = toolTip;
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "StatusBarMouseEnter_Click " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void ArrangeDeubgWinInVerticalMode_Click(object sender, RoutedEventArgs e)
	{
		debugWindowCollection.DebugGrouping = DebugWindowsGroupings.Vertical;
	}

	private void ArrangeDeubgWinInHorizontalMode_Click(object sender, RoutedEventArgs e)
	{
		debugWindowCollection.DebugGrouping = DebugWindowsGroupings.Horizontal;
	}

	private void ArrangeDeubgWinInTabbedMode_Click(object sender, RoutedEventArgs e)
	{
		debugWindowCollection.DebugGrouping = DebugWindowsGroupings.Tabbed;
	}

	private void Window_MouseDown(object sender, MouseButtonEventArgs e)
	{
		Focus();
	}

	private void mainWindowGrid_MouseDown(object sender, MouseButtonEventArgs e)
	{
		mainWindowGrid.Focus();
	}

	private void QsprMainMenu_MouseDown(object sender, MouseButtonEventArgs e)
	{
		QsprMainMenu.Focus();
	}

	private void QsprMainToolBar_MouseDown(object sender, MouseButtonEventArgs e)
	{
		QsprMainToolBar.Focus();
	}

	private void ultraStatusBar1_MouseDown(object sender, MouseButtonEventArgs e)
	{
		ultraStatusBar1.Focus();
	}

	private void mainToolbar_Loaded(object sender, RoutedEventArgs e)
	{
		if (sender is System.Windows.Controls.ToolBar toolBar && toolBar.Template.FindName("OverflowGrid", toolBar) is FrameworkElement frameworkElement)
		{
			frameworkElement.Visibility = Visibility.Collapsed;
		}
	}

	private void debugUserPluginsGrid_GotFocus(object sender, RoutedEventArgs e)
	{
		WPFTestTreeWindowCollection.TreeInFocus = false;
	}

	private void TestResultsContainerDockPanel_GotFocus(object sender, RoutedEventArgs e)
	{
		WPFTestTreeWindowCollection.TreeInFocus = false;
	}

	[DebuggerNonUserCode]
	[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
	internal Delegate _CreateDelegate(Type delegateType, string handler)
	{
		return Delegate.CreateDelegate(delegateType, this, handler);
	}
}
