public void Listen_events(Cpu.Pin pin, NativeEventHandler callback)
 {
     Thread t = new Thread(this.Listen);
     ThreadHelper th = new ThreadHelper();
     th.Pin = pin;
     th.Callback = callback;
     t.Start(th);
 }
예제 #2
0
		public void CreateNewLangProject_DbFilesExist()
		{
			var preExistingDirs = new List<string>(Directory.GetDirectories(FwDirectoryFinder.ProjectsDirectory));
			try
			{
				// Setup: Create "pre-existing" DB filenames
				using (new DummyFileMaker(Path.Combine(FwDirectoryFinder.ProjectsDirectory, "Gumby", FdoFileHelper.GetXmlDataFileName("Gumby"))))
				{
					using (var threadHelper = new ThreadHelper())
						FdoCache.CreateNewLangProj(new DummyProgressDlg(), "Gumby", FwDirectoryFinder.FdoDirectories, threadHelper);
				}
			}
			finally
			{
				RemoveTestDirs(preExistingDirs, Directory.GetDirectories(FwDirectoryFinder.ProjectsDirectory));
			}
		}
예제 #3
0
		public void SetUp()
		{
			m_activationContext = new ActivationContextHelper("FwParatextLexiconPlugin.dll.manifest");
			using (m_activationContext.Activate())
			{
				m_threadHelper = new ThreadHelper();
				var ui = new DummyFdoUI(m_threadHelper);
				var projectId = new ParatextLexiconPluginProjectID(FDOBackendProviderType.kMemoryOnly, "Test.fwdata");
				m_cache = FdoCache.CreateCacheWithNewBlankLangProj(projectId, "en", "fr", "en", ui, ParatextLexiconPluginDirectoryFinder.FdoDirectories, new FdoSettings());
				NonUndoableUnitOfWorkHelper.Do(m_cache.ActionHandlerAccessor, () =>
					{
						m_cache.ServiceLocator.WritingSystems.AddToCurrentAnalysisWritingSystems(m_cache.ServiceLocator.WritingSystemManager.Get("fr"));
						m_cache.LangProject.MorphologicalDataOA.ParserParameters = "<ParserParameters><XAmple><MaxNulls>1</MaxNulls><MaxPrefixes>5</MaxPrefixes><MaxInfixes>1</MaxInfixes><MaxSuffixes>5</MaxSuffixes><MaxInterfixes>0</MaxInterfixes><MaxAnalysesToReturn>10</MaxAnalysesToReturn></XAmple><ActiveParser>XAmple</ActiveParser></ParserParameters>";
					});
			}
			m_lexicon = new FdoLexicon("Test", "FieldWorks:Test", m_cache, m_cache.DefaultVernWs, m_activationContext);
		}
예제 #4
0
        public static void Main(string[] args) {

            var threadHelper = new ThreadHelper();

            var thread1 = new Thread(new ThreadStart(threadHelper.Thread1));
            thread1.Name = "thread1";
            thread1.Start();

            var thread2 = new Thread(new ThreadStart(threadHelper.Thread2));
            thread2.Name = "thread2";
            thread2.Priority = ThreadPriority.Highest;
            thread2.Start();

            thread1.Join();

            Version originVersion = new Version("2.1"),
                    newVersion = new Version("2.0");

            Console.WriteLine(newVersion.CompareTo(originVersion));

            Console.ReadKey();
        }
예제 #5
0
 private void _Reload()
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     Solution = EnvDTEWrapper.GetCurrentSolution();
 }
예제 #6
0
 private void OnSolutionClosed()
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     ClearData();
 }
예제 #7
0
 public void UpdateCheckState()
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     Solution.UpdateCheckState();
 }
예제 #8
0
		public void CreateNewLangProject_AnthropologyCategoriesExist()
		{
			const string dbName = "AnthropologicalTest";
			SureRemoveDb(dbName);
			var preExistingDirs = new List<string>(Directory.GetDirectories(FwDirectoryFinder.ProjectsDirectory));

			try
			{
				// create project
				string dbFileName;
				using (var threadHelper = new ThreadHelper())
					dbFileName = FdoCache.CreateNewLangProj(new DummyProgressDlg(), dbName, FwDirectoryFinder.FdoDirectories, threadHelper);

				using (var cache = FdoCache.CreateCacheFromLocalProjectFile(dbFileName, "en", m_ui, FwDirectoryFinder.FdoDirectories, new FdoSettings(), new DummyProgressDlg()))
				{
					Assert.AreEqual(Strings.ksAnthropologyCategories, cache.LangProject.AnthroListOA.Name.UiString,
						"Anthropology Categories list was not properly initialized.");
					Assert.AreEqual(Strings.ksAnth, cache.LangProject.AnthroListOA.Abbreviation.UiString,
						"Anthropology Categories list abrv was not properly initialized.");
					Assert.AreNotEqual(0, cache.LangProject.AnthroListOA.ItemClsid,
						"Anthropology Categories list class ID was not properly initialized.");
					Assert.AreNotEqual(0, cache.LangProject.AnthroListOA.Depth,
						"Anthropology Categories list depth was not properly initialized.");
				}
			}
			finally
			{
				RemoveTestDirs(preExistingDirs, Directory.GetDirectories(FwDirectoryFinder.ProjectsDirectory));
			}
		}
예제 #9
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Loads the list of all FDO class names from the meta data cache.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		private static void LoadFDOClassNames()
		{
			if (s_allFDOClassNames != null)
				return;

			using (var threadHelper = new ThreadHelper())
			using (FdoCache cache = FdoCache.CreateCacheWithNoLangProj(new BrowserProjectId(FDOBackendProviderType.kMemoryOnly, null), "en", new SilentFdoUI(threadHelper), FwDirectoryFinder.FdoDirectories, new FdoSettings()))
			{
				IFwMetaDataCacheManaged mdc = (IFwMetaDataCacheManaged)cache.MainCacheAccessor.MetaDataCache;
				s_allFDOClassNames = new List<string>();

				foreach (int clsid in mdc.GetClassIds())
					s_allFDOClassNames.Add(mdc.GetClassName(clsid));

				s_allFDOClassNames.Sort((x, y) => x.CompareTo(y));
			}
		}
 /// <summary>
 /// Gets the file path of the .sln file.
 /// </summary>
 public static string?GetFilePath(this IVsSolution solution)
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     ErrorHandler.ThrowOnFailure(solution.GetSolutionInfo(out _, out var file, out _));
     return(file);
 }
예제 #11
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Create a new language project showing a progress dialog.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		protected void CreateNewLangProjWithProgress()
		{
			try
			{
				using (var progressDlg = new ProgressDialogWithTask(this))
				{
					progressDlg.Title = string.Format(FwCoreDlgs.kstidCreateLangProjCaption, ProjectName);
					string anthroFile = null;
					if (DisplayUi) // Prevents dialogs from showing during unit tests.
					{
						anthroFile = FwCheckAnthroListDlg.PickAnthroList(null, m_helpTopicProvider);
					}
					using (new WaitCursor())
					{
						// Remove primary WritingSystems; remaining WS's will be used as Additional WritingSystems for the new project
						RemoveWs(m_newVernWss, m_cbVernWrtSys.SelectedItem);
						RemoveWs(m_newAnalysisWss, m_cbAnalWrtSys.SelectedItem);

						using (var threadHelper = new ThreadHelper())
						{

							m_dbFile = (string)progressDlg.RunTask(DisplayUi, FdoCache.CreateNewLangProj,
																	ProjectName, FwDirectoryFinder.FdoDirectories, threadHelper, m_cbAnalWrtSys.SelectedItem,
																	m_cbVernWrtSys.SelectedItem,
																	((PalasoWritingSystem)m_wsManager.UserWritingSystem).RFC5646,
																	m_newAnalysisWss, m_newVernWss, anthroFile);
						}
					}
				}
			}
			catch (WorkerThreadException wex)
			{
				Exception e = wex.InnerException;
				if (e is UnauthorizedAccessException)
				{
					if (MiscUtils.IsUnix)
					{
						// Tell Mono user he/she needs to logout and log back in
						MessageBox.Show(ResourceHelper.GetResourceString("ksNeedToJoinFwGroup"));
					}
					else
					{
						MessageBox.Show(string.Format(FwCoreDlgs.kstidErrorNewDb, e.Message),
							FwUtils.ksSuiteName);
					}
					m_fIgnoreClose = true;
					DialogResult = DialogResult.Cancel;
				}
				else if (e.GetBaseException() is PathTooLongException)
				{
					Show();
					m_fIgnoreClose = true;
					MessageBox.Show(String.Format(FwCoreDlgs.kstidErrorProjectNameTooLong, ProjectName),
						FwUtils.ksSuiteName);
				}
				else if (e is ApplicationException)
				{
					MessageBox.Show(string.Format(FwCoreDlgs.kstidErrorNewDb, e.Message),
						FwUtils.ksSuiteName);

					m_fIgnoreClose = true;
					DialogResult = DialogResult.Cancel;
				}
				else if (e is StartupException)
				{
					MessageBox.Show(string.Format(FwCoreDlgs.kstidErrorNewDb, e.Message),
						FwUtils.ksSuiteName);

					DialogResult = DialogResult.Cancel;
				}
				else
				{
					// REVIEW Hasso 2013.10: If we don't need to call OnClosing (we shouldn't), instead of using m_fIgnoreClose, we could set
					// DialogResult = DialogResult.None; and eliminate a redundant flow-control variable
					m_fIgnoreClose = true;
					DialogResult = DialogResult.Cancel;
					throw new Exception(FwCoreDlgs.kstidErrApp, e);
				}
			}
		}
예제 #12
0
 private void worker_DoWork(object sender, ThreadHelper.DoWorkEventArgs e)
 {
     e.Result = GetNewData();
 }
예제 #13
0
 private void worker_RunWorkerCompleted(object sender, ThreadHelper.RunWorkerCompletedEventArgs e)
 {
     List<ProductInfo> products = e.Result as List<ProductInfo>;
     if (syncInvoker != null)
     {
         System.Windows.Forms.MethodInvoker mi = delegate
         {
             MergeNewData(products);
         };
         syncInvoker.Invoke(mi, null);
     }
 }
예제 #14
0
		static int Main(string[] rgArgs)
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			for (int i = 0; i < rgArgs.Length; ++i)
			{
				if (rgArgs[i] == "-debug")
					s_fDebug = true;
				else if (rgArgs[i] == "-autoclose")
					s_fAutoClose = true;
				else if (rgArgs[i] == "-chars")
					s_fMigrateChars = true;
			}
			RegistryHelper.ProductName = "FieldWorks";	// needed to access proper registry values

			if (s_fMigrateChars && s_fDebug)
				MessageBox.Show("Warning: MigrateSqlDbs called with no-longer valid argument, '-chars'. Run 'UnicodeCharEditor -i' instead.");

			// TE-9422. If we had an older version of FW7 installed, ldml files are < verion 2, so will cause
			// a crash if we don't migrate the files to version 2 before opening a project with the current version.
			string globalWsFolder = DirectoryFinder.GlobalWritingSystemStoreDirectory;
			var globalMigrator = new LdmlInFolderWritingSystemRepositoryMigrator(globalWsFolder, NoteMigration);
			globalMigrator.Migrate();

			using (var threadHelper = new ThreadHelper())
			using (var progressDlg = new ProgressDialogWithTask(threadHelper))
			{
				ImportFrom6_0 importer = new ImportFrom6_0(progressDlg, FwDirectoryFinder.ConverterConsoleExe, FwDirectoryFinder.DbExe, s_fDebug);
				if (!importer.IsFwSqlServerInstalled())
					return -1;
				string version;
				if (!importer.IsValidOldFwInstalled(out version))
				{
					if (!String.IsNullOrEmpty(version) && version.CompareTo("5.4") < 0)
					{
						string launchesFlex = "0";
						string launchesTE = "0";
						if (RegistryHelper.KeyExists(FwRegistryHelper.FieldWorksRegistryKey, "Language Explorer"))
						{
							using (RegistryKey keyFlex = FwRegistryHelper.FieldWorksRegistryKey.CreateSubKey("Language Explorer"))
								launchesFlex = keyFlex.GetValue("launches", "0") as string;
						}
						if (RegistryHelper.KeyExists(FwRegistryHelper.FieldWorksRegistryKey, FwSubKey.TE))
						{
							using (RegistryKey keyTE = FwRegistryHelper.FieldWorksRegistryKey.CreateSubKey(FwSubKey.TE))
								launchesTE = keyTE.GetValue("launches", "0") as string;
						}
						if (launchesFlex == "0" && launchesTE == "0")
						{
							FwRegistryHelper.FieldWorksRegistryKey.SetValue("MigrationTo7Needed", "true");
						}
						using (var dlg = new FWVersionTooOld(version))
						{
							dlg.ShowDialog();
						}
					}
					return -1;
				}
				List<string> projects = GetProjectList();
				if (projects.Count > 0)
				{
					using (var migrateProjects = new MigrateProjects(importer, version, projects, s_fAutoClose))
					{
						Application.Run(migrateProjects);
					}
				}
				else if (s_fDebug)
				{
					MessageBox.Show("No FieldWorks (SQL) projects were detected.", "DEBUG!");
				}
			}
			return s_ReturnValue;
		}
예제 #15
0
		public void Teardown()
		{
			if (m_timer != null)
			{
				m_timer.Dispose();
				m_timer = null;
			}

			if (m_dlg != null)
			{
				m_dlg.Dispose();
				m_dlg = null;
			}

			if (m_threadHelper != null)
			{
				m_threadHelper.Dispose();
				m_threadHelper = null;
			}

		}
예제 #16
0
		public void Setup()
		{
			m_threadHelper = new ThreadHelper();
			m_dlg = new DummyProgressDlg(m_threadHelper) {Maximum = 10};
		}
예제 #17
0
 public static void Run()
 {
     ThreadHelper.RunThread(LINE_CLEANER_THREAD_NAME, LineCleanerThread, ThreadPriority.BelowNormal);
 }
예제 #18
0
		static int Main(string[] rgArgs)
		{
			Thread.CurrentThread.Name = "Main thread";
			Logger.Init(FwUtils.ksSuiteName);
			FdoCache.NewerWritingSystemFound += ComplainToUserAboutNewWs;
			// Note to developers: Uncomment this line to be able to attach the debugger to a process for a project
			// other than the initial one that gets started up in VS:
			//MessageBox.Show("Attach debugger now");
			try
			{
#region Initialize XULRunner - required to use the geckofx WebBrowser Control (GeckoWebBrowser).

#if __MonoCS__
				var xulRunnerLocation = XULRunnerLocator.GetXULRunnerLocation();
				if (string.IsNullOrEmpty(xulRunnerLocation))
					throw new ApplicationException("The XULRunner library is missing or has the wrong version");
				var librarySearchPath = Environment.GetEnvironmentVariable("LD_LIBRARY_PATH") ?? String.Empty;
				if (!librarySearchPath.Contains(xulRunnerLocation))
					throw new ApplicationException("LD_LIBRARY_PATH must contain " + xulRunnerLocation);
#else
				// LT-16559: Specifying a hint path is necessary on Windows, but causes a crash in Xpcom.Initialize on Linux. Go figure.
				var xulRunnerLocation = XULRunnerLocator.GetXULRunnerLocation("xulrunner");
				if (string.IsNullOrEmpty(xulRunnerLocation))
					throw new ApplicationException("The XULRunner library is missing or has the wrong version");
#endif
				Xpcom.Initialize(xulRunnerLocation);
				GeckoPreferences.User["gfx.font_rendering.graphite.enabled"] = true;
#endregion Initialize XULRunner

				Logger.WriteEvent("Starting app");
				SetGlobalExceptionHandler();
				SetupErrorReportInformation();
				// We need FieldWorks here to get the correct registry key HKLM\Software\SIL\FieldWorks.
				// The default without this would be HKLM\Software\SIL\SIL FieldWorks (wrong).
				RegistryHelper.ProductName = "FieldWorks";

				// Invoke does nothing directly, but causes BroadcastEventWindow to be initialized
				// on this thread to prevent race conditions on shutdown.See TE-975
				// See http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=911603&SiteID=1
#if !__MonoCS__
				SystemEvents.InvokeOnEventsThread(new Action(DoNothing));
#else
				// TODO-Linux: uses mono feature that is not implemented. What are the implications of this? Review.
#endif
				s_threadHelper = new ThreadHelper();

				// ENHANCE (TimS): Another idea for ensuring that we have only one process started for
				// this project is to use a Mutex. They can be used for cross-process resource access
				// and would probably be less error-prone then our current implementation since it
				// doesn't use TCP connections which can get hampered by firewalls. We would probably still
				// need our current listener functionality for communicating with the other FW process,
				// so it may not buy us much.
				// See http://kristofverbiest.blogspot.com/2008/11/creating-single-instance-application.html.

				// Make sure we do this ASAP. If another FieldWorks.exe is started we need
				// to make sure it can find this one to ask about its project. (FWR-595)
				CreateRemoteRequestListener();

#if DEBUG
				WriteExecutablePathSettingForDevs();
#endif

				if (IsInSingleFWProccessMode())
				{
					Logger.WriteEvent("Exiting: Detected single process mode");
					return 0;
				}

				if (MigrateProjectsTo70())
				{
					Logger.WriteEvent("Migration to Version 7 was still needed.");
				}

				// Enable visual styles. Ignored on Windows 2000. Needs to be called before
				// we create any controls! Unfortunately, this alone is not good enough. We
				// also need to use a manifest, because some ListView and TreeView controls
				// in native code do not have icons if we just use this method. This is caused
				// by a bug in XP.
				Application.EnableVisualStyles();

				// initialize ICU
				Icu.InitIcuDataDir();

				// initialize Palaso keyboarding
				KeyboardController.Initialize();

				FwAppArgs appArgs = new FwAppArgs(rgArgs);
				s_noUserInterface = appArgs.NoUserInterface;
				s_appServerMode = appArgs.AppServerMode;

				s_ui = new FwFdoUI(GetHelpTopicProvider(appArgs.AppAbbrev), s_threadHelper);

				if (Settings.Default.CallUpgrade)
				{
					Settings.Default.Upgrade();
					Settings.Default.CallUpgrade = false;
				}
				var reportingSettings = Settings.Default.Reporting;
				if (reportingSettings == null)
				{
					// Note: to simulate this, currently it works to delete all subfolders of
					// (e.g.) C:\Users\thomson\AppData\Local\SIL\FieldWorks.exe_Url_tdkbegygwiuamaf3mokxurci022yv1kn
					// That guid may depend on version or something similar; it's some artifact of how the Settings persists.
					s_noPreviousReportingSettings = true;
					reportingSettings = new ReportingSettings();
					Settings.Default.Reporting = reportingSettings; // to avoid a defect in Settings, rely on the Save in the code below
				}

				// Allow develpers and testers to avoid cluttering our analytics by setting an environment variable (FEEDBACK = false)
				var feedbackEnvVar = Environment.GetEnvironmentVariable("FEEDBACK");
				if (feedbackEnvVar != null)
				{
					reportingSettings.OkToPingBasicUsageData = feedbackEnvVar.ToLower().Equals("true") || feedbackEnvVar.ToLower().Equals("yes");
				}

				// Note that in FLEx we are using this flag to indicate whether we can send usage data at all.
				// Despite its name, Cambell says this is the original intent (I think there may have been
				// some thought of adding flags one day to control sending more detailed info, but if 'basic
				// navigation' is suppressed nothing is sent). May want to consider renaming to something like
				// OkToPingAtAll, but that affects other Palaso clients.
				// The usage reporter does not currently send anything at all if the flag is false, but to make
				// sure, we don't even initialize reporting if it is false.
				// (Note however that it starts out true. Thus, typically a few pings will be sent
				// on the very first startup, before the user gets a chance to disable it.)
				if (reportingSettings.OkToPingBasicUsageData)
				{
					UsageReporter.Init(reportingSettings, "flex.palaso.org", "UA-39238981-3",
#if DEBUG
						true
#else
						false
#endif
						);
					// Init updates various things in the ReportingSettings, such as the number of times
					// the application has been launched and the 'previous' version.
					Settings.Default.Save();
				}

				// e.g. the first time the user runs FW8, we need to copy a bunch of registry keys
				// from HKCU/Software/SIL/FieldWorks/7.0 -> FieldWorks/8.
				FwRegistryHelper.UpgradeUserSettingsIfNeeded();

				// initialize client-server services to use Db4O backend
				ClientServerServices.SetCurrentToDb4OBackend(s_ui, FwDirectoryFinder.FdoDirectories);

				// initialize the TE styles path so that ScrMappingList can load default styles
				ScrMappingList.TeStylesPath = FwDirectoryFinder.TeStylesPath;

				if (appArgs.ShowHelp)
				{
					ShowCommandLineHelp();
					return 0;
				}
				else if (!string.IsNullOrEmpty(appArgs.ChooseProjectFile))
				{
					ProjectId projId = ChooseLangProject(null, GetHelpTopicProvider(FwUtils.ksFlexAbbrev));
					if (projId == null)
						return 1; // User probably canceled
					try
					{
						// Use PipeHandle because this will probably be used to locate a named pipe using
						// PipeHandle as the identifier.
						File.WriteAllText(appArgs.ChooseProjectFile, projId.Handle, Encoding.UTF8);
					}
					catch (Exception e)
					{
						Logger.WriteError(e);
						return 2;
					}
					return 0;
				}

				if (!SetUICulture(appArgs))
					return 0; // Error occurred and user chose not to continue.

				if (FwRegistryHelper.FieldWorksRegistryKeyLocalMachine == null && FwRegistryHelper.FieldWorksRegistryKey == null)
				{
					// See LT-14461. Some users have managed to get their computers into a state where
					// neither HKML nor HKCU registry entries can be read. We don't know how this is possible.
					// This is so far the best we can do.
					var expected = "HKEY_LOCAL_MACHINE/Software/SIL/FieldWorks/" + FwRegistryHelper.FieldWorksRegistryKeyName;
					MessageBoxUtils.Show(string.Format(Properties.Resources.ksHklmProblem, expected), Properties.Resources.ksHklmCaption);
					return 0;
				}

				s_fwManager = new FieldWorksManager();

				if (!string.IsNullOrEmpty(appArgs.BackupFile))
				{
					LaunchRestoreFromCommandLine(appArgs);
					if (s_teApp == null && s_flexApp == null)
						return 0; // Restore was cancelled or failed, or another process took care of it.
					if (!String.IsNullOrEmpty(s_LinkDirChangedTo))
					{
						NonUndoableUnitOfWorkHelper.Do(s_cache.ActionHandlerAccessor,
							() => s_cache.LangProject.LinkedFilesRootDir = s_LinkDirChangedTo);
					}
				}
				else if (!LaunchApplicationFromCommandLine(appArgs))
					return 0; // Didn't launch, but probably not a serious error

				// Create a listener for this project for applications using FLEx as a LexicalProvider.
				LexicalProviderManager.StartLexicalServiceProvider(s_projectId, s_cache);

#if __MonoCS__
				UglyHackForXkbIndicator();
#endif

				// Application was started successfully, so start the message loop
				Application.Run();
			}
			catch (ApplicationException ex)
			{
				MessageBox.Show(ex.Message, FwUtils.ksSuiteName);
				return 2;
			}
			catch (Exception ex)
			{
				SafelyReportException(ex, s_activeMainWnd, true);
				return 2;
			}
			finally
			{
				StaticDispose();
				if (Xpcom.IsInitialized)
				{
					// The following line appears to be necessary to keep Xpcom.Shutdown()
					// from triggering a scary looking "double free or corruption" message most
					// of the time.  But the Xpcom.Shutdown() appears to be needed to keep the
					// program from hanging around sometimes after it supposedly exits.
					// Doing the shutdown here seems cleaner than using an ApplicationExit
					// delegate.
					var foo = new GeckoWebBrowser();
					Xpcom.Shutdown();
				}
			}
			return 0;
		}
 /// <summary>
 /// Create view mode when window object is created.
 /// </summary>
 public override void OnToolWindowCreated()
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     base.OnToolWindowCreated();
     CreateNewViewModel();
 }
예제 #20
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Releases unmanaged and managed resources
		/// </summary>
		/// ------------------------------------------------------------------------------------
		private static void StaticDispose()
		{
			s_appServerMode = false; // Make sure the cache can be cleaned up
			LexicalProviderManager.StaticDispose(); // Must be done before disposing the cache
			if (s_serviceChannel != null)
			{
				ChannelServices.UnregisterChannel(s_serviceChannel);
				s_serviceChannel = null;
			}

			KeyboardController.Shutdown();

			GracefullyShutDown();

			if (s_threadHelper != null)
				s_threadHelper.Dispose();
			s_threadHelper = null;

			FwRegistrySettings.Release();
		}
 /// <summary>
 /// Gets the directory of the currently loaded solution.
 /// </summary>
 public static string?GetDirectory(this IVsSolution solution)
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     ErrorHandler.ThrowOnFailure(solution.GetSolutionInfo(out var dir, out _, out _));
     return(dir);
 }
예제 #22
0
 private void SetStartHelper(Delegate start, int maxStackSize)
 {
     ThreadHelper threadStartCallBack = new ThreadHelper(start);
     if(start is ThreadStart)
     {
         SetStart(new ThreadStart(threadStartCallBack.ThreadStart), maxStackSize);
     }
     else
     {
         SetStart(new ParameterizedThreadStart(threadStartCallBack.ThreadStart), maxStackSize);
     }                
 }
 private void SetStartHelper(Delegate start, int maxStackSize)
 {
     ulong processDefaultStackSize = GetProcessDefaultStackSize();
     if (((ulong) maxStackSize) > processDefaultStackSize)
     {
         try
         {
             CodeAccessPermission.Demand(PermissionType.FullTrust);
         }
         catch (SecurityException)
         {
             maxStackSize = (int) Math.Min(processDefaultStackSize, 0x7fffffffL);
         }
     }
     ThreadHelper helper = new ThreadHelper(start);
     if (start is ThreadStart)
     {
         this.SetStart(new ThreadStart(helper.ThreadStart), maxStackSize);
     }
     else
     {
         this.SetStart(new ParameterizedThreadStart(helper.ThreadStart), maxStackSize);
     }
 }
 private static void GenerateErrorInternal(IVsGeneratorProgress pGenerateProgress, Exception exception)
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     pGenerateProgress?.GeneratorError(0, 0, exception.Message, 0, 0);
     Trace.WriteLine(exception);
 }
예제 #25
0
		public void CreateNewLangProject_NameWithSingleQuote()
		{
			const string dbName = "!!t'st";
			string dbDir = Path.Combine(FwDirectoryFinder.ProjectsDirectory, dbName);
			SureRemoveDb(dbName);

			var expectedDirs = new List<string>(Directory.GetDirectories(FwDirectoryFinder.ProjectsDirectory)) { dbDir };
			var writingSystemsCommonDir = Path.Combine(FwDirectoryFinder.ProjectsDirectory, FdoFileHelper.ksWritingSystemsDir);

			List<string> currentDirs = null;
			try
			{
				string dbFileName;
				using (var threadHelper = new ThreadHelper())
					dbFileName = FdoCache.CreateNewLangProj(new DummyProgressDlg(), dbName, FwDirectoryFinder.FdoDirectories, threadHelper);

				currentDirs = new List<string>(Directory.GetDirectories(FwDirectoryFinder.ProjectsDirectory));
				if (currentDirs.Contains(writingSystemsCommonDir) && !expectedDirs.Contains(writingSystemsCommonDir))
					expectedDirs.Add(writingSystemsCommonDir);
				CollectionAssert.AreEquivalent(expectedDirs, currentDirs);
				string dbFileBase = Path.GetFileNameWithoutExtension(dbFileName);
				Assert.AreEqual(dbName, dbFileBase);
			}
			finally
			{
				if (currentDirs != null)
					RemoveTestDirs(expectedDirs, currentDirs);
			}
		}
예제 #26
0
 public ThreadHelper()
 {
     _actionQueu = new List<Action>();
     MAIN = this;
 }
예제 #27
0
 internal PhysicalFolder(IVsHierarchyItem item, SolutionItemType type) : base(item, type)
 {
     ThreadHelper.ThrowIfNotOnUIThread();
 }
예제 #28
0
        private async Task <IVsWindowFrame> CreateDocWindowForSolutionAsync()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            IVsWindowFrame windowFrame = null;
            var            solution    = await this.GetServiceAsync <IVsSolution>();

            var uiShell = await this.GetServiceAsync <SVsUIShell, IVsUIShell>();

            var windowFlags =
                (uint)_VSRDTFLAGS.RDT_DontAddToMRU |
                (uint)_VSRDTFLAGS.RDT_DontSaveAs;

            // when VSSolutionManager is already initialized, then use the existing APIs to check pre-conditions.
            if (!await SolutionManager.Value.IsSolutionAvailableAsync())
            {
                throw new InvalidOperationException(Resources.SolutionIsNotSaved);
            }

            var projects = (await SolutionManager.Value.GetNuGetProjectsAsync()).ToArray();

            if (projects.Length == 0)
            {
                MessageHelper.ShowWarningMessage(Resources.NoSupportedProjectsInSolution, Resources.ErrorDialogBoxTitle);
                return(null);
            }

            // pass empty array of NuGetProject
            var uiController = UIFactory.Value.Create(projects);

            var solutionName = (string)_dte.Solution.Properties.Item("Name").Value;

            var model = new PackageManagerModel(
                uiController,
                isSolution: true,
                editorFactoryGuid: GuidList.guidNuGetEditorType)
            {
                SolutionName = solutionName
            };

            var vsWindowSearchHostfactory = await GetServiceAsync(typeof(SVsWindowSearchHostFactory)) as IVsWindowSearchHostFactory;

            var vsShell = await GetServiceAsync(typeof(SVsShell)) as IVsShell4;

            var control        = new PackageManagerControl(model, Settings.Value, vsWindowSearchHostfactory, vsShell, OutputConsoleLogger.Value);
            var windowPane     = new PackageManagerWindowPane(control);
            var guidEditorType = GuidList.guidNuGetEditorType;
            var guidCommandUI  = Guid.Empty;
            var caption        = Resx.Label_SolutionNuGetWindowCaption;
            var documentName   = await SolutionManager.Value.GetSolutionFilePathAsync();

            var ppunkDocView = IntPtr.Zero;
            var ppunkDocData = IntPtr.Zero;
            var hr           = 0;

            try
            {
                ppunkDocView = Marshal.GetIUnknownForObject(windowPane);
                ppunkDocData = Marshal.GetIUnknownForObject(model);
                hr           = uiShell.CreateDocumentWindow(
                    windowFlags,
                    documentName,
                    (IVsUIHierarchy)solution,
                    (uint)VSConstants.VSITEMID.Root,
                    ppunkDocView,
                    ppunkDocData,
                    ref guidEditorType,
                    null,
                    ref guidCommandUI,
                    null,
                    caption,
                    string.Empty,
                    null,
                    out windowFrame);

                if (windowFrame != null)
                {
                    WindowFrameHelper.AddF1HelpKeyword(windowFrame, keywordValue: F1KeywordValuePmUI);
                }
            }
            finally
            {
                if (ppunkDocView != IntPtr.Zero)
                {
                    Marshal.Release(ppunkDocData);
                }

                if (ppunkDocData != IntPtr.Zero)
                {
                    Marshal.Release(ppunkDocView);
                }
            }

            ErrorHandler.ThrowOnFailure(hr);
            return(windowFrame);
        }
예제 #29
0
 public bool IsSolutionAvailable()
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     return(Solution != null && Solution.IsReady);
 }
 /// <summary>
 /// Opens a file in the Preview Tab (provisional tab) if supported by the editor factory.
 /// </summary>
 public static void OpenInPreviewTab(this ProjectItem item)
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     OpenInPreviewTab(item.FileNames[1]);
 }
예제 #31
0
 private void OnSolutionOpened()
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     Reload();
 }
        public static string GetFullVsVersionString(this EnvDTE.DTE dte)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            return(dte.Edition + "/" + dte.Version);
        }
예제 #33
0
 public void Reload()
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     Logger.ProfileFunction(function: () => _Reload(), name: $"Reload solution {EnvDTEWrapper.GetCurrentSolutionName()}");
 }
 /// <summary>
 /// This function is the callback used to execute the command when the menu item is clicked.
 /// See the constructor to see how the menu item is associated with this function using
 /// OleMenuCommandService service and MenuCommand class.
 /// </summary>
 /// <param name="sender">Event sender.</param>
 /// <param name="e">Event args.</param>
 private void Execute(object sender, EventArgs e)
 {
     ThreadHelper.ThrowIfNotOnUIThread();
 }
예제 #35
0
 public void ClearData()
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     Solution.Dispose();
     Solution = null;
 }
 /// <summary>
 /// Reloads a project and its nested project nodes.
 /// </summary>
 protected override void Reload()
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     base.Reload();
     this.CreateNestedProjectNodes();
 }
 private void OnProjectIdChanged(object sender, EventArgs e)
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     CreateNewViewModel();
 }
        /// <summary>
        /// Reloads a nested project node by deleting it and readding it.
        /// </summary>
        /// <param name="node">The node to reload.</param>
        protected virtual void ReloadNestedProjectNode(NestedProjectNode node)
        {
            if (node == null)
            {
                throw new ArgumentNullException("node");
            }
            ThreadHelper.ThrowIfNotOnUIThread();

            IVsSolution solution = this.GetService(typeof(IVsSolution)) as IVsSolution;

            if (solution == null)
            {
                throw new InvalidOperationException();
            }

            NestedProjectNode newNode = null;

            try
            {
                // (VS 2005 UPDATE) When deleting and re-adding the nested project,
                // we do not want SCC to see this as a delete and add operation.
                this.EventTriggeringFlag = ProjectNode.EventTriggering.DoNotTriggerTrackerEvents;

                // notify SolutionEvents listeners that we are about to add children
                IVsFireSolutionEvents fireSolutionEvents = solution as IVsFireSolutionEvents;

                if (fireSolutionEvents == null)
                {
                    throw new InvalidOperationException();
                }

                ErrorHandler.ThrowOnFailure(fireSolutionEvents.FireOnBeforeUnloadProject(node.NestedHierarchy));

                int isDirtyAsInt = 0;
                this.IsDirty(out isDirtyAsInt);

                bool isDirty = (isDirtyAsInt == 0) ? false : true;

                ProjectElement element = node.ItemNode;
                node.CloseNestedProjectNode();

                // Remove from the solution
                this.RemoveChild(node);

                // Now readd it
                try
                {
                    __VSCREATEPROJFLAGS flags = __VSCREATEPROJFLAGS.CPF_NOTINSLNEXPLR | __VSCREATEPROJFLAGS.CPF_SILENT | __VSCREATEPROJFLAGS.CPF_OPENFILE;
                    newNode = this.AddExistingNestedProject(element, flags);
                    newNode.AddVirtualProject();
                }
                catch (Exception e)
                {
                    // We get a System.Exception if anything failed, thus we have no choice but catch it.
                    // Exceptions are digested by VS. Show the error if not in automation.
                    if (!Utilities.IsInAutomationFunction(this.Site))
                    {
                        string message = (String.IsNullOrEmpty(e.Message)) ? SR.GetString(SR.NestedProjectFailedToReload, CultureInfo.CurrentUICulture) : e.Message;
                        string title   = string.Empty;
                        VS.MessageBox.ShowError(title, message);
                    }

                    // Do not digest exception. let the caller handle it. If in a later stage this exception is not digested then the above messagebox is not needed.
                    throw;
                }

#if DEBUG
                IVsHierarchy nestedHierarchy;
                solution.GetProjectOfUniqueName(newNode.GetMkDocument(), out nestedHierarchy);
                Debug.Assert(nestedHierarchy != null && Utilities.IsSameComObject(nestedHierarchy, newNode.NestedHierarchy), "The nested hierrachy was not reloaded correctly.");
#endif
                this.SetProjectFileDirty(isDirty);

                fireSolutionEvents.FireOnAfterLoadProject(newNode.NestedHierarchy);
            }
            finally
            {
                // In this scenario the nested project failed to unload or reload the nested project. We will unload the whole project, otherwise the nested project is lost.
                // This is similar to the scenario when one wants to open a project and the nested project cannot be loaded because for example the project file has xml errors.
                // We should note that we rely here that if the unload fails then exceptions are not digested and are shown to the user.
                if (newNode == null || newNode.NestedHierarchy == null)
                {
                    solution.CloseSolutionElement((uint)__VSSLNCLOSEOPTIONS.SLNCLOSEOPT_UnloadProject | (uint)__VSSLNSAVEOPTIONS.SLNSAVEOPT_ForceSave, this, 0);
                }
                else
                {
                    this.EventTriggeringFlag = ProjectNode.EventTriggering.TriggerAll;
                }
            }
        }
예제 #39
0
        /// <summary>
        /// Requires the UI Thread
        /// </summary>
        /// <returns></returns>
        public static ThemeInfo Generate()
        {
            try {
                ThreadHelper.ThrowIfNotOnUIThread();
                var shell = Package.GetGlobalService(typeof(SVsUIShell)) as IVsUIShell5;

                var backgroundColor = GetThemedColor(shell, EnvironmentColors.ToolWindowBackgroundColorKey);
                var textColor       = GetThemedColor(shell, EnvironmentColors.ToolWindowTextColorKey);

                // assume this theme is 'dark' if the ToolWindow background is dark
                var backgroundIsDark = backgroundColor.IsDark();

                var colors = new List <ThemeColorMetadata>
                {
                    new ThemeColorMetadata {
                        Key = "app-background-color", Color = backgroundColor
                    },
                    new ThemeColorMetadata {
                        Key = "sidebar-background", Color = backgroundColor
                    },
                    new ThemeColorMetadata {
                        Key = "app-background-color-darker", Color = backgroundColor, DarkModifier = c => c.Darken(0.04f), LightModifier = c => c.Lighten(0.04f)
                    },
                    new ThemeColorMetadata {
                        Key = "app-background-color-hover", Color = backgroundColor, DarkModifier = c => c.Lighten(0.03f), LightModifier = c => c.Darken(0.015f)
                    },

                    new ThemeColorMetadata {
                        Key = "base-background-color", Color = backgroundColor, DarkModifier = c => c.Lighten(0.04f), LightModifier = c => c.Darken(0.03f)
                    },
                    new ThemeColorMetadata {
                        Key = "base-border-color", Color = GetThemedColor(shell, EnvironmentColors.ToolWindowBorderColorKey), DarkModifier = c => c.Lighten(0.1f), LightModifier = c => c.Darken(0.1f)
                    },

                    new ThemeColorMetadata {
                        Key = "panel-tool-background-color", Color = backgroundColor, DarkModifier = c => c.Lighten(0.1f), LightModifier = c => c.Darken(0.1f)
                    },
                    new ThemeColorMetadata {
                        Key = "panel-section-foreground-color", Color = textColor, DarkModifier = c => c.Opacity(80), LightModifier = c => c.Opacity(80)
                    },
                    new ThemeColorMetadata {
                        Key = "panel-section-header-background-color", Color = backgroundColor
                    },
                    new ThemeColorMetadata {
                        Key = "panel-section-header-foreground-color", Color = textColor, DarkModifier = c => c.Opacity(80), LightModifier = c => c.Opacity(80)
                    },

                    new ThemeColorMetadata {
                        Key = "text-color", Color = textColor, DarkModifier = c => c.Opacity(80), LightModifier = c => c.Opacity(80)
                    },
                    new ThemeColorMetadata {
                        Key = "text-color-highlight", Color = textColor
                    },
                    new ThemeColorMetadata {
                        Key = "text-color-subtle", Color = textColor, DarkModifier = c => c.Opacity(60), LightModifier = c => c.Opacity(60)
                    },
                    new ThemeColorMetadata {
                        Key = "text-color-subtle-extra", Color = textColor, DarkModifier = c => c.Lighten(0.5f).Opacity(60), LightModifier = c => c.Darken(0.5f).Opacity(60)
                    },

                    new ThemeColorMetadata {
                        Key = "text-color-info", Color = GetThemedColor(shell, EnvironmentColors.StartPageTextControlLinkSelectedColorKey)
                    },
                    new ThemeColorMetadata {
                        Key = "text-color-info-muted", Color = GetThemedColor(shell, EnvironmentColors.StartPageTextControlLinkSelectedColorKey), DarkModifier = c => c.Darken(0.1f)
                    },

                    new ThemeColorMetadata {
                        Key = "text-focus-border-color", Color = GetThemedColor(shell, EnvironmentColors.StartPageTextControlLinkSelectedColorKey), DarkModifier = c => c.Darken(0.1f).Opacity(60), LightModifier = c => c.Opacity(60)
                    },

                    new ThemeColorMetadata {
                        Key = "button-background-color", Color = GetThemedColor(shell, backgroundIsDark ? EnvironmentColors.ToolWindowButtonDownColorKey : EnvironmentColors.ToolWindowBorderColorKey), LightModifier = c => c.Darken(0.3f)
                    },
                    new ThemeColorMetadata {
                        Key = "button-background-color-hover", Color = GetThemedColor(shell, backgroundIsDark ? EnvironmentColors.ToolWindowButtonDownColorKey : EnvironmentColors.ToolWindowBorderColorKey), DarkModifier = c => c.Lighten(0.1f), LightModifier = c => c.Darken(0.2f)
                    },

                    new ThemeColorMetadata {
                        Key = "line-numbers-foreground-color", Color = textColor, DarkModifier = c => c.Opacity(40), LightModifier = c => c.Opacity(40)
                    },

                    new ThemeColorMetadata {
                        Key = "scrollbar-color", Color = GetThemedColor(shell, EnvironmentColors.SystemScrollBarColorKey)
                    },
                    new ThemeColorMetadata {
                        Key = "scrollbar-color-hover", Color = GetThemedColor(shell, EnvironmentColors.ScrollBarThumbMouseOverBackgroundColorKey)
                    }
                };

                if (Log.IsDebugEnabled())
                {
                    Log.Debug($"BackgroundIsDark={backgroundIsDark}, BackgroundColor={backgroundColor.ToRgba()}, TextColor={textColor.ToRgba()}");
#if DEBUG
                    //GenerateVisualStudioColorTheme();
#endif
                }

                // if (isDark && textColor.IsDark())
                // {
                //  // in this case, there's a dark on dark issue -- default texts to something reasonable
                //  var color = Color.FromArgb(228, 227, 227);
                //  colors.Add(new ThemeColorMetadata { Key = "text-color", Color = color.Opacity(80) });
                //  colors.Add(new ThemeColorMetadata { Key = "text-color-highlight", Color = color });
                //  colors.Add(new ThemeColorMetadata { Key = "text-color-subtle", Color = color.Opacity(60) });
                //  colors.Add(new ThemeColorMetadata { Key = "text-color-subtle-extra", Color = color.Lighten(0.5f).Opacity(60) });

                //  colors.Add(new ThemeColorMetadata { Key = "vscode-sideBarSectionHeader-foreground", Color = color.Opacity(80) });

                //  if (Log.IsEnabled(Serilog.Events.LogEventLevel.Debug))
                //  {
                //      Log.Debug($"Dark on Dark, TextColor={textColor},{textColor.ToRgba()} BackgroundColor={backgroundColor}, {backgroundColor.ToRgba()}");
                //  }
                // }
                // else if (!isDark && !textColor.IsDark())
                // {
                //  // in this case, there's a light on light issue -- default texts to something reasonable
                //  var color = Color.FromArgb(17, 17, 17);
                //  colors.Add(new ThemeColorMetadata { Key = "text-color", Color = color.Opacity(80) });
                //  colors.Add(new ThemeColorMetadata { Key = "text-color-highlight", Color = color });
                //  colors.Add(new ThemeColorMetadata { Key = "text-color-subtle", Color = color.Opacity(60) });
                //  colors.Add(new ThemeColorMetadata { Key = "text-color-subtle-extra", Color = color.Darken(0.5f).Opacity(60) });

                //  colors.Add(new ThemeColorMetadata { Key = "vscode-sideBarSectionHeader-foreground", Color = color.Opacity(80) });

                //  if (Log.IsEnabled(Serilog.Events.LogEventLevel.Debug))
                //  {
                //      Log.Debug($"Light on Light, TextColor={textColor},{textColor.ToRgba()} BackgroundColor={backgroundColor}, {backgroundColor.ToRgba()}");
                //  }
                // }

                string fontFamilyString;
                var    fontFamily = System.Windows.Application.Current.FindResource(VsFonts.EnvironmentFontFamilyKey) as FontFamily;
                if (fontFamily != null)
                {
                    fontFamilyString = fontFamily.ToString();
                    if (fontFamilyString.Contains(" "))
                    {
                        fontFamilyString = $"\"{fontFamilyString}\"";
                    }
                }
                else
                {
                    fontFamilyString = "\"Segoe WPC\", \"Segoe UI\", HelveticaNeue-Light, Ubuntu, \"Droid Sans\", Arial, Consolas, sans-serif";
                }

                var metrics  = CreateEditorMetrics(null);
                var fontSize = metrics == null?
                               DefaultFontSize.ToString() :
                                   metrics.FontSize.ToIntSafe(DefaultFontSize).ToString();

                var resources = new List <ThemeResourceMetadata>
                {
                    new ThemeResourceMetadata {
                        Key = "font-family", Value = fontFamilyString
                    },
                    new ThemeResourceMetadata {
                        Key = "font-size", Value = fontSize
                    }
                };

                return(new ThemeInfo {
                    ThemeColors = colors,
                    ThemeResources = resources,
                    IsDark = backgroundIsDark
                });
            }
            catch (Exception ex) {
                Log.Error(ex, nameof(Generate));

                return(new ThemeInfo());
            }
        }
예제 #40
0
        public void ShowMessage(string format, params object[] items)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            ShowMessage(OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST, OLEMSGICON.OLEMSGICON_INFO, format, items);
        }
 /// <summary>
 /// Gets all projects in the solution as IVsHierarchy items.
 /// </summary>
 public static IEnumerable <IVsHierarchy> GetAllProjectHierarchys(this IVsSolution solution)
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     return(GetAllProjectHierarchys(solution, __VSENUMPROJFLAGS.EPF_LOADEDINSOLUTION));
 }
 public void TestInitialize()
 {
     ThreadHelper.SetCurrentThreadAsUIThread();
 }
예제 #43
0
        public void ReloadFontAndColors()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            m_fontInfoInitialized = true;

            #region fill out temorary resources
            var colorStorage = FontAndColorStorage;
            var categoryGuid = CategoryGuid;
            var fflags       =
                (UInt32)__FCSTORAGEFLAGS.FCSF_LOADDEFAULTS |
                (UInt32)__FCSTORAGEFLAGS.FCSF_NOAUTOCOLORS |
                (UInt32)__FCSTORAGEFLAGS.FCSF_READONLY;

            if (ErrorHandler.Succeeded(colorStorage.OpenCategory(ref categoryGuid, fflags)))
            {
                try
                {
                    var pLOGFONT  = new LOGFONTW[1];
                    var pFontInfo = new FontInfo[1];
                    if (ErrorHandler.Succeeded(colorStorage.GetFont(pLOGFONT, pFontInfo)) && (pFontInfo[0].bFaceNameValid == 1))
                    {
                        var fontInfoRef = pFontInfo[0];
                        var fontFamily  = new FontFamily(fontInfoRef.bstrFaceName);
                        var fontSize    = ConvertFromPoint(fontInfoRef.wPointSize);

                        m_resourceDictionary[new FontResourceKey(CategoryGuid, FontResourceKeyType.FontFamily)] = fontFamily;
                        m_resourceDictionary[new FontResourceKey(CategoryGuid, FontResourceKeyType.FontSize)]   = fontSize;
                    }
                    else
                    {
                        m_resourceDictionary.Remove(new FontResourceKey(CategoryGuid, FontResourceKeyType.FontFamily));
                        m_resourceDictionary.Remove(new FontResourceKey(CategoryGuid, FontResourceKeyType.FontSize));
                    }

                    foreach (var colorEntry in ColorEntries)
                    {
                        Color?backgroundColor = null;
                        Color?foregroundColor = null;

                        var pColorInfo = new ColorableItemInfo[1];
                        if (ErrorHandler.Succeeded(colorStorage.GetItem(colorEntry.Name, pColorInfo)))
                        {
                            if (pColorInfo[0].bBackgroundValid == 1)
                            {
                                backgroundColor = Services.CreateWpfColor(pColorInfo[0].crBackground);
                            }
                            if (pColorInfo[0].bForegroundValid == 1)
                            {
                                foregroundColor = Services.CreateWpfColor(pColorInfo[0].crForeground);
                            }
                        }

                        colorEntry.UpdateResources(m_resourceDictionary, backgroundColor, foregroundColor);
                    }
                }
                finally
                {
                    colorStorage.CloseCategory();
                }
            }
            #endregion
        }
        /// <summary>
        ///   This function is the callback used to execute the command when the menu item is clicked.
        ///   See the constructor to see how the menu item is associated with this function using
        ///   OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void Execute(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            ExecuteInternalAsync().FireAndForget();
        }
예제 #45
0
파일: main.cs 프로젝트: bbriggs/FieldWorks
		static void Main(string[] arguments)
		{
			// <summary>
			// any filters that we want, for example, to only output items which satisfy their constraint.
			// </summary>
			IFilterStrategy[] filters=null;

			if (arguments.Length < 3)
			{
				Console.WriteLine("usage: fxt dbName fxtTemplatePath xmlOutputPath (-guids)");
				Console.WriteLine("");
				Console.WriteLine("example using current directory: fxt TestLangProj WebPageSample.xhtml LangProj.xhtml");
				Console.WriteLine("example with environment variables: fxt ZPU \"%fwroot%/distfiles/fxtTest.fxt\" \"%temp%/fxtTest.xml\"");
				return;
			}


			string fxtPath = System.Environment.ExpandEnvironmentVariables(arguments[1]);
			if(!File.Exists(fxtPath))
			{
				Console.WriteLine("could not find the file "+fxtPath);
				return;
			}

			string outputPath = System.Environment.ExpandEnvironmentVariables(arguments[2]);

			FdoCache cache = null;
			try
			{
				Console.WriteLine("Initializing cache...");
				var bepType = GetBEPTypeFromFileExtension(fxtPath);
				var isMemoryBEP = bepType == FDOBackendProviderType.kMemoryOnly;
				var threadHelper = new ThreadHelper();
				var consoleProj = new ConsoleProgress();

				if (isMemoryBEP)
					cache = FdoCache.CreateCacheWithNewBlankLangProj(new BrowserProjectId(bepType, null), "en", "en", "en", threadHelper);
				else
				{
					using (var progressDlg = new ProgressDialogWithTask(consoleProj))
					{
						cache = FdoCache.CreateCacheFromExistingData(new BrowserProjectId(bepType, fxtPath), "en", progressDlg);
					}
				}
			}
			catch (Exception error)
			{
				Console.WriteLine(error.Message);
				return;
			}
			//try
			//{
			//    Console.WriteLine("Initializing cache...");
			//    Dictionary<string, string> cacheOptions = new Dictionary<string, string>();
			//    cacheOptions.Add("db", arguments[0]);
			//    cache = FdoCache.Create(cacheOptions);
			//}
			//catch (Exception error)
			//{
			//    Console.WriteLine(error.Message);
			//    return;
			//}

			Console.WriteLine("Beginning output...");
			DateTime dtstart = DateTime.Now;
			XDumper d = new XDumper(cache);
			if (arguments.Length == 4)
			{
				if(arguments[3] == "-parserDump")
				{
					filters = new IFilterStrategy[]{new ConstraintFilterStrategy()};
				}
				else
					//boy do we have a brain-dead argument parser in this app!
					System.Diagnostics.Debug.Assert(arguments[3] == "-guids");
				d.OutputGuids = true;
			}
			try
			{
				d.Go(cache.LangProject as ICmObject, fxtPath, File.CreateText(outputPath), filters);

				//clean up, add the <?xml tag, etc. Won't be necessary if/when we make the dumper use an xmlwriter instead of a textwriter
				//was introducing changes such as single quote to double quote				XmlDocument doc=new XmlDocument();
				//				doc.Load(outputPath);
				//				doc.Save(outputPath);
			}
			catch (Exception error)
			{
				if (cache != null)
					cache.Dispose();

				Console.WriteLine(error.Message);
				return;
			}


			TimeSpan tsTimeSpan = new TimeSpan(DateTime.Now.Ticks - dtstart.Ticks);

			Console.WriteLine("Finished: " + tsTimeSpan.TotalSeconds.ToString() + " Seconds");

			if(outputPath.ToLower().IndexOf("fxttestout") > -1)
				System.Diagnostics.Debug.WriteLine(File.OpenText(outputPath).ReadToEnd());

			if (cache != null)
				cache.Dispose();

			System.Diagnostics.Debug.WriteLine("Finished: " + tsTimeSpan.TotalSeconds.ToString() + " Seconds");
		}
        private void SubmissionBufferAdded(object sender, SubmissionBufferAddedEventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            GetToolbarHost().ForceUpdateUI();
        }
예제 #47
0
 private void SetStartHelper(Delegate start, int maxStackSize)
 {
     ThreadHelper helper = new ThreadHelper(start);
     if (start is ThreadStart)
     {
         this.SetStart(new ThreadStart(helper.ThreadStart), maxStackSize);
     }
     else
     {
         this.SetStart(new ParameterizedThreadStart(helper.ThreadStart), maxStackSize);
     }
 }
 public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     return(_commandTarget.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText));
 }
 public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     return(_commandTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut));
 }
예제 #50
0
        int IVsSccGlyphs.GetCustomGlyphList(uint baseIndex, out uint pdwImageListHandle)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (baseIndex == _baseIndex && _glyphList != null)
            {
                pdwImageListHandle = unchecked ((uint)_glyphList.Handle);

                return(VSErr.S_OK);
            }

            if (_glyphList != null)
            {
                _glyphList.Dispose();
                _glyphList = null;
            }

            // Visual Studio 2002-2010 use a System TreeView control which
            // supports up to 16 glyph images. 12 of those are filled by
            // Visual Studio and the other 4 are overridable.
            // In these versions AnkhSVN provides its 4 images here. (It also
            // forces its own imagelist in the treeview to support more glyphs)
            //
            // 'Visual Studio 11' switched to a WPF control which supports more
            // common controls, but the api isn't extended (yet). We now provide
            // the same 4 glyphs, but add the entire list of images at the end
            // (offset + 16)
            //
            // In VS11 when someone asks for a glyph we provide the higher value.
            // If a user uses the old control (read=Classviewer) it will overflow
            // and provide the default icon, but if it is the new solution explorer
            // it won't overflow and provide our nice glyph.

            // In an attempt to trick the VS2010 'Solution navigator' extension we
            // try to do the same overflow trick in 2010. The solution explorer will
            // then just fall back to our forced image control

            if (StatusImages == null)
            {
                pdwImageListHandle = 0;
                return(VSErr.E_FAIL); // Vital service missing
            }

            _glyphList = StatusImages.CreateStatusImageList();

            if (VSVersion.VS2012OrLater || SolutionNavigatorInstalled())
            {
                for (int i = 0; i < 16; i++)
                {
                    using (System.Drawing.Image img = _glyphList.Images[i])
                    {
                        _glyphList.Images.Add(img);
                    }
                }
                _glyphOffset = 16;
            }

            // Now we delete all images before BaseIndex, to properly align our images
            for (int i = (int)baseIndex - 1; i >= 0; i--)
            {
                _glyphList.Images.RemoveAt(i);
            }

            _baseIndex         = baseIndex;
            pdwImageListHandle = unchecked ((uint)_glyphList.Handle);

            return(VSErr.S_OK);
        }
예제 #51
0
 public static ThreadHelper CurrentThread()
 {
     ThreadHelper CurrentThread = new ThreadHelper();
     CurrentThread.Instance = Thread.CurrentThread;
     return CurrentThread;
 }
예제 #52
0
 public void addShutdownHook(ThreadHelper thread)
 {
     throw new System.NotImplementedException();
 }