public String[] knownNamespaces() { final PsiElement parentElement = getParent(); BidirectionalMap<String, String> map = initNamespaceMaps(parentElement); Set<String> known = Collections.emptySet(); if (map != null) { known = new HashSet<String>(map.values()); } if (parentElement instanceof XmlTag) { if (known.isEmpty()) return ((XmlTag) parentElement).knownNamespaces(); ContainerUtil.addAll(known, ((XmlTag) parentElement).knownNamespaces()); } else { XmlExtension xmlExtension = XmlExtension.getExtensionByElement(this); if (xmlExtension != null) { final XmlFile xmlFile = xmlExtension.getContainingFile(this); if (xmlFile != null) { final XmlTag rootTag = xmlFile.getRootTag(); if (rootTag != null && rootTag != this) { if (known.isEmpty()) return rootTag.knownNamespaces(); ContainerUtil.addAll(known, rootTag.knownNamespaces()); } } } } return ArrayUtil.toStringArray(known); }
@Override public boolean canCloseProject(Project project) { if (!myUnsavedDocuments.isEmpty()) { myOnClose = true; try { saveAllDocuments(); } finally { myOnClose = false; } } return myUnsavedDocuments.isEmpty(); }
private static Map<String, PsiType> getCompatibleTypeNames( @NotNull PsiType type, @Nullable PsiType min, PsiManager manager, GlobalSearchScope scope) { if (type instanceof PsiDisjunctionType) type = ((PsiDisjunctionType) type).getLeastUpperBound(); // if initial type is not assignable to min type we don't take into consideration min type. if (min != null && !TypesUtil.isAssignable(min, type, manager, scope)) { min = null; } Map<String, PsiType> map = new LinkedHashMap<String, PsiType>(); final PsiPrimitiveType unboxed = PsiPrimitiveType.getUnboxedType(type); if (unboxed != null) type = unboxed; final Set<PsiType> set = new LinkedHashSet<PsiType>(); set.add(type); while (!set.isEmpty()) { PsiType cur = set.iterator().next(); set.remove(cur); if (!map.containsValue(cur) && (min == null || TypesUtil.isAssignable(min, cur, manager, scope))) { if (isPartiallySubstituted(cur)) { LOG.assertTrue(cur instanceof PsiClassType); PsiClassType rawType = ((PsiClassType) cur).rawType(); map.put(rawType.getPresentableText(), rawType); } else { map.put(cur.getPresentableText(), cur); } for (PsiType superType : cur.getSuperTypes()) { if (!map.containsValue(superType)) { set.add(superType); } } } } return map; }
public boolean checkCanRemove(final List<? extends PackagingElementNode<?>> nodes) { Set<PackagingNodeSource> rootSources = new HashSet<PackagingNodeSource>(); for (PackagingElementNode<?> node : nodes) { rootSources.addAll(getRootNodeSources(node.getNodeSources())); } if (!rootSources.isEmpty()) { final String message; if (rootSources.size() == 1) { final String name = rootSources.iterator().next().getPresentableName(); message = "The selected node belongs to '" + name + "' element. Do you want to remove the whole '" + name + "' element from the artifact?"; } else { message = "The selected node belongs to " + nodes.size() + " elements. Do you want to remove all these elements from the artifact?"; } final int answer = Messages.showYesNoDialog( myArtifactsEditor.getMainComponent(), message, "Remove Elements", null); if (answer != Messages.YES) return false; } return true; }
@Override public void saveAllDocuments() { ApplicationManager.getApplication().assertIsDispatchThread(); myMultiCaster.beforeAllDocumentsSaving(); if (myUnsavedDocuments.isEmpty()) return; final Map<Document, IOException> failedToSave = new HashMap<Document, IOException>(); final Set<Document> vetoed = new HashSet<Document>(); while (true) { int count = 0; for (Document document : myUnsavedDocuments) { if (failedToSave.containsKey(document)) continue; if (vetoed.contains(document)) continue; try { doSaveDocument(document); } catch (IOException e) { //noinspection ThrowableResultOfMethodCallIgnored failedToSave.put(document, e); } catch (SaveVetoException e) { vetoed.add(document); } count++; } if (count == 0) break; } if (!failedToSave.isEmpty()) { handleErrorsOnSave(failedToSave); } }
@NotNull public Change[] getSelectedChanges() { Set<Change> changes = new LinkedHashSet<Change>(); final TreePath[] paths = getSelectionPaths(); if (paths == null) { return new Change[0]; } for (TreePath path : paths) { ChangesBrowserNode<?> node = (ChangesBrowserNode) path.getLastPathComponent(); changes.addAll(node.getAllChangesUnder()); } if (changes.isEmpty()) { final List<VirtualFile> selectedModifiedWithoutEditing = getSelectedModifiedWithoutEditing(); if (selectedModifiedWithoutEditing != null && !selectedModifiedWithoutEditing.isEmpty()) { for (VirtualFile file : selectedModifiedWithoutEditing) { AbstractVcs vcs = ProjectLevelVcsManager.getInstance(myProject).getVcsFor(file); if (vcs == null) continue; final VcsCurrentRevisionProxy before = VcsCurrentRevisionProxy.create(file, myProject, vcs.getKeyInstanceMethod()); if (before != null) { ContentRevision afterRevision = new CurrentContentRevision(new FilePathImpl(file)); changes.add(new Change(before, afterRevision, FileStatus.HIJACKED)); } } } } return changes.toArray(new Change[changes.size()]); }
private boolean checkReadonlyUsages() { final Set<VirtualFile> readOnlyUsages = getReadOnlyUsagesFiles(); return readOnlyUsages.isEmpty() || !ReadonlyStatusHandler.getInstance(myProject) .ensureFilesWritable(VfsUtil.toVirtualFileArray(readOnlyUsages)) .hasReadonlyFiles(); }
@Override @NotNull public Document[] getUnsavedDocuments() { if (myUnsavedDocuments.isEmpty()) { return Document.EMPTY_ARRAY; } List<Document> list = new ArrayList<Document>(myUnsavedDocuments); return list.toArray(new Document[list.size()]); }
public boolean isModified() { Sdk projectSdk = getSdk(); if (projectSdk != null) { projectSdk = myProjectSdksModel.findSdk(projectSdk.getName()); } return getSelectedSdk() != projectSdk || mySdkListChanged || myProjectSdksModel.isModified() || !myModifiedModificators.isEmpty(); }
private ActionCallback processAjusted( final Map<Object, Condition> adjusted, final Set<Object> originallySelected) { final ActionCallback result = new ActionCallback(); final Set<Object> allSelected = myUi.getSelectedElements(); Set<Object> toSelect = new HashSet<Object>(); for (Map.Entry<Object, Condition> entry : adjusted.entrySet()) { if (entry.getValue().value(entry.getKey())) continue; for (final Object eachSelected : allSelected) { if (isParentOrSame(entry.getKey(), eachSelected)) continue; toSelect.add(entry.getKey()); } if (allSelected.isEmpty()) { toSelect.add(entry.getKey()); } } final Object[] newSelection = ArrayUtil.toObjectArray(toSelect); if (newSelection.length > 0) { myUi._select( newSelection, new Runnable() { @Override public void run() { final Set<Object> hangByParent = new HashSet<Object>(); processUnsuccessfulSelections( newSelection, new Function<Object, Object>() { @Override public Object fun(final Object o) { if (myUi.isInStructure(o) && !adjusted.get(o).value(o)) { hangByParent.add(o); } else { addAdjustedSelection(o, adjusted.get(o), null); } return null; } }, originallySelected); processHangByParent(hangByParent).notify(result); } }, false, true, true); } else { result.setDone(); } return result; }
@TestOnly public void dropAllUnsavedDocuments() { if (!ApplicationManager.getApplication().isUnitTestMode()) { throw new RuntimeException("This method is only for test mode!"); } ApplicationManager.getApplication().assertWriteAccessAllowed(); if (!myUnsavedDocuments.isEmpty()) { myUnsavedDocuments.clear(); fireUnsavedDocumentsDropped(); } }
@Override public void commitAllDocuments() { ApplicationManager.getApplication().assertIsDispatchThread(); if (myUncommittedDocuments.isEmpty()) return; final Document[] documents = getUncommittedDocuments(); for (Document document : documents) { commitDocument(document); } LOG.assertTrue(!hasUncommitedDocuments(), myUncommittedDocuments); }
private ActionCallback processHangByParent(Set<Object> elements) { if (elements.isEmpty()) return new ActionCallback.Done(); ActionCallback result = new ActionCallback(elements.size()); for (Object hangElement : elements) { if (!myAdjustmentCause2Adjustment.containsKey(hangElement)) { processHangByParent(hangElement).notify(result); } else { result.setDone(); } } return result; }
public List debugLastStates() { List states = new ArrayList(); Set set = machine.getStateSet(); if (set.isEmpty()) set = machine.getStartStates(); Iterator iterator = set.iterator(); while (iterator.hasNext()) { states.add(getState((String) iterator.next())); } return states; }
private void processUnsuccessfulSelections( final Object[] toSelect, Function<Object, Object> restore, Set<Object> originallySelected) { final Set<Object> selected = myUi.getSelectedElements(); boolean wasFullyRejected = false; if (toSelect.length > 0 && !selected.isEmpty() && !originallySelected.containsAll(selected)) { final Set<Object> successfulSelections = new HashSet<Object>(); ContainerUtil.addAll(successfulSelections, toSelect); successfulSelections.retainAll(selected); wasFullyRejected = successfulSelections.isEmpty(); } else if (selected.isEmpty() && originallySelected.isEmpty()) { wasFullyRejected = true; } if (wasFullyRejected && !selected.isEmpty()) return; for (Object eachToSelect : toSelect) { if (!selected.contains(eachToSelect)) { restore.fun(eachToSelect); } } }
/** * Allows to answer if given ide project has 1-1 mapping with the given external project, i.e. the * ide project has been imported from external system and no other external projects have been * added. * * <p>This might be necessary in a situation when project-level setting is changed (e.g. project * name). We don't want to rename ide project if it doesn't completely corresponds to the given * ide project then. * * @param ideProject target ide project * @param externalProject target external project * @return <code>true</code> if given ide project has 1-1 mapping to the given external project; * <code>false</code> otherwise */ public static boolean isOneToOneMapping( @NotNull Project ideProject, @NotNull DataNode<ProjectData> externalProject) { String linkedExternalProjectPath = null; for (ExternalSystemManager<?, ?, ?, ?, ?> manager : ExternalSystemApiUtil.getAllManagers()) { ProjectSystemId externalSystemId = manager.getSystemId(); AbstractExternalSystemSettings systemSettings = ExternalSystemApiUtil.getSettings(ideProject, externalSystemId); Collection projectsSettings = systemSettings.getLinkedProjectsSettings(); int linkedProjectsNumber = projectsSettings.size(); if (linkedProjectsNumber > 1) { // More than one external project of the same external system type is linked to the given // ide project. return false; } else if (linkedProjectsNumber == 1) { if (linkedExternalProjectPath == null) { // More than one external project of different external system types is linked to the // current ide project. linkedExternalProjectPath = ((ExternalProjectSettings) projectsSettings.iterator().next()) .getExternalProjectPath(); } else { return false; } } } ProjectData projectData = externalProject.getData(); if (linkedExternalProjectPath != null && !linkedExternalProjectPath.equals(projectData.getLinkedExternalProjectPath())) { // New external project is being linked. return false; } Set<String> externalModulePaths = ContainerUtilRt.newHashSet(); for (DataNode<ModuleData> moduleNode : ExternalSystemApiUtil.findAll(externalProject, ProjectKeys.MODULE)) { externalModulePaths.add(moduleNode.getData().getLinkedExternalProjectPath()); } externalModulePaths.remove(linkedExternalProjectPath); PlatformFacade platformFacade = ServiceManager.getService(PlatformFacade.class); for (Module module : platformFacade.getModules(ideProject)) { String path = module.getOptionValue(ExternalSystemConstants.LINKED_PROJECT_PATH_KEY); if (!StringUtil.isEmpty(path) && !externalModulePaths.remove(path)) { return false; } } return externalModulePaths.isEmpty(); }
public Collection<AbstractVcs> getAffectedVcses() { final ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(myProject); final Set<AbstractVcs> vcses = new HashSet<AbstractVcs>(Arrays.asList(vcsManager.getAllActiveVcss())); final Set<AbstractVcs> result = new HashSet<AbstractVcs>(); for (Change change : myBrowser.myAllChanges) { if (vcses.isEmpty()) break; final AbstractVcs vcs = ChangesUtil.getVcsForChange(change, myBrowser.myProject); if (vcs != null) { result.add(vcs); vcses.remove(vcs); } } return result; }
/** * Cancel previously registered action and schedules (new) action to be executed when all * documents are committed. * * @param key the (unique) id of the action. * @param action The action to be executed after automatic commit. This action will overwrite any * action which was registered under this key earlier. The action will be executed in EDT. * @return true if action has been run immediately, or false if action was scheduled for execution * later. */ public boolean cancelAndRunWhenAllCommitted( @NonNls @NotNull Object key, @NotNull final Runnable action) { ApplicationManager.getApplication().assertIsDispatchThread(); if (myProject.isDisposed()) { action.run(); return true; } if (myUncommittedDocuments.isEmpty()) { action.run(); assert actionsWhenAllDocumentsAreCommitted.isEmpty() : actionsWhenAllDocumentsAreCommitted; return true; } actionsWhenAllDocumentsAreCommitted.put(key, action); return false; }
private boolean showToolTipByMouseMove(final MouseEvent e, final double width) { MouseEvent me = e; Set<RangeHighlighter> highlighters = new THashSet<RangeHighlighter>(); getNearestHighlighters(this, me, width, highlighters); getNearestHighlighters( (MarkupModelEx) myEditor.getDocument().getMarkupModel(getEditor().getProject()), me, width, highlighters); if (highlighters.isEmpty()) return false; int minDelta = Integer.MAX_VALUE; int y = e.getY(); for (RangeHighlighter each : highlighters) { ProperTextRange range = offsetToYPosition(each.getStartOffset(), each.getEndOffset()); int eachStartY = range.getStartOffset(); int eachEndY = range.getEndOffset(); int eachY = eachStartY + (eachEndY - eachStartY) / 2; if (Math.abs(e.getY() - eachY) < minDelta) { y = eachY; } } me = new MouseEvent( (Component) e.getSource(), e.getID(), e.getWhen(), e.getModifiers(), e.getX(), y + 1, e.getClickCount(), e.isPopupTrigger()); TooltipRenderer bigRenderer = myTooltipRendererProvider.calcTooltipRenderer(highlighters); if (bigRenderer != null) { showTooltip( me, bigRenderer, new HintHint(me).setAwtTooltip(true).setPreferredPosition(Balloon.Position.atLeft)); return true; } return false; }
@Nullable private Ref<? extends PyType> getYieldStatementType(@NotNull final TypeEvalContext context) { Ref<PyType> elementType = null; final PyBuiltinCache cache = PyBuiltinCache.getInstance(this); final PyStatementList statements = getStatementList(); final Set<PyType> types = new LinkedHashSet<>(); statements.accept( new PyRecursiveElementVisitor() { @Override public void visitPyYieldExpression(PyYieldExpression node) { final PyExpression expr = node.getExpression(); final PyType type = expr != null ? context.getType(expr) : null; if (node.isDelegating() && type instanceof PyCollectionType) { final PyCollectionType collectionType = (PyCollectionType) type; // TODO: Select the parameter types that matches T in Iterable[T] final List<PyType> elementTypes = collectionType.getElementTypes(context); types.add(elementTypes.isEmpty() ? null : elementTypes.get(0)); } else { types.add(type); } } @Override public void visitPyFunction(PyFunction node) { // Ignore nested functions } }); final int n = types.size(); if (n == 1) { elementType = Ref.create(types.iterator().next()); } else if (n > 0) { elementType = Ref.create(PyUnionType.union(types)); } if (elementType != null) { final PyClass generator = cache.getClass(PyNames.FAKE_GENERATOR); if (generator != null) { final List<PyType> parameters = Arrays.asList(elementType.get(), null, getReturnStatementType(context)); return Ref.create(new PyCollectionTypeImpl(generator, false, parameters)); } } if (!types.isEmpty()) { return Ref.create(null); } return null; }
private boolean checkReferencedRastersIncluded() { final Set<String> notIncludedNames = new TreeSet<String>(); final List<String> includedNodeNames = Arrays.asList(productSubsetDef.getNodeNames()); for (final String nodeName : includedNodeNames) { final RasterDataNode rasterDataNode = product.getRasterDataNode(nodeName); if (rasterDataNode != null) { collectNotIncludedReferences(rasterDataNode, notIncludedNames); } } boolean ok = true; if (!notIncludedNames.isEmpty()) { StringBuilder nameListText = new StringBuilder(); for (String notIncludedName : notIncludedNames) { nameListText.append(" '").append(notIncludedName).append("'\n"); } final String pattern = "The following dataset(s) are referenced but not included\n" + "in your current subset definition:\n" + "{0}\n" + "If you do not include these dataset(s) into your selection,\n" + "you might get unexpected results while working with the\n" + "resulting product.\n\n" + "Do you wish to include the referenced dataset(s) into your\n" + "subset definition?\n"; /*I18N*/ final MessageFormat format = new MessageFormat(pattern); int status = JOptionPane.showConfirmDialog( getJDialog(), format.format(new Object[] {nameListText.toString()}), "Incomplete Subset Definition", /*I18N*/ JOptionPane.YES_NO_CANCEL_OPTION); if (status == JOptionPane.YES_OPTION) { final String[] nodenames = notIncludedNames.toArray(new String[notIncludedNames.size()]); productSubsetDef.addNodeNames(nodenames); ok = true; } else if (status == JOptionPane.NO_OPTION) { ok = true; } else if (status == JOptionPane.CANCEL_OPTION) { ok = false; } } return ok; }
public void apply() throws ConfigurationException { if (!myModifiedModificators.isEmpty()) { mySdkSettingsWereModified.run(); } for (SdkModificator modificator : myModifiedModificators) { /* This should always be true barring bug elsewhere, log error on else? */ if (modificator.isWritable()) { modificator.commitChanges(); } } myModificators.clear(); myModifiedModificators.clear(); mySdkListChanged = false; final Sdk sdk = getSelectedSdk(); myShowMoreCallback.consume(sdk); PyPackageManagers.getInstance().clearCache(sdk); Disposer.dispose(getDisposable()); }
private InspectionProfile guessProfileToSelect( final InspectionProjectProfileManager profileManager) { final Set<InspectionProfile> profiles = new HashSet<InspectionProfile>(); final RefEntity[] selectedElements = myTree.getSelectedElements(); for (RefEntity selectedElement : selectedElements) { if (selectedElement instanceof RefElement) { final RefElement refElement = (RefElement) selectedElement; final PsiElement element = refElement.getElement(); if (element != null) { profiles.add(profileManager.getInspectionProfile()); } } } if (profiles.isEmpty()) { return (InspectionProfile) profileManager.getProjectProfileImpl(); } return profiles.iterator().next(); }
@Nullable private Ref<? extends PyType> getYieldStatementType(@NotNull final TypeEvalContext context) { Ref<PyType> elementType = null; final PyBuiltinCache cache = PyBuiltinCache.getInstance(this); final PyStatementList statements = getStatementList(); final Set<PyType> types = new LinkedHashSet<PyType>(); if (statements != null) { statements.accept( new PyRecursiveElementVisitor() { @Override public void visitPyYieldExpression(PyYieldExpression node) { final PyType type = context.getType(node); if (node.isDelegating() && type instanceof PyCollectionType) { final PyCollectionType collectionType = (PyCollectionType) type; types.add(collectionType.getElementType(context)); } else { types.add(type); } } @Override public void visitPyFunction(PyFunction node) { // Ignore nested functions } }); final int n = types.size(); if (n == 1) { elementType = Ref.create(types.iterator().next()); } else if (n > 0) { elementType = Ref.create(PyUnionType.union(types)); } } if (elementType != null) { final PyClass generator = cache.getClass(PyNames.FAKE_GENERATOR); if (generator != null) { return Ref.create(new PyCollectionTypeImpl(generator, false, elementType.get())); } } if (!types.isEmpty()) { return Ref.create(null); } return null; }
private void runQuery() { if (getRootPane() == null) return; Set<InlineProgressIndicator> indicators = getCurrentInlineIndicators(); if (indicators.isEmpty()) return; for (InlineProgressIndicator each : indicators) { each.updateProgress(); } myQueryAlarm.cancelAllRequests(); myQueryAlarm.addRequest( new Runnable() { @Override public void run() { runQuery(); } }, 2000); }
/** * Schedules action to be executed when all documents are committed. * * @return true if action has been run immediately, or false if action was scheduled for execution * later. */ @Override public boolean performWhenAllCommitted(@NotNull final Runnable action) { ApplicationManager.getApplication().assertIsDispatchThread(); assert !myProject.isDisposed() : "Already disposed: " + myProject; if (myUncommittedDocuments.isEmpty()) { action.run(); return true; } CompositeRunnable actions = (CompositeRunnable) actionsWhenAllDocumentsAreCommitted.get(PERFORM_ALWAYS_KEY); if (actions == null) { actions = new CompositeRunnable(); actionsWhenAllDocumentsAreCommitted.put(PERFORM_ALWAYS_KEY, actions); } actions.add(action); myDocumentCommitProcessor.log( "PDI: added performWhenAllCommitted", null, false, action, myUncommittedDocuments); return false; }
@Nullable private UsageTarget[] getSelectedUsageTargets() { TreePath[] selectionPaths = myTree.getSelectionPaths(); if (selectionPaths == null) return null; Set<UsageTarget> targets = new THashSet<UsageTarget>(); for (TreePath selectionPath : selectionPaths) { Object lastPathComponent = selectionPath.getLastPathComponent(); if (lastPathComponent instanceof UsageTargetNode) { UsageTargetNode usageTargetNode = (UsageTargetNode) lastPathComponent; UsageTarget target = usageTargetNode.getTarget(); if (target != null && target.isValid()) { targets.add(target); } } } return targets.isEmpty() ? null : targets.toArray(new UsageTarget[targets.size()]); }
/** * Executes when FETCH button is pressed. Fetches repository in background. Then updates the * commit tree. */ private void fetch() { Map<VirtualFile, Set<String>> unchecked = new HashMap<VirtualFile, Set<String>>(); for (int i = 0; i < myTreeRoot.getChildCount(); i++) { Set<String> uncheckedCommits = new HashSet<String>(); CheckedTreeNode node = (CheckedTreeNode) myTreeRoot.getChildAt(i); Root r = (Root) node.getUserObject(); for (int j = 0; j < node.getChildCount(); j++) { if (node.getChildAt(j) instanceof CheckedTreeNode) { CheckedTreeNode commitNode = (CheckedTreeNode) node.getChildAt(j); if (!commitNode.isChecked()) { uncheckedCommits.add(((Commit) commitNode.getUserObject()).commitId()); } } } if (!uncheckedCommits.isEmpty()) { unchecked.put(r.root, uncheckedCommits); } } refreshTree(true, unchecked); }
private String canCreateAllFilesForAllLocales() { final String name = getBaseName(); if (name.isEmpty()) { return "Base name is empty"; } final Set<String> files = getFileNamesToCreate(); if (files.isEmpty()) { return "No locales added"; } for (PsiElement element : myDirectory.getChildren()) { if (element instanceof PsiFile) { if (element instanceof PropertiesFile) { PropertiesFile propertiesFile = (PropertiesFile) element; final String propertiesFileName = propertiesFile.getName(); if (files.contains(propertiesFileName)) { return "Some of files already exist"; } } } } return null; }
@Nullable private AnalysisScope getScope() { final Set<PsiFile> selectedScope = getSelectedScope(myRightTree); Set<PsiFile> result = new HashSet<PsiFile>(); ((PackageDependenciesNode) myLeftTree.getModel().getRoot()) .fillFiles(result, !mySettings.UI_FLATTEN_PACKAGES); selectedScope.removeAll(result); if (selectedScope.isEmpty()) return null; List<VirtualFile> files = new ArrayList<VirtualFile>(); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex(); for (PsiFile psiFile : selectedScope) { final VirtualFile file = psiFile.getVirtualFile(); LOG.assertTrue(file != null); if (fileIndex.isInContent(file)) { files.add(file); } } if (!files.isEmpty()) { return new AnalysisScope(myProject, files); } return null; }