Example #1
0
    public static void Init()
    {
        // Gets the existing version of this window or creates a new one, then show it
        AutoSaver _instance = (AutoSaver)GetWindow(typeof(AutoSaver));

        _instance.Show();
    }
Example #2
0
        private void OnAutoSave(object sender, EventArgs e)
        {
            if (AutoSaver == null)
            {
                return;
            }

            var template = sender as RazorTemplateViewModel ?? CurrentTemplate;

            if (template == null)
            {
                return;
            }

            new TaskFactory().StartNew(() => {
                try
                {
                    AutoSaver.Save(template.Document);
                    Log.Info("Auto-Saved the document for you -- you can thank me later.");
                }
                catch (Exception ex)
                {
                    Log.WarnException("Auto-save failed", ex);
                }
            });
        }
Example #3
0
    static void Init()
    {
        AutoSaver window = (AutoSaver)GetWindowWithRect(
            typeof(AutoSaver),
            new Rect(0, 0, 160, 60));

        window.Show();
    }
Example #4
0
        /// <summary>
        /// Wird aufgerufen, wenn die Ausführung der Anwendung angehalten wird.  Der Anwendungszustand wird gespeichert,
        /// ohne zu wissen, ob die Anwendung beendet oder fortgesetzt wird und die Speicherinhalte dabei
        /// unbeschädigt bleiben.
        /// </summary>
        /// <param name="sender">Die Quelle der Anhalteanforderung.</param>
        /// <param name="e">Details zur Anhalteanforderung.</param>
        private async void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();
            //TODO: Anwendungszustand speichern und alle Hintergrundaktivitäten beenden

            await AutoSaver.SaveAsync();

            deferral.Complete();
        }
Example #5
0
        public void Handle(AutoSaveRecoveryEvent message)
        {
            _autoSaveRecoveryIndex = message.AutoSaveMasterIndex;

            if (!message.RecoveryInProgress)
            {
                // if auto save recovery is not already in progress
                // prompt the user for which files should be recovered
                var autoSaveRecoveryDialog = new AutoSaveRecoveryDialogViewModel();

                var filesToRecover = message.AutoSaveMasterIndex.Values.Where(i => i.ShouldRecover && i.IsCurrentVersion).SelectMany(entry => entry.Files);

                if (filesToRecover.Count() == 0)
                {
                    // if there are no files to recover then clean up
                    // the recovery folder and exit here
                    AutoSaver.CleanUpRecoveredFiles();
                    return;
                }

                autoSaveRecoveryDialog.Files = new ObservableCollection <AutoSaveIndexEntry>(filesToRecover);

                _windowManager.ShowDialogBox(autoSaveRecoveryDialog, settings: new Dictionary <string, object>
                {
                    { "WindowStyle", WindowStyle.None },
                    { "ShowInTaskbar", false },
                    { "ResizeMode", ResizeMode.NoResize },
                    { "Background", System.Windows.Media.Brushes.Transparent },
                    { "AllowsTransparency", true }
                });

                if (autoSaveRecoveryDialog.Result != OpenDialogResult.Cancel)
                {
                    message.RecoveryInProgress = true;

                    var fileToOpen = _autoSaveRecoveryIndex.Values.Where(i => i.ShouldRecover).FirstOrDefault().Files.Where(x => x.ShouldOpen).FirstOrDefault();

                    if (fileToOpen != null)
                    {
                        // the first file will mark itself as opened then re-publish the message
                        // to open the next file (if there is one)
                        RecoverAutoSaveFile(fileToOpen);
                    }
                }
                else
                {
                    // if recovery has been cancelled open a new blank document
                    NewQueryDocument("");
                    // and remove unwanted recovery files
                    AutoSaver.CleanUpRecoveredFiles();
                }
            }

            // TODO - maybe move this to a RecoverNextFile message and store the files to recover in a private var
            //        then at the end of the ViewLoaded event we can trigger this event and run code like the
            //        section below
        }
Example #6
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AutoSaver obj = new AutoSaver(10);

            Task.Factory.StartNew(() => { obj.StartSaving(); });
        }
Example #7
0
    /// <summary>
    /// Continues the evolution from the save state.
    ///
    /// This function call has to replace calls to StartEvolution (and therefore also SetupEvolution) when a simulation would be started
    /// from the beginning.
    ///
    /// </summary>
    /// <param name="generationNum">The generation number that the simulation should continue at from.</param>
    /// <param name="timePerGen">The time for each generation simulation.</param>
    /// <param name="bestChromosomes">The list of best chromosomes of the already simluated generations.</param>
    /// <param name="currentChromosomes">A list of chromosomes of creatures of the last (current) generation.</param>
    //public void ContinueEvolution(int generationNum, int timePerGen, List<ChromosomeInfo> bestChromosomes, List<string> currentChromosomes) {
    public void ContinueEvolution(int generationNum, EvolutionSettings evolutionSettings, NeuralNetworkSettings networkSettings, List <ChromosomeStats> bestChromosomes, List <string> currentChromosomes)
    {
        this.settings      = evolutionSettings;
        this.brainSettings = networkSettings;

        viewController = GameObject.Find("ViewController").GetComponent <ViewController>();
        Assert.IsNotNull(viewController);

        this.currentGenerationNumber = generationNum;
        this.currentChromosomes      = currentChromosomes.ToArray();

        creature.RemoveMuscleColliders();
        creature.Alive = false;
        running        = true;

        viewController.UpdateGeneration(generationNum);

        autoSaver = new AutoSaver();

        // Setup Evolution call
        CalculateDropHeight();

        BCController            = GameObject.Find("Best Creature Controller").GetComponent <BestCreaturesController>();
        BCController.dropHeight = dropHeight;
        BCController.Creature   = creature;

        BCController.SetBestChromosomes(bestChromosomes);
        BCController.ShowBCThumbScreen();
        BCController.RunBestCreatures(generationNum - 1);

        currentGeneration = CreateGeneration();

        // Batch simulation
        currentlySimulatingBatch = 1;
        simulateInBatchesCached  = settings.simulateInBatches;
        batchSizeCached          = settings.simulateInBatches ? settings.batchSize : settings.populationSize;
        var currentBatchSize = Mathf.Min(batchSizeCached, settings.populationSize - ((currentlySimulatingBatch - 1) * batchSizeCached));

        currentCreatureBatch = new Creature[currentBatchSize];

        Array.Copy(currentGeneration, 0, currentCreatureBatch, 0, currentBatchSize);

        creature.gameObject.SetActive(false);

        SimulateGeneration();

        var cameraFollow = Camera.main.GetComponent <CameraFollowScript>();

        cameraFollow.toFollow = currentGeneration[0];
        cameraFollow.currentlyWatchingIndex = 0;

        RefreshVisibleCreatures();
    }
Example #8
0
 public async Task Stop()
 {
     autoSaverCancelTokenSource.Cancel();
     Logger.LogInfo("Disconnecting...");
     if (client != null && (client.ConnectionState == Discord.ConnectionState.Connected || client.ConnectionState == Discord.ConnectionState.Connecting))
     {
         await client.StopAsync();
     }
     Logger.LogInfo("Saving settings...");
     AutoSaver.SaveAll();
     Logger.LogInfo("Stopped succesfully!");
 }
Example #9
0
 public override void TryClose(bool?dialogResult = null)
 {
     //Properties.Settings.Default.Save();
     base.TryClose(dialogResult);
     if (dialogResult != false)
     {
         Ribbon.OnClose();
         notifyIcon?.Dispose();
         AutoSaveTimer.Enabled = false;
         AutoSaver.RemoveAll();
     }
 }
Example #10
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (e.Parameter is Simulation handedSimulation)
            {
                Simulation = handedSimulation;
            }

            Bindings.Update();

            AutoSaver.Subscribe(this.Simulation);
        }
Example #11
0
 private void AppBarToggleButton_AutoSave_Click(object sender, RoutedEventArgs e)
 {
     if ((bool)AppBarToggleButton_AutoSave.IsChecked)
     {
         InfoBar_DraftModus.IsOpen = false;
         AutoSaver.Subscribe(this.Simulation);
     }
     else
     {
         InfoBar_DraftModus.IsOpen = true;
         AutoSaver.Subscribe(null);
     }
 }
Example #12
0
 private async void AutoSaveTimerElapsed(object sender, ElapsedEventArgs e)
 {
     try
     {
         await AutoSaver.Save(Tabs);
     }
     catch (Exception ex)
     {
         // we just catch and log any errors, we don't want the autosave timer to be
         // the cause of any crashes itself
         Log.Error(ex, "{class} {method} {message}", "ShellViewModel", "AutoSaveTimerElapsed", ex.Message);
     }
 }
Example #13
0
    void Awake()
    {
        if (instance != null)
        {
            Destroy(gameObject);
            return;
        }

        instance = this;

        DontDestroyOnLoad(gameObject);

        GameManager.OnReloadStage += GameManager_OnReloadStage;
    }
Example #14
0
 public override void TryClose(bool?dialogResult = null)
 {
     //Properties.Settings.Default.Save();
     base.TryClose(dialogResult);
     if (dialogResult != false)
     {
         Ribbon.OnClose();
         notifyIcon?.Dispose();
         AutoSaveTimer.Enabled = false;
         if (!Application.Current.Properties.Contains("HasCrashed"))
         {
             AutoSaver.RemoveAll();
         }
     }
 }
Example #15
0
    public void Use()
    {
        if (used)
        {
            return;
        }
        used = true;
        var otherPlayerCharacter = PlayerCharacter.localPlayer;

        SceneInitializer.instance.inside = false;
        otherPlayerCharacter.GetComponent <AutoSaver>().SaveCharacter();
        saveBlocker = otherPlayerCharacter.GetComponent <AutoSaver>();
        otherPlayerCharacter.litArea = true;
        onWayOut = true;
    }
Example #16
0
        public void LoadAutoSave()
        {
            try
            {
                var template = AutoSaver.Load();

                if (template != null)
                {
                    AddNewTemplateEditor(template);
                }
            }
            catch (Exception ex)
            {
                Log.WarnException("Auto-save file found, but there was an error loading it.", ex);
            }
        }
Example #17
0
    public void Use()
    {
        //if (!NetworkServer.active) return;
        if (used)
        {
            return;
        }
        used = true;
        var otherPlayerCharacter = PlayerCharacter.localPlayer;

        otherPlayerCharacter.configLoaded = false;
        SceneInitializer.instance.inside  = true;
        otherPlayerCharacter.litArea      = false;
        otherPlayerCharacter.GetComponent <AutoSaver>().SaveCharacter();
        saveBlocker = otherPlayerCharacter.GetComponent <AutoSaver>();
        onWayUp     = true;
    }
    public void Use()
    {
        if (used)
        {
            return;
        }
        used = true;
        var otherPlayerCharacter = PlayerCharacter.localPlayer;

        SceneInitializer.instance.inside = true;
        LevelGen.targetLevel             = dungeonLevel;
        LevelGen.settingLevel            = true;
        LevelGen.dungeonData             = dungeonData;
        otherPlayerCharacter.GetComponent <AutoSaver>().SaveCharacter();
        saveBlocker = otherPlayerCharacter.GetComponent <AutoSaver>();
        otherPlayerCharacter.litArea = true;
        onWayDown = true;
    }
Example #19
0
 public void Use()
 {
     //if (!NetworkServer.active) return;
     if (used)
     {
         return;
     }
     used = true;
     //PlayerCharacter.localPlayer.configLoaded = false;
     //InitializeLevel.currentFloor += 1;
     //InitializeLevel.instance.CmdSetTargetLevel(InitializeLevel.targetLevel);
     //InitializeLevel.instance.CmdSetCurrentFloor(InitializeLevel.currentFloor);
     //InitializeLevel.SetStartingPosition();
     //InitializeLevel.goingDown = true;
     //InitializeLevel.ClearObjectLists();
     PlayerCharacter.localPlayer.GetComponent <AutoSaver>().SaveCharacter();
     saveBlocker     = PlayerCharacter.localPlayer.GetComponent <AutoSaver>();
     onWayDownstairs = true;
 }
Example #20
0
        public string SaveAs(RazorTemplateViewModel document, string filename = null)
        {
            try
            {
                if (filename == null)
                {
                    Log.Debug("Filename was null -- triggering SaveAs...");
                    filename = GetSaveAsFilenameThunk(document);
                }

                if (string.IsNullOrWhiteSpace(filename))
                {
                    Log.Warn("Filename is empty - skipping save");
                    return(filename);
                }

                Log.Debug("Saving document to {0}...", filename);

                _documentManager.Save(document.Document, filename);

                Log.Info("Document saved to {0}", filename);

                document.Filename = filename;

                if (!string.IsNullOrWhiteSpace(filename))
                {
                    RecentFiles.Add(filename);
                }

                if (AutoSaver != null)
                {
                    AutoSaver.Clear();
                }
            }
            catch (Exception ex)
            {
                Log.ErrorException("Error saving document", ex);
                Error.SafeInvoke(ex.Message);
            }

            return(filename);
        }
Example #21
0
        public TamaChan()
        {
            Instance                = this;
            Logger                  = new Logger("Main");
            AutoSaver               = new AutoSaver();
            botSettings             = new BotSettings().LoadFromFile() as BotSettings;
            Logger.allowSystemBeeps = botSettings.allowErrorBeeps;
            Logger.ignoreDebug      = !botSettings.printDebugLogs;
            client                  = new DiscordSocketClient();
            EventSystem             = new EventSystem(client);
            ModuleRegistry          = new ModuleRegistry();
            CommandRegistry         = new CommandRegistry();
            ModuleRegistry.RegisterModules();

            autoSaverCancelTokenSource = new CancellationTokenSource();
            CancellationToken cancellationToken = autoSaverCancelTokenSource.Token;

            Task.Run(() => AutoSaver.Run(cancellationToken), cancellationToken);

            Logger.LogInfo($"TamaChanBot Version \"{VERSION}\" instantiated.");
        }
Example #22
0
    private void SetupEvolution()
    {
        CalculateDropHeight();

        BCController            = GameObject.Find("Best Creature Controller").GetComponent <BestCreaturesController>();
        BCController.dropHeight = dropHeight;
        BCController.Creature   = creature;

        // The first generation will have random brains.
        currentGeneration = CreateCreatures();
        ApplyBrains(currentGeneration, true);


        // Batch simulation
        currentlySimulatingBatch = 1;
        simulateInBatchesCached  = settings.simulateInBatches;
        batchSizeCached          = settings.simulateInBatches ? settings.batchSize : settings.populationSize;
        var currentBatchSize = Mathf.Min(batchSizeCached, settings.populationSize - ((currentlySimulatingBatch - 1) * batchSizeCached));

        currentCreatureBatch = new Creature[currentBatchSize];
        Array.Copy(currentGeneration, 0, currentCreatureBatch, 0, currentBatchSize);

        SimulateGeneration();

        creature.gameObject.SetActive(false);

        var cameraFollow = Camera.main.GetComponent <CameraFollowScript>();

        cameraFollow.toFollow = currentGeneration[0];
        cameraFollow.currentlyWatchingIndex = 0;

        RefreshVisibleCreatures();

        viewController.UpdateGeneration(currentGenerationNumber);

        autoSaver = new AutoSaver();
    }
Example #23
0
        private async void AutoSaveTimerElapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                // disable the timer while we are saving, so that if access to the UI thread is
                // blocked and we cannot read the contents of the editor controls we do not keep
                // firing access denied errors on the autosave file. Once the UI thread is free
                // the initial request will continue and the timer will be re-enabled.

                AutoSaveTimer.Enabled = false;

                await AutoSaver.Save(Tabs).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                // we just catch and log any errors, we don't want the autosave timer to be
                // the cause of any crashes itself
                Log.Error(ex, "{class} {method} {message}", "ShellViewModel", "AutoSaveTimerElapsed", ex.Message);
            }
            finally
            {
                AutoSaveTimer.Enabled = true;
            }
        }
Example #24
0
        public void Handle(RecoverNextAutoSaveFileEvent message)
        {
            var fileToOpen = _autoSaveRecoveryIndex.Values.Where(i => i.ShouldRecover).FirstOrDefault().Files.Where(x => x.ShouldOpen).FirstOrDefault();

            if (fileToOpen != null)
            {
                // the first file will mark itself as opened then re-publish the message
                // to open the next file (if there is one)
                RecoverAutoSaveFile(fileToOpen);
            }
            else
            {
                // if no files have been opened open a new blank document
                if (Items.Count == 0)
                {
                    OpenNewBlankDocument(null);
                }

                AutoSaver.CleanUpRecoveredFiles();

                // Now that any files have been recovered start the auto save timer
                _eventAggregator.PublishOnUIThreadAsync(new StartAutoSaveTimerEvent());
            }
        }
Example #25
0
 public void Handle(AutoSaveEvent message)
 {
     AutoSaver.Save(Tabs).AsResult();
 }
Example #26
0
        private async void Page_Unloaded(object sender, RoutedEventArgs e)
        {
            await AutoSaver.SaveAsync();

            AutoSaver.Subscribe(null);
        }
Example #27
0
    void OnGUI()
    {
        #region AutoSaver button
        if (GUILayout.Button((AutoSaver.IsEnabled) ? "AutoSaver: ON" : "AutoSaver: OFF"))
        {
            if (AutoSaver.IsEnabled)
            {
                AutoSaver.DeactivateAutosaver();
            }
            else
            {
                AutoSaver.ActivateAutosaver();
            }
        }
        #endregion
        #region AutoSaver Debug button
        if (GUILayout.Button((AutoSaver.IsDebugEnabled) ? "AutoSaver Debug: ON" : "AutoSaver Debug: OFF"))
        {
            if (AutoSaver.IsDebugEnabled)
            {
                AutoSaver.IsDebugEnabled = false;
            }
            else
            {
                AutoSaver.IsDebugEnabled = true;
            }
        }
        #endregion

        #region Assets saver and Save on play buttons
        EditorGUILayout.BeginHorizontal();

        EditorGUILayout.BeginVertical();
        if (GUILayout.Button((AutoSaver.AutosaveAssets) ? "Assets saver: ON" : "Assets saver: OFF"))
        {
            if (AutoSaver.AutosaveAssets)
            {
                AutoSaver.AutosaveAssets = false;
            }
            else
            {
                AutoSaver.AutosaveAssets = true;
            }
        }
        EditorGUILayout.EndVertical();

        EditorGUILayout.BeginVertical();
        if (GUILayout.Button((AutoSaver.SaveOnPlay) ? "Save on play: ON" : "Save on play: OFF"))
        {
            if (AutoSaver.SaveOnPlay)
            {
                AutoSaver.SaveOnPlay = false;
            }
            else
            {
                AutoSaver.SaveOnPlay = true;
            }
        }
        EditorGUILayout.EndVertical();

        EditorGUILayout.EndHorizontal();
        #endregion

        #region Interval slider
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.BeginVertical();
        AutoSaver.AutosaveInterval = EditorGUILayout.IntSlider("AutoSave Interval:", AutoSaver.AutosaveInterval, 1, 60);
        EditorGUILayout.EndHorizontal();
        EditorGUILayout.EndVertical();
        #endregion

        #region Save and Delete buttons
        EditorGUILayout.BeginHorizontal(GUI.skin.box);

        EditorGUILayout.BeginVertical();
        if (GUILayout.Button("Save prefs"))
        {
            SaveEditorPrefs();
        }
        EditorGUILayout.EndVertical();

        EditorGUILayout.BeginVertical();
        if (GUILayout.Button("Delete prefs"))
        {
            DeleteEditorPrefs();
        }
        EditorGUILayout.EndVertical();

        EditorGUILayout.EndHorizontal();
        #endregion
    }
Example #28
0
        public SimulationPage()
        {
            this.InitializeComponent();

            AutoSaver.Subscribe(this.Simulation);
        }
Example #29
0
        public IDisposable CreateAutoSaveContext()
        {
            if (!_autoSaveContext.WaitOne(300000))
                throw new Exception("Cannot create auto-save context");

            return _autoSaver = new AutoSaver(Save, _autoSaveContext);
        }
Example #30
0
 /* ----------------------------------------------------------------- */
 ///
 /// OnShown
 ///
 /// <summary>
 /// 初回表示時に実行されます。
 /// </summary>
 ///
 /* ----------------------------------------------------------------- */
 protected override void OnShown(EventArgs e)
 {
     base.OnShown(e);
     Saver = new AutoSaver(Pages, Settings, Aggregator.Get());
     this.LogDebug($"Location:{Location}\tSize:{Size}");
 }
Example #31
0
        public ShellViewModel(IWindowManager windowManager
                              , IEventAggregator eventAggregator
                              , RibbonViewModel ribbonViewModel
                              , StatusBarViewModel statusBar
                              , IConductor conductor
                              , IDaxStudioHost host
                              , IVersionCheck versionCheck
                              , ISettingProvider settingProvider)
        {
            Ribbon           = ribbonViewModel;
            Ribbon.Shell     = this;
            StatusBar        = statusBar;
            SettingProvider  = settingProvider;
            _windowManager   = windowManager;
            _eventAggregator = eventAggregator;
            _eventAggregator.Subscribe(this);
            Tabs = (DocumentTabViewModel)conductor;
            Tabs.ConductWith(this);
            //Tabs.CloseStrategy = new ApplicationCloseStrategy();
            Tabs.CloseStrategy = IoC.Get <ApplicationCloseAllStrategy>();
            _host = host;
            _app  = Application.Current;

            // TODO - get master auto save indexes and only get crashed index files...

            // check for auto-saved files and offer to recover them
            var autoSaveInfo = AutoSaver.LoadAutoSaveMasterIndex();

            if (autoSaveInfo.Values.Where(idx => idx.ShouldRecover).Count() > 0)
            {
                RecoverAutoSavedFiles(autoSaveInfo);
            }
            else
            {
                // if a filename was passed in on the command line open it
                if (_host.CommandLineFileName != string.Empty)
                {
                    Tabs.NewQueryDocument(_host.CommandLineFileName);
                }

                // if no tabs are open at this point open a blank one
                if (Tabs.Items.Count == 0)
                {
                    NewDocument();
                }

                // if there are no auto-save files to recover, start the auto save timer
                eventAggregator.PublishOnUIThreadAsync(new StartAutoSaveTimerEvent());
            }

            VersionChecker = versionCheck;

#if PREVIEW
            DisplayName = string.Format("DaxStudio - {0} (PREVIEW)", Version.ToString(4));
#else
            DisplayName = string.Format("DaxStudio - {0}", Version.ToString(3));
#endif
            Application.Current.Activated += OnApplicationActivated;
            Log.Verbose("============ Shell Started - v{version} =============", Version.ToString());

            _autoSaveTimer          = new Timer(Constants.AutoSaveIntervalMs);
            _autoSaveTimer.Elapsed += new ElapsedEventHandler(AutoSaveTimerElapsed);
        }