Example #1
0
        public ProductSettingsTracker(Lifetime lifetime, IProductNameAndVersion product, ClientFactory clientFactory, GlobalPerProductStorage globalPerProductStorage, IFileSystemTracker fileSystemTracker, JetBoxSettingsStorage jetBoxSettings)
        {
            myClientFactory = clientFactory;
              mySettingsStore = jetBoxSettings.SettingsStore.BindToContextLive(lifetime, ContextRange.ApplicationWide);
              mySettingsStore.Changed.Advise(lifetime, _ => InitClient());

              myRootFolder = FileSystemPath.Parse(product.ProductName);
              InitClient();

              var productSettingsPath = globalPerProductStorage.XmlFileStorage.Path;

              SyncFromCloud(productSettingsPath.Value);

              var fileTrackingLifetime = new SequentialLifetimes(lifetime);
              productSettingsPath.Change.Advise(lifetime,
            args =>
            {
              var path = args.Property.Value;
              if (lifetime.IsTerminated || path.IsNullOrEmpty())
              {
            fileTrackingLifetime.TerminateCurrent();
              }
              else
              {
            fileTrackingLifetime.Next(lt => fileSystemTracker.AdviseFileChanges(lt, path, delta => delta.Accept(new FileChangesVisitor(myClient, myRootFolder))));
              }
            });
        }
Example #2
0
        public void TestFailedInNext()
        {
            var sequence = new SequentialLifetimes(TestLifetime);
            var sb       = new StringBuilder();

            try
            {
                sequence.Next(lifetime =>
                {
                    lifetime.Bracket(
                        () => sb.AppendLine($"start"),
                        () => sb.AppendLine($"end"));

                    sb.AppendLine("Before exception");
                    throw new Exception("Expected");
                });
            }
            catch (Exception e) when(e.Message == "Expected")
            {
                sb.AppendLine("Expected exception");
            }

            Assert.IsTrue(sequence.IsCurrentTerminated);
            Assert.AreEqual("start\nBefore exception\nend\nExpected exception\n", sb.ToString().Replace("\r\n", "\n"));
        }
Example #3
0
        public void ReentrancyPriorityAdviceTest()
        {
            using var lifetimeDefinition = new LifetimeDefinition();
            var lifetime = lifetimeDefinition.Lifetime;

            var priorityAdvice = 0;
            var advice1        = 0;
            var advice2        = 0;

            var signal    = new Signal <Unit>();
            var lifetimes = new SequentialLifetimes(TestLifetime);

            signal.Advise(lifetime, _ =>
            {
                advice1++;
                using (Signal.PriorityAdviseCookie.Create())
                {
                    signal.Advise(lifetimes.Next(), _ => priorityAdvice++);
                }
            });

            signal.Advise(lifetime, _ => advice2++);

            for (int i = 0; i < 1000; i++)
            {
                signal.Fire();

                Assert.AreEqual(i + 1, advice1);
                Assert.AreEqual(i + 1, advice2);
                Assert.AreEqual(i, priorityAdvice);
            }
        }
Example #4
0
        public JetBoxOptionsPage(Lifetime lifetime, IUIApplication environment, ClientFactory clientFactory, JetBoxSettingsStorage jetBoxSettings, JetPopupMenus jetPopupMenus)
            : base(lifetime, environment, PID)
        {
            mySettingsStore = jetBoxSettings.SettingsStore.BindToContextLive(lifetime, ContextRange.ApplicationWide);
            myLifetimes     = new SequentialLifetimes(lifetime);

            myClient           = clientFactory.CreateClient();
            myClient.UserLogin = mySettingsStore.GetValue(JetBoxSettingsAccessor.Login);

            // init UI
            myLoggedPanel = new FlowLayoutPanel {
                Visible = false, AutoSize = true
            };
            myLoggedPanel.Controls.Add(myLoginLabel = new RichTextLabel(environment));
            myLoggedPanel.Controls.Add(new LinkLabel("Logout", Logout, jetPopupMenus));

            myNonLoggedPanel = new FlowLayoutPanel {
                Visible = false, AutoSize = true, FlowDirection = FlowDirection.TopDown
            };
            myNonLoggedPanel.Controls.Add(new LinkLabel("Login", Login, jetPopupMenus)
            {
                Image      = Environment.Theming.Icons[UnnamedThemedIcons.Dropbox.Id].CurrentGdipBitmapNotSure(),
                ImageAlign = ContentAlignment.MiddleLeft,
                Padding    = new Padding(20, 0, 0, 0)
            });

            Controls.Add(myLoggedPanel);
            Controls.Add(myNonLoggedPanel);

            InitLoginState();
        }
        public ProductSettingsTracker(Lifetime lifetime, ClientFactory clientFactory, IViewable <ISyncSource> syncSources, IFileSystemTracker fileSystemTracker, JetBoxSettingsStorage jetBoxSettings)
        {
            myClientFactory = clientFactory;
            mySettingsStore = jetBoxSettings.SettingsStore.BindToContextLive(lifetime, ContextRange.ApplicationWide);
            mySettingsStore.Changed.Advise(lifetime, _ => InitClient());

            myRootFolder = FileSystemPath.Parse("ReSharperPlatform");
            InitClient();

            syncSources.View(lifetime, (lt1, source) =>
                             source.FilesToSync.View(lt1, (lt2, fileToSync) =>
            {
                SyncFromCloud(fileToSync.Value);

                var fileTrackingLifetime = new SequentialLifetimes(lt2);
                fileToSync.Change.Advise(lt2,
                                         args =>
                {
                    var path = args.Property.Value;
                    if (lifetime.IsTerminated || path.IsNullOrEmpty())
                    {
                        fileTrackingLifetime.TerminateCurrent();
                    }
                    else
                    {
                        fileTrackingLifetime.Next(lt =>
                                                  fileSystemTracker.AdviseFileChanges(lt, path,
                                                                                      delta => delta.Accept(new FileChangesVisitor(myClient, myRootFolder))));
                    }
                });
            }));
        }
Example #6
0
        public JetBoxOptionsPage(Lifetime lifetime, IUIApplication environment, ClientFactory clientFactory, JetBoxSettingsStorage jetBoxSettings, JetPopupMenus jetPopupMenus)
            : base(lifetime, environment, PID)
        {
            mySettingsStore = jetBoxSettings.SettingsStore.BindToContextLive(lifetime, ContextRange.ApplicationWide);
              myLifetimes = new SequentialLifetimes(lifetime);

              myClient = clientFactory.CreateClient();
              myClient.UserLogin = mySettingsStore.GetValue(JetBoxSettingsAccessor.Login);

              // init UI
              myLoggedPanel = new FlowLayoutPanel { Visible = false, AutoSize = true };
              myLoggedPanel.Controls.Add(myLoginLabel = new RichTextLabel(environment));
              myLoggedPanel.Controls.Add(new LinkLabel("Logout", Logout, jetPopupMenus));

              myNonLoggedPanel = new FlowLayoutPanel { Visible = false, AutoSize = true, FlowDirection = FlowDirection.TopDown };
              myNonLoggedPanel.Controls.Add(new LinkLabel("Login", Login, jetPopupMenus)
              {
            Image = Environment.Theming.Icons[UnnamedThemedIcons.Dropbox.Id].CurrentGdipBitmapScreenDpi,
            ImageAlign = ContentAlignment.MiddleLeft,
            Padding = new Padding(20, 0, 0, 0)
              });

              Controls.Add(myLoggedPanel);
              Controls.Add(myNonLoggedPanel);

              InitLoginState();
        }
        public ProductSettingsTracker(Lifetime lifetime, ClientFactory clientFactory, IViewable<ISyncSource> syncSources, IFileSystemTracker fileSystemTracker, JetBoxSettingsStorage jetBoxSettings)
        {
            myClientFactory = clientFactory;
              mySettingsStore = jetBoxSettings.SettingsStore.BindToContextLive(lifetime, ContextRange.ApplicationWide);
              mySettingsStore.Changed.Advise(lifetime, _ => InitClient());

              myRootFolder = FileSystemPath.Parse("ReSharperPlatform");
              InitClient();

              syncSources.View(lifetime, (lt1, source) =>
            source.FilesToSync.View(lt1, (lt2, fileToSync) =>
            {
              SyncFromCloud(fileToSync.Value);

              var fileTrackingLifetime = new SequentialLifetimes(lt2);
              fileToSync.Change.Advise(lt2,
            args =>
            {
              var path = args.Property.Value;
              if (lifetime.IsTerminated || path.IsNullOrEmpty())
              {
                fileTrackingLifetime.TerminateCurrent();
              }
              else
              {
                fileTrackingLifetime.Next(lt =>
                    fileSystemTracker.AdviseFileChanges(lt, path,
                      delta => delta.Accept(new FileChangesVisitor(myClient, myRootFolder))));
              }
            });
            }));
        }
Example #8
0
        public UnityEditorProtocol(Lifetime lifetime, ILogger logger, UnityHost host,
                                   IScheduler dispatcher, IShellLocks locks, ISolution solution, PluginPathsProvider pluginPathsProvider,
                                   ISettingsStore settingsStore, JetBrains.Application.ActivityTrackingNew.UsageStatistics usageStatistics,
                                   UnitySolutionTracker unitySolutionTracker, IThreading threading)
        {
            myComponentLifetime   = lifetime;
            myLogger              = logger;
            myDispatcher          = dispatcher;
            myLocks               = locks;
            mySolution            = solution;
            myPluginPathsProvider = pluginPathsProvider;
            myUsageStatistics     = usageStatistics;
            myThreading           = threading;
            myHost = host;
            myBoundSettingsStore = settingsStore.BindToContextLive(lifetime, ContextRange.Smart(solution.ToDataContext()));
            mySessionLifetimes   = new SequentialLifetimes(lifetime);

            if (solution.GetData(ProjectModelExtensions.ProtocolSolutionKey) == null)
            {
                return;
            }

            unitySolutionTracker.IsUnityProject.View(lifetime, (lf, args) =>
            {
                if (!args)
                {
                    return;
                }

                var solFolder = mySolution.SolutionFilePath.Directory;
                AdviseModelData(lifetime);

                // todo: consider non-Unity Solution with Unity-generated projects
                var protocolInstancePath = solFolder.Combine("Library/ProtocolInstance.json");
                protocolInstancePath.Directory.CreateDirectory();

                var watcher          = new FileSystemWatcher();
                watcher.Path         = protocolInstancePath.Directory.FullPath;
                watcher.NotifyFilter =
                    NotifyFilters.LastAccess |
                    NotifyFilters.LastWrite; //Watch for changes in LastAccess and LastWrite times
                watcher.Filter = protocolInstancePath.Name;

                // Add event handlers.
                watcher.Changed += OnChanged;
                watcher.Created += OnChanged;

                lf.Bracket(() => { }, () =>
                {
                    watcher.Dispose();
                });

                watcher.EnableRaisingEvents = true; // Begin watching.
                // connect on start of Rider
                CreateProtocols(protocolInstancePath);
            });
        }
Example #9
0
        public MainWindow()
        {
            InitializeComponent();

            lifetime  = EternalLifetime.Instance;
            lifetimes = new SequentialLifetimes(lifetime);

            Loaded += MainWindow_Loaded;
        }
Example #10
0
        public BuildAnimations(Lifetime lifetime, Agent agent)
        {
            this.lifetime = lifetime;
            dte           = Shell.Instance.GetComponent <DTE>();
            this.agent    = agent;

            sequentialLifetimes = new SequentialLifetimes(lifetime);

            SubscribeEvents();
        }
        public UnityEditorProtocol(Lifetime lifetime, ILogger logger, UnityHost host,
                                   IScheduler dispatcher, IShellLocks locks, ISolution solution, PluginPathsProvider pluginPathsProvider,
                                   ISettingsStore settingsStore, Application.ActivityTrackingNew.UsageStatistics usageStatistics,
                                   UnitySolutionTracker unitySolutionTracker)
        {
            myComponentLifetime   = lifetime;
            myLogger              = logger;
            myDispatcher          = dispatcher;
            myLocks               = locks;
            mySolution            = solution;
            myPluginPathsProvider = pluginPathsProvider;
            myUsageStatistics     = usageStatistics;
            myHost = host;
            myBoundSettingsStore =
                settingsStore.BindToContextLive(lifetime, ContextRange.Smart(solution.ToDataContext()));
            mySessionLifetimes = new SequentialLifetimes(lifetime);
            myUnityModel       = new Property <EditorPluginModel>(lifetime, "unityModelProperty", null)
                                 .EnsureReadonly(myReadonlyToken).EnsureThisThread();

            if (!unitySolutionTracker.IsAbleToEstablishProtocolConnectionWithUnity.Value)
            {
                return;
            }

            if (solution.GetData(ProjectModelExtensions.ProtocolSolutionKey) == null)
            {
                return;
            }

            var solFolder = mySolution.SolutionFilePath.Directory;

            AdviseModelData(lifetime, mySolution.GetProtocolSolution());

            // todo: consider non-Unity Solution with Unity-generated projects
            var protocolInstancePath = solFolder.Combine("Library/ProtocolInstance.json");

            protocolInstancePath.Directory.CreateDirectory();

            var watcher = new FileSystemWatcher();

            watcher.Path         = protocolInstancePath.Directory.FullPath;
            watcher.NotifyFilter =
                NotifyFilters.LastAccess |
                NotifyFilters.LastWrite; //Watch for changes in LastAccess and LastWrite times
            watcher.Filter = protocolInstancePath.Name;

            // Add event handlers.
            watcher.Changed += OnChanged;
            watcher.Created += OnChanged;

            watcher.EnableRaisingEvents = true; // Begin watching.

            // connect on start of Rider
            CreateProtocols(protocolInstancePath);
        }
Example #12
0
        public void TestTerminateCurrent01()
        {
            var sequentialLifetimes = new SequentialLifetimes(TestLifetime);

            sequentialLifetimes.Next(lifetime => lifetime.OnTermination(() =>
            {
                Assert.IsTrue(lifetime.IsNotAlive, "lifetime.IsNotAlive");
                Assert.IsTrue(sequentialLifetimes.IsCurrentTerminated, "sequentialLifetimes.IsCurrentTerminated");
            }));
            sequentialLifetimes.TerminateCurrent();
        }
        public InplaceRefactoringHandler(Lifetime lifetime, Agent agent,
                                         InplaceRefactoringsHighlightingManagerWrapper highlightingManager,
                                         IThreading threading, IActionManager actionManager, ISolution solution)
        {
            this.lifetime            = lifetime;
            this.agent               = agent;
            this.highlightingManager = highlightingManager;
            this.threading           = threading;
            this.actionManager       = actionManager;
            this.solution            = solution;

            sequentialLifetimes = new SequentialLifetimes(lifetime);
        }
Example #14
0
        public UnityPluginProtocolController(Lifetime lifetime, ILogger logger,
                                             IScheduler dispatcher, IShellLocks locks, ISolution solution)
        {
            if (!ProjectExtensions.IsSolutionGeneratedByUnity(solution.SolutionFilePath.Directory))
            {
                return;
            }

            myLifetime         = lifetime;
            myLogger           = logger;
            myDispatcher       = dispatcher;
            myLocks            = locks;
            mySolution         = solution;
            mySessionLifetimes = new SequentialLifetimes(lifetime);

            if (solution.GetData <Solution>(ProjectModelExtensions.ProtocolSolutionKey) == null)
            {
                return;
            }

            var solFolder = mySolution.SolutionFilePath.Directory;

            AdviseCustomDataFromFrontend(lifetime, mySolution.GetProtocolSolution());

            // todo: consider non-Unity Solution with Unity-generated projects
            var protocolInstancePath = solFolder.Combine("Library/ProtocolInstance.json");

            if (!protocolInstancePath.ExistsFile)
            {
                File.Create(protocolInstancePath.FullPath);
            }

            var watcher = new FileSystemWatcher();

            watcher.Path         = protocolInstancePath.Directory.FullPath;
            watcher.NotifyFilter =
                NotifyFilters.LastAccess |
                NotifyFilters.LastWrite; //Watch for changes in LastAccess and LastWrite times
            watcher.Filter = protocolInstancePath.Name;

            // Add event handlers.
            watcher.Changed += OnChanged;
            watcher.Created += OnChanged;

            watcher.EnableRaisingEvents = true; // Begin watching.

            // connect on start of Rider
            CreateProtocol(protocolInstancePath, mySolution.GetProtocolSolution());
        }
        private void SubscribeToSessionLaunch(Lifetime sessionLifetime, IUnitTestSession session)
        {
            var sequentialLifetimes = new SequentialLifetimes(sessionLifetime);

            session.Launch.Change.Advise(sessionLifetime, args =>
            {
                if (args.HasNew && args.New != null)
                {
                    sequentialLifetimes.Next(launchLifetime =>
                    {
                        SubscribeToLaunchState(launchLifetime, session, args.New.State);
                    });
                }
            });
        }
Example #16
0
        public static void View <T>(this IReadonlyProperty <T> me, Lifetime lifetime, Action <Lifetime, T> handler)
        {
            if (!lifetime.IsAlive)
            {
                return;
            }

            // nested lifetime is needed due to exception that could be thrown
            // while viewing a property change right at the moment of <param>lifetime</param>'s termination
            // but before <param>handler</param> gets removed
            var lf  = lifetime == Lifetime.Eternal ? lifetime : Lifetime.Define(lifetime).Lifetime;
            var seq = new SequentialLifetimes(lf);

            me.Advise(lf, v => handler(seq.Next(), v));
        }
Example #17
0
        public LocalOccurrencesHighlighter([NotNull] Lifetime lifetime,
                                           [NotNull] IShellLocks shellLocks,
                                           [NotNull] ITextControl textControl,
                                           [NotNull] IDocumentMarkupManager markupManager)
        {
            myLifetime                = lifetime;
            myShellLocks              = shellLocks;
            myMarkupManager           = markupManager;
            myTextControl             = textControl;
            mySequentialOccurrences   = new SequentialLifetimes(lifetime);
            mySequentialFocused       = new SequentialLifetimes(lifetime);
            myTextControlViewportRect = textControl.Scrolling.ViewportRect.Value;

            mySyncRoot = new object();

            myLifetime.AddAction(DropHighlightings);
        }
Example #18
0
        public BackendUnityProtocol(Lifetime lifetime, ILogger logger,
                                    BackendUnityHost backendUnityHost, FrontendBackendHost frontendBackendHost,
                                    IScheduler dispatcher, IShellLocks locks, ISolution solution,
                                    IApplicationWideContextBoundSettingStore settingsStore,
                                    UnitySolutionTracker unitySolutionTracker,
                                    UnityVersion unityVersion, NotificationsModel notificationsModel,
                                    IHostProductInfo hostProductInfo, IFileSystemTracker fileSystemTracker)
        {
            myPluginInstallations = new JetHashSet <FileSystemPath>();

            myLifetime            = lifetime;
            myLogger              = logger;
            myBackendUnityHost    = backendUnityHost;
            myDispatcher          = dispatcher;
            myLocks               = locks;
            mySolution            = solution;
            myUnityVersion        = unityVersion;
            myNotificationsModel  = notificationsModel;
            myHostProductInfo     = hostProductInfo;
            myFrontendBackendHost = frontendBackendHost;
            myBoundSettingsStore  = settingsStore.BoundSettingsStore;
            mySessionLifetimes    = new SequentialLifetimes(lifetime);

            if (solution.GetData(ProjectModelExtensions.ProtocolSolutionKey) == null)
            {
                return;
            }

            unitySolutionTracker.IsUnityProject.View(lifetime, (lf, args) =>
            {
                if (!args)
                {
                    return;
                }

                var solFolder = mySolution.SolutionDirectory;

                // todo: consider non-Unity Solution with Unity-generated projects
                var protocolInstancePath = solFolder.Combine("Library/ProtocolInstance.json");
                fileSystemTracker.AdviseFileChanges(lf, protocolInstancePath, OnProtocolInstanceJsonChange);

                // connect on start of Rider
                CreateProtocol(protocolInstancePath);
            });
        }
        public UnityEditorProtocol(Lifetime lifetime, ILogger logger, UnityHost host,
                                   IScheduler dispatcher, IShellLocks locks, ISolution solution,
                                   ISettingsStore settingsStore, JetBrains.Application.ActivityTrackingNew.UsageStatistics usageStatistics,
                                   UnitySolutionTracker unitySolutionTracker, IThreading threading,
                                   UnityVersion unityVersion, NotificationsModel notificationsModel,
                                   IHostProductInfo hostProductInfo, IFileSystemTracker fileSystemTracker)
        {
            myPluginInstallations = new JetHashSet <FileSystemPath>();

            myComponentLifetime  = lifetime;
            myLogger             = logger;
            myDispatcher         = dispatcher;
            myLocks              = locks;
            mySolution           = solution;
            myUsageStatistics    = usageStatistics;
            myThreading          = threading;
            myUnityVersion       = unityVersion;
            myNotificationsModel = notificationsModel;
            myHostProductInfo    = hostProductInfo;
            myHost = host;
            myBoundSettingsStore = settingsStore.BindToContextLive(lifetime, ContextRange.Smart(solution.ToDataContext()));
            mySessionLifetimes   = new SequentialLifetimes(lifetime);

            if (solution.GetData(ProjectModelExtensions.ProtocolSolutionKey) == null)
            {
                return;
            }

            unitySolutionTracker.IsUnityProject.View(lifetime, (lf, args) =>
            {
                if (!args)
                {
                    return;
                }

                var solFolder = mySolution.SolutionDirectory;
                AdviseModelData(lifetime);

                // todo: consider non-Unity Solution with Unity-generated projects
                var protocolInstancePath = solFolder.Combine("Library/ProtocolInstance.json");
                fileSystemTracker.AdviseFileChanges(lf, protocolInstancePath, OnChangeAction);
                // connect on start of Rider
                CreateProtocols(protocolInstancePath);
            });
        }
        /// <summary>
        /// Initializes a new instance of the HighlightingRegistering class.
        /// </summary>
        /// <param name="lifetime">Lifetime of the component</param>
        /// <param name="partsCatalogueSet">The catalogue set</param>
        /// <param name="settingsStore">The settings store.</param>
        /// <param name="fileSystemTracker">
        /// The file System Tracker.
        /// </param>
        public HighlightingRegistering(Lifetime lifetime, JetEnvironment jetEnvironment, ISettingsStore settingsStore, IFileSystemTracker fileSystemTracker)
        {
            this.partsCatalogueSet     = jetEnvironment.FullPartCatalogSet;
            this.registrationLifetimes = new SequentialLifetimes(lifetime);

            // TODO: We shouldn't be doing any of this at runtime, especially not on each load
            // Registering highlightings should happen declaratively
            // Create this instance directly, rather than use the pool, because the pool needs to
            // be per-solution, as it caches settings for files in the solution
            Lifetimes.Using(
                temporaryLifetime =>
            {
                // We don't really need the file system tracker - it's only used when we get
                // settings, which we don't do as part of highlighting initialisation
                StyleCopCore core = StyleCopCoreFactory.Create(temporaryLifetime, settingsStore, fileSystemTracker);
                this.Register(core);
            });
        }
Example #21
0
        internal SocketProxy(string id, Lifetime lifetime, int serverPort)
        {
            Id           = id;
            myLifetime   = lifetime;
            myServerPort = serverPort;
            myLogger     = Log.GetLog <SocketProxy>().GetSublogger(id);

            myServerToClientLifetime = new SequentialLifetimes(myLifetime).With(lifetimes => lifetimes.Next());
            myClientToServerLifetime = new SequentialLifetimes(myLifetime).With(lifetimes => lifetimes.Next());

            myLifetime.OnTermination(() =>
            {
                myPort = null;

                StopServerToClientMessaging();
                StopClientToServerMessaging();
            });
        }
Example #22
0
        public void TestTerminateInNext()
        {
            var sequence = new SequentialLifetimes(TestLifetime);
            var sb       = new StringBuilder();

            sequence.Next(lifetime =>
            {
                lifetime.Bracket(
                    () => sb.AppendLine($"start"),
                    () => sb.AppendLine($"end"));
                sb.AppendLine("Before terminate");
                sequence.TerminateCurrent();
                sb.AppendLine("After terminate");
            });

            Assert.IsTrue(sequence.IsCurrentTerminated);
            Assert.AreEqual("start\nBefore terminate\nAfter terminate\nend\n", sb.ToString().Replace("\r\n", "\n"));
        }
Example #23
0
        public void TestTerminateCurrent02()
        {
            var sb = new StringBuilder();
            var sequentialLifetimes = new SequentialLifetimes(TestLifetime);

            sequentialLifetimes.Next(lifetime => lifetime.OnTermination(() =>
            {
                sb.Append("T1");
                Assert.IsTrue(lifetime.IsNotAlive, "lifetime.IsNotAlive");
                Assert.IsTrue(sequentialLifetimes.IsCurrentTerminated, "sequentialLifetimes.IsCurrentTerminated");
            }));
            sequentialLifetimes.Next(lifetime =>
            {
                sb.Append("N2");
            });

            Assert.AreEqual("T1N2", sb.ToString());
        }
Example #24
0
        public void TestSimpleDefineNext()
        {
            var sequence = new SequentialLifetimes(TestLifetime);
            var sb       = new StringBuilder();
            var expected = new StringBuilder();

            const int max = 3;

            for (int i = 0; i < max; i++)
            {
                sb.AppendLine($"before {i}");
                sequence.DefineNext(lifetimeDefinition =>
                {
                    var c = i;
                    lifetimeDefinition.Bracket(
                        () => sb.AppendLine($"start {c}"),
                        () => sb.AppendLine($"end {c}"));
                    sb.AppendLine($"in {c}");
                });


                if (i == 0)
                {
                    expected.AppendLine($"before {i}");
                }

                expected.AppendLine($"start {i}");
                expected.AppendLine($"in {i}");

                if (i != max - 1)
                {
                    expected.AppendLine($"before {i+1}");
                    expected.AppendLine($"end {i}");
                }
            }

            Assert.IsFalse(sequence.IsCurrentTerminated);
            Assert.AreEqual(expected.ToString(), sb.ToString());

            sequence.TerminateCurrent();
            Assert.IsTrue(sequence.IsCurrentTerminated);
            expected.AppendLine($"end {max - 1}");
            Assert.AreEqual(expected.ToString(), sb.ToString());
        }
        public TodoItemsCountProvider(
            Lifetime lifetime,
            IPrimaryTodoManager primaryTodoManager,
            SolutionSettingsCache solutionSettingsCache,
            TodoItemsCountDefinitionsCachedSettingsReader todoItemsCountDefinitionsCachedSettingsReader,
            IEnumerable <ITodoItemsCountConsumer> todoItemsCountConsumers,
            ISettingsStore settingsStore)
        {
            _primaryTodoManager = primaryTodoManager;
            _settingsCache      = solutionSettingsCache;
            _todoItemsCountDefinitionsCachedSettingsReader = todoItemsCountDefinitionsCachedSettingsReader;
            _todoItemsCountConsumers = todoItemsCountConsumers.ToIReadOnlyList();

            _primaryTodoManager.FilesWereUpdated.Advise(lifetime, files =>
            {
                // Check for invalid changed files, else we'll get "not valid" exceptions in the 'AllItems' access
                // later (at least as observed during unit test shut down):
                if (files.WhereNotNull().All(x => x.IsValid()))
                {
                    UpdateTodoItemsCounts();
                }
            });

            var settingsCacheGetDataSequentialLifeTime = new SequentialLifetimes(lifetime);

            _currentSettingsCacheLifeTime = settingsCacheGetDataSequentialLifeTime.Next();

            settingsStore.AdviseChange(lifetime, _todoItemsCountDefinitionsCachedSettingsReader.KeyExposed, () =>
            {
                // We use the following lifetime to solve the issue that this 'ISettingsStore.AdviseChange()' callback
                // arrives earlier than the one used in the cache. => The cache has still the old value when accessed
                // in 'UpdateTodoItemsCounts()'. => Terminate the cache lifetime explicitly.
                _currentSettingsCacheLifeTime = settingsCacheGetDataSequentialLifeTime.Next();

                UpdateTodoItemsCounts();
            });

            foreach (var consumer in _todoItemsCountConsumers)
            {
                consumer.UpdateRequestSignal.Advise(lifetime, () => { UpdateTodoItemsCounts(); });
            }

            // IDEA: Combine the three event sources and execute update in background thread?
        }
Example #26
0
        private void EnableShortcuts(Lifetime enabledLifetime)
        {
            var popupWindowLifetimeDefinition = Lifetimes.Define(enabledLifetime, "PresentationAssistant::PopupWindow");

            var window = new PresentationAssistantWindow();

            window.Owner = mainWindow.MainWpfWindow.Value;


            theming.PopulateResourceDictionary(popupWindowLifetimeDefinition.Lifetime, window.Resources);

            var popupWindow = new FadingWpfPopupWindow(popupWindowLifetimeDefinition, context, context.Mutex,
                                                       popupWindowManager, window, opacity: 0.8);

            var visibilityLifetimes = new SequentialLifetimes(popupWindowLifetimeDefinition.Lifetime);

            showAction = shortcut =>
            {
                window.SetShortcut(shortcut);
                popupWindow.ShowWindow();

                visibilityLifetimes.DefineNext((visibleLifetimeDefinition, visibleLifetime) =>
                {
                    // Hide the window after a timespan, and queue it on the visible sequential lifetime so
                    // that the timer is cancelled when we want to show a new shortcut. Don't hide the window
                    // by attaching it to the sequential lifetime, as that will cause the window to hide when
                    // we need to show a new shortcut. But, make sure we do terminate the lifetime so that
                    // the topmost timer hack is stopped when this window is not visible
                    threading.TimedActions.Queue(visibleLifetime, "PresentationAssistantWindow::HideWindow",
                                                 () => popupWindow.HideWindow(), VisibleTimeSpan,
                                                 TimedActionsHost.Recurrence.OneTime, Rgc.Invariant);
                });
            };

            enabledLifetime.AddAction(() =>
            {
                showAction = _ => { };
            });
        }
Example #27
0
        private async void Messaging(string id, Stream source, Stream destination, byte[] buffer,
                                     SequentialLifetimes lifetimes)
        {
            while (myLifetime.IsAlive)
            {
                try
                {
                    var length = await source.ReadAsync(buffer, 0, buffer.Length, myLifetime);

                    if (length == 0)
                    {
                        myLogger.Verbose($"{id}: Connection lost");
                        break;
                    }

                    myLogger.Verbose($"{id}: Message of length: {length} was read");
                    if (!lifetimes.IsCurrentTerminated)
                    {
                        await Task.Delay(Latency, myLifetime);

                        await destination.WriteAsync(buffer, 0, length, myLifetime);

                        myLogger.Verbose($"{id}: Message of length: {length} was written");
                    }
                    else
                    {
                        myLogger.Verbose($"{id}: Message of length {length} was not transferred, because lifetime was terminated");
                    }
                }
                catch (OperationCanceledException)
                {
                    myLogger.Verbose($"{id}: Messaging cancelled");
                }
                catch (Exception e)
                {
                    myLogger.Warn(e, $"{id}: Messaging failed");
                }
            }
        }
 public BalloonManager(Lifetime overallLifetime)
 {
     balloonLifetimes     = new SequentialLifetimes(overallLifetime);
     ButtonClicked        = new Signal <string>(overallLifetime, "BalloonManager::ButtonClicked");
     BalloonOptionClicked = new Signal <object>(overallLifetime, "BalloonManager::BalloonOptionClicked");
 }
Example #29
0
        public RiderBackendToUnrealEditor(Lifetime lifetime, IShellLocks locks, IScheduler dispatcher, ILogger logger,
                                          UnrealHost unrealHost, UnrealLinkResolver linkResolver, EditorNavigator editorNavigator,
                                          UnrealPluginDetector pluginDetector)
        {
            myComponentLifetime          = lifetime;
            myLocks                      = locks;
            myConnectionLifetimeProducer = new SequentialLifetimes(lifetime);
            myDispatcher                 = dispatcher;
            myLogger                     = logger;
            myUnrealHost                 = unrealHost;
            myLinkResolver               = linkResolver;
            myEditorNavigator            = editorNavigator;

            myLogger.Info("RiderBackendToUnrealEditor building started");

            pluginDetector.InstallInfoProperty.View(myComponentLifetime, (lt, pluginInfo) =>
            {
                if (pluginInfo == null)
                {
                    return;
                }

                var portDirectoryFullPath = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "..",
                    "Local", "Jetbrains", "Rider", "Unreal", "Ports");

                Directory.CreateDirectory(portDirectoryFullPath);

                var watcher = new FileSystemWatcher(portDirectoryFullPath)
                {
                    NotifyFilter = NotifyFilters.LastWrite
                };
                var projects = pluginInfo.ProjectPlugins.Select(it => it.UprojectFilePath.NameWithoutExtension)
                               .ToList();

                FileSystemEventHandler handler = (obj, fileSystemEvent) =>
                {
                    var path = FileSystemPath.Parse(fileSystemEvent.FullPath);
                    if (projects.Contains(path.NameWithoutExtension) && myComponentLifetime.IsAlive)
                    {
                        myLocks.ExecuteOrQueue(myComponentLifetime, "CreateProtocol", () => CreateProtocols(path));
                    }
                };

                watcher.Changed += handler;
                watcher.Created += handler;

                // Check if it's even possible to happen
                lt.Bracket(() => { }, () => { watcher.Dispose(); });

                StartWatcher(watcher);

                foreach (var projectName in projects)
                {
                    var portFileFullPath = Path.Combine(portDirectoryFullPath, projectName);
                    CreateProtocols(FileSystemPath.Parse(portFileFullPath));
                }
            });

            myLogger.Info("RiderBackendToUnrealEditor building finished");
        }