public void Execute(ISolution solution, ITextControl textControl) { if (!MethodDeclaration.IsValid()) { return; } var containingFile = MethodDeclaration.GetContainingFile(); var psiModule = MethodDeclaration.GetPsiModule(); var elementFactory = CSharpElementFactory.GetInstance(psiModule); var declared = MethodDeclaration.DeclaredElement; if (declared != null) { var newName = declared.ShortName + "Async"; var refactoringService = solution.GetComponent<RenameRefactoringService>(); var suggests = new List<string> {newName}; SearchDomainFactory searchDomainFactory = solution.GetComponent<SearchDomainFactory>(); var workflow = (IRefactoringWorkflow)new MethodRenameWorkflow(suggests, solution.GetComponent<IShellLocks>(), searchDomainFactory, refactoringService, solution, "TypoRename"); var renames = RenameRefactoringService.Instance.CreateAtomicRenames(declared, newName, true).ToList(); // var workflow = RenameFromContexts.InitFromNameChanges(solution, renames); // workflow.CreateRefactoring(); Lifetimes.Using(lifetime => RefactoringActionUtil.ExecuteRefactoring(solution.GetComponent<IActionManager>().DataContexts.CreateOnSelection(lifetime, DataRules.AddRule("DoTypoRenameWorkflow", DataConstants.SOLUTION, solution)), workflow)); } }
public void Execute(ISolution solution, ITextControl textControl) { if (!_literalExpression.IsValid()) return; IFile containingFile = _literalExpression.GetContainingFile(); CSharpElementFactory elementFactory = CSharpElementFactory.GetInstance(_literalExpression.GetPsiModule()); IExpression newExpression = null; _literalExpression.GetPsiServices().PsiManager.DoTransaction( () => { using (solution.GetComponent<IShellLocks>().UsingWriteLock()) newExpression = ModificationUtil.ReplaceChild( _literalExpression, elementFactory.CreateExpression("System.Int16.MaxValue")); }, GetType().Name); if (newExpression != null) { IRangeMarker marker = newExpression.GetDocumentRange().CreateRangeMarker(solution.GetComponent<DocumentManager>()); containingFile.OptimizeImportsAndRefs( marker, false, true, NullProgressIndicator.Instance); } }
private Action <ITextControl> ChangeParameters(ISolution solution) { var model = ClrChangeSignatureModel.CreateModel(myMethodDeclaration.DeclaredElement).NotNull(); for (var i = 0; i < myExpectedMethodSignature.Parameters.Length; i++) { var requiredParameter = myExpectedMethodSignature.Parameters[i]; var modelParameter = FindBestMatch(requiredParameter, model, i); if (modelParameter != null) { // If the current index is correct, do nothing. If not, use the original index to find the item to move if (modelParameter.ParameterIndex != i) { model.MoveTo(modelParameter.OriginalParameterIndex, i); } } else { model.Add(i); modelParameter = (ClrChangeSignatureParameter)model.ChangeSignatureParameters[i]; } modelParameter.ParameterName = requiredParameter.Name; modelParameter.ParameterKind = ParameterKind.VALUE; modelParameter.ParameterType = requiredParameter.Type; // Reset everything else modelParameter.IsOptional = false; modelParameter.IsParams = false; modelParameter.IsThis = false; modelParameter.IsVarArg = false; } for (var i = model.ChangeSignatureParameters.Length - 1; i >= myExpectedMethodSignature.Parameters.Length; i--) { model.RemoveAt(i); } var refactoring = new ChangeSignatureRefactoring(model); refactoring.Execute(NullProgressIndicator.Create()); // Ideally, we would now call InplaceRefactoringsManager.Reset to make sure we didn't have // an inplace refactoring highlight. But InplaceRefactoringsManager is internal, so we can't. // We don't want a highlight telling us to "apply signature change refactoring" because we // just have. The only way to remove it is to fire the Escape action return(tc => { var highlightingManager = solution.GetComponent <InplaceRefactoringsHighlightingManager>(); if (highlightingManager.GetHighlightersForTests(tc).Any()) { var actionManager = solution.GetComponent <IActionManager>(); var escapeActionHandler = actionManager.Defs.GetActionDef <EscapeActionHandler>(); escapeActionHandler.EvaluateAndExecute(actionManager); } }); }
// Returns a symbol table for all items. Used to resolve references and provide completion public ISymbolTable GetSymbolTable() { if (myDeclaredElements.IsEmpty()) { return(EmptySymbolTable.INSTANCE); } var psiServices = mySolution.GetComponent <IPsiServices>(); return(new DeclaredElementsSymbolTable <IDeclaredElement>(psiServices, myDeclaredElements.Values)); }
public T4ProjectReferenceManager( [NotNull] IProjectFile projectFile, [NotNull] ISolution solution ) { Graph = solution.GetComponent <IT4FileDependencyGraph>(); TemplateKindProvider = solution.GetComponent <IT4TemplateKindProvider>(); ProjectFile = projectFile; Solution = solution; }
public string GetPresentation(ISolution solution, IDeclaredElement declaredElement, bool prefabImport) { solution.GetComponent <IShellLocks>().AssertReadAccessAllowed(); var hierarchyContainer = solution.GetComponent <AssetDocumentHierarchyElementContainer>(); if (UnityApi.IsDescendantOfScriptableObject((declaredElement as IField)?.Type.GetTypeElement())) { if (Reference is LocalReference localReference && localReference.LocalDocumentAnchor == 0) { return("None"); } var sourceFile = hierarchyContainer.GetSourceFile(Reference, out _); if (sourceFile == null) { return("..."); } var relativePath = sourceFile.DisplayName.Replace('\\', '/').RemoveStart("Assets/"); return(relativePath); } if (Reference.LocalDocumentAnchor == 0) { return("None"); } var processor = solution.GetComponent <AssetHierarchyProcessor>(); var consumer = new UnityScenePathGameObjectConsumer(true); var element = hierarchyContainer.GetHierarchyElement(Reference, prefabImport); if (element == null) { return("..."); } string result = ""; if (!element.IsStripped) { processor.ProcessSceneHierarchyFromComponentToRoot(element, consumer, prefabImport); if (consumer.NameParts.Count == 0) { return("..."); } result += string.Join("/", consumer.NameParts); } if (element is IComponentHierarchy componentHierarchy) { result += $" ({AssetUtils.GetComponentName(solution.GetComponent<MetaFileGuidCache>(), componentHierarchy)})"; } return(result); }
public static void ShowTooltip(IDataContext context, ISolution solution, RichText tooltip) { var shellLocks = solution.Locks; var tooltipManager = solution.GetComponent <ITooltipManager>(); // UPDATE MK var windowContextSource = context.GetData <PopupWindowContextSource>(UIDataConstants.PopupWindowContextSource) ?? solution.GetComponent <IMainWindowPopupWindowContext>().Source; tooltipManager.Show(tooltip, windowContextSource); }
protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var unitTestSessionManager = solution.GetComponent<IUnitTestSessionManager>(); var element = MethodRunnerElement.GetInstance(solution.GetComponent<MethodRunnerProvider>(), myClassDeclaration.GetClrName().FullName, myMethodDeclaration.DeclaredName, myClassDeclaration.IsStatic, myMethodDeclaration.IsStatic); var sessionView = unitTestSessionManager.CreateSession(); sessionView.RunAll(solution.GetComponent<ProcessHostProvider>()); return null; }
public override bool Navigate(ISolution solution, PopupWindowContextSource windowContext, bool transferFocus, TabOptions tabOptions = TabOptions.Default) { if (!solution.GetComponent <ConnectionTracker>().IsConnectionEstablished()) { return(base.Navigate(solution, windowContext, transferFocus, tabOptions)); } var findRequestCreator = solution.GetComponent <UnityEditorFindUsageResultCreator>(); return(findRequestCreator.CreateRequestToUnity(myUnityEventTargetReference, true)); }
private static IParameterInfoContext Enhance([CanBeNull] IParameterInfoContext context, [NotNull] ISolution solution, [NotNull] IContextBoundSettingsStore settings) { if (context == null || !settings.GetValue((ParameterInfoSettings s) => s.Enabled)) { return(context); } return(new EnhancedParameterInfoContext( context, solution.GetComponent <ColorizerPresenter>(), solution.GetComponent <HighlighterIdProviderFactory>(), settings)); }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var sceneName = myWarning.SceneName; Assertion.Assert(sceneName != null, "sceneName != null"); var unityModule = GetUnityModule(solution); Assertion.Assert(unityModule != null, "unityModule != null"); var buildSettings = GetEditorBuildSettings(unityModule); var scenes = GetSceneCollection(buildSettings.GetDominantPsiFile <UnityYamlLanguage>() as IYamlFile) as IBlockSequenceNode; Assertion.Assert(scenes != null, "scene != null"); foreach (var entry in scenes.Entries) { var scene = entry.Value; var sceneRecord = scene as IBlockMappingNode; if (sceneRecord == null) { continue; } var path = GetUnityScenePathRepresentation( (sceneRecord.Entries[1].Content.Value as IPlainScalarNode).NotNull("PlainScalarNode:1").Text.GetText()); var simple = path.Split('/').Last(); var isEnabledPlaneScalarNode = (sceneRecord.Entries[0].Content.Value as IPlainScalarNode).NotNull("PlainScalarNode:0"); var isEnabled = isEnabledPlaneScalarNode.Text.GetText().Equals("1"); if (!isEnabled && (path.Equals(sceneName) || simple.Equals(sceneName))) { using (WriteLockCookie.Create(myWarning.Argument.IsPhysical())) { var text = YamlTokenType.NS_PLAIN_ONE_LINE_IN.Create("1"); if (isEnabledPlaneScalarNode.Text != null) { LowLevelModificationUtil.ReplaceChildRange(isEnabledPlaneScalarNode.Text, isEnabledPlaneScalarNode.Text, text); } else { LowLevelModificationUtil.AddChild(isEnabledPlaneScalarNode.Text, text); } } } solution.GetComponent <IDaemon>().Invalidate(); solution.GetComponent <UnityRefresher>().Refresh(RefreshType.Normal); } return(null); }
/// <summary> /// Performs the QuickFix, ensures the file is both writable and creates a transaction. /// </summary> /// <param name="solution"> /// Current Solution. /// </param> /// <param name="progress"> /// Progress Indicator for the fix. /// </param> /// <returns> /// The execute transaction. /// </returns> protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, JB::JetBrains.Application.Progress.IProgressIndicator progress) { return(delegate(ITextControl textControl) { solution.GetComponent <DocumentManagerOperations>().SaveAllDocuments(); using ( JB::JetBrains.Util.ITransactionCookie documentTransaction = solution.GetComponent <DocumentTransactionManager>().CreateTransactionCookie(JB::JetBrains.Util.DefaultAction.Commit, "action name")) { PsiManager.GetInstance(solution).DoTransaction(() => this.ExecuteWriteLockableTransaction(solution, textControl), "Code cleanup"); } }); }
/// <summary> /// Performs the QuickFix, ensures the file is both writable and creates a transaction. /// </summary> /// <param name="solution"> /// Current Solution. /// </param> /// <param name="progress"> /// Progress Indicator for the fix. /// </param> /// <returns> /// The execute transaction. /// </returns> protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, JetBrains.Application.Progress.IProgressIndicator progress) { return(delegate(ITextControl textControl) { solution.GetComponent <DocumentManagerOperations>().SaveAllDocuments(); using (solution.GetComponent <DocumentTransactionManager>().CreateTransactionCookie(JetBrains.Util.DefaultAction.Commit, "action name")) { var services = solution.GetPsiServices(); services.Transactions.Execute( "Code cleanup", () => services.Locks.ExecuteWithWriteLock(() => { ExecuteTransactionInner(solution, textControl); })); } }); }
public override bool Navigate( ISolution solution, PopupWindowContextSource windowContext, bool transferFocus, TabOptions tabOptions = TabOptions.Default) { var textControlManager = solution.GetComponent <ITextControlManager>(); var declaredElement = OccurrenceElement.NotNull().GetValidDeclaredElement(); if (declaredElement == null) { return(false); } foreach (var declaration in declaredElement.GetDeclarations()) { var sourceFile = declaration.GetSourceFile(); if (sourceFile == null) { continue; } foreach (var textControl in textControlManager.TextControls) { if (textControl.Document != sourceFile.Document) { continue; } var declarationRange = declaration.GetDocumentRange(); var textControlOffset = textControl.Caret.DocumentOffset(); if (!declarationRange.Contains(textControlOffset)) { continue; } var popupWindowContextSource = solution.GetComponent <IMainWindowPopupWindowContext>().Source; return(sourceFile.Navigate( textControl.Selection.OneDocRangeWithCaret(), transferFocus, tabOptions, popupWindowContextSource)); } } return(base.Navigate(solution, windowContext, transferFocus, tabOptions)); }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var element = myMethodDeclaration.DeclaredElement; if (element == null) { return(null); } var unityApi = solution.GetComponent <UnityApi>(); var eventFunction = unityApi.GetUnityEventFunction(element); IType returnType = TypeFactory.CreateTypeByCLRName(eventFunction.ReturnType, myMethodDeclaration.GetPsiModule()); if (eventFunction.ReturnTypeIsArray) { returnType = TypeFactory.CreateArrayType(returnType, 1); } var language = myMethodDeclaration.Language; var changeTypeHelper = LanguageManager.Instance.GetService <IChangeTypeHelper>(language); changeTypeHelper.ChangeType(returnType, element); return(null); }
public IUnitTestRunStrategy GetRunStrategy(IUnitTestElement element) { var project = element.Id.Project; if (!project.IsDotNetCoreProject() || element.Id.TargetFrameworkId.IsNetFramework) { return(Default); } if (_dotNetCoreSdkResolver.GetVersion(project) < ImportantSdkVersions.VsTestVersion) { return(_solution.GetComponent <MspecDotNetTestRunStrategy>()); } return(_solution.GetComponent <MspecDotNetVsTestRunStrategy>()); }
private static (string guid, string[] propertyNames) GetAssetGuidAndPropertyName(ISolution solution, IField declaredElement) { Assertion.Assert(solution.Locks.IsReadAccessAllowed(), "ReadLock required"); var containingType = declaredElement.GetContainingType(); if (containingType == null) { return(null, null); } var sourceFile = declaredElement.GetSourceFiles().FirstOrDefault(); if (sourceFile == null || !sourceFile.GetLocation().NameWithoutExtension.Equals(containingType.ShortName)) { return(null, null); } if (!sourceFile.IsValid()) { return(null, null); } var guid = solution.GetComponent <MetaFileGuidCache>().GetAssetGuid(sourceFile); if (guid == null) { return(null, null); } return(guid, AssetUtils.GetAllNamesFor(declaredElement).ToArray()); }
public GotoGeneratorController( [NotNull] Lifetime lifetime, [NotNull] ISolution solution, [NotNull] IShellLocks locks, [NotNull] IDataContext context, IMainWindowPopupWindowContext mainWindowPopupWindowContext, bool enableMulticore) : base(lifetime, solution, solution, LibrariesFlag.SolutionOnly, locks, enableMulticore, new GotoByNameModel(lifetime), mainWindowPopupWindowContext) { this.EtcItemIcon = IdeThemedIcons.SearchResults.Id; this.ItemsPassFilter = new Property <Func <IOccurrence, bool> >("ItemsPassFilter", this.DefaultFilter); GotoByNameModelManager instance = GotoByNameModelManager.GetInstance(solution); instance.ProcessModel <GotoGeneratorModelInitilizer>(this.Model, lifetime, this.GetType()); ITextControl textControl = context.GetData(TextControlDataConstants.TEXT_CONTROL); Debug.Assert(textControl != null, "textControl != null"); var dataBuilder = new CSharpContextActionDataBuilder(); var generatorDataProvider = new GeneratorDataProvider((ICSharpContextActionDataProvider)dataBuilder.Build(solution, textControl)); var generatorsProvider = solution.GetComponent <GeneratorsProvider>(); var applicableGeneratorsCache = new ApplicableGeneratorsCache(generatorsProvider, generatorDataProvider); this.GotoContext.PutData(ApplicableGeneratorsCacheKey, applicableGeneratorsCache); _executionHost = context.GetComponent <GeneratorExecutionHost>(); }
private void RunBackgroundActivity() { myShellLocks.Dispatcher.AssertAccess(); using (ReadLockCookie.Create()) { Assertion.Assert(myCurrentBackgroundActivityLifetime.IsAlive, "myCurrentBackgroundActivityLifetime.IsAlive"); if (HasDirtyFiles()) { var filesToDelete = new SynchronizedList <IPsiSourceFile>(myDeferredHelperCache.FilesToDrop.Take(BATCH_SIZE)); var filesToAdd = new SynchronizedList <IPsiSourceFile>(myDeferredHelperCache.FilesToProcess.Take(BATCH_SIZE)); var calculatedData = new ConcurrentDictionary <IPsiSourceFile, (long, Dictionary <IDeferredCache, object>)>(); ScheduleBackgroundProcess(filesToDelete, filesToAdd, calculatedData); } else { myCurrentBackgroundActivityLifetimeDefinition.Terminate(); myCurrentBackgroundActivityLifetimeDefinition = null; myCompletedOnce.Value = true; myIsProcessing = false; myLogger.Verbose("Finish processing files in deferred caches"); mySolution.GetComponent <IDaemon>().Invalidate(); } } }
/// <summary>Generates a C# file from a T4 file.</summary> /// <param name="modificationInfo">The modifications that occurred in the T4 file.</param> public override ISecondaryDocumentGenerationResult Generate(PrimaryFileModificationInfo modificationInfo) { if (!(modificationInfo.NewPsiFile is IT4File t4File)) { return(null); } var generator = new T4CSharpCodeGenerator(t4File, _directiveInfoManager); GenerationResult result = generator.Generate(); LanguageService csharpLanguageService = CSharpLanguage.Instance.LanguageService(); if (csharpLanguageService == null) { return(null); } var includedFiles = new OneToSetMap <FileSystemPath, FileSystemPath>(); includedFiles.AddRange(modificationInfo.SourceFile.GetLocation(), t4File.GetNonEmptyIncludePaths()); ISolution solution = modificationInfo.SourceFile.GetSolution(); var t4FileDependencyManager = solution.GetComponent <T4FileDependencyManager>(); return(new T4SecondaryDocumentGenerationResult( modificationInfo.SourceFile, result.Builder.ToString(), csharpLanguageService.LanguageType, new RangeTranslatorWithGeneratedRangeMap(result.GeneratedRangeMap), csharpLanguageService.GetPrimaryLexerFactory(), t4FileDependencyManager, t4File.GetNonEmptyIncludePaths() )); }
public void Execute(ISolution solution, ITextControl textControl) { if (!_literalExpression.IsValid()) { return; } IFile containingFile = _literalExpression.GetContainingFile(); CSharpElementFactory elementFactory = CSharpElementFactory.GetInstance(_literalExpression.GetPsiModule()); IExpression newExpression = null; _literalExpression.GetPsiServices().PsiManager.DoTransaction( () => { using (solution.GetComponent <IShellLocks>().UsingWriteLock()) newExpression = ModificationUtil.ReplaceChild( _literalExpression, elementFactory.CreateExpression("System.Int16.MaxValue")); }, GetType().Name); if (newExpression != null) { IRangeMarker marker = newExpression.GetDocumentRange().CreateRangeMarker(solution.GetComponent <DocumentManager>()); containingFile.OptimizeImportsAndRefs( marker, false, true, NullProgressIndicator.Instance); } }
private static IdentifierTooltipContent TryGetIdentifierTooltipContent([NotNull] IHighlighter highlighter, [NotNull] PsiLanguageType languageType, [NotNull] ISolution solution, [NotNull] IContextBoundSettingsStore settings) { var contentProvider = solution.GetComponent <IdentifierTooltipContentProvider>(); return(contentProvider.TryGetIdentifierContent(highlighter, languageType, settings)); }
public void Execute(ISolution solution, ITextControl textControl) { Shell.Instance.GetComponent <UITaskExecutor>().SingleThreaded.ExecuteTask("Cleanup file", TaskCancelable.No, progress => { progress.TaskName = _profile.Name; progress.Start(1); using (Shell.Instance.GetComponent <ICommandProcessor>().UsingBatchTextChange("Code Cleanup")) { using (var cookie = solution.GetComponent <SolutionDocumentTransactionManager>().CreateTransactionCookie(DefaultAction.Rollback, "Code cleanup")) { var progressIndicator = NullProgressIndicator.Create(); CodeCleanup instance = CodeCleanup.GetInstance(solution); int caret = -1; instance.Run(this._dataProvider.SourceFile, DocumentRange.InvalidRange, ref caret, _profile, NullProgressIndicator.Create()); cookie.Commit(progressIndicator); } } progress.Stop(); }); }
private IEnumerable <DebuggerOutputAssemblyInfo> GetOutputAssembliesInfoInternal() { var assemblyInfoDatabase = mySolution.GetComponent <AssemblyInfoDatabase>(); foreach (var project in mySolution.GetAllProjects().Where(x => x.IsProjectFromUserView())) { var configurations = project.ProjectProperties.ActiveConfigurations; foreach (var targetFrameworkId in project.TargetFrameworkIds) { var pathMap = configurations.TryGetPathMap(targetFrameworkId); var outputAssemblyName = project.GetOutputFilePath(targetFrameworkId).Name; var projectLocation = project.ProjectFileLocation.Parent; var unityOutputPath = projectLocation.Combine("Library/ScriptAssemblies").Combine(outputAssemblyName); if (!unityOutputPath.IsEmpty && unityOutputPath.IsAbsolute) { var assemblyNameInfo = assemblyInfoDatabase.GetAssemblyName(unityOutputPath); if (assemblyNameInfo.IsNullOrEmpty()) { // The file should always exist - Unity will make sure it's there, as long as there are no // compile errors. And if there are compile errors (or the file doesn't exist for other // reasons), then debugging is unlikely to be successful, so there's nothing useful we can // do here myLogger.Warn("Cannot create assembly name for {0}", unityOutputPath); continue; } yield return(new DebuggerOutputAssemblyInfo(assemblyNameInfo, projectLocation.FullPath, unityOutputPath.FullPath, in pathMap)); } } } }
private void AddFile([NotNull] IProjectFile projectFile, [NotNull] PsiModuleChangeBuilder changeBuilder) { ISolution solution = projectFile.GetSolution(); // creates a new T4PsiModule for the file var lifetimeDefinition = Lifetime.Define(_lifetime, T4FilePsiModule.Prefix + projectFile.Name); var psiModule = new T4FilePsiModule( lifetimeDefinition.Lifetime, projectFile, _changeManager, _shellLocks, _t4Environment, PrimaryTargetFrameworkId ); _modules[projectFile] = new ModuleWrapper(psiModule, lifetimeDefinition); psiModule.AddBaseReferences(); changeBuilder.AddModuleChange(psiModule, PsiModuleChange.ChangeType.Added); changeBuilder.AddFileChange(psiModule.SourceFile, PsiModuleChange.ChangeType.Added); // Invalidate files that had this specific files as an include, // and whose IPsiSourceFile was previously managed by T4OutsideSolutionSourceFileManager. // Those files will be reparsed with the new source file. var fileManager = solution.GetComponent <T4OutsideSolutionSourceFileManager>(); VirtualFileSystemPath location = projectFile.Location; if (fileManager.HasSourceFile(location)) { fileManager.DeleteSourceFile(location); } }
public void Execute(IDataContext context, DelegateExecute nextExecute) { ISolution solution = context.GetData(ProjectModelDataConstants.SOLUTION); IShellLocks locks = context.GetComponent <IShellLocks>(); PopupWindowContextSource popupWindowContextSource = context.GetData(UIDataConstants.PopupWindowContextSource); Debug.Assert(popupWindowContextSource != null, "popupWindowContextSource != null"); Debug.Assert(solution != null, "solution != null"); void Atomic(LifetimeDefinition lifetimeDefinition, Lifetime lifetime) { var controller = new GotoGeneratorController( lifetime, solution, locks, context, Shell.Instance.GetComponent <IMainWindowPopupWindowContext>(), false /* enableMulticore */ ); GotoByNameMenu menu = new GotoByNameMenu( context.GetComponent <GotoByNameMenuComponent>(), lifetimeDefinition, controller.Model, context.GetComponent <UIApplication>().MainWindow.TryGetActiveWindow(), solution.GetComponent <GotoByNameModelManager>().GetSearchTextData(context, controller), popupWindowContextSource.Create(lifetime) ); MakeBusyIconVisibleOnEmptyFilter(menu, controller.Model, lifetime); } Lifetimes.Define(solution.GetLifetime(), null /* id */, Atomic); }
private static IdentifierContentGroup GetIdentifierContentGroup( DocumentRange documentRange, [NotNull] ISolution solution, [NotNull] IContextBoundSettingsStore settings) => solution .GetComponent <IdentifierTooltipContentProvider>() .GetIdentifierContentGroup(documentRange, settings);
private static IdentifierContentGroup GetIdentifierContentGroup( [NotNull] IHighlighter highlighter, [NotNull] ISolution solution, [NotNull] IContextBoundSettingsStore settings) => solution .GetComponent <IdentifierTooltipContentProvider>() .GetIdentifierContentGroup(highlighter, settings);
private void CloseTextControl(ITextControl textControl) { if (textControl != null) { _loadedTestSolution.GetComponent <IEditorManager>().CloseTextControl(textControl, CloseTextControlSaveOptions.SaveIfDirty); } }
// Returns a symbol table for all items. Used to resolve references and provide completion public ISymbolTable GetSymbolTable() { var elements = Map.Select(i => { if (!myDeclaredElements.ContainsKey(i.Key)) { lock (this) { if (!myDeclaredElements.ContainsKey(i.Key)) { var element = new AsmDefNameDeclaredElement(mySolution.GetComponent <JavaScriptServices>(), i.Value.Name, i.Key, i.Value.DeclarationOffset); myDeclaredElements.Add(i.Key, element); return(element); } } } return(myDeclaredElements[i.Key]); }).ToList(); if (elements.IsEmpty()) { return(EmptySymbolTable.INSTANCE); } var psiServices = elements.First().GetPsiServices(); return(new DeclaredElementsSymbolTable <IDeclaredElement>(psiServices, elements)); }
public void Execute(ISolution solution, ITextControl textControl) { if (!_literalExpression.IsValid()) { return; } var containingFile = _literalExpression.GetContainingFile(); var psiModule = _literalExpression.GetPsiModule(); var elementFactory = CSharpElementFactory.GetInstance(psiModule); IExpression newExpression = null; _literalExpression.GetPsiServices().Transactions.Execute(GetType().Name, () => { using (solution.GetComponent <IShellLocks>().UsingWriteLock()) newExpression = ModificationUtil.ReplaceChild( _literalExpression.Task, elementFactory.CreateExpression("$0.ConfigureAwait($1)", _literalExpression.Task, elementFactory.CreateExpressionByConstantValue(CSharpConstantValueFactory.CreateBoolValue(_value, psiModule)))); }); if (newExpression != null) { IRangeMarker marker = newExpression.GetDocumentRange().CreateRangeMarker(solution.GetComponent <DocumentManager>()); containingFile.OptimizeImportsAndRefs(marker, false, true, NullProgressIndicator.Instance); } }
private static IEnumerable <IPsiSourceFile> GetAllSolutionFiles([NotNull] ISolution solution) { var psiModules = solution.GetComponent <IPsiModules>(); foreach (var project in solution.GetAllProjects()) { var projectKind = project.ProjectProperties.ProjectKind; if (projectKind == ProjectKind.MISC_FILES_PROJECT) { continue; } foreach (var module in psiModules.GetPsiModules(project)) { foreach (var sourceFile in module.SourceFiles) { // filter out synthetic files out of solution var projectFile = sourceFile.ToProjectFile(); if (projectFile == null) { continue; } yield return(sourceFile); } } } }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var invocationConverter = solution.GetComponent <IInvocationConverter>(); invocationConverter.TryReplaceInvocationToAsync(canBeUseAsyncMethodHighlighting.InvocationExpression); return(null); }
private static IJavaScriptTreeNode DoTransaction(ISolution solution, JavaScriptElementFactory elementFactory, Func<JavaScriptElementFactory, IJavaScriptTreeNode> addMethod) { IJavaScriptTreeNode newExpression; using (solution.GetComponent<IShellLocks>().UsingWriteLock()) { newExpression = addMethod(elementFactory); } return newExpression; }
public void Execute(ISolution solution, ITextControl textControl) { try { if (!_literalExpression.IsValid()) { return; } var psiModule = _literalExpression.GetPsiModule(); var psiManager = _literalExpression.GetPsiServices().PsiManager; var containingFile = _literalExpression.GetContainingFile(); var csharpFile = containingFile as ICSharpFile; var elementFactory = CSharpElementFactory.GetInstance(psiModule); IExpression newExpression = null; psiManager.DoTransaction( () => { using (solution.GetComponent<IShellLocks>().UsingWriteLock()) { var replacementExpression = elementFactory.CreateExpression(_literalExpression.GetText() + ".AsObservable()"); newExpression = ModificationUtil.ReplaceChild(_literalExpression, replacementExpression); EnsureNamespaceExists(csharpFile, elementFactory); } }, GetType().Name); if (newExpression != null) { var marker = newExpression.GetDocumentRange().CreateRangeMarker(solution.GetComponent<DocumentManager>()); containingFile.OptimizeImportsAndRefs(marker, false, true, NullProgressIndicator.Instance); } } catch (Exception exn) { Debug.WriteLine("Failed AsObservableBulbItem, exception message - '{0}'", exn.Message); } }
public void Execute(ISolution solution, ITextControl textControl) { if (!MethodDeclaration.IsValid()) { return; } var declared = MethodDeclaration.DeclaredElement; if (declared != null) { var suggests = AsyncMethodNameSuggestions.Get(MethodDeclaration); var workflow = (IRefactoringWorkflow) new MethodRenameWorkflow(suggests, solution.GetComponent<RenameRefactoringService>(), solution, "AsyncSuffixMethodRename"); Lifetimes.Using(lifetime => { var dataRules = DataRules.AddRule("DoAsyncMethodRenameWorkflow", ProjectModelDataConstants.SOLUTION, solution); var dataContext = solution.GetComponent<IActionManager>().DataContexts.CreateOnSelection(lifetime, dataRules); RefactoringActionUtil.ExecuteRefactoring(dataContext, workflow); }); } }
/// <summary> /// The execute transaction inner. /// </summary> /// <param name="solution"> /// The solution. /// </param> /// <param name="textControl"> /// The text control. /// </param> public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl) { ICSharpFile file = Utils.GetCSharpFile(solution, textControl); Lifetimes.Using( lifetime => { StyleCopApi api = solution.GetComponent<StyleCopApiPool>().GetInstance(lifetime); Settings settings = api.Settings.GetSettings(file.GetSourceFile().ToProjectFile()); // Fixes SA1208, SA1209, SA1210, SA1211 OrderingRules.ExecuteAll(file, settings); }); }
public void Execute(ISolution solution, ITextControl textControl) { if (!_literalExpression.IsValid()) return; var containingFile = _literalExpression.GetContainingFile(); var psiModule = _literalExpression.GetPsiModule(); var elementFactory = CSharpElementFactory.GetInstance(psiModule); IExpression newExpression = null; _literalExpression.GetPsiServices().Transactions.Execute(GetType().Name, () => { using (solution.GetComponent<IShellLocks>().UsingWriteLock()) newExpression = ModificationUtil.ReplaceChild( _literalExpression.Task, elementFactory.CreateExpression("$0.ConfigureAwait($1)", _literalExpression.Task, elementFactory.CreateExpressionByConstantValue(CSharpConstantValueFactory.CreateBoolValue(_value, psiModule)))); }); if (newExpression != null) { IRangeMarker marker = newExpression.GetDocumentRange().CreateRangeMarker(solution.GetComponent<DocumentManager>()); containingFile.OptimizeImportsAndRefs(marker, false, true, NullProgressIndicator.Instance); } }
public YouTrackPowerToyOptionsPage(IOptionsDialog optionsDialog, ISolution solution) { this.solution = solution; if (this.solution != null) { InitializeComponent(); this.youTrackSettings = solution.GetComponent<YouTrackSettings>(); this.youTrackSettingsControl = new YouTrackSettingsControl(this.youTrackSettings); this.Controls.Add(this.youTrackSettingsControl); } else { Controls.Add(JetBrains.UI.Options.Helpers.Controls.CreateNoSolutionCueBanner()); //Controls.Add(new RichTextLabel("You need to have an open solution to access these settings")); } }
public void ExploreSolution(ISolution solution, UnitTestElementConsumer consumer) { TestCache component; try { component = solution.GetComponent<TestCache>(); } catch { return; } component.ReanalyzeDirtyFiles(); foreach (var element in from e in component.UnitTestElements where e.State.IsValid() && (e.Provider is KarmaTestProvider) select e) { consumer(element); } }
/// <inheritdoc /> public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl) { ICSharpFile file = Utils.GetCSharpFile(solution, textControl); Lifetimes.Using( lifetime => { StyleCopApi api = solution.GetComponent<StyleCopApiPool>().GetInstance(lifetime); var settings = api.Settings.GetSettings(file.GetSourceFile().ToProjectFile()); // this covers the issue that constants (and maybe others) return the class if called as GetContainingElement<IDeclaration>) IDeclaration declaration = Utils.GetTypeClosestToTextControl<IDeclaration>(solution, textControl); if (declaration != null) { DocumentationRules.CheckDeclarationDocumentation(file, declaration, settings); } }); }
protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { if (!expression.IsValid()) return null; IFile containingFile = expression.GetContainingFile(); JavaScriptElementFactory elementFactory = JavaScriptElementFactory.GetInstance(expression.GetPsiModule(), JavaScriptLanguage.Instance); IJavaScriptTreeNode newExpression = null; Func<JavaScriptElementFactory, IJavaScriptTreeNode> addMethod = AddUseStrict; expression.GetPsiServices().PsiManager.DoTransaction( () => { newExpression = DoTransaction(solution, elementFactory, addMethod); }, GetType().Name); if (newExpression != null) { IRangeMarker marker = newExpression.GetDocumentRange().CreateRangeMarker(solution.GetComponent<DocumentManager>()); containingFile.OptimizeImportsAndRefs(marker, false, true, NullProgressIndicator.Instance); } return null; }
private static void ShowTooltip(IDataContext context, ISolution solution, RichText tooltip) { var shellLocks = solution.GetComponent<IShellLocks>(); var tooltipManager = solution.GetComponent<ITooltipManager>(); tooltipManager.Show(tooltip, lifetime => { var windowContextSource = context.GetData(UI.DataConstants.PopupWindowContextSource); if (windowContextSource != null) { var windowContext = windowContextSource.Create(lifetime); var ctxTextControl = windowContext as TextControlPopupWindowContext; return ctxTextControl == null ? windowContext : ctxTextControl.OverrideLayouter(lifetime, lifetimeLayouter => new DockingLayouter(lifetimeLayouter, new TextControlAnchoringRect(lifetimeLayouter, ctxTextControl.TextControl, ctxTextControl.TextControl. Caret.Offset(), shellLocks), Anchoring2D.AnchorTopOrBottom)); } return solution.GetComponent<MainWindowPopupWindowContext>().Create(lifetime); }); }
public static L4NIdentifierTooltipProvider GetInstance(ISolution solution) { return solution.GetComponent<L4NIdentifierTooltipProvider>(); }
protected NTriplesCache GetCache(ISolution solution) { // always perform unscoped search return solution.GetComponent<NTriplesCache>(); }
/// <inheritdoc/> protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { return textControl => { using (solution.GetComponent<DocumentTransactionManager>() .CreateTransactionCookie(DefaultAction.Commit, "action name")) { var services = solution.GetPsiServices(); services.Transactions.Execute( "Code cleanup", () => services.Locks.ExecuteWithWriteLock(() => { ICSharpTypeAndNamespaceHolderDeclaration holder = _highlighting.TypeAndNamespaceHolder; Fixes.FixOrder(holder, _highlighting.Config); Fixes.FixSpacing(holder, _highlighting.Config); })); } }; }
public void Execute(ISolution solution, ITextControl textControl) { try { var psiManager = _expression.GetPsiServices().PsiManager; var sourceFile = _expression.GetSourceFile(); if (sourceFile == null) { // What not source file! return; } var psiFile = sourceFile.GetNonInjectedPsiFile<CSharpLanguage>(); if (psiFile == null) { // It's not a CSharp file... return; } var expressions = new List<IInvocationExpression>(); psiFile.ProcessChildren<IInvocationExpression>(expressions.Add); var index = expressions.FindIndex(c => c == _expression); var previousIndex = index + 1; if (previousIndex > (expressions.Count - 1)) { // There isn't a previous invocation expression... return; } var previousExpression = expressions[previousIndex]; var firstChild = previousExpression.FirstChild; if (firstChild == null) { return; } var arugmentList = previousExpression.Children<IArgumentList>().SingleOrDefault(); if (arugmentList == null) { return; } var containingFile = _expression.GetContainingFile(); var elementFactory = CSharpElementFactory.GetInstance(sourceFile.PsiModule); IExpression newExpression = null; psiManager.DoTransaction( () => { using (solution.GetComponent<IShellLocks>().UsingWriteLock()) { var preText = firstChild.GetText(); var arugmentListText = arugmentList.GetText(); var lastSelectIndex = preText.LastIndexOf(Constants.SelectMethodName, StringComparison.Ordinal); var formattedPreText = preText.Remove(lastSelectIndex, Constants.SelectMethodName.Length) .Insert(lastSelectIndex, Constants.SelectManyMethodName); var replacementExpressionText = string.Format(ReplacementTextFormat, formattedPreText, arugmentListText); var replacementExpression = elementFactory.CreateExpression(replacementExpressionText); newExpression = ModificationUtil.ReplaceChild(_expression, replacementExpression); } }, GetType().Name); if (newExpression != null) { var marker = newExpression.GetDocumentRange().CreateRangeMarker(solution.GetComponent<DocumentManager>()); containingFile.OptimizeImportsAndRefs(marker, false, true, NullProgressIndicator.Instance); } } catch (Exception exn) { Debug.WriteLine("Failed SelectAndMergeBulbItem, exception message - '{0}'", exn.Message); } }
/// <summary> /// Performs the QuickFix, ensures the file is both writable and creates a transaction. /// </summary> /// <param name="solution"> /// Current Solution. /// </param> /// <param name="progress"> /// Progress Indicator for the fix. /// </param> /// <returns> /// The execute transaction. /// </returns> protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, JB::JetBrains.Application.Progress.IProgressIndicator progress) { return delegate(ITextControl textControl) { solution.GetComponent<DocumentManagerOperations>().SaveAllDocuments(); using ( JB::JetBrains.Util.ITransactionCookie documentTransaction = solution.GetComponent<DocumentTransactionManager>().CreateTransactionCookie(JB::JetBrains.Util.DefaultAction.Commit, "action name")) { PsiManager.GetInstance(solution).DoTransaction(() => this.ExecuteWriteLockableTransaction(solution, textControl), "Code cleanup"); } }; }
public static DatabaseManager GetInstance(ISolution solution) { return solution.GetComponent<DatabaseManager>(); }
protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var unitTestSessionManager = solution.GetComponent<IUnitTestSessionManager>(); var element = solution.GetComponent<MethodRunnerProvider>().CreateElement(myClassDeclaration.GetSourceFile().GetProject(), new ClrTypeName(myClassDeclaration.CLRName), myMethodDeclaration.DeclaredName, myClassDeclaration.IsStatic, myMethodDeclaration.IsStatic); var unitTestElementManager = solution.GetComponent<IUnitTestElementManager>(); unitTestElementManager.AddElement(element); var sessionView = unitTestSessionManager.GetSession(SessionID) ?? unitTestSessionManager.CreateSession(id: SessionID); sessionView.Title.Value = "Run Method " + myMethodDeclaration.DeclaredName; sessionView.Session.AddElement(element); var launchLifetime = Lifetimes.Define(solution.GetLifetime(), "MethodRunner"); launchLifetime.Lifetime.AddAction(() => { unitTestElementManager.RemoveElements(new[] {element}); unitTestSessionManager.CloseSession(sessionView); }); var unitTestResultManager = solution.GetComponent<IUnitTestResultManager>(); EventHandler<UnitTestResultEventArgs> onUnitTestResultUpdated = (sender, args) => { if (args.Element == element && args.Result.RunStatus == UnitTestRunStatus.Completed) { var exceptions = string.Empty; var resultData = unitTestResultManager.GetResultData(args.Element); if (resultData.Exceptions.Any()) exceptions = resultData.Exceptions.First().StackTrace; MessageBox.ShowInfo(args.Result.Message + " " + resultData.Output + " " + exceptions); // cleanup launchLifetime.Terminate(); } }; unitTestResultManager.UnitTestResultUpdated += onUnitTestResultUpdated; launchLifetime.Lifetime.AddAction(() => unitTestResultManager.UnitTestResultUpdated -= onUnitTestResultUpdated); sessionView.Run(new UnitTestElements(new[] {element}), solution.GetComponent<ProcessHostProvider>()); Assembly.LoadFile(typeof(RunMethodTask).Assembly.Location); return null; }
/// <summary> /// Performs the QuickFix, ensures the file is both writable and creates a transaction. /// </summary> /// <param name="solution"> /// Current Solution. /// </param> /// <param name="progress"> /// Progress Indicator for the fix. /// </param> /// <returns> /// The execute transaction. /// </returns> protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, JetBrains.Application.Progress.IProgressIndicator progress) { return delegate(ITextControl textControl) { solution.GetComponent<DocumentManagerOperations>().SaveAllDocuments(); using (solution.GetComponent<DocumentTransactionManager>().CreateTransactionCookie(JetBrains.Util.DefaultAction.Commit, "action name")) { var services = solution.GetPsiServices(); services.Transactions.Execute( "Code cleanup", () => services.Locks.ExecuteWithWriteLock(() => { ExecuteTransactionInner(solution, textControl); })); } }; }
private IEnumerable<NTriplesFileMemberData> GetPrimaryMembers(ISolution solution) { var cache = solution.GetComponent<NTriplesCache>(); //var subjects = cache.GetImportantSubjects().ToArray(); var symbolsByFile = cache.GetAllUriIdentifierSymbolsByFile(); var services = solution.GetPsiServices(); foreach (var symbols in symbolsByFile) { var file = symbols.Key; var sourceFile = file.GetPsiFile(NTriplesLanguage.Instance, new DocumentRange(file.Document, 0)); foreach (var symbol in symbols.Value) { var uriIdentifier = new UriIdentifierDeclaredElement( sourceFile, symbol.Namespace, symbol.LocalName, symbol.Info, services, true); yield return new NTriplesFileMemberData(uriIdentifier, ContainerDisplayStyle.NoContainer); } } }