@SuppressWarnings("StringConcatenationInsideStringBufferAppend") @NotNull private static String makeDescription( @NotNull Collection<VcsRootError> unregisteredRoots, @NotNull Collection<VcsRootError> invalidRoots) { Function<VcsRootError, String> rootToDisplayableString = rootError -> { if (rootError.getMapping().equals(VcsDirectoryMapping.PROJECT_CONSTANT)) { return StringUtil.escapeXml(rootError.getMapping()); } return FileUtil.toSystemDependentName(rootError.getMapping()); }; StringBuilder description = new StringBuilder(); if (!invalidRoots.isEmpty()) { if (invalidRoots.size() == 1) { VcsRootError rootError = invalidRoots.iterator().next(); String vcsName = rootError.getVcsKey().getName(); description.append( String.format( "The directory %s is registered as a %s root, but no %s repositories were found there.", rootToDisplayableString.fun(rootError), vcsName, vcsName)); } else { description.append( "The following directories are registered as VCS roots, but they are not: <br/>" + StringUtil.join(invalidRoots, rootToDisplayableString, "<br/>")); } description.append("<br/>"); } if (!unregisteredRoots.isEmpty()) { if (unregisteredRoots.size() == 1) { VcsRootError unregisteredRoot = unregisteredRoots.iterator().next(); description.append( String.format( "The directory %s is under %s, but is not registered in the Settings.", rootToDisplayableString.fun(unregisteredRoot), unregisteredRoot.getVcsKey().getName())); } else { description.append( "The following directories are roots of VCS repositories, but they are not registered in the Settings: <br/>" + StringUtil.join(unregisteredRoots, rootToDisplayableString, "<br/>")); } description.append("<br/>"); } String add = invalidRoots.isEmpty() ? "<a href='add'>Add " + pluralize("root", unregisteredRoots.size()) + "</a> " : ""; String configure = "<a href='configure'>Configure</a>"; String ignore = invalidRoots.isEmpty() ? " <a href='ignore'>Ignore</a>" : ""; description.append(add + configure + ignore); return description.toString(); }
@Override protected TableCellEditor createCellEditor(DomElement element, Class type) { if (Enum.class.isAssignableFrom(type)) { return new ComboTableCellEditor((Class<? extends Enum>) type, false); } final Function<DomElement, TableCellEditor> function = myCustomCellEditorCreators.get(type); assert function != null : "Type not supported: " + type; return function.fun(element); }
@Override protected void notifyByBalloon( JUnitRunningModel model, boolean started, final JUnitConsoleProperties consoleProperties) { if (myFoundTests) { super.notifyByBalloon(model, started, consoleProperties); } else { final String packageName = myConfiguration.getPackage(); if (packageName == null) return; final Project project = myConfiguration.getProject(); final PsiPackage aPackage = JavaPsiFacade.getInstance(project).findPackage(packageName); if (aPackage == null) return; final Module module = myConfiguration.getConfigurationModule().getModule(); if (module == null) return; final Set<Module> modulesWithPackage = new HashSet<Module>(); final PsiDirectory[] directories = aPackage.getDirectories(); for (PsiDirectory directory : directories) { final Module currentModule = ModuleUtil.findModuleForFile(directory.getVirtualFile(), project); if (module != currentModule && currentModule != null) { modulesWithPackage.add(currentModule); } } if (!modulesWithPackage.isEmpty()) { final String testRunDebugId = consoleProperties.isDebug() ? ToolWindowId.DEBUG : ToolWindowId.RUN; final ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project); final Function<Module, String> moduleNameRef = new Function<Module, String>() { @Override public String fun(Module module) { final String moduleName = module.getName(); return "<a href=\"" + moduleName + "\">" + moduleName + "</a>"; } }; String message = "Tests were not found in module \"" + module.getName() + "\".\n" + "Use "; if (modulesWithPackage.size() == 1) { message += "module \"" + moduleNameRef.fun(modulesWithPackage.iterator().next()) + "\" "; } else { message += "one of\n" + StringUtil.join(modulesWithPackage, moduleNameRef, "\n") + "\n"; } message += "instead"; toolWindowManager.notifyByBalloon( testRunDebugId, MessageType.WARNING, message, null, new ResetConfigurationModuleAdapter( project, consoleProperties, toolWindowManager, testRunDebugId)); } } }
@NotNull @Override public Pair<R2, State> parse(@NotNull List<Token<T>> tokens, @NotNull State state) throws ParserException { final Pair<R, State> result = myParser.parse(tokens, state); return Pair.create(myFunction.fun(result.getFirst()), result.getSecond()); }
@Override protected void previewRefactoring(@NotNull final UsageInfo[] usages) { MigrationPanel panel = new MigrationPanel(myRoot, myLabeler, myProject, isPreviewUsages()); String name; if (myRoot.length == 1) { String fromType = assertNotNull(TypeMigrationLabeler.getElementType(myRoot[0])).getPresentableText(); String toType = myRootTypes.fun(myRoot[0]).getPresentableText(); String text; text = getPresentation(myRoot[0]); name = "Migrate Type of " + text + " from \'" + fromType + "\' to \'" + toType + "\'"; } else { final int rootsInPresentationCount = myRoot.length > MAX_ROOT_IN_PREVIEW_PRESENTATION ? MAX_ROOT_IN_PREVIEW_PRESENTATION : myRoot.length; String[] rootsPresentation = new String[rootsInPresentationCount]; for (int i = 0; i < rootsInPresentationCount; i++) { final PsiElement root = myRoot[i]; rootsPresentation[i] = root instanceof PsiNamedElement ? ((PsiNamedElement) root).getName() : root.getText(); } rootsPresentation = StringUtil.surround(rootsPresentation, "\'", "\'"); name = "Migrate Type of " + StringUtil.join(rootsPresentation, ", "); if (myRoot.length > MAX_ROOT_IN_PREVIEW_PRESENTATION) { name += "..."; } } Content content = UsageViewManager.getInstance(myProject).addContent(name, false, panel, true, true); panel.setContent(content); ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.FIND).activate(null); }
private static boolean checkDependants( final IdeaPluginDescriptor pluginDescriptor, final Function<PluginId, IdeaPluginDescriptor> pluginId2Descriptor, final Condition<PluginId> check, final Set<PluginId> processed) { processed.add(pluginDescriptor.getPluginId()); final PluginId[] dependentPluginIds = pluginDescriptor.getDependentPluginIds(); final Set<PluginId> optionalDependencies = new HashSet<PluginId>(Arrays.asList(pluginDescriptor.getOptionalDependentPluginIds())); for (final PluginId dependentPluginId : dependentPluginIds) { if (processed.contains(dependentPluginId)) continue; // TODO[yole] should this condition be a parameter? if (isModuleDependency(dependentPluginId) && (ourAvailableModules.isEmpty() || ourAvailableModules.contains(dependentPluginId.getIdString()))) { continue; } if (!optionalDependencies.contains(dependentPluginId)) { if (!check.value(dependentPluginId)) { return false; } final IdeaPluginDescriptor dependantPluginDescriptor = pluginId2Descriptor.fun(dependentPluginId); if (dependantPluginDescriptor != null && !checkDependants(dependantPluginDescriptor, pluginId2Descriptor, check, processed)) { return false; } } } return true; }
/** @return read-only set consisting of the elements from collection converted by mapper */ @NotNull public static <T, V> Set<V> map2Set( @NotNull Collection<? extends T> collection, @NotNull Function<T, V> mapper) { if (collection.isEmpty()) return Collections.emptySet(); Set<V> set = new HashSet<V>(collection.size()); for (final T t : collection) { set.add(mapper.fun(t)); } return set; }
/** @return read-only list consisting of the elements from collection converted by mapper */ @NotNull public static <T, V> List<V> map2List( @NotNull Collection<? extends T> collection, @NotNull Function<T, V> mapper) { if (collection.isEmpty()) return emptyList(); List<V> list = new ArrayList<V>(collection.size()); for (final T t : collection) { list.add(mapper.fun(t)); } return list; }
public static void outputCompilerMessagesAndHandleExitCode( @NotNull MessageCollector messageCollector, @NotNull OutputItemsCollector outputItemsCollector, @NotNull Function<PrintStream, Integer> compilerRun) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PrintStream out = new PrintStream(outputStream); int exitCode = compilerRun.fun(out); BufferedReader reader = new BufferedReader(new StringReader(outputStream.toString())); CompilerOutputParser.parseCompilerMessagesFromReader( messageCollector, reader, outputItemsCollector); handleProcessTermination(exitCode, messageCollector); }
@Nullable public static <T> T processInputStream( @NotNull final VirtualFile file, @NotNull Function<InputStream, T> function) { InputStream stream = null; try { stream = file.getInputStream(); return function.fun(stream); } catch (IOException e) { LOG.error(e); } finally { try { if (stream != null) { stream.close(); } } catch (IOException e) { LOG.error(e); } } return null; }
private static <T> boolean processProject( MavenDomProjectModel projectDom, MavenProject mavenProjectOrNull, Processor<T> processor, Project project, Function<? super MavenDomProfile, T> domProfileFunction, Function<? super MavenDomProjectModel, T> projectDomFunction) { if (processProfilesXml( MavenDomUtil.getVirtualFile(projectDom), mavenProjectOrNull, processor, project, domProfileFunction)) { return true; } if (processProfiles( projectDom.getProfiles(), mavenProjectOrNull, processor, domProfileFunction)) return true; T t = projectDomFunction.fun(projectDom); return t == null ? false : processor.process(t); }
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); } } }
private static File getOldPath( final File oldInstallHome, final ConfigImportSettings settings, final String propertyName, final Function<String, String> fromPathSelector) { final File[] launchFileCandidates = getLaunchFilesCandidates(oldInstallHome, settings); // custom config folder for (File candidate : launchFileCandidates) { if (candidate.exists()) { String configDir = PathManager.substituteVars( getPropertyFromLaxFile(candidate, propertyName), oldInstallHome.getPath()); if (configDir != null) { File probableConfig = new File(configDir); if (probableConfig.exists()) return probableConfig; } } } // custom config folder not found - use paths selector for (File candidate : launchFileCandidates) { if (candidate.exists()) { final String pathsSelector = getPropertyFromLaxFile(candidate, PathManager.PROPERTY_PATHS_SELECTOR); if (pathsSelector != null) { final String configDir = fromPathSelector.fun(pathsSelector); final File probableConfig = new File(configDir); if (probableConfig.exists()) { return probableConfig; } } } } return null; }
protected <T> void addClassesListToJavaParameters( Collection<? extends T> elements, Function<T, String> nameFunction, String packageName, boolean createTempFile, boolean junit4) { try { if (createTempFile) { myTempFile = FileUtil.createTempFile("idea_junit", ".tmp"); myTempFile.deleteOnExit(); myJavaParameters.getProgramParametersList().add("@" + myTempFile.getAbsolutePath()); } final PrintWriter writer = new PrintWriter(myTempFile, "UTF-8"); try { writer.println(packageName); final List<String> testNames = new ArrayList<String>(); for (final T element : elements) { final String name = nameFunction.fun(element); if (name == null) { LOG.error("invalid element " + element); return; } testNames.add(name); } Collections.sort(testNames); // sort tests in FQN order for (String testName : testNames) { writer.println(testName); } } finally { writer.close(); } } catch (IOException e) { LOG.error(e); } }
@Nullable public <T extends PsiExpression> PsiType getType( @NotNull T expr, @NotNull Function<T, PsiType> f) { PsiType type = getCachedType(expr); if (type == null) { final RecursionGuard.StackStamp dStackStamp = PsiDiamondType.ourDiamondGuard.markStack(); final RecursionGuard.StackStamp gStackStamp = PsiResolveHelper.ourGraphGuard.markStack(); type = f.fun(expr); if (!dStackStamp.mayCacheNow() || !gStackStamp.mayCacheNow()) { return type; } if (type == null) type = TypeConversionUtil.NULL_TYPE; Reference<PsiType> ref = new SoftReference<PsiType>(type); myCalculatedTypes.put(expr, ref); if (type instanceof PsiClassReferenceType) { // convert reference-based class type to the PsiImmediateClassType, since the reference may // become invalid PsiClassType.ClassResolveResult result = ((PsiClassReferenceType) type).resolveGenerics(); PsiClass psiClass = result.getElement(); type = psiClass == null ? type // for type with unresolved reference, leave it in the cache // for clients still might be able to retrieve its getCanonicalText() from the // reference text : new PsiImmediateClassType( psiClass, result.getSubstitutor(), ((PsiClassReferenceType) type).getLanguageLevel(), type.getAnnotations()); } } if (!type.isValid()) { if (expr.isValid()) { PsiJavaCodeReferenceElement refInside = type instanceof PsiClassReferenceType ? ((PsiClassReferenceType) type).getReference() : null; @NonNls String typeinfo = type + " (" + type.getClass() + ")" + (refInside == null ? "" : "; ref inside: " + refInside + " (" + refInside.getClass() + ") valid:" + refInside.isValid()); LOG.error( "Type is invalid: " + typeinfo + "; expr: '" + expr + "' (" + expr.getClass() + ") is valid"); } else { LOG.error("Expression: '" + expr + "' is invalid, must not be used for getType()"); } } return type == TypeConversionUtil.NULL_TYPE ? null : type; }
public static StringBuffer addDiagnosticMarkersToText( @NotNull final PsiFile psiFile, @NotNull Collection<Diagnostic> diagnostics, @NotNull Map<Diagnostic, TextDiagnostic> diagnosticToExpectedDiagnostic, @NotNull Function<PsiFile, String> getFileText) { String text = getFileText.fun(psiFile); StringBuffer result = new StringBuffer(); diagnostics = Collections2.filter( diagnostics, new Predicate<Diagnostic>() { @Override public boolean apply(Diagnostic diagnostic) { return psiFile.equals(diagnostic.getPsiFile()); } }); if (!diagnostics.isEmpty()) { List<DiagnosticDescriptor> diagnosticDescriptors = getSortedDiagnosticDescriptors(diagnostics); Stack<DiagnosticDescriptor> opened = new Stack<DiagnosticDescriptor>(); ListIterator<DiagnosticDescriptor> iterator = diagnosticDescriptors.listIterator(); DiagnosticDescriptor currentDescriptor = iterator.next(); for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); while (!opened.isEmpty() && i == opened.peek().end) { closeDiagnosticString(result); opened.pop(); } while (currentDescriptor != null && i == currentDescriptor.start) { openDiagnosticsString(result, currentDescriptor, diagnosticToExpectedDiagnostic); if (currentDescriptor.getEnd() == i) { closeDiagnosticString(result); } else { opened.push(currentDescriptor); } if (iterator.hasNext()) { currentDescriptor = iterator.next(); } else { currentDescriptor = null; } } result.append(c); } if (currentDescriptor != null) { assert currentDescriptor.start == text.length(); assert currentDescriptor.end == text.length(); openDiagnosticsString(result, currentDescriptor, diagnosticToExpectedDiagnostic); opened.push(currentDescriptor); } while (!opened.isEmpty() && text.length() == opened.peek().end) { closeDiagnosticString(result); opened.pop(); } assert opened.isEmpty() : "Stack is not empty: " + opened; } else { result.append(text); } return result; }
@CalledInAwt @NotNull public static ProgressIndicator executeAndTryWait( @NotNull final Function<ProgressIndicator, Runnable> backgroundTask, @Nullable final Runnable onSlowAction, final int waitMillis, final boolean forceEDT) { final ModalityState modality = ModalityState.current(); final ProgressIndicator indicator = new EmptyProgressIndicator() { @NotNull @Override public ModalityState getModalityState() { return modality; } }; final Semaphore semaphore = new Semaphore(0); final AtomicReference<Runnable> resultRef = new AtomicReference<Runnable>(); if (forceEDT) { try { Runnable callback = backgroundTask.fun(indicator); finish(callback, indicator); } catch (ProcessCanceledException ignore) { } catch (Throwable t) { LOG.error(t); } } else { ApplicationManager.getApplication() .executeOnPooledThread( new Runnable() { @Override public void run() { ProgressManager.getInstance() .executeProcessUnderProgress( new Runnable() { @Override public void run() { final Runnable callback = backgroundTask.fun(indicator); if (indicator.isCanceled()) { semaphore.release(); return; } if (!resultRef.compareAndSet(null, callback)) { ApplicationManager.getApplication() .invokeLater( new Runnable() { @Override public void run() { finish(callback, indicator); } }, modality); } semaphore.release(); } }, indicator); } }); try { semaphore.tryAcquire(waitMillis, TimeUnit.MILLISECONDS); } catch (InterruptedException ignore) { } if (!resultRef.compareAndSet(null, TOO_SLOW_OPERATION)) { // update presentation in the same thread to reduce blinking, caused by 'invokeLater' and // fast background operation finish(resultRef.get(), indicator); } else { if (onSlowAction != null) onSlowAction.run(); } } return indicator; }
public MacMainFrameDecorator(@NotNull final IdeFrameImpl frame, final boolean navBar) { myFrame = frame; final ID window = MacUtil.findWindowForTitle(frame.getTitle()); if (window == null) return; if (CURRENT_SETTER == null) { CURRENT_SETTER = navBar ? NAVBAR_SETTER : TOOLBAR_SETTER; CURRENT_GETTER = navBar ? NAVBAR_GETTER : TOOLBAR_GETTER; SHOWN = CURRENT_GETTER.fun(null); } UISettings.getInstance().addUISettingsListener(this, this); final ID pool = invoke("NSAutoreleasePool", "new"); int v = UNIQUE_COUNTER.incrementAndGet(); if (Patches.APPLE_BUG_ID_10514018) { frame.addWindowListener( new WindowAdapter() { @Override public void windowDeiconified(WindowEvent e) { if (e.getWindow() == frame && frame.getState() == Frame.ICONIFIED) { frame.setState(Frame.NORMAL); } } }); } try { if (SystemInfo.isMacOSLion) { if (!FULL_SCREEN_AVAILABLE) return; FullScreenUtilities.addFullScreenListenerTo( frame, new FullScreenAdapter() { @Override public void windowEnteredFullScreen(AppEvent.FullScreenEvent event) { myInFullScreen = true; JRootPane rootPane = frame.getRootPane(); if (rootPane != null) rootPane.putClientProperty(FULL_SCREEN, Boolean.TRUE); if (Patches.APPLE_BUG_ID_10207064) { // fix problem with bottom empty bar // it seems like the title is still visible in fullscreen but the window itself // shifted up for titlebar height // and the size of the frame is still calculated to be the height of the screen // which is wrong // so just add these titlebar height to the frame height once again Timer timer = new Timer( 300, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater( new Runnable() { @Override public void run() { frame.setSize( frame.getWidth(), frame.getHeight() + frame.getInsets().top); } }); } }); timer.setRepeats(false); timer.start(); } } @Override public void windowExitedFullScreen(AppEvent.FullScreenEvent event) { myInFullScreen = false; frame.storeFullScreenStateIfNeeded(false); JRootPane rootPane = frame.getRootPane(); if (rootPane != null) rootPane.putClientProperty(FULL_SCREEN, null); } }); } else { // toggle toolbar String className = "IdeaToolbar" + v; final ID ownToolbar = Foundation.allocateObjcClassPair(Foundation.getObjcClass("NSToolbar"), className); Foundation.registerObjcClassPair(ownToolbar); ID toolbar = invoke( invoke(className, "alloc"), "initWithIdentifier:", Foundation.nsString(className)); Foundation.cfRetain(toolbar); invoke(toolbar, "setVisible:", 0); // hide native toolbar by default Foundation.addMethod( ownToolbar, Foundation.createSelector("setVisible:"), SET_VISIBLE_CALLBACK, "v*"); Foundation.addMethod(ownToolbar, Foundation.createSelector("isVisible"), IS_VISIBLE, "B*"); invoke(window, "setToolbar:", toolbar); invoke(window, "setShowsToolbarButton:", 1); } } finally { invoke(pool, "release"); } }
@Override public void uiSettingsChanged(final UISettings source) { if (CURRENT_GETTER != null) { SHOWN = CURRENT_GETTER.fun(null); } }
public String valueOf(final PostfixTemplate template) { return myValueOfFunction.fun(template); }
private String escapeString(String line, Function<String, String> escapeFunction) { line = XmlStringUtil.escapeString(line); return escapeFunction == null ? line : escapeFunction.fun(line); }
private void assertConsistency( @NotNull VirtualFileSystemEntry[] array, boolean ignoreCase, @NotNull Object... details) { if (!CHECK) return; boolean allChildrenLoaded = allChildrenLoaded(); for (int i = 0; i < array.length; i++) { VirtualFileSystemEntry file = array[i]; boolean isAdopted = isAdoptedChild(file); assert !isAdopted || !allChildrenLoaded; if (isAdopted && i != array.length - 1) { assert isAdoptedChild(array[i + 1]); } if (i != 0) { VirtualFileSystemEntry prev = array[i - 1]; String prevName = prev.getName(); int cmp = file.compareNameTo(prevName, ignoreCase); if (cmp == 0) { Function<VirtualFileSystemEntry, String> verboseToString = new Function<VirtualFileSystemEntry, String>() { @Override public String fun(VirtualFileSystemEntry entry) { return entry + " (name: '" + entry.getName() + "', " + entry.getClass() + ", parent:" + entry.getParent() + "; id:" + entry.getId() + "; FS:" + entry.getFileSystem() + "; delegate.attrs:" + entry.getFileSystem().getAttributes(entry) + "; caseSensitive:" + entry.getFileSystem().isCaseSensitive() + "; canonical:" + entry.getFileSystem().getCanonicallyCasedName(entry) + ") "; } }; String children = StringUtil.join(array, verboseToString, ","); throw new AssertionError( verboseToString.fun(prev) + " equals to " + verboseToString.fun(file) + "; children: " + children + "\nDetails: " + ContainerUtil.map( details, new Function<Object, Object>() { @Override public Object fun(Object o) { return o instanceof Object[] ? Arrays.toString((Object[]) o) : o; } })); } if (isAdopted == isAdoptedChild(prev)) { assert cmp > 0 : "Not sorted. " + Arrays.toString(details); } } } }
private static <T> boolean processProfile( MavenDomProfile profileDom, Processor<T> processor, Function<? super MavenDomProfile, T> f) { T t = f.fun(profileDom); return t != null && processor.process(t); }