Example #1
0
        void ScanGames(object state)
        {
            var exe = state as string;

            ControlsHelper.Invoke(() =>
            {
                ScanProgressLevel0Label.Text = "...";
                ScanProgressLevel1Label.Text = "";
                ScanProgressPanel.Visibility = Visibility.Visible;
                ScanButton.IsEnabled         = false;
            });
            GameScanner           = new XInputMaskScanner();
            GameScanner.Progress += Scanner_Progress;
            string[] paths;
            string   name = null;

            if (string.IsNullOrEmpty(exe))
            {
                paths = SettingsManager.Options.GameScanLocations.ToArray();
            }
            else
            {
                // Set properties to scan single file.
                paths = new string[] { System.IO.Path.GetDirectoryName(exe) };
                name  = System.IO.Path.GetFileName(exe);
            }
            var games    = SettingsManager.UserGames.Items;
            var programs = SettingsManager.Programs.Items;

            GameScanner.ScanGames(paths, games, programs, name);
        }
Example #2
0
 private void AddLog(string format, params object[] args)
 {
     ControlsHelper.Invoke(new Action(() =>
     {
         var box = LogTextBox;
         lock (box)
         {
             var nl      = Environment.NewLine;
             var oldText = box.Text;
             var addText = string.Format(format, args);
             // Get size which will go over the maximum.
             var delSize = oldText.Length + addText.Length - box.MaxLength;
             // If must remove then...
             if (delSize > 0)
             {
                 // Try to remove with next new line.
                 var index = oldText.IndexOf(nl, delSize);
                 if (index > 0)
                 {
                     delSize = index + nl.Length;
                 }
                 box.Select(0, delSize);
                 box.SelectedText = string.Empty;
             }
             // Appedn new text.
             box.Select(box.TextLength + 1, 0);
             box.SelectedText = addText;
             if (box.Visible)
             {
                 box.SelectionStart = box.TextLength;
                 box.ScrollToCaret();
             }
         }
     }));
 }
Example #3
0
 static void OnEvent <T>(EventHandler <EventArgs <T> > handler, T data)
 {
     if (handler != null)
     {
         ControlsHelper.Invoke(handler, null, new EventArgs <T>(data));
     }
 }
Example #4
0
 private void QueueMonitorTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
 {
     ControlsHelper.Invoke(() =>
     {
         var t = Global.CloudClient.TasksTimer;
         if (t == null)
         {
             return;
         }
         var nextRunTime  = t.NextRunTime;
         TimeSpan remains = new TimeSpan();
         if (nextRunTime.Ticks > 0)
         {
             remains = nextRunTime.Subtract(DateTime.Now);
         }
         var nextRun = string.Format("Next Run {2}: {0:00}:{1:00}", remains.Minutes,
                                     remains.Seconds + (remains.Milliseconds / 1000m), Global.CloudClient.IsNetworkAvailable ? "ON" : "OFF");
         ControlsHelper.SetText(NextRunLabel, nextRun);
         var lrt     = t.LastActionDoneTime;
         var lastRun = string.Format("Last Done: {0:00}:{1:00}", lrt.Minutes, lrt.Seconds + (lrt.Milliseconds / 1000m));
         //ControlsHelper.SetText(LastDoneLabel, lastRun);
         var state = t.IsRunning ? "↑" : " ";
         ControlsHelper.SetText(RunStateLabel, state);
         //ControlsHelper.SetText(AddCountLabel, string.Format("Add: {0}", queueTimer.AddCount));
         //ControlsHelper.SetText(StartCountLabel, string.Format("Start: {0}", queueTimer.StartCount));
         //ControlsHelper.SetText(ThreadCountLabel, string.Format("Thread: {0}", queueTimer.ThreadCount));
         //ControlsHelper.SetText(ActionCountLabel, string.Format("Action: {0}", queueTimer.ActionCount));
         //ControlsHelper.SetText(ActionNoneCountLabel, string.Format("Action (null): {0}", queueTimer.ActionNoneCount));
     });
 }
Example #5
0
 void AddStatus(string format, params object[] args)
 {
     ControlsHelper.Invoke(() =>
     {
         StatusLabel.Text += string.Format(format, args);
         BodyPanel.VerticalScroll.Value = BodyPanel.VerticalScroll.Maximum;
     });
 }
Example #6
0
        public override void CheckTask()
        {
            var required = SettingsManager.UserGames.Items.Any(x => x.EmulationType == (int)EmulationType.Library);

            if (!required)
            {
                SetSeverity(IssueSeverity.None);
                return;
            }
            var architectures = new Dictionary <string, ProcessorArchitecture>();
            var architecture  = Assembly.GetExecutingAssembly().GetName().ProcessorArchitecture;
            var exes          = EngineHelper.GetFiles(".", "*.exe");

            // Exclude x360ce files.
            exes = exes.Where(x => !x.ToLower().Contains("x360ce")).ToArray();
            // If single executable was found then...
            if (exes.Length == 1 && CheckFile)
            {
                CheckFile = false;
                // Update current settings file.
                ControlsHelper.Invoke(() =>
                {
                    Global._MainWindow.UserProgramsPanel.ListPanel.ProcessExecutable(exes[0]);
                });
            }
            foreach (var exe in exes)
            {
                var pa = PEReader.GetProcessorArchitecture(exe);
                architectures.Add(exe, pa);
            }
            var fi = new FileInfo(Application.ExecutablePath);
            // Select all architectures of executables.
            var archs    = architectures.Select(x => x.Value).ToArray();
            var x86Count = archs.Count(x => x == ProcessorArchitecture.X86);
            var x64Count = archs.Count(x => x == ProcessorArchitecture.Amd64);

            // If executables are 32-bit, but this program is 64-bit then...
            if (x86Count > 0 && x64Count == 0 && architecture == ProcessorArchitecture.Amd64)
            {
                SetSeverity(
                    IssueSeverity.Moderate, 1,
                    "This folder contains 32-bit game. You should use 32-bit X360CE Application:\r\n" +
                    "http://www.x360ce.com/Files/x360ce.zip"
                    );
                return;
            }
            // If executables are 64-bit, but this program is 32-bit then...
            if (x64Count > 0 && x86Count == 0 && architecture == ProcessorArchitecture.X86)
            {
                SetSeverity(
                    IssueSeverity.Moderate, 2,
                    "This folder contains 64-bit game. You should use 64-bit X360CE Application:\r\n" +
                    "http://www.x360ce.com/Files/x360ce_x64.zip"
                    );
                return;
            }
            SetSeverity(IssueSeverity.None);
        }
        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var handler = PropertyChanged;

            if (handler != null)
            {
                ControlsHelper.Invoke(handler, this, new PropertyChangedEventArgs(propertyName));
            }
        }
Example #8
0
        // Used from derived classes to raise ProgressStarted.
        protected void OnMessageReceived(string text)
        {
            MessagesReceived++;
            var handler = MessageReceived;

            if (handler != null)
            {
                ControlsHelper.Invoke(handler, this, new ClassLibrary.EventArgs <string>(text));
            }
        }
Example #9
0
 /// <summary>
 /// This function will run on different thread than UI. Make sure to use Invoke for interface update.
 /// </summary>
 /// <param name="item"></param>
 /// <returns></returns>
 void queueTimer_DoWork(object sender, QueueTimerEventArgs e)
 {
     if (IsSuspended())
     {
         return;
     }
     CheckAll();
     // Update list will affect Warnings list, which is bound to MainDataGrid on UI,
     // therefore use Invoke to make sure that it runs on the same thread as UI.
     ControlsHelper.Invoke(() => {
         UpdateDisplayedList();
     });
 }
Example #10
0
        void TestDispose(object state)
        {
            var text = TestMemoryLeakAssemblies(
                typeof(App).Assembly,
                typeof(Engine.EngineHelper).Assembly
                );

            ControlsHelper.Invoke(() =>
            {
                ProgressBarPanel.UpdateProgress();
                LogTextBox.Text = text;
            });
        }
Example #11
0
        private void Queue_ListChanged(object sender, ListChangedEventArgs e)
        {
            var w = win;
            var q = Global.CloudClient.TasksTimer.Queue;

            if (win != null && q != null)
            {
                var item = q.FirstOrDefault(x => x.Action == CloudAction.SendMailMessage);
                ControlsHelper.Invoke(new Action(() =>
                {
                    win.ErrorReportPanel.StatusLabel.Content = item == null ? "Message Delivered" : "Sending...";
                }));
            }
        }
Example #12
0
        void ProcessResult(CloudMessage command, CloudMessage result)
        {
            // Execute on interface thread.
            if (ControlsHelper.InvokeRequired)
            {
                ControlsHelper.Invoke(new Action(() => ProcessResult(command, result)));
                return;
            }
            switch (command.Action)
            {
            case CloudAction.Select:
                if (result.UserGames != null)
                {
                    Global._MainWindow.UserProgramsPanel.ListPanel.ImportAndBindItems(result.UserGames);
                    if (!string.IsNullOrEmpty(result.ErrorMessage))
                    {
                        if (result.ErrorCode != 0)
                        {
                            Global.HMan.SetBodyError(result.ErrorMessage);
                        }
                        else
                        {
                            Global.HMan.SetBodyInfo(result.ErrorMessage);
                        }
                    }
                }
                if (result.UserDevices != null)
                {
                    Global._MainWindow.MainBodyPanel.DevicesPanel.ImportAndBindItems(result.UserDevices);
                    if (!string.IsNullOrEmpty(result.ErrorMessage))
                    {
                        if (result.ErrorCode != 0)
                        {
                            Global.HMan.SetBodyError(result.ErrorMessage);
                        }
                        else
                        {
                            Global.HMan.SetBodyInfo(result.ErrorMessage);
                        }
                    }
                }
                break;

            case CloudAction.CheckUpdates:
                Global._MainWindow.ProcessUpdateResults(result);
                break;
            }
        }
Example #13
0
        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var handler = PropertyChanged;

            if (handler != null)
            {
                if (ControlsHelper.MainTaskScheduler == null)
                {
                    handler(this, new PropertyChangedEventArgs(propertyName));
                }
                else
                {
                    ControlsHelper.Invoke(handler, this, new PropertyChangedEventArgs(propertyName));
                }
            }
        }
Example #14
0
        private void Options_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (ControlsHelper.InvokeRequired)
            {
                ControlsHelper.Invoke(() => Options_PropertyChanged(sender, e));
                return;
            }
            var o = SettingsManager.Options;

            // Update controls by specific property.
            switch (e.PropertyName)
            {
            case nameof(Options.ShowTestButton):
                ControlsHelper.SetVisible(TestButton, o.ShowTestButton);
                break;
            }
        }
Example #15
0
        protected void OnStatusChanged(string error, string filter = null, string packets = null, string state = null)
        {
            var handler = StatusChanged;

            if (handler == null)
            {
                return;
            }
            var e = new MonitorEventArgs()
            {
                Error   = error,
                Filter  = filter,
                Packets = packets,
                State   = state,
            };

            ControlsHelper.Invoke(handler, this, e);
        }
Example #16
0
        void RefreshAmazonVoices(Engine engine, BindingList <InstalledVoiceEx> list)
        {
            _CancelGetVoices           = false;
            StatusLabel.Text           = "";
            LogTabPage.Text            = "Log: Scanning voices. Please wait...";
            RefreshButton.Enabled      = false;
            MainTabControl.SelectedTab = LogTabPage;
            list.Clear();
            var voices = new List <InstalledVoiceEx>();
            var ts     = new System.Threading.ThreadStart(delegate()
            {
                voices = GetAmazonVoices(null, engine, null);
                // Uncehck selection by default.
                //foreach (var item in list)
                //	if (item.Enabled)
                //		item.Enabled = false;
                ControlsHelper.Invoke(() =>
                {
                    foreach (var voice in voices)
                    {
                        list.Add(voice);
                    }
                    if (voices.Count == 0)
                    {
                        StatusLabel.Text += "No new voices found.";
                    }
                    if (voices.Count > 0)
                    {
                        MainTabControl.SelectedTab = VoicesTabPage;
                    }
                    LogTabPage.Text       = "Log";
                    RefreshButton.Enabled = true;
                });
            });

            _Thread = new Thread(ts);
            _Thread.Start();
        }
Example #17
0
 private void _downloader_Progress(object sender, DownloaderEventArgs e)
 {
     lock (progressLock)
     {
         var progress = Math.Round(100m * e.BytesReceived / e.TotalBytesToReceive, 1);
         if (oldProgress != progress || _downloader.Params.ResponseData != null)
         {
             oldProgress = progress;
             ControlsHelper.Invoke(() =>
             {
                 var mb = Math.Round(e.BytesReceived / 1024m / 1024m, 1);
                 CurrentLogItem.Message = string.Format("Download... {0}% - {1} MB", progress, mb);
                 if (_downloader.Params.ResponseData != null)
                 {
                     CurrentLogItem.Message = "Saving File...";
                     var zipFileName        = processFileName + ".zip";
                     System.IO.File.WriteAllBytes(zipFileName, _downloader.Params.ResponseData);
                     CurrentLogItem.Message += " Done";
                     Step3AExtractFiles(zipFileName);
                 }
             });
         }
     }
 }
Example #18
0
        public string TestMemoryLeakAssemblies(params System.Reflection.Assembly[] assemblies)
        {
            var log           = new List <string>();
            var disposedCount = 0;
            var aliveCount    = 0;
            var errorsCount   = 0;
            var e             = new ProgressEventArgs();

            for (int a = 0; a < assemblies.Length; a++)
            {
                var assembly = assemblies[a];
                e.TopCount   = assemblies.Length;
                e.TopIndex   = a;
                e.TopData    = assemblies;
                e.TopMessage = $"Assembly: {assembly.FullName}";
                ControlsHelper.Invoke(() => ProgressBarPanel.UpdateProgress(e));
                var types = assembly.GetTypes();
                for (int t = 0; t < types.Length; t++)
                {
                    var type = types[t];
                    e.SubCount   = types.Length;
                    e.SubIndex   = t;
                    e.SubData    = types;
                    e.SubMessage = $"Type: {type.FullName}";
                    ControlsHelper.Invoke(() => ProgressBarPanel.UpdateProgress(e));
                    if (type.IsInterface)
                    {
                        continue;
                    }
                    if (!type.FullName.Contains(".Controls.") && !type.FullName.Contains(".Forms."))
                    {
                        continue;
                    }
                    ControlsHelper.Invoke(() =>
                    {
                        try
                        {
                            var o  = Activator.CreateInstance(type);
                            var wr = new WeakReference(o);
                            // Verify that the WeakReference actually points to the intended object instance.
                            if (wr.Target.Equals(o))
                            {
                                // Dispose object.
                                o = null;
                                for (int i = 0; i < 4; i++)
                                {
                                    GC.Collect();
                                    GC.WaitForPendingFinalizers();
                                    GC.WaitForFullGCComplete();
                                    GC.Collect();
                                }
                                // Note: Debug mode turns off a lot of optimizations, because compiler is trying to be helpful.
                                // Debug build can keep values rooted even if you set them to null i.e. wr.IsAlive will always return TRUE.
                                if (wr.IsAlive)
                                {
                                    log.Add($"Is Alive: {type.FullName}");
                                    aliveCount++;
                                }
                                else
                                {
                                    log.Add($"Disposed: {type.FullName}");
                                    disposedCount++;
                                }
                            }
                            else
                            {
                                log.Add($"Error: NOT same as {type.FullName}");
                                errorsCount++;
                            }
                        }
                        catch (Exception ex)
                        {
                            log.Add($"Error: {type.FullName} {ex.Message}");
                            errorsCount++;
                        }
                    });
                }
            }
            var results = $"Disposed = {disposedCount}, Alive = {aliveCount}, Errors = {errorsCount}\r\n" + string.Join("\r\n", log);

            return(results);
        }
Example #19
0
        private void Scanner_Progress(object sender, XInputMaskScannerEventArgs e)
        {
            if (ControlsHelper.InvokeRequired)
            {
                ControlsHelper.Invoke(() =>
                                      Scanner_Progress(sender, e)
                                      );
                return;
            }
            var scanner = (XInputMaskScanner)sender;
            var label   = e.Level == 0
                                ? ScanProgressLevel0Label
                                : ScanProgressLevel1Label;

            switch (e.State)
            {
            case XInputMaskScannerState.Started:
                label.Text = "Scanning...";
                break;

            case XInputMaskScannerState.GameFound:
                lock (GameAddLock)
                {
                    // Get game to add.
                    var game        = e.Game;
                    var dirFullName = e.GameFileInfo.Directory.FullName.ToLower();
                    // Get existing games in the same folder.
                    var oldGames    = SettingsManager.UserGames.Items.Where(x => x.FullPath.ToLower().StartsWith(dirFullName)).ToList();
                    var oldGame     = oldGames.FirstOrDefault(x => x.IsEnabled && x.DateCreated < ScanStarted);
                    var enabledGame = oldGames.FirstOrDefault(x => x.IsEnabled);
                    // If this is 32-bit windows but game is 64-bit then...
                    if (!Environment.Is64BitOperatingSystem && game.Is64Bit)
                    {
                        // Disable game.
                        game.IsEnabled = false;
                    }
                    // If list contains enabled old game for other platform before scan started then...
                    else if (oldGame != null)
                    {
                        // Enable if platform is the same, disable otherwise.
                        game.IsEnabled = game.ProcessorArchitecture == oldGame.ProcessorArchitecture;
                    }
                    // At this point, oldGames list contains only new games added during the scan.
                    // If this is 64-bit game then...
                    else if (game.Is64Bit)
                    {
                        foreach (var g in oldGames)
                        {
                            // Disable non 64-bit games.
                            if (g.IsEnabled && !g.Is64Bit)
                            {
                                g.IsEnabled = false;
                            }
                        }
                    }
                    // If contains enabled game then...
                    else if (enabledGame != null)
                    {
                        // Enable if platform is the same, disable otherwise.
                        game.IsEnabled = game.ProcessorArchitecture == enabledGame.ProcessorArchitecture;
                    }
                    SettingsManager.UserGames.Add(game);
                }
                break;

            case XInputMaskScannerState.GameUpdated:
                e.Game.FullPath = e.GameFileInfo.FullName;
                if (string.IsNullOrEmpty(e.Game.FileProductName) && !string.IsNullOrEmpty(e.Program.FileProductName))
                {
                    e.Game.FileProductName = e.Program.FileProductName;
                }
                break;

            case XInputMaskScannerState.DirectoryUpdate:
            case XInputMaskScannerState.FileUpdate:
                var sb = new StringBuilder();
                sb.AppendLine(e.Message);
                if (e.State == XInputMaskScannerState.DirectoryUpdate && e.Directories != null)
                {
                    sb.AppendFormat("Current Folder: {0}", e.Directories[(int)e.DirectoryIndex].FullName);
                }
                if (e.State == XInputMaskScannerState.FileUpdate && e.Files != null)
                {
                    var file = e.Files[(int)e.FileIndex];
                    var size = file.Length / 1024 / 1024;
                    sb.AppendFormat("Current File ({0:0.0} MB): {1} ", size, file.FullName);
                }
                if (e.Level == 0)
                {
                    sb.AppendLine();
                    sb.AppendFormat("Skipped = {0}, Added = {1}, Updated = {2}", e.Skipped, e.Added, e.Updated);
                }
                sb.AppendLine();
                ControlsHelper.Invoke(() =>
                {
                    label.Text = sb.ToString();
                });
                break;

            case XInputMaskScannerState.Completed:
                ControlsHelper.Invoke(() =>
                {
                    ScanButton.IsEnabled         = true;
                    ScanProgressPanel.Visibility = Visibility.Collapsed;
                });
                SettingsManager.Save();
                break;

            default:
                break;
            }
        }
Example #20
0
 private async Task CheckAndClean(bool clean)
 {
     LogTextBox.Clear();
     MainTabControl.SelectedTab = LogsTabPage;
     var cancellationToken = new CancellationToken(false);
     var so     = ControlsHelper.MainTaskScheduler;
     var unused = Task.Factory.StartNew(() =>
     {
         AddLogLine("Enumerating Devices...");
         var devices = DeviceDetector.GetDevices();
         var offline = devices.Where(x => !x.IsPresent && x.IsRemovable && !x.Description.Contains("RAS Async Adapter")).ToArray();
         var problem = devices.Where(x => x.Status.HasFlag(DeviceNodeStatus.DN_HAS_PROBLEM)).Except(offline).ToArray();
         var unknown = devices.Where(x => x.Description.Contains("Unknown")).Except(offline).Except(problem).ToArray();
         var list    = new List <string>();
         if (offline.Length > 0)
         {
             list.Add(string.Format("{0} offline devices.", offline.Length));
         }
         if (problem.Length > 0)
         {
             list.Add(string.Format("{0} problem devices.", problem.Length));
         }
         if (unknown.Length > 0)
         {
             list.Add(string.Format("{0} unknown devices.", unknown.Length));
         }
         var message = string.Join("\r\n", list);
         if (list.Count == 0)
         {
             AddLogLine("No offline, problem or unknown devices found.");
         }
         else if (clean)
         {
             foreach (var item in list)
             {
                 AddLogLine(item);
             }
             var result = DialogResult.No;
             ControlsHelper.Invoke(new Action(() =>
             {
                 var form = new JocysCom.ClassLibrary.Controls.MessageBoxForm
                 {
                     StartPosition = FormStartPosition.CenterParent
                 };
                 ControlsHelper.CheckTopMost(form);
                 result = form.ShowForm(
                     "Do you want to remove offline, problem or unknown devices?\r\n\r\n" + message,
                     "Do you want to remove devices?",
                     MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                 form.Dispose();
             }));
             if (result != DialogResult.Yes)
             {
                 return;
             }
             var devList = new List <DeviceInfo>();
             devList.AddRange(offline);
             devList.AddRange(problem);
             devList.AddRange(unknown);
             for (var i = 0; i < devList.Count; i++)
             {
                 var item = devList[i];
                 AddLogLine("Removing Device: {0}/{1} - {2}", i + 1, list.Count, item.Description);
                 try
                 {
                     var exception = DeviceDetector.RemoveDevice(item.DeviceId);
                     if (exception != null)
                     {
                         AddLogLine(exception.Message);
                     }
                     //System.Windows.Forms.Application.DoEvents();
                 }
                 catch (Exception ex)
                 {
                     AddLogLine(ex.Message);
                 }
             }
         }
         AddLogLine("Done");
     }, CancellationToken.None, TaskCreationOptions.LongRunning, so).ConfigureAwait(true);
 }