public static void invokeAndWaitInterruptedWhenClosing( final Project project, final Runnable runnable, final ModalityState modalityState) { final Ref<Boolean> start = new Ref<Boolean>(Boolean.TRUE); final Application application = ApplicationManager.getApplication(); LOG.assertTrue(!application.isDispatchThread()); final Semaphore semaphore = new Semaphore(); semaphore.down(); Runnable runnable1 = new Runnable() { public void run() { try { runnable.run(); } finally { semaphore.up(); } } @NonNls public String toString() { return "PeriodicalTaskCloser's invoke and wait [" + runnable.toString() + "]"; } }; LaterInvocator.invokeLater( runnable1, modalityState, new Condition<Object>() { public boolean value(Object o) { synchronized (start) { return !start.get(); } } }); while (true) { if (semaphore.waitFor(1000)) { return; } final Ref<Boolean> fire = new Ref<Boolean>(); synchronized (ourLock) { final Boolean state = myStates.get(project); if (!Boolean.TRUE.equals(state)) { fire.set(Boolean.TRUE); } if (Boolean.TRUE.equals(fire.get())) { synchronized (start) { start.set(Boolean.FALSE); return; } } } } }
/** * Finds an existing run configuration matching the context. * * @return an existing configuration, or null if none was found. */ @Nullable public RunnerAndConfigurationSettings findExisting() { if (myExistingConfiguration != null) return myExistingConfiguration.get(); myExistingConfiguration = new Ref<>(); if (myLocation == null) { return null; } final PsiElement psiElement = myLocation.getPsiElement(); if (!psiElement.isValid()) { return null; } final List<RuntimeConfigurationProducer> producers = findPreferredProducers(); if (myRuntimeConfiguration != null) { if (producers != null) { for (RuntimeConfigurationProducer producer : producers) { final RunnerAndConfigurationSettings configuration = producer.findExistingConfiguration(myLocation, this); if (configuration != null && configuration.getConfiguration() == myRuntimeConfiguration) { myExistingConfiguration.set(configuration); } } } for (RunConfigurationProducer producer : RunConfigurationProducer.getProducers(getProject())) { RunnerAndConfigurationSettings configuration = producer.findExistingConfiguration(this); if (configuration != null && configuration.getConfiguration() == myRuntimeConfiguration) { myExistingConfiguration.set(configuration); } } } if (producers != null) { for (RuntimeConfigurationProducer producer : producers) { final RunnerAndConfigurationSettings configuration = producer.findExistingConfiguration(myLocation, this); if (configuration != null) { myExistingConfiguration.set(configuration); } } } for (RunConfigurationProducer producer : RunConfigurationProducer.getProducers(getProject())) { RunnerAndConfigurationSettings configuration = producer.findExistingConfiguration(this); if (configuration != null) { myExistingConfiguration.set(configuration); } } return myExistingConfiguration.get(); }
public void getServerFilesManagers( final Ref<SvnServerFileManager> systemManager, final Ref<SvnServerFileManager> userManager) { // created only if does not exist final File dir = new File(getConfigurationDirectory()); if (!dir.exists()) { SVNConfigFile.createDefaultConfiguration(dir); } systemManager.set( new SvnServerFileManagerImpl( new IdeaSVNConfigFile( new File(SVNFileUtil.getSystemConfigurationDirectory(), SERVERS_FILE_NAME)))); initServers(); userManager.set(new SvnServerFileManagerImpl(myConfigFile)); }
@NotNull @Override protected JBPopup createPopup(@NotNull AnActionEvent e) { Project project = e.getProject(); if (project == null) project = ProjectManager.getInstance().getDefaultProject(); Ref<JBPopup> popup = new Ref<JBPopup>(); ChangesBrowser cb = new MyChangesBrowser(project, getChanges(), getCurrentSelection(), popup); popup.set( JBPopupFactory.getInstance() .createComponentPopupBuilder(cb, cb.getPreferredFocusedComponent()) .setResizable(true) .setModalContext(false) .setFocusable(true) .setRequestFocus(true) .setCancelOnWindowDeactivation(true) .setCancelOnOtherWindowOpen(true) .setMovable(true) .setCancelKeyEnabled(true) .setCancelOnClickOutside(true) .setDimensionServiceKey(project, "Diff.GoToChangePopup", false) .createPopup()); return popup.get(); }
private CompletionInitializationContext runContributorsBeforeCompletion( Editor editor, PsiFile psiFile, int invocationCount, Caret caret) { final Ref<CompletionContributor> current = Ref.create(null); CompletionInitializationContext context = new CompletionInitializationContext( editor, caret, psiFile, myCompletionType, invocationCount) { CompletionContributor dummyIdentifierChanger; @Override public void setDummyIdentifier(@NotNull String dummyIdentifier) { super.setDummyIdentifier(dummyIdentifier); if (dummyIdentifierChanger != null) { LOG.error( "Changing the dummy identifier twice, already changed by " + dummyIdentifierChanger); } dummyIdentifierChanger = current.get(); } }; List<CompletionContributor> contributors = CompletionContributor.forLanguage(context.getPositionLanguage()); Project project = psiFile.getProject(); List<CompletionContributor> filteredContributors = DumbService.getInstance(project).filterByDumbAwareness(contributors); for (final CompletionContributor contributor : filteredContributors) { current.set(contributor); contributor.beforeCompletion(context); CompletionAssertions.checkEditorValid(editor); assert !PsiDocumentManager.getInstance(project).isUncommited(editor.getDocument()) : "Contributor " + contributor + " left the document uncommitted"; } return context; }
private JComponent createActionLink( final String text, final String groupId, Icon icon, boolean focusListOnLeft) { final Ref<ActionLink> ref = new Ref<ActionLink>(null); AnAction action = new AnAction() { @Override public void actionPerformed(@NotNull AnActionEvent e) { ActionGroup configureGroup = (ActionGroup) ActionManager.getInstance().getAction(groupId); final PopupFactoryImpl.ActionGroupPopup popup = (PopupFactoryImpl.ActionGroupPopup) JBPopupFactory.getInstance() .createActionGroupPopup( null, new IconsFreeActionGroup(configureGroup), e.getDataContext(), JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, false, ActionPlaces.WELCOME_SCREEN); popup.showUnderneathOfLabel(ref.get()); UsageTrigger.trigger("welcome.screen." + groupId); } }; ref.set(new ActionLink(text, icon, action)); ref.get().setPaintUnderline(false); ref.get().setNormalColor(getLinkNormalColor()); NonOpaquePanel panel = new NonOpaquePanel(new BorderLayout()); panel.setBorder(JBUI.Borders.empty(4, 6, 4, 6)); panel.add(ref.get()); panel.add(createArrow(ref.get()), BorderLayout.EAST); installFocusable(panel, action, KeyEvent.VK_UP, KeyEvent.VK_DOWN, focusListOnLeft); return panel; }
private boolean getExistingInfo(Ref<RunningInfo> ref, Pair<Target, Parameters> key) { Info info; synchronized (myProcMap) { info = myProcMap.get(key); try { while (info != null && (!(info instanceof RunningInfo) || info.handler.isProcessTerminating() || info.handler.isProcessTerminated())) { myProcMap.wait(1000); ProgressManager.checkCanceled(); info = myProcMap.get(key); } } catch (InterruptedException e) { ProgressManager.checkCanceled(); } if (info == null) { myProcMap.put(key, new PendingInfo(ref, null)); } } if (info instanceof RunningInfo) { //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (ref) { ref.set((RunningInfo) info); ref.notifyAll(); } } return info != null; }
public static boolean isValidPropertyReference( @NotNull Project project, @NotNull PsiLiteralExpression expression, @NotNull String key, @NotNull Ref<String> outResourceBundle) { final HashMap<String, Object> annotationAttributeValues = new HashMap<String, Object>(); annotationAttributeValues.put(AnnotationUtil.PROPERTY_KEY_RESOURCE_BUNDLE_PARAMETER, null); if (mustBePropertyKey(project, expression, annotationAttributeValues)) { final Object resourceBundleName = annotationAttributeValues.get(AnnotationUtil.PROPERTY_KEY_RESOURCE_BUNDLE_PARAMETER); if (!(resourceBundleName instanceof PsiExpression)) { return false; } PsiExpression expr = (PsiExpression) resourceBundleName; final Object value = JavaPsiFacade.getInstance(expr.getProject()) .getConstantEvaluationHelper() .computeConstantExpression(expr); if (value == null) { return false; } String bundleName = value.toString(); outResourceBundle.set(bundleName); return isPropertyRef(expression, key, bundleName); } return true; }
private boolean getStringToReplace( int textOffset, int textEndOffset, Document document, FindModel findModel, Ref<String> stringToReplace) throws FindManager.MalformedReplacementStringException { if (textOffset < 0 || textOffset >= document.getTextLength()) { return false; } if (textEndOffset < 0 || textOffset > document.getTextLength()) { return false; } FindManager findManager = FindManager.getInstance(myProject); final CharSequence foundString = document.getCharsSequence().subSequence(textOffset, textEndOffset); PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(document); FindResult findResult = findManager.findString( document.getCharsSequence(), textOffset, findModel, file != null ? file.getVirtualFile() : null); if (!findResult.isStringFound()) { return false; } stringToReplace.set( FindManager.getInstance(myProject) .getStringToReplace(foundString.toString(), findModel, textOffset, document.getText())); return true; }
@Nullable public static MavenDomDependency searchManagingDependency( @NotNull final MavenDomDependency dependency, @NotNull final Project project) { final DependencyConflictId depId = DependencyConflictId.create(dependency); if (depId == null) return null; final MavenDomProjectModel model = dependency.getParentOfType(MavenDomProjectModel.class, false); if (model == null) return null; final Ref<MavenDomDependency> res = new Ref<MavenDomDependency>(); Processor<MavenDomDependency> processor = dependency1 -> { if (depId.equals(DependencyConflictId.create(dependency1))) { res.set(dependency1); return true; } return false; }; processDependenciesInDependencyManagement(model, processor, project); return res.get(); }
/** * remove highlights (bounded with <marker>...</marker>) from test case file * * @param document document to process */ private void extractExpectedHighlightsSet(final Document document) { final String text = document.getText(); final Set<String> markers = myHighlightingTypes.keySet(); final String typesRx = "(?:" + StringUtil.join(markers, ")|(?:") + ")"; final String openingTagRx = "<(" + typesRx + ")" + "(?:\\s+descr=\"((?:[^\"]|\\\\\"|\\\\\\\\\"|\\\\\\[|\\\\\\])*)\")?" + "(?:\\s+type=\"([0-9A-Z_]+)\")?" + "(?:\\s+foreground=\"([0-9xa-f]+)\")?" + "(?:\\s+background=\"([0-9xa-f]+)\")?" + "(?:\\s+effectcolor=\"([0-9xa-f]+)\")?" + "(?:\\s+effecttype=\"([A-Z]+)\")?" + "(?:\\s+fonttype=\"([0-9]+)\")?" + "(?:\\s+textAttributesKey=\"((?:[^\"]|\\\\\"|\\\\\\\\\"|\\\\\\[|\\\\\\])*)\")?" + "(?:\\s+bundleMsg=\"((?:[^\"]|\\\\\"|\\\\\\\\\")*)\")?" + "(/)?>"; final Matcher matcher = Pattern.compile(openingTagRx).matcher(text); int pos = 0; final Ref<Integer> textOffset = Ref.create(0); while (matcher.find(pos)) { textOffset.set(textOffset.get() + matcher.start() - pos); pos = extractExpectedHighlight(matcher, text, document, textOffset); } }
@Override public boolean canPutAt( @NotNull final VirtualFile file, final int line, @NotNull final Project project) { final Ref<Boolean> stoppable = Ref.create(false); final Document document = FileDocumentManager.getInstance().getDocument(file); if (document != null) { if (file.getFileType() == PythonFileType.INSTANCE) { XDebuggerUtil.getInstance() .iterateLine( project, document, line, new Processor<PsiElement>() { @Override public boolean process(PsiElement psiElement) { if (psiElement instanceof PsiWhiteSpace || psiElement instanceof PsiComment) return true; if (psiElement.getNode() != null && notStoppableElementType(psiElement.getNode().getElementType())) return true; // Python debugger seems to be able to stop on pretty much everything stoppable.set(true); return false; } }); if (PyDebugSupportUtils.isContinuationLine(document, line - 1)) { stoppable.set(false); } } } return stoppable.get(); }
/** * Begins the in-place refactoring operation. * * @return true if the in-place refactoring was successfully started, false if it failed to start * and a dialog should be shown instead. */ public boolean startInplaceIntroduceTemplate() { final boolean replaceAllOccurrences = isReplaceAllOccurrences(); final Ref<Boolean> result = new Ref<>(); CommandProcessor.getInstance() .executeCommand( myProject, () -> { final String[] names = suggestNames(replaceAllOccurrences, getLocalVariable()); final V variable = createFieldToStartTemplateOn(replaceAllOccurrences, names); boolean started = false; if (variable != null) { int caretOffset = getCaretOffset(); myEditor.getCaretModel().moveToOffset(caretOffset); myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); final LinkedHashSet<String> nameSuggestions = new LinkedHashSet<>(); nameSuggestions.add(variable.getName()); nameSuggestions.addAll(Arrays.asList(names)); initOccurrencesMarkers(); setElementToRename(variable); updateTitle(getVariable()); started = super.performInplaceRefactoring(nameSuggestions); if (started) { onRenameTemplateStarted(); myDocumentAdapter = new DocumentAdapter() { @Override public void documentChanged(DocumentEvent e) { if (myPreview == null) return; final TemplateState templateState = TemplateManagerImpl.getTemplateState(myEditor); if (templateState != null) { final TextResult value = templateState.getVariableValue( InplaceRefactoring.PRIMARY_VARIABLE_NAME); if (value != null) { updateTitle(getVariable(), value.getText()); } } } }; myEditor.getDocument().addDocumentListener(myDocumentAdapter); updateTitle(getVariable()); if (TemplateManagerImpl.getTemplateState(myEditor) != null) { myEditor.putUserData(ACTIVE_INTRODUCE, this); } } } result.set(started); if (!started) { finish(true); } }, getCommandName(), getCommandName()); return result.get(); }
private static void ensureTemplatesShown( Ref<Boolean> templatesShown, List<TemplateImpl> templates, CompletionResultSet result) { if (!templatesShown.get()) { templatesShown.set(true); for (final TemplateImpl possible : templates) { result.addElement(new LiveTemplateLookupElement(possible, false)); } } }
public ElementNodeImpl( @Nullable DefaultMutableTreeNode parent, MemberChooserObject delegate, Ref<Integer> order) { myOrder = order.get(); order.set(myOrder + 1); myDelegate = delegate; if (parent != null) { parent.add(this); } }
public static Library addProjectLibrary( Module module, String libName, List<VirtualFile> classesRoots, List<VirtualFile> sourceRoots) { Ref<Library> result = Ref.create(); ModuleRootModificationUtil.updateModel( module, model -> result.set(addProjectLibrary(module, model, libName, classesRoots, sourceRoots))); return result.get(); }
private void collectLogEntries( final ProgressIndicator indicator, FilePath file, VcsException[] exception, final Consumer<VcsFileRevision> result, final Ref<Boolean> supports15Ref) throws SVNException, VcsException { SVNWCClient wcClient = myVcs.createWCClient(); SVNInfo info = wcClient.doInfo(new File(file.getIOFile().getAbsolutePath()), SVNRevision.UNDEFINED); wcClient.setEventHandler( new ISVNEventHandler() { public void handleEvent(SVNEvent event, double progress) throws SVNException {} public void checkCancelled() throws SVNCancelException { indicator.checkCanceled(); } }); if (info == null || info.getRepositoryRootURL() == null) { exception[0] = new VcsException("File ''{0}'' is not under version control" + file.getIOFile()); return; } final String url = info.getURL() == null ? null : info.getURL().toString(); String relativeUrl = url; final SVNURL repoRootURL = info.getRepositoryRootURL(); final String root = repoRootURL.toString(); if (url != null && url.startsWith(root)) { relativeUrl = url.substring(root.length()); } if (indicator != null) { indicator.setText2(SvnBundle.message("progress.text2.changes.establishing.connection", url)); } final SVNRevision pegRevision = info.getRevision(); SVNLogClient client = myVcs.createLogClient(); final boolean supports15 = SvnUtil.checkRepositoryVersion15(myVcs, url); supports15Ref.set(supports15); client.doLog( new File[] {new File(file.getIOFile().getAbsolutePath())}, SVNRevision.HEAD, SVNRevision.create(1), SVNRevision.UNDEFINED, false, true, supports15, 0, null, new MyLogEntryHandler( myVcs, url, pegRevision, relativeUrl, result, repoRootURL, file.getCharset())); }
@Override public Result preprocessEnter( @NotNull final PsiFile file, @NotNull final Editor editor, @NotNull final Ref<Integer> caretOffsetRef, @NotNull final Ref<Integer> caretAdvance, @NotNull final DataContext dataContext, final EditorActionHandler originalHandler) { int caretOffset = caretOffsetRef.get().intValue(); PsiElement psiAtOffset = file.findElementAt(caretOffset); if (psiAtOffset != null && psiAtOffset.getTextOffset() < caretOffset) { ASTNode token = psiAtOffset.getNode(); Document document = editor.getDocument(); CharSequence text = document.getText(); final Language language = psiAtOffset.getLanguage(); final Commenter languageCommenter = LanguageCommenters.INSTANCE.forLanguage(language); final CodeDocumentationAwareCommenter commenter = languageCommenter instanceof CodeDocumentationAwareCommenter ? (CodeDocumentationAwareCommenter) languageCommenter : null; if (commenter != null && token.getElementType() == commenter.getLineCommentTokenType()) { final int offset = CharArrayUtil.shiftForward(text, caretOffset, " \t"); if (offset < document.getTextLength() && text.charAt(offset) != '\n') { String prefix = commenter.getLineCommentPrefix(); assert prefix != null : "Line Comment type is set but Line Comment Prefix is null!"; if (!StringUtil.startsWith(text, offset, prefix)) { if (text.charAt(caretOffset) != ' ' && !prefix.endsWith(" ")) { prefix += " "; } document.insertString(caretOffset, prefix); return Result.Default; } else { int afterPrefix = offset + prefix.length(); if (afterPrefix < document.getTextLength() && text.charAt(afterPrefix) != ' ') { document.insertString(afterPrefix, " "); // caretAdvance.set(0); } caretOffsetRef.set(offset); } return Result.Default; } } } return Result.Continue; }
@Override protected boolean setupConfigurationFromContext( JUnitConfiguration configuration, ConfigurationContext context, Ref<PsiElement> sourceElement) { PsiPackage psiPackage = JavaRuntimeConfigurationProducerBase.checkPackage(context.getPsiLocation()); if (psiPackage == null) return false; sourceElement.set(psiPackage); if (!LocationUtil.isJarAttached( context.getLocation(), psiPackage, JUnitUtil.TESTCASE_CLASS, JUnitUtil.TEST5_ANNOTATION)) return false; final JUnitConfiguration.Data data = configuration.getPersistentData(); data.PACKAGE_NAME = psiPackage.getQualifiedName(); data.TEST_OBJECT = JUnitConfiguration.TEST_PACKAGE; data.setScope(setupPackageConfiguration(context, configuration, data.getScope())); configuration.setGeneratedName(); return true; }
private int calculatePreferredWidth() { if (checkDirty()) return 1; assertValidState(); VisualLinesIterator iterator = new VisualLinesIterator(myView, 0); int maxWidth = 0; while (!iterator.atEnd()) { int visualLine = iterator.getVisualLine(); int width = myLineWidths.get(visualLine); if (width == UNKNOWN_WIDTH) { final Ref<Boolean> approximateValue = new Ref<Boolean>(Boolean.FALSE); width = getVisualLineWidth(iterator, () -> approximateValue.set(Boolean.TRUE)); if (approximateValue.get()) width = -width; myLineWidths.set(visualLine, width); } maxWidth = Math.max(maxWidth, Math.abs(width)); iterator.advance(); } return maxWidth; }
@NotNull private static String[] getUpToDateLines(final Document document) { final Ref<String[]> linesRef = new Ref<String[]>(); final Runnable runnable = () -> { final int lineCount = document.getLineCount(); final String[] lines = new String[lineCount]; final CharSequence chars = document.getCharsSequence(); for (int i = 0; i < lineCount; i++) { lines[i] = chars .subSequence(document.getLineStartOffset(i), document.getLineEndOffset(i)) .toString(); } linesRef.set(lines); }; ApplicationManager.getApplication().runReadAction(runnable); return linesRef.get(); }
private static VirtualFile findFileByPath( final String resPath, @Nullable final String dtdUrl, ProgressIndicator indicator) { final Ref<VirtualFile> ref = new Ref<>(); ApplicationManager.getApplication() .invokeAndWait( () -> ApplicationManager.getApplication() .runWriteAction( () -> { ref.set( LocalFileSystem.getInstance() .refreshAndFindFileByPath( resPath.replace(File.separatorChar, '/'))); if (dtdUrl != null) { ExternalResourceManager.getInstance().addResource(dtdUrl, resPath); } }), indicator.getModalityState()); return ref.get(); }
public static MavenDomDependency findManagedDependency( MavenDomProjectModel domModel, Project project, @NotNull final String groupId, @NotNull final String artifactId) { final Ref<MavenDomDependency> ref = new Ref<>(); MavenDomProjectProcessorUtils.processDependenciesInDependencyManagement( domModel, dependency -> { if (groupId.equals(dependency.getGroupId().getStringValue()) && artifactId.equals(dependency.getArtifactId().getStringValue())) { ref.set(dependency); return true; } return false; }, project); return ref.get(); }
private void collectLogEntriesForRepository( final ProgressIndicator indicator, FilePath file, final Consumer<VcsFileRevision> result, final Ref<Boolean> supports15Ref) throws SVNException, VcsException { final String url = file.getPath().replace('\\', '/'); if (indicator != null) { indicator.setText2(SvnBundle.message("progress.text2.changes.establishing.connection", url)); } SVNWCClient wcClient = myVcs.createWCClient(); final SVNURL svnurl = SVNURL.parseURIEncoded(url); SVNInfo info = wcClient.doInfo(svnurl, SVNRevision.UNDEFINED, SVNRevision.HEAD); final String root = info.getRepositoryRootURL().toString(); String relativeUrl = url; if (url.startsWith(root)) { relativeUrl = url.substring(root.length()); } SVNLogClient client = myVcs.createLogClient(); final boolean supports15 = SvnUtil.checkRepositoryVersion15(myVcs, root); supports15Ref.set(supports15); // todo log in history provider client.doLog( svnurl, new String[] {}, SVNRevision.UNDEFINED, SVNRevision.HEAD, SVNRevision.create(1), false, true, supports15, 0, null, new RepositoryLogEntryHandler( myVcs, url, SVNRevision.UNDEFINED, relativeUrl, result, info.getRepositoryRootURL())); }
@Override protected boolean preprocessUsages(@NotNull Ref<UsageInfo[]> refUsages) { UsageInfo[] usages = refUsages.get(); ArrayList<String> conflicts = new ArrayList<String>(); for (PsiElement element : myElements) { for (SafeDeleteProcessorDelegate delegate : Extensions.getExtensions(SafeDeleteProcessorDelegate.EP_NAME)) { if (delegate.handlesElement(element)) { Collection<String> foundConflicts = delegate instanceof SafeDeleteProcessorDelegateBase ? ((SafeDeleteProcessorDelegateBase) delegate) .findConflicts(element, myElements, usages) : delegate.findConflicts(element, myElements); if (foundConflicts != null) { conflicts.addAll(foundConflicts); } break; } } } final HashMap<PsiElement, UsageHolder> elementsToUsageHolders = sortUsages(usages); final Collection<UsageHolder> usageHolders = elementsToUsageHolders.values(); for (UsageHolder usageHolder : usageHolders) { if (usageHolder.hasUnsafeUsagesInCode()) { conflicts.add(usageHolder.getDescription()); } } if (!conflicts.isEmpty()) { final RefactoringEventData conflictData = new RefactoringEventData(); conflictData.putUserData(RefactoringEventData.CONFLICTS_KEY, conflicts); myProject .getMessageBus() .syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC) .conflictsDetected("refactoring.safeDelete", conflictData); if (ApplicationManager.getApplication().isUnitTestMode()) { if (!ConflictsInTestsException.isTestIgnore()) throw new ConflictsInTestsException(conflicts); } else { UnsafeUsagesDialog dialog = new UnsafeUsagesDialog(ArrayUtil.toStringArray(conflicts), myProject); if (!dialog.showAndGet()) { final int exitCode = dialog.getExitCode(); prepareSuccessful(); // dialog is always dismissed; if (exitCode == UnsafeUsagesDialog.VIEW_USAGES_EXIT_CODE) { showUsages( Arrays.stream(usages) .filter( usage -> usage instanceof SafeDeleteReferenceUsageInfo && !((SafeDeleteReferenceUsageInfo) usage).isSafeDelete()) .toArray(UsageInfo[]::new)); } return false; } else { myPreviewNonCodeUsages = false; } } } UsageInfo[] preprocessedUsages = usages; for (SafeDeleteProcessorDelegate delegate : Extensions.getExtensions(SafeDeleteProcessorDelegate.EP_NAME)) { preprocessedUsages = delegate.preprocessUsages(myProject, preprocessedUsages); if (preprocessedUsages == null) return false; } final UsageInfo[] filteredUsages = UsageViewUtil.removeDuplicatedUsages(preprocessedUsages); prepareSuccessful(); // dialog is always dismissed if (filteredUsages == null) { return false; } refUsages.set(filteredUsages); return true; }
public boolean preprocessUsages(final Ref<UsageInfo[]> refUsages) { UsageInfo[] usagesIn = refUsages.get(); MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>(); RenameUtil.addConflictDescriptions(usagesIn, conflicts); RenamePsiElementProcessor.forElement(myPrimaryElement) .findExistingNameConflicts(myPrimaryElement, myNewName, conflicts); if (!conflicts.isEmpty()) { if (ApplicationManager.getApplication().isUnitTestMode()) { throw new ConflictsInTestsException(conflicts.values()); } ConflictsDialog conflictsDialog = prepareConflictsDialog(conflicts, refUsages.get()); conflictsDialog.show(); if (!conflictsDialog.isOK()) { if (conflictsDialog.isShowConflicts()) prepareSuccessful(); return false; } } final List<UsageInfo> variableUsages = new ArrayList<UsageInfo>(); if (!myRenamers.isEmpty()) { if (!findRenamedVariables(variableUsages)) return false; final LinkedHashMap<PsiElement, String> renames = new LinkedHashMap<PsiElement, String>(); for (final AutomaticRenamer renamer : myRenamers) { final List<? extends PsiNamedElement> variables = renamer.getElements(); for (final PsiNamedElement variable : variables) { final String newName = renamer.getNewName(variable); if (newName != null) { addElement(variable, newName); prepareRenaming(variable, newName, renames); } } } if (!renames.isEmpty()) { myAllRenames.putAll(renames); final Runnable runnable = new Runnable() { public void run() { for (Map.Entry<PsiElement, String> entry : renames.entrySet()) { final UsageInfo[] usages = RenameUtil.findUsages( entry.getKey(), entry.getValue(), mySearchInComments, mySearchTextOccurrences, myAllRenames); Collections.addAll(variableUsages, usages); } } }; if (!ProgressManager.getInstance() .runProcessWithProgressSynchronously( runnable, RefactoringBundle.message("searching.for.variables"), true, myProject)) { return false; } } } final Set<UsageInfo> usagesSet = new HashSet<UsageInfo>(Arrays.asList(usagesIn)); usagesSet.addAll(variableUsages); final List<UnresolvableCollisionUsageInfo> conflictUsages = RenameUtil.removeConflictUsages(usagesSet); if (conflictUsages != null) { mySkippedUsages.addAll(conflictUsages); } refUsages.set(usagesSet.toArray(new UsageInfo[usagesSet.size()])); prepareSuccessful(); return true; }
@RequiredReadAction private static boolean processInheritors( @NotNull final Processor<DotNetTypeDeclaration> consumer, @NotNull final String baseVmQName, @NotNull final SearchScope searchScope, @NotNull final SearchParameters parameters) { if (DotNetTypes.System.Object.equals(baseVmQName)) { return AllTypesSearch.search( searchScope, parameters.getProject(), parameters.getNameCondition()) .forEach( new Processor<DotNetTypeDeclaration>() { @Override public boolean process(final DotNetTypeDeclaration aClass) { ProgressIndicatorProvider.checkCanceled(); final String qname1 = ApplicationManager.getApplication() .runReadAction( new Computable<String>() { @Override @Nullable public String compute() { return aClass.getVmQName(); } }); return DotNetTypes.System.Object.equals(qname1) || consumer.process(parameters.myTransformer.fun(aClass)); } }); } final Ref<String> currentBase = Ref.create(null); final Stack<String> stack = new Stack<String>(); // there are two sets for memory optimization: it's cheaper to hold FQN than PsiClass final Set<String> processedFqns = new THashSet<String>(); // FQN of processed classes if the class has one final Processor<DotNetTypeDeclaration> processor = new Processor<DotNetTypeDeclaration>() { @Override public boolean process(final DotNetTypeDeclaration candidate) { ProgressIndicatorProvider.checkCanceled(); final Ref<Boolean> result = new Ref<Boolean>(); final Ref<String> vmQNameRef = new Ref<String>(); ApplicationManager.getApplication() .runReadAction( new Runnable() { @Override public void run() { vmQNameRef.set(candidate.getVmQName()); if (parameters.isCheckInheritance() || parameters.isCheckDeep()) { if (!candidate.isInheritor(currentBase.get(), false)) { result.set(true); return; } } if (PsiSearchScopeUtil.isInScope(searchScope, candidate)) { final String name = candidate.getName(); if (name != null && parameters.getNameCondition().value(name) && !consumer.process(parameters.myTransformer.fun(candidate))) { result.set(false); } } } }); if (!result.isNull()) { return result.get(); } if (parameters.isCheckDeep() && !isSealed(candidate)) { stack.push(vmQNameRef.get()); } return true; } }; stack.push(baseVmQName); final GlobalSearchScope projectScope = GlobalSearchScope.allScope(parameters.getProject()); while (!stack.isEmpty()) { ProgressIndicatorProvider.checkCanceled(); String vmQName = stack.pop(); if (!processedFqns.add(vmQName)) { continue; } currentBase.set(vmQName); if (!DirectTypeInheritorsSearch.search(parameters.getProject(), vmQName, projectScope, false) .forEach(processor)) { return false; } } return true; }
private void showHint(Info info) { if (myDisposed || myEditor.isDisposed()) return; Component internalComponent = myEditor.getContentComponent(); if (myHighlighter != null) { if (!info.isSimilarTo(myHighlighter.getStoredInfo())) { disposeHighlighter(); } else { // highlighter already set internalComponent.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); return; } } if (!info.isValid(myEditor.getDocument())) { return; } myHighlighter = installHighlighterSet(info, myEditor); DocInfo docInfo = info.getInfo(); if (docInfo.text == null) return; if (myDocumentationManager.hasActiveDockedDocWindow()) { info.showDocInfo(myDocumentationManager); } HyperlinkListener hyperlinkListener = docInfo.docProvider == null ? null : new QuickDocHyperlinkListener(docInfo.docProvider, info.myElementAtPointer); final Ref<QuickDocInfoPane> quickDocPaneRef = new Ref<QuickDocInfoPane>(); MouseListener mouseListener = new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { QuickDocInfoPane pane = quickDocPaneRef.get(); if (pane != null) { pane.mouseEntered(e); } } @Override public void mouseExited(MouseEvent e) { QuickDocInfoPane pane = quickDocPaneRef.get(); if (pane != null) { pane.mouseExited(e); } } @Override public void mouseClicked(MouseEvent e) { QuickDocInfoPane pane = quickDocPaneRef.get(); if (pane != null) { pane.mouseClicked(e); } } }; Ref<Consumer<String>> newTextConsumerRef = new Ref<Consumer<String>>(); JComponent label = HintUtil.createInformationLabel( docInfo.text, hyperlinkListener, mouseListener, newTextConsumerRef); Consumer<String> newTextConsumer = newTextConsumerRef.get(); QuickDocInfoPane quickDocPane = null; if (docInfo.documentationAnchor != null) { quickDocPane = new QuickDocInfoPane(docInfo.documentationAnchor, info.myElementAtPointer, label); quickDocPaneRef.set(quickDocPane); } JComponent hintContent = quickDocPane == null ? label : quickDocPane; final LightweightHint hint = new LightweightHint(hintContent); myHint = hint; hint.addHintListener( new HintListener() { @Override public void hintHidden(EventObject event) { myHint = null; } }); myDocAlarm.cancelAllRequests(); if (newTextConsumer != null && docInfo.docProvider != null && docInfo.documentationAnchor != null) { fulfillDocInfo( docInfo.text, docInfo.docProvider, info.myElementAtPointer, docInfo.documentationAnchor, newTextConsumer, hint); } showHint(hint); }
private static JBPopup getPsiElementPopup( final Object[] elements, final Map<PsiElement, GotoRelatedItem> itemsMap, final String title, final Processor<Object> processor) { final Ref<Boolean> hasMnemonic = Ref.create(false); final DefaultPsiElementCellRenderer renderer = new DefaultPsiElementCellRenderer() { { setFocusBorderEnabled(false); } @Override public String getElementText(PsiElement element) { String customName = itemsMap.get(element).getCustomName(); return (customName != null ? customName : super.getElementText(element)); } @Override protected Icon getIcon(PsiElement element) { Icon customIcon = itemsMap.get(element).getCustomIcon(); return customIcon != null ? customIcon : super.getIcon(element); } @Override public String getContainerText(PsiElement element, String name) { PsiFile file = element.getContainingFile(); return file != null && !getElementText(element).equals(file.getName()) ? "(" + file.getName() + ")" : null; } @Override protected DefaultListCellRenderer getRightCellRenderer() { return null; } @Override protected boolean customizeNonPsiElementLeftRenderer( ColoredListCellRenderer renderer, JList list, Object value, int index, boolean selected, boolean hasFocus) { final GotoRelatedItem item = (GotoRelatedItem) value; Color color = list.getForeground(); final SimpleTextAttributes nameAttributes = new SimpleTextAttributes(Font.PLAIN, color); final String name = item.getCustomName(); if (name == null) return false; renderer.append(name, nameAttributes); renderer.setIcon(item.getCustomIcon()); return true; } @Override public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { final JPanel component = (JPanel) super.getListCellRendererComponent( list, value, index, isSelected, cellHasFocus); if (!hasMnemonic.get()) return component; final JPanel panelWithMnemonic = new JPanel(new BorderLayout()); final int mnemonic = getMnemonic(value, itemsMap); final JLabel label = new JLabel(""); if (mnemonic != -1) { label.setText(mnemonic + "."); label.setDisplayedMnemonicIndex(0); } label.setPreferredSize(new JLabel("8.").getPreferredSize()); final JComponent leftRenderer = (JComponent) component.getComponents()[0]; component.remove(leftRenderer); panelWithMnemonic.setBackground(leftRenderer.getBackground()); label.setBackground(leftRenderer.getBackground()); panelWithMnemonic.add(label, BorderLayout.WEST); panelWithMnemonic.add(leftRenderer, BorderLayout.CENTER); component.add(panelWithMnemonic); return component; } }; final ListPopupImpl popup = new ListPopupImpl( new BaseListPopupStep<Object>(title, Arrays.asList(elements)) { @Override public boolean isSpeedSearchEnabled() { return true; } @Override public PopupStep onChosen(Object selectedValue, boolean finalChoice) { processor.process(selectedValue); return super.onChosen(selectedValue, finalChoice); } }) { @Override protected ListCellRenderer getListElementRenderer() { return renderer; } }; popup.setMinimumSize(new Dimension(200, -1)); for (Object item : elements) { final int mnemonic = getMnemonic(item, itemsMap); if (mnemonic != -1) { final Action action = createNumberAction(mnemonic, popup, itemsMap, processor); popup.registerAction( mnemonic + "Action", KeyStroke.getKeyStroke(String.valueOf(mnemonic)), action); hasMnemonic.set(true); } } return popup; }
private int extractExpectedHighlight( final Matcher matcher, final String text, final Document document, final Ref<Integer> textOffset) { document.deleteString(textOffset.get(), textOffset.get() + matcher.end() - matcher.start()); int groupIdx = 1; final String marker = matcher.group(groupIdx++); String descr = matcher.group(groupIdx++); final String typeString = matcher.group(groupIdx++); final String foregroundColor = matcher.group(groupIdx++); final String backgroundColor = matcher.group(groupIdx++); final String effectColor = matcher.group(groupIdx++); final String effectType = matcher.group(groupIdx++); final String fontType = matcher.group(groupIdx++); final String attrKey = matcher.group(groupIdx++); final String bundleMessage = matcher.group(groupIdx++); final boolean closed = matcher.group(groupIdx) != null; if (descr == null) { descr = ANY_TEXT; // no descr means any string by default } else if (descr.equals("null")) { descr = null; // explicit "null" descr } if (descr != null) { descr = descr.replaceAll( "\\\\\\\\\"", "\""); // replace: \\" to ", doesn't check symbol before sequence \\" descr = descr.replaceAll("\\\\\"", "\""); } HighlightInfoType type = WHATEVER; if (typeString != null) { try { type = getTypeByName(typeString); } catch (Exception e) { LOG.error(e); } LOG.assertTrue(type != null, "Wrong highlight type: " + typeString); } TextAttributes forcedAttributes = null; if (foregroundColor != null) { //noinspection MagicConstant forcedAttributes = new TextAttributes( Color.decode(foregroundColor), Color.decode(backgroundColor), Color.decode(effectColor), EffectType.valueOf(effectType), Integer.parseInt(fontType)); } final int rangeStart = textOffset.get(); final int toContinueFrom; if (closed) { toContinueFrom = matcher.end(); } else { int pos = matcher.end(); final Matcher closingTagMatcher = Pattern.compile("</" + marker + ">").matcher(text); while (true) { if (!closingTagMatcher.find(pos)) { LOG.error("Cannot find closing </" + marker + "> in position " + pos); } final int nextTagStart = matcher.find(pos) ? matcher.start() : text.length(); if (closingTagMatcher.start() < nextTagStart) { textOffset.set(textOffset.get() + closingTagMatcher.start() - pos); document.deleteString( textOffset.get(), textOffset.get() + closingTagMatcher.end() - closingTagMatcher.start()); toContinueFrom = closingTagMatcher.end(); break; } textOffset.set(textOffset.get() + nextTagStart - pos); pos = extractExpectedHighlight(matcher, text, document, textOffset); } } final ExpectedHighlightingSet expectedHighlightingSet = myHighlightingTypes.get(marker); if (expectedHighlightingSet.enabled) { TextAttributesKey forcedTextAttributesKey = attrKey == null ? null : TextAttributesKey.createTextAttributesKey(attrKey); HighlightInfo.Builder builder = HighlightInfo.newHighlightInfo(type) .range(rangeStart, textOffset.get()) .severity(expectedHighlightingSet.severity); if (forcedAttributes != null) builder.textAttributes(forcedAttributes); if (forcedTextAttributesKey != null) builder.textAttributes(forcedTextAttributesKey); if (bundleMessage != null) { final List<String> split = StringUtil.split(bundleMessage, "|"); final ResourceBundle bundle = ResourceBundle.getBundle(split.get(0)); descr = CommonBundle.message(bundle, split.get(1), split.stream().skip(2).toArray()); } if (descr != null) { builder.description(descr); builder.unescapedToolTip(descr); } if (expectedHighlightingSet.endOfLine) builder.endOfLine(); HighlightInfo highlightInfo = builder.createUnconditionally(); expectedHighlightingSet.infos.add(highlightInfo); } return toContinueFrom; }