Пример #1
0
        /// <summary>
        /// The initializer for this ShellComponent.
        /// </summary>
        /// <param name="lifetime">
        /// The lifetime for this object.
        /// </param>
        public void Init(JB::JetBrains.DataFlow.Lifetime lifetime)
        {
            RegistryUtils registryUtils = new RegistryUtils();

            object   oneTimeInitializationRequiredRegistryKey = registryUtils.CUGetValue("LastInitializationDate");
            DateTime initializationDate = Convert.ToDateTime(oneTimeInitializationRequiredRegistryKey);

            string todayAsString = DateTime.Today.ToString("yyyy-MM-dd");

            string value = registryUtils.LMGetValue("InstallDate") as string;

            DateTime lastInstalledDate;

            try
            {
                lastInstalledDate = Convert.ToDateTime(value);

                // If the installer stored a date that has now been read back in and seems to be in the future
                // then use the LocalUserInstallDate value.
                if (lastInstalledDate > DateTime.Today)
                {
                    lastInstalledDate = GetInstallDateFromLocalUserRegistry(registryUtils, todayAsString);
                }
            }
            catch (FormatException ex)
            {
                // In some locales the installer saves the date in a format we can't parse back out.
                // Use today as the installed date and store it in the HKCU key.
                lastInstalledDate = GetInstallDateFromLocalUserRegistry(registryUtils, todayAsString);
            }

            if (oneTimeInitializationRequiredRegistryKey == null || initializationDate < lastInstalledDate)
            {
                SettingsStore settingsStore = Shell.Instance.GetComponent <SettingsStore>();

                IContextBoundSettingsStoreLive settings = settingsStore.BindToContextLive(lifetime, ContextRange.ApplicationWide);

                bool checkReSharperCodeStyleOptionsAtStartUp = settings.GetValue((StyleCopOptionsSettingsKey key) => key.CheckReSharperCodeStyleOptionsAtStartUp);

                if (checkReSharperCodeStyleOptionsAtStartUp)
                {
                    if (!StyleCopOptionsPage.CodeStyleOptionsValid(settings))
                    {
                        DialogResult result =
                            MessageBox.Show(
                                @"Your ReSharper code style settings are not completely compatible with StyleCop. Would you like to reset them now?",
                                @"StyleCop",
                                MessageBoxButtons.YesNo,
                                MessageBoxIcon.Question,
                                MessageBoxDefaultButton.Button2);
                        if (result == DialogResult.Yes)
                        {
                            StyleCopOptionsPage.CodeStyleOptionsReset(settings);
                        }
                    }
                }
            }

            registryUtils.CUSetValue("LastInitializationDate", todayAsString);
        }
Пример #2
0
        private void CreateRichTextExceptionTypesAsHint(Lifetime lifetime, IContextBoundSettingsStoreLive storeOptionsTransactionContext)
        {
            IProperty <string> property = new Property <string>(lifetime, "Exceptional::ExceptionTypesAsHint::ExceptionTypes");

            property.SetValue(storeOptionsTransactionContext.GetValue((Settings.ExceptionalSettings key) => key.OptionalExceptions2));

            property.Change.Advise(lifetime, a =>
            {
                if (!a.HasNew)
                {
                    return;
                }

                storeOptionsTransactionContext.SetValue((Settings.ExceptionalSettings key) => key.OptionalExceptions2, a.New);
            });

            var textControl = BeControls.GetTextControl(isReadonly: false);

            textControl.Text.SetValue(property.GetValue());
            textControl.Text.Change.Advise(lifetime, str =>
            {
                storeOptionsTransactionContext.SetValue((Settings.ExceptionalSettings key) => key.OptionalExceptions2, str);
            });

            AddControl(textControl);
        }
Пример #3
0
        public JetBoxOptionsPage(Lifetime lifetime, IUIApplication environment, ClientFactory clientFactory, JetBoxSettingsStorage jetBoxSettings, JetPopupMenus jetPopupMenus, OpensUri opensUri)
            : base(lifetime, environment, PID)
        {
            mySettingsStore = jetBoxSettings.SettingsStore.BindToContextLive(lifetime, ContextRange.ApplicationWide);
            myOpensUri      = opensUri;

            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));
            myNonLoggedPanel.Controls.Add(new LinkLabel("Get access (click after approving access on the web)", GetInfo, jetPopupMenus));

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

            InitLoginState();
        }
Пример #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].CurrentGdipBitmapScreenDpi,
            ImageAlign = ContentAlignment.MiddleLeft,
            Padding = new Padding(20, 0, 0, 0)
              });

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

              InitLoginState();
        }
Пример #5
0
        /// <summary>
        /// Calls Refresh in Unity, and RefreshPaths in vfs. If called multiple times while already running, schedules itself again
        /// </summary>
        /// <param name="lifetime"></param>
        /// <param name="refreshType"></param>
        public Task Refresh(Lifetime lifetime, RefreshType refreshType)
        {
            myLocks.AssertMainThread();

            if (myEditorProtocol.UnityModel.Value == null)
            {
                return(Task.CompletedTask);
            }

            if (!myBoundSettingsStore.GetValue((UnitySettings s) => s.AllowAutomaticRefreshInUnity) &&
                refreshType == RefreshType.Normal)
            {
                return(Task.CompletedTask);
            }

            if (myRunningRefreshTask != null && !myRunningRefreshTask.IsCompleted)
            {
                // we may schedule secondary refresh here, which will start after first refresh and protocol reconnect
                // we already do something like that in UnitTesting
                myLogger.Verbose($"Refresh already running. Skip starting a new one.");
                return(myRunningRefreshTask);
            }

            lifetime.OnTermination(() => myRunningRefreshTask = Task.CompletedTask);

            myRunningRefreshTask = RefreshInternal(lifetime, refreshType);
            return(myRunningRefreshTask);
        }
Пример #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].CurrentGdipBitmapNotSure(),
                ImageAlign = ContentAlignment.MiddleLeft,
                Padding    = new Padding(20, 0, 0, 0)
            });

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

            InitLoginState();
        }
Пример #7
0
        private void InstallPluginIfRequired()
        {
            if (!myUnitySolutionTracker.IsUnityProjectFolder.Value)
            {
                return;
            }

            if (myPluginInstallations.Contains(mySolution.SolutionFilePath))
            {
                return;
            }

            if (!myBoundSettingsStore.GetValue((UnitySettings s) => s.InstallUnity3DRiderPlugin))
            {
                return;
            }

            // forcing fresh install due to being unable to provide proper setting until InputField is patched in Rider
            // ReSharper disable once ArgumentsStyleNamedExpression
            var installationInfo = myDetector.GetInstallationInfo(myCurrentVersion, previousInstallationDir: FileSystemPath.Empty);

            if (!installationInfo.ShouldInstallPlugin)
            {
                myLogger.Info("Plugin should not be installed.");
                if (installationInfo.ExistingFiles.Count > 0)
                {
                    myLogger.Info("Already existing plugin files:\n{0}", string.Join("\n", installationInfo.ExistingFiles));
                }

                return;
            }

            QueueInstall(installationInfo);
            myQueue.Enqueue(() => { myRefresher.Refresh(false); });
        }
Пример #8
0
        protected override bool IsAvailable(IUserDataHolder cache, IMethodDeclaration containingMethod)
        {
            var isHotIconsEnabled = mySettingStore.GetValue((UnitySettings key) => key.EnableIconsForPerformanceCriticalCode);

            if (isHotIconsEnabled)
            {
                return(false);
            }

            return(base.IsAvailable(cache, containingMethod));
        }
Пример #9
0
        public void Refresh(bool force)
        {
            myLocks.AssertMainThread();
            if (IsRefreshing)
            {
                return;
            }

            if (myPluginProtocolController.UnityModel.Value == null)
            {
                return;
            }

            if (!myBoundSettingsStore.GetValue((UnitySettings s) => s.AllowAutomaticRefreshInUnity) && !force)
            {
                return;
            }

            IsRefreshing = true;
            var result = myPluginProtocolController.UnityModel.Value.Refresh.Start(force)?.Result;

            if (result == null)
            {
                IsRefreshing = false;
                return;
            }

            var lifetimeDef = Lifetimes.Define(myLifetime);
            var solution    = mySolution.GetProtocolSolution();
            var solFolder   = mySolution.SolutionFilePath.Directory;

            mySolution.GetComponent <RiderBackgroundTaskHost>().AddNewTask(lifetimeDef.Lifetime,
                                                                           RiderBackgroundTaskBuilder.Create().WithHeader("Refreshing solution in Unity Editor...").AsIndeterminate().AsNonCancelable());

            result.Advise(lifetimeDef.Lifetime, _ =>
            {
                try
                {
                    var list = new List <string> {
                        solFolder.FullPath
                    };
                    solution.GetFileSystemModel().RefreshPaths.Start(new RdRefreshRequest(list, true));
                }
                finally
                {
                    IsRefreshing = false;
                    lifetimeDef.Terminate();
                }
            });
        }
Пример #10
0
        public Task Refresh(bool force)
        {
            myLocks.AssertMainThread();
            if (CurrentTask != null)
            {
                return(CurrentTask);
            }

            if (myEditorProtocol.UnityModel.Value == null)
            {
                return(new Task(() => {}));
            }

            if (!myBoundSettingsStore.GetValue((UnitySettings s) => s.AllowAutomaticRefreshInUnity) && !force)
            {
                return(new Task(() => {}));
            }

            myLogger.Verbose($"myPluginProtocolController.UnityModel.Value.Refresh.StartAsTask, force = {force}");
            var task = myEditorProtocol.UnityModel.Value.Refresh.StartAsTask(force);

            CurrentTask = task;

            var lifetimeDef = Lifetimes.Define(myLifetime);
            var solution    = mySolution.GetProtocolSolution();
            var solFolder   = mySolution.SolutionFilePath.Directory;

            mySolution.GetComponent <RiderBackgroundTaskHost>().AddNewTask(lifetimeDef.Lifetime,
                                                                           RiderBackgroundTaskBuilder.Create().WithHeader("Refreshing solution in Unity Editor...").AsIndeterminate().AsNonCancelable());

            task.ContinueWith(_ =>
            {
                mySolution.Locks.ExecuteOrQueueEx(lifetimeDef.Lifetime, "RefreshPaths", () =>
                {
                    try
                    {
                        var list = new List <string> {
                            solFolder.FullPath
                        };
                        solution.GetFileSystemModel().RefreshPaths.Start(new RdRefreshRequest(list, true));
                    }
                    finally
                    {
                        CurrentTask = null;
                        lifetimeDef.Terminate();
                    }
                });
            });
            return(task);
        }
Пример #11
0
        private void HandleAutoUpdatePlugin(UnrealPluginInstallInfo unrealPluginInstallInfo)
        {
            var     status           = PluginInstallStatus.NoPlugin;
            var     outOfSync        = true;
            Version installedVersion = new Version();

            if (unrealPluginInstallInfo.Location == PluginInstallLocation.Engine)
            {
                status    = PluginInstallStatus.InEngine;
                outOfSync = unrealPluginInstallInfo.EnginePlugin.PluginVersion !=
                            myPathsProvider.CurrentPluginVersion;
                installedVersion = unrealPluginInstallInfo.EnginePlugin.PluginVersion;
            }

            if (unrealPluginInstallInfo.Location == PluginInstallLocation.Game)
            {
                status    = PluginInstallStatus.InGame;
                outOfSync = unrealPluginInstallInfo.ProjectPlugins.Any(description =>
                {
                    var isNotSynced = description.PluginVersion != myPathsProvider.CurrentPluginVersion;
                    if (isNotSynced)
                    {
                        installedVersion = description.PluginVersion;
                    }
                    return(isNotSynced);
                });
            }

            if (!outOfSync)
            {
                return;
            }

            if (myBoundSettingsStore.GetValue((UnrealLinkSettings s) => s.InstallRiderLinkPlugin))
            {
                QueueAutoUpdate(unrealPluginInstallInfo);
                return;
            }

            myLogger.Warn("[UnrealLink]: Plugin is out of sync");
            myUnrealHost.PerformModelAction(model =>
            {
                var isGameAvailable   = !unrealPluginInstallInfo.ProjectPlugins.IsEmpty();
                var isEngineAvailable = myPluginDetector.IsValidEngine();
                model.OnEditorPluginOutOfSync(new EditorPluginOutOfSync(
                                                  installedVersion.ToString(), myPathsProvider.CurrentPluginVersion.ToString(), status,
                                                  isGameAvailable, isEngineAvailable));
            });
        }
Пример #12
0
        private void CreateCheckboxInspectPrivate(Lifetime lifetime, IContextBoundSettingsStoreLive storeOptionsTransactionContext)
        {
            IProperty <bool> property = new Property <bool>(lifetime, "Exceptional::InspectionLevel::InspectPrivateMethodsAndProperties");

            property.SetValue(storeOptionsTransactionContext.GetValue((Settings.ExceptionalSettings key) => key.InspectPrivateMethods));

            property.Change.Advise(lifetime, a =>
            {
                if (!a.HasNew)
                {
                    return;
                }

                storeOptionsTransactionContext.SetValue((Settings.ExceptionalSettings key) => key.InspectPrivateMethods, a.New);
            });

            AddBoolOption((Settings.ExceptionalSettings key) => key.InspectPrivateMethods, OptionsLabels.InspectionLevel.InspectPrivateMethodsAndProperties);
        }
Пример #13
0
        private void CreateCheckboxUsePredefined(Lifetime lifetime, IContextBoundSettingsStoreLive storeOptionsTransactionContext)
        {
            IProperty <bool> property = new Property <bool>(lifetime, "Exceptional::ExceptionTypesAsHint::UsePredefined");

            property.SetValue(storeOptionsTransactionContext.GetValue((Settings.ExceptionalSettings key) => key.UseDefaultOptionalExceptions2));

            property.Change.Advise(lifetime, a =>
            {
                if (!a.HasNew)
                {
                    return;
                }

                storeOptionsTransactionContext.SetValue((Settings.ExceptionalSettings key) => key.UseDefaultOptionalExceptions2, a.New);
            });

            AddBoolOption((Settings.ExceptionalSettings key) => key.UseDefaultOptionalExceptions2, OptionsLabels.ExceptionTypesAsHint.UsePredefined);
        }
Пример #14
0
        private void CreateCheckboxIsDocumentationOfExceptionSubtypeSufficientForReferenceExpressions(Lifetime lifetime, IContextBoundSettingsStoreLive storeOptionsTransactionContext)
        {
            IProperty <bool> property = new Property <bool>(lifetime, "Exceptional::General::IsDocumentationOfExceptionSubtypeSufficientForReferenceExpressions");

            property.SetValue(storeOptionsTransactionContext.GetValue((Settings.ExceptionalSettings key) => key.IsDocumentationOfExceptionSubtypeSufficientForReferenceExpressions));

            property.Change.Advise(lifetime, a =>
            {
                if (!a.HasNew)
                {
                    return;
                }

                storeOptionsTransactionContext.SetValue((Settings.ExceptionalSettings key) => key.IsDocumentationOfExceptionSubtypeSufficientForReferenceExpressions, a.New);
            });

            AddBoolOption((Settings.ExceptionalSettings key) => key.IsDocumentationOfExceptionSubtypeSufficientForReferenceExpressions, OptionsLabels.General.IsDocumentationOfExceptionSubtypeSufficientForReferenceExpressions);
        }
Пример #15
0
        private void CreateCheckboxInspectPublic(Lifetime lifetime, IContextBoundSettingsStoreLive storeOptionsTransactionContext)
        {
            IProperty <bool> property = new Property <bool>(lifetime, "Exceptional::General::DelegateInvocationsMayThrowSystemException");

            property.SetValue(storeOptionsTransactionContext.GetValue((Settings.ExceptionalSettings key) => key.DelegateInvocationsMayThrowExceptions));

            property.Change.Advise(lifetime, a =>
            {
                if (!a.HasNew)
                {
                    return;
                }

                storeOptionsTransactionContext.SetValue((Settings.ExceptionalSettings key) => key.DelegateInvocationsMayThrowExceptions, a.New);
            });

            AddBoolOption((Settings.ExceptionalSettings key) => key.DelegateInvocationsMayThrowExceptions, OptionsLabels.General.DelegateInvocationsMayThrowSystemException);
        }
Пример #16
0
        public UnrealPluginInstaller(Lifetime lifetime, ILogger logger, UnrealPluginDetector pluginDetector,
                                     PluginPathsProvider pathsProvider, ISolution solution, ISettingsStore settingsStore,
                                     IShellLocks shellLocks, UnrealHost unrealHost)
        {
            myLifetime           = lifetime;
            myLogger             = logger;
            myPathsProvider      = pathsProvider;
            myShellLocks         = shellLocks;
            myUnrealHost         = unrealHost;
            myBoundSettingsStore = settingsStore.BindToContextLive(myLifetime, ContextRange.Smart(solution.ToDataContext()));
            myPluginDetector     = pluginDetector;

            myPluginDetector.InstallInfoProperty.Change.Advise_NewNotNull(myLifetime, installInfo =>
            {
                myShellLocks.ExecuteOrQueueReadLockEx(myLifetime, "UnrealPluginInstaller.CheckAllProjectsIfAutoInstallEnabled",
                                                      () =>
                {
                    var unrealPluginInstallInfo = installInfo.New;
                    if (unrealPluginInstallInfo.EnginePlugin.IsPluginAvailable)
                    {
                        // TODO: add install plugin to Engine
                    }
                    ;

                    if (!myBoundSettingsStore.GetValue((UnrealLinkSettings s) => s.InstallRiderLinkPlugin))
                    {
                        foreach (var installDescription in unrealPluginInstallInfo.ProjectPlugins)
                        {
                            if (installDescription.IsPluginAvailable == false ||
                                installDescription.PluginVersion != myPathsProvider.CurrentPluginVersion)
                            {
                                myUnrealHost.PerformModelAction(model => model.OnEditorModelOutOfSync());
                            }
                        }

                        return;
                    }

                    InstallPluginIfRequired(unrealPluginInstallInfo);
                });
            });
            BindToInstallationSettingChange();
            BindToNotificationFixAction();
        }
Пример #17
0
        private void InstallPluginIfRequired(ICollection <IProject> projects)
        {
            if (projects.Count == 0)
            {
                return;
            }

            InstallFromResource(@"Library\resharper-unity-libs\nunit3.5.0\nunit.framework.dll", ".Unity3dRider.Library.resharper_unity_libs.nunit3._5._0.nunit.framework.dll");
            InstallFromResource(@"Library\resharper-unity-libs\pdb2mdb.exe", ".Unity3dRider.Library.resharper_unity_libs.pdb2mdb.exe");

            if (myPluginInstallations.Contains(mySolution.SolutionFilePath))
            {
                return;
            }

            if (!myBoundSettingsStore.GetValue((UnitySettings s) => s.InstallUnity3DRiderPlugin))
            {
                return;
            }

            // forcing fresh install due to being unable to provide proper setting until InputField is patched in Rider
            // ReSharper disable once ArgumentsStyleNamedExpression
            var installationInfo = myDetector.GetInstallationInfo(projects, previousInstallationDir: FileSystemPath.Empty);

            if (!installationInfo.ShouldInstallPlugin)
            {
                myLogger.Info("Plugin should not be installed.");
                if (installationInfo.ExistingFiles.Count > 0)
                {
                    myLogger.Info("Already existing plugin files:\n{0}", string.Join("\n", installationInfo.ExistingFiles));
                }

                return;
            }

            myQueue.Enqueue(() =>
            {
                Install(installationInfo);
                myPluginInstallations.Add(mySolution.SolutionFilePath);
            });
        }
Пример #18
0
        /// <summary>
        /// Calls Refresh in Unity, and RefreshPaths in vfs. If called multiple times while already running, schedules itself again
        /// </summary>
        /// <param name="lifetime"></param>
        /// <param name="refreshType"></param>
        public Task Refresh(Lifetime lifetime, RefreshType refreshType)
        {
            myLocks.AssertMainThread();
            myLocks.ReentrancyGuard.AssertGuarded();

            if (myEditorProtocol.UnityModel.Value == null)
            {
                return(Task.CompletedTask);
            }

            if (!myBoundSettingsStore.GetValue((UnitySettings s) => s.AllowAutomaticRefreshInUnity) &&
                refreshType == RefreshType.Normal)
            {
                return(Task.CompletedTask);
            }



            if (myRunningRefreshTask != null && !myRunningRefreshTask.IsCompleted)
            {
                myLogger.Verbose($"Secondary execution with {refreshType} type saved.");
                mySecondaryRefreshType = refreshType;
                return(myRunningRefreshTask);
            }

            myRunningRefreshTask = RefreshInternal(lifetime, refreshType);
            return(myRunningRefreshTask.ContinueWith(_ =>
            {
                myRunningRefreshTask = null;
                // if refresh signal came during execution preserve it and execute after finish
                if (mySecondaryRefreshType != null)
                {
                    myLogger.Verbose($"Secondary execution with {mySecondaryRefreshType}");
                    return Refresh(lifetime, (RefreshType)mySecondaryRefreshType)
                    .ContinueWith(___ => { mySecondaryRefreshType = null; }, lifetime);
                }

                return Task.CompletedTask;
            }, lifetime).Unwrap());
        }
Пример #19
0
        /// <summary>
        /// Calls Refresh in Unity, and RefreshPaths in vfs. If called multiple times while already running, schedules itself again
        /// </summary>
        /// <param name="force"></param>
        public async void Refresh(RefreshType force)
        {
            myLocks.AssertMainThread();
            if (myEditorProtocol.UnityModel.Value == null)
            {
                return;
            }

            if (!myBoundSettingsStore.GetValue((UnitySettings s) => s.AllowAutomaticRefreshInUnity) && force == RefreshType.Normal)
            {
                return;
            }

            if (myIsRunning)
            {
                myLogger.Verbose($"Secondary execution with {force} type saved.");
                myRefreshType = force;
                return;
            }

            myIsRunning = true;

            await RefreshInternal(force);

            myIsRunning = false;

            if (myRefreshType == null)
            {
                return;
            }

            var type = myRefreshType.Value;

            myRefreshType = null;

            myLogger.Verbose($"Secondary execution with {type}");
            Refresh(type); // if refresh signal came during execution preserve it and execute after finish
        }
Пример #20
0
        public JetBoxOptionsPage(Lifetime lifetime, IUIApplication environment, ClientFactory clientFactory, JetBoxSettingsStorage jetBoxSettings, JetPopupMenus jetPopupMenus, OpensUri opensUri)
            : base(lifetime, environment, PID)
        {
            mySettingsStore = jetBoxSettings.SettingsStore.BindToContextLive(lifetime, ContextRange.ApplicationWide);
              myOpensUri = opensUri;

              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));
              myNonLoggedPanel.Controls.Add(new LinkLabel("Get access (click after approving access on the web)", GetInfo, jetPopupMenus));

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

              InitLoginState();
        }
Пример #21
0
 private void InitClient()
 {
     myClient           = myClientFactory.CreateClient();
     myClient.UserLogin = mySettingsStore.GetValue(JetBoxSettingsAccessor.Login);
 }
        public static IStylerOptions FromSettings(
            IContextBoundSettingsStoreLive settings,
            [CanBeNull] ISolution solution,
            [CanBeNull] string projectPath,
            [CanBeNull] string sourceFilePath)
        {
            // 1. Load global settings
            IStylerOptions fallbackOptions = new StylerOptions();
            IStylerOptions stylerOptions   = new StylerOptions();

            stylerOptions.IndentSize     = settings.GetValue((XamlStylerSettings s) => s.IndentSize);
            stylerOptions.IndentWithTabs = settings.GetValue((XamlStylerSettings s) => s.IndentWithTabs);

            stylerOptions.AttributesTolerance           = settings.GetValue((XamlStylerSettings s) => s.AttributesTolerance);
            stylerOptions.KeepFirstAttributeOnSameLine  = settings.GetValue((XamlStylerSettings s) => s.KeepFirstAttributeOnSameLine);
            stylerOptions.MaxAttributeCharactersPerLine = settings.GetValue((XamlStylerSettings s) => s.MaxAttributeCharactersPerLine);
            stylerOptions.MaxAttributesPerLine          = settings.GetValue((XamlStylerSettings s) => s.MaxAttributesPerLine);
            stylerOptions.NoNewLineElements             = settings.GetValue((XamlStylerSettings s) => s.NoNewLineElements);
            stylerOptions.PutAttributeOrderRuleGroupsOnSeparateLines = settings.GetValue((XamlStylerSettings s) => s.PutAttributeOrderRuleGroupsOnSeparateLines);
            stylerOptions.AttributeIndentation        = settings.GetValue((XamlStylerSettings s) => s.AttributeIndentation);
            stylerOptions.AttributeIndentationStyle   = settings.GetValue((XamlStylerSettings s) => s.AttributeIndentationStyle);
            stylerOptions.RemoveDesignTimeReferences  = settings.GetValue((XamlStylerSettings s) => s.RemoveDesignTimeReferences);
            stylerOptions.EnableAttributeReordering   = settings.GetValue((XamlStylerSettings s) => s.EnableAttributeReordering);
            stylerOptions.AttributeOrderingRuleGroups = settings.GetValue((XamlStylerSettings s) => s.AttributeOrderingRuleGroups)?.SplitByNewLine();
            if (stylerOptions.AttributeOrderingRuleGroups == null || stylerOptions.AttributeOrderingRuleGroups.Length == 0)
            {
                stylerOptions.AttributeOrderingRuleGroups = fallbackOptions.AttributeOrderingRuleGroups;
            }
            stylerOptions.FirstLineAttributes           = settings.GetValue((XamlStylerSettings s) => s.FirstLineAttributes);
            stylerOptions.OrderAttributesByName         = settings.GetValue((XamlStylerSettings s) => s.OrderAttributesByName);
            stylerOptions.PutEndingBracketOnNewLine     = settings.GetValue((XamlStylerSettings s) => s.PutEndingBracketOnNewLine);
            stylerOptions.RemoveEndingTagOfEmptyElement = settings.GetValue((XamlStylerSettings s) => s.RemoveEndingTagOfEmptyElement);
            stylerOptions.SpaceBeforeClosingSlash       = settings.GetValue((XamlStylerSettings s) => s.SpaceBeforeClosingSlash);
            stylerOptions.RootElementLineBreakRule      = settings.GetValue((XamlStylerSettings s) => s.RootElementLineBreakRule);
            stylerOptions.ReorderVSM                = settings.GetValue((XamlStylerSettings s) => s.ReorderVSM);
            stylerOptions.ReorderGridChildren       = settings.GetValue((XamlStylerSettings s) => s.ReorderGridChildren);
            stylerOptions.ReorderCanvasChildren     = settings.GetValue((XamlStylerSettings s) => s.ReorderCanvasChildren);
            stylerOptions.ReorderSetters            = settings.GetValue((XamlStylerSettings s) => s.ReorderSetters);
            stylerOptions.FormatMarkupExtension     = settings.GetValue((XamlStylerSettings s) => s.FormatMarkupExtension);
            stylerOptions.NoNewLineMarkupExtensions = settings.GetValue((XamlStylerSettings s) => s.NoNewLineMarkupExtensions);
            stylerOptions.ThicknessStyle            = settings.GetValue((XamlStylerSettings s) => s.ThicknessStyle);
            stylerOptions.ThicknessAttributes       = settings.GetValue((XamlStylerSettings s) => s.ThicknessAttributes);
            stylerOptions.FormatOnSave              = settings.GetValue((XamlStylerSettings s) => s.FormatOnSave);
            stylerOptions.CommentSpaces             = settings.GetValue((XamlStylerSettings s) => s.CommentSpaces);
            stylerOptions.ConfigPath                = settings.GetValue((XamlStylerSettings s) => s.ConfigPath)?.FullPath;
            stylerOptions.SearchToDriveRoot         = settings.GetValue((XamlStylerSettings s) => s.SearchToDriveRoot);
            stylerOptions.SuppressProcessing        = settings.GetValue((XamlStylerSettings s) => s.SuppressProcessing);

            // 2. Try finding settings in our project/solution?
            if (!string.IsNullOrEmpty(projectPath) || !string.IsNullOrEmpty(sourceFilePath))
            {
                var searchToDriveRoot = settings.GetValue((XamlStylerSettings s) => s.SearchToDriveRoot);

                var highestRootPath = solution != null && !solution.IsTemporary
                    ? (searchToDriveRoot ? Path.GetPathRoot(solution.SolutionFilePath.FullPath) : Path.GetDirectoryName(solution.SolutionFilePath.FullPath))
                    : string.Empty;

                var itemPath = sourceFilePath;

                var configPath = (!string.IsNullOrEmpty(itemPath) && itemPath.StartsWith(highestRootPath, StringComparison.OrdinalIgnoreCase))
                    ? GetConfigPathForProject(highestRootPath, itemPath)
                    : GetConfigPathForProject(projectPath ?? itemPath, itemPath);
                if (!string.IsNullOrEmpty(configPath))
                {
                    stylerOptions            = ((StylerOptions)stylerOptions).Clone();
                    stylerOptions.ConfigPath = configPath;
                }
            }

            // 3. Override with IDE-specifics
            var xamlFormatter = XamlLanguage.Instance.Formatter <ICodeFormatterImpl>();

            if (xamlFormatter != null)
            {
                // Note: stylerOptions.UseVisualStudioIndentSize is hardcoded to "True", which means we'll always use IDE settings when in IDE context.
                // To overcome this, we're ignoring the setting from XamlStyler settings files, and using the configuration in the IDE, so we can toggle this on/off.
                var schema = Shell.Instance.GetComponent <ISettingsSchema>();
                if (/*stylerOptions.UseVisualStudioIndentSize ||*/ settings.GetValue((XamlStylerSettings s) => s.UseIdeIndentSize))
                {
                    stylerOptions.IndentSize = (int)xamlFormatter.GetEntry(schema, key => key.INDENT_SIZE).GetDefaultValueInEntryMemberType();
                }

                if (/*stylerOptions.UseVisualStudioIndentWithTabs ||*/ settings.GetValue((XamlStylerSettings s) => s.UseIdeIndentWithTabs))
                {
                    var ideIndentStyle = (IndentStyle)xamlFormatter.GetEntry(schema, key => key.INDENT_SIZE).GetDefaultValueInEntryMemberType();
                    stylerOptions.IndentWithTabs = ideIndentStyle == IndentStyle.Tab;
                }
            }

            return(stylerOptions);
        }
Пример #23
0
        /// <summary>
        /// Initializes a new instance of the StyleCopOptionsPage class.
        /// </summary>
        /// <param name="lifetime">
        /// The lifetime of the options page.
        /// </param>
        /// <param name="settingsSmartContext">
        /// Our settings context.
        /// </param>
        /// <param name="container">
        /// The component container
        /// </param>
        public StyleCopOptionsPage(
            Lifetime lifetime,
            OptionsSettingsSmartContext settingsSmartContext,
            IComponentContainer container)
            : base(lifetime, settingsSmartContext)
        {
            IContextBoundSettingsStoreLive settingsContext =
                this.OptionsSettingsSmartContext.StoreOptionsTransactionContext;

            this.originalEnablePlugins =
                settingsContext.GetValue((StyleCopOptionsSettingsKey options) => options.PluginsEnabled);
            this.originalPluginsPath =
                settingsContext.GetValue((StyleCopOptionsSettingsKey options) => options.PluginsPath);

            this.AddHeader("Version");

            Assembly assembly            = typeof(StyleCopEnvironment).Assembly;
            string   styleCopFileVersion = GetFileVersionInfo(assembly);

            this.AddText(string.Format("StyleCop.dll {0} ({1})", assembly.GetName().Version, styleCopFileVersion));

            assembly = this.GetType().Assembly;
            string ourFileVersion = GetFileVersionInfo(assembly);

            this.AddText(string.Format("StyleCop.ReSharper.dll {0} ({1})", assembly.GetName().Version, ourFileVersion));

            if (ourFileVersion != styleCopFileVersion)
            {
                TextStyle style = new TextStyle(FontStyle.Bold, Color.Empty, Color.Empty);
                this.AddRichText(
                    new RichText(
                        "Mismatched StyleCop.dll version! Are you running an older version of the Visual Studio plugin?",
                        style));
            }

            this.AddHeader("Options");

            // Note that we have to check to see if the lifetime is terminated before accessing the
            // settings context because WPF will continue to call our CanExecute until a garbage collection
            // breaks the weak reference that WPF holds on command
            this.AddButton(
                "Reset code style options",
                new DelegateCommand(
                    () => CodeStyleOptions.CodeStyleOptionsReset(settingsSmartContext),
                    () => !lifetime.IsTerminated && !CodeStyleOptions.CodeStyleOptionsValid(settingsSmartContext)));

            this.AddHeader("Analysis Performance");
            if (DoesHostSupportRoslynAnalzyers(container))
            {
                this.AddText(
                    "Note: Analysis is automatically disabled if the project references the StyleCop.Analyzers NuGet package, which provides StyleCop analysis for Visual Studio 2015 and C# 6.");
            }

            this.AddBoolOption(
                (StyleCopOptionsSettingsKey options) => options.AnalysisEnabled,
                "Run StyleCop as you type");
            BoolOptionViewModel nonUserFiles =
                this.AddBoolOption(
                    (StyleCopOptionsSettingsKey options) => options.AnalyzeReadOnlyFiles,
                    "Analyze non-user files (not recommended)");

            this.AddBinding(
                nonUserFiles,
                BindingStyle.IsEnabledProperty,
                (StyleCopOptionsSettingsKey options) => options.AnalysisEnabled,
                JetFunc <object> .Identity);

            this.AddHeader("Headers");
            this.AddBoolOption(
                (StyleCopOptionsSettingsKey options) => options.InsertTextIntoDocumentation,
                "Insert text into documentation and file headers");
            this.AddBoolOption(
                (StyleCopOptionsSettingsKey options) => options.UseSingleLineDeclarationComments,
                "Use single lines for declaration headers");
            this.AddBoolOption(
                (StyleCopOptionsSettingsKey options) => options.InsertToDoText,
                "Insert TODO into headers");
            this.AddIntOption(
                (StyleCopOptionsSettingsKey options) => options.DashesCountInFileHeader,
                "Number of dashes in file header text:");

            this.AddHeader("StyleCop Plugins");
            this.AddBoolOption(
                (StyleCopOptionsSettingsKey options) => options.PluginsEnabled,
                "Enable StyleCop plugins");
            this.AddText("Location of StyleCop plugins:");
            Property <FileSystemPath> pluginsPath = this.SetupPluginsPathProperty(lifetime);
            FileChooserViewModel      fileChooser = this.AddFolderChooserOption(
                pluginsPath,
                "Location of StyleCop plugins",
                FileSystemPath.Empty);

            fileChooser.IsEnabledProperty.SetValue(true);
            this.AddBinding(
                fileChooser,
                BindingStyle.IsEnabledProperty,
                (StyleCopOptionsSettingsKey options) => options.PluginsEnabled,
                JetFunc <object> .Identity);

            this.AddHeader("Misc");
            this.AddBoolOption(
                (StyleCopOptionsSettingsKey options) => options.UseExcludeFromStyleCopSetting,
                "Use ExcludeFromStyleCop setting in csproj files");
            this.AddStringOption(
                (StyleCopOptionsSettingsKey options) => options.SuppressStyleCopAttributeJustificationText,
                "Justification for SuppressMessage attribute:");

            // TODO: Add "update file header style" that used to be in code cleanup
            this.FinishPage();
        }
Пример #24
0
        private void InstallPluginIfRequired(Lifetime lifetime, [NotNull] IProject project)
        {
            if (!myBoundSettingsStore.GetValue((UnityPluginSettings s) => s.InstallUnity3DRiderPlugin))
            {
                return;
            }

            if (myPluginInstallations.Contains(project.ProjectFileLocation))
            {
                return;
            }

            var installationInfo = myDetector.GetInstallationInfo(project);

            if (!installationInfo.ShouldInstallPlugin)
            {
                return;
            }

            var currentVersion = typeof(UnityPluginInstaller).Assembly.GetName().Version;

            if (currentVersion <= installationInfo.Version)
            {
                return;
            }

            var isFreshInstall = installationInfo.Version == new Version();

            if (isFreshInstall)
            {
                myLogger.LogMessage(LoggingLevel.INFO, "Fresh install");
            }

            lock (mySyncObj)
            {
                if (myPluginInstallations.Contains(project.ProjectFileLocation))
                {
                    return;
                }

                FileSystemPath installedPath;

                if (!TryInstall(installationInfo, out installedPath))
                {
                    myLogger.LogMessage(LoggingLevel.WARN, "Plugin was not installed");
                }
                else
                {
                    string userTitle;
                    string userMessage;

                    if (isFreshInstall)
                    {
                        userTitle   = "Unity: plugin installed";
                        userMessage =
                            $@"Rider plugin v{currentVersion} for the Unity Editor was automatically installed for the project '{mySolution.Name}'
This allows better integration between the Unity Editor and Rider IDE.
The plugin file can be found on the following path:
{installedPath.MakeRelativeTo(mySolution.SolutionFilePath)}";
                    }
                    else
                    {
                        userTitle   = "Unity: plugin updated";
                        userMessage = $"Rider plugin was succesfully upgraded from version {installationInfo.Version} to {currentVersion}";
                    }

                    myLogger.LogMessage(LoggingLevel.INFO, userTitle);

                    var notification = new RdNotificationEntry(userTitle,
                                                               userMessage, true,
                                                               RdNotificationEntryType.INFO);
                    myNotifications.Notification.Fire(notification);
                }

                myPluginInstallations.Add(project.ProjectFileLocation);
            }
        }
Пример #25
0
        private void InstallPluginIfRequired()
        {
            if (!myUnitySolutionTracker.IsUnityProjectFolder.Value)
            {
                return;
            }

            if (myPluginInstallations.Contains(mySolution.SolutionFilePath))
            {
                return;
            }

            if (!myBoundSettingsStore.GetValue((UnitySettings s) => s.InstallUnity3DRiderPlugin))
            {
                return;
            }

            var versionForSolution = myUnityVersion.ActualVersionForSolution.Value;

            if (versionForSolution >= new Version("2019.2")) // 2019.2+ would not work fine either without Rider package, and when package is present it loads EditorPlugin directly from Rider installation.
            {
                var installationInfoToRemove = myDetector.GetInstallationInfo(myCurrentVersion, previousInstallationDir: FileSystemPath.Empty);
                if (!installationInfoToRemove.PluginDirectory.IsAbsolute)
                {
                    return;
                }

                var pluginDll = installationInfoToRemove.PluginDirectory.Combine(PluginPathsProvider.BasicPluginDllFile);
                if (pluginDll.ExistsFile)
                {
                    myQueue.Enqueue(() =>
                    {
                        myLogger.Info($"Remove {pluginDll}. Rider package should be used instead.");
                        pluginDll.DeleteFile();
                        FileSystemPath.Parse(pluginDll.FullPath + ".meta").DeleteFile();

                        // jetbrainsDir is usually "Assets\Plugins\Editor\JetBrains", however custom locations were also possible
                        var jetbrainsDir = installationInfoToRemove.PluginDirectory;
                        if (jetbrainsDir.GetChildren().Any() || jetbrainsDir.Name != "JetBrains")
                        {
                            return;
                        }
                        jetbrainsDir.DeleteDirectoryNonRecursive();
                        FileSystemPath.Parse(jetbrainsDir.FullPath + ".meta").DeleteFile();
                        var pluginsEditorDir = jetbrainsDir.Directory;
                        if (pluginsEditorDir.GetChildren().Any() || pluginsEditorDir.Name != "Editor")
                        {
                            return;
                        }
                        pluginsEditorDir.DeleteDirectoryNonRecursive();
                        FileSystemPath.Parse(pluginsEditorDir.FullPath + ".meta").DeleteFile();
                        var pluginsDir = pluginsEditorDir.Directory;
                        if (pluginsDir.GetChildren().Any() || pluginsDir.Name != "Plugins")
                        {
                            return;
                        }
                        pluginsDir.DeleteDirectoryNonRecursive();
                        FileSystemPath.Parse(pluginsDir.FullPath + ".meta").DeleteFile();
                    });
                }
                return;
            }

            // forcing fresh install due to being unable to provide proper setting until InputField is patched in Rider
            // ReSharper disable once ArgumentsStyleNamedExpression
            var installationInfo = myDetector.GetInstallationInfo(myCurrentVersion, previousInstallationDir: FileSystemPath.Empty);

            if (!installationInfo.ShouldInstallPlugin)
            {
                myLogger.Info("Plugin should not be installed.");
                if (installationInfo.ExistingFiles.Count > 0)
                {
                    myLogger.Info("Already existing plugin files:\n{0}",
                                  string.Join("\n", installationInfo.ExistingFiles));
                }

                return;
            }

            QueueInstall(installationInfo);
            myQueue.Enqueue(() =>
            {
                mySolution.Locks.Tasks.StartNew(myLifetime, Scheduling.MainGuard,
                                                () => myRefresher.StartRefresh(RefreshType.Normal));
            });
        }
Пример #26
0
        private void InstallPluginIfRequired()
        {
            if (!myUnitySolutionTracker.IsUnityProjectFolder.Value)
            {
                return;
            }

            if (myPluginInstallations.Contains(mySolution.SolutionFilePath))
            {
                return;
            }

            if (!myBoundSettingsStore.GetValue((UnitySettings s) => s.InstallUnity3DRiderPlugin))
            {
                return;
            }

            // Unity 2019.2+ is expected to have com.unity.ide.rider package, which loads EditorPlugin directly from Rider installation
            var manifestJsonFile = mySolution.SolutionDirectory.Combine("Packages/manifest.json");

            if (manifestJsonFile.ExistsFile)
            {
                var text = manifestJsonFile.ReadAllText2().Text;
                //"com.unity.ide.rider": "1.0.7"
                var match = Regex.Match(text, @"""com\.unity\.ide\.rider""\s*:\s*""(?<version>.*)""", RegexOptions.Multiline);
                if (match.Success)
                {
                    if (Version.TryParse(match.Groups["version"].Value, out var version))
                    {
                        if (version >= new Version(1, 0, 7))
                        {
                            myLogger.Verbose($"com.unity.ide.rider version {version}. Skip EditorPlugin installation.");
                            return;
                        }

                        myLogger.Verbose($"com.unity.ide.rider version {version}. EditorPlugin installation continues.");
                    }
                }
            }

            var localPackage = mySolution.SolutionDirectory.Combine("Packages/com.unity.ide.rider/package.json");

            if (localPackage.ExistsFile)
            {
                myLogger.Verbose("Local package com.unity.ide.rider detected, skip EditorPlugin installation.");
                return;
            }

            // forcing fresh install due to being unable to provide proper setting until InputField is patched in Rider
            // ReSharper disable once ArgumentsStyleNamedExpression
            var installationInfo = myDetector.GetInstallationInfo(myCurrentVersion, previousInstallationDir: FileSystemPath.Empty);

            if (!installationInfo.ShouldInstallPlugin)
            {
                myLogger.Info("Plugin should not be installed.");
                if (installationInfo.ExistingFiles.Count > 0)
                {
                    myLogger.Info("Already existing plugin files:\n{0}",
                                  string.Join("\n", installationInfo.ExistingFiles));
                }

                return;
            }

            QueueInstall(installationInfo);
            myQueue.Enqueue(() =>
            {
                mySolution.Locks.Tasks.StartNew(myLifetime, Scheduling.MainDispatcher,
                                                () => myRefresher.Refresh(RefreshType.Normal));
            });
        }