DebugHelper class.
Inheritance: MonoBehaviour
Exemple #1
0
 public PersistenceDeleteTest()
 {
     int databaseRead = (int)EntityTypeEnum.LOCAL_DATABASE;
     int databaseWrite = (int)EntityTypeEnum.LOCAL_DATABASE;
     this.persistence = new PersistenceEBS(databaseRead, databaseWrite);
     this.debug = new DebugHelper();
 }
 public VisualEnvironmentCompiler(InvokeDegegate beginInvoke, 
     SetFlagDelegate setCompilingButtonsEnabled, SetFlagDelegate setCompilingDebugEnabled, SetTextDelegate setStateText, 
     SetTextDelegate addTextToCompilerMessages, ToolStripMenuItem pluginsMenuItem, 
     ToolStrip pluginsToolStrip, ExecuteSourceLocationActionDelegate ExecuteSLAction, 
     ExecuteVisualEnvironmentCompilerActionDelegate ExecuteVECAction,
     PascalABCCompiler.Errors.ErrorsStrategyManager ErrorsManager, RunManager RunnerManager, DebugHelper DebugHelper,UserOptions UserOptions,System.Collections.Hashtable StandartDirectories,
     Dictionary<string, CodeFileDocumentControl> OpenDocuments, IWorkbench workbench)
 {
     this.StandartDirectories = StandartDirectories;
     this.ErrorsManager = ErrorsManager;
     this.ChangeVisualEnvironmentState += new ChangeVisualEnvironmentStateDelegate(onChangeVisualEnvironmentState);
     SetCompilingButtonsEnabled = setCompilingButtonsEnabled;
     SetDebugButtonsEnabled = setCompilingDebugEnabled;
     SetStateText = setStateText;
     AddTextToCompilerMessages = addTextToCompilerMessages;
     this.beginInvoke = beginInvoke;
     this.ExecuteSLAction=ExecuteSLAction;
     this.ExecuteVECAction = ExecuteVECAction;
     PluginsMenuItem = pluginsMenuItem;
     PluginsToolStrip = pluginsToolStrip;
     PluginsController = new VisualPascalABCPlugins.PluginsController(this, PluginsMenuItem, PluginsToolStrip, workbench);
     this.RunnerManager = RunnerManager;
     this.DebugHelper = DebugHelper;
     DebugHelper.Starting += new DebugHelper.DebugHelperActionDelegate(DebugHelper_Starting);
     DebugHelper.Exited += new DebugHelper.DebugHelperActionDelegate(DebugHelper_Exited);
     RunnerManager.Starting += new RunManager.RunnerManagerActionDelegate(RunnerManager_Starting);
     RunnerManager.Exited += new RunManager.RunnerManagerActionDelegate(RunnerManager_Exited);
     this.CodeCompletionParserController = WorkbenchServiceFactory.CodeCompletionParserController;
     this.CodeCompletionParserController.visualEnvironmentCompiler = this;
     this.UserOptions = UserOptions;
     this.OpenDocuments = OpenDocuments;
 }
Exemple #3
0
        //IUserOptions UserOptions;
        //IVisualEnvironmentCompiler VisualEnvironmentCompiler;

        public WorkbenchRunService()
        {
            //UserOptions = WorkbenchServiceFactory.Workbench.UserOptions;
            Workbench = WorkbenchServiceFactory.Workbench;
            //VisualEnvironmentCompiler = WorkbenchServiceFactory.Workbench.VisualEnvironmentCompiler;
            RunnerManager = new RunManager(ReadStringRequest);
            RunnerManager.Exited += new RunManager.RunnerManagerActionDelegate(RunnerManager_Exited);
            RunnerManager.Starting += new RunManager.RunnerManagerActionDelegate(RunnerManager_Started);
            RunnerManager.OutputStringReceived += new RunManager.TextRecivedDelegate(RunnerManager_OutputStringReceived);
            RunnerManager.RunnerManagerUnhanledRuntimeException += new RunManager.RunnerManagerUnhanledRuntimeExceptionDelegate(RunnerManager_RunnerManagerUnhanledRuntimeException);
            DesignerService = WorkbenchServiceFactory.DesignerService;
            this.DebuggerManager = WorkbenchServiceFactory.DebuggerManager;
            BuildService = WorkbenchServiceFactory.BuildService;
            DebuggerOperationsService = WorkbenchServiceFactory.DebuggerOperationsService;
            DocumentService = WorkbenchServiceFactory.DocumentService;
        }
Exemple #4
0
        public static int Run(string[] args)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            var app = new CommandLineApplication();

            app.Name        = "dotnet new";
            app.FullName    = ".NET Initializer";
            app.Description = "Initializes empty project for .NET Platform";
            app.HelpOption("-h|--help");

            var csharp = new { Name      = "C#", Alias = new[] { "c#", "cs", "csharp" }, TemplatePrefix = "CSharp",
                               Templates = new[]
                               {
                                   new { Name = "Console", isMsBuild = true },
                                   new { Name = "Web", isMsBuild = true },
                                   new { Name = "Lib", isMsBuild = true },
                                   new { Name = "Mstest", isMsBuild = true },
                                   new { Name = "Xunittest", isMsBuild = true }
                               } };

            var fsharp = new { Name      = "F#", Alias = new[] { "f#", "fs", "fsharp" }, TemplatePrefix = "FSharp",
                               Templates = new[]
                               {
                                   new { Name = "Console", isMsBuild = true },
                                   new { Name = "Web", isMsBuild = true },
                                   new { Name = "Lib", isMsBuild = true },
                                   new { Name = "Mstest", isMsBuild = true },
                                   new { Name = "Xunittest", isMsBuild = true }
                               } };

            var languages = new[] { csharp, fsharp };

            string langValuesString = string.Join(", ", languages.Select(l => l.Name));
            var    typeValues       =
                from l in languages
                let values = string.Join(", ", l.Templates.Select(t => t.Name))
                             select $"Valid values for {l.Name}: {values}.";
            string typeValuesString = string.Join(" ", typeValues);

            var lang = app.Option("-l|--lang <LANGUAGE>", $"Language of project    Valid values: {langValuesString}.", CommandOptionType.SingleValue);
            var type = app.Option("-t|--type <TYPE>", $"Type of project        {typeValuesString}", CommandOptionType.SingleValue);

            var dotnetNew = new NewCommand();

            app.OnExecute(() =>
            {
                string languageValue = lang.Value() ?? csharp.Name;

                var language = languages
                               .FirstOrDefault(l => l.Alias.Contains(languageValue, StringComparer.OrdinalIgnoreCase));

                if (language == null)
                {
                    Reporter.Error.WriteLine($"Unrecognized language: {languageValue}".Red());
                    return(-1);
                }

                string typeValue = type.Value() ?? language.Templates.First().Name;

                var template = language.Templates.FirstOrDefault(t => StringComparer.OrdinalIgnoreCase.Equals(typeValue, t.Name));
                if (template == null)
                {
                    Reporter.Error.WriteLine($"Unrecognized type: {typeValue}".Red());
                    Reporter.Error.WriteLine($"Available types for {language.Name} :".Red());
                    foreach (var t in language.Templates)
                    {
                        Reporter.Error.WriteLine($"- {t}".Red());
                    }
                    return(-1);
                }

                string templateDir = $"{language.TemplatePrefix}_{template.Name}";

                return(dotnetNew.CreateEmptyProject(language.Name, templateDir, template.isMsBuild));
            });

            try
            {
                return(app.Execute(args));
            }
            catch (Exception ex)
            {
#if DEBUG
                Reporter.Error.WriteLine(ex.ToString());
#else
                Reporter.Error.WriteLine(ex.Message);
#endif
                return(1);
            }
        }
    private IEnumerator CheckForBomb()
    {
        yield return(new WaitUntil(() => SceneManager.Instance.GameplayState.Bombs != null && SceneManager.Instance.GameplayState.Bombs.Count > 0));

        yield return(null);

        var bombs = SceneManager.Instance.GameplayState.Bombs;

        try
        {
            ModuleCameras = Instantiate(moduleCamerasPrefab);
        }
        catch (Exception ex)
        {
            DebugHelper.LogException(ex, "Failed to instantiate the module camera system due to an exception:");
            ModuleCameras = null;
        }

        if (GameRoom.GameRoomTypes.Where((t, i) => t() != null && GameRoom.CreateRooms[i](FindObjectsOfType(t()), out GameRoom.Instance)).Any())
        {
            GameRoom.Instance.InitializeBombs(bombs);
        }
        ModuleCameras?.ChangeBomb(Bombs[0]);

        try
        {
            GameRoom.Instance.InitializeBombNames();
        }
        catch (Exception ex)
        {
            DebugHelper.LogException(ex, "An exception has occurred while setting the bomb names");
        }
        StartCoroutine(GameRoom.Instance.ReportBombStatus());
        StartCoroutine(GameRoom.Instance.InterruptLights());

        try
        {
            if (GameRoom.Instance.HoldBomb)
            {
                StartCoroutine(BombCommands.Hold(Bombs[0]));
            }
        }
        catch (Exception ex)
        {
            DebugHelper.LogException(ex, "An exception has occurred attempting to hold the bomb.");
        }

        NotesDictionary.Clear();
        CommandQueue.Clear();
        ModuleCameras?.SetNotes();

        if (EnableDisableInput())
        {
            TwitchModule.SolveUnsupportedModules(true);
        }

        // Set up some stuff for the !unclaimed command.
        GameCommands.unclaimedModules     = Modules.Where(h => h.CanBeClaimed).Shuffle().ToList();
        GameCommands.unclaimedModuleIndex = 0;

        while (OtherModes.Unexplodable)
        {
            foreach (var bomb in Bombs)
            {
                if (bomb.Bomb.GetTimer() != null && bomb.Bomb.GetTimer().GetRate() > 0)
                {
                    bomb.Bomb.GetTimer().SetRateModifier(-bomb.Bomb.GetTimer().GetRate());
                }
            }
            yield return(null);
        }

        TwitchPlaysService.Instance.UpdateUiHue();
    }
    private void OnDisable()
    {
        GameRoom.ShowCamera();
        BombActive = false;
        EnableDisableInput();
        bool claimsEnabled = TwitchModule.ClaimsEnabled;

        TwitchModule.ClearUnsupportedModules();
        if (!claimsEnabled)
        {
            TwitchModule.ClaimsEnabled = true;
        }
        StopAllCoroutines();
        GoodPlayers.Clear();
        EvilPlayers.Clear();
        VSSetFlag    = false;
        QueueEnabled = false;
        Leaderboard.Instance.BombsAttempted++;
        // ReSharper disable once DelegateSubtraction
        ParentService.GetComponent <KMGameInfo>().OnLightsChange -= OnLightsChange;
        ParentService.AddStateCoroutine(ParentService.AnimateHeaderVisibility(false));

        LogUploader.Instance.GetBombUrl();
        ParentService.AddStateCoroutine(DelayBombResult());
        if (!claimsEnabled)
        {
            ParentService.AddStateCoroutine(SendDelayedMessage(1.1f, "Claims have been enabled."));
        }

        if (ModuleCameras != null)
        {
            ModuleCameras.StartCoroutine(ModuleCameras.DisableCameras());
        }

        // Award users who maintained modules.
        var methods       = Modules.SelectMany(module => module.ScoreMethods).Where(method => method.Players.Count != 0);
        var awardedPoints = new Dictionary <string, int>();

        foreach (var player in methods.SelectMany(method => method.Players).Distinct())
        {
            int points = (methods.Sum(method => method.CalculateScore(player)) * OtherModes.ScoreMultiplier).RoundToInt();
            if (points != 0)
            {
                awardedPoints[player] = points;
                Leaderboard.Instance.AddScore(player, points);
            }
        }

        if (awardedPoints.Count > 0)
        {
            IRCConnection.SendMessage($"These players have been awarded points for managing a needy: {awardedPoints.Select(pair => $"{pair.Key} ({pair.Value})").Join(", ")}");
        }

        GameCommands.unclaimedModules = null;
        DestroyComponentHandles();

        MusicPlayer.StopAllMusic();

        GameRoom.Instance?.OnDisable();

        try
        {
            string path = Path.Combine(Application.persistentDataPath, "TwitchPlaysLastClaimed.json");
            File.WriteAllText(path, SettingsConverter.Serialize(LastClaimedModule));
        }
        catch (Exception ex)
        {
            DebugHelper.LogException(ex, "Couldn't write TwitchPlaysLastClaimed.json:");
        }
    }
        public override IPluginEditableViewSettings CloneForEdit()
        {
            DebugHelper.AssertUIThread();

            return(new BodyIndexPlugin3DViewSettings());
        }
 /// <summary>
 /// Adds the specified file to the internal list for tracking.
 /// </summary>
 /// <param name="descriptor">The descriptor to add.</param>
 protected void AddFile(StoredFileDescriptor descriptor)
 {
     DebugHelper.Assert(descriptor != null);
     this.data.Add(descriptor);
 }
Exemple #9
0
        private bool DoAfterCaptureJobs()
        {
            if (tempImage == null)
            {
                return(true);
            }

            if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.AddImageEffects))
            {
                tempImage = TaskHelpers.AddImageEffects(tempImage, Info.TaskSettings.ImageSettingsReference);

                if (tempImage == null)
                {
                    DebugHelper.WriteLine("Error: Applying image effects resulted empty image.");
                    return(false);
                }
            }

            if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.AnnotateImage))
            {
                tempImage = TaskHelpers.AnnotateImage(tempImage, Info.FileName, Info.TaskSettings, true);

                if (tempImage == null)
                {
                    return(false);
                }
            }

            if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.CopyImageToClipboard))
            {
                ClipboardHelpers.CopyImage(tempImage);
                DebugHelper.WriteLine("Image copied to clipboard.");
            }

            if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.SendImageToPrinter))
            {
                TaskHelpers.PrintImage(tempImage);
            }

            if (Info.TaskSettings.AfterCaptureJob.HasFlagAny(AfterCaptureTasks.SaveImageToFile, AfterCaptureTasks.SaveImageToFileWithDialog, AfterCaptureTasks.DoOCR,
                                                             AfterCaptureTasks.UploadImageToHost))
            {
                using (tempImage)
                {
                    ImageData imageData = TaskHelpers.PrepareImage(tempImage, Info.TaskSettings);
                    Data          = imageData.ImageStream;
                    Info.FileName = Path.ChangeExtension(Info.FileName, imageData.ImageFormat.GetDescription());

                    if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.SaveImageToFile))
                    {
                        string filePath = TaskHelpers.CheckFilePath(Info.TaskSettings.CaptureFolder, Info.FileName, Info.TaskSettings);

                        if (!string.IsNullOrEmpty(filePath))
                        {
                            Info.FilePath = filePath;
                            imageData.Write(Info.FilePath);
                            DebugHelper.WriteLine("Image saved to file: " + Info.FilePath);
                        }
                    }

                    if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.SaveImageToFileWithDialog))
                    {
                        using (SaveFileDialog sfd = new SaveFileDialog())
                        {
                            bool imageSaved;

                            do
                            {
                                if (string.IsNullOrEmpty(lastSaveAsFolder) || !Directory.Exists(lastSaveAsFolder))
                                {
                                    lastSaveAsFolder = Info.TaskSettings.CaptureFolder;
                                }

                                sfd.InitialDirectory = lastSaveAsFolder;
                                sfd.FileName         = Info.FileName;
                                sfd.DefaultExt       = Path.GetExtension(Info.FileName).Substring(1);
                                sfd.Filter           = string.Format("*{0}|*{0}|All files (*.*)|*.*", Path.GetExtension(Info.FileName));
                                sfd.Title            = Resources.UploadTask_DoAfterCaptureJobs_Choose_a_folder_to_save + " " + Path.GetFileName(Info.FileName);

                                if (sfd.ShowDialog() == DialogResult.OK && !string.IsNullOrEmpty(sfd.FileName))
                                {
                                    Info.FilePath    = sfd.FileName;
                                    lastSaveAsFolder = Path.GetDirectoryName(Info.FilePath);
                                    imageSaved       = imageData.Write(Info.FilePath);

                                    if (imageSaved)
                                    {
                                        DebugHelper.WriteLine("Image saved to file with dialog: " + Info.FilePath);
                                    }
                                }
                                else
                                {
                                    break;
                                }
                            } while (!imageSaved);
                        }
                    }

                    if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.SaveThumbnailImageToFile))
                    {
                        string thumbnailFilename, thumbnailFolder;

                        if (!string.IsNullOrEmpty(Info.FilePath))
                        {
                            thumbnailFilename = Path.GetFileName(Info.FilePath);
                            thumbnailFolder   = Path.GetDirectoryName(Info.FilePath);
                        }
                        else
                        {
                            thumbnailFilename = Info.FileName;
                            thumbnailFolder   = Info.TaskSettings.CaptureFolder;
                        }

                        Info.ThumbnailFilePath = TaskHelpers.CreateThumbnail(tempImage, thumbnailFolder, thumbnailFilename, Info.TaskSettings);

                        if (!string.IsNullOrEmpty(Info.ThumbnailFilePath))
                        {
                            DebugHelper.WriteLine("Thumbnail saved to file: " + Info.ThumbnailFilePath);
                        }
                    }
                }
            }

            return(true);
        }
        public bool OtherIsSupplyingSurface()
        {
            DebugHelper.AssertUIThread();

            return(true);
        }
Exemple #11
0
        private UploadResult InternalUpload(Stream stream, string fileName, bool refreshTokenOnError)
        {
            Dictionary <string, string> args = new Dictionary <string, string>();
            NameValueCollection         headers;

            if (UploadMethod == AccountType.User)
            {
                if (!CheckAuthorization())
                {
                    return(null);
                }

                if (!string.IsNullOrEmpty(UploadAlbumID))
                {
                    args.Add("album", UploadAlbumID);
                }

                headers = GetAuthHeaders();
            }
            else
            {
                headers = new NameValueCollection();
                headers.Add("Authorization", "Client-ID " + AuthInfo.Client_ID);
            }

            WebExceptionReturnResponse = true;
            UploadResult result = UploadData(stream, "https://api.imgur.com/3/image", fileName, "image", args, headers);

            if (!string.IsNullOrEmpty(result.Response))
            {
                ImgurResponse imgurResponse = JsonConvert.DeserializeObject <ImgurResponse>(result.Response);

                if (imgurResponse != null)
                {
                    if (imgurResponse.success && imgurResponse.status == 200)
                    {
                        ImgurImageData imageData = ((JObject)imgurResponse.data).ToObject <ImgurImageData>();

                        if (imageData != null && !string.IsNullOrEmpty(imageData.link))
                        {
                            if (DirectLink)
                            {
                                if (UseGIFV && !string.IsNullOrEmpty(imageData.gifv))
                                {
                                    result.URL = imageData.gifv;
                                }
                                else
                                {
                                    result.URL = imageData.link;
                                }
                            }
                            else
                            {
                                result.URL = "http://imgur.com/" + imageData.id;
                            }

                            string thumbnail = string.Empty;

                            switch (ThumbnailType)
                            {
                            case ImgurThumbnailType.Small_Square:
                                thumbnail = "s";
                                break;

                            case ImgurThumbnailType.Big_Square:
                                thumbnail = "b";
                                break;

                            case ImgurThumbnailType.Small_Thumbnail:
                                thumbnail = "t";
                                break;

                            case ImgurThumbnailType.Medium_Thumbnail:
                                thumbnail = "m";
                                break;

                            case ImgurThumbnailType.Large_Thumbnail:
                                thumbnail = "l";
                                break;

                            case ImgurThumbnailType.Huge_Thumbnail:
                                thumbnail = "h";
                                break;
                            }

                            result.ThumbnailURL = string.Format("http://i.imgur.com/{0}{1}.jpg", imageData.id, thumbnail); // Thumbnails always jpg
                            result.DeletionURL  = "http://imgur.com/delete/" + imageData.deletehash;
                        }
                    }
                    else
                    {
                        ImgurErrorData errorData = ((JObject)imgurResponse.data).ToObject <ImgurErrorData>();

                        if (errorData != null)
                        {
                            if (UploadMethod == AccountType.User && refreshTokenOnError &&
                                errorData.error.Equals("The access token provided is invalid.", StringComparison.InvariantCultureIgnoreCase) && RefreshAccessToken())
                            {
                                DebugHelper.WriteLine("Imgur access token refreshed, reuploading image.");

                                return(InternalUpload(stream, fileName, false));
                            }

                            string errorMessage = string.Format("Imgur upload failed: ({0}) {1}", imgurResponse.status, errorData.error);
                            Errors.Clear();
                            Errors.Add(errorMessage);
                        }
                    }
                }
            }

            return(result);
        }
Exemple #12
0
        public byte[] ReceiveReply()
        {
            var buffer = new byte[BufferLength];
            var packet = new List <byte>();

            try
            {
                var ret = Connection.Receive(buffer);
#if DEBUG
                //logger.Info(ret);
#endif
                if (ret == 0)
                {
                    return(null);
                }
                var receive = GlobalFunction.SplitByteArray(buffer, 0, ret);
                packet.AddRange(receive);
                //Console.WriteLine("Receive {0:d} bytes", ret);

                while (ret < 4)
                {
                    //if (Connection.Available == 0) break;
                    var ret_ = Connection.Receive(buffer);
#if DEBUG
                    logger.Info(ret_);
#endif
                    if (ret_ == 0)
                    {
                        break;
                    }
                    ret += ret_;
                    var receive_ = GlobalFunction.SplitByteArray(buffer, 0, ret_);
                    packet.AddRange(receive_);
                }

                var tmpSize = GlobalFunction.SplitByteArray(buffer, 2, 2);
                var size    = GlobalFunction.BE2ToDec(tmpSize);

                while (ret < size)
                {
                    //Console.WriteLine("need receive more {0:d} bytes.", size - ret);
                    //if (Connection.Available == 0) break;
                    var ret_ = Connection.Receive(buffer);
#if DEBUG
                    logger.Info(ret_);
#endif
                    if (ret_ == 0)
                    {
                        break;
                    }
                    ret += ret_;
                    var receive_ = GlobalFunction.SplitByteArray(buffer, 0, ret_);
                    packet.AddRange(receive_);
                }
            }
            catch (SocketException se)
            {
                if (se.SocketErrorCode == SocketError.TimedOut)
                {
#if DEBUG
                    logger.Error(se.Message);
#endif
                    DebugHelper.WriteLine("Receive timed out!");
                    return(null);
                }
            }
            return(packet.ToArray());
        }
Exemple #13
0
        protected override void OnBindCommands(CommandBindingCollection bindings)
        {
            DebugHelper.AssertUIThread();

            base.OnBindCommands(bindings);

            if (bindings != null)
            {
                {
                    ICommand cmd = FindResource("KinectStudioPlugin.CameraViewCommand") as ICommand;
                    if (cmd != null)
                    {
                        bindings.Add(new CommandBinding(cmd,
                                                        (source2, e2) =>
                        {
                            DebugHelper.AssertUIThread();

                            switch (e2.Parameter.ToString())
                            {
                            case "Default":
                                e2.Handled = true;

                                ViewDefault();
                                break;

                            case "Front":
                                e2.Handled = true;

                                ViewFront();
                                break;

                            case "Left":
                                e2.Handled = true;

                                ViewLeft();
                                break;

                            case "Top":
                                e2.Handled = true;

                                ViewTop();
                                break;
                            }
                        },
                                                        (source2, e2) =>
                        {
                            e2.Handled    = true;
                            e2.CanExecute = true;
                        }));
                    }
                }

                {
                    ICommand cmd = FindResource("KinectStudioPlugin.ZoomInOutCommand") as ICommand;
                    if (cmd != null)
                    {
                        bindings.Add(new CommandBinding(cmd,
                                                        (source2, e2) =>
                        {
                            DebugHelper.AssertUIThread();

                            string str = e2.Parameter as string;
                            switch (str)
                            {
                            case "+":
                                e2.Handled = true;
                                this.ZoomIn();
                                break;

                            case "-":
                                e2.Handled = true;
                                this.ZoomOut();
                                break;
                            }
                        },
                                                        (source2, e2) =>
                        {
                            e2.Handled    = true;
                            e2.CanExecute = true;
                        }));
                    }
                }
            }
        }
Exemple #14
0
 public Image3DVisualizationControl(IServiceProvider serviceProvider, EventType eventType, VisualizationViewSettings viewSettings, IAvailableStreams availableStreamsGetter)
     : base(serviceProvider, eventType, viewSettings, (p) => p is I3DVisualPlugin, availableStreamsGetter)
 {
     DebugHelper.AssertUIThread();
 }
Exemple #15
0
        public GameInfoBase StartGame(GameContextBase InGameContext)
        {
            DebugHelper.Assert(InGameContext != null);
            if (InGameContext == null)
            {
                return(null);
            }
            if (Singleton <BattleLogic> .get_instance().isRuning)
            {
                return(null);
            }
            SynchrReport.Reset();
            GameSettings.DecideDynamicParticleLOD();
            Singleton <CHeroSelectBaseSystem> .get_instance().m_fOpenHeroSelectForm = Time.time - Singleton <CHeroSelectBaseSystem> .get_instance().m_fOpenHeroSelectForm;

            this.m_fLoadingTime = Time.time;
            this.m_eventsLoadingTime.Clear();
            ApolloAccountInfo accountInfo = Singleton <ApolloHelper> .GetInstance().GetAccountInfo(false);

            DebugHelper.Assert(accountInfo != null, "account info is null");
            this.m_iMapId    = InGameContext.levelContext.m_mapID;
            this.m_kGameType = InGameContext.levelContext.GetGameType();
            this.m_eventsLoadingTime.Add(new KeyValuePair <string, string>("OpenID", (accountInfo == null) ? "0" : accountInfo.get_OpenId()));
            this.m_eventsLoadingTime.Add(new KeyValuePair <string, string>("LevelID", InGameContext.levelContext.m_mapID.ToString()));
            this.m_eventsLoadingTime.Add(new KeyValuePair <string, string>("isPVPLevel", InGameContext.levelContext.IsMobaMode().ToString()));
            this.m_eventsLoadingTime.Add(new KeyValuePair <string, string>("isPVPMode", InGameContext.levelContext.IsMobaMode().ToString()));
            this.m_eventsLoadingTime.Add(new KeyValuePair <string, string>("bLevelNo", InGameContext.levelContext.m_levelNo.ToString()));
            Singleton <BattleLogic> .GetInstance().isRuning = true;

            Singleton <BattleLogic> .GetInstance().isFighting = false;

            Singleton <BattleLogic> .GetInstance().isGameOver = false;

            Singleton <BattleLogic> .GetInstance().isWaitMultiStart = false;

            ActionManager.Instance.frameMode = true;
            MonoSingleton <ActionManager> .GetInstance().ForceStop();

            Singleton <GameObjMgr> .GetInstance().ClearActor();

            Singleton <SceneManagement> .GetInstance().Clear();

            MonoSingleton <SceneMgr> .GetInstance().ClearAll();

            MonoSingleton <GameLoader> .GetInstance().ResetLoader();

            InGameContext.PrepareStartup();
            if (!MonoSingleton <GameFramework> .get_instance().EditorPreviewMode)
            {
                DebugHelper.Assert(InGameContext.levelContext != null);
                DebugHelper.Assert(!string.IsNullOrEmpty(InGameContext.levelContext.m_levelDesignFileName));
                if (string.IsNullOrEmpty(InGameContext.levelContext.m_levelArtistFileName))
                {
                    MonoSingleton <GameLoader> .get_instance().AddLevel(InGameContext.levelContext.m_levelDesignFileName);
                }
                else
                {
                    MonoSingleton <GameLoader> .get_instance().AddDesignSerializedLevel(InGameContext.levelContext.m_levelDesignFileName);

                    MonoSingleton <GameLoader> .get_instance().AddArtistSerializedLevel(InGameContext.levelContext.m_levelArtistFileName);
                }
                MonoSingleton <GameLoader> .get_instance().AddSoundBank("Effect_Common");

                MonoSingleton <GameLoader> .get_instance().AddSoundBank("System_Voice");
            }
            GameInfoBase gameInfoBase = InGameContext.CreateGameInfo();

            DebugHelper.Assert(gameInfoBase != null, "can't create game logic object!");
            this.gameInfo = gameInfoBase;
            gameInfoBase.PreBeginPlay();
            Singleton <BattleLogic> .get_instance().m_LevelContext = this.gameInfo.gameContext.levelContext;

            try
            {
                DebugHelper.CustomLog("GameBuilder Start Game: ispvplevel={0} ispvpmode={4} levelid={1} leveltype={6} levelname={3} Gametype={2} pick={5}", new object[]
                {
                    InGameContext.levelContext.IsMobaMode(),
                    InGameContext.levelContext.m_mapID,
                    InGameContext.levelContext.GetGameType(),
                    InGameContext.levelContext.m_levelName,
                    InGameContext.levelContext.IsMobaMode(),
                    InGameContext.levelContext.GetSelectHeroType(),
                    InGameContext.levelContext.m_pveLevelType
                });
                Player hostPlayer = Singleton <GamePlayerCenter> .get_instance().GetHostPlayer();

                if (hostPlayer != null)
                {
                    DebugHelper.CustomLog("HostPlayer player id={1} name={2} ", new object[]
                    {
                        hostPlayer.PlayerId,
                        hostPlayer.Name
                    });
                }
            }
            catch (Exception)
            {
            }
            if (!MonoSingleton <GameFramework> .get_instance().EditorPreviewMode)
            {
                this.m_fLoadProgress = 0f;
                MonoSingleton <GameLoader> .GetInstance().Load(new GameLoader.LoadProgressDelegate(this.onGameLoadProgress), new GameLoader.LoadCompleteDelegate(this.OnGameLoadComplete));

                MonoSingleton <VoiceSys> .GetInstance().HeroSelectTobattle();

                Singleton <GameStateCtrl> .GetInstance().GotoState("LoadingState");
            }
            return(gameInfoBase);
        }
Exemple #16
0
        public void EndGame()
        {
            if (!Singleton <BattleLogic> .get_instance().isRuning)
            {
                return;
            }
            try
            {
                DebugHelper.CustomLog("Prepare GameBuilder EndGame");
            }
            catch (Exception)
            {
            }
            MonoSingleton <GSDKsys> .GetInstance().EndSpeed();

            Singleton <GameLogic> .GetInstance().HashCheckFreq = 500u;

            Singleton <GameLogic> .GetInstance().SnakeTraceMasks = 0u;

            Singleton <GameLogic> .GetInstance().SnakeTraceSize = 1024000u;

            Singleton <LobbyLogic> .GetInstance().StopGameEndTimer();

            Singleton <LobbyLogic> .GetInstance().StopSettleMsgTimer();

            Singleton <LobbyLogic> .GetInstance().StopSettlePanelTimer();

            MonoSingleton <GameLoader> .get_instance().AdvanceStopLoad();

            Singleton <WatchController> .GetInstance().Stop();

            Singleton <FrameWindow> .GetInstance().ResetSendCmdSeq();

            Singleton <CBattleGuideManager> .GetInstance().resetPause();

            MonoSingleton <ShareSys> .get_instance().SendQQGameTeamStateChgMsg(ShareSys.QQGameTeamEventType.end, 0, 0, 0u, string.Empty);

            Singleton <StarSystem> .GetInstance().EndGame();

            Singleton <WinLoseByStarSys> .GetInstance().EndGame();

            Singleton <CMatchingSystem> .GetInstance().EndGame();

            string openID = Singleton <ApolloHelper> .GetInstance().GetOpenID();

            List <KeyValuePair <string, string> > list = new List <KeyValuePair <string, string> >();

            list.Add(new KeyValuePair <string, string>("g_version", CVersion.GetAppVersion()));
            list.Add(new KeyValuePair <string, string>("WorldID", MonoSingleton <TdirMgr> .GetInstance().SelectedTdir.logicWorldID.ToString()));
            list.Add(new KeyValuePair <string, string>("platform", Singleton <ApolloHelper> .GetInstance().CurPlatform.ToString()));
            list.Add(new KeyValuePair <string, string>("openid", openID));
            list.Add(new KeyValuePair <string, string>("GameType", this.m_kGameType.ToString()));
            list.Add(new KeyValuePair <string, string>("MapID", this.m_iMapId.ToString()));
            list.Add(new KeyValuePair <string, string>("LoadingTime", this.m_fLoadingTime.ToString()));
            Singleton <ApolloHelper> .GetInstance().ApolloRepoertEvent("Service_LoadingBattle", list, true);

            List <KeyValuePair <string, string> > list2 = new List <KeyValuePair <string, string> >();

            list2.Add(new KeyValuePair <string, string>("g_version", CVersion.GetAppVersion()));
            list2.Add(new KeyValuePair <string, string>("WorldID", MonoSingleton <TdirMgr> .GetInstance().SelectedTdir.logicWorldID.ToString()));
            list2.Add(new KeyValuePair <string, string>("platform", Singleton <ApolloHelper> .GetInstance().CurPlatform.ToString()));
            list2.Add(new KeyValuePair <string, string>("openid", openID));
            list2.Add(new KeyValuePair <string, string>("totaltime", Singleton <CHeroSelectBaseSystem> .get_instance().m_fOpenHeroSelectForm.ToString()));
            list2.Add(new KeyValuePair <string, string>("gameType", this.m_kGameType.ToString()));
            list2.Add(new KeyValuePair <string, string>("role_list", string.Empty));
            list2.Add(new KeyValuePair <string, string>("errorCode", string.Empty));
            list2.Add(new KeyValuePair <string, string>("error_msg", string.Empty));
            Singleton <ApolloHelper> .GetInstance().ApolloRepoertEvent("Service_Login_EnterGame", list2, true);

            float num = Singleton <FrameSynchr> .GetInstance().LogicFrameTick * 0.001f;

            Singleton <FrameSynchr> .GetInstance().PingVariance();

            List <KeyValuePair <string, string> > list3 = new List <KeyValuePair <string, string> >();

            list3.Add(new KeyValuePair <string, string>("g_version", CVersion.GetAppVersion()));
            list3.Add(new KeyValuePair <string, string>("WorldID", MonoSingleton <TdirMgr> .GetInstance().SelectedTdir.logicWorldID.ToString()));
            list3.Add(new KeyValuePair <string, string>("platform", Singleton <ApolloHelper> .GetInstance().CurPlatform.ToString()));
            list3.Add(new KeyValuePair <string, string>("openid", openID));
            list3.Add(new KeyValuePair <string, string>("GameType", this.m_kGameType.ToString()));
            list3.Add(new KeyValuePair <string, string>("MapID", this.m_iMapId.ToString()));
            list3.Add(new KeyValuePair <string, string>("Max_FPS", Singleton <CBattleSystem> .GetInstance().m_MaxBattleFPS.ToString()));
            list3.Add(new KeyValuePair <string, string>("Min_FPS", Singleton <CBattleSystem> .GetInstance().m_MinBattleFPS.ToString()));
            float num2 = -1f;

            if (Singleton <CBattleSystem> .GetInstance().m_BattleFPSCount > 0f)
            {
                num2 = Singleton <CBattleSystem> .GetInstance().m_AveBattleFPS / Singleton <CBattleSystem> .GetInstance().m_BattleFPSCount;
            }
            list3.Add(new KeyValuePair <string, string>("Avg_FPS", num2.ToString()));
            list3.Add(new KeyValuePair <string, string>("Ab_FPS_time", Singleton <BattleLogic> .GetInstance().m_Ab_FPS_time.ToString()));
            list3.Add(new KeyValuePair <string, string>("Abnormal_FPS", Singleton <BattleLogic> .GetInstance().m_Abnormal_FPS_Count.ToString()));
            list3.Add(new KeyValuePair <string, string>("Less10FPSCount", Singleton <BattleLogic> .GetInstance().m_fpsCunt10.ToString()));
            list3.Add(new KeyValuePair <string, string>("Less18FPSCount", Singleton <BattleLogic> .GetInstance().m_fpsCunt18.ToString()));
            list3.Add(new KeyValuePair <string, string>("Ab_4FPS_time", Singleton <BattleLogic> .GetInstance().m_Ab_4FPS_time.ToString()));
            list3.Add(new KeyValuePair <string, string>("Abnormal_4FPS", Singleton <BattleLogic> .GetInstance().m_Abnormal_4FPS_Count.ToString()));
            list3.Add(new KeyValuePair <string, string>("Min_Ping", Singleton <FrameSynchr> .get_instance().m_MinPing.ToString()));
            list3.Add(new KeyValuePair <string, string>("Max_Ping", Singleton <FrameSynchr> .get_instance().m_MaxPing.ToString()));
            list3.Add(new KeyValuePair <string, string>("Avg_Ping", Singleton <FrameSynchr> .get_instance().m_AvePing.ToString()));
            list3.Add(new KeyValuePair <string, string>("Abnormal_Ping", Singleton <FrameSynchr> .get_instance().m_Abnormal_PingCount.ToString()));
            list3.Add(new KeyValuePair <string, string>("Ping300", Singleton <FrameSynchr> .get_instance().m_ping300Count.ToString()));
            list3.Add(new KeyValuePair <string, string>("Ping150to300", Singleton <FrameSynchr> .get_instance().m_ping150to300.ToString()));
            list3.Add(new KeyValuePair <string, string>("Ping150", Singleton <FrameSynchr> .get_instance().m_ping150.ToString()));
            list3.Add(new KeyValuePair <string, string>("LostpingCount", Singleton <FrameSynchr> .get_instance().m_pingLost.ToString()));
            list3.Add(new KeyValuePair <string, string>("PingSeqCount", Singleton <FrameSynchr> .get_instance().m_LastReceiveHeartSeq.ToString()));
            list3.Add(new KeyValuePair <string, string>("PingVariance", Singleton <FrameSynchr> .get_instance().m_PingVariance.ToString()));
            list3.Add(new KeyValuePair <string, string>("Battle_Time", num.ToString()));
            list3.Add(new KeyValuePair <string, string>("BattleSvr_Reconnect", Singleton <NetworkModule> .GetInstance().m_GameReconnetCount.ToString()));
            list3.Add(new KeyValuePair <string, string>("GameSvr_Reconnect", Singleton <NetworkModule> .GetInstance().m_lobbyReconnetCount.ToString()));
            list3.Add(new KeyValuePair <string, string>("music", GameSettings.EnableMusic.ToString()));
            list3.Add(new KeyValuePair <string, string>("quality", GameSettings.RenderQuality.ToString()));
            list3.Add(new KeyValuePair <string, string>("status", "1"));
            list3.Add(new KeyValuePair <string, string>("Quality_Mode", GameSettings.ModelLOD.ToString()));
            list3.Add(new KeyValuePair <string, string>("Quality_Particle", GameSettings.ParticleLOD.ToString()));
            list3.Add(new KeyValuePair <string, string>("receiveMoveCmdAverage", Singleton <FrameSynchr> .get_instance().m_receiveMoveCmdAverage.ToString()));
            list3.Add(new KeyValuePair <string, string>("receiveMoveCmdMax", Singleton <FrameSynchr> .get_instance().m_receiveMoveCmdMax.ToString()));
            list3.Add(new KeyValuePair <string, string>("execMoveCmdAverage", Singleton <FrameSynchr> .get_instance().m_execMoveCmdAverage.ToString()));
            list3.Add(new KeyValuePair <string, string>("execMoveCmdMax", Singleton <FrameSynchr> .get_instance().m_execMoveCmdMax.ToString()));
            list3.Add(new KeyValuePair <string, string>("LOD_Down", Singleton <BattleLogic> .GetInstance().m_iAutoLODState.ToString()));
            if (NetworkAccelerator.started)
            {
                if (NetworkAccelerator.isAccerating())
                {
                    list3.Add(new KeyValuePair <string, string>("AccState", "Acc"));
                }
                else
                {
                    list3.Add(new KeyValuePair <string, string>("AccState", "Direct"));
                }
            }
            else
            {
                list3.Add(new KeyValuePair <string, string>("AccState", "Off"));
            }
            int num3 = 0;

            if (MonoSingleton <VoiceSys> .GetInstance().UseSpeak&& MonoSingleton <VoiceSys> .GetInstance().UseMic)
            {
                num3 = 2;
            }
            else if (MonoSingleton <VoiceSys> .GetInstance().UseSpeak)
            {
                num3 = 1;
            }
            list3.Add(new KeyValuePair <string, string>("Mic", num3.ToString()));
            Singleton <ApolloHelper> .GetInstance().ApolloRepoertEvent("Service_PVPBattle_Summary", list3, true);

            this.m_eventsLoadingTime.Clear();
            try
            {
                float num4 = (float)Singleton <BattleLogic> .GetInstance().m_fpsCunt10 / (float)Singleton <BattleLogic> .GetInstance().m_fpsCount;

                int   iFps10PercentNum = Mathf.CeilToInt(num4 * 100f / 10f) * 10;
                float num5             = (float)(Singleton <BattleLogic> .GetInstance().m_fpsCunt18 + Singleton <BattleLogic> .GetInstance().m_fpsCunt10) / (float)Singleton <BattleLogic> .GetInstance().m_fpsCount;

                int   iFps18PercentNum = Mathf.CeilToInt(num5 * 100f / 10f) * 10;
                CSPkg cSPkg            = NetworkModule.CreateDefaultCSPKG(5000u);
                cSPkg.stPkgData.get_stCltPerformance().iMapID     = this.m_iMapId;
                cSPkg.stPkgData.get_stCltPerformance().iPlayerCnt = Singleton <GamePlayerCenter> .get_instance().GetAllPlayers().get_Count();

                cSPkg.stPkgData.get_stCltPerformance().chModelLOD       = (sbyte)GameSettings.ModelLOD;
                cSPkg.stPkgData.get_stCltPerformance().chParticleLOD    = (sbyte)GameSettings.ParticleLOD;
                cSPkg.stPkgData.get_stCltPerformance().chCameraHeight   = (sbyte)GameSettings.CameraHeight;
                cSPkg.stPkgData.get_stCltPerformance().chEnableOutline  = ((!GameSettings.EnableOutline) ? 0 : 1);
                cSPkg.stPkgData.get_stCltPerformance().iFps10PercentNum = iFps10PercentNum;
                cSPkg.stPkgData.get_stCltPerformance().iFps18PercentNum = iFps18PercentNum;
                cSPkg.stPkgData.get_stCltPerformance().iAveFps          = (int)Singleton <CBattleSystem> .GetInstance().m_AveBattleFPS;

                cSPkg.stPkgData.get_stCltPerformance().iPingAverage = Singleton <FrameSynchr> .get_instance().m_PingAverage;

                cSPkg.stPkgData.get_stCltPerformance().iPingVariance = Singleton <FrameSynchr> .get_instance().m_PingVariance;

                Utility.StringToByteArray(SystemInfo.deviceModel, ref cSPkg.stPkgData.get_stCltPerformance().szDeviceModel);
                Utility.StringToByteArray(SystemInfo.graphicsDeviceName, ref cSPkg.stPkgData.get_stCltPerformance().szGPUName);
                cSPkg.stPkgData.get_stCltPerformance().iCpuCoreNum    = SystemInfo.processorCount;
                cSPkg.stPkgData.get_stCltPerformance().iSysMemorySize = SystemInfo.systemMemorySize;
                cSPkg.stPkgData.get_stCltPerformance().iAvailMemory   = DeviceCheckSys.GetAvailMemory();
                cSPkg.stPkgData.get_stCltPerformance().iIsTongCai     = ((!MonoSingleton <CTongCaiSys> .GetInstance().IsCanUseTongCai()) ? 0 : 1);
                int iIsSpeedUp;
                if (NetworkAccelerator.started)
                {
                    if (NetworkAccelerator.isAccerating())
                    {
                        iIsSpeedUp = 1;
                    }
                    else
                    {
                        iIsSpeedUp = 2;
                    }
                }
                else
                {
                    iIsSpeedUp = 0;
                }
                if (MonoSingleton <GSDKsys> .GetInstance().enabled)
                {
                    iIsSpeedUp = 4;
                }
                cSPkg.stPkgData.get_stCltPerformance().iIsSpeedUp = iIsSpeedUp;
                Singleton <NetworkModule> .GetInstance().SendLobbyMsg(ref cSPkg, false);
            }
            catch (Exception ex)
            {
                Debug.Log(ex.get_Message());
            }
            MonoSingleton <DialogueProcessor> .GetInstance().Uninit();

            Singleton <TipProcessor> .GetInstance().Uninit();

            Singleton <LobbyLogic> .get_instance().inMultiRoom = false;

            Singleton <LobbyLogic> .get_instance().inMultiGame = false;

            Singleton <LobbyLogic> .GetInstance().reconnGameInfo = null;

            Singleton <BattleLogic> .GetInstance().isRuning = false;

            Singleton <BattleLogic> .GetInstance().isFighting = false;

            Singleton <BattleLogic> .GetInstance().isGameOver = false;

            Singleton <BattleLogic> .GetInstance().isWaitMultiStart = false;

            Singleton <NetworkModule> .GetInstance().CloseGameServerConnect(true);

            Singleton <ShenFuSystem> .get_instance().ClearAll();

            MonoSingleton <ActionManager> .GetInstance().ForceStop();

            Singleton <GameObjMgr> .GetInstance().ClearActor();

            Singleton <SceneManagement> .GetInstance().Clear();

            MonoSingleton <SceneMgr> .GetInstance().ClearAll();

            Singleton <GamePlayerCenter> .GetInstance().ClearAllPlayers();

            Singleton <ActorDataCenter> .get_instance().ClearHeroServerData();

            Singleton <FrameSynchr> .GetInstance().ResetSynchr();

            Singleton <GameReplayModule> .GetInstance().OnGameEnd();

            Singleton <BattleLogic> .GetInstance().ResetBattleSystem();

            ActionManager.Instance.frameMode = false;
            MonoSingleton <VoiceInteractionSys> .get_instance().OnEndGame();

            if (!Singleton <GameStateCtrl> .get_instance().isLobbyState)
            {
                DebugHelper.CustomLog("GotoLobbyState by EndGame");
                Singleton <GameStateCtrl> .GetInstance().GotoState("LobbyState");
            }
            Singleton <BattleSkillHudControl> .DestroyInstance();

            this.m_kGameType = 12;
            this.m_iMapId    = 0;
            try
            {
                FogOfWar.EndLevel();
            }
            catch (DllNotFoundException ex2)
            {
                DebugHelper.Assert(false, "FOW Exception {0} {1}", new object[]
                {
                    ex2.get_Message(),
                    ex2.get_StackTrace()
                });
            }
            Singleton <BattleStatistic> .get_instance().PostEndGame();

            try
            {
                DebugHelper.CustomLog("Finish GameBuilder EndGame");
            }
            catch (Exception)
            {
            }
        }
Exemple #17
0
 /// <summary>
 /// Returns the message name for a corresponding type.
 /// </summary>
 /// <param name="t">The type of message.</param>
 /// <returns>The name of the message.</returns>
 public static string GetName(Type t)
 {
     DebugHelper.Assert(typeof(MessageBase).GetTypeInfo().IsAssignableFrom(t.GetTypeInfo()));
     return(t.Name);
 }
Exemple #18
0
        private void DoUploadJob()
        {
            if (Program.Settings.ShowUploadWarning && MessageBox.Show(Resources.UploadTask_DoUploadJob_First_time_upload_warning_text,
                                                                      "ShareX - " + Resources.UploadTask_DoUploadJob_First_time_upload_warning,
                                                                      MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
            {
                Program.Settings.ShowUploadWarning          = false;
                Program.DefaultTaskSettings.AfterCaptureJob = Program.DefaultTaskSettings.AfterCaptureJob.Remove(AfterCaptureTasks.UploadImageToHost);
                RequestSettingUpdate = true;
                Stop();
            }

            if (Program.Settings.LargeFileSizeWarning > 0)
            {
                long dataSize = Program.Settings.BinaryUnits ? Program.Settings.LargeFileSizeWarning * 1024 * 1024 : Program.Settings.LargeFileSizeWarning * 1000 * 1000;
                if (Data != null && Data.Length > dataSize)
                {
                    using (MyMessageBox msgbox = new MyMessageBox(Resources.UploadTask_DoUploadJob_You_are_attempting_to_upload_a_large_file, "ShareX",
                                                                  MessageBoxButtons.YesNo, Resources.UploadManager_IsUploadConfirmed_Don_t_show_this_message_again_))
                    {
                        msgbox.ShowDialog();
                        if (msgbox.IsChecked)
                        {
                            Program.Settings.LargeFileSizeWarning = 0;
                        }
                        if (msgbox.DialogResult == DialogResult.No)
                        {
                            Stop();
                        }
                    }
                }
            }

            if (!StopRequested)
            {
                Program.Settings.ShowUploadWarning = false;

                SettingManager.WaitUploadersConfig();

                Status      = TaskStatus.Working;
                Info.Status = Resources.UploadTask_DoUploadJob_Uploading;

                TaskbarManager.SetProgressState(Program.MainForm, TaskbarProgressBarStatus.Normal);

                bool cancelUpload = false;

                if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.ShowBeforeUploadWindow))
                {
                    using (BeforeUploadForm form = new BeforeUploadForm(Info))
                    {
                        cancelUpload = form.ShowDialog() != DialogResult.OK;
                    }
                }

                if (!cancelUpload)
                {
                    OnUploadStarted();

                    bool isError = DoUpload();

                    if (isError && Program.Settings.MaxUploadFailRetry > 0)
                    {
                        DebugHelper.WriteLine("Upload failed. Retrying upload.");

                        for (int retry = 1; isError && retry <= Program.Settings.MaxUploadFailRetry; retry++)
                        {
                            isError = DoUpload(retry);
                        }
                    }

                    if (!isError)
                    {
                        OnUploadCompleted();
                    }
                }
                else
                {
                    Info.Result.IsURLExpected = false;
                }
            }
        }
Exemple #19
0
        private void Authenticate(string userName, string pass)
        {
            try
            {
                _BUSY_INDICATOR.IsBusy = true;
                if (App.Store.Authentication.Authenticate(userName, pass))
                {
                    var userKey = Membership.GetUser()?.ProviderUserKey;
                    if (userKey != null)
                    {
                        App.CurrentUser = App.Store.Authentication.GetUser((Guid)userKey);
                    }

                    var userSpace = (UserSpace)App.CurrentUser.UserSpaces.First().Value;

                    switch (userSpace)
                    {
                    case UserSpace.AdminSpace:
                        Dispatcher.BeginInvoke(new Action(()
                                                          => NavigationService?.Navigate(new HomePage(), UriKind.Relative)));
                        break;

                    //case UserSpace.SecretaireSpace:
                    //    new Task(() => Dispatcher.BeginInvoke(new Action(()
                    //        => NavigationService?.Navigate(new TeacherSpace(), UriKind.Relative)))).Start();
                    //    break;
                    //case UserSpace.EconomatSpace:
                    //    new Task(() => Dispatcher.BeginInvoke(new Action(()
                    //        => NavigationService?.Navigate(new EconomatView(false), UriKind.Relative)))).Start();
                    //    break;
                    default:
                        _ERROR_LABEL.Visibility = Visibility.Visible;
                        _ERROR_LABEL.Text       = "Oops! Espace utilisateur non Implementer";
                        break;
                    }
                    _BUSY_INDICATOR.IsBusy = false;
                }
                else
                {
                    _BUSY_INDICATOR.IsBusy  = false;
                    _ERROR_LABEL.Visibility = Visibility.Visible;
                    _ERROR_LABEL.Text       = "Pseudo / mot de passe incorrect / ou compte Inactif";
                }
            }
            catch (SecurityException)
            {
                _ERROR_LABEL.Visibility = Visibility.Visible;
                _ERROR_LABEL.Text       = "Permission Refusée, Votre Compte est bloqué !";
                _BUSY_INDICATOR.IsBusy  = false;
            }
            catch (SqlException sqlException)
            {
                _ERROR_LABEL.Visibility = Visibility.Visible;
                _ERROR_LABEL.Text       = "Connection au serveur a echoué, Veiller configurer le Sql serveur!";
                _ERROR_LABEL.ToolTip    = sqlException.Message;
                _BUSY_INDICATOR.IsBusy  = false;
            }
            catch (Exception exx)
            {
                DebugHelper.WriteException(exx);
                _ERROR_LABEL.Visibility = Visibility.Visible;
                _ERROR_LABEL.Text       = "Erreur Inconnue !";
                _ERROR_LABEL.ToolTip    = exx.Message;
                _BUSY_INDICATOR.IsBusy  = false;
            }
            finally
            {
                _BUSY_INDICATOR.IsBusy = false;
            }
        }
Exemple #20
0
        private bool DoUpload(int retry = 0)
        {
            bool isError = false;

            if (retry > 0)
            {
                if (Program.Settings.UseSecondaryUploaders)
                {
                    Info.TaskSettings.ImageDestination     = Program.Settings.SecondaryImageUploaders[retry - 1];
                    Info.TaskSettings.ImageFileDestination = Program.Settings.SecondaryFileUploaders[retry - 1];
                    Info.TaskSettings.TextDestination      = Program.Settings.SecondaryTextUploaders[retry - 1];
                    Info.TaskSettings.TextFileDestination  = Program.Settings.SecondaryFileUploaders[retry - 1];
                    Info.TaskSettings.FileDestination      = Program.Settings.SecondaryFileUploaders[retry - 1];
                }
                else
                {
                    Thread.Sleep(1000);
                }
            }

            SSLBypassHelper sslBypassHelper = null;

            try
            {
                if (HelpersOptions.AcceptInvalidSSLCertificates)
                {
                    sslBypassHelper = new SSLBypassHelper();
                }

                if (!CheckUploadFilters(Data, Info.FileName))
                {
                    switch (Info.UploadDestination)
                    {
                    case EDataType.Image:
                        Info.Result = UploadImage(Data, Info.FileName);
                        break;

                    case EDataType.Text:
                        Info.Result = UploadText(Data, Info.FileName);
                        break;

                    case EDataType.File:
                        Info.Result = UploadFile(Data, Info.FileName);
                        break;
                    }
                }

                StopRequested |= taskReferenceHelper.StopRequested;
            }
            catch (Exception e)
            {
                if (!StopRequested)
                {
                    DebugHelper.WriteException(e);
                    isError = true;
                    AddErrorMessage(e.ToString());
                }
            }
            finally
            {
                if (sslBypassHelper != null)
                {
                    sslBypassHelper.Dispose();
                }

                if (Info.Result == null)
                {
                    Info.Result = new UploadResult();
                }

                if (uploader != null)
                {
                    AddErrorMessage(uploader.Errors.ToArray());
                }

                isError |= Info.Result.IsError;
            }

            return(isError);
        }
 public MetadataViewService()
 {
     DebugHelper.AssertUIThread();
 }
Exemple #22
0
        private void DoAfterUploadJobs()
        {
            try
            {
                if (Info.TaskSettings.AdvancedSettings.ResultForceHTTPS)
                {
                    Info.Result.ForceHTTPS();
                }

                if (Info.Job != TaskJob.ShareURL && (Info.TaskSettings.AfterUploadJob.HasFlag(AfterUploadTasks.UseURLShortener) || Info.Job == TaskJob.ShortenURL ||
                                                     (Info.TaskSettings.AdvancedSettings.AutoShortenURLLength > 0 && Info.Result.URL.Length > Info.TaskSettings.AdvancedSettings.AutoShortenURLLength)))
                {
                    UploadResult result = ShortenURL(Info.Result.URL);

                    if (result != null)
                    {
                        Info.Result.ShortenedURL = result.ShortenedURL;
                        Info.Result.Errors.AddRange(result.Errors);
                    }
                }

                if (Info.Job != TaskJob.ShortenURL && (Info.TaskSettings.AfterUploadJob.HasFlag(AfterUploadTasks.ShareURL) || Info.Job == TaskJob.ShareURL))
                {
                    UploadResult result = ShareURL(Info.Result.ToString());

                    if (result != null)
                    {
                        Info.Result.Errors.AddRange(result.Errors);
                    }

                    if (Info.Job == TaskJob.ShareURL)
                    {
                        Info.Result.IsURLExpected = false;
                    }
                }

                if (Info.TaskSettings.AfterUploadJob.HasFlag(AfterUploadTasks.CopyURLToClipboard))
                {
                    string txt;

                    if (!string.IsNullOrEmpty(Info.TaskSettings.AdvancedSettings.ClipboardContentFormat))
                    {
                        txt = new UploadInfoParser().Parse(Info, Info.TaskSettings.AdvancedSettings.ClipboardContentFormat);
                    }
                    else
                    {
                        txt = Info.Result.ToString();
                    }

                    if (!string.IsNullOrEmpty(txt))
                    {
                        ClipboardHelpers.CopyText(txt);
                    }
                }

                if (Info.TaskSettings.AfterUploadJob.HasFlag(AfterUploadTasks.OpenURL))
                {
                    string result;

                    if (!string.IsNullOrEmpty(Info.TaskSettings.AdvancedSettings.OpenURLFormat))
                    {
                        result = new UploadInfoParser().Parse(Info, Info.TaskSettings.AdvancedSettings.OpenURLFormat);
                    }
                    else
                    {
                        result = Info.Result.ToString();
                    }

                    URLHelpers.OpenURL(result);
                }

                if (Info.TaskSettings.AfterUploadJob.HasFlag(AfterUploadTasks.ShowQRCode))
                {
                    threadWorker.InvokeAsync(() => new QRCodeForm(Info.Result.ToString()).Show());
                }
            }
            catch (Exception e)
            {
                DebugHelper.WriteException(e);
                AddErrorMessage(e.ToString());
            }
        }
        public void ClearActor()
        {
            Dictionary <int, List <ActorRoot> > .Enumerator enumerator = this.CachedActors.GetEnumerator();
            while (enumerator.MoveNext())
            {
                KeyValuePair <int, List <ActorRoot> > current = enumerator.get_Current();
                List <ActorRoot> value = current.get_Value();
                for (int i = 0; i < value.get_Count(); i++)
                {
                    ActorRoot  actorRoot  = value.get_Item(i);
                    GameObject gameObject = actorRoot.gameObject;
                    actorRoot.ObjLinker.DetachActorRoot();
                    Singleton <CGameObjectPool> .GetInstance().RecycleGameObject(gameObject);
                }
                value.Clear();
            }
            this.CachedActors.Clear();
            int count = this.GameActors.get_Count();

            for (int j = 0; j < count; j++)
            {
                DebugHelper.Assert(this.GameActors.get_Item(j));
                if (!this.GameActors.get_Item(j).handle.ObjLinker.isStatic)
                {
                    GameObject gameObject2 = this.GameActors.get_Item(j).handle.gameObject;
                    this.GameActors.get_Item(j).handle.ObjLinker.DetachActorRoot();
                    Singleton <CGameObjectPool> .GetInstance().RecycleGameObject(gameObject2);
                }
                else
                {
                    GameObject gameObject3 = this.GameActors.get_Item(j).handle.gameObject;
                    this.GameActors.get_Item(j).handle.ObjLinker.DetachActorRoot();
                    Object.DestroyObject(gameObject3);
                }
            }
            this.GameActors.Clear();
            for (int k = 0; k < this.StaticActors.get_Count(); k++)
            {
                DebugHelper.Assert(count == 0);
                GameObject gameObject4 = this.StaticActors.get_Item(k).handle.gameObject;
                this.StaticActors.get_Item(k).handle.ObjLinker.DetachActorRoot();
                Object.DestroyObject(gameObject4);
            }
            this.StaticActors.Clear();
            for (int l = 0; l < this.DynamicActors.get_Count(); l++)
            {
                DebugHelper.Assert(count == 0);
                GameObject gameObject5 = this.DynamicActors.get_Item(l).handle.gameObject;
                this.DynamicActors.get_Item(l).handle.ObjLinker.DetachActorRoot();
                Singleton <CGameObjectPool> .GetInstance().RecycleGameObject(gameObject5);
            }
            this.DynamicActors.Clear();
            this.HeroActors.Clear();
            this.OrganActors.Clear();
            this.TowerActors.Clear();
            this.MonsterActors.Clear();
            this.SoldierActors.Clear();
            this.FakeTrueEyes.Clear();
            for (int m = 0; m < 3; m++)
            {
                this.CampsActors[m].Clear();
            }
            this.DelayRecycle.Clear();
            this.NewActorID = 0u;
            for (int n = 0; n < 3; n++)
            {
                this.CampsBullet[n].Clear();
            }
        }
        public bool OtherIsSupplyingTexture()
        {
            DebugHelper.AssertUIThread();

            return(false);
        }
Exemple #25
0
    ///////////////////////////////////////////////////////////////////////////////
    // functions
    ///////////////////////////////////////////////////////////////////////////////

    // ------------------------------------------------------------------ 
    // Desc: 
    // ------------------------------------------------------------------ 

    void Awake () {
        if( instance == null )
            instance = this;
    }
        private void MetadataView_Closed(object sender, EventArgs e)
        {
            DebugHelper.AssertUIThread();

            this.metadataViews.Remove(sender as MetadataView);
        }
Exemple #27
0
        private static void Run()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            IsSilentRun = CLI.IsCommandExist("silent", "s");
            IsSandbox   = CLI.IsCommandExist("sandbox");

            if (!IsSandbox)
            {
                IsPortable = CLI.IsCommandExist("portable", "p");

                if (IsPortable)
                {
                    CustomPersonalPath = PortablePersonalPath;
                }
                else
                {
                    CheckPersonalPathConfig();
                }

                if (!Directory.Exists(PersonalPath))
                {
                    try
                    {
                        Directory.CreateDirectory(PersonalPath);
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(Resources.Program_Run_Unable_to_create_folder_ + string.Format(" \"{0}\"\r\n\r\n{1}", PersonalPath, e),
                                        "ShareX - " + Resources.Program_Run_Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        CustomPersonalPath = "";
                    }
                }
            }

            DebugHelper.WriteLine("{0} started", Title);
            DebugHelper.WriteLine("Operating system: " + Environment.OSVersion.VersionString);
            DebugHelper.WriteLine("Command line: " + Environment.CommandLine);
            DebugHelper.WriteLine("Personal path: " + PersonalPath);

            string gitHash = GetGitHash();

            if (!string.IsNullOrEmpty(gitHash))
            {
                DebugHelper.WriteLine("Git: https://github.com/ShareX/ShareX/tree/" + gitHash);
            }

            LoadProgramSettings();

            UploaderSettingsResetEvent = new ManualResetEvent(false);
            HotkeySettingsResetEvent   = new ManualResetEvent(false);
            TaskEx.Run(LoadSettings);

            LanguageHelper.ChangeLanguage(Settings.Language);

            DebugHelper.WriteLine("MainForm init started");
            MainForm = new MainForm();
            DebugHelper.WriteLine("MainForm init finished");

            Application.Run(MainForm);

            if (WatchFolderManager != null)
            {
                WatchFolderManager.Dispose();
            }
            SaveSettings();
            BackupSettings();

            DebugHelper.WriteLine("ShareX closing");
            DebugHelper.Logger.SaveLog(LogsFilePath);
        }
        public IEnumerable <MetadataView> GetMetadataViews(Window window)
        {
            DebugHelper.AssertUIThread();

            if (window == null)
            {
                throw new ArgumentNullException("window");
            }

            while (window.Owner != null)
            {
                window = window.Owner;
            }

            IEnumerable <MetadataView> value = null;

            ToolsUIWindow toolsWindow = window as ToolsUIWindow;

            if (toolsWindow != null)
            {
                LayoutTabControl tabControl = toolsWindow.LayoutTabControl;

                if (tabControl != null)
                {
                    int layoutIndex = tabControl.SelectedIndex;

                    List <MetadataView> activeTab = new List <MetadataView>();
                    List <MetadataView> otherTabs = new List <MetadataView>();
                    List <MetadataView> temp      = new List <MetadataView>();

                    for (int i = 0; i < tabControl.Items.Count; ++i)
                    {
                        List <MetadataView> list = (i == layoutIndex) ? activeTab : temp;

                        LayoutInstance layout = tabControl.Items[i] as LayoutInstance;
                        if (layout != null)
                        {
                            foreach (View v in layout.FindViews("MetadataView"))
                            {
                                MetadataView mv = v as MetadataView;

                                if (mv != null)
                                {
                                    list.Add(mv);
                                }
                            }
                        }

                        if ((i != layoutIndex) && (list.Count > 0))
                        {
                            if (otherTabs.Count > 0)
                            {
                                otherTabs.Add(null);
                            }

                            otherTabs.AddRange(list.OrderBy(mv => mv.Title));

                            list.Clear();
                        }
                    }

                    List <MetadataView> metadataViews = new List <MetadataView>();

                    if (activeTab.Count > 0)
                    {
                        metadataViews.AddRange(activeTab.OrderBy(mv => mv.Title));

                        if (otherTabs.Count > 0)
                        {
                            metadataViews.Add(null);
                        }
                    }

                    metadataViews.AddRange(otherTabs);
                    value = metadataViews;
                }
            }

            return(value);
        }
Exemple #29
0
        public static int Run(string[] args)
        {
            // IMPORTANT:
            // When updating the command line args for dotnet-migrate, we need to update the in-VS caller of dotnet migrate as well.
            // It is located at dotnet/roslyn-project-system:
            //     src/Microsoft.VisualStudio.ProjectSystem.CSharp.VS/ProjectSystem/VS/Xproj/MigrateXprojFactory.cs

            DebugHelper.HandleDebugSwitch(ref args);

            CommandLineApplication app = new CommandLineApplication();

            app.Name                = "dotnet migrate";
            app.FullName            = ".NET Migrate Command";
            app.Description         = "Command used to migrate project.json projects to msbuild";
            app.HandleResponseFiles = true;
            app.HelpOption("-h|--help");

            CommandArgument projectArgument = app.Argument("<PROJECT_JSON/GLOBAL_JSON/PROJECT_DIR>",
                                                           string.Join(Environment.NewLine,
                                                                       "The path to ",
                                                                       " - a project.json file to migrate.",
                                                                       "or",
                                                                       " - a global.json file, it will migrate the folders specified in global.json.",
                                                                       "or",
                                                                       " - a directory to migrate, it will recursively search for project.json files to migrate.",
                                                                       "Defaults to current directory if nothing is specified."));

            CommandOption template              = app.Option("-t|--template-file", "Base MSBuild template to use for migrated app. The default is the project included in dotnet new -t msbuild", CommandOptionType.SingleValue);
            CommandOption sdkVersion            = app.Option("-v|--sdk-package-version", "The version of the sdk package that will be referenced in the migrated app. The default is the version of the sdk in dotnet new -t msbuild", CommandOptionType.SingleValue);
            CommandOption xprojFile             = app.Option("-x|--xproj-file", "The path to the xproj file to use. Required when there is more than one xproj in a project directory.", CommandOptionType.SingleValue);
            CommandOption skipProjectReferences = app.Option("-s|--skip-project-references", "Skip migrating project references. By default project references are migrated recursively", CommandOptionType.BoolValue);

            CommandOption reportFile             = app.Option("-r|--report-file", "Output migration report to a file in addition to the console.", CommandOptionType.SingleValue);
            CommandOption structuredReportOutput = app.Option("--format-report-file-json", "Output migration report file as json rather than user messages", CommandOptionType.BoolValue);

            app.OnExecute(() =>
            {
                MigrateCommand migrateCommand = new MigrateCommand(
                    template.Value(),
                    projectArgument.Value,
                    sdkVersion.Value(),
                    xprojFile.Value(),
                    reportFile.Value(),
                    skipProjectReferences.BoolValue.HasValue ? skipProjectReferences.BoolValue.Value : false,
                    structuredReportOutput.BoolValue.HasValue ? structuredReportOutput.BoolValue.Value : false);

                return(migrateCommand.Execute());
            });

            try
            {
                return(app.Execute(args));
            }
            catch (Exception ex)
            {
#if DEBUG
                Reporter.Error.WriteLine(ex.ToString());
#else
                Reporter.Error.WriteLine(ex.Message);
#endif
                return(1);
            }
        }
 public void HoldStaticActor(PoolObjHandle <ActorRoot> actor)
 {
     DebugHelper.Assert(actor.handle.ObjLinker.isStatic);
     this.StaticActors.Add(actor);
 }
Exemple #31
0
        /// <summary>
        /// Parses a <see cref="VariantValue"/> from binary data.
        /// </summary>
        /// <param name="data">The data to parse.</param>
        /// <param name="tag">Data indicating the type of  this data.</param>
        public VariantValue(IBuffer data, byte tag)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            if (!TagMap.ContainsKey(tag))
            {
                throw new ArgumentException($"Unknown tag value {tag}", nameof(tag));
            }

            this.type = TagMap[tag];
            this.data = new byte[data.Length];
            if (data.Length > 0)
            {
                data.CopyTo(this.data);
            }

            switch (VariantType)
            {
            case Type.UInt32:
                if (Size != 4)
                {
                    throw new ArgumentException($"Expected 4 bytes for {VariantType}, got {Size}", nameof(data));
                }
                this.value = BufferToLittleEndianUInt32(this.data, 0);

                break;

            case Type.UInt64:
                if (Size != 8)
                {
                    throw new ArgumentException($"Expected 8 bytes for {VariantType}, got {Size}", nameof(data));
                }
                this.value = BufferToLittleEndianUInt64(this.data, 0);

                break;

            case Type.Bool:
                if (Size != 1)
                {
                    throw new ArgumentException($"Expected 1 byte for {VariantType}, got {Size}", nameof(data));
                }
                this.value = this.data[0] != 0;

                break;

            case Type.Int32:
                if (Size != 4)
                {
                    throw new ArgumentException($"Expected 4 bytes for {VariantType}, got {Size}", nameof(data));
                }
                this.value = (int)BufferToLittleEndianUInt32(this.data, 0);

                break;

            case Type.Int64:
                if (Size != 8)
                {
                    throw new ArgumentException($"Expected 8 bytes for {VariantType}, got {Size}", nameof(data));
                }
                this.value = (long)BufferToLittleEndianUInt64(this.data, 0);

                break;

            case Type.String:
                this.value = Encoding.UTF8.GetString(this.data);
                break;

            case Type.ByteArray:
                this.value = this.data;
                break;

            default:
                DebugHelper.Assert(false);
                throw new InvalidOperationException();
            }
        }
Exemple #32
0
        public static int Main(string[] args)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            CommonCompilerOptions commonOptions = null;
            string tempOutDir = null;
            IReadOnlyList <string> references = Array.Empty <string>();
            IReadOnlyList <string> resources  = Array.Empty <string>();
            IReadOnlyList <string> sources    = Array.Empty <string>();
            string outputName = null;

            try
            {
                ArgumentSyntax.Parse(args, syntax =>
                {
                    commonOptions = CommonCompilerOptionsExtensions.Parse(syntax);

                    syntax.DefineOption("temp-output", ref tempOutDir, "Compilation temporary directory");

                    syntax.DefineOption("out", ref outputName, "Name of the output assembly");

                    syntax.DefineOptionList("reference", ref references, "Path to a compiler metadata reference");

                    syntax.DefineOptionList("resource", ref resources, "Resources to embed");

                    syntax.DefineParameterList("source-files", ref sources, "Compilation sources");

                    if (tempOutDir == null)
                    {
                        syntax.ReportError("Option '--temp-output' is required");
                    }
                });
            }
            catch (ArgumentSyntaxException)
            {
                return(ExitFailed);
            }

            var translated = TranslateCommonOptions(commonOptions);

            var allArgs = new List <string>(translated);

            allArgs.AddRange(GetDefaultOptions());

            if (outputName != null)
            {
                allArgs.Add($"-out:\"{outputName}\"");
            }

            allArgs.AddRange(references.Select(r => $"-r:\"{r}\""));
            allArgs.AddRange(resources.Select(resource => $"-resource:{resource}"));
            allArgs.AddRange(sources.Select(s => $"\"{s}\""));

            var rsp = Path.Combine(tempOutDir, "dotnet-compile-csc.rsp");

            File.WriteAllLines(rsp, allArgs, Encoding.UTF8);

            // Execute CSC!
            var result = RunCsc($"-noconfig @\"{rsp}\"")
                         .ForwardStdErr()
                         .ForwardStdOut()
                         .Execute();

            return(result.ExitCode);
        }
Exemple #33
0
        private static void StartRecording(ScreenRecordOutput outputType, TaskSettings taskSettings, ScreenRecordStartMethod startMethod = ScreenRecordStartMethod.Region)
        {
            string debugText;

            if (outputType == ScreenRecordOutput.FFmpeg)
            {
                debugText = string.Format("Starting FFmpeg recording. Video encoder: \"{0}\", Audio encoder: \"{1}\", FPS: {2}",
                                          taskSettings.CaptureSettings.FFmpegOptions.VideoCodec.GetDescription(), taskSettings.CaptureSettings.FFmpegOptions.AudioCodec.GetDescription(),
                                          taskSettings.CaptureSettings.ScreenRecordFPS);
            }
            else
            {
                debugText = string.Format("Starting Animated GIF recording. GIF encoding: \"{0}\", FPS: {1}",
                                          taskSettings.CaptureSettings.GIFEncoding.GetDescription(), taskSettings.CaptureSettings.GIFFPS);
            }

            DebugHelper.WriteLine(debugText);

            if (taskSettings.CaptureSettings.RunScreencastCLI)
            {
                if (!Program.Settings.VideoEncoders.IsValidIndex(taskSettings.CaptureSettings.VideoEncoderSelected))
                {
                    MessageBox.Show(Resources.ScreenRecordForm_StartRecording_There_is_no_valid_CLI_video_encoder_selected_,
                                    "ShareX", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (!Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected].IsValid())
                {
                    MessageBox.Show(Resources.ScreenRecordForm_StartRecording_CLI_video_encoder_file_does_not_exist__ +
                                    Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected].Path,
                                    "ShareX", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            if (outputType == ScreenRecordOutput.GIF && taskSettings.CaptureSettings.GIFEncoding == ScreenRecordGIFEncoding.FFmpeg)
            {
                outputType = ScreenRecordOutput.FFmpeg;
                taskSettings.CaptureSettings.FFmpegOptions.VideoCodec        = FFmpegVideoCodec.gif;
                taskSettings.CaptureSettings.FFmpegOptions.UseCustomCommands = false;
            }

            if (outputType == ScreenRecordOutput.FFmpeg)
            {
                if (!TaskHelpers.CheckFFmpeg(taskSettings))
                {
                    return;
                }

                if (!taskSettings.CaptureSettings.FFmpegOptions.IsSourceSelected)
                {
                    MessageBox.Show(Resources.ScreenRecordForm_StartRecording_FFmpeg_video_and_audio_source_both_can_t_be__None__,
                                    "ShareX - " + Resources.ScreenRecordForm_StartRecording_FFmpeg_error, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            Rectangle captureRectangle = Rectangle.Empty;

            switch (startMethod)
            {
            case ScreenRecordStartMethod.Region:
                TaskHelpers.SelectRegion(out captureRectangle, taskSettings);
                break;

            case ScreenRecordStartMethod.ActiveWindow:
                if (taskSettings.CaptureSettings.CaptureClientArea)
                {
                    captureRectangle = CaptureHelpers.GetActiveWindowClientRectangle();
                }
                else
                {
                    captureRectangle = CaptureHelpers.GetActiveWindowRectangle();
                }
                break;

            case ScreenRecordStartMethod.LastRegion:
                captureRectangle = Program.Settings.ScreenRecordRegion;
                break;
            }

            captureRectangle = CaptureHelpers.EvenRectangleSize(captureRectangle);

            if (IsRecording || !captureRectangle.IsValid() || screenRecorder != null)
            {
                return;
            }

            Program.Settings.ScreenRecordRegion = captureRectangle;

            IsRecording = true;

            Screenshot.CaptureCursor = taskSettings.CaptureSettings.ScreenRecordShowCursor;

            string path           = "";
            bool   abortRequested = false;

            float duration = taskSettings.CaptureSettings.ScreenRecordFixedDuration ? taskSettings.CaptureSettings.ScreenRecordDuration : 0;

            recordForm = new ScreenRecordForm(captureRectangle, startMethod == ScreenRecordStartMethod.Region, duration);
            recordForm.StopRequested += StopRecording;
            recordForm.Show();

            TaskEx.Run(() =>
            {
                try
                {
                    if (outputType == ScreenRecordOutput.FFmpeg)
                    {
                        path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, taskSettings.CaptureSettings.FFmpegOptions.Extension));
                    }
                    else
                    {
                        path = Program.ScreenRecorderCacheFilePath;
                    }

                    ScreencastOptions options = new ScreencastOptions()
                    {
                        FFmpeg          = taskSettings.CaptureSettings.FFmpegOptions,
                        ScreenRecordFPS = taskSettings.CaptureSettings.ScreenRecordFPS,
                        GIFFPS          = taskSettings.CaptureSettings.GIFFPS,
                        Duration        = duration,
                        OutputPath      = path,
                        CaptureArea     = captureRectangle,
                        DrawCursor      = taskSettings.CaptureSettings.ScreenRecordShowCursor
                    };

                    recordForm.ChangeState(ScreenRecordState.BeforeStart);

                    if (taskSettings.CaptureSettings.ScreenRecordAutoStart)
                    {
                        int delay = (int)(taskSettings.CaptureSettings.ScreenRecordStartDelay * 1000);

                        if (delay > 0)
                        {
                            recordForm.InvokeSafe(() => recordForm.StartCountdown(delay));

                            recordForm.RecordResetEvent.WaitOne(delay);
                        }
                    }
                    else
                    {
                        recordForm.RecordResetEvent.WaitOne();
                    }

                    if (recordForm.AbortRequested)
                    {
                        abortRequested = true;
                    }

                    if (!abortRequested)
                    {
                        screenRecorder = new ScreenRecorder(outputType, options, captureRectangle);
                        screenRecorder.RecordingStarted += () => recordForm.ChangeState(ScreenRecordState.AfterRecordingStart);
                        recordForm.ChangeState(ScreenRecordState.AfterStart);
                        screenRecorder.StartRecording();

                        if (recordForm.AbortRequested)
                        {
                            abortRequested = true;
                        }
                    }
                }
                catch (Exception e)
                {
                    DebugHelper.WriteException(e);
                }

                try
                {
                    if (!abortRequested && screenRecorder != null)
                    {
                        recordForm.ChangeState(ScreenRecordState.AfterStop);

                        if (outputType == ScreenRecordOutput.GIF)
                        {
                            path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, "gif"));
                            screenRecorder.EncodingProgressChanged += progress => recordForm.ChangeStateProgress(progress);
                            GIFQuality gifQuality = taskSettings.CaptureSettings.GIFEncoding == ScreenRecordGIFEncoding.OctreeQuantizer ? GIFQuality.Bit8 : GIFQuality.Default;
                            screenRecorder.SaveAsGIF(path, gifQuality);
                        }
                        else if (outputType == ScreenRecordOutput.FFmpeg && taskSettings.CaptureSettings.FFmpegOptions.VideoCodec == FFmpegVideoCodec.gif)
                        {
                            path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, "gif"));
                            screenRecorder.FFmpegEncodeAsGIF(path);
                        }

                        if (taskSettings.CaptureSettings.RunScreencastCLI)
                        {
                            VideoEncoder encoder  = Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected];
                            string sourceFilePath = path;
                            path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, encoder.OutputExtension));
                            screenRecorder.EncodeUsingCommandLine(encoder, sourceFilePath, path);
                        }
                    }
                }
                finally
                {
                    if (recordForm != null)
                    {
                        recordForm.InvokeSafe(() =>
                        {
                            recordForm.Close();
                            recordForm.Dispose();
                            recordForm = null;
                        });
                    }

                    if (screenRecorder != null)
                    {
                        if ((outputType == ScreenRecordOutput.GIF || taskSettings.CaptureSettings.RunScreencastCLI ||
                             (outputType == ScreenRecordOutput.FFmpeg && taskSettings.CaptureSettings.FFmpegOptions.VideoCodec == FFmpegVideoCodec.gif)) &&
                            !string.IsNullOrEmpty(screenRecorder.CachePath) && File.Exists(screenRecorder.CachePath))
                        {
                            File.Delete(screenRecorder.CachePath);
                        }

                        screenRecorder.Dispose();
                        screenRecorder = null;

                        if (abortRequested && !string.IsNullOrEmpty(path) && File.Exists(path))
                        {
                            File.Delete(path);
                        }
                    }
                }
            },
                       () =>
            {
                string customFileName;

                if (!abortRequested && !string.IsNullOrEmpty(path) && File.Exists(path) && TaskHelpers.ShowAfterCaptureForm(taskSettings, out customFileName))
                {
                    WorkerTask task = WorkerTask.CreateFileJobTask(path, taskSettings, customFileName);
                    TaskManager.Start(task);
                }

                abortRequested = false;
                IsRecording    = false;
            });
        }
Exemple #34
0
        public Form1()
        {
            PascalABCCompiler.StringResourcesLanguage.LoadDefaultConfig();
            if (PascalABCCompiler.StringResourcesLanguage.AccessibleLanguages.Count > 0)
                PascalABCCompiler.StringResourcesLanguage.CurrentLanguageName = PascalABCCompiler.StringResourcesLanguage.AccessibleLanguages[0];
           
            InitializeComponent();
            InitForm();
            AddOwnedForm(CompileOptionsForm1 = new CompileOptionsForm());
            AddOwnedForm(UserOptionsForm1 = new UserOptionsForm());
            AddOwnedForm(CompilerForm1 = new CompilerForm());
            AddOwnedForm(AboutBox1 = new AboutBox());
            AddOwnedForm(FindForm = new FindReplaceForm(FindReplaceForm.FormType.Find));
            AddOwnedForm(ReplaceForm = new FindReplaceForm(FindReplaceForm.FormType.Replace));
            CompilerOptions1 = new PascalABCCompiler.CompilerOptions();
            CompilerOptions1.Debug = true;
            LastOpenFiles = new List<string>();

            RunProcessOptions1 = new RunProcessOptions();
            

            CompilerOptions1.OutputFileType = PascalABCCompiler.CompilerOptions.OutputType.ConsoleApplicaton;


            Form1StringResources.SetTextForAllControls(this);
            Form1StringResources.SetTextForAllControls(this.contextMenuStrip1);
            Form1StringResources.SetTextForAllControls(this.cmEditor);
            PascalABCCompiler.StringResources.SetTextForAllObjects(UserOptionsForm1, "VP_OPTFORM_");
            PascalABCCompiler.StringResources.SetTextForAllObjects(CompileOptionsForm1, "VP_COMPOPTFORM_");
            PascalABCCompiler.StringResources.SetTextForAllObjects(AboutBox1, "VP_ABOUTBOXFORM_");
            PascalABCCompiler.StringResources.SetTextForAllObjects(FindForm, "VP_FINDFORM_");
            PascalABCCompiler.StringResources.SetTextForAllObjects(ReplaceForm, "VP_REPLACEFORM_");

            tsatConsoleApplication.Tag = PascalABCCompiler.CompilerOptions.OutputType.ConsoleApplicaton;
            tsatWindowsApplication.Tag = PascalABCCompiler.CompilerOptions.OutputType.WindowsApplication;
            tsatDll.Tag = PascalABCCompiler.CompilerOptions.OutputType.ClassLibrary;

            SelectAppType(CompilerOptions1.OutputFileType);

            //ivan
            dbgHelper = new DebugHelper(this);
            //\ivan
            //this.dataGridView1.MinimumSize = new Size(0, Screen.PrimaryScreen.WorkingArea.Height);

        }
Exemple #35
0
        public void StartRecording(ScreenRecordOutput outputType, TaskSettings taskSettings, ScreenRecordStartMethod startMethod = ScreenRecordStartMethod.Region)
        {
            string debugText;

            if (outputType == ScreenRecordOutput.FFmpeg)
            {
                debugText = string.Format("Starting FFmpeg recording. Video encoder: \"{0}\", Audio encoder: \"{1}\", FPS: {2}",
                                          taskSettings.CaptureSettings.FFmpegOptions.VideoCodec.GetDescription(), taskSettings.CaptureSettings.FFmpegOptions.AudioCodec.GetDescription(),
                                          taskSettings.CaptureSettings.ScreenRecordFPS);
            }
            else
            {
                debugText = string.Format("Starting Animated GIF recording. GIF encoding: \"{0}\", FPS: {1}",
                                          taskSettings.CaptureSettings.GIFEncoding.GetDescription(), taskSettings.CaptureSettings.GIFFPS);
            }

            DebugHelper.WriteLine(debugText);

            if (taskSettings.CaptureSettings.RunScreencastCLI)
            {
                if (!Program.Settings.VideoEncoders.IsValidIndex(taskSettings.CaptureSettings.VideoEncoderSelected))
                {
                    MessageBox.Show(Resources.ScreenRecordForm_StartRecording_There_is_no_valid_CLI_video_encoder_selected_,
                                    "ShareX", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (!Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected].IsValid())
                {
                    MessageBox.Show(Resources.ScreenRecordForm_StartRecording_CLI_video_encoder_file_does_not_exist__ +
                                    Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected].Path,
                                    "ShareX", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            if (outputType == ScreenRecordOutput.GIF && taskSettings.CaptureSettings.GIFEncoding == ScreenRecordGIFEncoding.FFmpeg)
            {
                outputType = ScreenRecordOutput.FFmpeg;
                taskSettings.CaptureSettings.FFmpegOptions.VideoCodec = FFmpegVideoCodec.gif;
            }

            if (outputType == ScreenRecordOutput.FFmpeg)
            {
                if (!File.Exists(taskSettings.CaptureSettings.FFmpegOptions.CLIPath))
                {
                    string ffmpegText = string.IsNullOrEmpty(taskSettings.CaptureSettings.FFmpegOptions.CLIPath) ? "ffmpeg.exe" : taskSettings.CaptureSettings.FFmpegOptions.CLIPath;

                    if (MessageBox.Show(string.Format(Resources.ScreenRecordForm_StartRecording_does_not_exist, ffmpegText),
                                        "ShareX - " + Resources.ScreenRecordForm_StartRecording_Missing + " ffmpeg.exe", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                    {
                        if (FFmpegDownloader.DownloadFFmpeg(false, DownloaderForm_InstallRequested) == DialogResult.OK)
                        {
                            Program.DefaultTaskSettings.CaptureSettings.FFmpegOptions.CLIPath = taskSettings.TaskSettingsReference.CaptureSettings.FFmpegOptions.CLIPath =
                                taskSettings.CaptureSettings.FFmpegOptions.CLIPath            = Path.Combine(Program.ToolsFolder, "ffmpeg.exe");
                        }
                    }
                    else
                    {
                        return;
                    }
                }

                if (!taskSettings.CaptureSettings.FFmpegOptions.IsSourceSelected)
                {
                    MessageBox.Show(Resources.ScreenRecordForm_StartRecording_FFmpeg_video_and_audio_source_both_can_t_be__None__,
                                    "ShareX - " + Resources.ScreenRecordForm_StartRecording_FFmpeg_error, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            Rectangle captureRectangle = Rectangle.Empty;

            switch (startMethod)
            {
            case ScreenRecordStartMethod.Region:
                TaskHelpers.SelectRegion(out captureRectangle, taskSettings);
                break;

            case ScreenRecordStartMethod.ActiveWindow:
                if (taskSettings.CaptureSettings.CaptureClientArea)
                {
                    captureRectangle = CaptureHelpers.GetActiveWindowClientRectangle();
                }
                else
                {
                    captureRectangle = CaptureHelpers.GetActiveWindowRectangle();
                }
                break;

            case ScreenRecordStartMethod.LastRegion:
                captureRectangle = Program.Settings.ScreenRecordRegion;
                break;
            }

            captureRectangle = CaptureHelpers.EvenRectangleSize(captureRectangle);

            if (IsRecording || !captureRectangle.IsValid() || screenRecorder != null)
            {
                return;
            }

            Program.Settings.ScreenRecordRegion = captureRectangle;

            IsRecording = true;

            Screenshot.CaptureCursor = taskSettings.CaptureSettings.ShowCursor;

            string trayText = "ShareX - " + Resources.ScreenRecordForm_StartRecording_Waiting___;

            TrayIcon.Text    = trayText.Truncate(63);
            TrayIcon.Icon    = Resources.control_record_yellow.ToIcon();
            TrayIcon.Visible = true;

            string path = "";

            float duration = taskSettings.CaptureSettings.ScreenRecordFixedDuration ? taskSettings.CaptureSettings.ScreenRecordDuration : 0;

            regionForm = ScreenRegionForm.Show(captureRectangle, StopRecording, startMethod == ScreenRecordStartMethod.Region, duration);
            regionForm.RecordResetEvent = new ManualResetEvent(false);

            TaskEx.Run(() =>
            {
                try
                {
                    if (outputType == ScreenRecordOutput.FFmpeg)
                    {
                        path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, taskSettings.CaptureSettings.FFmpegOptions.Extension));
                    }
                    else
                    {
                        path = Program.ScreenRecorderCacheFilePath;
                    }

                    ScreencastOptions options = new ScreencastOptions()
                    {
                        FFmpeg          = taskSettings.CaptureSettings.FFmpegOptions,
                        ScreenRecordFPS = taskSettings.CaptureSettings.ScreenRecordFPS,
                        GIFFPS          = taskSettings.CaptureSettings.GIFFPS,
                        Duration        = duration,
                        OutputPath      = path,
                        CaptureArea     = captureRectangle,
                        DrawCursor      = taskSettings.CaptureSettings.ShowCursor
                    };

                    screenRecorder = new ScreenRecorder(outputType, options, captureRectangle);

                    if (regionForm != null && regionForm.RecordResetEvent != null)
                    {
                        trayText      = "ShareX - " + Resources.ScreenRecordForm_StartRecording_Click_tray_icon_to_start_recording_;
                        TrayIcon.Text = trayText.Truncate(63);

                        if (taskSettings.CaptureSettings.ScreenRecordAutoStart)
                        {
                            int delay = (int)(taskSettings.CaptureSettings.ScreenRecordStartDelay * 1000);

                            if (delay > 0)
                            {
                                regionForm.InvokeSafe(() => regionForm.StartCountdown(delay));

                                regionForm.RecordResetEvent.WaitOne(delay);
                            }
                        }
                        else
                        {
                            regionForm.RecordResetEvent.WaitOne();
                        }

                        if (regionForm.AbortRequested)
                        {
                            abortRequested = true;
                        }
                    }

                    if (!abortRequested)
                    {
                        trayText      = "ShareX - " + Resources.ScreenRecordForm_StartRecording_Click_tray_icon_to_stop_recording_;
                        TrayIcon.Text = trayText.Truncate(63);
                        TrayIcon.Icon = Resources.control_record.ToIcon();

                        if (regionForm != null)
                        {
                            regionForm.InvokeSafe(() => regionForm.StartRecordingTimer(duration > 0, duration));
                        }

                        screenRecorder.StartRecording();

                        if (regionForm != null && regionForm.AbortRequested)
                        {
                            abortRequested = true;
                        }
                    }
                }
                catch (Exception e)
                {
                    DebugHelper.WriteException(e);
                }
                finally
                {
                    if (regionForm != null)
                    {
                        if (regionForm.RecordResetEvent != null)
                        {
                            regionForm.RecordResetEvent.Dispose();
                        }

                        regionForm.InvokeSafe(() => regionForm.Close());
                        regionForm = null;
                    }
                }

                try
                {
                    if (!abortRequested && screenRecorder != null)
                    {
                        TrayIcon.Text = "ShareX - " + Resources.ScreenRecordForm_StartRecording_Encoding___;
                        TrayIcon.Icon = Resources.camcorder_pencil.ToIcon();

                        if (outputType == ScreenRecordOutput.GIF)
                        {
                            path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, "gif"));
                            screenRecorder.EncodingProgressChanged += progress => TrayIcon.Text = string.Format("ShareX - {0} ({1}%)", Resources.ScreenRecordForm_StartRecording_Encoding___, progress);
                            GIFQuality gifQuality = taskSettings.CaptureSettings.GIFEncoding == ScreenRecordGIFEncoding.OctreeQuantizer ? GIFQuality.Bit8 : GIFQuality.Default;
                            screenRecorder.SaveAsGIF(path, gifQuality);
                        }
                        else if (outputType == ScreenRecordOutput.FFmpeg && taskSettings.CaptureSettings.FFmpegOptions.VideoCodec == FFmpegVideoCodec.gif)
                        {
                            path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, "gif"));
                            screenRecorder.FFmpegEncodeAsGIF(path);
                        }

                        if (taskSettings.CaptureSettings.RunScreencastCLI)
                        {
                            VideoEncoder encoder  = Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected];
                            string sourceFilePath = path;
                            path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, encoder.OutputExtension));
                            screenRecorder.EncodeUsingCommandLine(encoder, sourceFilePath, path);
                        }
                    }
                }
                finally
                {
                    if (screenRecorder != null)
                    {
                        if ((outputType == ScreenRecordOutput.GIF || taskSettings.CaptureSettings.RunScreencastCLI ||
                             (outputType == ScreenRecordOutput.FFmpeg && taskSettings.CaptureSettings.FFmpegOptions.VideoCodec == FFmpegVideoCodec.gif)) &&
                            !string.IsNullOrEmpty(screenRecorder.CachePath) && File.Exists(screenRecorder.CachePath))
                        {
                            File.Delete(screenRecorder.CachePath);
                        }

                        screenRecorder.Dispose();
                        screenRecorder = null;

                        if (abortRequested && !string.IsNullOrEmpty(path) && File.Exists(path))
                        {
                            File.Delete(path);
                        }
                    }
                }
            },
                       () =>
            {
                if (TrayIcon.Visible)
                {
                    TrayIcon.Visible = false;
                }

                if (!abortRequested && !string.IsNullOrEmpty(path) && File.Exists(path) && TaskHelpers.ShowAfterCaptureForm(taskSettings))
                {
                    UploadTask task = UploadTask.CreateFileJobTask(path, taskSettings);
                    TaskManager.Start(task);
                }

                abortRequested = false;
                IsRecording    = false;
            });
        }