protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var factory = CSharpElementFactory.GetInstance(_statement); var valueType = GuessValueType(_dictionary) ?? "var"; var valueVariableName = SuggestVariableName(_statement, "value"); var valueReference = factory.CreateReferenceExpression(valueVariableName); var valueDeclaration = factory.CreateStatement("$0 $1;", valueType, valueVariableName); var newCondition = factory.CreateExpression("$0.TryGetValue($1, out $2)", _dictionary, _key, valueReference); using (_statement.CreateWriteLock()) { _dictionaryAccess.Where(x => x.IsValid()).ForEach(e => ModificationUtil.ReplaceChild(e, valueReference)); ModificationUtil.ReplaceChild(_matchedElement, newCondition); if (_statement.Parent is IBlock) { ModificationUtil.AddChildBefore(_statement, valueDeclaration); } else { _statement.ReplaceBy(factory.CreateBlock("{$0$1}", valueDeclaration, _statement)); } } return null; }
/// <summary> /// Executes QuickFix or ContextAction. Returns post-execute method. /// </summary> /// <returns> /// Action to execute after document and PSI transaction finish. Use to open TextControls, navigate caret, etc. /// </returns> protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { this.highlighting.PropertyDeclaration.AccessorDeclarations.First(o => o.Kind == AccessorKind.SETTER).SetAccessRights(AccessRights.PRIVATE); return null; }
protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var factory = CSharpElementFactory.GetInstance(_literalExpression); var newExpr = factory.CreateExpressionAsIs(_replacement); _literalExpression.ReplaceBy(newExpr); return null; }
protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var block = myProvider.GetSelectedElement<IBlock>().NotNull(); var statements = block.GetStatementsRange(myProvider.SelectedTreeRange).Statements; var invocation = ExtractInvocation(statements[0]).NotNull(); for (int i = 1; i < statements.Count - 1; i++) { var nextInvocation = ExtractInvocation(statements[i]).NotNull(); invocation = MergeInvocations(invocation, nextInvocation); } var lastDeclaredVariable = ExtractDeclaredVariableName(statements[statements.Count - 2]); var lastInvocationUse = FindLastInvocationUse(statements[statements.Count - 1], lastDeclaredVariable.Name).NotNull(); var lastInvocation = lastInvocationUse.GetContainingNode<IInvocationExpression>().NotNull(); MergeInvocations(invocation, lastInvocation); for (int i = 0; i < statements.Count - 1; i++) { block.RemoveStatement((ICSharpStatement) statements[i]); } var lastStatementCoords = DocumentHelper.GetPositionAfterStatement(statements[statements.Count - 1], myProvider.Document); return textControl => { textControl.Selection.RemoveSelection(false); textControl.Caret.MoveTo(lastStatementCoords, CaretVisualPlacement.DontScrollIfVisible); }; }
protected sealed override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { Debug.Assert(attributesOwnerDeclaration != null); Debug.Assert(createAttributeFactory != null); try { using (WriteLockCookie.Create()) { var factory = CSharpElementFactory.GetInstance(provider.PsiModule); var attribute = createAttributeFactory(factory); Debug.Assert(attribute != null); attributesOwnerDeclaration.AddAttributeAfter(attribute, attributeToRemove); if (attributeToRemove != null) { attributesOwnerDeclaration.RemoveAttribute(attributeToRemove); } ContextActionUtils.FormatWithDefaultProfile(attribute); } return _ => { }; } finally { attributeToRemove = null; createAttributeFactory = null; attributesOwnerDeclaration = null; } }
public StringExtractor(string text, IProgressIndicator progressIndicator) : base(progressIndicator) { m_Text = text; ProgressIndicator = progressIndicator; ProgressIndicator.Maximum = m_Text.Length; }
protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { if (_invocationExpression.ArgumentList.Arguments.Count == 4) { _invocationExpression.RemoveArgument(_invocationExpression.ArgumentList.Arguments[3]); var argument = Provider.ElementFactory.CreateArgument(ParameterKind.VALUE, Provider.ElementFactory.CreateExpression("false")); _invocationExpression.AddArgumentAfter(argument, _invocationExpression.ArgumentList.Arguments[2]); } else { if (_invocationExpression.ArgumentList.Arguments.Count == 1) { var argument = Provider.ElementFactory.CreateArgument(ParameterKind.VALUE, Provider.ElementFactory.CreateExpression("default($0)", PropertyDeclaration.Type)); _invocationExpression.AddArgumentAfter(argument, _invocationExpression.ArgumentList.Arguments[0]); } if (_invocationExpression.ArgumentList.Arguments.Count == 2) { var argument = Provider.ElementFactory.CreateArgument(ParameterKind.VALUE, Provider.ElementFactory.CreateExpression("null")); _invocationExpression.AddArgumentAfter(argument, _invocationExpression.ArgumentList.Arguments[1]); } if (_invocationExpression.ArgumentList.Arguments.Count == 3) { var argument = Provider.ElementFactory.CreateArgument(ParameterKind.VALUE, Provider.ElementFactory.CreateExpression("false")); _invocationExpression.AddArgumentAfter(argument, _invocationExpression.ArgumentList.Arguments[2]); } } return null; }
public override bool PostExecute(IProgressIndicator pi) { try { if (!base.PostExecute(pi)) return false; RunnerFileWatcher.Path = Solution.SolutionFilePath.Directory.FullPath; RunnerFileWatcher.OnFileChange(f => ObjectFactory.NewRenameStep ( f.FeatureFileFromRunner(), InitialName, InitialStageExecuter.NewName ) .Execute()); } catch (Exception e) { MessageBox.ShowInfo(e.ToString()); } return true; }
/// <summary> /// Executes QuickFix or ContextAction. Returns post-execute method. /// </summary> /// <param name="solution">The solution.</param> /// <param name="progress">The progress.</param> /// <returns>Action to execute after document and PSI transaction finish. Use to open TextControls, navigate caret, etc.</returns> protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var model = this.GetModel(); if (model == null) { return null; } var function = model.Method; if (function != null) { function.SetAbstract(true); function.SetVirtual(false); function.SetBody(null); } var property = model.Property; if (property != null) { property.SetAbstract(true); property.SetVirtual(false); foreach (var accessor in property.AccessorDeclarations) { accessor.SetBody(null); } } model.Class.SetAbstract(true); return null; }
private bool ConvertMethods(IProgressIndicator pi) { if (base.NewMembers == null) return false; const int totalWorkUnits = 3; pi.Start(totalWorkUnits); var myWorkflow = Workflow as SharedToExtensionWorkflow; if (myWorkflow != null) Methods = base.NewMembers.OfType<IMethod>().ToList(); using (var progressIndicator = pi.CreateSubProgress(1.0)) FindUsages(progressIndicator); var isSharedToExtension = (this.Direction == SharedToExtensionWorkflow.WorkflowDirection.SharedToExtension); this.Methods.ForEachWithProgress(pi.CreateSubProgress(1.0), "", method => { this.Constructors[method.PresentationLanguage].MakeFirstPrameterThis(method, isSharedToExtension, this.Driver); method.GetPsiServices().Caches.Update(); }); if (isSharedToExtension) using (var progressIndicator = pi.CreateSubProgress(1.0)) MakeCallExtension(progressIndicator); else using (var progressIndicator = pi.CreateSubProgress(1.0)) MakeCallShared(progressIndicator); return true; }
/// <summary> /// Executes QuickFix or ContextAction. Returns post-execute method. /// </summary> /// <returns> /// Action to execute after document and PSI transaction finish. Use to open TextControls, navigate caret, etc. /// </returns> protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var declaration = this.highlight.GetEstablishmentMethodDeclaration(); declaration.SetSealed(true); return null; }
protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var exceptionDeclaration = (IClassDeclaration)_highlighting.ExceptionClass.GetDeclarations().FirstOrDefault(); Contract.Assert(exceptionDeclaration != null); using (var workflow = GeneratorWorkflowFactory.CreateWorkflowWithoutTextControl( GeneratorStandardKinds.Constructor, exceptionDeclaration, exceptionDeclaration)) { Contract.Assert(workflow != null); var ctors = workflow.Context.ProvidedElements .OfType<GeneratorDeclaredElement<IConstructor>>() .Where(ge => _missedConstructorPredicate(ge.DeclaredElement)) .ToList(); Contract.Assert(ctors.Count != 0); workflow.Context.InputElements.Clear(); workflow.Context.InputElements.AddRange(ctors); workflow.BuildOptions(); workflow.Generate("Generate missing constructor", NullProgressIndicator.Instance); } return null; }
protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { T4StatementBlock statementBlock = _highlighting.AssociatedNode; var file = statementBlock.GetContainingFile() as IT4File; Assertion.AssertNotNull(file, "file != null"); T4FeatureBlock feature = file.GetFeatureBlocks().First(); ITreeNode featureBlock; using (file.CreateWriteLock()) { // clone the statement block and add it before the feature block ITreeNode featurePrevSibling = feature.PrevSibling; featureBlock = ModificationUtil.CloneNode(statementBlock, node => { }); featureBlock = ModificationUtil.AddChildBefore(feature, featureBlock); // add a new line before the new statement block if needed if (featurePrevSibling != null && featurePrevSibling.GetTokenType() == T4TokenNodeTypes.NewLine) ModificationUtil.AddChildAfter(featureBlock, T4TokenNodeTypes.NewLine.CreateLeafElement()); ModificationUtil.DeleteChild(statementBlock); } return textControl => { TextRange range = featureBlock.GetDocumentRange().TextRange; textControl.Caret.MoveTo(range.EndOffset, CaretVisualPlacement.Generic); }; }
protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { _executing = true; var treeRange = AdjustTreeRange(_range); if (treeRange == null) return null; var first = treeRange.First; var last = treeRange.Last; for (var prevSibling = first.PrevSibling; prevSibling is IWhitespaceNode && !((IWhitespaceNode) prevSibling).IsNewLine; prevSibling = prevSibling.PrevSibling) first = prevSibling; for (var nextSibling = last.NextSibling; nextSibling is IWhitespaceNode; nextSibling = nextSibling.NextSibling) { last = nextSibling; if (((IWhitespaceNode) last).IsNewLine) break; } var containingNode = first.GetContainingNode<IJavaScriptStatement>(true); using (WriteLockCookie.Create()) ModificationUtil.DeleteChildRange(new TreeRange(first, last)); _executing = false; if (containingNode != null && containingNode.IsValid()) { var containingFile = containingNode.GetContainingFile(); if (containingFile != null) containingFile.ReParse(containingNode.GetTreeTextRange(), containingNode.GetText()); } return null; }
protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { ITypeDeclaration typeDeclaration = GetTargetTypeDeclaration(_highlighting.DeclaredTypeUsage); if (typeDeclaration == null) return null; MemberSignature signature = CreateTransformTextSignature(typeDeclaration); TypeTarget target = CreateTarget(typeDeclaration); var context = new CreateMethodDeclarationContext { AccessRights = AccessRights.PUBLIC, ExecuteTemplateOverMemberBody = false, ExecuteTemplateOverName = false, ExecuteTemplateOverParameters = false, ExecuteTemplateOverReturnType = false, IsAbstract = true, IsStatic = false, MethodSignatures = new[] { signature }, MethodName = T4CSharpCodeGenerator.TransformTextMethodName, SourceReferenceExpressionReference = null, Target = target, }; IntentionResult intentionResult = MethodDeclarationBuilder.Create(context); intentionResult.ExecuteTemplate(); return null; }
public override ICollection<IOccurence> Search(IProgressIndicator progressIndicator) { var typeElements = new List<ITypeDeclaration>(); var multiCoreFibersPool = new MultiCoreFibersPool("Search type declarations", locks); using (IMultiCoreFibers multiCoreFibers = multiCoreFibersPool.Create()) { foreach (var project in solution.GetAllProjects()) { var sourceFiles = project.GetAllProjectFiles().SelectMany(projectFile => projectFile.ToSourceFiles()); foreach (var psiSourceFile in sourceFiles) { IFile file = psiSourceFile.GetPsiFile(CSharpLanguage.Instance); if (file == null) { continue; } multiCoreFibers.EnqueueJob(() => file.ProcessChildren<ITypeDeclaration>(typeElements.Add)); } } } return (from typeDeclaration in typeElements let element = typeDeclaration.DeclaredElement where element != null where componentRegistration.IsSatisfiedBy(element) select new DeclaredElementOccurence(element)).Cast<IOccurence>().ToList(); }
/// <summary> /// Executes QuickFix or ContextAction. Returns post-execute method. /// </summary> /// <param name="solution">The solution.</param> /// <param name="progress">The progress.</param> /// <returns>Action to execute after document and PSI transaction finish. Use to open TextControls, navigate caret, etc.</returns> protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var model = this.GetModel(); if (model == null) { return null; } var code = model.Method.GetText(); if (string.IsNullOrEmpty(code)) { return null; } var typeMember = this.provider.ElementFactory.CreateTypeMemberDeclaration(code); var classDeclaration = model.ContainingType as IClassLikeDeclaration; if (classDeclaration == null) { return null; } var memberDeclaration = typeMember as IClassMemberDeclaration; Debug.Assert(memberDeclaration != null, "memberDeclaration != null"); var result = classDeclaration.AddClassMemberDeclarationBefore(memberDeclaration, model.Method); FormattingUtils.Format(result); return null; }
protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var factory = JavaScriptElementFactory.GetInstance(_referenceExpression); using (WriteLockCookie.Create()) ModificationUtil.ReplaceChild(_referenceExpression, factory.CreateExpression(_replacement)); return null; }
protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var methodDeclaration = _highlighting.MethodDeclaration; methodDeclaration.SetExtern(true); methodDeclaration.SetStatic(true); return null; }
protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { if (_highlighting.ObjectCreationExpression.Initializer != null) { return textControl => JetBrains.UI.Application.ShellComponentsEx.Tooltips(Shell.Instance.Components) .Show("Not supported for object initializers", l => (IPopupWindowContext)new TextControlPopupWindowContext(l, textControl, Shell.Instance.GetComponent<IShellLocks>(), Shell.Instance.GetComponent<IActionManager>())); } var psiModule = _highlighting.ObjectCreationExpression.GetPsiModule(); var factory = CSharpElementFactory.GetInstance(psiModule); var activatorType = TypeFactory.CreateTypeByCLRName("System.Activator", psiModule); var typeType = TypeFactory.CreateTypeByCLRName("System.Type", psiModule); var intefaceType = TypeFactory.CreateTypeByCLRName(_highlighting.InterfaceTypeName, psiModule); var statement = factory.CreateExpression("($3)$0.CreateInstance($1.GetTypeFromCLSID(typeof($2).GUID))", activatorType.GetTypeElement(), typeType.GetTypeElement(), _highlighting.CoClassTypeElement, intefaceType ); var containingDeclarationStatement = _highlighting.ObjectCreationExpression.GetContainingStatement() as IDeclarationStatement; if (containingDeclarationStatement != null && containingDeclarationStatement.Declaration.Declarators.Count == 1) { containingDeclarationStatement.Declaration.Declarators[0].SetTypeOrVar(intefaceType); } _highlighting.ObjectCreationExpression.ReplaceBy(statement); return null; }
/// <summary> /// Executes QuickFix or ContextAction. Returns post-execute method. /// </summary> /// <param name="solution">The solution.</param> /// <param name="progress">The progress.</param> /// <returns>Action to execute after document and PSI transaction finish. Use to open TextControls, navigate caret, etc.</returns> protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var model = this.GetModel(); if (model == null) { return null; } model.Class.SetAbstract(false); foreach (var function in model.Class.MethodDeclarations.Where(f => f.IsAbstract)) { function.SetAbstract(false); function.SetVirtual(true); if (function.Body == null) { function.SetBody(this.provider.ElementFactory.CreateEmptyBlock()); } } foreach (var property in model.Class.PropertyDeclarations.Where(p => p.IsAbstract)) { property.SetAbstract(false); property.SetVirtual(true); foreach (var accessor in property.AccessorDeclarations.Where(a => a.Body == null)) { accessor.SetBody(this.provider.ElementFactory.CreateEmptyBlock()); } } return null; }
/// <summary> /// Executes ContextAction, optionally returns post-execute method. /// </summary> /// <param name="solution">Current solution.</param> /// <param name="progress">Progress indicator to use for long operations.</param> protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var node = _commentNode.GetContainingNode<IDocCommentBlockNode>(); if (null == node) return null; var settingsStore = Shell.Instance .GetComponent<ISettingsStore>() .BindToContextTransient(ContextRange.ApplicationWide); var cleanupSettings = settingsStore.GetKey<CodeCleanupSettings>(SettingsOptimization.OptimizeDefault); string profileContent = cleanupSettings.Profiles.Get(cleanupSettings.SilentCleanupProfile, string.Empty); if (!string.IsNullOrEmpty(profileContent)) { CodeCleanupProfile profile = new CodeCleanupProfile(false, profileContent); int caret = 0; CodeCleanup cleanup = CodeCleanup.GetInstance(solution); cleanup.Run(_provider.SourceFile, node.GetDocumentRange(), ref caret, profile, progress); } return null; }
/// <summary> /// Executes QuickFix or ContextAction. Returns post-execute method. /// </summary> /// <param name="solution">The solution.</param> /// <param name="progress">The progress.</param> /// <returns>Action to execute after document and PSI transaction finish. Use to open TextControls, navigate caret, etc.</returns> protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var model = this.GetModel(); if (model == null) { return null; } var statement = this.provider.ElementFactory.CreateStatement("var stringBuilder = new System.Text.StringBuilder();"); model.Block.AddStatementBefore(statement, (ICSharpStatement)model.Anchor); foreach (var expression in model.Expressions) { statement = this.provider.ElementFactory.CreateStatement("stringBuilder.Append(" + expression.GetText() + ");"); model.Block.AddStatementBefore(statement, (ICSharpStatement)model.Anchor); } var toString = this.provider.ElementFactory.CreateExpression("stringBuilder.ToString()"); model.AdditiveExpression.ReplaceBy(toString); FormattingUtils.Format(model.Block); return null; }
protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { ClassDeclaration.RemoveClassMemberDeclaration(FieldDeclaration); ClassDeclaration.RemoveClassMemberDeclaration(PropertyDeclaration); return null; }
public void Process(IPsiSourceFile sourceFile, IRangeMarker rangeMarker, CodeCleanupProfile profile, IProgressIndicator progressIndicator) { var file = sourceFile.GetNonInjectedPsiFile<CSharpLanguage>(); if (file == null) return; if (!profile.GetSetting(DescriptorInstance)) return; CSharpElementFactory elementFactory = CSharpElementFactory.GetInstance(sourceFile.PsiModule); file.GetPsiServices().PsiManager.DoTransaction( () => { using (_shellLocks.UsingWriteLock()) file.ProcessChildren<IExpression>( expression => { ConstantValue value = expression.ConstantValue; if (value.IsInteger() && Convert.ToInt32(value.Value) == int.MaxValue) ModificationUtil.ReplaceChild(expression, elementFactory.CreateExpression("int.MaxValue")); } ); }, "Code cleanup"); }
protected sealed override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { MergeInvocations(myOuterInvocation.NotNull()); var hotspotInfo = CreateHostHotspotInfo(); return HotspotHelper.ExecuteHotspotSession(solution, new[] {hotspotInfo}); }
protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var methodDeclaration = _highlighting.MethodDeclaration; methodDeclaration.SetExtern(false); var textRange = LanguageManager.Instance.GetService<IMemberBodyOperations>(methodDeclaration.Language).SetBodyToDefault(methodDeclaration); var rangeMarker = new DocumentRange(methodDeclaration.GetDocumentRange().Document, textRange).CreateRangeMarker(DocumentManager.GetInstance(solution)); return control => control.Selection.SetRange(rangeMarker.Range); }
public override ITreeRange Format( ITreeNode firstElement, ITreeNode lastElement, CodeFormatProfile profile, IProgressIndicator progressIndicator, IContextBoundSettingsStore overrideSettingsStore = null, IPotentSettingsTracker settingsTracker = null) => new TreeRange(firstElement, lastElement);
protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var inputFile = _provider.PsiFile; var approximator = new Approximator(inputFile); var res = approximator.Approximate(); Console.WriteLine(res); return null; }
protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { using (WriteLockCookie.Create()) { highlighting.MethodDeclaration.SetType(taskType.ToIType()); } return _ => { }; }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { ITypeDeclaration typeDeclaration = GetTargetTypeDeclaration(_highlighting.BaseClass); if (typeDeclaration == null) { return(null); } MemberSignature signature = CreateTransformTextSignature(typeDeclaration); TypeTarget target = CreateTarget(typeDeclaration); var context = new CreateMethodDeclarationContext { AccessRights = AccessRights.PUBLIC, ExecuteTemplateOverMemberBody = false, ExecuteTemplateOverName = false, ExecuteTemplateOverParameters = false, ExecuteTemplateOverReturnType = false, IsAbstract = true, IsStatic = false, MethodSignatures = new[] { signature }, MethodName = T4CSharpIntermediateConverterBase.TransformTextMethodName, SourceReferenceExpressionReference = null, Target = target, }; IntentionResult intentionResult = MethodDeclarationBuilder.Create(context); intentionResult.ExecuteTemplate(); return(null); }
protected BaseExtractor(IProgressIndicator progressIndicator) { ProgressIndicator = progressIndicator; }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { if (this._myParameterDeclarations == null) { return(null); } var list = new List <ICSharpStatement>(); foreach (ICSharpParameterDeclaration current in this._myParameterDeclarations) { list.AddRange(this.ExecuteOverParameter(current)); } return(this.HandleAddedStatements(list.ToArray())); }
/// <inheritdoc /> public async Task DoSceneTransition(IEnumerable <Func <Task> > sceneOperations, float fadeOutTime, float fadeInTime, IProgressIndicator progressIndicator = null) { using (DoSceneTransitionPerfMarker.Auto()) { fadeOutTime = Mathf.Clamp(fadeOutTime, 0, maxFadeOutTime); fadeInTime = Mathf.Clamp(fadeInTime, 0, maxFadeInTime); if (TransitionInProgress) { throw new Exception("Attempting to do a transition while one is already in progress."); } #region Transition begin TransitionInProgress = true; OnTransitionStarted?.Invoke(); if (progressIndicator == null && sceneTransitionServiceProfile.UseDefaultProgressIndicator) { // If we haven't been given a progress indicator, and we're supposed to use a default // find / create the default progress indicator CreateDefaultProgressIndicator(); progressIndicator = defaultProgressIndicator; } if (UseFadeColor) { await FadeOut(fadeOutTime); } if (progressIndicator != null) { await progressIndicator.OpenAsync(); } #endregion #region Task execution // Make sure we're on the main thread foreach (Func <Task> sceneOperation in sceneOperations) { await sceneOperation(); } #endregion #region Transition end // If we used a progress indicator, close it if (progressIndicator != null) { await progressIndicator.CloseAsync(); } if (UseFadeColor) { await FadeIn(fadeInTime); } TransitionInProgress = false; OnTransitionCompleted?.Invoke(); #endregion } }
/// <inheritdoc /> public async Task DoSceneTransition(Func <Task> sceneOp1, Func <Task> sceneOp2, IProgressIndicator progressIndicator = null) { await DoSceneTransition(new Func <Task>[] { sceneOp1, sceneOp2 }, FadeOutTime, FadeInTime, progressIndicator); }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { using (WriteLockCookie.Create()) { var factory = CSharpElementFactory.GetInstance(_stringLiteral.Expression, false); var expression = factory.CreateExpression( $"\"{_regex.Replace(_stringLiteral.Expression.GetUnquotedText(), string.Empty)}\""); ModificationUtil.ReplaceChild(_stringLiteral.Expression, expression); } return(null); }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { ITreeNode node = _highlighting.AssociatedNode; using (node.CreateWriteLock()) { ITokenNode nextToken = node.GetNextToken(); ITreeNode end = nextToken != null && nextToken.GetTokenType() == T4TokenNodeTypes.NewLine ? nextToken : node; ModificationUtil.DeleteChildRange(node, end); } return(null); }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var invocationConverter = solution.GetComponent <IInvocationConverter>(); invocationConverter.TryReplaceInvocationToAsync(canBeUseAsyncMethodHighlighting.InvocationExpression); return(null); }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var declaredElement = this.Declaration?.DeclaredElement; if (declaredElement == null) { return(null); } var typeName = declaredElement.GetClrName().FullName; var moduleName = declaredElement.Module.DisplayName; if (declaredElement.Module is IProjectPsiModule projectModule) { var proj = projectModule.Project; moduleName = proj.GetOutputAssemblyName(proj.GetCurrentTargetFrameworkId()); } var fullName = $"{typeName}, {moduleName}"; this._clipboard.SetText(fullName); return(null); }
private void btnCreatePackage_Click(object sender, EventArgs e) { if (sfdSavePackage.ShowDialog() == DialogResult.OK) { string curDir = Directory.GetCurrentDirectory(); IProgressIndicator ind = ProgressIndicator.CreateProgressIndicator(panelProgress); ind.SetProgress("Running Preparations.", 0, 2); if (cbExport.Checked) { IProgressIndicator preps = ind.CreateSubTask(false); preps.SetProgress("Copying Folder Contents...", 0, 1); string dir = Path.Combine( Path.GetDirectoryName(Directory.GetCurrentDirectory()), "temp_" + Path.GetFileNameWithoutExtension(Directory.GetCurrentDirectory()) ); CopyDirectory(Directory.GetCurrentDirectory(), dir, preps.CreateSubTask(false)); Directory.SetCurrentDirectory(dir); string[] files = Directory.GetFiles(dir, "*.fl", SearchOption.AllDirectories); preps.SetProgress("Exporting FL Scripts..", 0, 1); IProgressIndicator fl2flc = ind.CreateSubTask(false); IProgressIndicator fl2flcf = fl2flc.CreateSubTask(false); for (int i = 0; i < files.Length; i++) { string file = files[i]; fl2flc.SetProgress("Exporting File:" + file, i, files.Length); fl2flcf.SetProgress("Parsing..", 0, 1); Editor.Path = file; Editor.FLContainer.SerializedProgram = null; //Editor.InitProgram(); Editor.Build(); if (Editor.FLContainer.SerializedProgram == null) { return; } fl2flcf.SetProgress("Exporting..", 1, 1); string f = file + "c"; Stream stream = File.OpenWrite(f); FLSerializer.SaveProgram( stream, Editor.FLContainer.SerializedProgram, Editor.FLContainer.InstructionSet, new string[0] ); stream.Close(); if (!cbKeepFlScripts.Checked) { File.Delete(file); } } fl2flcf.Dispose(); fl2flc.Dispose(); preps.Dispose(); } ind.SetProgress("Creating Package.", 1, 2); ProgressIndicator.RunTask( indicator => ResourceManager.Create( Directory.GetCurrentDirectory(), sfdSavePackage.FileName, tbPackageName.Text, tbUnpackConfig.Text, indicator ), panelProgress, Application.DoEvents, ind.CreateSubTask(false) ); ind.SetProgress("Cleaning Up.", 2, 2); string oldDir = Directory.GetCurrentDirectory(); Directory.SetCurrentDirectory(curDir); if (cbExport.Checked) { Directory.Delete(oldDir, true); } Close(); ind.Dispose(); } }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { CSharpImplUtil.ReplaceIdentifier(_warning.Method.NameIdentifier, _warning.ExpectedName); return(_ => { }); }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var methodDeclaration = (IMethodDeclaration)_declaration; // This is greatly simplified, since we're not updating any references // You will probably see a small indicator in the lower-right // that tells you about an exception being thrown. methodDeclaration.SetName(methodDeclaration.DeclaredName.ToLower()); return(null); }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var fieldDeclaration = myDataProvider.GetSelectedElement <IFieldDeclaration>(); if (fieldDeclaration != null) { var typeElement = TypeFactory.CreateTypeByCLRName(KnownTypes.SerializeField, myDataProvider.PsiModule).GetTypeElement(); if (typeElement == null) { return(null); } var attribute = myDataProvider.ElementFactory.CreateAttribute(typeElement); fieldDeclaration.AddAttributeAfter(attribute, null); } return(null); }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var propertyDeclaration = myDataProvider.GetSelectedElement <IPropertyDeclaration>(); return(Execute(propertyDeclaration, myDataProvider.Solution, myDataProvider.ElementFactory)); }
/// <inheritdoc /> protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { using (WriteLockCookie.Create()) { var invocationExpression = _highlighting.InvocationExpression; ModificationUtil.ReplaceChild(invocationExpression, _migrationService.CreateMigrationExpression(invocationExpression)); } return(null); }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { if (_changeVisibility) { Contract.Assert(_highlighing.ReferingFieldOrProperty != null); ModifiersUtil.SetAccessRights(_highlighing.ReferingFieldOrProperty, AccessRights.PUBLIC); } if (_generateProperty) { Contract.Assert(_highlighing.ReferingFieldOrProperty == null); GenerateRefereingProperty(); } return(null); }
/// <inheritdoc /> public async Task DoSceneTransition(IEnumerable <Func <Task> > sceneOperations, IProgressIndicator progressIndicator = null) { await DoSceneTransition(sceneOperations, FadeOutTime, FadeInTime, progressIndicator); }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { T4StatementBlock statementBlock = _highlighting.AssociatedNode; var file = statementBlock.GetContainingFile() as IT4File; Assertion.AssertNotNull(file, "file != null"); T4FeatureBlock feature = file.GetFeatureBlocks().First(); ITreeNode featureBlock; using (file.CreateWriteLock()) { // clone the statement block and add it before the feature block ITreeNode featurePrevSibling = feature.PrevSibling; featureBlock = ModificationUtil.CloneNode(statementBlock, node => { }); featureBlock = ModificationUtil.AddChildBefore(feature, featureBlock); // add a new line before the new statement block if needed if (featurePrevSibling != null && featurePrevSibling.GetTokenType() == T4TokenNodeTypes.NewLine) { ModificationUtil.AddChildAfter(featureBlock, T4TokenNodeTypes.NewLine.CreateLeafElement()); } ModificationUtil.DeleteChild(statementBlock); } return(textControl => { TextRange range = featureBlock.GetDocumentRange().TextRange; textControl.Caret.MoveTo(range.EndOffset, CaretVisualPlacement.Generic); }); }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var values = new[] { new Pair <string, AttributeValue>("menuName", new AttributeValue(new ConstantValue($"Create {myClassLikeDeclaration.DeclaredName}", myModule))), new Pair <string, AttributeValue>("fileName", new AttributeValue(new ConstantValue(myClassLikeDeclaration.DeclaredName, myModule))), new Pair <string, AttributeValue>("order", new AttributeValue(new ConstantValue(0, myModule))), }; var attribute = AttributeUtil.AddAttributeToSingleDeclaration(myClassLikeDeclaration, KnownTypes.CreateAssetMenuAttribute, EmptyArray <AttributeValue> .Instance, values, myModule, myElementFactory); return(attribute.CreateHotspotSession()); }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { ExecuteTransaction(); return(null); }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { _executing = true; var treeRange = AdjustTreeRange(_range); if (treeRange == null) { return(null); } var first = treeRange.First; var last = treeRange.Last; for (var prevSibling = first.PrevSibling; prevSibling is IWhitespaceNode && !((IWhitespaceNode)prevSibling).IsNewLine; prevSibling = prevSibling.PrevSibling) { first = prevSibling; } for (var nextSibling = last.NextSibling; nextSibling is IWhitespaceNode; nextSibling = nextSibling.NextSibling) { last = nextSibling; if (((IWhitespaceNode)last).IsNewLine) { break; } } var containingNode = first.GetContainingNode <IJavaScriptStatement>(true); using (WriteLockCookie.Create()) ModificationUtil.DeleteChildRange(new TreeRange(first, last)); _executing = false; if (containingNode != null && containingNode.IsValid()) { var containingFile = containingNode.GetContainingFile(); if (containingFile != null) { containingFile.ReParse(containingNode.GetTreeTextRange(), containingNode.GetText()); } } return(null); }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { using (WriteLockCookie.Create()) { var qualifierOperand = (myRewriteLeftOperand ? myExpression.LeftOperand : myExpression.RightOperand) as IReferenceExpression; var qualifierExpression = qualifierOperand?.QualifierExpression; var otherOperand = myRewriteLeftOperand ? myExpression.RightOperand : myExpression.LeftOperand; var factory = CSharpElementFactory.GetInstance(myExpression); ICSharpExpression newExpression; if (qualifierExpression != null) { newExpression = factory.CreateExpression("$0$1.CompareTag($2)", myExpression.EqualityType == EqualityExpressionType.EQEQ ? string.Empty : "!", qualifierExpression, otherOperand); } else { newExpression = factory.CreateExpression("$0CompareTag($1)", myExpression.EqualityType == EqualityExpressionType.EQEQ ? string.Empty : "!", otherOperand); } ModificationUtil.ReplaceChild(myExpression, newExpression); } return(null); }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { IHtmlTagHeader tagHeader = GetTag(); if (tagHeader == null) { return(null); } // The easiest way to create an attribute is to create an HTML tag with an attribute in it // and then get the attribute from the tag. HtmlElementFactory factory = HtmlElementFactory.GetInstance(tagHeader.Language); IHtmlTag dummy = factory.CreateHtmlTag("<tag id=\"\"/>", tagHeader); ITagAttribute idAttr = dummy.Attributes.Single(); tagHeader.AddAttributeBefore(idAttr, null); // continuation to do after transaction committed return(textControl => // move cursor inside new created id attribute textControl.Caret.MoveTo(idAttr.ValueElement.GetDocumentRange().TextRange.StartOffset, CaretVisualPlacement.Generic)); }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { _highlighting.PreconditionStatement.RemoveOrReplaceByEmptyStatement(); return(null); }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var factory = CSharpElementFactory.GetInstance(myHighlightedReference); var property = (myHighlightedReference.Reference.Resolve().DeclaredElement as IProperty).NotNull(); // save declaration (in case of expression lambda) var declaration = myHighlightedReference.GetContainingFunctionLikeDeclarationOrClosure(); var type = property.Type; var name = GetUniqueName(myHighlightedReference, property.ShortName); IReferenceExpression originValue = myHighlightedReference.Copy(); for (var i = 0; i < myReferences.Count; i++) { var reference = myReferences[i]; myReferences[i] = reference.ReplaceBy(factory.CreateReferenceExpression("$0", name)); } var firstReference = myReferences[0]; if (declaration is IExpressionBodyOwnerDeclaration expressionBodyOwnerDeclaration && expressionBodyOwnerDeclaration.GetCodeBody().ExpressionBody != null) { using (var marker = new DisposableMarker <IReferenceExpression>(firstReference)) { var body = expressionBodyOwnerDeclaration.EnsureStatementMemberBody(); HandleExpressionBody(body, factory, type, name, marker, originValue); } return(null); } if (declaration is ILambdaExpression lambdaExpression && lambdaExpression.GetCodeBody().ExpressionBody != null) { using (var marker = new DisposableMarker <IReferenceExpression>(firstReference)) { var body = lambdaExpression.EnsureStatementLambda(); HandleExpressionBody(body, factory, type, name, marker, originValue); } return(null); } Assertion.Assert(myCacheAnchor is ICSharpStatement, "myInlineCache is IStatement"); var statementCacheAnchor = (ICSharpStatement)myCacheAnchor; if (myInlineCache) // replace first read with assignment expression { foreach (var reference in myReferences) { if (reference.GetContainingStatement() != myCacheAnchor) { continue; } // is write first??? // example: var x = (transform.position = Vector3.Up) + transform.position + transform.position ... // if yes, we have already save our variable in cycle above, if no use inline to cache. if (AssignmentExpressionNavigator.GetByDest(reference.GetContainingParenthesizedExpression()) == null) { reference.ReplaceBy(factory.CreateExpression("($0 = $1)", name, originValue.Copy())); } break; } var cacheStatement = factory.CreateStatement("$0 $1;", type, name); StatementUtil.InsertStatement(cacheStatement, ref statementCacheAnchor, true); } else { var cacheStatement = factory.CreateStatement("var $0 = $1;", name, originValue.Copy()); StatementUtil.InsertStatement(cacheStatement, ref statementCacheAnchor, true); } if (myRestoreAnchor != null) { Assertion.Assert(myRestoreAnchor is ICSharpStatement, "myRestoreAnchor is IStatement"); var statementRestoreAnchor = (ICSharpStatement)myRestoreAnchor; if (myInlineRestore) { var size = myReferences.Count; for (int i = size - 1; i >= 0; i--) { var reference = myReferences[i]; if (reference.GetContainingStatement() == myRestoreAnchor) { reference.ReplaceBy(factory.CreateReferenceExpression("$0", originValue)); break; } } } else { var restoreStatement = factory.CreateStatement("$0 = $1;", originValue, name); StatementUtil.InsertStatement(restoreStatement, ref statementRestoreAnchor, false); } } return(null); }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator _) { var methodDeclaration = SelectedTestMethodDeclaration.NotNull(); var psiModule = methodDeclaration.GetPsiModule(); var elementFactory = CSharpElementFactory.GetInstance(methodDeclaration); var parameterDeclaration = methodDeclaration.AddParameterDeclarationBefore( elementFactory.CreateParameterDeclaration( ParameterKind.VALUE, isParams: false, isVarArg: false, type: psiModule.GetPredefinedType().Object, name: "parameter", defaultValue: null), anchor: null); var testCaseAttributeType = TypeFactory.CreateTypeByCLRName(ParameterizedTests.TestCaseAttribute, NullableAnnotation.Unknown, psiModule) .GetTypeElement().NotNull($"Cannot resolve '{ParameterizedTests.TestCaseAttribute}'"); var testCaseAttribute = methodDeclaration.AddAttributeBefore(elementFactory.CreateAttribute(testCaseAttributeType), anchor: null); var testCaseArgument = testCaseAttribute.AddArgumentBefore( elementFactory.CreateArgument(ParameterKind.VALUE, elementFactory.CreateExpression("argument")), anchor: null); var hotspotNodes = new ITreeNode[] { parameterDeclaration.TypeUsage, parameterDeclaration.NameIdentifier, testCaseArgument, }; return(textControl => { var endSelectionRange = DocumentRange.InvalidRange; var hotspotSession = textControl.CreateHotspotSessionAtopExistingText(solution, endSelectionRange, hotspotNodes); hotspotSession.ExecuteAndForget(); }); }
public override void Rename( RenameRefactoring executer, IProgressIndicator pi, bool hasConflictsWithDeclarations, IRefactoringDriver driver) { this.BuildDeclarations(); //Logger.Assert(myDeclarations.Count > 0, "myDeclarations.Count > 0"); IDeclaredElement declaredElement = this.myOriginalElementPointer.FindDeclaredElement(); if (declaredElement == null) { return; } IPsiServices psiServices = declaredElement.GetPsiServices(); IList <IReference> primaryReferences = executer.Workflow.GetElementReferences(this.PrimaryDeclaredElement); List <Pair <IDeclaredElement, IList <IReference> > > secondaryElementWithReferences = this.SecondaryDeclaredElements.Select(x => Pair.Of(x, executer.Workflow.GetElementReferences(x))).ToList(); pi.Start(this.myDeclarations.Count + primaryReferences.Count); foreach (IDeclaration declaration in this.myDeclarations) { InterruptableActivityCookie.CheckAndThrow(pi); declaration.SetName(this.myNewName); pi.Advance(); } psiServices.Caches.Update(); IDeclaredElement newDeclaredElement; if (this.myDeclarations.Count > 0) { newDeclaredElement = this.myDeclarations[0].DeclaredElement; } else { if (this.myElement is PrefixDeclaredElement) { newDeclaredElement = this.myElement; ((PrefixDeclaredElement)this.myElement).ChangeName = true; ((PrefixDeclaredElement)this.myElement).NewName = this.NewName; ((PrefixDeclaredElement)newDeclaredElement).SetName(this.NewName); } else { newDeclaredElement = null; } } Assertion.Assert(newDeclaredElement != null, "The condition (newDeclaredElement != null) is false."); this.myNewElementPointer = newDeclaredElement.CreateElementPointer(); Assertion.Assert(newDeclaredElement.IsValid(), "myNewDeclaredElement.IsValid()"); this.myNewReferences.Clear(); OneToSetMap <PsiLanguageType, IReference> references = LanguageUtil.SortReferences(primaryReferences.Where(x => x.IsValid())); IList <IReference> referencesToRename = new List <IReference>(); foreach (var pair in references) { List <IReference> sortedReferences = pair.Value.ToList(); //LanguageUtil.GetSortedReferences(pair.Value); foreach (IReference reference in sortedReferences) { IReference oldReferenceForConflict = reference; InterruptableActivityCookie.CheckAndThrow(pi); if (reference.IsValid()) // reference may invalidate during additional reference processing { RenameHelperBase rename = executer.Workflow.LanguageSpecific[reference.GetTreeNode().Language]; IReference reference1 = rename.TransformProjectedInitializer(reference); DeclaredElementInstance subst = GetSubst(newDeclaredElement, executer); IReference newReference; if (subst != null) { if (subst.Substitution.Domain.IsEmpty()) { newReference = reference1.BindTo(subst.Element); } else { newReference = reference1.BindTo(subst.Element, subst.Substitution); } } else { newReference = reference1.BindTo(newDeclaredElement); } if (!(newReference is IImplicitReference)) { IDeclaredElement element = newReference.Resolve().DeclaredElement; if (!hasConflictsWithDeclarations && !this.myDoNotShowBindingConflicts && (element == null || !element.Equals(newDeclaredElement)) && !rename.IsAlias(newDeclaredElement)) { driver.AddLateConflict( () => new Conflict( newReference.GetTreeNode().GetSolution(), "Usage {0} can not be updated correctly.", ConflictSeverity.Error, oldReferenceForConflict), "not bound"); } referencesToRename.Add(newReference); } this.myNewReferences.Insert(0, newReference); rename.AdditionalReferenceProcessing(newDeclaredElement, newReference, this.myNewReferences); } pi.Advance(); } } foreach (var pair in secondaryElementWithReferences) { IDeclaredElement element = pair.First; IList <IReference> secondaryReferences = pair.Second; foreach (IReference reference in secondaryReferences) { InterruptableActivityCookie.CheckAndThrow(pi); if (reference.IsValid()) { reference.BindTo(element); } } } if (this.myElement is PrefixDeclaredElement) { ((PrefixDeclaredElement)this.myElement).ChangeName = false; ((PrefixDeclaredElement)this.myElement).SetName(this.NewName); foreach (IReference reference in referencesToRename) { ((NTriplesPrefixReference)reference).SetName(this.NewName); reference.CurrentResolveResult = null; ((NTriplesFile)((PrefixDeclaredElement)this.myElement).File).ClearTables(); } } }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { Action <ITextControl> action = null; if ((myMatch & MethodSignatureMatch.IncorrectStaticModifier) == MethodSignatureMatch.IncorrectStaticModifier && myExpectedMethodSignature.IsStatic.HasValue) { myMethodDeclaration.SetStatic(myExpectedMethodSignature.IsStatic.Value); } if ((myMatch & MethodSignatureMatch.IncorrectParameters) == MethodSignatureMatch.IncorrectParameters) { action = ChangeParameters(solution); } if ((myMatch & MethodSignatureMatch.IncorrectReturnType) == MethodSignatureMatch.IncorrectReturnType) { var element = myMethodDeclaration.DeclaredElement; Assertion.AssertNotNull(element, "element != null"); var language = myMethodDeclaration.Language; var changeTypeHelper = LanguageManager.Instance.GetService <IChangeTypeHelper>(language); changeTypeHelper.ChangeType(myExpectedMethodSignature.ReturnType, element); } if ((myMatch & MethodSignatureMatch.IncorrectTypeParameters) == MethodSignatureMatch.IncorrectTypeParameters) { // There are no generic Unity methods, so just remove any that are already there myMethodDeclaration.SetTypeParameterList(null); } return(action); }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var factory = CSharpElementFactory.GetInstance(myExpression); var newScalars = myScalars.Select(t => t.CopyWithResolve()).ToList(); var newExpression = RemoveScalars(factory, myExpression); var scalars = CreateMulExpression(factory, newScalars); myExpression.ReplaceBy(factory.CreateExpression(mul, newExpression, scalars)); return(null); }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { using (WriteLockCookie.Create()) { highlighting.Declaration.SetType(taskType.ToIType()); } return(_ => { }); }