Unnamed: 0
int64
0
305k
body
stringlengths
7
52.9k
name
stringlengths
1
185
7,700
Promise<Object> (@NotNull PlaybackContext context) { AsyncPromise<Object> promise = new AsyncPromise<>(); AppExecutorUtil.getAppExecutorService().execute(() -> { try { computePromise(context.getProject()); promise.setResult("completed"); } catch (Throwable t) { promise.setError(t); } }); return promise; }
_execute
7,701
URL[] () { return myClasspath.stream().map(f -> { try { URL fileURL = f.toURI().toURL(); if (!fileURL.getProtocol().equals("file")) { throw new RuntimeException("Remote resources are not allowed in the classpath: " + fileURL); } return fileURL; } catch (MalformedURLException e) { throw new RuntimeException("Failed to get URL for " + f + ". " + e.getMessage(), e); } }).toArray(sz -> new URL[sz]); }
convertClasspathToURLs
7,702
CompletionType () { String completionTypeArg = getArgument(0); switch (completionTypeArg) { case "SMART" -> { LOG.info(String.format("'%s' was passed as argument, so SMART completion will be used", completionTypeArg)); return CompletionType.SMART; } //case "BASIC", default -> { LOG.info(String.format("'%s' was passed as argument, so BASIC completion will be used", completionTypeArg)); return CompletionType.BASIC; } } }
getCompletionType
7,703
String (int index) { String[] completionArgs = extractCommandArgument(PREFIX).trim().toUpperCase().split(" "); if(completionArgs.length > index) { return completionArgs[index]; } else { return ""; } }
getArgument
7,704
String () { return NAME; }
getName
7,705
Editor (PlaybackContext context) { return FileEditorManager.getInstance(context.getProject()).getSelectedTextEditor(); }
getEditor
7,706
Promise<Object> (final @NotNull PlaybackContext context) { final ActionCallback actionCallback = new ActionCallbackProfilerStopper(); Disposable listenerDisposable = Disposer.newDisposable(); Ref<Span> span = new Ref<>(); Ref<Scope> scope = new Ref<>(); Ref<Long> completionTimeStarted = new Ref<>(); AtomicBoolean lookupListenerInited = new AtomicBoolean(false); ApplicationManager.getApplication().getMessageBus().connect(listenerDisposable) .subscribe(CompletionPhaseListener.TOPIC, new CompletionPhaseListener() { @Override public void completionPhaseChanged(boolean isCompletionRunning) { Editor editor = getEditor(context); LookupEx lookup = LookupManager.getActiveLookup(editor); if (lookup != null && !lookupListenerInited.get()) { lookup.addLookupListener(new LookupListener() { @Override public void firstElementShown() { span.get().setAttribute("firstElementShown", System.currentTimeMillis() - completionTimeStarted.get()); } }); lookupListenerInited.set(true); } if (!isCompletionRunning && !CompletionServiceImpl.isPhase(CompletionPhase.CommittingDocuments.class) && !span.isNull()) { if (CompletionServiceImpl.getCurrentCompletionProgressIndicator() == null) { String description = "CompletionServiceImpl.getCurrentCompletionProgressIndicator() is null on " + CompletionServiceImpl.getCompletionPhase(); span.get().setStatus(StatusCode.ERROR, description); actionCallback.reject(description); } else { List<LookupElement> items = CompletionServiceImpl.getCurrentCompletionProgressIndicator().getLookup().getItems(); int size = items.size(); span.get().setAttribute("number", size); span.get().end(); scope.get().close(); context.message("Number of elements: " + size, getLine()); Path dir = getCompletionItemsDir(); if (dir != null) { dumpCompletionVariants(items, dir); } actionCallback.setDone(); } Disposer.dispose(listenerDisposable); } } }); ApplicationManager.getApplication().invokeLater(Context.current().wrap(() -> { Project project = context.getProject(); Editor editor = getEditor(context); span.set(startSpan(SPAN_NAME)); scope.set(span.get().makeCurrent()); completionTimeStarted.set(System.currentTimeMillis()); new CodeCompletionHandlerBase(getCompletionType(), true, false, true).invokeCompletion(project, editor); })); return Promises.toPromise(actionCallback); }
_execute
7,707
void (boolean isCompletionRunning) { Editor editor = getEditor(context); LookupEx lookup = LookupManager.getActiveLookup(editor); if (lookup != null && !lookupListenerInited.get()) { lookup.addLookupListener(new LookupListener() { @Override public void firstElementShown() { span.get().setAttribute("firstElementShown", System.currentTimeMillis() - completionTimeStarted.get()); } }); lookupListenerInited.set(true); } if (!isCompletionRunning && !CompletionServiceImpl.isPhase(CompletionPhase.CommittingDocuments.class) && !span.isNull()) { if (CompletionServiceImpl.getCurrentCompletionProgressIndicator() == null) { String description = "CompletionServiceImpl.getCurrentCompletionProgressIndicator() is null on " + CompletionServiceImpl.getCompletionPhase(); span.get().setStatus(StatusCode.ERROR, description); actionCallback.reject(description); } else { List<LookupElement> items = CompletionServiceImpl.getCurrentCompletionProgressIndicator().getLookup().getItems(); int size = items.size(); span.get().setAttribute("number", size); span.get().end(); scope.get().close(); context.message("Number of elements: " + size, getLine()); Path dir = getCompletionItemsDir(); if (dir != null) { dumpCompletionVariants(items, dir); } actionCallback.setDone(); } Disposer.dispose(listenerDisposable); } }
completionPhaseChanged
7,708
void () { span.get().setAttribute("firstElementShown", System.currentTimeMillis() - completionTimeStarted.get()); }
firstElementShown
7,709
Path () { String property = System.getProperty(DUMP_COMPLETION_ITEMS_DIR); if (property != null) { return Paths.get(property); } return null; }
getCompletionItemsDir
7,710
void (List<LookupElement> item, @NotNull Path reportPath) { File dir = reportPath.toFile(); dir.mkdirs(); File file = new File(dir, createTestReportFilename()); CompletionItemsReport report = new CompletionItemsReport(ContainerUtil.map(item, CompletionVariant::fromLookUp)); DataDumper.dump(report, file.toPath()); }
dumpCompletionVariants
7,711
String () { return "completion-" + getCompletionType() + "-" + System.currentTimeMillis() + (isWarmupMode() ? "_warmup" : "") + ".txt"; }
createTestReportFilename
7,712
String () { return name; }
getName
7,713
CompletionVariant (LookupElement element) { return new CompletionVariant(element.getLookupString()); }
fromLookUp
7,714
String (@NotNull Iterator<String> args, @NotNull String text) { if (!args.hasNext()) throw new RuntimeException("Too few arguments in " + text); return args.next(); }
nextArg
7,715
void (@NotNull Consumer<String> logMessage, @NotNull Project project) { logMessage.accept("Settings up SDK: name: " + mySdkName + ", type: " + mySdkType + ", home: " + mySdkHome); Sdk sdk = setupOrDetectSdk(logMessage); ProjectRootManager rootManager = ProjectRootManager.getInstance(project); Sdk projectSdk = rootManager.getProjectSdk(); if (!Objects.equals(projectSdk, sdk)) { logMessage.accept("Project uses different SDK: " + projectSdk + " " + "(sdkName is " + rootManager.getProjectSdkName() + ", " + "type " + rootManager.getProjectSdkTypeName() + "). Updating..."); rootManager.setProjectSdk(sdk); } logMessage.accept("Project SDK is set to use the new SDK"); for (Module module : ModuleManager.getInstance(project).getModules()) { Sdk moduleSdk = ModuleRootManager.getInstance(module).getSdk(); if (!Objects.equals(moduleSdk, sdk)) { logMessage.accept("Module " + module.getName() + " uses different SDK: " + moduleSdk + " IGNORING!"); } } }
runUnderPromiseInEDT
7,716
Sdk (@NotNull Consumer<String> logMessage) { Sdk oldSdk = ProjectJdkTable.getInstance().findJdk(mySdkName); if (oldSdk != null) { if (Objects.equals(oldSdk.getSdkType().getName(), mySdkName) && FileUtil.pathsEqual(oldSdk.getHomePath(), mySdkHome)) { logMessage.accept("Existing SDK is already configured the expected way"); return oldSdk; } logMessage.accept("Existing different SDK will be removed: " + oldSdk); ProjectJdkTable.getInstance().removeJdk(oldSdk); } SdkType sdkType = SdkType.findByName(mySdkType); if (sdkType == null) { throw new IllegalArgumentException("Failed to find SdkType: " + mySdkType); } boolean isValidSdkHome; try { isValidSdkHome = sdkType.isValidSdkHome(mySdkHome); } catch (Throwable t) { throw new IllegalArgumentException("Sdk home " + mySdkHome + " for " + sdkType + " is not valid. " + t.getMessage(), t); } if (!isValidSdkHome) { throw new IllegalArgumentException("Sdk home " + mySdkHome + " for " + sdkType + " is not valid"); } Sdk newSdk = ProjectJdkTable.getInstance().createSdk(mySdkName, sdkType); SdkModificator mod = newSdk.getSdkModificator(); try { mod.setVersionString(sdkType.getVersionString(mySdkHome)); mod.setHomePath(mySdkHome); } catch (Throwable t) { throw new IllegalArgumentException( "Failed to configure Sdk instance home for " + mySdkHome + " for " + sdkType + " is not valid. " + t.getMessage(), t); } finally { mod.commitChanges(); } try { sdkType.setupSdkPaths(newSdk); } catch (Throwable t) { throw new IllegalArgumentException( "Failed to setup Sdk home for " + mySdkHome + " for " + sdkType + " is not valid. " + t.getMessage(), t); } registerNewSdk(newSdk); logMessage.accept("Registered new SDK to ProjectJdkTable: " + newSdk); return newSdk; }
setupOrDetectSdk
7,717
void (@NotNull Sdk newSdk) { ProjectJdkTable.getInstance().addJdk(newSdk); }
registerNewSdk
7,718
Promise<Object> (@NotNull PlaybackContext context) { AsyncPromise<Object> promise = new AsyncPromise<>(); ApplicationManager.getApplication().invokeLater(() -> { Promises.compute(promise, () -> { computePromise(s -> context.message(s, getLine()), context.getProject()); return null; }); }); return promise; }
_execute
7,719
void (@NotNull Consumer<String> logMessage, @NotNull Project project) { WriteAction.run(() -> { runUnderPromiseInEDT(logMessage, project); }); }
computePromise
7,720
void (@NotNull ActionCallback callback, @NotNull PlaybackContext context) { ActionManager actionManager = ActionManager.getInstance(); Component focusedComponent = IdeFocusManager.findInstance().getFocusOwner(); // real focused component (editor/project view/..) DataContext dataContext = DataManager.getInstance().getDataContext(focusedComponent); ActionGroup mainMenu = (ActionGroup)actionManager.getAction(getGroupId()); TraceUtil.runWithSpanThrows(PerformanceTestSpan.TRACER, getSpanName(), totalSpan -> { JBTreeTraverser.<AnAction>from(action -> { totalSpan.addEvent(action.getClass().getSimpleName()); if (!(action instanceof ActionGroup group)) return JBIterable.empty(); String groupSpanName = ObjectUtils.coalesce(actionManager.getId(group), group.getTemplateText(), group.getClass().getName()); Span groupSpan = PerformanceTestSpan.TRACER.spanBuilder(groupSpanName).startSpan(); List<AnAction> actions = Utils.expandActionGroup(group, new PresentationFactory(), dataContext, getPlace()); groupSpan.end(); return actions; }).withRoots(mainMenu.getChildren(null)).traverse().size(); }); callback.setDone(); }
execute
7,721
String () { return PREFIX; }
getSpanName
7,722
String () { return IdeActions.GROUP_PROJECT_VIEW_POPUP; }
getGroupId
7,723
String () { return ActionPlaces.PROJECT_VIEW_POPUP; }
getPlace
7,724
void (@NotNull ActionCallback callback, @NotNull PlaybackContext context) { String filePath = getText().split(" ", 2)[1]; VirtualFile file = findFile(filePath, context.getProject()); ProjectView.getInstance(context.getProject()).select(null, file, true); callback.setDone(); }
execute
7,725
void (List<Usage> allUsages, @NotNull Project project) { List<FoundUsage> foundUsages = ContainerUtil.map(allUsages, usage -> convertToFoundUsage(project, usage)); Path jsonPath = getFoundUsagesJsonPath(); if (jsonPath != null) { dumpFoundUsagesToFile(foundUsages, jsonPath); } }
storeMetricsDumpFoundUsages
7,726
void (@NotNull List<FoundUsage> foundUsages, @NotNull Path jsonPath) { LOG.info("Found usages will be dumped to " + jsonPath); Collections.sort(foundUsages); FoundUsagesReport foundUsagesReport = new FoundUsagesReport(foundUsages.size(), foundUsages); DataDumper.dump(foundUsagesReport, jsonPath); }
dumpFoundUsagesToFile
7,727
FoundUsage (@NotNull Project project, @NotNull Usage usage) { PortableFilePath portableFilePath = null; Integer line = null; if (usage instanceof UsageInfo2UsageAdapter adapter) { VirtualFile file = ReadAction.compute(() -> adapter.getFile()); if (file != null) { portableFilePath = PortableFilePaths.INSTANCE.getPortableFilePath(file, project); } line = adapter.getLine() + 1; } String text = ReadAction.compute(() -> usage.getPresentation().getPlainText()); return new FoundUsage(text, portableFilePath, line); }
convertToFoundUsage
7,728
Path () { String property = System.getProperty(DUMP_FOUND_USAGES_DESTINATION_FILE); if (property != null) { return Paths.get(property); } return null; }
getFoundUsagesJsonPath
7,729
int (@NotNull FindUsagesDumper.FoundUsage other) { return COMPARATOR.compare(this, other); }
compareTo
7,730
boolean (Object o) { if (this == o) return true; if (!(o instanceof FoundUsage usage)) return false; return text.equals(usage.text) && Objects.equals(portableFilePath, usage.portableFilePath) && Objects.equals(line, usage.line); }
equals
7,731
int () { return Objects.hash(text, portableFilePath, line); }
hashCode
7,732
String () { StringBuilder builder = new StringBuilder(); if (portableFilePath != null) { builder.append("In file '").append(portableFilePath.getPresentablePath()).append("' "); } if (line != null) { builder.append("(at line #").append(line).append(") "); } if (!builder.isEmpty()) { builder.append("\n"); } builder.append(text); return builder.toString(); }
toString
7,733
String () { return PREFIX; }
getSpanName
7,734
String () { return IdeActions.GROUP_EDITOR_POPUP; }
getGroupId
7,735
String () { return ActionPlaces.EDITOR_POPUP; }
getPlace
7,736
Promise<Object> (@NotNull final PlaybackContext context) { final ActionCallback actionCallback = new ActionCallbackProfilerStopper(); if (StringUtil.isNotEmpty(myOptions.downloadFileUrl)) { if (StringUtil.isEmpty(myOptions.toolShortName)) { LOGGER.error("myOptions.toolShortName cannot be null if you want to download file for test"); } else { downloadTestRequiredFile(myOptions.toolShortName, myOptions.downloadFileUrl); } } @NotNull Project project = context.getProject(); InspectionManagerEx inspectionManagerEx = (InspectionManagerEx)InspectionManager.getInstance(project); final InspectionProfileManager profileManager = InspectionProfileManager.getInstance(project); InspectionProfileImpl profile = profileManager.getCurrentProfile(); if (StringUtil.isNotEmpty(myOptions.toolShortName)) { profile.disableAllTools(project); profile.enableTool(myOptions.toolShortName, project); } List<Tools> enabledInspectionTools = profile.getAllEnabledInspectionTools(project); if (!ArrayUtil.isEmpty(myOptions.inspectionTrueFields)) { setInspectionFields(enabledInspectionTools, myOptions.inspectionTrueFields, true); } if (!ArrayUtil.isEmpty(myOptions.inspectionFalseFields)) { setInspectionFields(enabledInspectionTools, myOptions.inspectionFalseFields, false); } NamedScope namedScope = NamedScopesHolder.getScope(project, myOptions.scopeName); AnalysisScope analysisScope = null; if (namedScope != null) { analysisScope = new AnalysisScope(GlobalSearchScopesCore.filterScope(project, namedScope), project); } else { if (StringUtil.isNotEmpty(myOptions.directory)) { VirtualFile directory = VfsUtil.findRelativeFile(ProjectUtil.guessProjectDir(project), myOptions.directory); if (directory != null) { PsiDirectory psiDirectory = ReadAction.compute(() -> PsiManager.getInstance(project).findDirectory(directory)); if (psiDirectory != null) { analysisScope = new AnalysisScope(psiDirectory); } } } } if (analysisScope == null) { analysisScope = new AnalysisScope(project); } @SuppressWarnings("TestOnlyProblems") GlobalInspectionContextImpl inspectionContext = new GlobalInspectionContextImpl(project, inspectionManagerEx.getContentManager()) { @Override public void addView(@NotNull InspectionResultsView view, @NotNull String title, boolean isOffline) { super.addView(view, title, isOffline); ToolWindow resultWindow = ProblemsView.getToolWindow(project); if (resultWindow != null && myOptions.hideResults) { resultWindow.hide(); } } @Override protected void notifyInspectionsFinished(@NotNull AnalysisScope scope) { super.notifyInspectionsFinished(scope); context.message(PerformanceTestingBundle.message("command.inspection.finish"), getLine()); if (enabledInspectionTools.size() == 1 && !myOptions.hideResults) { try { File tempDirectory = FileUtil.createTempDirectory("inspection", "result"); final InspectionResultsView view = getView(); if (view != null) { ExportToXMLActionKt.dumpToXml(view.getCurrentProfile(), view.getTree(), view.getProject(), view.getGlobalInspectionContext(), tempDirectory.toPath()); File[] files = tempDirectory.listFiles(); if (files != null) { for (File file : files) { if (file.isHidden()) { continue; } String identifier = buildIdentifier(file.getName(), myOptions.inspectionTrueFields, project); context.message("#########", getLine()); context.message(file.getName(), getLine()); context.message( ArrayUtil.isEmpty(myOptions.inspectionTrueFields) ? null : StringUtil.join(myOptions.inspectionTrueFields, "-"), getLine()); context.message(project.getName(), getLine()); context.message("#########", getLine()); Path path = file.toPath(); context.message(path.toString(), getLine()); long warningCount; try (Stream<String> lines = Files.lines(path).filter(line -> line.contains("<problem>"))) { warningCount = lines.count(); } if (ApplicationManagerEx.isInIntegrationTest()) { if (warningCount < Integer.MAX_VALUE) { Path perfMetricsPath = Paths.get(PathManager.getLogPath()).resolve("performance-metrics").resolve("inspectionMetrics.json"); ResultsToFileProcessor.writeMetricsToJson(perfMetricsPath, "inspection_execution", (int)warningCount, null); } else { LOGGER.error("warningCount is greater than Integer.MAX_VALUE"); } } reportStatisticsToTeamCity(identifier, String.valueOf(warningCount)); saveArtifact(path, identifier); } } else { LOGGER.error("tempDirectory.listFiles() is null"); } } } catch (IOException ex) { LOGGER.error(ex); } } actionCallback.setDone(); } }; inspectionContext.setExternalProfile(profile); inspectionContext.doInspections(analysisScope); return Promises.toPromise(actionCallback); }
_execute
7,737
void (@NotNull InspectionResultsView view, @NotNull String title, boolean isOffline) { super.addView(view, title, isOffline); ToolWindow resultWindow = ProblemsView.getToolWindow(project); if (resultWindow != null && myOptions.hideResults) { resultWindow.hide(); } }
addView
7,738
void (@NotNull AnalysisScope scope) { super.notifyInspectionsFinished(scope); context.message(PerformanceTestingBundle.message("command.inspection.finish"), getLine()); if (enabledInspectionTools.size() == 1 && !myOptions.hideResults) { try { File tempDirectory = FileUtil.createTempDirectory("inspection", "result"); final InspectionResultsView view = getView(); if (view != null) { ExportToXMLActionKt.dumpToXml(view.getCurrentProfile(), view.getTree(), view.getProject(), view.getGlobalInspectionContext(), tempDirectory.toPath()); File[] files = tempDirectory.listFiles(); if (files != null) { for (File file : files) { if (file.isHidden()) { continue; } String identifier = buildIdentifier(file.getName(), myOptions.inspectionTrueFields, project); context.message("#########", getLine()); context.message(file.getName(), getLine()); context.message( ArrayUtil.isEmpty(myOptions.inspectionTrueFields) ? null : StringUtil.join(myOptions.inspectionTrueFields, "-"), getLine()); context.message(project.getName(), getLine()); context.message("#########", getLine()); Path path = file.toPath(); context.message(path.toString(), getLine()); long warningCount; try (Stream<String> lines = Files.lines(path).filter(line -> line.contains("<problem>"))) { warningCount = lines.count(); } if (ApplicationManagerEx.isInIntegrationTest()) { if (warningCount < Integer.MAX_VALUE) { Path perfMetricsPath = Paths.get(PathManager.getLogPath()).resolve("performance-metrics").resolve("inspectionMetrics.json"); ResultsToFileProcessor.writeMetricsToJson(perfMetricsPath, "inspection_execution", (int)warningCount, null); } else { LOGGER.error("warningCount is greater than Integer.MAX_VALUE"); } } reportStatisticsToTeamCity(identifier, String.valueOf(warningCount)); saveArtifact(path, identifier); } } else { LOGGER.error("tempDirectory.listFiles() is null"); } } } catch (IOException ex) { LOGGER.error(ex); } } actionCallback.setDone(); }
notifyInspectionsFinished
7,739
void (@NotNull Path path, @NotNull String identifier) { // We are currently at IDEA_HOME/ruby/integrationTests/run/RubyMine/bin File dest = new File("../../../report/incorrect-resolves/" + identifier + ".xml"); File destDir = dest.getParentFile(); if (!destDir.exists() && !destDir.mkdirs()) { LOGGER.error("Haven't managed to create directory: " + destDir.getAbsolutePath()); } try { Files.move(path, dest.toPath(), StandardCopyOption.REPLACE_EXISTING); LOGGER.info("Incorrect resolve artifact saved to " + dest.getAbsolutePath()); } catch (IOException e) { LOGGER.error("Cannot save artifact: " + identifier); LOGGER.error(e); } }
saveArtifact
7,740
void (@NotNull List<Tools> enabledInspectionTools, String @NotNull [] fieldNames, boolean flag) { if (enabledInspectionTools.size() == 1) { InspectionProfileEntry inspection = enabledInspectionTools.get(0).getTool().getTool(); Class<? extends InspectionProfileEntry> inspectionClass = inspection.getClass(); for (String inspectionFieldName : fieldNames) { try { Field field = inspectionClass.getField(inspectionFieldName); field.setBoolean(inspection, flag); } catch (NoSuchFieldException | IllegalAccessException e) { LOGGER.error(e); } } } else { LOGGER.error("Cannot set true flags for more than one inspection"); } }
setInspectionFields
7,741
void (@NotNull String toolShortName, @NotNull String downloadUrl) { String tempDirectory = FileUtil.getTempDirectory(); String filename = toolShortName + ".txt"; File downloadedFile = Paths.get(tempDirectory, filename).toFile(); if (downloadedFile.exists()) { //noinspection ResultOfMethodCallIgnored downloadedFile.delete(); } DownloadableFileService service = DownloadableFileService.getInstance(); DownloadableFileDescription description = service.createFileDescription(downloadUrl, filename); FileDownloader downloader = service.createDownloader(Collections.singletonList(description), "Download correct resolves file"); try { downloader.download(new File(tempDirectory)); } catch (IOException e) { LOGGER.error(e); } if (!downloadedFile.exists()) { LOGGER.error("Downloaded file doesn't exist"); } }
downloadTestRequiredFile
7,742
String (@NotNull final String inspectionResultFilename, final String @Nullable [] inspectionTrueFields, @NotNull Project project) { return Stream.of(project.getName(), StringUtil.trimExtensions(inspectionResultFilename), ArrayUtil.isEmpty(inspectionTrueFields) ? null : StringUtil.join(inspectionTrueFields, "-"), "warning-count") .filter(nonNull()) .collect(Collectors.joining("-")); }
buildIdentifier
7,743
void (@NotNull String key, @NotNull String value) { // As TeamCity doesn't show statistic I report to stdout I will report it twice in order to be able to see it in logs System.out.println("Report statistics key = " + key + " value = " + value); System.out.println("##teamcity[buildStatisticValue key='" + key + "' value='" + value + "']"); }
reportStatisticsToTeamCity
7,744
Promise<Object> (@NotNull PlaybackContext context) { final ActionCallback actionCallback = new ActionCallbackProfilerStopper(); final MessageBusConnection busConnection = context.getProject().getMessageBus().connect(); busConnection.subscribe(PowerSaveMode.TOPIC, () -> actionCallback.setDone()); ApplicationManager.getApplication().invokeAndWait(() -> { PowerSaveMode.setEnabled(false); }); return Promises.toPromise(actionCallback); }
_execute
7,745
void () { }
dispose
7,746
Promise<Object> (final @NotNull PlaybackContext context) { AsyncPromise<Object> completion = new AsyncPromise<>(); completeWhenSmartModeIsLongEnough(context.getProject(), completion); return completion; }
_execute
7,747
void (@NotNull Project project, @NotNull AsyncPromise<Object> completion) { DumbService.getInstance(project).runWhenSmart(() -> myAlarm.addRequest(() -> { if (DumbService.isDumb(project)) { completeWhenSmartModeIsLongEnough(project, completion); } else { completion.setResult(null); } }, SMART_MODE_MINIMUM_DELAY)); }
completeWhenSmartModeIsLongEnough
7,748
Sdk (@NotNull String name, @NotNull String type, @NotNull String home) { Ref<Sdk> sdkRef = new Ref<>(); ApplicationManager.getApplication().invokeAndWait(() -> { WriteAction.run(() -> { Sdk sdk = setup(name, type, home); sdkRef.set(sdk); }); }); return sdkRef.get(); }
setupOrDetectSdk
7,749
void (@NotNull Project project, @NotNull String name, @NotNull String type, @NotNull String home) { ApplicationManager.getApplication().invokeAndWait(() -> { WriteAction.run(() -> { Sdk sdk = setup(name, type, home); ProjectRootManager rootManager = ProjectRootManager.getInstance(project); Sdk projectSdk = rootManager.getProjectSdk(); if (!Objects.equals(projectSdk, sdk)) { LOG.info("Project uses different SDK: " + projectSdk + " " + "(sdkName is " + rootManager.getProjectSdkName() + ", " + "type " + rootManager.getProjectSdkTypeName() + "). Updating..."); rootManager.setProjectSdk(sdk); } LOG.info("Project SDK is set to use the new SDK"); for (Module module : ModuleManager.getInstance(project).getModules()) { Sdk moduleSdk = ModuleRootManager.getInstance(module).getSdk(); if (!Objects.equals(moduleSdk, sdk)) { LOG.info("Module " + module.getName() + " uses different SDK: " + moduleSdk + " IGNORING!"); } } }); }); }
setupOrDetectSdk
7,750
Sdk (String mySdkName, String mySdkType, String mySdkHome) { Sdk oldSdk = ProjectJdkTable.getInstance().findJdk(mySdkName); if (oldSdk != null) { if (Objects.equals(oldSdk.getSdkType().getName(), mySdkName) && FileUtil.pathsEqual(oldSdk.getHomePath(), mySdkHome)) { LOG.info("Existing SDK is already configured the expected way"); return oldSdk; } LOG.info("Existing different SDK will be removed: " + oldSdk); ProjectJdkTable.getInstance().removeJdk(oldSdk); } SdkType sdkType = SdkType.findByName(mySdkType); if (sdkType == null) { throw new IllegalArgumentException("Failed to find SdkType: " + mySdkType); } boolean isValidSdkHome; try { isValidSdkHome = sdkType.isValidSdkHome(mySdkHome); } catch (Throwable t) { throw new IllegalArgumentException("Sdk home " + mySdkHome + " for " + sdkType + " is not valid. " + t.getMessage(), t); } if (!isValidSdkHome) { throw new IllegalArgumentException("Sdk home " + mySdkHome + " for " + sdkType + " is not valid"); } Sdk newSdk = ProjectJdkTable.getInstance().createSdk(mySdkName, sdkType); SdkModificator mod = newSdk.getSdkModificator(); try { mod.setVersionString(sdkType.getVersionString(mySdkHome)); mod.setHomePath(mySdkHome); } catch (Throwable t) { throw new IllegalArgumentException( "Failed to configure Sdk instance home for " + mySdkHome + " for " + sdkType + " is not valid. " + t.getMessage(), t); } finally { mod.commitChanges(); } try { sdkType.setupSdkPaths(newSdk); } catch (Throwable t) { throw new IllegalArgumentException( "Failed to setup Sdk home for " + mySdkHome + " for " + sdkType + " is not valid. " + t.getMessage(), t); } ProjectJdkTable.getInstance().addJdk(newSdk); LOG.info("Registered new SDK to ProjectJdkTable: " + newSdk); return newSdk; }
setup
7,751
Promise<Object> (@NotNull PlaybackContext context) { final ActionCallback actionCallback = new ActionCallbackProfilerStopper(); WriteAction.runAndWait(() -> { Project project = context.getProject(); PsiManager.getInstance(project).dropResolveCaches(); PsiManager.getInstance(project).dropPsiCaches(); ((StubIndexEx)StubIndex.getInstance()).cleanCaches(); ((PersistentFSImpl)PersistentFS.getInstance()).incStructuralModificationCount(); actionCallback.setDone(); }); return Promises.toPromise(actionCallback); }
_execute
7,752
long () { return usedMb; }
getUsedMb
7,753
long () { return maxMb; }
getMaxMb
7,754
long () { return metaspaceMb; }
getMetaspaceMb
7,755
void (@NotNull ActionCallback actionCallback, @NotNull PlaybackContext context) { String[] arguments = getText().split(" ", 3); String filePath = arguments[1]; long timeout = Long.parseLong(arguments[2]); Project project = context.getProject(); VirtualFile file = findFile(filePath, project); assert file != null : PerformanceTestingBundle.message("command.file.not.found", filePath); FileEditorManager.getInstance(project).openFile(file, true); ApplicationManager.getApplication().executeOnPooledThread(() -> { try { TimeUnit.SECONDS.sleep(timeout); ApplicationManager.getApplication().exit(true, true, false); actionCallback.setDone(); } catch (InterruptedException e) { actionCallback.reject(e.getMessage()); } }); }
execute
7,756
Promise<Object> (@NotNull PlaybackContext context) { ActionCallback actionCallback = new ActionCallbackProfilerStopper(); String input = extractCommandArgument(PREFIX); String[] lineAndColumn = input.split(" "); final int startLine = Integer.parseInt(lineAndColumn[0]) - 1; final int startColumn = Integer.parseInt(lineAndColumn[1]) - 1; final int endLine = Integer.parseInt(lineAndColumn[2]) - 1; final int endColumn = Integer.parseInt(lineAndColumn[3]) - 1; ApplicationManager.getApplication().executeOnPooledThread(() -> { try { Waiter.checkCondition(() -> findTarget(context) != null).await(10, TimeUnit.MINUTES); } catch (InterruptedException e) { actionCallback.reject(e.getMessage()); return; } ApplicationManager.getApplication().invokeAndWait(() -> { TypingTarget target = findTarget(context); if (target instanceof EditorComponentImpl) { EditorImpl editor = ((EditorComponentImpl)target).getEditor(); Document document = editor.getDocument(); editor.getSelectionModel() .setSelection(document.getLineStartOffset(startLine) + startColumn, document.getLineStartOffset(endLine) + endColumn); actionCallback.setDone(); } else { actionCallback.reject("Cannot replace text on non-Editor component"); } }); }); return Promises.toPromise(actionCallback); }
_execute
7,757
Promise<Object> (@NotNull final PlaybackContext context) { //example: %runConfiguration TILL_TERMINATED My Run Configuration String[] command = extractCommandArgument(PREFIX).split(" ", 2); String mode = command[0]; String configurationNameToRun = command[1]; Timer timer = new Timer(); final ActionCallback actionCallback = new ActionCallbackProfilerStopper(); Project project = context.getProject(); MessageBusConnection connection = project.getMessageBus().connect(); connection.subscribe(ExecutionManager.EXECUTION_TOPIC, new ExecutionListener() { @Override public void processStarting(@NotNull String executorId, @NotNull ExecutionEnvironment env, @NotNull ProcessHandler handler) { timer.start(); myExecutionEnvironment = env; context.message("processStarting: " + env, getLine()); } @Override public void processStarted(@NotNull String executorId, @NotNull ExecutionEnvironment env, @NotNull ProcessHandler handler) { myExecutionEnvironment = env; if (mode.equals(WAIT_FOR_PROCESS_STARTED)) { timer.stop(); long executionTime = timer.getTotalTime(); context.message("processStarted in: " + env + ": " + executionTime, getLine()); actionCallback.setDone(); } } @Override public void processTerminated(@NotNull String executorId, @NotNull ExecutionEnvironment env, @NotNull ProcessHandler handler, int exitCode) { if (mode.equals(WAIT_FOR_PROCESS_TERMINATED)) { timer.stop(); long executionTime = timer.getTotalTime(); context.message("processTerminated in: " + env + ": " + executionTime, getLine()); if (env.equals(myExecutionEnvironment)) { if (exitCode == 0) { actionCallback.setDone(); } else { actionCallback.reject("Run configuration is finished with exitCode: " + exitCode); } connection.disconnect(); } } } }); RunManagerImpl runManager = RunManagerImpl.getInstanceImpl(project); ApplicationManager.getApplication().invokeLater(() -> { if (!mode.contains(WAIT_FOR_PROCESS_STARTED) && !mode.contains(WAIT_FOR_PROCESS_TERMINATED)) { actionCallback.reject("Specified mode is neither TILL_STARTED nor TILL_TERMINATED"); } Executor executor = new DefaultRunExecutor(); ExecutionTarget target = DefaultExecutionTarget.INSTANCE; RunConfiguration configurationToRun = getConfigurationByName(runManager, configurationNameToRun); if (configurationToRun == null) { actionCallback.reject("Specified configuration is not found: " + configurationNameToRun); printAllConfigurationsNames(runManager); } else { RunnerAndConfigurationSettingsImpl runnerAndConfigurationSettings = new RunnerAndConfigurationSettingsImpl(runManager, configurationToRun); ExecutionManager.getInstance(project).restartRunProfile(project, executor, target, runnerAndConfigurationSettings, null); } }); return Promises.toPromise(actionCallback); }
_execute
7,758
void (@NotNull String executorId, @NotNull ExecutionEnvironment env, @NotNull ProcessHandler handler) { timer.start(); myExecutionEnvironment = env; context.message("processStarting: " + env, getLine()); }
processStarting
7,759
void (@NotNull String executorId, @NotNull ExecutionEnvironment env, @NotNull ProcessHandler handler) { myExecutionEnvironment = env; if (mode.equals(WAIT_FOR_PROCESS_STARTED)) { timer.stop(); long executionTime = timer.getTotalTime(); context.message("processStarted in: " + env + ": " + executionTime, getLine()); actionCallback.setDone(); } }
processStarted
7,760
void (@NotNull String executorId, @NotNull ExecutionEnvironment env, @NotNull ProcessHandler handler, int exitCode) { if (mode.equals(WAIT_FOR_PROCESS_TERMINATED)) { timer.stop(); long executionTime = timer.getTotalTime(); context.message("processTerminated in: " + env + ": " + executionTime, getLine()); if (env.equals(myExecutionEnvironment)) { if (exitCode == 0) { actionCallback.setDone(); } else { actionCallback.reject("Run configuration is finished with exitCode: " + exitCode); } connection.disconnect(); } } }
processTerminated
7,761
RunConfiguration (RunManager runManager, String configurationName) { return ContainerUtil.find(runManager.getAllConfigurationsList(), configuration -> configurationName.equals(configuration.getName())); }
getConfigurationByName
7,762
void (RunManager runManager) { LOG.info("*****************************"); LOG.info("Available configurations are:"); runManager.getAllConfigurationsList().stream().map(RunProfile::getName).forEach(LOG::info); LOG.info("*****************************"); }
printAllConfigurationsNames
7,763
void (List<String> filePaths) { synchronizeFiles(filePaths, ProjectManager.getInstance().getOpenProjects()[0]); }
synchronizeFiles
7,764
void (@NotNull ActionCallback callback, @NotNull PlaybackContext context) { var project = context.getProject(); synchronizeFiles(extractCommandList(PREFIX, " "), project); callback.setDone(); }
execute
7,765
void (List<String> filePaths, Project project) { VirtualFile[] files = filePaths.stream().map(path -> { var file = findFile(path, project); if (file == null) { throw new IllegalArgumentException("File not found " + path); } return file; }).toArray(VirtualFile[]::new); markDirtyAndRefresh(false, true, true, files); }
synchronizeFiles
7,766
MemoryMetrics () { return memory; }
getMemory
7,767
Promise<Object> (@NotNull PlaybackContext context) { ActionCallback actionCallback = new ActionCallbackProfilerStopper(); String extractCommandList = extractCommandArgument(PREFIX); String[] commandList = extractCommandList.split("\\|"); final String actionName = commandList[0]; final boolean invoke = commandList.length == 1 || Boolean.parseBoolean(commandList[1]); ApplicationManager.getApplication().invokeAndWait(Context.current().wrap(() -> { @NotNull Project project = context.getProject(); Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor(); if (editor != null) { PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (psiFile != null) { TraceUtil.runWithSpanThrows(PerformanceTestSpan.TRACER, SPAN_NAME, span -> { CachedIntentions intentions = ShowIntentionActionsHandler.calcCachedIntentions(project, editor, psiFile); if (!actionName.isEmpty()) { List<IntentionActionWithTextCaching> combined = new ArrayList<>(); combined.addAll(intentions.getIntentions()); combined.addAll(intentions.getInspectionFixes()); combined.addAll(intentions.getErrorFixes()); //combined.addAll(intentions.guttersToShow); combined.addAll(intentions.getNotifications()); span.setAttribute("number", combined.size()); Optional<IntentionActionWithTextCaching> singleIntention = combined.stream().filter(s -> s.getAction().getText().startsWith(actionName)).findFirst(); if (singleIntention.isEmpty()) { actionCallback.reject(actionName + " is not found among " + combined); return; } if (invoke) { singleIntention.ifPresent( c -> ShowIntentionActionsHandler.chooseActionAndInvoke(psiFile, editor, c.getAction(), c.getAction().getText())); } } if (!invoke || actionName.isEmpty()) { IntentionHintComponent.showIntentionHint(project, psiFile, editor, true, intentions); } }); if(!actionCallback.isRejected()){ actionCallback.setDone(); } } else { actionCallback.reject("PSI File is null"); } } else { actionCallback.reject("Editor is not opened"); } })); return Promises.toPromise(actionCallback); }
_execute
7,768
void () { }
dispose
7,769
String () { return NAME; }
getName
7,770
Promise<Object> (@NotNull PlaybackContext context) { ActionCallback actionCallback = new ActionCallbackProfilerStopper(); ApplicationManager.getApplication().invokeAndWait(Context.current().wrap(() -> { boolean highlightErrorElements = true; boolean runAnnotators = true; Project project = context.getProject(); final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor(); if (editor == null) { actionCallback.reject("Editor is not open"); return; } PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (psiFile == null) { actionCallback.reject("Missing PSI file in the editor"); return; } getInstance(project).dropPsiCaches(); ReadAction.nonBlocking(Context.current().wrap((Callable<Void>)() -> { long start = System.nanoTime(); TraceUtil.runWithSpanThrows(PerformanceTestSpan.TRACER, SPAN_NAME, span -> { GlobalInspectionTool tool = new HighlightVisitorBasedInspection() .setHighlightErrorElements(highlightErrorElements).setRunAnnotators(runAnnotators).setRunVisitors(false); InspectionManager inspectionManager = InspectionManager.getInstance(project); GlobalInspectionContext globalContext = inspectionManager.createNewGlobalContext(); InspectionEngine.runInspectionOnFile(psiFile, new GlobalInspectionToolWrapper(tool), globalContext); span.setAttribute("lines", editor.getDocument().getLineCount()); long stop = System.nanoTime(); span.setAttribute("timeToLines", (double)(stop - start) / MILLIS_IN_NANO / (Math.max(1, editor.getDocument().getLineCount()))); }); actionCallback.setDone(); return null; })).wrapProgress(new DaemonProgressIndicator()).submit(AppExecutorUtil.getAppExecutorService()); })); return Promises.toPromise(actionCallback); }
_execute
7,771
Promise<Object> (final @NotNull PlaybackContext context) { final ActionCallback actionCallback = new ActionCallbackProfilerStopper(); Project project = context.getProject(); PsiManagerImpl myPsiManager = (PsiManagerImpl)PsiManager.getInstance(project); String input = extractCommandArgument(PREFIX); String[] lineAndColumn = input.split(" "); final String sourcePath = lineAndColumn[0]; final String targetPath = lineAndColumn[1]; VirtualFile projectDir = ProjectUtil.guessProjectDir(project); if(projectDir != null) { VirtualFile sourceVirtualFile = projectDir.findFileByRelativePath(sourcePath); VirtualFile targetVirtualFile = projectDir.findFileByRelativePath(targetPath); if(sourceVirtualFile != null && targetVirtualFile != null) { final PsiDirectory sourcePsiDir = myPsiManager.findDirectory(sourceVirtualFile); final PsiDirectory targetPsiDir = myPsiManager.findDirectory(targetVirtualFile); ApplicationManager.getApplication().invokeAndWait(() -> WriteCommandAction.writeCommandAction(project).run(() -> { MoveFilesOrDirectoriesUtil.doMoveDirectory(sourcePsiDir, targetPsiDir); LOG.info("Dir " + sourcePath + " has been moved to " + targetPath); actionCallback.setDone(); }), ModalityState.nonModal()); } else { actionCallback.reject("Source or target dir is not found"); } } else { actionCallback.reject("Project dir can't be guessed"); } return Promises.toPromise(actionCallback); }
_execute
7,772
void (@NotNull ActionCallback callback, @NotNull PlaybackContext context) { if (ApplicationManager.getApplication().isInternal()) { try { CreateAllServicesAndExtensionsActionKt.performAction(); callback.setDone(); } catch (Exception e) { callback.reject(e.getMessage()); } } else { callback.reject("Internal mode is required for the '" + CreateAllServicesAndExtensionsActionKt.ACTION_ID + "' command." + "Please see https://plugins.jetbrains.com/docs/intellij/enabling-internal.html"); } }
execute
7,773
Promise<Object> (@NotNull PlaybackContext context) { ActionCallback actionCallback = new ActionCallbackProfilerStopper(); ApplicationManager.getApplication().invokeAndWait(Context.current().wrap(() -> { @NotNull Project project = context.getProject(); FileEditor fileEditor = FileEditorManager.getInstance(project).getSelectedEditor(); if (fileEditor != null) { Span span = PerformanceTestSpan.TRACER.spanBuilder(SPAN_NAME).startSpan(); try (Scope ignored = span.makeCurrent()) { final FileStructurePopup popup = createPopup(project, fileEditor); if (popup != null) { Span spanShow = PerformanceTestSpan.TRACER.spanBuilder(SPAN_NAME + "#Show").startSpan(); Span spanFill = PerformanceTestSpan.TRACER.spanBuilder(SPAN_NAME + "#Fill").startSpan(); popup.showWithResult().onProcessed(path -> { actionCallback.setDone(); spanFill.end(); span.end(); }); spanShow.end(); } else { span.setStatus(StatusCode.ERROR, "File structure popup is null"); actionCallback.reject("File structure popup is null"); } } } else { actionCallback.reject("File editor is null"); } })); return Promises.toPromise(actionCallback); }
_execute
7,774
void () { }
dispose
7,775
Promise<Object> (@NotNull PlaybackContext context) { if (!MemoryDumpHelper.memoryDumpAvailable()) { return Promises.rejectedPromise("Memory dump can't be collected"); } //noinspection CallToSystemGC System.gc(); String path = getMemoryDumpPath(); try { MemoryDumpHelper.captureMemoryDumpZipped(path); context.message("Memory snapshot is saved at " + path, getLine()); return Promises.resolvedPromise(); } catch (Exception e) { return Promises.rejectedPromise("Memory dump can't be collected"); } }
_execute
7,776
String () { String memoryDumpPath = System.getProperties().getProperty("memory.snapshots.path", PathManager.getLogPath()); String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")); return memoryDumpPath + File.separator + (Timer.instance.getActivityName() + '-' + currentTime + ".hprof"); }
getMemoryDumpPath
7,777
void (@NotNull ActionCallback callback, @NotNull PlaybackContext context) { writeExitMetricsIfNeeded(); String[] arguments = getText().split(" ", 2); boolean forceExit = true; if (arguments.length > 1) { forceExit = Boolean.parseBoolean(arguments[1]); } ApplicationManager.getApplication().exit(forceExit, true, false); callback.setDone(); }
execute
7,778
void () { String exitMetricsPath = System.getProperty("idea.log.exit.metrics.file"); if (exitMetricsPath != null) { writeExitMetrics(exitMetricsPath); } }
writeExitMetricsIfNeeded
7,779
void (String path) { MemoryCapture capture = MemoryCapture.capture(); MemoryMetrics memory = new MemoryMetrics(capture.getUsedMb(), capture.getMaxMb(), capture.getMetaspaceMb()); ExitMetrics metrics = new ExitMetrics(memory); try { new ObjectMapper().writeValue(new File(path), metrics); } catch (IOException e) { //noinspection UseOfSystemOutOrSystemErr System.err.println("Unable to write exit metrics from " + ExitAppCommand.class.getSimpleName() + " " + e.getMessage()); } }
writeExitMetrics
7,780
Promise<Object> (final @NotNull PlaybackContext context) { final ActionCallback actionCallback = new ActionCallbackProfilerStopper(); String input = extractCommandArgument(PREFIX); String[] args = input.split(" "); if (args.length == 1) { int offset = Integer.parseInt(args[0]); ApplicationManager.getApplication().invokeLater(() -> { Project project = context.getProject(); final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor(); assert editor != null; goToOffset(context, actionCallback, editor, offset); }); } else { final int line = Integer.parseInt(args[0]) - 1; final int columnArg = Integer.parseInt(args[1]); final int column = columnArg == 0 ? 0 : columnArg - 1; ApplicationManager.getApplication().invokeLater(() -> { Project project = context.getProject(); final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor(); assert editor != null; Document document = editor.getDocument(); if (line <= document.getLineCount()) { int lineStartOffset = document.getLineStartOffset(line); int lineLength = document.getLineEndOffset(line) - lineStartOffset; if (column > lineLength) { //noinspection TestOnlyProblems WriteCommandAction.runWriteCommandAction(project, () -> document.insertString(lineStartOffset + lineLength, IntStream.range(0, column - lineLength).mapToObj(i -> " ").collect(Collectors.joining()))); } int offset = lineStartOffset + column; goToOffset(context, actionCallback, editor, offset); } else { context.error("Line is out of range", getLine()); actionCallback.setRejected(); } }); } return Promises.toPromise(actionCallback); }
_execute
7,781
void (@NotNull PlaybackContext context, @NotNull ActionCallback actionCallback, @NotNull Editor editor, int offset) { final CaretListener caretListener = new CaretListener() { @Override public void caretPositionChanged(@NotNull CaretEvent e) { context.message(PerformanceTestingBundle.message("command.goto.finish"), getLine()); actionCallback.setDone(); } }; editor.getCaretModel().addCaretListener(caretListener); actionCallback.doWhenDone(() -> editor.getCaretModel().removeCaretListener(caretListener)); if (editor.getCaretModel().getOffset() == offset) { context.message(PerformanceTestingBundle.message("command.goto.finish"), getLine()); actionCallback.setDone(); } else { editor.getCaretModel().moveToOffset(offset); editor.getScrollingModel().scrollToCaret(ScrollType.CENTER); } }
goToOffset
7,782
void (@NotNull CaretEvent e) { context.message(PerformanceTestingBundle.message("command.goto.finish"), getLine()); actionCallback.setDone(); }
caretPositionChanged
7,783
Promise<Object> (@NotNull PlaybackContext context) { final AsyncPromise<Object> result = new AsyncPromise<>(); Options options = new Options(); Args.parse(options, extractCommandArgument(PREFIX).split(" ")); ApplicationManager.getApplication().executeOnPooledThread(() -> { try { Waiter.checkCondition(() -> findTarget(context) != null).await(10, TimeUnit.MINUTES); } catch (InterruptedException e) { result.setError(e); return; } ApplicationManager.getApplication().invokeAndWait(() -> { TypingTarget target = findTarget(context); if (target instanceof EditorComponentImpl) { DocumentEx document = ((EditorComponentImpl)target).getEditor().getDocument(); int startOffset = options.startOffset == null ? 0 : options.startOffset; int endOffset = options.endOffset == null ? document.getTextLength() : options.endOffset; WriteCommandAction.runWriteCommandAction(context.getProject(), () -> document.replaceString(startOffset, endOffset, options.newText)); result.setResult(null); } else { result.setError("Cannot replace text on non-Editor component"); } }); }); return result; }
_execute
7,784
Promise<Object> (final @NotNull PlaybackContext context) { final AsyncPromise<Object> result = new AsyncPromise<>(); String input = extractCommandArgument(PREFIX); String[] delayText = input.split("\\|"); final long delay = Integer.parseInt(delayText[0]); final String text = delayText[1] + END_CHAR; final boolean calculateAnalyzesTime = delayText.length > 2 && Boolean.parseBoolean(delayText[2]); Ref<Span> spanRef = new Ref<>(); var projectConnection = context.getProject().getMessageBus().simpleConnect(); var applicationConnection = ApplicationManager.getApplication().getMessageBus().connect(); var latencyRecorder = new LatencyRecord(); applicationConnection.subscribe(LatencyListener.TOPIC, new LatencyListener() { @Override public void recordTypingLatency(@NotNull Editor editor, String action, long latencyMs) { latencyRecorder.update(((int)latencyMs)); } }); Ref<DaemonCodeAnalyzerResult> job = new Ref<>(); ApplicationManager.getApplication().executeOnPooledThread(Context.current().wrap(() -> { TraceUtil.runWithSpanThrows(PerformanceTestSpan.TRACER, SPAN_NAME, span -> { span.addEvent("Finding typing target"); try { Waiter.checkCondition(() -> findTarget(context) != null).await(1, TimeUnit.MINUTES); } catch (InterruptedException e) { span.recordException(e); result.setError(e); return; } CountDownLatch allScheduled = new CountDownLatch(1); for (int i = 0; i < text.length(); i++) { char currentChar = text.charAt(i); boolean nextCharIsTheLast = ((i + 1) < text.length()) && (text.charAt(i + 1) == END_CHAR); myExecutor.schedule(() -> ApplicationManager.getApplication().invokeAndWait(Context.current().wrap( () -> { if (nextCharIsTheLast && calculateAnalyzesTime) { job.set(DaemonCodeAnalyzerListener.INSTANCE.listen(projectConnection, spanRef, 0, null)); var spanBuilder = PerformanceTestSpan.TRACER.spanBuilder(CODE_ANALYSIS_SPAN_NAME).setParent(Context.current().with(span)); spanRef.set(spanBuilder.startSpan()); } if (currentChar == END_CHAR) { allScheduled.countDown(); myExecutor.shutdown(); } else { span.addEvent("Calling find target second time in DelayTypeCommand"); TypingTarget typingTarget = findTarget(context); if (typingTarget != null) { span.addEvent("Typing " + currentChar); typingTarget.type(String.valueOf(currentChar)); } } })), i * delay, TimeUnit.MILLISECONDS); } try { allScheduled.await(); myExecutor.awaitTermination(1, TimeUnit.MINUTES); if (!latencyRecorder.getSamples().isEmpty()) { span.setAttribute("latency#max", latencyRecorder.getMaxLatency()); span.setAttribute("latency#p90", latencyRecorder.percentile(90)); span.setAttribute("latency#mean_value", latencyRecorder.getAverageLatency()); } } catch (InterruptedException e) { result.setError(e); } }); if (calculateAnalyzesTime) { job.get().blockingWaitForComplete(); } applicationConnection.disconnect(); result.setResult(null); })); return result; }
_execute
7,785
void (@NotNull Editor editor, String action, long latencyMs) { latencyRecorder.update(((int)latencyMs)); }
recordTypingLatency
7,786
void (@NotNull AnActionEvent e) { Project project = e.getProject(); if (project == null) { return; } ExecuteScriptDialog executeScriptDialog = new ExecuteScriptDialog(project); executeScriptDialog.show(); }
actionPerformed
7,787
ActionUpdateThread () { return ActionUpdateThread.BGT; }
getActionUpdateThread
7,788
void (@NotNull AnActionEvent e) { e.getPresentation().setEnabledAndVisible(e.getProject() != null); }
update
7,789
void (@NotNull AnActionEvent e) { Project project = e.getProject(); if (project == null) { return; } Path reportHtml = IndexDiagnosticDumper.Companion.getProjectDiagnosticDirectory(project).resolve("report.html"); BrowserUtil.browse(reportHtml); }
actionPerformed
7,790
ActionUpdateThread () { return ActionUpdateThread.BGT; }
getActionUpdateThread
7,791
void (@NotNull AnActionEvent e) { e.getPresentation().setEnabledAndVisible(e.getProject() != null); }
update
7,792
String () { return "IntegrationPerformanceTest"; }
getName
7,793
String () { return PerformanceTestingBundle.message("filetype.ijperformance.test.display.name"); }
getDisplayName
7,794
String () { return PerformanceTestingBundle.message("filetype.ijperformance.test.description"); }
getDescription
7,795
String () { return DEFAULT_EXTENSION; }
getDefaultExtension
7,796
Icon () { return AllIcons.FileTypes.Text; }
getIcon
7,797
SyntaxHighlighter (@Nullable Project project, @Nullable VirtualFile virtualFile) { return new IJPerfSyntaxHighlighter(); }
getSyntaxHighlighter
7,798
Lexer (Project project) { return new IJPerfLexerAdapter(); }
createLexer
7,799
PsiParser (Project project) { return new IJPerfParser(); }
createParser