Example #1
0
        /*
         * On Linux we try to launch.
         */
        private static LaunchResult LaunchInTerminalLinux(string directory, string runtimePath, string[] runtimeArgs, string program, string[] programArgs, Dictionary <string, string> environmentVariables)
        {
            Process terminalProcess = new Process();

            terminalProcess.StartInfo.CreateNoWindow  = true;
            terminalProcess.StartInfo.UseShellExecute = false;

            terminalProcess.StartInfo.WorkingDirectory = directory;
            terminalProcess.StartInfo.FileName         = LINUX_TERM;
            terminalProcess.StartInfo.Arguments        = string.Format(CultureInfo.InvariantCulture, "--title {0} -x bash -c 'cd {1}; {2} {3} {4} {5} ; echo; read -p {6} -n1;'",
                                                                       Quote(TERMINAL_TITLE), Quote(directory), Quote(runtimePath), ConcatArgs(runtimeArgs), Quote(program), ConcatArgs(programArgs), Quote(PRESS_KEY_TO_CONTINUE));

            if (environmentVariables != null)
            {
                ProcessStartInfo processStartInfo = terminalProcess.StartInfo;
                foreach (var entry in environmentVariables)
                {
                    processStartInfo.SetEnvironmentVariable(entry.Key, entry.Value);
                }
            }

            var result = new LaunchResult();

            try
            {
                terminalProcess.Start();
                result.SetProcess(terminalProcess, terminalProcess.Id);
            }
            catch (Exception e)
            {
                result.SetError(e.Message);
            }

            return(result);
        }
Example #2
0
        // --- private ---------------------------------------------------------------------------------------------------------

        /*
         * Generic launch: lauch node directly
         */
        private static LaunchResult LaunchInTerminalGeneric(string directory, string runtimePath, string[] runtimeArgs, string program, string[] programArgs, Dictionary <string, string> environmentVariables)
        {
            Process process = new Process();

            process.StartInfo.CreateNoWindow   = true;
            process.StartInfo.UseShellExecute  = true;
            process.StartInfo.WorkingDirectory = directory;
            process.StartInfo.FileName         = runtimePath;
            process.StartInfo.Arguments        = string.Format(CultureInfo.InvariantCulture, "{0} {1} {2}", ConcatArgs(runtimeArgs), Terminal.Quote(program), ConcatArgs(programArgs));

            if (environmentVariables != null)
            {
                // we cannot set the env vars on the process StartInfo because we need to set StartInfo.UseShellExecute to true at the same time.
                // instead we set the env vars on OpenDebug itself because we know that OpenDebug lives as long as a debug session.
                foreach (var entry in environmentVariables)
                {
                    System.Environment.SetEnvironmentVariable(entry.Key, entry.Value);
                }
            }

            var result = new LaunchResult();

            try
            {
                process.Start();
                result.SetProcess(process, process.Id);
            }
            catch (Exception e)
            {
                result.SetError(e.Message);
            }
            return(result);
        }
        internal static LaunchResult SafeLaunchBrowserOnlyIfPossible(Uri originatingUri, Uri destinationUri, string targetName, bool fIsTopLevel)
        {
            LaunchResult launchResult = LaunchResult.NotLaunched;
            bool         flag         = destinationUri.Scheme == Uri.UriSchemeHttp || destinationUri.Scheme == Uri.UriSchemeHttps || destinationUri.IsFile;
            bool         flag2        = string.Compare(destinationUri.Scheme, Uri.UriSchemeMailto, StringComparison.OrdinalIgnoreCase) == 0;

            if (!BrowserInteropHelper.IsInitialViewerNavigation && SecurityHelper.CallerHasUserInitiatedNavigationPermission() && ((fIsTopLevel && flag) || flag2))
            {
                if (flag)
                {
                    IBrowserCallbackServices browserCallbackServices = (Application.Current != null) ? Application.Current.BrowserCallbackServices : null;
                    if (browserCallbackServices != null)
                    {
                        launchResult = AppSecurityManager.CanNavigateToUrlWithZoneCheck(originatingUri, destinationUri);
                        if (launchResult == LaunchResult.Launched)
                        {
                            browserCallbackServices.DelegateNavigation(BindUriHelper.UriToString(destinationUri), targetName, AppSecurityManager.GetHeaders(destinationUri));
                            launchResult = LaunchResult.Launched;
                        }
                    }
                }
                else if (flag2)
                {
                    UnsafeNativeMethods.ShellExecute(new HandleRef(null, IntPtr.Zero), null, BindUriHelper.UriToString(destinationUri), null, null, 0);
                    launchResult = LaunchResult.Launched;
                }
            }
            return(launchResult);
        }
Example #4
0
 private void CancelLaunching(LaunchResult result)
 {
     if (!result.Process.HasExited)
     {
         result.Process.Kill();
     }
 }
Example #5
0
        /*
         * On Windows....
         */
        private static LaunchResult LaunchInTerminalWindows(string workingDirectory, string runtimePath, string[] runtimeArguments, string program, string[] program_args, Dictionary <string, string> environmentVariables)
        {
            var title = workingDirectory + " - VS Code";

            var consoleProc = new Process();

            consoleProc.StartInfo.CreateNoWindow   = true;
            consoleProc.StartInfo.UseShellExecute  = true;
            consoleProc.StartInfo.WorkingDirectory = workingDirectory;
            consoleProc.StartInfo.FileName         = CMD;
            consoleProc.StartInfo.Arguments        = string.Format("/C title {0} && {1} {2} {3} {4} || pause",
                                                                   title, Terminal.Quote(runtimePath), ConcatArgs(runtimeArguments), Terminal.Quote(program), ConcatArgs(program_args));

            if (environmentVariables != null)
            {
                // we cannot set the env vars on the process StartInfo because we need to set StartInfo.UseShellExecute to true at the same time.
                // instead we set the env vars on MonoDebug itself because we know that MonoDebug lives as long as a debug session.
                foreach (var entry in environmentVariables)
                {
                    System.Environment.SetEnvironmentVariable(entry.Key, entry.Value);
                }
            }

            var result = new LaunchResult();

            try {
                consoleProc.Start();
                result.SetConsoleProcess(consoleProc);
            }
            catch (Exception e) {
                result.SetError(e.Message);
            }

            return(result);
        }
        internal static void SafeLaunchBrowserDemandWhenUnsafe(Uri originatingUri, Uri destinationUri, bool fIsTopLevel)
        {
            LaunchResult launchResult = AppSecurityManager.SafeLaunchBrowserOnlyIfPossible(originatingUri, destinationUri, fIsTopLevel);

            if (launchResult == LaunchResult.NotLaunched)
            {
                SecurityHelper.DemandUnmanagedCode();
                AppSecurityManager.UnsafeLaunchBrowser(destinationUri, null);
            }
        }
Example #7
0
        ///<summary>
        ///     Safely launch the browser if you can.
        ///     If you can't demand unmanaged code permisison.
        ///
        ///     originatingUri = the current uri
        ///     destinationUri = the uri you are going to.
        ///</summary>
        internal static void SafeLaunchBrowserDemandWhenUnsafe(Uri originatingUri, Uri destinationUri, bool fIsTopLevel)
        {
            LaunchResult launched = LaunchResult.NotLaunched;

            launched = SafeLaunchBrowserOnlyIfPossible(originatingUri, destinationUri, fIsTopLevel);
            if (launched == LaunchResult.NotLaunched)
            {
                UnsafeLaunchBrowser(destinationUri);
            }
        }
Example #8
0
        //Demo
        public static void Main(string[] args)
        {
            OneMCL mcl = new OneMCL("E:/BestOwl/Desktop/LauncherTest");

            mcl.UserAuthenticator = new OfflineAuthenticator("MicroOwl");
            LaunchOptionBase message = new LaunchOptionBase("demo")
            {
                gameDir   = "E:\\BestOwl\\Desktop\\LauncherTest_GameDir",
                versionId = "1.12.2",
                javaExt   = "C:\\Program Files\\Java\\jre-9.0.4\\bin\\javaw.exe"
            };
            LaunchResult result = mcl.Launch(message);
        }
Example #9
0
 public static void SetGameTitle(LaunchResult result, string title)
 {
     Task.Factory.StartNew(() =>
     {
         try
         {
             var handle = result.Process.MainWindowHandle;
             while (!result.Process.HasExited)
             {
                 SetWindowText(handle, title);
                 Thread.Sleep(1000);
             }
         }
         catch (Exception) {}
     });
 }
        protected override void Execute(NativeActivityContext context)
        {
            string AppId     = string.Empty;
            string exepath   = string.Empty;
            string arguments = string.Empty;

            try
            {
                AppId = ApplicationID.Get(context);
                if ((Arguments != null) && (Arguments.Expression != null))
                {
                    arguments = Arguments.Get(context);
                }
                if (AppId != string.Empty) //scraping time
                {
                    if (!SelectHelper.CurrentRuntimeApplicationHelper.RuntimeApplicationObjects.ContainsKey(AppId))
                    {
                        if ((EXEPath != null) && (EXEPath.Expression != null))
                        {
                            exepath = EXEPath.Get(context);

                            if (string.IsNullOrEmpty(arguments))
                            {
                                Process.Start(exepath);
                            }
                            else
                            {
                                Process.Start(exepath, arguments);
                            }
                            SelectHelper.CurrentRuntimeApplicationHelper.RuntimeApplicationObjects.Add(AppId, new object());
                            LaunchResult.Set(context, true);
                        }
                    }
                }
            }catch (Exception ex)
            {
                LaunchResult.Set(context, false);
                Logger.Log.Logger.LogData(ex.Message + " in activity OpenDesktopApplication", Logger.LogLevel.Error);
                if (!ContinueOnError)
                {
                    context.Abort();
                }
            }

            //throw new NotImplementedException();
        }
Example #11
0
        ///<summary>
        /// Safely launch the browser if it's possible to do so in partial trust
        /// Returns enum indicating whether we safely launched ( or at least think we did).
        /// Html target names can be passed in with this.
        ///     This function is appropriate for use when we launch the browser from partial trust
        ///     ( as it doesn't perform demands for the "unsafe" cases )
        ///</summary>
        internal static LaunchResult SafeLaunchBrowserOnlyIfPossible(Uri originatingUri, Uri destinationUri, string targetName, bool fIsTopLevel)
        {
            LaunchResult launched = LaunchResult.NotLaunched;

            bool isKnownScheme = (Object.ReferenceEquals(destinationUri.Scheme, Uri.UriSchemeHttp)) ||
                                 (Object.ReferenceEquals(destinationUri.Scheme, Uri.UriSchemeHttps)) ||
                                 destinationUri.IsFile;

            bool fIsMailTo = String.Compare(destinationUri.Scheme, Uri.UriSchemeMailto, StringComparison.OrdinalIgnoreCase) == 0;

            // We elevate to navigate the browser iff:
            //  We are user initiated AND
            //      Scheme == http/https & topLevel OR scheme == mailto.
            //
            // For all other cases ( evil protocols etc).
            // We will demand.
            //
            // The check of IsInitialViewerNavigation is necessary because viewer applications will probably
            // need to call Navigate on the URI they receive, but we want them to be able to do it in partial trust.
            if ((!BrowserInteropHelper.IsInitialViewerNavigation &&
                 MS.Internal.PresentationFramework.SecurityHelper.CallerHasUserInitiatedNavigationPermission()) &&
                ((fIsTopLevel && isKnownScheme) || fIsMailTo))
            {
                if (!isKnownScheme && fIsMailTo) // unnecessary if - but being paranoid.
                {
                    // Shell-Exec the browser to the mailto url.
                    // assumed safe - because we're only allowing this for mailto urls.
                    //

                    UnsafeNativeMethods.ShellExecute(new HandleRef(null, IntPtr.Zero),          /*hwnd*/
                                                     null,                                      /*operation*/
                                                     BindUriHelper.UriToString(destinationUri), /*file*/
                                                     null,                                      /*parameters*/
                                                     null,                                      /*directory*/
                                                     0);                                        /*nShowCmd*/
                    launched = LaunchResult.Launched;
                }
            }

            return(launched);
        }
Example #12
0
 private void Btn_launch_Click(object sender, RoutedEventArgs e)
 {
     KMCCC.Launcher.Version selectedItem = (KMCCC.Launcher.Version) this.ListVersions.SelectedItem;
     if (selectedItem == null)
     {
         MessageBox.Show("检测到没有游戏文件!");
     }
     else
     {
         Config.LastVersion = selectedItem.Id;
         LaunchOptions options = new LaunchOptions {
             Version       = selectedItem,
             MaxMemory     = Config.MaxMemory,
             Authenticator = (Config.Authenticator == "Yggdrasil") ? ((IAuthenticator) new YggdrasilLogin(Config.UserName, Config.Password, true, null, null)) : ((IAuthenticator) new OfflineAuthenticator(Config.UserName)),
             Server        = (Config.Server != null) ? new ServerInfo() : null,
             Mode          = (Config.LaunchMode == "BMCL") ? ((LaunchMode)LaunchMode.BmclMode) : ((Config.LaunchMode == "MCLauncher") ? ((LaunchMode)LaunchMode.MCLauncher) : null)
         };
         Action <MinecraftLaunchArguments>[] argumentsOperators = new Action <MinecraftLaunchArguments>[] { args => args.AdvencedArguments.Add(Config.AdvancedArguments) };
         LaunchResult result = App.Core.Launch(options, argumentsOperators);
         if (!result.Success)
         {
             MessageBox.Show(result.ErrorMessage, result.ErrorType.ToString(), MessageBoxButton.OK, MessageBoxImage.Hand);
             switch (result.ErrorType)
             {
             case ErrorType.NoJAVA:
             case ErrorType.AuthenticationFailed:
                 new ConfigWindow {
                     Owner = this
                 }.ShowDialog();
                 break;
             }
         }
         else
         {
             base.Hide();
         }
     }
 }
Example #13
0
		/*
		 * On Linux we try to launch.
		 */
		private static LaunchResult LaunchInTerminalLinux(string directory, string runtimePath, string[] runtimeArgs, string program, string[] programArgs, Dictionary<string, string> environmentVariables)
		{
			Process terminalProcess = new Process();
			terminalProcess.StartInfo.CreateNoWindow = true;
			terminalProcess.StartInfo.UseShellExecute = false;

			terminalProcess.StartInfo.WorkingDirectory = directory;
			terminalProcess.StartInfo.FileName = LINUX_TERM;
			terminalProcess.StartInfo.Arguments = string.Format("--title {0} -x bash -c 'cd {1}; {2} {3} {4} {5} ; echo; read -p {6} -n1;'",
				Quote(TERMINAL_TITLE), Quote(directory), Quote(runtimePath), ConcatArgs(runtimeArgs), Quote(program), ConcatArgs(programArgs), Quote(PRESS_KEY_TO_CONTINUE));

			if (environmentVariables != null) {
				#if DNXCORE50
				var dict = terminalProcess.StartInfo.Environment;
				#else
				var dict = terminalProcess.StartInfo.EnvironmentVariables;
				#endif
				foreach (var entry in environmentVariables) {
					dict.Add(entry.Key, entry.Value);
				}
			}

			var result = new LaunchResult();
			try {
				terminalProcess.Start();
				result.SetProcess(terminalProcess, terminalProcess.Id);
			}
			catch (Exception e) {
				result.SetError(e.Message);
			}

			return result;
		}
Example #14
0
        private static LaunchResult CanNavigateToUrlWithZoneCheck(Uri originatingUri, Uri destinationUri)
        {
            LaunchResult launchResult = LaunchResult.NotLaunched;            // fail securely - assume this is the default.
            int          targetZone   = NativeMethods.URLZONE_LOCAL_MACHINE; // fail securely this is the most priveleged zone
            int          sourceZone   = NativeMethods.URLZONE_INTERNET;      // fail securely this is the least priveleged zone.
            bool         fEnabled     = true;

            EnsureSecurityManager();

            // is this feature enabled ?
            fEnabled = UnsafeNativeMethods.CoInternetIsFeatureEnabled(
                NativeMethods.FEATURE_ZONE_ELEVATION,
                NativeMethods.GET_FEATURE_FROM_PROCESS) != NativeMethods.S_FALSE;

            targetZone = MapUrlToZone(destinationUri);

            // Get source zone.

            // Initialize sourceUri to null so that source zone defaults to the least privileged zone.
            Uri sourceUri = null;

            // If the MimeType is not a container, attempt to find sourceUri.
            // sourceUri should be null for Container cases, since it always assumes
            // the least privileged zone (InternetZone).
            if (Application.Current.MimeType != MimeType.Document)
            {
                sourceUri = BrowserInteropHelper.Source;
            }
            else if (destinationUri.IsFile &&
                     System.IO.Path.GetExtension(destinationUri.LocalPath)
                     .Equals(DocumentStream.XpsFileExtension, StringComparison.OrdinalIgnoreCase))
            {
                // In this case we know the following:
                //  1) We are currently a Container
                //  2) The destination is a File and another Container

                // In this case we want to treat the destination as internet too so Container
                // can navigate to other Containers by passing zone checks
                targetZone = NativeMethods.URLZONE_INTERNET;
            }

            if (sourceUri != null)
            {
                sourceZone = MapUrlToZone(sourceUri);
            }
            else
            {
                // 2 potential ways to get here.
                //      a) We aren't a fusion hosted app. Assume full-trust.
                //      b) Some



                bool fTrusted = SecurityHelper.CheckUnmanagedCodePermission();

                if (fTrusted)
                {
                    return(LaunchResult.Launched);
                }
                else
                {
                    //
                    //  If we didn't get a SourceUri, we'll assume internet zone.
                    //  And use Source for the uri of origin.
                    //
                    //  This isn't quite right - but the sourceUri is only used to show a message to the user.
                    //  Worse case is confusing user experience. ( this uri is not used in the elevation determination).
                    //

                    sourceZone = NativeMethods.URLZONE_INTERNET;
                    sourceUri  = originatingUri;
                }
            }

            // <Notes from Trident>
            // ------------------------------
            // Check if there is a zone elevation.
            // Custom zones would have a higher value that URLZONE_UNTRUSTED, so this solution isn't quite complete.
            // However, we don't know of any product actively using custom zones, so rolling this out.
            // INTRANET and TRUSTED are treated as equals.
            // ------------------------------
            // </Notes from Trident>

            //
            // Note the negative logic - it first sees to see something is *not* a zone elevation.
            //
            if (
                // Even if feature is disabled.
                // We still block navigation to local machine.
                // IF source zone is internet or restricted.

                (!fEnabled &&
                 ((sourceZone != NativeMethods.URLZONE_INTERNET &&
                   sourceZone != NativeMethods.URLZONE_UNTRUSTED) ||
                  targetZone != NativeMethods.URLZONE_LOCAL_MACHINE)) ||

                // If feature is enabled
                // It's not a zone elevation if
                //     the zones are equal OR
                //        the zones are both less than restricted and
                //            the sourceZone is more trusted than Target OR
                //            sourceZone and TargetZone are both Intranet or Trusted
                //
                // per aganjam - Intranet and Trusted are treated as equivalent
                // as it was a common scenario for IE. ( website on intranet points to trusted site).
                //

                (fEnabled &&
                 (
                     sourceZone == targetZone ||
                     (
                         sourceZone <= NativeMethods.URLZONE_UNTRUSTED &&
                         targetZone <= NativeMethods.URLZONE_UNTRUSTED &&
                         (
                             sourceZone < targetZone ||
                             (
                                 (sourceZone == NativeMethods.URLZONE_TRUSTED || sourceZone == NativeMethods.URLZONE_INTRANET) &&
                                 (targetZone == NativeMethods.URLZONE_TRUSTED || targetZone == NativeMethods.URLZONE_INTRANET)
                             )
                         )
                     )
                 )))
            {
                // There is no zone elevation. You can launch away !
                return(LaunchResult.Launched);
            }

            launchResult = CheckBlockNavigation(sourceUri,
                                                destinationUri,
                                                fEnabled);

            return(launchResult);
        }
Example #15
0
		// --- private ---------------------------------------------------------------------------------------------------------

		/*
		 * Generic launch: lauch node directly
		 */
		private static LaunchResult LaunchInTerminalGeneric(string directory, string runtimePath, string[] runtimeArgs, string program, string[] programArgs, Dictionary<string, string> environmentVariables)
		{
			Process process = new Process();
			process.StartInfo.CreateNoWindow = true;
			process.StartInfo.UseShellExecute = true;
			process.StartInfo.WorkingDirectory = directory;
			process.StartInfo.FileName = runtimePath;
			process.StartInfo.Arguments = string.Format("{0} {1} {2}", ConcatArgs(runtimeArgs), Terminal.Quote(program), ConcatArgs(programArgs));

			if (environmentVariables != null) {
				// we cannot set the env vars on the process StartInfo because we need to set StartInfo.UseShellExecute to true at the same time.
				// instead we set the env vars on OpenDebug itself because we know that OpenDebug lives as long as a debug session.
				foreach (var entry in environmentVariables) {
					System.Environment.SetEnvironmentVariable(entry.Key, entry.Value);
				}
			}

			var result = new LaunchResult();
			try {
				process.Start();
				result.SetProcess(process, process.Id);
			}
			catch (Exception e) {
				result.SetError(e.Message);
			}
			return result;
		}
Example #16
0
        ///<summary>
        /// Safely launch the browser if it's possible to do so in partial trust
        /// Returns enum indicating whether we safely launched ( or at least think we did).
        /// Html target names can be passed in with this.
        ///     This function is appropriate for use when we launch the browser from partial trust
        ///     ( as it doesn't perform demands for the "unsafe" cases )
        ///</summary>
        internal static LaunchResult SafeLaunchBrowserOnlyIfPossible(Uri originatingUri, Uri destinationUri, string targetName, bool fIsTopLevel)
        {
            LaunchResult launched = LaunchResult.NotLaunched;

            bool isKnownScheme = (Object.ReferenceEquals(destinationUri.Scheme, Uri.UriSchemeHttp)) ||
                                 (Object.ReferenceEquals(destinationUri.Scheme, Uri.UriSchemeHttps)) ||
                                 destinationUri.IsFile;

            bool fIsMailTo = String.Compare(destinationUri.Scheme, Uri.UriSchemeMailto, StringComparison.OrdinalIgnoreCase) == 0;

            // We elevate to navigate the browser iff:
            //  We are user initiated AND
            //      Scheme == http/https & topLevel OR scheme == mailto.
            //
            // For all other cases ( evil protocols etc).
            // We will demand.
            //
            // The check of IsInitialViewerNavigation is necessary because viewer applications will probably
            // need to call Navigate on the URI they receive, but we want them to be able to do it in partial trust.
            if ((!BrowserInteropHelper.IsInitialViewerNavigation &&
                 MS.Internal.PresentationFramework.SecurityHelper.CallerHasUserInitiatedNavigationPermission()) &&
                ((fIsTopLevel && isKnownScheme) || fIsMailTo))
            {
                if (isKnownScheme)
                {
#if NETFX
                    IBrowserCallbackServices ibcs = (Application.Current != null) ? Application.Current.BrowserCallbackServices : null;
                    if (ibcs != null)
                    {
                        launched = CanNavigateToUrlWithZoneCheck(originatingUri, destinationUri);
                        if (launched == LaunchResult.Launched)
                        {
                            // resetting launched to NotLaunched here; if the assert succeeds
                            // and ibcs.DelegateNavigation does not throw then we will set it to Launched.
                            launched = LaunchResult.NotLaunched;
                            // Browser app.
                            // We need to see if this is the right behavior when clicking on a link in
                            // a secondary window in a multi-window browser app
                            ibcs.DelegateNavigation(BindUriHelper.UriToString(destinationUri), targetName, GetHeaders(destinationUri));

                            launched = LaunchResult.Launched;
                        }
                    }
#endif
                }
                else if (fIsMailTo) // unnecessary if - but being paranoid.
                {
                    // Shell-Exec the browser to the mailto url.
                    // assumed safe - because we're only allowing this for mailto urls.
                    //

                    UnsafeNativeMethods.ShellExecute(new HandleRef(null, IntPtr.Zero),          /*hwnd*/
                                                     null,                                      /*operation*/
                                                     BindUriHelper.UriToString(destinationUri), /*file*/
                                                     null,                                      /*parameters*/
                                                     null,                                      /*directory*/
                                                     0);                                        /*nShowCmd*/
                    launched = LaunchResult.Launched;
                }
            }

            return(launched);
        }
Example #17
0
        private async Task launch()
        {
            Config.INSTANCE.User = ViewModel.User;
            Config.SaveConfigToFileAsync();
            KMCCC.Launcher.Version kver = ViewModel.SelectedVersion;
            if (kver == null)
            {
                await MainWindow.Current.ShowMessageAsync("启动失败", "版本未指定,请选择一个要启动的Minecraft版本");

                return;
            }
            if (CoreMCL.UserAuthenticator == null)
            {
                await MainWindow.Current.ShowMessageAsync("启动失败", "未指定用户,请前往账户设置选择要登入Minecraft的用户");

                return;
            }
            Option.versionId = kver.Id;
            Option.javaExt   = Config.INSTANCE.JavaExt;
            Option.javaArgs  = Config.INSTANCE.JavaArgs;
            if (Config.INSTANCE.MaxMemory > 0)
            {
                Option.javaArgs = string.Format("-Xmx{0}M {1}", Config.INSTANCE.MaxMemory, Option.javaArgs);
            }

            #region Check libraries and natives
            ViewModel.LaunchButtonContent = "正在检查核心文件...";

            List <MinecraftAssembly> missing = null;
            await Task.Run(() =>
            {
                missing = CoreMCL.CheckLibraries(kver);
                missing?.AddRange(CoreMCL.CheckNatives(kver));
            });

            if (missing?.Count > 0)
            {
                ViewModel.LaunchButtonContent = "正在下载核心文件...";
                DownloadDialog dialog = new DownloadDialog("正在下载运行Minecraft所需的文件...");
                missing.ForEach(lib =>
                {
                    if (Uri.TryCreate(lib.Url, UriKind.Absolute, out Uri uri))
                    {
                        DownloadItem item = new DownloadItem(lib.Name, lib.Path, uri);
                        dialog.DownloadQuene.Add(item);
                    }
                });
                dialog.StartDownload();
                if (await ShowDownloadDialog(dialog))
                {
                    return;
                }
            }
            #endregion

            // Check Assets
            ViewModel.LaunchButtonContent = "正在检查资源文件";
            if (!CheckAssetsIndex(kver))
            {
                ViewModel.LaunchButtonContent = "正在获取资源元数据";
                try
                {
                    await Task.Run(async() =>
                    {
                        using (HttpClient client = new HttpClient())
                        {
                            string json       = await client.GetStringAsync(kver.AssetsIndex.Url);
                            string path       = string.Format(@"{0}\assets\indexes\{1}.json", CoreMCL.Core.GameRootPath, kver.Assets);
                            FileInfo fileInfo = new FileInfo(path);
                            if (!fileInfo.Directory.Exists)
                            {
                                fileInfo.Directory.Create();
                            }
                            fileInfo.Create().Dispose();
                            File.WriteAllText(path, json);
                        }
                    });
                }
                catch (HttpRequestException ex)
                {
                    await MainWindow.Current.ShowMessageAsync("获取资源元数据失败", ex.Message + ex.StackTrace, MessageDialogStyle.Affirmative, DefaultDialogSettings);

                    return;
                }
                catch (IOException ex)
                {
                    await MainWindow.Current.ShowMessageAsync("获取资源元数据失败", ex.Message + ex.StackTrace, MessageDialogStyle.Affirmative, DefaultDialogSettings);

                    return;
                }
            }

            ViewModel.LaunchButtonContent = "正在检查资源文件...";
            (bool hasValidIndex, List <MinecraftAsset> missingAssets)assetsResult = (false, null);
            await Task.Run(() =>
            {
                assetsResult = CoreMCL.CheckAssets(kver);
            });

            if (!assetsResult.hasValidIndex)
            {
                await MainWindow.Current.ShowMessageAsync("获取资源元数据失败", "发生未知错误,无法获取有效的资源元数据,我们将为您继续启动游戏,但这可能会导致游戏中出现无翻译和无声音等问题");
            }
            else
            {
                if (assetsResult.missingAssets.Count > 0)
                {
                    DownloadDialog dialog = new DownloadDialog("正在下载资源文件...");
                    assetsResult.missingAssets.ForEach(ass =>
                    {
                        if (Uri.TryCreate(ass.GetDownloadUrl(), UriKind.Absolute, out Uri uri))
                        {
                            DownloadItem item = new DownloadItem("资源: " + ass.Hash, CoreMCL.Core.GameRootPath + "\\" + ass.GetPath(), uri);
                            dialog.DownloadQuene.Add(item);
                        }
                    });
                    if (await ShowDownloadDialog(dialog))
                    {
                        return;
                    }
                }
            }

            ViewModel.LaunchButtonContent = "正在启动...";
            LaunchResult result = CoreMCL.Launch(Option);
            if (!result.Success)
            {
                await MainWindow.Current.ShowMessageAsync("启动失败", result.ErrorMessage + "\r\n" + result.Exception);
            }
        }
Example #18
0
        /*
         * On OS X we do not launch command directly but we launch an AppleScript that creates (or reuses) a Terminal window
         * and then launches the command inside that window. The script returns the process of the command or an error.
         */
        private static LaunchResult LaunchInTerminalOSX(string directory, string runtimePath, string[] runtimeArgs, string program, string[] programArgs, Dictionary <string, string> environmentVariables)
        {
            // first fix the PATH so that 'runtimePath' can be found if installed with 'brew'
            Utilities.FixPathOnOSX();

            var activate_terminal = false;  // see bug 17519

            string thisModulePath = typeof(Terminal).GetTypeInfo().Assembly.ManifestModule.FullyQualifiedName;
            var    scriptPath     = Path.Combine(Path.GetDirectoryName(thisModulePath), "TerminalHelper.scpt");
            var    runtimeName    = Path.GetFileName(runtimePath);

            var arguments = string.Format(CultureInfo.InvariantCulture, "{0} -t {1} -w {2} -r {3} -rn {4} -p {5}",
                                          Quote(scriptPath), Quote(TERMINAL_TITLE), Quote(directory), Quote(runtimePath), Quote(runtimeName), Quote(program));

            if (runtimeArgs != null)
            {
                foreach (var r in runtimeArgs)
                {
                    arguments += string.Format(CultureInfo.InvariantCulture, " -ra {0}", Quote(r));
                }
            }
            if (programArgs != null)
            {
                foreach (var a in programArgs)
                {
                    arguments += string.Format(CultureInfo.InvariantCulture, " -pa {0}", Quote(a));
                }
            }
            if (environmentVariables != null)
            {
                foreach (var entry in environmentVariables)
                {
                    arguments += string.Format(CultureInfo.InvariantCulture, " -e \"{0}={1}\"", entry.Key, entry.Value);
                }
            }
            if (activate_terminal)
            {
                arguments += " -a";
            }

            var scriptProcess = new Process();

            scriptProcess.StartInfo.CreateNoWindow         = true;
            scriptProcess.StartInfo.UseShellExecute        = false;
            scriptProcess.StartInfo.FileName               = OSASCRIPT;
            scriptProcess.StartInfo.Arguments              = arguments;
            scriptProcess.StartInfo.RedirectStandardOutput = true;
            scriptProcess.StartInfo.RedirectStandardError  = true;

            var result = new LaunchResult();

            try
            {
                scriptProcess.Start();

                var stdout = scriptProcess.StandardOutput.ReadToEnd();
                var stderr = scriptProcess.StandardError.ReadToEnd();

                if (stdout.Length > 0)
                {
                    int pid;
                    var lines = Regex.Split(stdout, "\r\n|\r|\n");
                    if (lines.Length > 0)
                    {
                        if (Int32.TryParse(lines[0], out pid))
                        {
                            if (pid > 0)
                            {    // we got a real process ID
                                result.SetProcess(null, pid);
                            }
                        }
                        else
                        {
                            // could not parse, assume the reason is in stdout
                            result.SetError(stdout);
                        }
                    }
                }
                else
                {
                    // we got nothing on stdout; assume that stderr contains an error message
                    result.SetError(stderr);
                }
            }
            catch (Exception e)
            {
                result.SetError(e.Message);
            }

            return(result);
        }
        public override ValueSet OnRequest(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            string auth_type     = args.Request.Message["auth_type"].ToString();
            string auth_username = args.Request.Message["auth_username"].ToString();

            Logger.Info("User type: " + auth_type);
            Logger.Info("Username: "******"offline":
                Program.Launcher.UserAuthenticator = new OfflineAuthenticator(auth_username);
                break;
                //case "mojang":
            }
            if (Program.Launcher.UserAuthenticator == null)
            {
                Logger.Error("User authenticator no set or passed a wrong auth massage");
                return(null);
            }

            string json = args.Request.Message["launch_option"].ToString();

            Logger.Info("LaunchOption: " + json);
            Logger.Info("Deserializing launch option");

            LaunchOptionBase launchOption = null;
            ValueSet         ret          = new ValueSet();

            ret["result"] = false;

            try
            {
                launchOption = JsonConvert.DeserializeObject <LaunchOptionBase>(json);
            }
            catch (JsonException e)
            {
                ret["errorMessage"] = e.Message;
                ret["errorStack"]   = e.StackTrace;

                Logger.Error("ERROR: " + e.Message);
                Logger.Error("     " + e.StackTrace);
            }

            if (launchOption != null)
            {
                Logger.Info("Ready to launch");

                LaunchResult launchResult = Program.Launcher.Launch(launchOption);

                if (launchResult.Success)
                {
                    ret["result"] = true;

                    Logger.Info("Launch successfully");
                }
                else
                {
                    ret["errorMessage"] = launchResult.ErrorMessage;
                    ret["errorStack"]   = launchResult.Exception?.StackTrace;

                    Logger.Warn("Launch failed: " + launchResult.ErrorMessage);
                }
            }

            Logger.Info("Sending launch result to app");
            return(ret);
        }
Example #20
0
		/*
		 * On OS X we do not launch command directly but we launch an AppleScript that creates (or reuses) a Terminal window
		 * and then launches the command inside that window. The script returns the process of the command or an error.
		 */
		private static LaunchResult LaunchInTerminalOSX(string directory, string runtimePath, string[] runtimeArgs, string program, string[] programArgs, Dictionary<string, string> environmentVariables)
		{
			// first fix the PATH so that 'runtimePath' can be found if installed with 'brew'
			Utilities.FixPathOnOSX();

			var activate_terminal = false;	// see bug 17519

			var scriptPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TerminalHelper.scpt");
			var runtimeName = Path.GetFileName(runtimePath);

			var arguments = string.Format("{0} -t {1} -w {2} -r {3} -rn {4} -p {5}",
				Quote(scriptPath), Quote(TERMINAL_TITLE), Quote(directory), Quote(runtimePath), Quote(runtimeName), Quote(program));
			if (runtimeArgs != null) {
				foreach (var r in runtimeArgs) {
					arguments += string.Format(" -ra {0}", Quote(r));
				}
			}
			if (programArgs != null) {
				foreach (var a in programArgs) {
					arguments += string.Format(" -pa {0}", Quote(a));
				}
			}
			if (environmentVariables != null) {
				foreach (var entry in environmentVariables) {
					arguments += string.Format(" -e \"{0}={1}\"", entry.Key, entry.Value);
				}
			}
			if (activate_terminal) {
				arguments += " -a";
			}

			var scriptProcess = new Process();

			scriptProcess.StartInfo.CreateNoWindow = true;
			scriptProcess.StartInfo.UseShellExecute = false;
			scriptProcess.StartInfo.FileName = OSASCRIPT;
			scriptProcess.StartInfo.Arguments = arguments;
			scriptProcess.StartInfo.RedirectStandardOutput = true;
			scriptProcess.StartInfo.RedirectStandardError = true;

			var result = new LaunchResult();
			try {
				scriptProcess.Start();

				var stdout = scriptProcess.StandardOutput.ReadToEnd();
				var stderr = scriptProcess.StandardError.ReadToEnd();

				if (stdout.Length > 0) {
					int pid;
					var lines = Regex.Split(stdout, "\r\n|\r|\n");
					if (lines.Length > 0) {
						if (Int32.TryParse(lines[0], out pid)) {
							if (pid > 0) {    // we got a real process ID
								result.SetProcess(null, pid);
							}
						}
						else {
							// could not parse, assume the reason is in stdout
							result.SetError(stdout);
						}
					}
				}
				else {
					// we got nothing on stdout; assume that stderr contains an error message
					result.SetError(stderr);
				}
			}
			catch (Exception e) {
				result.SetError(e.Message);
			}

			return result;
		}
Example #21
0
		/*
		 * On Windows....
		 */
		private static LaunchResult LaunchInTerminalWindows(string workingDirectory, string runtimePath, string[] runtimeArguments, string program, string[] program_args, Dictionary<string, string> environmentVariables)
		{
			var title = workingDirectory + " - VS Code";

			var consoleProc = new Process();
			consoleProc.StartInfo.CreateNoWindow = true;
			consoleProc.StartInfo.UseShellExecute = true;
			consoleProc.StartInfo.WorkingDirectory = workingDirectory;
			consoleProc.StartInfo.FileName = CMD;
			consoleProc.StartInfo.Arguments = string.Format("/C title {0} && {1} {2} {3} {4} || pause",
				title, Terminal.Quote(runtimePath), ConcatArgs(runtimeArguments), Terminal.Quote(program), ConcatArgs(program_args));

			if (environmentVariables != null) {
				// we cannot set the env vars on the process StartInfo because we need to set StartInfo.UseShellExecute to true at the same time.
				// instead we set the env vars on OpenDebug itself because we know that OpenDebug lives as long as a debug session.
				foreach (var entry in environmentVariables) {
					System.Environment.SetEnvironmentVariable(entry.Key, entry.Value);
				}
			}

			var result = new LaunchResult();
			try {
				consoleProc.Start();
				result.SetConsoleProcess(consoleProc);
			}
			catch (Exception e) {
				result.SetError(e.Message);
			}

			return result;
		}
Example #22
0
        private void skinButton1_Click(object sender, EventArgs e)
        {
            //Regex reEamil = new Regex(@"^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$");
            //Regex rePwd = new Regex(@"[a-zA-Z0-9]{8,}");
            //bool ui = reEamil.IsMatch(this.skinTextBox1.Text);
            //MessageBox.Show(ui.ToString());
            //bool ui2 = rePwd.IsMatch(this.skinTextBox2.Text);
            //MessageBox.Show(ui2.ToString());
            var          ver    = (KMCCC.Launcher.Version)skinComboBox1.SelectedItem;
            LaunchResult result = null;

            if (this.Owner.Config.PositiveEdition)
            {
                result = App.launcherCore.Launch(new LaunchOptions
                {
                    Version       = ver,                                                                                            //Ver为Versions里你要启动的版本名字
                    MaxMemory     = 512,                                                                                            //最大内存,int类型
                    Authenticator = new YggdrasilLogin(this.skinTextBox1.Text.ToString(), this.skinTextBox2.Text.ToString(), true), // 正版启动,最后一个为是否twitch登录
                    Size          = new WindowSize {
                        Height = 768, Width = 1280
                    }                                                    //设置窗口大小,可以不要
                });
            }
            else
            {
                result = App.launcherCore.Launch(new LaunchOptions
                {
                    Version       = ver,                                              //Ver为Versions里你要启动的版本名字
                    MaxMemory     = 512,                                              //最大内存,int类型
                    Authenticator = new OfflineAuthenticator(this.skinTextBox1.Text), //离线启动,ZhaiSoul那儿为你要设置的游戏名
                    //Mode = LaunchMode.BmclMode, //启动模式,这个我会在后面解释有哪几种
                    Size = new WindowSize {
                        Height = 768, Width = 1280
                    }                                                    //设置窗口大小,可以不要
                });
            }

            if (!result.Success)
            {
                switch (result.ErrorType)
                {
                case ErrorType.NoJAVA:
                    MessageBox.Show("你系统的Java有异常,可能你非正常途径删除过Java,请尝试重新安装Java\n详细信息:" + result.ErrorMessage, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;

                case ErrorType.AuthenticationFailed:
                    MessageBox.Show(this, "正版验证失败!请检查你的账号密码", "账号错误\n详细信息:" + result.ErrorMessage, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;

                case ErrorType.UncompressingFailed:
                    MessageBox.Show(this, "可能的多开或文件损坏,请确认文件完整且不要多开\n如果你不是多开游戏的话,请检查libraries文件夹是否完整\n详细信息:" + result.ErrorMessage, "可能的多开或文件损坏", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;

                default:
                    MessageBox.Show(this,
                                    result.ErrorMessage + "\n" +
                                    (result.Exception == null ? string.Empty : result.Exception.StackTrace),
                                    "启动错误,请将此窗口截图向开发者寻求帮助");
                    break;
                }
            }
        }