Example #1
0
 private void _configService_SettingsChanged(object sender, EventArgs e)
 {
     _config = _configService.LoadConfiguration();
     _hooks.HookHotkeys();
     // also updates the ShortcutKey text
     _appMenus.Localize();
     UpdateLoggingLevel();
 }
Example #2
0
        private void _configService_SettingsChanged(object sender, ConfigurationChangedEventArgs e)
        {
            _config = _configService.LoadConfiguration();
            _hooks.HookHotkeys();
            UpdateLoggingLevel();

            if (e.LanguageChanged)
            {
                ApplyCultureConfig();
            }
        }
        public RubberduckMenu(VBE vbe, AddIn addIn, IGeneralConfigService configService, IRubberduckParser parser, IActiveCodePaneEditor editor, IInspector inspector)
            : base(vbe, addIn)
        {
            _addIn = addIn;
            _parser = parser;
            _configService = configService;

            var testExplorer = new TestExplorerWindow();
            var testEngine = new TestEngine();
            var testGridViewSort = new GridViewSort<TestExplorerItem>(RubberduckUI.Result, false);
            var testPresenter = new TestExplorerDockablePresenter(vbe, addIn, testExplorer, testEngine, testGridViewSort);
            _testMenu = new TestMenu(vbe, addIn, testExplorer, testPresenter);

            var codeExplorer = new CodeExplorerWindow();
            var codePresenter = new CodeExplorerDockablePresenter(parser, vbe, addIn, codeExplorer);
            codePresenter.RunAllTests += CodePresenterRunAllAllTests;
            codePresenter.RunInspections += codePresenter_RunInspections;
            codePresenter.Rename += codePresenter_Rename;
            codePresenter.FindAllReferences += codePresenter_FindAllReferences;
            codePresenter.FindAllImplementations += codePresenter_FindAllImplementations;
            _codeExplorerMenu = new CodeExplorerMenu(vbe, addIn, codeExplorer, codePresenter);

            var todoSettings = configService.LoadConfiguration().UserSettings.ToDoListSettings;
            var todoExplorer = new ToDoExplorerWindow();
            var todoGridViewSort = new GridViewSort<ToDoItem>(RubberduckUI.Priority, false);
            var todoPresenter = new ToDoExplorerDockablePresenter(parser, todoSettings.ToDoMarkers, vbe, addIn, todoExplorer, todoGridViewSort);
            _todoItemsMenu = new ToDoItemsMenu(vbe, addIn, todoExplorer, todoPresenter);

            var inspectionExplorer = new CodeInspectionsWindow();
            var inspectionGridViewSort = new GridViewSort<CodeInspectionResultGridViewItem>(RubberduckUI.Component, false);
            var inspectionPresenter = new CodeInspectionsDockablePresenter(inspector, vbe, addIn, inspectionExplorer, inspectionGridViewSort);
            _codeInspectionsMenu = new CodeInspectionsMenu(vbe, addIn, inspectionExplorer, inspectionPresenter);

            _refactorMenu = new RefactorMenu(IDE, AddIn, parser, editor);
        }
Example #4
0
        public void HookHotkeys()
        {
            Detach();
            _hooks.Clear();

            var config   = _config.LoadConfiguration();
            var settings = config.UserSettings.HotkeySettings;

            _rawinput = new RawInput(_mainWindowHandle);

            var kb = (RawKeyboard)_rawinput.CreateKeyboard();

            _rawinput.AddDevice(kb);
            kb.RawKeyInputReceived += Keyboard_RawKeyboardInputReceived;
            _kb = kb;

            var mouse = (RawMouse)_rawinput.CreateMouse();

            _rawinput.AddDevice(mouse);
            mouse.RawMouseInputReceived += Mouse_RawMouseInputReceived;
            _mouse = mouse;

            foreach (var hotkey in settings.Settings.Where(hotkey => hotkey.IsEnabled))
            {
                RubberduckHotkey assigned;
                if (Enum.TryParse(hotkey.Name, out assigned))
                {
                    var command = Command(assigned);
                    Debug.Assert(command != null);

                    AddHook(new Hotkey(_mainWindowHandle, hotkey.ToString(), command));
                }
            }
            Attach();
        }
Example #5
0
        private void ConfigServiceSettingsChanged(object sender, EventArgs e)
        {
            _config = _configService.LoadConfiguration();

            _timer.Enabled  = _config.UserSettings.GeneralSettings.AutoSaveEnabled;
            _timer.Interval = _config.UserSettings.GeneralSettings.AutoSavePeriod * 1000;
        }
Example #6
0
        public SettingsForm(IGeneralConfigService configService, IOperatingSystem operatingSystem, SettingsViews activeView = SettingsViews.GeneralSettings) : this()
        {
            var config = configService.LoadConfiguration();

            ViewModel = new SettingsControlViewModel(configService,
                                                     config,
                                                     new SettingsView
            {
                Control = new GeneralSettings(new GeneralSettingsViewModel(config, operatingSystem)),
                View    = SettingsViews.GeneralSettings
            },
                                                     new SettingsView
            {
                Control = new TodoSettings(new TodoSettingsViewModel(config)),
                View    = SettingsViews.TodoSettings
            },
                                                     new SettingsView
            {
                Control = new InspectionSettings(new InspectionSettingsViewModel(config)),
                View    = SettingsViews.InspectionSettings
            },
                                                     new SettingsView
            {
                Control = new UnitTestSettings(new UnitTestSettingsViewModel(config)),
                View    = SettingsViews.UnitTestSettings
            },
                                                     new SettingsView
            {
                Control = new IndenterSettings(new IndenterSettingsViewModel(config)),
                View    = SettingsViews.IndenterSettings
            },
                                                     activeView);

            ViewModel.OnWindowClosed += ViewModel_OnWindowClosed;
        }
Example #7
0
        public SettingsForm(IGeneralConfigService configService, SettingsViews activeView = SettingsViews.GeneralSettings) : this()
        {
            var config = configService.LoadConfiguration();

            ViewModel = new SettingsControlViewModel(configService,
                config,
                new SettingsView
                {
                    Control = new GeneralSettings(new GeneralSettingsViewModel(config)),
                    View = SettingsViews.GeneralSettings
                },
                new SettingsView
                {
                    Control = new TodoSettings(new TodoSettingsViewModel(config)),
                    View = SettingsViews.TodoSettings
                },
                new SettingsView
                {
                    Control = new InspectionSettings(new InspectionSettingsViewModel(config)),
                    View = SettingsViews.InspectionSettings
                },
                new SettingsView
                {
                    Control = new UnitTestSettings(new UnitTestSettingsViewModel(config)),
                    View = SettingsViews.UnitTestSettings
                },
                new SettingsView
                {
                    Control = new IndenterSettings(new IndenterSettingsViewModel(config)),
                    View = SettingsViews.IndenterSettings
                },
                activeView);

            ViewModel.OnWindowClosed += ViewModel_OnWindowClosed;
        }
Example #8
0
        public InspectionResultsViewModel(
            RubberduckParserState state,
            IInspector inspector,
            IQuickFixProvider quickFixProvider,
            INavigateCommand navigateCommand,
            ReparseCommand reparseCommand,
            IClipboardWriter clipboard,
            IGeneralConfigService configService,
            ISettingsFormFactory settingsFormFactory,
            IUiDispatcher uiDispatcher)
        {
            _state               = state;
            _inspector           = inspector;
            _quickFixProvider    = quickFixProvider;
            NavigateCommand      = navigateCommand;
            _clipboard           = clipboard;
            _configService       = configService;
            _settingsFormFactory = settingsFormFactory;
            _uiDispatcher        = uiDispatcher;

            RefreshCommand = new DelegateCommand(LogManager.GetCurrentClassLogger(),
                                                 o =>
            {
                IsRefreshing = true;
                IsBusy       = true;
                reparseCommand.Execute(o);
            },
                                                 o => !IsBusy && reparseCommand.CanExecute(o));

            DisableInspectionCommand     = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteDisableInspectionCommand);
            QuickFixCommand              = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteQuickFixCommand, CanExecuteQuickFixCommand);
            QuickFixInProcedureCommand   = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteQuickFixInProcedureCommand, _ => SelectedItem != null && _state.Status == ParserState.Ready);
            QuickFixInModuleCommand      = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteQuickFixInModuleCommand, _ => SelectedItem != null && _state.Status == ParserState.Ready);
            QuickFixInProjectCommand     = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteQuickFixInProjectCommand, _ => SelectedItem != null && _state.Status == ParserState.Ready);
            QuickFixInAllProjectsCommand = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteQuickFixInAllProjectsCommand, _ => SelectedItem != null && _state.Status == ParserState.Ready);
            CopyResultsCommand           = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteCopyResultsCommand, CanExecuteCopyResultsCommand);
            OpenInspectionSettings       = new DelegateCommand(LogManager.GetCurrentClassLogger(), OpenSettings);

            _configService.SettingsChanged += _configService_SettingsChanged;

            // todo: remove I/O work in constructor
            _runInspectionsOnReparse = _configService.LoadConfiguration().UserSettings.CodeInspectionSettings.RunInspectionsOnSuccessfulParse;

            SetInspectionTypeGroupingCommand = new DelegateCommand(LogManager.GetCurrentClassLogger(), param =>
            {
                GroupByInspectionType = (bool)param;
                GroupByLocation       = !(bool)param;
            });

            SetLocationGroupingCommand = new DelegateCommand(LogManager.GetCurrentClassLogger(), param =>
            {
                GroupByLocation       = (bool)param;
                GroupByInspectionType = !(bool)param;
            });

            _state.StateChanged += HandleStateChanged;

            BindingOperations.CollectionRegistering += BindingOperations_CollectionRegistering;
        }
        private IEnumerable <ToDoItem> GetToDoMarkers(CommentNode comment)
        {
            var markers = _configService.LoadConfiguration().UserSettings.ToDoListSettings.ToDoMarkers;

            return(markers.Where(marker => !string.IsNullOrEmpty(marker.Text) &&
                                 comment.CommentText.ToLowerInvariant().Contains(marker.Text.ToLowerInvariant()))
                   .Select(marker => new ToDoItem(marker.Text, comment)));
        }
 private void InitializeConfig()
 {
     _initializing = true;
     // No reason to think this would throw, but if it does, _initializing state needs to be reset.
     try
     {
         if (!_initialized)
         {
             var config = _configService.LoadConfiguration();
             ApplyAutoCompleteSettings(config);
         }
     }
     finally
     {
         _initializing = false;
     }
 }
Example #11
0
        public void ConfigServiceSettingsChanged(object sender, EventArgs e)
        {
            var config = _configService.LoadConfiguration();

            _timer.Enabled = config.UserSettings.GeneralSettings.AutoSaveEnabled &&
                             config.UserSettings.GeneralSettings.AutoSavePeriod != 0;

            _timer.Interval = config.UserSettings.GeneralSettings.AutoSavePeriod * 1000;
        }
Example #12
0
        public _SettingsDialog(IGeneralConfigService configService)
            : this()
        {
            _configService          = configService;
            _config                 = _configService.LoadConfiguration();
            _codeInspectionSettings = _config.UserSettings.CodeInspectionSettings.CodeInspections;

            LoadWindow();

            RegisterEvents();
        }
Example #13
0
        public SettingsForm(IGeneralConfigService configService, IOperatingSystem operatingSystem, IMessageBox messageBox, IVbeSettings vbeSettings, SettingsViews activeView = SettingsViews.GeneralSettings) : this()
        {
            var config = configService.LoadConfiguration();

            ViewModel = new SettingsControlViewModel(messageBox, configService,
                                                     config,
                                                     new SettingsView
            {
                // FIXME inject types marked as ExperimentalFeatures

                /*
                 * These ExperimentalFeatureTypes were originally obtained by directly calling into the IoC container
                 * (since only it knows, which Assemblies have been loaded as Plugins). The code is preserved here for easy access.
                 * RubberduckIoCInstaller.AssembliesToRegister()
                 *     .SelectMany(s => s.DefinedTypes)
                 *     .Where(w => Attribute.IsDefined(w, typeof(ExperimentalAttribute)))
                 */
                Control = new GeneralSettings(new GeneralSettingsViewModel(config, operatingSystem, messageBox, vbeSettings, new List <Type>())),
                View    = SettingsViews.GeneralSettings
            },
                                                     new SettingsView
            {
                Control = new TodoSettings(new TodoSettingsViewModel(config)),
                View    = SettingsViews.TodoSettings
            },
                                                     new SettingsView
            {
                Control = new InspectionSettings(new InspectionSettingsViewModel(config)),
                View    = SettingsViews.InspectionSettings
            },
                                                     new SettingsView
            {
                Control = new UnitTestSettings(new UnitTestSettingsViewModel(config)),
                View    = SettingsViews.UnitTestSettings
            },
                                                     new SettingsView
            {
                Control = new IndenterSettings(new IndenterSettingsViewModel(config)),
                View    = SettingsViews.IndenterSettings
            },
                                                     new SettingsView
            {
                Control = new AutoCompleteSettings(new AutoCompleteSettingsViewModel(config)),
                View    = SettingsViews.AutoCompleteSettings
            },
                                                     new SettingsView
            {
                Control = new WindowSettings(new WindowSettingsViewModel(config)),
                View    = SettingsViews.WindowSettings
            },
                                                     activeView);

            ViewModel.OnWindowClosed += ViewModel_OnWindowClosed;
        }
Example #14
0
        public SettingsForm(IGeneralConfigService configService,
                            IMessageBox messageBox,
                            ISettingsViewModelFactory viewModelFactory,
                            SettingsViews activeView = SettingsViews.GeneralSettings)
            : this()
        {
            var config = configService.LoadConfiguration();

            ViewModel = new SettingsControlViewModel(messageBox, configService,
                                                     config,
                                                     new SettingsView
            {
                Control = new GeneralSettings(viewModelFactory.Create <Rubberduck.Settings.GeneralSettings>(config)),
                View    = SettingsViews.GeneralSettings
            },
                                                     new SettingsView
            {
                Control = new TodoSettings(viewModelFactory.Create <ToDoListSettings>(config)),
                View    = SettingsViews.TodoSettings
            },
                                                     new SettingsView
            {
                Control = new InspectionSettings(viewModelFactory.Create <CodeInspectionSettings>(config)),
                View    = SettingsViews.InspectionSettings
            },
                                                     new SettingsView
            {
                Control = new UnitTestSettings(viewModelFactory.Create <Rubberduck.UnitTesting.Settings.UnitTestSettings>(config)),
                View    = SettingsViews.UnitTestSettings
            },
                                                     new SettingsView
            {
                Control = new IndenterSettings(viewModelFactory.Create <SmartIndenter.IndenterSettings>(config)),
                View    = SettingsViews.IndenterSettings
            },
                                                     new SettingsView
            {
                Control = new AutoCompleteSettings(viewModelFactory.Create <Rubberduck.Settings.AutoCompleteSettings>(config)),
                View    = SettingsViews.AutoCompleteSettings
            },
                                                     new SettingsView
            {
                Control = new WindowSettings(viewModelFactory.Create <Rubberduck.Settings.WindowSettings>(config)),
                View    = SettingsViews.WindowSettings
            },
                                                     new SettingsView
            {
                Control = new AddRemoveReferencesUserSettings(viewModelFactory.Create <ReferenceSettings>()),
                View    = SettingsViews.ReferenceSettings
            },
                                                     activeView);

            ViewModel.OnWindowClosed += ViewModel_OnWindowClosed;
        }
Example #15
0
            private void UpdateInspectionSeverity()
            {
                var config = _configService.LoadConfiguration();

                foreach (var inspection in _inspections)
                {
                    foreach (var setting in config.UserSettings.CodeInspectionSettings.CodeInspections)
                    {
                        if (inspection.Description == setting.Description)
                        {
                            inspection.Severity = setting.Severity;
                        }
                    }
                }
            }
        private void ExecuteDisableInspectionCommand(object parameter)
        {
            if (_selectedInspection == null)
            {
                return;
            }

            var config = _configService.LoadConfiguration();

            var setting = config.UserSettings.CodeInspectionSettings.CodeInspections.Single(e => e.Name == _selectedInspection.Name);

            setting.Severity = CodeInspectionSeverity.DoNotShow;

            Task.Run(() => _configService.SaveConfiguration(config)).ContinueWith(t => RefreshCommand.Execute(null));
        }
        protected override void ExecuteImpl(object parameter)
        {
            var project = parameter as VBProject ?? GetProject();

            if (project == null)
            {
                return;
            }

            var         settings = _configLoader.LoadConfiguration().UserSettings.UnitTestSettings;
            VBComponent component;

            try
            {
                if (settings.BindingMode == BindingMode.EarlyBinding)
                {
                    project.EnsureReferenceToAddInLibrary();
                }

                component      = project.VBComponents.Add(vbext_ComponentType.vbext_ct_StdModule);
                component.Name = GetNextTestModuleName(project);

                var hasOptionExplicit = false;
                if (component.CodeModule.CountOfLines > 0 && component.CodeModule.CountOfDeclarationLines > 0)
                {
                    hasOptionExplicit = component.CodeModule.Lines[1, component.CodeModule.CountOfDeclarationLines].Contains("Option Explicit");
                }

                var options = string.Concat(hasOptionExplicit ? string.Empty : "Option Explicit\r\n", "Option Private Module\r\n\r\n");

                var defaultTestMethod = string.Empty;
                if (settings.DefaultTestStubInNewModule)
                {
                    defaultTestMethod = AddTestMethodCommand.TestMethodTemplate.Replace(
                        AddTestMethodCommand.NamePlaceholder, "TestMethod1");
                }

                component.CodeModule.AddFromString(options + GetTestModule(settings) + defaultTestMethod);
                component.Activate();
            }
            catch (Exception)
            {
                //can we please comment when we swallow every possible exception?
                return;
            }

            _state.OnParseRequested(this, component);
        }
Example #18
0
        private void LoadConfig()
        {
            _config = _configService.LoadConfiguration();

            var currentCulture = RubberduckUI.Culture;

            try
            {
                RubberduckUI.Culture = CultureInfo.GetCultureInfo(_config.UserSettings.LanguageSetting.Code);
            }
            catch (CultureNotFoundException exception)
            {
                MessageBox.Show(exception.Message, "Rubberduck", MessageBoxButtons.OK, MessageBoxIcon.Error);
                _config.UserSettings.LanguageSetting.Code = currentCulture.Name;
                _configService.SaveConfiguration(_config);
            }
        }
        public void HookHotkeys()
        {
            Detach();
            _hooks.Clear();

            var config   = _config.LoadConfiguration();
            var settings = config.UserSettings.GeneralSettings.HotkeySettings;

            AddHook(new KeyboardHook(_vbe));
            AddHook(new MouseHook(_vbe));
            foreach (var hotkey in settings.Where(hotkey => hotkey.IsEnabled))
            {
                AddHook(new Hotkey(_mainWindowHandle, hotkey.ToString(), hotkey.Command));
            }

            Attach();
        }
Example #20
0
        public void HookHotkeys()
        {
            Detach();
            _hooks.Clear();

            var config   = _config.LoadConfiguration();
            var settings = config.UserSettings.HotkeySettings;

            foreach (var hotkeySetting in settings.Settings.Where(hotkeySetting => hotkeySetting.IsEnabled))
            {
                var hotkey = _hotkeyFactory.Create(hotkeySetting, Hwnd);
                if (hotkey != null)
                {
                    AddHook(hotkey);
                }
            }

            Attach();
        }
        protected override void ExecuteImpl(object parameter)
        {
            var project = parameter as IVBProject ?? GetProject();

            if (project.IsWrappingNullReference)
            {
                return;
            }

            var settings = _configLoader.LoadConfiguration().UserSettings.UnitTestSettings;

            if (settings.BindingMode == BindingMode.EarlyBinding)
            {
                project.EnsureReferenceToAddInLibrary();
            }

            var component = project.VBComponents.Add(ComponentType.StandardModule);
            var module    = component.CodeModule;

            component.Name = GetNextTestModuleName(project);

            var hasOptionExplicit = false;

            if (module.CountOfLines > 0 && module.CountOfDeclarationLines > 0)
            {
                hasOptionExplicit = module.GetLines(1, module.CountOfDeclarationLines).Contains("Option Explicit");
            }

            var options = string.Concat(hasOptionExplicit ? string.Empty : "Option Explicit\r\n",
                                        "Option Private Module\r\n\r\n");

            var defaultTestMethod = string.Empty;

            if (settings.DefaultTestStubInNewModule)
            {
                defaultTestMethod = AddTestMethodCommand.TestMethodTemplate.Replace(
                    AddTestMethodCommand.NamePlaceholder, "TestMethod1");
            }

            module.AddFromString(options + GetTestModule(settings) + defaultTestMethod);
            component.Activate();
            _state.OnParseRequested(this, component);
        }
        public InspectionResultsViewModel(RubberduckParserState state, IInspector inspector,
                                          INavigateCommand navigateCommand, ReparseCommand reparseCommand,
                                          IClipboardWriter clipboard, IGeneralConfigService configService, IOperatingSystem operatingSystem)
        {
            _state           = state;
            _inspector       = inspector;
            _navigateCommand = navigateCommand;
            _clipboard       = clipboard;
            _configService   = configService;
            _operatingSystem = operatingSystem;
            _refreshCommand  = new DelegateCommand(LogManager.GetCurrentClassLogger(),
                                                   o => {
                IsBusy = true;
                reparseCommand.Execute(o);
            },
                                                   o => !IsBusy && reparseCommand.CanExecute(o));

            _disableInspectionCommand = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteDisableInspectionCommand);
            _quickFixCommand          = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteQuickFixCommand, CanExecuteQuickFixCommand);
            _quickFixInModuleCommand  = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteQuickFixInModuleCommand, _ => SelectedItem != null && _state.Status == ParserState.Ready);
            _quickFixInProjectCommand = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteQuickFixInProjectCommand, _ => SelectedItem != null && _state.Status == ParserState.Ready);
            _copyResultsCommand       = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteCopyResultsCommand, CanExecuteCopyResultsCommand);
            _openSettingsCommand      = new DelegateCommand(LogManager.GetCurrentClassLogger(), OpenSettings);

            _configService.SettingsChanged += _configService_SettingsChanged;

            // todo: remove I/O work in constructor
            _runInspectionsOnReparse = _configService.LoadConfiguration().UserSettings.CodeInspectionSettings.RunInspectionsOnSuccessfulParse;

            _setInspectionTypeGroupingCommand = new DelegateCommand(LogManager.GetCurrentClassLogger(), param =>
            {
                GroupByInspectionType = (bool)param;
                GroupByLocation       = !(bool)param;
            });

            _setLocationGroupingCommand = new DelegateCommand(LogManager.GetCurrentClassLogger(), param =>
            {
                GroupByLocation       = (bool)param;
                GroupByInspectionType = !(bool)param;
            });

            _state.StateChanged += _state_StateChanged;
        }
Example #23
0
        private void LoadConfig()
        {
            _logger.Debug("Loading configuration");
            _config = _configService.LoadConfiguration();

            var currentCulture = RubberduckUI.Culture;

            try
            {
                CultureManager.UICulture = CultureInfo.GetCultureInfo(_config.UserSettings.GeneralSettings.Language.Code);
                _appMenus.Localize();
            }
            catch (CultureNotFoundException exception)
            {
                _logger.Error(exception, "Error Setting Culture for Rubberduck");
                _messageBox.Show(exception.Message, "Rubberduck", MessageBoxButtons.OK, MessageBoxIcon.Error);
                _config.UserSettings.GeneralSettings.Language.Code = currentCulture.Name;
                _configService.SaveConfiguration(_config);
            }
        }
Example #24
0
        private static void LoadLanguage()
        {
            if (_configService == null)
            {
                _cultureInfo = Resources.RubberduckUI.Culture ?? Dispatcher.CurrentDispatcher.Thread.CurrentUICulture;
                return;
            }

            try
            {
                var config = _configService.LoadConfiguration();
                _cultureInfo = CultureInfo.GetCultureInfo(config.UserSettings.GeneralSettings.Language.Code);

                Dispatcher.CurrentDispatcher.Thread.CurrentUICulture = _cultureInfo;
            }
            catch (CultureNotFoundException)
            {
                _cultureInfo = Resources.RubberduckUI.Culture;
            }
        }
Example #25
0
        public void HookHotkeys()
        {
            Detach();
            _hooks.Clear();

            var config   = _config.LoadConfiguration();
            var settings = config.UserSettings.HotkeySettings;

            foreach (var hotkey in settings.Settings.Where(hotkey => hotkey.IsEnabled))
            {
                RubberduckHotkey assigned;
                if (Enum.TryParse(hotkey.Name, out assigned))
                {
                    var command = Command(assigned);
                    Debug.Assert(command != null);

                    AddHook(new Hotkey(Hwnd, hotkey.ToString(), command));
                }
            }
            Attach();
        }
Example #26
0
        public RubberduckMenu(VBE vbe, AddIn addIn, IGeneralConfigService configService, IRubberduckParser parser, IActiveCodePaneEditor editor, IInspector inspector)
            : base(vbe, addIn)
        {
            _addIn         = addIn;
            _parser        = parser;
            _configService = configService;

            var testExplorer     = new TestExplorerWindow();
            var testEngine       = new TestEngine();
            var testGridViewSort = new GridViewSort <TestExplorerItem>(RubberduckUI.Result, false);
            var testPresenter    = new TestExplorerDockablePresenter(vbe, addIn, testExplorer, testEngine, testGridViewSort);

            _testMenu = new TestMenu(vbe, addIn, testExplorer, testPresenter);

            var codeExplorer  = new CodeExplorerWindow();
            var codePresenter = new CodeExplorerDockablePresenter(parser, vbe, addIn, codeExplorer);

            codePresenter.RunAllTests            += CodePresenterRunAllAllTests;
            codePresenter.RunInspections         += codePresenter_RunInspections;
            codePresenter.Rename                 += codePresenter_Rename;
            codePresenter.FindAllReferences      += codePresenter_FindAllReferences;
            codePresenter.FindAllImplementations += codePresenter_FindAllImplementations;
            _codeExplorerMenu = new CodeExplorerMenu(vbe, addIn, codeExplorer, codePresenter);

            var todoSettings     = configService.LoadConfiguration().UserSettings.ToDoListSettings;
            var todoExplorer     = new ToDoExplorerWindow();
            var todoGridViewSort = new GridViewSort <ToDoItem>(RubberduckUI.Priority, false);
            var todoPresenter    = new ToDoExplorerDockablePresenter(parser, todoSettings.ToDoMarkers, vbe, addIn, todoExplorer, todoGridViewSort);

            _todoItemsMenu = new ToDoItemsMenu(vbe, addIn, todoExplorer, todoPresenter);

            var inspectionExplorer     = new CodeInspectionsWindow();
            var inspectionGridViewSort = new GridViewSort <CodeInspectionResultGridViewItem>(RubberduckUI.Component, false);
            var inspectionPresenter    = new CodeInspectionsDockablePresenter(inspector, vbe, addIn, inspectionExplorer, inspectionGridViewSort);

            _codeInspectionsMenu = new CodeInspectionsMenu(vbe, addIn, inspectionExplorer, inspectionPresenter);

            _refactorMenu = new RefactorMenu(IDE, AddIn, parser, editor);
        }
Example #27
0
        public _SettingsDialog(IGeneralConfigService configService)
            : this()
        {
            _configService = configService;
            _config = _configService.LoadConfiguration();
            _codeInspectionSettings = _config.UserSettings.CodeInspectionSettings.CodeInspections;

            LoadWindow();

            RegisterEvents();
        }
Example #28
0
        private void _configService_SettingsChanged(object sender, EventArgs e)
        {
            _config = _configService.LoadConfiguration();

            LoadWindow();
        }
Example #29
0
        private void ExecuteInternal(IVBProject project, Declaration projectDeclaration)
        {
            if (project == null || project.IsWrappingNullReference)
            {
                return;
            }

            var settings = _configLoader.LoadConfiguration().UserSettings.UnitTestSettings;

            if (settings.BindingMode == BindingMode.EarlyBinding)
            {
                // FIXME: Push the actual adding of TestModules into UnitTesting, which sidesteps VBEInteraction being inaccessble here
                _interaction.EnsureProjectReferencesUnitTesting(project);
            }

            try
            {
                using (var components = project.VBComponents)
                {
                    using (var component = components.Add(ComponentType.StandardModule))
                    {
                        using (var module = component.CodeModule)
                        {
                            component.Name = GetNextTestModuleName(project);

                            var hasOptionExplicit = false;
                            if (module.CountOfLines > 0 && module.CountOfDeclarationLines > 0)
                            {
                                hasOptionExplicit = module.GetLines(1, module.CountOfDeclarationLines)
                                                    .Contains("Option Explicit");
                            }

                            var options = string.Concat(hasOptionExplicit ? string.Empty : "Option Explicit\r\n",
                                                        "Option Private Module\r\n\r\n");

                            if (projectDeclaration != null)
                            {
                                var moduleCodeBuilder  = new StringBuilder();
                                var declarationsToStub = GetDeclarationsToStub(projectDeclaration);

                                foreach (var declaration in declarationsToStub)
                                {
                                    var name = string.Empty;

                                    switch (declaration.DeclarationType)
                                    {
                                    case DeclarationType.Procedure:
                                    case DeclarationType.Function:
                                        name = declaration.IdentifierName;
                                        break;

                                    case DeclarationType.PropertyGet:
                                        name = $"Get{declaration.IdentifierName}";
                                        break;

                                    case DeclarationType.PropertyLet:
                                        name = $"Let{declaration.IdentifierName}";
                                        break;

                                    case DeclarationType.PropertySet:
                                        name = $"Set{declaration.IdentifierName}";
                                        break;
                                    }

                                    var stub = AddTestMethodCommand.TestMethodTemplate.Replace(
                                        AddTestMethodCommand.NamePlaceholder, $"{name}_Test");
                                    moduleCodeBuilder.AppendLine(stub);
                                }

                                module.AddFromString(options + GetTestModule(settings) + moduleCodeBuilder);
                            }
                            else
                            {
                                var defaultTestMethod = settings.DefaultTestStubInNewModule
                                    ? AddTestMethodCommand.TestMethodTemplate.Replace(
                                    AddTestMethodCommand.NamePlaceholder,
                                    "TestMethod1")
                                    : string.Empty;

                                module.AddFromString(options + GetTestModule(settings) + defaultTestMethod);
                            }
                        }

                        component.Activate();
                    }
                }
            }
            catch (Exception ex)
            {
                _messageBox.Message(TestExplorer.Command_AddTestModule_Error);
                Logger.Warn("Unable to add test module. An exception was thrown.");
                Logger.Warn(ex);
            }

            _state.OnParseRequested(this);
        }
Example #30
0
        public InspectionResultsViewModel(
            RubberduckParserState state,
            IInspector inspector,
            IQuickFixProvider quickFixProvider,
            INavigateCommand navigateCommand,
            ReparseCommand reparseCommand,
            IClipboardWriter clipboard,
            IGeneralConfigService configService,
            ISettingsFormFactory settingsFormFactory,
            IUiDispatcher uiDispatcher)
        {
            _state               = state;
            _inspector           = inspector;
            _quickFixProvider    = quickFixProvider;
            NavigateCommand      = navigateCommand;
            _clipboard           = clipboard;
            _configService       = configService;
            _settingsFormFactory = settingsFormFactory;
            _uiDispatcher        = uiDispatcher;

            RefreshCommand = new DelegateCommand(LogManager.GetCurrentClassLogger(),
                                                 o =>
            {
                IsRefreshing     = true;
                IsBusy           = true;
                var cancellation = new ReparseCancellationFlag();
                reparseCommand.Execute(cancellation);
                if (cancellation.Canceled)
                {
                    IsBusy = false;
                }
            },
                                                 o => !IsBusy && reparseCommand.CanExecute(o));

            DisableInspectionCommand     = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteDisableInspectionCommand);
            QuickFixCommand              = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteQuickFixCommand, CanExecuteQuickFixCommand);
            QuickFixInProcedureCommand   = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteQuickFixInProcedureCommand, _ => SelectedItem != null && _state.Status == ParserState.Ready);
            QuickFixInModuleCommand      = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteQuickFixInModuleCommand, _ => SelectedItem != null && _state.Status == ParserState.Ready);
            QuickFixInProjectCommand     = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteQuickFixInProjectCommand, _ => SelectedItem != null && _state.Status == ParserState.Ready);
            QuickFixInAllProjectsCommand = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteQuickFixInAllProjectsCommand, _ => SelectedItem != null && _state.Status == ParserState.Ready);
            CopyResultsCommand           = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteCopyResultsCommand, CanExecuteCopyResultsCommand);
            OpenInspectionSettings       = new DelegateCommand(LogManager.GetCurrentClassLogger(), OpenSettings);
            CollapseAllCommand           = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteCollapseAll);
            ExpandAllCommand             = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteExpandAll);

            _configService.SettingsChanged += _configService_SettingsChanged;

            // todo: remove I/O work in constructor
            _runInspectionsOnReparse = _configService.LoadConfiguration().UserSettings.CodeInspectionSettings.RunInspectionsOnSuccessfulParse;

            if (CollectionViewSource.GetDefaultView(_results) is ListCollectionView results)
            {
                results.Filter     = inspection => InspectionFilter((IInspectionResult)inspection);
                results.CustomSort = this;
                Results            = results;
            }

            OnPropertyChanged(nameof(Results));
            Grouping = InspectionResultGrouping.Type;

            _state.StateChanged += HandleStateChanged;
        }
Example #31
0
            private void ConfigServiceSettingsChanged(object sender, EventArgs e)
            {
                var config = _configService.LoadConfiguration();

                UpdateInspectionSeverity(config);
            }
Example #32
0
        protected override void OnExecute(object parameter)
        {
            var parameterIsModuleDeclaration = parameter is ProceduralModuleDeclaration || parameter is ClassModuleDeclaration;

            var project = parameter as IVBProject ??
                          (parameterIsModuleDeclaration ? ((Declaration)parameter).Project : GetProject());

            if (project == null || project.IsWrappingNullReference)
            {
                return;
            }

            var settings = _configLoader.LoadConfiguration().UserSettings.UnitTestSettings;

            if (settings.BindingMode == BindingMode.EarlyBinding)
            {
                project.EnsureReferenceToAddInLibrary();
            }

            try
            {
                using (var components = project.VBComponents)
                {
                    using (var component = components.Add(ComponentType.StandardModule))
                    {
                        using (var module = component.CodeModule)
                        {
                            component.Name = GetNextTestModuleName(project);

                            var hasOptionExplicit = false;
                            if (module.CountOfLines > 0 && module.CountOfDeclarationLines > 0)
                            {
                                hasOptionExplicit = module.GetLines(1, module.CountOfDeclarationLines)
                                                    .Contains("Option Explicit");
                            }

                            var options = string.Concat(hasOptionExplicit ? string.Empty : "Option Explicit\r\n",
                                                        "Option Private Module\r\n\r\n");

                            if (parameterIsModuleDeclaration)
                            {
                                var moduleCodeBuilder  = new StringBuilder();
                                var declarationsToStub = GetDeclarationsToStub((Declaration)parameter);

                                foreach (var declaration in declarationsToStub)
                                {
                                    var name = string.Empty;

                                    switch (declaration.DeclarationType)
                                    {
                                    case DeclarationType.Procedure:
                                    case DeclarationType.Function:
                                        name = declaration.IdentifierName;
                                        break;

                                    case DeclarationType.PropertyGet:
                                        name = $"Get{declaration.IdentifierName}";
                                        break;

                                    case DeclarationType.PropertyLet:
                                        name = $"Let{declaration.IdentifierName}";
                                        break;

                                    case DeclarationType.PropertySet:
                                        name = $"Set{declaration.IdentifierName}";
                                        break;
                                    }

                                    var stub = AddTestMethodCommand.TestMethodTemplate.Replace(
                                        AddTestMethodCommand.NamePlaceholder, $"{name}_Test");
                                    moduleCodeBuilder.AppendLine(stub);
                                }

                                module.AddFromString(options + GetTestModule(settings) + moduleCodeBuilder);
                            }
                            else
                            {
                                var defaultTestMethod = settings.DefaultTestStubInNewModule
                                    ? AddTestMethodCommand.TestMethodTemplate.Replace(
                                    AddTestMethodCommand.NamePlaceholder,
                                    "TestMethod1")
                                    : string.Empty;

                                module.AddFromString(options + GetTestModule(settings) + defaultTestMethod);
                            }
                        }

                        component.Activate();
                    }
                }
            }
            catch (Exception ex)
            {
                _messageBox.Show(RubberduckUI.Command_AddTestModule_Error);
                Logger.Warn("Unable to add test module. An exception was thrown.");
                Logger.Warn(ex);
            }
            _state.OnParseRequested(this);
        }
Example #33
0
            public async Task <IEnumerable <IInspectionResult> > FindIssuesAsync(RubberduckParserState state, CancellationToken token)
            {
                if (state == null || !state.AllUserDeclarations.Any())
                {
                    return(new IInspectionResult[] { });
                }
                token.ThrowIfCancellationRequested();

                state.OnStatusMessageUpdate(RubberduckUI.CodeInspections_Inspecting);
                var allIssues = new ConcurrentBag <IInspectionResult>();

                token.ThrowIfCancellationRequested();

                var config = _configService.LoadConfiguration();

                UpdateInspectionSeverity(config);
                token.ThrowIfCancellationRequested();

                var parseTreeInspections = _inspections
                                           .Where(inspection => inspection.Severity != CodeInspectionSeverity.DoNotShow)
                                           .OfType <IParseTreeInspection>()
                                           .ToArray();

                token.ThrowIfCancellationRequested();

                foreach (var listener in parseTreeInspections.Select(inspection => inspection.Listener))
                {
                    listener.ClearContexts();
                }

                // Prepare ParseTreeWalker based inspections
                var passes = Enum.GetValues(typeof(CodeKind)).Cast <CodeKind>();

                foreach (var parsePass in passes)
                {
                    try
                    {
                        WalkTrees(config.UserSettings.CodeInspectionSettings, state, parseTreeInspections.Where(i => i.TargetKindOfCode == parsePass), parsePass);
                    }
                    catch (Exception e)
                    {
                        LogManager.GetCurrentClassLogger().Warn(e);
                    }
                }
                token.ThrowIfCancellationRequested();

                var inspectionsToRun = _inspections.Where(inspection =>
                                                          inspection.Severity != CodeInspectionSeverity.DoNotShow &&
                                                          RequiredLibrariesArePresent(inspection, state) &&
                                                          RequiredHostIsPresent(inspection));

                token.ThrowIfCancellationRequested();

                try
                {
                    await Task.Run(() => RunInspectionsInParallel(inspectionsToRun, allIssues, token));
                }
                catch (AggregateException exception)
                {
                    if (exception.Flatten().InnerExceptions.All(ex => ex is OperationCanceledException))
                    {
                        //This eliminates the stack trace, but for the cancellation, this is irrelevant.
                        throw exception.InnerException ?? exception;
                    }

                    LogManager.GetCurrentClassLogger().Error(exception);
                }
                catch (OperationCanceledException)
                {
                    throw;
                }
                catch (Exception e)
                {
                    LogManager.GetCurrentClassLogger().Error(e);
                }

                var issuesByType = allIssues.GroupBy(issue => issue.Inspection.Name)
                                   .ToDictionary(grouping => grouping.Key, grouping => grouping.ToList());
                var results = issuesByType.Where(kv => kv.Value.Count <= AGGREGATION_THRESHOLD)
                              .SelectMany(kv => kv.Value)
                              .Union(issuesByType.Where(kv => kv.Value.Count > AGGREGATION_THRESHOLD)
                                     .Select(kv => new AggregateInspectionResult(kv.Value.OrderBy(i => i.QualifiedSelection).First(), kv.Value.Count)))
                              .ToList();

                state.OnStatusMessageUpdate(RubberduckUI.ResourceManager.GetString("ParserState_" + state.Status, CultureInfo.CurrentUICulture)); // should be "Ready"
                return(results);
            }