Example #1
0
        /// <summary>
        /// Creates the update script on disk.
        /// </summary>
        /// <returns>ProcessStartInfo for the update script.</returns>
        public static ProcessStartInfo CreateUpdateScript()
        {
            try
            {
                var updateScriptPath   = GetUpdateScriptPath();
                var updateScriptSource = GetUpdateScriptSource();

                File.WriteAllText(updateScriptPath, updateScriptSource);

                if (PlatformHelpers.IsRunningOnUnix())
                {
                    var chmod = Process.Start("chmod", $"+x {updateScriptPath}");
                    chmod?.WaitForExit();
                }

                var updateShellProcess = new ProcessStartInfo
                {
                    FileName               = updateScriptPath,
                    UseShellExecute        = false,
                    RedirectStandardOutput = false,
                    CreateNoWindow         = true,
                    WindowStyle            = ProcessWindowStyle.Normal
                };

                return(updateShellProcess);
            }
            catch (IOException ioex)
            {
                Log.Warn("Failed to create update script (IOException): " + ioex.Message);

                return(null);
            }
        }
        public void ResponderWorkerScheduler_many_MinThreads_created_but_should_be_idle()
        {
            if (PlatformHelpers.IsLinux())
            {
                Assert.Inconclusive("This test is not designed to run on Linux");
            }

            var minThreads = Environment.ProcessorCount * 4;

            using (var scheduler = new ResponderWorkerScheduler(minThreads, minThreads))
            {
                Assert.AreEqual(minThreads, scheduler.CurrentWorkerThreadCount);

                var    timeout = TimeSpan.FromSeconds(5);
                var    started = DateTime.UtcNow;
                double oldTime;
                var    time = Process.GetCurrentProcess().TotalProcessorTime.TotalMilliseconds;
                do
                {
                    oldTime = time;
                    Thread.Sleep(1000);
                    time = Process.GetCurrentProcess().TotalProcessorTime.TotalMilliseconds;

                    if (DateTime.UtcNow - started > timeout)
                    {
                        Assert.Fail("Worker threads should be idle, when no worker is added");
                    }
                } while (time - oldTime > 100);

                Assert.Pass();
            }
        }
        /// <summary>
        /// Registers all the assemblies - looks for ExportService attributes
        /// </summary>
        private void RegisterAssemblyTypes()
        {
            var assemblies = PlatformHelpers.GetAssemblies();

            foreach (var asm in assemblies)
            {
                try
                {
                    var attributes = asm.GetCustomAttributes <ExportServiceAttribute>().ToList();

                    // Look for assembly level attributes.
                    foreach (var att in attributes.Where(a => !a.IsFallback))
                    {
                        Add(att.ContractType, att.ServiceType);
                    }

                    // Register fall back services if no other service is in place.
                    foreach (var att in attributes.Where(a => a.IsFallback))
                    {
                        if (!this.Exists(att.ContractType))
                        {
                            Add(att.ContractType, att.ServiceType);
                        }
                    }
                }
                catch
                {
                    // Skip.
                }
            }
        }
        public static void LoadTags(Models.Project project, ICacheFile cacheFile,
                                    string projectDirectory, Trie stringIdTrie)
        {
            var tagsDirectory = Path.Combine(projectDirectory, project.Properties.TagsFolder);

            if (!Directory.Exists(tagsDirectory))
            {
                Directory.CreateDirectory(tagsDirectory);
            }

            // Generate Tag List
            var tags = cacheFile.Tags
                       .Where(tag => tag != null && tag.Class != null && tag.MetaLocation != null)
                       .Select(tag =>
            {
                var className = CharConstant.ToString(tag.Class.Magic).Trim();
                var name      = cacheFile.FileNames.GetTagName(tag);
                if (string.IsNullOrWhiteSpace(name))
                {
                    name = tag.Index.ToString();
                }

                var directory        = tagsDirectory;
                var tagFileName      = $"{name}.{className}";
                var indexOfSeparator = tagFileName.LastIndexOf('\\');
                if (indexOfSeparator > -1)
                {
                    directory = Path
                                .Combine(tagsDirectory, tagFileName.Remove(indexOfSeparator))
                                .Replace('\\', Path.DirectorySeparatorChar);

                    tagFileName = tagFileName.Remove(0, indexOfSeparator + 1);
                }

                return(new TagEntry(tag, className, name, tagFileName, directory));
            });

            // Extract Tag Data
            foreach (var tag in tags)
            {
                // Create Directory
                if (!Directory.Exists(tag.Directory))
                {
                    Directory.CreateDirectory(tag.Directory);
                }

                using (var reader = XmlReader.Create($"data/plugins/halo3/{PlatformHelpers.EscapePath(tag.ClassName)}.xml"))
                {
                    var pluginVisitor = new JsonPluginVisitor(tags, stringIdTrie, cacheFile.MetaArea);
                    JsonPluginLoader.LoadPlugin(reader, pluginVisitor);

                    File.WriteAllText(tag.FullPath,
                                      JsonConvert.SerializeObject(pluginVisitor.TagData, Formatting.Indented, new JsonSerializerSettings
                    {
                        TypeNameHandling = TypeNameHandling.Auto
                    }));
                }
            }
        }
Example #5
0
        /// <summary>
        /// Gets the name of the embedded update script.
        /// </summary>
        private static string GetUpdateScriptPath()
        {
            if (PlatformHelpers.IsRunningOnUnix())
            {
                return(Path.Combine(Path.GetTempPath(), "launchpad_update.sh"));
            }

            return(Path.Combine(Path.GetTempPath(), "launchpad_update.bat"));
        }
 private void OnTriggerExit(Collider other)
 {
     if (other.gameObject.layer == Constants.PlayerLayer)
     {
         PlatformHelpers.WaitForPlatformExit = false;
         PlatformHelpers.IgnorePlayerPlatform(false, "OnTriggerExit");
         GameObject.Find("Player").GetComponent <Player>().SetParentPlatform();
     }
 }
Example #7
0
        /// <summary>
        /// Attempts to parse an entry from a raw input.
        /// The input is expected to be in [path]:[hash]:[size] format. Note that the file path is case sensitive,
        /// but the hash is not.
        /// </summary>
        /// <returns><c>true</c>, if the input was successfully parse, <c>false</c> otherwise.</returns>
        /// <param name="rawInput">Raw input.</param>
        /// <param name="inEntry">The resulting entry.</param>
        public static bool TryParse(string rawInput, out ManifestEntry inEntry)
        {
            // Clear out the entry for the new data
            inEntry = new ManifestEntry();

            if (string.IsNullOrEmpty(rawInput))
            {
                return(false);
            }

            var cleanInput = rawInput.RemoveLineSeparatorsAndNulls();

            // Split the string into its three components - file, hash and size
            var entryElements = cleanInput.Split(':');

            // If we have three elements (which we should always have), set them in the provided entry
            if (entryElements.Length != 3)
            {
                return(false);
            }

            // Sanitize the manifest path, converting \ to / on unix and / to \ on Windows.
            if (PlatformHelpers.IsRunningOnUnix())
            {
                inEntry.RelativePath = entryElements[0].Replace('\\', '/');
            }
            else
            {
                inEntry.RelativePath = entryElements[0].Replace('/', '\\');
            }

            // Hashes must be exactly 32 characters
            if (entryElements[1].Length != 32)
            {
                return(false);
            }

            // Set the hash to the second element
            inEntry.Hash = entryElements[1];

            // Attempt to parse the final element as a long-type byte count.
            if (!long.TryParse(entryElements[2], out var parsedSize))
            {
                // Oops. The parsing failed, so this entry is invalid.
                return(false);
            }

            // Negative sizes are not allowed
            if (parsedSize < 0)
            {
                return(false);
            }

            inEntry.Size = parsedSize;
            return(true);
        }
Example #8
0
 /// <summary>
 /// Gets the name of the embedded update script.
 /// </summary>
 private static string GetUpdateScriptResourceName()
 {
     if (PlatformHelpers.IsRunningOnUnix())
     {
         return("Launchpad.Launcher.Resources.launchpad_update.sh");
     }
     else
     {
         return("Launchpad.Launcher.Resources.launchpad_update.bat");
     }
 }
Example #9
0
 /// <summary>
 /// Gets the name of the embedded update script.
 /// </summary>
 private static string GetUpdateScriptPath()
 {
     if (PlatformHelpers.IsRunningOnUnix())
     {
         return($@"{Path.GetTempPath()}launchpad_update.sh");
     }
     else
     {
         return($@"{Path.GetTempPath()}launchpad_update.bat");
     }
 }
Example #10
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        private static void Main()
        {
            // Bind any unhandled exceptions in the main thread so that they are logged.
            AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;

            // Set correct working directory for compatibility with double-clicking
            Directory.SetCurrentDirectory(DirectoryHelpers.GetLocalLauncherDirectory());

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                Environment.SetEnvironmentVariable("GTK_EXE_PREFIX", Directory.GetCurrentDirectory());
                Environment.SetEnvironmentVariable("GTK_DATA_PREFIX", Directory.GetCurrentDirectory());
                Environment.SetEnvironmentVariable("GSETTINGS_SCHEMA_DIR", "share\\glib-2.0\\schemas\\");
            }
            Log.Info($"\n\n\n");
            Log.Info($"----------------------------------------------------------------------------");
            Log.Info($"Launching Youcanevent launcher {System.DateTime.Now}");
            Log.Info($"Launchpad v{LocalVersionService.GetLocalLauncherVersion()} starting...");

            var systemBitness  = Environment.Is64BitOperatingSystem ? "x64" : "x86";
            var processBitness = Environment.Is64BitProcess ? "64-bit" : "32-bit";

            Log.Info($"Current platform: {PlatformHelpers.GetCurrentPlatform()} ({systemBitness} platform, {processBitness} process)");

            Log.Info("Initializing UI...");

            // Bind any unhandled exceptions in the GTK UI so that they are logged.
            ExceptionManager.UnhandledException += OnGLibUnhandledException;

            // Run the GTK UI
            Gtk.Application.Init();

            var win = MainWindow.Create();

            win.Show();

            Timeout.Add
            (
                50,
                () =>
            {
                Task.Factory.StartNew
                (
                    () => win.InitializeAsync(),
                    CancellationToken.None,
                    TaskCreationOptions.DenyChildAttach,
                    TaskScheduler.FromCurrentSynchronizationContext()
                );
                return(false);
            }
            );

            Gtk.Application.Run();
        }
Example #11
0
        /// <summary>
        /// This method uses an internal object to gather the list of ViewModels based
        /// on the ExportViewModel attribute.
        /// </summary>
        /// <returns></returns>
        private void Initialize()
        {
            var assemblies = PlatformHelpers.GetAssemblies();

            foreach (var asm in assemblies)
            {
                foreach (var att in asm.GetCustomAttributes <ExportViewModelAttribute>())
                {
                    Add(att.Key, att.ViewModelType);
                }
            }
        }
Example #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Changelog"/> class.
        /// </summary>
        /// <param name="parentContainer">The parent GTK container where the changelog should be added.</param>
        public Changelog(Container parentContainer)
        {
            if (!PlatformHelpers.IsRunningOnUnix())
            {
                this.WindowsBrowser = new WindowsBrowser(parentContainer);
                this.WidgetHandle   = this.WindowsBrowser.WidgetHandle;

                this.WindowsBrowser.Browser.Navigating += OnWindowsBrowserNavigating;
            }
            else
            {
                this.UnixBrowser  = new WebView();
                this.WidgetHandle = this.UnixBrowser;
                this.UnixBrowser.NavigationRequested += OnUnixBrowserNavigating;

                parentContainer.Add(this.WidgetHandle);
            }
        }
Example #13
0
    IEnumerator TheBrekPlatform()
    {
        if (transform.GetComponent <TrafficLight>() == null)
        {
            transform.gameObject.AddComponent <TrafficLight>();
        }
        //Debug.Log("TheBrekPlatform " + transform.name);
        isBreakingProcess = true;
        transform.GetComponent <TrafficLight>().SetColor("y");
        yield return(new WaitForSeconds(timeBeforeBreak));

        PlatformHelpers.HidAndTrigger(true, transform.gameObject);
        yield return(new WaitForSeconds(createAfter));

        PlatformHelpers.HidAndTrigger(false, transform.gameObject);
        transform.GetComponent <TrafficLight>().SetColor("w");
        isBreakingProcess = false;
    }
Example #14
0
        private static async Task Main()
        {
            // Bind any unhandled exceptions in the main thread so that they are logged.
            AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;

            log4net.Config.XmlConfigurator.Configure();

            Log.Info("----------------");
            Log.Info($"Launchpad v{LocalVersionService.GetLocalLauncherVersion()} starting...");
            Log.Info($"Current platform: {PlatformHelpers.GetCurrentPlatform()} ({(Environment.Is64BitOperatingSystem ? "x64" : "x86")})");

            // Set correct working directory for compatibility with double-clicking
            Directory.SetCurrentDirectory(DirectoryHelpers.GetLocalLauncherDirectory());

            Log.Info("Initializing UI...");

            // Bind any unhandled exceptions in the GTK UI so that they are logged.
            ExceptionManager.UnhandledException += OnGLibUnhandledException;

            // Run the GTK UI
            Gtk.Application.Init();
            SynchronizationContext.SetSynchronizationContext(new GLibSynchronizationContext());

            var win = new MainWindow();

            win.Show();

            Timeout.Add
            (
                50,
                () =>
            {
                win.InitializeAsync();
                return(false);
            }
            );

            Gtk.Application.Run();
        }
Example #15
0
        /// <summary>
        /// Handles switching between different functionalities depending on what is visible on the button to the user, such as
        /// * Installing
        /// * Updating
        /// * Repairing
        /// * Launching
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">Empty arguments.</param>
        private void OnMainButtonClicked(object sender, EventArgs e)
        {
            // Drop out if the current platform isn't available on the server
            if (!this.Checks.IsPlatformAvailable(this.Configuration.SystemTarget))
            {
                this.StatusLabel.Text =
                    LocalizationCatalog.GetString("The server does not provide the game for the selected platform.");
                this.MainProgressBar.Text = string.Empty;

                Log.Info
                (
                    $"The server does not provide files for platform \"{PlatformHelpers.GetCurrentPlatform()}\". " +
                    "A .provides file must be present in the platforms' root directory."
                );

                SetLauncherMode(ELauncherMode.Inactive, false);

                return;
            }

            // else, run the relevant function
            switch (this.Mode)
            {
            case ELauncherMode.Repair:
            {
                // Repair the game asynchronously
                SetLauncherMode(ELauncherMode.Repair, true);
                this.Game.VerifyGame();

                break;
            }

            case ELauncherMode.Install:
            {
                // Install the game asynchronously
                SetLauncherMode(ELauncherMode.Install, true);
                this.Game.InstallGame();

                break;
            }

            case ELauncherMode.Update:
            {
                if (this.Checks.IsLauncherOutdated())
                {
                    // Update the launcher asynchronously
                    SetLauncherMode(ELauncherMode.Update, true);
                    this.Launcher.UpdateLauncher();
                }
                else
                {
                    // Update the game asynchronously
                    SetLauncherMode(ELauncherMode.Update, true);
                    this.Game.UpdateGame();
                }

                break;
            }

            case ELauncherMode.Launch:
            {
                this.StatusLabel.Text     = LocalizationCatalog.GetString("Idle");
                this.MainProgressBar.Text = string.Empty;

                SetLauncherMode(ELauncherMode.Launch, true);
                this.Game.LaunchGame();

                break;
            }

            default:
            {
                Log.Warn("The main button was pressed with an invalid active mode. No functionality has been defined for this mode.");
                break;
            }
            }
        }
Example #16
0
        /// <summary>
        /// Initializes the UI of the launcher, performing varying checks against the patching server.
        /// </summary>
        /// <returns>A task that must be awaited.</returns>
        public Task InitializeAsync()
        {
            if (this.IsInitialized)
            {
                return(Task.CompletedTask);
            }

            // First of all, check if we can connect to the patching service.
            if (!this.Checks.CanPatch())
            {
                var dialog = new MessageDialog
                             (
                    this,
                    DialogFlags.Modal,
                    MessageType.Warning,
                    ButtonsType.Ok,
                    LocalizationCatalog.GetString("Failed to connect to the patch server. Please check your settings.")
                             );

                dialog.Run();

                dialog.Destroy();
                this.StatusLabel.Text         = LocalizationCatalog.GetString("Could not connect to server.");
                this.MenuRepairItem.Sensitive = false;
            }
            else
            {
                LoadBanner();

                LoadChangelog();

                // If we can connect, proceed with the rest of our checks.
                if (ChecksHandler.IsInitialStartup())
                {
                    DisplayInitialStartupDialog();
                }

                // If the launcher does not need an update at this point, we can continue checks for the game
                if (!this.Checks.IsLauncherOutdated())
                {
                    if (!this.Checks.IsPlatformAvailable(this.Configuration.SystemTarget))
                    {
                        Log.Info
                        (
                            $"The server does not provide files for platform \"{PlatformHelpers.GetCurrentPlatform()}\". " +
                            "A .provides file must be present in the platforms' root directory."
                        );

                        SetLauncherMode(ELauncherMode.Inactive, false);
                    }
                    else
                    {
                        if (!this.Checks.IsGameInstalled())
                        {
                            // If the game is not installed, offer to install it
                            Log.Info("The game has not yet been installed.");
                            SetLauncherMode(ELauncherMode.Install, false);

                            // Since the game has not yet been installed, disallow manual repairs
                            this.MenuRepairItem.Sensitive = false;

                            // and reinstalls
                            this.MenuReinstallItem.Sensitive = false;
                        }
                        else
                        {
                            // If the game is installed (which it should be at this point), check if it needs to be updated
                            if (this.Checks.IsGameOutdated())
                            {
                                // If it does, offer to update it
                                Log.Info("The game is outdated.");
                                SetLauncherMode(ELauncherMode.Update, false);
                            }
                            else
                            {
                                // All checks passed, so we can offer to launch the game.
                                Log.Info("All checks passed. Game can be launched.");
                                SetLauncherMode(ELauncherMode.Launch, false);
                            }
                        }
                    }
                }
                else
                {
                    // The launcher was outdated.
                    Log.Info($"The launcher is outdated. \n\tLocal version: {this.LocalVersionService.GetLocalLauncherVersion()}");
                    SetLauncherMode(ELauncherMode.Update, false);
                }
            }

            this.IsInitialized = true;
            return(Task.CompletedTask);
        }
Example #17
0
 public void OnMoveDown(Vector3 dir)
 {
     //Debug.Log("OnMove Down");
     rb.AddForce(dir * speed);
     PlatformHelpers.IgnorePlayerPlatform(true, "OnMoveDown", true);
 }
Example #18
0
        /// <summary>
        /// Installs the dependencies.
        /// </summary>
        protected override void InstallDependencies()
        {
            try
            {
                var executable = Path.Combine(DirectoryHelpers.GetLocalGameDirectory(), "Engine/Extras/Redist/en-us/UE4PrereqSetup_x64.exe");
                Log.Info($"executable {executable}");
                if (!File.Exists(executable))
                {
                    throw new FileNotFoundException($"Game executable at path (\"{executable}\") not found.");
                }

                var executableDir = Path.GetDirectoryName(executable) ?? DirectoryHelpers.GetLocalLauncherDirectory();

                // Do not move the argument assignment inside the gameStartInfo initializer.
                // It causes a TargetInvocationException crash through black magic.
                var gameStartInfo = new ProcessStartInfo
                {
                    FileName         = executable,
                    Arguments        = string.Empty,
                    WorkingDirectory = executableDir
                };

                Log.Info($"Launching game. \n\tExecutable path: {gameStartInfo.FileName}");

                var gameProcess = new Process
                {
                    StartInfo           = gameStartInfo,
                    EnableRaisingEvents = true
                };

                gameProcess.Exited += (sender, args) =>
                {
                    if (gameProcess.ExitCode != 0)
                    {
                        Log.Info
                        (
                            $"The game exited with an exit code of {gameProcess.ExitCode}. " +
                            "There may have been issues during runtime, or the game may not have started at all."
                        );
                    }

                    // Manual disposing
                    gameProcess.Dispose();
                };

                // Make sure the game executable is flagged as such on Unix
                if (PlatformHelpers.IsRunningOnUnix())
                {
                    Process.Start("chmod", $"+x {gameStartInfo.FileName}");
                }

                gameProcess.Start();
            }
            catch (FileNotFoundException fex)
            {
                Log.Warn($"Dependencies installation failed (FileNotFoundException): {fex.Message}");
                Log.Warn("Check for the UE4 installation.");
            }
            catch (IOException ioex)
            {
                Log.Warn($"Dependencies installation failed (IOException): {ioex.Message}");
            }
        }
Example #19
0
 public static IAppQuery XamlParent(this IAppQuery query, string controlName)
 {
     return(query.Parent(PlatformHelpers.On(iOS: () => controlName.Replace(".", "_"), Android: () => GetAndroidName(controlName))));
 }
Example #20
0
        /// <summary>
        /// Launches the game.
        /// </summary>
        public void LaunchGame()
        {
            try
            {
                var executable = Path.Combine(DirectoryHelpers.GetLocalGameDirectory(), Configuration.ExecutablePath);
                if (!File.Exists(executable))
                {
                    throw new FileNotFoundException($"Game executable at path (\"{executable}\") not found.");
                }

                var executableDir = Path.GetDirectoryName(executable) ?? DirectoryHelpers.GetLocalLauncherDirectory();

                // Do not move the argument assignment inside the gameStartInfo initializer.
                // It causes a TargetInvocationException crash through black magic.
                var gameArguments = string.Join(" ", this.GameArgumentService.GetGameArguments());
                var gameStartInfo = new ProcessStartInfo
                {
                    FileName         = executable,
                    Arguments        = gameArguments,
                    WorkingDirectory = executableDir
                };

                Log.Info($"Launching game. \n\tExecutable path: {gameStartInfo.FileName}");

                var gameProcess = new Process
                {
                    StartInfo           = gameStartInfo,
                    EnableRaisingEvents = true
                };

                gameProcess.Exited += (sender, args) =>
                {
                    if (gameProcess.ExitCode != 0)
                    {
                        Log.Info
                        (
                            $"The game exited with an exit code of {gameProcess.ExitCode}. " +
                            "There may have been issues during runtime, or the game may not have started at all."
                        );
                    }

                    OnGameExited(gameProcess.ExitCode);

                    // Manual disposing
                    gameProcess.Dispose();
                };

                // Make sure the game executable is flagged as such on Unix
                if (PlatformHelpers.IsRunningOnUnix())
                {
                    Process.Start("chmod", $"+x {gameStartInfo.FileName}");
                }

                gameProcess.Start();
            }
            catch (FileNotFoundException fex)
            {
                Log.Warn($"Game launch failed (FileNotFoundException): {fex.Message}");
                Log.Warn("If the game executable is there, try overriding the executable name in the configuration file.");

                OnGameLaunchFailed();
            }
            catch (IOException ioex)
            {
                Log.Warn($"Game launch failed (IOException): {ioex.Message}");

                OnGameLaunchFailed();
            }
        }
Example #21
0
 public void OnMoveUp(Vector3 dir)
 {
     //Debug.Log("OnMove Up");
     PlatformHelpers.IgnorePlayerPlatform(true, "OnMoveUp");
     rb.AddForce(dir * speed * upMoveKoef);
 }