Ejemplo n.º 1
0
        public void CreateFwAppArgs_Link_NoDatabaseSpecified()
        {
            FwAppArgs args = new FwAppArgs("silfw://localhost/link?&app=Translation Editor" +
                                           "&server=&tool=BTdraftView&guid=F48AC2E4-27E3-404e-965D-9672337E0AAF&tag=front");

            Assert.IsTrue(args.ShowHelp, "Bad arguments should set ShowHelp to true");
        }
Ejemplo n.º 2
0
        public void CreateFwAppArgs_Link_NoDatabaseSpecified()
        {
            FwAppArgs args = new FwAppArgs("silfw://localhost/link?" +
                                           "&tool=default&guid=F48AC2E4-27E3-404e-965D-9672337E0AAF&tag=");

            Assert.IsTrue(args.ShowHelp, "Bad arguments should set ShowHelp to true");
        }
Ejemplo n.º 3
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Checks to see whether this instance is connected to the requested project. If so,
		/// starts up the requested app or activates a main window for that app if already
		/// running.
		/// </summary>
		/// <param name="projectId">The requested project ID.</param>
		/// <param name="args">The application arguments</param>
		/// <returns>The result of checking to see if the specified project matches the
		/// project this instance is running</returns>
		/// ------------------------------------------------------------------------------------
		public ProjectMatch HandleOpenProjectRequest(ProjectId projectId, FwAppArgs args)
		{
			ProjectMatch isMyProject = FieldWorks.GetProjectMatchStatus(projectId);
			if (isMyProject != ProjectMatch.ItsMyProject)
				return isMyProject;

			FieldWorks.KickOffAppFromOtherProcess(args);
			return ProjectMatch.ItsMyProject; // The request has been handled at this point
		}
Ejemplo n.º 4
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Some comparisons don't care about the content of the property table, so we provide a
        /// method similar to Equals but not quite as demanding.
        /// </summary>
        /// <param name="lnk">The link to compare.</param>
        /// ------------------------------------------------------------------------------------
        public override bool EssentiallyEquals(FwLinkArgs lnk)
        {
            FwAppArgs appArgs = lnk as FwAppArgs;

            if (appArgs == null || !base.EssentiallyEquals(lnk))
            {
                return(false);
            }
            return(appArgs.Database == Database);
        }
Ejemplo n.º 5
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Handles the specified link request.
		/// </summary>
		/// <param name="link">The link.</param>
		/// <returns>True if the link was successfully handled, false otherwise.</returns>
		/// ------------------------------------------------------------------------------------
		public bool HandleLinkRequest(FwAppArgs link)
		{
			ProjectMatch isMyProject = FieldWorks.GetProjectMatchStatus(
				new ProjectId(link.DatabaseType, link.Database, link.Server));
			if (isMyProject != ProjectMatch.ItsMyProject)
				return false;

			FieldWorks.FollowLink(link);
			return true;
		}
Ejemplo n.º 6
0
        public void CreateFwAppArgs_RunTogether()
        {
            FwAppArgs args = new FwAppArgs("-projmonkey", "-typexml");

            Assert.AreEqual("monkey", args.Database);
            Assert.AreEqual(string.Empty, args.ConfigFile);
            Assert.AreEqual(string.Empty, args.Locale);
            Assert.IsFalse(args.ShowHelp);
            Assert.AreEqual(1, args.PropertyTableEntries.Count);
            Assert.AreEqual(string.Empty, args.Tag);
            Assert.AreEqual(Guid.Empty, args.TargetGuid);
            Assert.AreEqual(string.Empty, args.ToolName);
            Assert.IsFalse(args.HasLinkInformation);
        }
Ejemplo n.º 7
0
        public void CreateFwAppArgs_DbAbsolutePath_Linux()
        {
            FwAppArgs args = new FwAppArgs("-db", "/database.fwdata");

            Assert.AreEqual("/database.fwdata", args.Database, "Should be able to open up database by absolute path");
            Assert.AreEqual(string.Empty, args.ConfigFile);
            Assert.AreEqual(string.Empty, args.DatabaseType);
            Assert.AreEqual(string.Empty, args.Locale);
            Assert.IsFalse(args.ShowHelp);
            Assert.AreEqual(0, args.PropertyTableEntries.Count);
            Assert.AreEqual(string.Empty, args.Tag);
            Assert.AreEqual(Guid.Empty, args.TargetGuid);
            Assert.AreEqual(string.Empty, args.ToolName);
            Assert.IsFalse(args.HasLinkInformation);
        }
Ejemplo n.º 8
0
        public void CreateFwAppArgs_MultiWordQuotedValue()
        {
            FwAppArgs args = new FwAppArgs("-db", "monkey on a string.fwdata");

            Assert.AreEqual("monkey on a string.fwdata", args.Database);
            Assert.AreEqual(string.Empty, args.DatabaseType);
            Assert.AreEqual(string.Empty, args.ConfigFile);
            Assert.AreEqual(string.Empty, args.Locale);
            Assert.IsFalse(args.ShowHelp);
            Assert.AreEqual(0, args.PropertyTableEntries.Count);
            Assert.AreEqual(string.Empty, args.Tag);
            Assert.AreEqual(Guid.Empty, args.TargetGuid);
            Assert.AreEqual(string.Empty, args.ToolName);
            Assert.IsFalse(args.HasLinkInformation);
        }
Ejemplo n.º 9
0
        public void CreateFwAppArgs_Normal()
        {
            FwAppArgs args = new FwAppArgs("-db", "monkey");

            Assert.AreEqual("monkey", args.Database);
            Assert.AreEqual(string.Empty, args.ConfigFile);
            Assert.AreEqual(string.Empty, args.DatabaseType);
            Assert.AreEqual(string.Empty, args.Locale);
            Assert.IsFalse(args.ShowHelp);
            Assert.AreEqual(0, args.PropertyTableEntries.Count);
            Assert.AreEqual(string.Empty, args.Tag);
            Assert.AreEqual(Guid.Empty, args.TargetGuid);
            Assert.AreEqual(string.Empty, args.ToolName);
            Assert.IsFalse(args.HasLinkInformation);
            StringAssert.Contains("database%3dmonkey%26", args.ToString(), "missing & after project.");
        }
Ejemplo n.º 10
0
        public void CreateFwAppArgs_Link_NoKeySpecified()
        {
            FwAppArgs args = new FwAppArgs("silfw://localhost/link?&database=primate" +
                                           "&tool=default&guid=F48AC2E4-27E3-404e-965D-9672337E0AAF&tag=");

            Assert.AreEqual("primate", args.Database);
            Assert.AreEqual(String.Empty, args.Tag);
            Assert.AreEqual(new Guid("F48AC2E4-27E3-404e-965D-9672337E0AAF"), args.TargetGuid);
            Assert.AreEqual("default", args.ToolName);
            Assert.IsTrue(args.HasLinkInformation);
            Assert.AreEqual(string.Empty, args.ConfigFile);
            Assert.AreEqual(string.Empty, args.DatabaseType);
            Assert.AreEqual(string.Empty, args.Locale);
            Assert.IsFalse(args.ShowHelp);
            Assert.AreEqual(0, args.PropertyTableEntries.Count);
        }
Ejemplo n.º 11
0
        public void CreateFwAppArgs_UnknownSwitch()
        {
            FwAppArgs args = new FwAppArgs("-init", "DN");

            Assert.AreEqual(1, args.PropertyTableEntries.Count);
            Assert.AreEqual("init", args.PropertyTableEntries[0].name);
            Assert.AreEqual("DN", args.PropertyTableEntries[0].value);
            Assert.AreEqual(string.Empty, args.Database);
            Assert.AreEqual(string.Empty, args.ConfigFile);
            Assert.AreEqual(string.Empty, args.DatabaseType);
            Assert.AreEqual(string.Empty, args.Locale);
            Assert.IsFalse(args.ShowHelp);
            Assert.AreEqual(string.Empty, args.Tag);
            Assert.AreEqual(Guid.Empty, args.TargetGuid);
            Assert.AreEqual(string.Empty, args.ToolName);
            Assert.IsFalse(args.HasLinkInformation);
        }
Ejemplo n.º 12
0
        public void CreateFwAppArgs_Help()
        {
            FwAppArgs args = new FwAppArgs("-?", "-app", "te", "-type", "XML", "-db", "monkey", "-s", "soup");

            Assert.IsTrue(args.ShowHelp);
            Assert.AreEqual(string.Empty, args.AppName, "Showing help should ignore all other parameters");
            Assert.AreEqual(string.Empty, args.Database, "Showing help should ignore all other parameters");
            Assert.AreEqual(string.Empty, args.Server, "Showing help should ignore all other parameters");
            Assert.AreEqual(string.Empty, args.DatabaseType, "Showing help should ignore all other parameters");
            Assert.AreEqual(string.Empty, args.ConfigFile);
            Assert.AreEqual(string.Empty, args.Locale);
            Assert.AreEqual(0, args.PropertyTableEntries.Count);
            Assert.AreEqual(string.Empty, args.Tag);
            Assert.AreEqual(Guid.Empty, args.TargetGuid);
            Assert.AreEqual(string.Empty, args.ToolName);
            Assert.IsFalse(args.HasLinkInformation);

            args = new FwAppArgs(new[] { "-h" });
            Assert.IsTrue(args.ShowHelp);
            Assert.AreEqual(string.Empty, args.AppName);
            Assert.AreEqual(string.Empty, args.Database);
            Assert.AreEqual(string.Empty, args.Server);
            Assert.AreEqual(string.Empty, args.DatabaseType);
            Assert.AreEqual(string.Empty, args.ConfigFile);
            Assert.AreEqual(string.Empty, args.Locale);
            Assert.AreEqual(0, args.PropertyTableEntries.Count);
            Assert.AreEqual(string.Empty, args.Tag);
            Assert.AreEqual(Guid.Empty, args.TargetGuid);
            Assert.AreEqual(string.Empty, args.ToolName);
            Assert.IsFalse(args.HasLinkInformation);

            args = new FwAppArgs(new[] { "-help" });
            Assert.IsTrue(args.ShowHelp);
            Assert.AreEqual(string.Empty, args.AppName);
            Assert.AreEqual(string.Empty, args.Database);
            Assert.AreEqual(string.Empty, args.Server);
            Assert.AreEqual(string.Empty, args.DatabaseType);
            Assert.AreEqual(string.Empty, args.ConfigFile);
            Assert.AreEqual(string.Empty, args.Locale);
            Assert.AreEqual(0, args.PropertyTableEntries.Count);
            Assert.AreEqual(string.Empty, args.Tag);
            Assert.AreEqual(Guid.Empty, args.TargetGuid);
            Assert.AreEqual(string.Empty, args.ToolName);
            Assert.IsFalse(args.HasLinkInformation);
        }
Ejemplo n.º 13
0
        public void CreateFwAppArgs_RunTogether()
        {
            FwAppArgs args = new FwAppArgs("-appte", "-projmonkey", "-ssoup", "-typexml");

            Assert.AreEqual(FwUtils.ksTeAppName.ToLowerInvariant(), args.AppName);
            Assert.AreEqual(FwUtils.ksTeAbbrev.ToLowerInvariant(), args.AppAbbrev);
            Assert.AreEqual("monkey", args.Database);
            Assert.AreEqual("soup", args.Server);
            Assert.AreEqual("xml", args.DatabaseType);
            Assert.AreEqual(string.Empty, args.ConfigFile);
            Assert.AreEqual(string.Empty, args.Locale);
            Assert.IsFalse(args.ShowHelp);
            Assert.AreEqual(0, args.PropertyTableEntries.Count);
            Assert.AreEqual(string.Empty, args.Tag);
            Assert.AreEqual(Guid.Empty, args.TargetGuid);
            Assert.AreEqual(string.Empty, args.ToolName);
            Assert.IsFalse(args.HasLinkInformation);
        }
Ejemplo n.º 14
0
        public void CreateFwAppArgs_Link_NoKeySpecified()
        {
            FwAppArgs args = new FwAppArgs("silfw://localhost/link?&app=Translation Editor&database=primate" +
                                           "&server=&tool=BTdraftView&guid=F48AC2E4-27E3-404e-965D-9672337E0AAF&tag=front");

            Assert.AreEqual(FwUtils.ksTeAppName.ToLowerInvariant(), args.AppName);
            Assert.AreEqual(FwUtils.ksTeAbbrev.ToLowerInvariant(), args.AppAbbrev);
            Assert.AreEqual("primate", args.Database);
            Assert.AreEqual(string.Empty, args.Server);
            Assert.AreEqual("front", args.Tag);
            Assert.AreEqual(new Guid("F48AC2E4-27E3-404e-965D-9672337E0AAF"), args.TargetGuid);
            Assert.AreEqual("BTdraftView", args.ToolName);
            Assert.IsTrue(args.HasLinkInformation);
            Assert.AreEqual(string.Empty, args.ConfigFile);
            Assert.AreEqual(string.Empty, args.DatabaseType);
            Assert.AreEqual(string.Empty, args.Locale);
            Assert.IsFalse(args.ShowHelp);
            Assert.AreEqual(0, args.PropertyTableEntries.Count);
        }
Ejemplo n.º 15
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Shows an instance of this dialog on a separate thread.
		/// </summary>
		/// <param name="args">The application arguments</param>
		/// <param name="whatToWaitFor">The condition we're waiting for.</param>
		/// <param name="appToStart">The application to start.</param>
		/// <param name="appToWaitFor">The application to wait for (null if waiting for
		/// WindowToActivate).</param>
		/// ------------------------------------------------------------------------------------
		internal static void ShowOnSeparateThread(FwAppArgs args, WaitFor whatToWaitFor,
			FwApp appToStart, FwApp appToWaitFor)
		{
			if (whatToWaitFor != WaitFor.WindowToActivate && appToWaitFor == null)
				throw new ArgumentNullException("appToWaitFor");
			if (appToStart == null)
				throw new ArgumentNullException("appToStart");

			ApplicationBusyDialog dlg = new ApplicationBusyDialog();
			dlg.m_whatToWaitFor = whatToWaitFor;
			dlg.m_args = args;
			dlg.m_appToStart = appToStart;
			dlg.m_appToWaitFor = appToWaitFor;
			Thread thread = new Thread(dlg.WaitForOtherApp);
			thread.IsBackground = true;
			thread.SetApartmentState(ApartmentState.STA);
			thread.Name = "WaitForOtherBusyApp";
			thread.CurrentUICulture = Thread.CurrentThread.CurrentUICulture;
			thread.Start();
		}
Ejemplo n.º 16
0
        public void CreateFwAppArgs_Link_OverridesOtherSettings()
        {
            FwAppArgs args = new FwAppArgs("-app", FwUtils.ksFlexAbbrev, "-db", "monkey",
                                           "-s", "soup", "-link", "silfw://localhost/link?&app=TE&database=primate" +
                                           "&server=salad&tool=BTdraftView&guid=F48AC2E4-27E3-404e-965D-9672337E0AAF&tag=front");

            Assert.AreEqual(FwUtils.ksTeAppName.ToLowerInvariant(), args.AppName);
            Assert.AreEqual(FwUtils.ksTeAbbrev.ToLowerInvariant(), args.AppAbbrev);
            Assert.AreEqual("primate", args.Database);
            Assert.AreEqual("salad", args.Server);
            Assert.AreEqual("front", args.Tag);
            Assert.AreEqual(new Guid("F48AC2E4-27E3-404e-965D-9672337E0AAF"), args.TargetGuid);
            Assert.AreEqual("BTdraftView", args.ToolName);
            Assert.IsTrue(args.HasLinkInformation);
            Assert.AreEqual(string.Empty, args.ConfigFile);
            Assert.AreEqual(string.Empty, args.DatabaseType);
            Assert.AreEqual(string.Empty, args.Locale);
            Assert.IsFalse(args.ShowHelp);
            Assert.AreEqual(0, args.PropertyTableEntries.Count);
        }
Ejemplo n.º 17
0
        public void CreateFwAppArgs_UnknownSwitch()
        {
            FwAppArgs args = new FwAppArgs("-app", FwUtils.ksFlexAbbrev, "-init", "DN");

            Assert.AreEqual(FwUtils.ksFlexAppName.ToLowerInvariant(), args.AppName);
            Assert.AreEqual(FwUtils.ksFlexAbbrev.ToLowerInvariant(), args.AppAbbrev);
            Assert.AreEqual(1, args.PropertyTableEntries.Count);
            Assert.AreEqual("init", args.PropertyTableEntries[0].name);
            Assert.AreEqual("DN", args.PropertyTableEntries[0].value);
            Assert.AreEqual(string.Empty, args.Database);
            Assert.AreEqual(string.Empty, args.Server);
            Assert.AreEqual(string.Empty, args.ConfigFile);
            Assert.AreEqual(string.Empty, args.DatabaseType);
            Assert.AreEqual(string.Empty, args.Locale);
            Assert.IsFalse(args.ShowHelp);
            Assert.AreEqual(string.Empty, args.Tag);
            Assert.AreEqual(Guid.Empty, args.TargetGuid);
            Assert.AreEqual(string.Empty, args.ToolName);
            Assert.IsFalse(args.HasLinkInformation);
        }
Ejemplo n.º 18
0
		private static bool CreateApp(FwAppArgs appArgs)
		{
			FwApp app = GetOrCreateApplication(appArgs);
			if (app == null)
				return false; // We can't do much without an application to start
			Debug.Assert(!app.HasBeenFullyInitialized);

			Logger.WriteEvent("Created application: " + app.GetType().Name);
			return true;
		}
Ejemplo n.º 19
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Launches the application when requested from the command-line.
		/// </summary>
		/// <param name="appArgs">The application command-line arguments.</param>
		/// ------------------------------------------------------------------------------------
		private static bool LaunchApplicationFromCommandLine(FwAppArgs appArgs)
		{
			// Get the application requested on the command line
			if (!CreateApp(appArgs))
				return false;

			// Get the project the user wants to open and attempt to launch it.
			ProjectId projectId = DetermineProject(appArgs);
			if (projectId != null && IsSharedXmlBackendNeeded(projectId))
				projectId.Type = FDOBackendProviderType.kSharedXML;

			// s_projectId can be non-null if the user decided to restore a project from
			// the Welcome to Fieldworks dialog. (FWR-2146)
			if (s_projectId == null && !LaunchProject(appArgs, ref projectId))
				return false;

			// The project was successfully loaded so store it. This will let any other
			// FieldWorks processes that are waiting on us be able to continue.
			s_projectId = projectId;

			WarnUserAboutFailedLiftImportIfNecessary(GetOrCreateApplication(appArgs));

			if (s_noUserInterface)
			{
				// We should have a main window by now, so the help button on the dialog
				// will work if needed.
				CheckForMovingExternalLinkDirectory(GetOrCreateApplication(appArgs));
			}

			return true;
		}
Ejemplo n.º 20
0
		/// <summary>
		/// Returns some active, non-disposed application if possible, otherwise, null. Currently Flex is preferred
		/// if both are re-opened.
		/// </summary>
		/// <param name="project"></param>
		/// <param name="appArgs"></param>
		/// <returns></returns>
		internal static FwApp ReopenProject(string project, FwAppArgs appArgs)
		{
			ExecuteWithAppsShutDown("FLEx", ()=>
												{
													try
													{
														HandleLinkRequest(appArgs);
															return s_projectId ??
																new ProjectId(ClientServerServices.Current.Local.IdForLocalProject(project), null);
													}
													catch (Exception e)
													{
														//This is not good.
													}
													return null;
												});
			return s_flexApp ?? s_teApp;
		}
Ejemplo n.º 21
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Tries to find an existing FieldWorks process that is running the specified project.
		/// See the class comment on FwLinkArgs for details on how all the parts of hyperlinking work.
		/// </summary>
		/// <param name="project">The project we want to conect to.</param>
		/// <param name="args">The application arguments.</param>
		/// <returns>
		/// True if an existing process was found with the specified project and
		/// control was released to the found process, false otherwise
		/// </returns>
		/// ------------------------------------------------------------------------------------
		private static bool TryFindExistingProcess(ProjectId project, FwAppArgs args)
		{
			return RunOnRemoteClients(kFwRemoteRequest, requestor =>
			{
				ProjectMatch isMyProject;
				Func<ProjectId, FwAppArgs, ProjectMatch> invoker = requestor.HandleOpenProjectRequest;
				var start = DateTime.Now;
				do
				{
					IAsyncResult ar = invoker.BeginInvoke(project, args, null, null);
					while (!ar.IsCompleted)
					{
						s_fWaitingForUserOrOtherFw = true;
						// Wait until this process knows which project it is loading.
						if (!ar.AsyncWaitHandle.WaitOne(9000, false))
						{
							// timed out.
							if (MessageBox.Show(Properties.Resources.kstidFieldWorksDidNotRespond, Properties.Resources.kstidStartupProblem,
								MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
							{
								return true;
							}
						}
					}
					// We can now ask for the answer.
					isMyProject = invoker.EndInvoke(ar);

					if (isMyProject == ProjectMatch.SingleProcessMode)
					{
						Logger.WriteEvent("WEIRD! Detected single FW process mode while this process is trying to open a project.");
						Debug.Fail("We don't think this can happen, but it's no big deal.");
						return true; // Should kill this process
					}
					if (DateTime.Now - start > new TimeSpan(0, 0, 10))
					{
						// Some other process apparently keeps telling us it doesn't know. It's probably stuck in this same loop,
						// waiting for us!
						MessageBox.Show(Properties.Resources.kstidFieldWorksRespondedNotSure, Properties.Resources.kstidStartupProblem,
							MessageBoxButtons.OK, MessageBoxIcon.Warning);
						return true; // pretends some other process has the project opened and is handling the request; this process will quit
					}
				} while (isMyProject == ProjectMatch.DontKnowYet);

				s_fWaitingForUserOrOtherFw = false;
				return (isMyProject == ProjectMatch.ItsMyProject);
			});
		}
Ejemplo n.º 22
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Gets the default application to start for the project specified in the the
		/// command-line arguments.
		/// </summary>
		/// <param name="args">The command-line arguments.</param>
		/// ------------------------------------------------------------------------------------
		private static string GetDefaultApp(FwAppArgs args)
		{
			if (String.IsNullOrEmpty(args.Database))
				return FwUtils.ksFlexAbbrev; // no idea what to do, this is our general default.

			var projectFolder = Path.GetDirectoryName(args.Database);
			if (!Directory.Exists(projectFolder))
				return FwUtils.ksFlexAbbrev; // got to do something

			var settingsFolder = Path.Combine(projectFolder, FdoFileHelper.ksConfigurationSettingsDir);
			if (!Directory.Exists(settingsFolder))
				return FwUtils.ksFlexAbbrev; // no settings at all, take the default.

			var teMarkerPath = Path.Combine(settingsFolder, ksTeOpenMarkerFileName);
			if (File.Exists(teMarkerPath))
				return FwUtils.ksTeAbbrev;
			return FwUtils.ksFlexAbbrev; // TE hasn't recorded that it opened it, assume FLEx.
		}
Ejemplo n.º 23
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Gets an existing app or creates a new one for the application type specified on
		/// the command line.
		/// </summary>
		/// <param name="args">The application arguments.</param>
		/// <returns>An app to use (can be null if no valid app was specified)</returns>
		/// ------------------------------------------------------------------------------------
		private static FwApp GetOrCreateApplication(FwAppArgs args)
		{
			var appAbbrev = args.AppAbbrev;
			if (String.IsNullOrEmpty(appAbbrev))
			{
				// Probably a double-click of the data file. See if we can figure out who last had it open.
				appAbbrev = GetDefaultApp(args);
			}
			if (appAbbrev.Equals(FwUtils.ksTeAbbrev, StringComparison.InvariantCultureIgnoreCase))
			{
				if (FwUtils.IsTEInstalled)
				{
					if (s_teApp == null)
					{
						s_teApp = (FwApp)DynamicLoader.CreateObject(FwDirectoryFinder.TeDll,
							FwUtils.ksFullTeAppObjectName, s_fwManager, GetHelpTopicProvider(appAbbrev), args);
						s_teAppKey = s_teApp.SettingsKey;
					}
					return s_teApp;
				}
			}
			else if (appAbbrev.Equals(FwUtils.ksFlexAbbrev, StringComparison.InvariantCultureIgnoreCase))
			{
				if (FwUtils.IsFlexInstalled)
				{
					if (s_flexApp == null)
					{
						s_flexApp = (FwApp)DynamicLoader.CreateObject(FwDirectoryFinder.FlexDll,
							FwUtils.ksFullFlexAppObjectName, s_fwManager, GetHelpTopicProvider(appAbbrev), args);
						s_flexAppKey = s_flexApp.SettingsKey;
					}
					return s_flexApp;
				}
			}

			ShowCommandLineHelp();
			return null;
		}
Ejemplo n.º 24
0
        public void CreateFwAppArgs_DbAndProjSame()
        {
            FwAppArgs args = new FwAppArgs("-app", "te", "-db", "tim", "-proj", "monkey");

            Assert.IsTrue(args.ShowHelp, "Bad arguments should set ShowHelp to true");
        }
Ejemplo n.º 25
0
        public void CreateFwAppArgs_DuplicateSwitches()
        {
            FwAppArgs args = new FwAppArgs("-app", FwUtils.ksTeAppName, "-app", FwUtils.ksFlexAbbrev, "-proj", "monkey");

            Assert.IsTrue(args.ShowHelp, "Bad arguments should set ShowHelp to true");
        }
Ejemplo n.º 26
0
 private bool SameDatabase(FwAppArgs fwargs, FdoCache cache)
 {
     return fwargs.Database == "this$" ||
         fwargs.Database.ToLowerInvariant() == cache.ProjectId.Name.ToLowerInvariant()
         || fwargs.Database.ToLowerInvariant() == cache.ProjectId.Path.ToLowerInvariant()
         || Path.GetFileName(fwargs.Database).ToLowerInvariant() == cache.ProjectId.Name.ToLowerInvariant();
 }
Ejemplo n.º 27
0
        public void CreateFwAppArgs_BogusApp()
        {
            FwAppArgs args = new FwAppArgs("-app", "gobledygook", "-proj", "monkey");

            Assert.IsTrue(args.ShowHelp, "Bad arguments should set ShowHelp to true");
        }
Ejemplo n.º 28
0
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 public bool OnCopyLocationAsHyperlink(object unused)
 {
     CheckDisposed();
     if (m_currentContext != null)
     {
         FdoCache cache = (FdoCache)m_mediator.PropertyTable.GetValue("cache");
         var args = new FwAppArgs(FwUtils.ksFlexAbbrev, cache.ProjectId.Handle,
             cache.ProjectId.ServerName, m_currentContext.ToolName, m_currentContext.TargetGuid);
         ClipboardUtils.SetDataObject(args.ToString(), true);
     }
     return true;
 }
Ejemplo n.º 29
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Links to lexicon.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		internal void LinkToLexicon()
		{
			CheckDisposed();
			int hvo = m_hvoSelected;
			if (hvo == 0 && m_rghvo != null && m_rghvo.Count > 0)
				hvo = m_rghvo[0];
			// REVIEW: THIS SHOULD NEVER HAPPEN, BUT IF IT DOES, SHOULD WE TELL THE USER ANYTHING?
			if (hvo == 0)
				return;
			ICmObject cmo = m_cache.ServiceLocator.GetInstance<ICmObjectRepository>().GetObject(hvo);
			FwAppArgs link = new FwAppArgs(FwUtils.ksFlexAppName, m_cache.ProjectId.Handle,
				m_cache.ProjectId.ServerName, "lexiconEdit", cmo.Guid);
			Debug.Assert(m_mediator != null, "The program must pass in a mediator to follow a link in the same application!");
			IApp app = (IApp)m_mediator.PropertyTable.GetValue("App");
			app.HandleOutgoingLink(link);
		}
Ejemplo n.º 30
0
		private static FwXWindow RefreshCacheWindowAndAll(LexTextApp app, string fullProjectFileName)
		{
			var manager = app.FwManager;
			var appArgs = new FwAppArgs(fullProjectFileName);
			var newAppWindow =
				(FwXWindow)manager.ReopenProject(manager.Cache.ProjectId.Name, appArgs).ActiveMainWindow;
			if (IsVernacularSpellingEnabled(newAppWindow.Mediator))
				WfiWordformServices.ConformSpellingDictToWordforms(newAppWindow.Cache);
			//clear out any sort cache files (or whatever else might mess us up) and then refresh
			newAppWindow.ClearInvalidatedStoredData();
			newAppWindow.RefreshDisplay();
			return newAppWindow;
		}
Ejemplo n.º 31
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Launches a restore project when requested from the command-line.
		/// </summary>
		/// <param name="appArgs">The application command-line arguments.</param>
		/// ------------------------------------------------------------------------------------
		private static void LaunchRestoreFromCommandLine(FwAppArgs appArgs)
		{
			if (string.IsNullOrEmpty(appArgs.AppName)) // ENHANCE: Consider a more robust (less cryptic) way of doing this.
			{
				RestoreProject(null, appArgs.BackupFile);
				return;
			}

			// Command-line most likely came from a restore in another process.
			// There is no need to re-show the dialog since the user has already chosen
			// the options and confirmed to overwrite any existing database.
			Logger.WriteEvent("Restoring project: " + appArgs.BackupFile);
			RestoreProjectSettings restoreSettings = new RestoreProjectSettings(FwDirectoryFinder.ProjectsDirectory, appArgs.Database,
				appArgs.BackupFile, appArgs.RestoreOptions);
			RestoreCurrentProject(new FwRestoreProjectSettings(appArgs.AppAbbrev, restoreSettings), null);
		}
Ejemplo n.º 32
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Starts or activates an application requested from another process. This method is
		/// thread safe.
		/// See the class comment on FwLinkArgs for details on how all the parts of hyperlinking work.
		/// </summary>
		/// <param name="args">The application arguments</param>
		/// ------------------------------------------------------------------------------------
		internal static void KickOffAppFromOtherProcess(FwAppArgs args)
		{
			s_threadHelper.Invoke(() =>
			{
				// Get the new application first so it can give us the application name, etc.
				FwApp app = GetOrCreateApplication(args);
				if (app == null)
					return;

				if (app.HasBeenFullyInitialized)
				{
					// The application is already running so make sure we don't try re-initialize it
					if (app.MainWindows.Count == 0)
						ApplicationBusyDialog.ShowOnSeparateThread(args,
							ApplicationBusyDialog.WaitFor.WindowToActivate, app, null);
					else
					{
						app.ActivateWindow(0);
						if (args.HasLinkInformation)
							app.HandleIncomingLink(args);
					}
					return;
				}

				if (s_appServerMode)
				{
					// Make sure the cache is initialized for the application.
					using (ProgressDialogWithTask dlg = new ProgressDialogWithTask(s_threadHelper))
						InitializeApp(app, dlg);
					return;
				}

				FwApp otherApp = (app == s_teApp) ? s_flexApp : s_teApp;
				if (otherApp == null)
				{
					// The other app was null which means the requested application was the only
					// one already started. However, that application has not been fully
					// initialized yet. Just ignore this request from the other process since a
					// window will eventually be shown by this process later.
					return;
				}

				if (s_cache.ActionHandlerAccessor.CurrentDepth > 0)
				{
					ApplicationBusyDialog.ShowOnSeparateThread(args,
						ApplicationBusyDialog.WaitFor.OtherBusyApp, app, otherApp);
				}
				else if (otherApp.IsModalDialogOpen)
				{
					ApplicationBusyDialog.ShowOnSeparateThread(args,
						ApplicationBusyDialog.WaitFor.ModalDialogsToClose, app, otherApp);
				}
				else
				{
					// Make sure the cache is initialized for the application
					using (var dlg = new ProgressDialogWithTask(otherApp.ActiveMainWindow))
						InitializeApp(app, dlg);
				}
			});
		}
Ejemplo n.º 33
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Sets the UI culture.
		/// </summary>
		/// <param name="args">The application arguments</param>
		/// ------------------------------------------------------------------------------------
		private static bool SetUICulture(FwAppArgs args)
		{
			// Try the UI locale found on the command-line (if any).
			string locale = args.Locale;
			// If that doesn't exist, try the UI locale found in the registry.
			if (string.IsNullOrEmpty(locale))
				locale = (string)FwRegistryHelper.FieldWorksRegistryKey.GetValue(FwRegistryHelper.UserLocaleValueName, string.Empty);
			// If that doesn't exist, try the current system UI locale set at program startup
			// This is typically en-US, but we want this to match en since our English localizations use en.
			if (string.IsNullOrEmpty(locale) && Thread.CurrentThread.CurrentUICulture != null)
			{
				locale = Thread.CurrentThread.CurrentUICulture.Name;
				if (locale.StartsWith("en-"))
					locale = "en";
			}
			// If that doesn't exist, just use English ("en").
			if (string.IsNullOrEmpty(locale))
			{
				locale = "en";
			}
			else if (locale != "en")
			{
				// Check whether the desired locale has a localization, ignoring the
				// country code if necessary.  Fall back to English ("en") if no
				// localization exists.
				var rgsLangs = GetAvailableLangsFromSatelliteDlls();
				if (!rgsLangs.Contains(locale))
				{
					var originalLocale = locale;
					int idx = locale.IndexOf('-');
					if (idx > 0)
						locale = locale.Substring(0, idx);
					if (!rgsLangs.Contains(locale))
					{
						if (MessageBox.Show(string.Format(Properties.Resources.kstidFallbackToEnglishUi, originalLocale),
							Application.ProductName, MessageBoxButtons.YesNo) == DialogResult.No)
						{
							return false;
						}
						locale = "en";
						FwRegistryHelper.FieldWorksRegistryKey.SetValue(FwRegistryHelper.UserLocaleValueName, locale);
					}
				}
			}
			if (locale != Thread.CurrentThread.CurrentUICulture.Name)
				Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(locale);

			s_sWsUser = Thread.CurrentThread.CurrentUICulture.Name;
			return true;
		}
Ejemplo n.º 34
0
        public void CreateFwAppArgs_MultipleValues()
        {
            FwAppArgs args = new FwAppArgs("-app", "te", "flex", "-proj", "monkey");

            Assert.IsTrue(args.ShowHelp, "Bad arguments should set ShowHelp to true");
        }
Ejemplo n.º 35
0
		private static ProjectId DetermineProject(FwAppArgs args)
		{
			// Get project information from one of four places, in this order of preference:
			// 1. Command-line arguments
			// 2. Sample DB (if this is the first time this app has been run)
			// 3. Registry (if last startup was successful)
			// 4. Ask the user
			//
			// Except that with the new Welcome dialog, 2 through 4 are lumped into the Welcome dialog
			// functionality. If the user checks the "...always open the last edited project..." checkbox,
			// we will try to do that and only show the dialog if we fail.
			// If we try to use command-line arguments and it fails, we will use the Welcome dialog
			// to help the user figure out what to do next.
			var projId = new ProjectId(args.DatabaseType, args.Database, args.Server);
			StartupException projectOpenError;
			if (TryCommandLineOption(projId, out projectOpenError))
				return projId;

			// If this app hasn't been run before, ask user about opening sample DB.
			var app = GetOrCreateApplication(args);
			if (app.RegistrySettings.FirstTimeAppHasBeenRun)
				return ShowWelcomeDialog(args, app, null, projectOpenError);

			// Valid project information was not passed on the command-line, so try looking in
			// the registry for the last-run project.
			var previousStartupStatus = GetPreviousStartupStatus(app);
			var latestProject = app.RegistrySettings.LatestProject;
			if ((String.IsNullOrEmpty(projId.Name) || projectOpenError != null) &&
				previousStartupStatus != StartupStatus.Failed && !String.IsNullOrEmpty(latestProject))
			{
				// User didn't specify a project or gave bad command-line args,
				// so set projId to the last successfully opened project.
				projId = GetBestGuessProjectId(latestProject, app.RegistrySettings.LatestServer);
			}
			else if (previousStartupStatus == StartupStatus.Failed && !string.IsNullOrEmpty(latestProject))
			{
				// The previous project failed to open, so notify the user.
				projectOpenError = new StartupException(String.Format(
					Properties.Resources.kstidUnableToOpenLastProject, app.ApplicationName,
					latestProject));
			}

			var fOpenLastEditedProject = GetAutoOpenRegistrySetting(app);

			if (fOpenLastEditedProject && projId.IsValid && projectOpenError == null
				&& previousStartupStatus == StartupStatus.Successful)
				return projId;

			// No valid command line args, not the first time we've run the program,
			// and we aren't set to auto-open the last project, so give user options to open/create a project.
			return ShowWelcomeDialog(args, app, projId, projectOpenError);
		}
Ejemplo n.º 36
0
		public bool OnViewIncorrectWords(object argument)
		{
			FwLinkArgs link = new FwAppArgs(FwUtils.ksFlexAppName, Cache.ProjectId.Handle,
				Cache.ProjectId.ServerName, "Analyses", ActiveWordform(Cache, m_mediator));
			List<Property> additionalProps = link.PropertyTableEntries;
			additionalProps.Add(new Property("SuspendLoadListUntilOnChangeFilter", link.ToolName));
			additionalProps.Add(new Property("LinkSetupInfo", "TeCorrectSpelling"));
			m_mediator.PostMessage("FollowLink", link);
			return true;
		}
Ejemplo n.º 37
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Handles an outgoing link request from this application.
		/// </summary>
		/// <param name="link">The link.</param>
		/// ------------------------------------------------------------------------------------
		public void HandleOutgoingLink(FwAppArgs link)
		{
			m_fwManager.HandleLinkRequest(link);
		}
Ejemplo n.º 38
0
		private static bool LaunchProject(FwAppArgs args, ref ProjectId projectId)
		{
			while (true)
			{
				if (projectId == null)
				{
					Logger.WriteEvent("User has decided to quit");
					return false;
				}
				Logger.WriteEvent("User requested project " + projectId.UiName + " for BEP " + projectId.Type);

				// Look to see if another FieldWorks process is already running that is for
				// the requested project. If so, then transfer the request to that process.
				if (TryFindExistingProcess(projectId, args))
				{
					Logger.WriteEvent("Found FieldWorks.exe for project " + projectId.UiName + " for BEP " + projectId.Type);
					return false; // Found another process for this project, so we're done.
				}

				// Now that we know what project to load and it is openable. Start a new
				// log file for that project.
				Logger.WriteEvent("Transferring log to project log file " + projectId.UiName);
				Logger.Init(projectId.UiName);

				FwApp app = GetOrCreateApplication(args);
				try
				{
					return InitializeFirstApp(app, projectId);
				}
				catch (StartupException e)
				{
					if (s_cache != null)
					{
						s_cache.Dispose();
						s_cache = null;
					}
					Logger.Init(FwUtils.ksSuiteName);
					projectId = ShowWelcomeDialog(args, app, projectId, e);
				}
			}
		}
Ejemplo n.º 39
0
			public void HandleOutgoingLink(FwAppArgs link)
			{
				throw new NotImplementedException();
			}
Ejemplo n.º 40
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;
		}
Ejemplo n.º 41
0
 /// <summary>
 /// Handle the specified link if it is local.
 /// </summary>
 /// <param name="source"></param>
 /// <returns></returns>
 public bool OnHandleLocalHotlink(object source)
 {
     LocalLinkArgs args = source as LocalLinkArgs;
     if (args == null)
         return true; // we can't handle it, but probably no one else can either. Maybe should crash?
     var url = args.Link;
     if(!url.StartsWith(FwLinkArgs.kFwUrlPrefix))
         return true; // we can't handle it, but no other colleague can either. Needs to launch whatever can (see VwBaseVc.DoHotLinkAction).
     try
     {
         var fwargs = new FwAppArgs(new[] {url});
         FdoCache cache = (FdoCache) m_mediator.PropertyTable.GetValue("cache");
         if (SameServer(fwargs, cache) && SameDatabase(fwargs, cache))
         {
             OnFollowLink(fwargs);
             args.LinkHandledLocally = true;
         }
     }
     catch (Exception)
     {
         // Something went wrong, probably its not a kind of link we understand.
     }
     return true;
 }
Ejemplo n.º 42
0
		private static ProjectId ShowWelcomeDialog(FwAppArgs args, FwApp startingApp, ProjectId lastProjectId, StartupException exception)
		{
			CloseSplashScreen();

			var helpTopicProvider = startingApp as IHelpTopicProvider;

			// Use the last edited project as the base guess for which project we'll open.
			var projectToTry = lastProjectId;

			// Continue to ask for an option until one is selected.
			s_fWaitingForUserOrOtherFw = true;
			do
			{
				if (exception != null)
				{
					if (projectToTry != null)
						Logger.WriteEvent("Problem opening " + projectToTry.UiName + ".");
					Logger.WriteError(exception);
				}

				// Put this here (i.e. inside the do loop) so any exceptions
				// will be logged before terminating.
				if (s_noUserInterface)
					return null;

				// If we changed our projectToTry below and we're coming through again,
				// reset our projectId.
				projectToTry = lastProjectId;

				using (WelcomeToFieldWorksDlg dlg = new WelcomeToFieldWorksDlg(helpTopicProvider, args.AppAbbrev, exception, s_noPreviousReportingSettings))
				{
					if (exception != null)
					{
						dlg.ShowErrorLabelHideLink();
					}
					else
					{
						if (projectToTry != null && projectToTry.IsValid)
						{
							dlg.ProjectLinkUiName = projectToTry.Name;
							dlg.SetFirstOrLastProjectText(false);
						}
						else
						{
							var sampleProjId = GetSampleProjectId(startingApp);
							if (sampleProjId != null)
							{
								dlg.ProjectLinkUiName = sampleProjId.Name;
								dlg.SetFirstOrLastProjectText(true);
								// LT-13943 - forgot to set this variable, which made it not be able to open
								// the sample db.
								projectToTry = new ProjectId(startingApp.SampleDatabase, null);
							}
							else // user didn't install Sena 3!
							{
								projectToTry = null;
							}
						}
						if (projectToTry != null)
							dlg.ShowLinkHideErrorLabel();
						else
							dlg.ShowErrorLabelHideLink();
					}
					bool gotAutoOpenSetting = false;
					if (startingApp.RegistrySettings != null) // may be null if disposed after canceled restore.
					{
					dlg.OpenLastProjectCheckboxIsChecked = GetAutoOpenRegistrySetting(startingApp);
						gotAutoOpenSetting = true;
					}
					dlg.StartPosition = FormStartPosition.CenterScreen;
					dlg.ShowDialog();
					exception = null;
					// We get the app each time through the loop because a failed Restore operation can dispose it.
					var app = GetOrCreateApplication(args);
					if (gotAutoOpenSetting)
					app.RegistrySettings.AutoOpenLastEditedProject = dlg.OpenLastProjectCheckboxIsChecked;
					switch (dlg.DlgResult)
					{
						case WelcomeToFieldWorksDlg.ButtonPress.New:
							projectToTry = CreateNewProject(dlg, app, helpTopicProvider);
							Debug.Assert(projectToTry == null || projectToTry.IsValid);
							break;
						case WelcomeToFieldWorksDlg.ButtonPress.Open:
							projectToTry = ChooseLangProject(null, helpTopicProvider);
							try
							{
								if (projectToTry != null)
									projectToTry.AssertValid();
							}
							catch (StartupException e)
							{
								exception = e;
							}
							break;
						case WelcomeToFieldWorksDlg.ButtonPress.Link:
							// LT-13943 - this guard keeps the projectToTry from getting blasted by a null when it has
							// a useful projectId (like the initial sample db the first time FLEx is run).
							if (lastProjectId != null && !lastProjectId.Equals(projectToTry))
								projectToTry = lastProjectId; // just making sure!
							Debug.Assert(projectToTry.IsValid);
							break;
						case WelcomeToFieldWorksDlg.ButtonPress.Restore:
							s_allowFinalShutdown = false;
							RestoreProject(null, app);
							s_allowFinalShutdown = true;
							projectToTry = s_projectId; // Restore probably used this process
							break;
						case WelcomeToFieldWorksDlg.ButtonPress.Exit:
							return null; // Should cause the FW process to exit later
						case WelcomeToFieldWorksDlg.ButtonPress.Receive:
							if (!FwNewLangProject.CheckProjectDirectory(null, helpTopicProvider))
								break;
							ObtainedProjectType obtainedProjectType;
							projectToTry = null; // If the user cancels the send/receive, this null will result in a return to the welcome dialog.
							// Hard to say what Form.ActiveForm is here. The splash and welcome dlgs are both gone.
							var projectDataPathname = ObtainProjectMethod.ObtainProjectFromAnySource(Form.ActiveForm,
								helpTopicProvider, out obtainedProjectType);
							if (!string.IsNullOrEmpty(projectDataPathname))
							{
								projectToTry = new ProjectId(FDOBackendProviderType.kXML, projectDataPathname, null);
								var activeWindow = startingApp.ActiveMainWindow;
								if (activeWindow != null)
								{
									((IFwMainWnd)activeWindow).Mediator.PropertyTable.SetProperty("LastBridgeUsed",
										obtainedProjectType == ObtainedProjectType.Lift ? "LiftBridge" : "FLExBridge",
										PropertyTable.SettingsGroup.LocalSettings);
								}
							}
							break;
						case WelcomeToFieldWorksDlg.ButtonPress.Import:
							projectToTry = CreateNewProject(dlg, app, helpTopicProvider);
							if (projectToTry != null)
							{
							var projectLaunched = LaunchProject(args, ref projectToTry);
								if (projectLaunched)
							{
								s_projectId = projectToTry; // Window is open on this project, we must not try to initialize it again.
								var mainWindow = Form.ActiveForm;
									if (mainWindow is IxWindow)
								{
										((IxWindow) mainWindow).Mediator.SendMessage("SFMImport", null);
								}
								else
								{
									return null;
								}
							}
							else
							{
								return null;
							}
							}
							break;
					}
				}
			}
			while (projectToTry == null || !projectToTry.IsValid);

			Logger.WriteEvent("Project selected in Welcome dialog: " + projectToTry);

			s_fWaitingForUserOrOtherFw = false;
			return projectToTry;
		}
Ejemplo n.º 43
0
 private bool SameServer(FwAppArgs fwargs, FdoCache cache)
 {
     if (String.IsNullOrEmpty(fwargs.Server) && String.IsNullOrEmpty(cache.ProjectId.ServerName))
         return true;
     if (String.IsNullOrEmpty(fwargs.Server) && fwargs.Database == "this$")
         return true;
     if (String.IsNullOrEmpty(fwargs.Server) || String.IsNullOrEmpty(cache.ProjectId.ServerName))
         return false;
     return fwargs.Server.ToLowerInvariant() == cache.ProjectId.ServerName.ToLowerInvariant();
 }
Ejemplo n.º 44
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Handles a link request. This handles determining the correct application to start
		/// up and for the correct project. This method is thread safe.
		/// </summary>
		/// <param name="link">The link.</param>
		/// ------------------------------------------------------------------------------------
		internal static void HandleLinkRequest(FwAppArgs link)
		{
			s_threadHelper.Invoke(() =>
			{
				Debug.Assert(s_projectId != null, "We shouldn't try to handle a link request until an application is started");
				ProjectId linkedProject = new ProjectId(link.DatabaseType, link.Database, link.Server);
				if (IsSharedXmlBackendNeeded(linkedProject))
					linkedProject.Type = FDOBackendProviderType.kSharedXML;
				if (linkedProject.Equals(s_projectId))
					FollowLink(link);
				else if (!TryFindLinkHandler(link))
				{
					// No other FieldWorks process was running that could handle the request, so
					// start a brand new process for the project requested by the link.
					// REVIEW: it might look strange to dispose the return value of OpenProjectWithNewProcess.
					// However, that is a Process that gets started, and it is ok to dispose that
					// right away if we don't work with the process object. It might be better
					// though to change the signature of OpenProjectWithNewProcess to return
					// a boolean (true iff the link was successfully handled).
					using (OpenProjectWithNewProcess(linkedProject, link.AppAbbrev, "-" + FwLinkArgs.kLink, link.ToString()))
					{
					}
				}
			});
		}
Ejemplo n.º 45
0
		/// <summary>
		/// Called by reflection to implement the command.
		/// </summary>
		/// <param name="argument"></param>
		/// <returns></returns>
		public bool OnEditSpellingStatus(object argument)
		{
			// Without checking both the SpellingStatus and (virtual) FullConcordanceCount
			// fields for the ActiveWordform() result, it's too likely that the user
			// will get a puzzling "Target not found" message popping up.  See LT-8717.
			FwLinkArgs link = new FwAppArgs(FwUtils.ksFlexAppName, Cache.ProjectId.Handle,
				Cache.ProjectId.ServerName, "toolBulkEditWordforms", Guid.Empty);
			List<Property> additionalProps = link.PropertyTableEntries;
			additionalProps.Add(new Property("SuspendLoadListUntilOnChangeFilter", link.ToolName));
			additionalProps.Add(new Property("LinkSetupInfo", "TeReviewUndecidedSpelling"));
			m_mediator.PostMessage("FollowLink", link);
			return true;
		}
Ejemplo n.º 46
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Follows the specified link request for this project.
		/// </summary>
		/// <param name="link">The link request.</param>
		/// ------------------------------------------------------------------------------------
		internal static void FollowLink(FwAppArgs link)
		{
			// Make sure the application that needs to handle the link is created.
			KickOffAppFromOtherProcess(link);

			// FWR-2504 Maybe I'm missing something but "KickOffAppFromOtherProcess(link)"
			// seems to activate the link already in "InitializeApp()". If so, FwAppArgs
			// will have been cleared out by now. I'll leave this in, since there may be
			// other cases where the link information survives and we need to follow it now.
			if (link.HasLinkInformation)
			{
				FwApp app = GetAppFromAppNameOrAbbrev(link.AppName);
				Debug.Assert(app != null && app.HasBeenFullyInitialized,
					"KickOffAppFromOtherProcess should create the application needed");
				// Let the application handle the link
				app.HandleIncomingLink(link);
			}
		}
Ejemplo n.º 47
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="fwManager">The FieldWorks manager for dealing with FieldWorks-level
        /// stuff.</param>
        /// <param name="helpTopicProvider">An application-specific help topic provider.</param>
        /// <param name="appArgs">The application arguments.</param>
        /// ------------------------------------------------------------------------------------
        public FwXApp(IFieldWorksManager fwManager, IHelpTopicProvider helpTopicProvider,
			FwAppArgs appArgs)
            : base(fwManager, helpTopicProvider)
        {
            m_appArgs = appArgs;
        }
Ejemplo n.º 48
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Attempts to find another FieldWorks process that can handle the specified link.
		/// </summary>
		/// <param name="link">The link.</param>
		/// <returns>True if to correct process was found to handle the link, false otherwise
		/// </returns>
		/// ------------------------------------------------------------------------------------
		private static bool TryFindLinkHandler(FwAppArgs link)
		{
			return RunOnRemoteClients(kFwRemoteRequest, requestor =>
			{
				// ENHANCE (TimS): We might want to do similar logic to TryFindExistingProcess to
				// wait for projects that are starting up.
				return (requestor.HandleLinkRequest(link));
			});
		}