Java Code Examples for com.intellij.openapi.util.EmptyRunnable

The following are top voted examples for showing how to use com.intellij.openapi.util.EmptyRunnable. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: intellij-ce-playground   File: ProjectConfigurable.java   Source Code and License 6 votes vote down vote up
private void createUIComponents() {
  myLanguageLevelCombo = new LanguageLevelCombo(JavaCoreBundle.message("default.language.level.description")) {
    @Override
    protected LanguageLevel getDefaultLevel() {
      Sdk sdk = myProjectJdkConfigurable.getSelectedProjectJdk();
      if (sdk == null) return null;
      JavaSdkVersion version = JavaSdk.getInstance().getVersion(sdk);
      return version == null ? null : version.getMaxLanguageLevel();
    }
  };
  final JTextField textField = new JTextField();
  final FileChooserDescriptor outputPathsChooserDescriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor();
  InsertPathAction.addTo(textField, outputPathsChooserDescriptor);
  outputPathsChooserDescriptor.setHideIgnored(false);
  BrowseFilesListener listener = new BrowseFilesListener(textField, "", ProjectBundle.message("project.compiler.output"), outputPathsChooserDescriptor);
  myProjectCompilerOutput = new FieldPanel(textField, null, null, listener, EmptyRunnable.getInstance());
  FileChooserFactory.getInstance().installFileCompletion(myProjectCompilerOutput.getTextField(), outputPathsChooserDescriptor, true, null);
}
 
Example 2
Project: intellij-ce-playground   File: TestRunnerUtil.java   Source Code and License 6 votes vote down vote up
public static void replaceIdeEventQueueSafely() {
  if (Toolkit.getDefaultToolkit().getSystemEventQueue() instanceof IdeEventQueue) {
    return;
  }
  if (SwingUtilities.isEventDispatchThread()) {
    throw new RuntimeException("must not call under EDT");
  }
  AWTAutoShutdown.getInstance().notifyThreadBusy(Thread.currentThread());
  UIUtil.pump();
  // in JDK 1.6 java.awt.EventQueue.push() causes slow painful death of current EDT
  // so we have to wait through its agony to termination
  try {
    SwingUtilities.invokeAndWait(new Runnable() {
      @Override
      public void run() {
        IdeEventQueue.getInstance();
      }
    });
    SwingUtilities.invokeAndWait(EmptyRunnable.getInstance());
    SwingUtilities.invokeAndWait(EmptyRunnable.getInstance());
  }
  catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example 3
Project: intellij-ce-playground   File: ApplicationImplTest.java   Source Code and License 6 votes vote down vote up
public void testWriteActionIsAllowedFromEDTOnly() throws InterruptedException {
  Thread thread = new Thread("test") {
    @Override
    public void run() {
      try {
        ApplicationManager.getApplication().runWriteAction(EmptyRunnable.getInstance());
      }
      catch (Throwable e) {
        exception = e;
      }
    }
  };
  thread.start();
  thread.join();
  assertNotNull(exception);
}
 
Example 4
Project: intellij-ce-playground   File: CoreCommandProcessor.java   Source Code and License 6 votes vote down vote up
@Override
@Nullable
public Object startCommand(final Project project,
                           @Nls final String name,
                           final Object groupId,
                           final UndoConfirmationPolicy undoConfirmationPolicy) {
  ApplicationManager.getApplication().assertIsDispatchThread();
  if (project != null && project.isDisposed()) return null;

  if (CommandLog.LOG.isDebugEnabled()) {
    CommandLog.LOG.debug("startCommand: name = " + name + ", groupId = " + groupId);
  }

  if (myCurrentCommand != null) {
    return null;
  }

  Document document = groupId instanceof Ref && ((Ref)groupId).get() instanceof Document ? (Document)((Ref)groupId).get() : null;
  myCurrentCommand = new CommandDescriptor(EmptyRunnable.INSTANCE, project, name, groupId, undoConfirmationPolicy, document);
  fireCommandStarted();
  return myCurrentCommand;
}
 
Example 5
Project: intellij-ce-playground   File: VisiblePropertyTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testVisibleProperty() throws Exception {
  JLabel label = new JLabel();
  VisibleProperty visibleProperty = new VisibleProperty(label);
  CountListener listener = new CountListener();
  visibleProperty.addListener(listener);

  assertThat(visibleProperty.get()).isTrue();
  assertThat(listener.getCount()).isEqualTo(0);

  label.setVisible(false);
  // Swing enqueues the visibility changed event, so we need to wait for it
  SwingUtilities.invokeAndWait(EmptyRunnable.INSTANCE);
  assertThat(visibleProperty.get()).isFalse();
  assertThat(listener.getCount()).isEqualTo(1);

  visibleProperty.set(true);
  assertThat(label.isVisible()).isTrue();
  assertThat(listener.getCount()).isGreaterThan(1);
}
 
Example 6
Project: intellij-ce-playground   File: MavenProjectsProcessorArtifactsDownloadingTask.java   Source Code and License 6 votes vote down vote up
public void perform(final Project project, MavenEmbeddersManager embeddersManager, MavenConsole console, MavenProgressIndicator indicator)
  throws MavenProcessCanceledException {
  MavenArtifactDownloader.DownloadResult result =
    myTree.downloadSourcesAndJavadocs(project, myProjects, myArtifacts, myDownloadSources, myDownloadDocs, embeddersManager, console, indicator);
  if (myCallbackResult != null) myCallbackResult.setDone(result);

  // todo: hack to update all file pointers.
  MavenUtil.invokeLater(project, new Runnable() {
    public void run() {
      AccessToken accessToken = WriteAction.start();
      try {
        ProjectRootManagerEx.getInstanceEx(project).makeRootsChange(EmptyRunnable.getInstance(), false, true);
      }
      finally {
        accessToken.finish();
      }
    }
  });
}
 
Example 7
Project: tools-idea   File: JavaAutoImportOptions.java   Source Code and License 6 votes vote down vote up
public void apply() {
  CodeInsightSettings codeInsightSettings = CodeInsightSettings.getInstance();
  DaemonCodeAnalyzerSettings daemonSettings = DaemonCodeAnalyzerSettings.getInstance();

  codeInsightSettings.ADD_IMPORTS_ON_PASTE = getSmartPasteValue();
  codeInsightSettings.EXCLUDED_PACKAGES = getExcludedPackages();
  daemonSettings.setImportHintEnabled(myCbShowImportPopup.isSelected());
  codeInsightSettings.OPTIMIZE_IMPORTS_ON_THE_FLY = myCbOptimizeImports.isSelected();
  codeInsightSettings.ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY = myCbAddUnambiguousImports.isSelected();

  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    public void run() {
      for (Project project : ProjectManager.getInstance().getOpenProjects()) {
        ProjectRootManagerEx.getInstanceEx(project).makeRootsChange(EmptyRunnable.getInstance(), false, true);
      }
    }
  });
}
 
Example 8
Project: tools-idea   File: CommandProcessorImpl.java   Source Code and License 6 votes vote down vote up
@Override
@Nullable
public Object startCommand(final Project project,
                           @Nls final String name,
                           final Object groupId,
                           final UndoConfirmationPolicy undoConfirmationPolicy) {
  ApplicationManager.getApplication().assertIsDispatchThread();
  if (project != null && project.isDisposed()) return null;

  if (CommandLog.LOG.isDebugEnabled()) {
    CommandLog.LOG.debug("startCommand: name = " + name + ", groupId = " + groupId);
  }

  if (myCurrentCommand != null) {
    return null;
  }

  Document document = groupId instanceof Ref && ((Ref)groupId).get() instanceof Document ? (Document)((Ref)groupId).get() : null;
  myCurrentCommand = new CommandDescriptor(EmptyRunnable.INSTANCE, project, name, groupId, undoConfirmationPolicy, document);
  fireCommandStarted();
  return myCurrentCommand;
}
 
Example 9
Project: tools-idea   File: EnforcedPlainTextFileTypeManager.java   Source Code and License 6 votes vote down vote up
private static void fireRootsChanged(final Collection<VirtualFile> files, final boolean isAdded) {
  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    @Override
    public void run() {
      for (Project project : ProjectManager.getInstance().getOpenProjects()) {
        ProjectRootManagerEx.getInstanceEx(project).makeRootsChange(EmptyRunnable.getInstance(), false, true);
        ProjectPlainTextFileTypeManager projectPlainTextFileTypeManager = ProjectPlainTextFileTypeManager.getInstance(project);
        for (VirtualFile file : files) {
          if (projectPlainTextFileTypeManager.hasProjectContaining(file)) {
            if (isAdded) {
              projectPlainTextFileTypeManager.addFile(file);
            }
            else {
              projectPlainTextFileTypeManager.removeFile(file);
            }
          }
        }
      }
    }
  });
}
 
Example 10
Project: tools-idea   File: MavenProjectsProcessorArtifactsDownloadingTask.java   Source Code and License 6 votes vote down vote up
public void perform(final Project project, MavenEmbeddersManager embeddersManager, MavenConsole console, MavenProgressIndicator indicator)
  throws MavenProcessCanceledException {
  MavenArtifactDownloader.DownloadResult result =
    myTree.downloadSourcesAndJavadocs(project, myProjects, myArtifacts, myDownloadSources, myDownloadDocs, embeddersManager, console, indicator);
  if (myCallbackResult != null) myCallbackResult.setDone(result);

  // todo: hack to update all file pointers.
  MavenUtil.invokeLater(project, new Runnable() {
    public void run() {
      AccessToken accessToken = WriteAction.start();
      try {
        ProjectRootManagerEx.getInstanceEx(project).makeRootsChange(EmptyRunnable.getInstance(), false, true);
      }
      finally {
        accessToken.finish();
      }
    }
  });
}
 
Example 11
Project: tools-idea   File: GitLogPerformanceTest.java   Source Code and License 6 votes vote down vote up
private void impl(RootsHolder rootsHolder, GitLogFilters filters) {
  final GitCommitsSequentialIndex commitsSequentially = new GitCommitsSequentialIndex();
  final MediatorImpl mediator = new MediatorImpl(myProject, commitsSequentially);
  final LoadController controller = new LoadController(myProject, mediator, null, commitsSequentially);

  mediator.setLoader(controller);
  final BigTableTableModel tableModel = new BigTableTableModel(Collections.<ColumnInfo>emptyList(), EmptyRunnable.getInstance());
  mediator.setTableModel(tableModel);
  tableModel.setRootsHolder(rootsHolder);
  final Semaphore semaphore = new Semaphore();
  final MyUIRefresh refresh = new MyUIRefresh(semaphore);
  mediator.setUIRefresh(refresh);

  final long start = System.currentTimeMillis();
  semaphore.down();
  mediator.reload(rootsHolder, Collections.<String>emptyList(), Collections.<String>emptyList(), filters, true);
  semaphore.waitFor(300000);
  refresh.assertMe();
  final long end = System.currentTimeMillis();
  System.out.println("Time: " + (end - start));
}
 
Example 12
Project: consulo-haxe   File: HaxeImportOptimizer.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public Runnable processFile(final PsiFile file)
{
	VirtualFile vFile = file.getVirtualFile();
	if(vFile instanceof VirtualFileWindow)
	{
		vFile = ((VirtualFileWindow) vFile).getDelegate();
	}
	if(vFile == null || !ProjectRootManager.getInstance(file.getProject()).getFileIndex().isInSourceContent(vFile))
	{
		return EmptyRunnable.INSTANCE;
	}

	return new Runnable()
	{
		@Override
		public void run()
		{
			optimizeImports(file);
		}
	};
}
 
Example 13
Project: consulo   File: ProgressWindow.java   Source Code and License 6 votes vote down vote up
@Override
public synchronized void stop() {
  LOG.assertTrue(!myStoppedAlready);

  super.stop();

  UIUtil.invokeLaterIfNeeded(() -> {
    boolean wasShowing = isDialogShowing();
    if (myDialog != null) {
      myDialog.hide();
    }

    synchronized (this) {
      myStoppedAlready = true;
    }

    Disposer.dispose(this);
  });

  SwingUtilities.invokeLater(EmptyRunnable.INSTANCE); // Just to give blocking dispatching a chance to go out.
}
 
Example 14
Project: consulo   File: CoreCommandProcessor.java   Source Code and License 6 votes vote down vote up
@Override
@Nullable
public Object startCommand(@Nonnull final Project project,
                           @Nls final String name,
                           final Object groupId,
                           @Nonnull final UndoConfirmationPolicy undoConfirmationPolicy) {
  ApplicationManager.getApplication().assertIsDispatchThread();
  if (project.isDisposed()) return null;

  if (CommandLog.LOG.isDebugEnabled()) {
    CommandLog.LOG.debug("startCommand: name = " + name + ", groupId = " + groupId);
  }

  if (myCurrentCommand != null) {
    return null;
  }

  Document document = groupId instanceof Ref && ((Ref)groupId).get() instanceof Document ? (Document)((Ref)groupId).get() : null;
  myCurrentCommand = new CommandDescriptor(EmptyRunnable.INSTANCE, project, name, groupId, undoConfirmationPolicy, true, document);
  fireCommandStarted();
  return myCurrentCommand;
}
 
Example 15
Project: consulo   File: EnforcedPlainTextFileTypeManager.java   Source Code and License 6 votes vote down vote up
private static void fireRootsChanged(final Collection<VirtualFile> files, final boolean isAdded) {
  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    @Override
    public void run() {
      for (Project project : ProjectManager.getInstance().getOpenProjects()) {
        ProjectRootManagerEx.getInstanceEx(project).makeRootsChange(EmptyRunnable.getInstance(), false, true);
        ProjectPlainTextFileTypeManager projectPlainTextFileTypeManager = ProjectPlainTextFileTypeManager.getInstance(project);
        for (VirtualFile file : files) {
          if (projectPlainTextFileTypeManager.hasProjectContaining(file)) {
            if (isAdded) {
              projectPlainTextFileTypeManager.addFile(file);
            }
            else {
              projectPlainTextFileTypeManager.removeFile(file);
            }
          }
        }
      }
    }
  });
}
 
Example 16
Project: intellij-ce-playground   File: TimingLog.java   Source Code and License 5 votes vote down vote up
public static Runnable startActivity(final String name) {
  if (!LOG.isDebugEnabled()) {
    return EmptyRunnable.INSTANCE;
  }
  final long start = System.currentTimeMillis();
  return new Runnable() {
    @Override
    public void run() {
      LOG.debug(name + " in " + (System.currentTimeMillis() - start) + "ms");
    }
  };
}
 
Example 17
Project: intellij-ce-playground   File: Extractor.java   Source Code and License 5 votes vote down vote up
@Override
public void dispose() {
  // wait until all our submitted tasks are executed
  try {
    myExecutor.submit(EmptyRunnable.getInstance()).get();
  }
  catch (Exception ignored) {
  }
}
 
Example 18
Project: intellij-ce-playground   File: IdeaProjectModelModifier.java   Source Code and License 5 votes vote down vote up
@Override
public Promise<Void> changeLanguageLevel(@NotNull Module module, @NotNull LanguageLevel level) {
  final LanguageLevel moduleLevel = LanguageLevelModuleExtensionImpl.getInstance(module).getLanguageLevel();
  if (moduleLevel != null && JavaSdkUtil.isLanguageLevelAcceptable(myProject, module, level)) {
    final ModifiableRootModel rootModel = ModuleRootManager.getInstance(module).getModifiableModel();
    rootModel.getModuleExtension(LanguageLevelModuleExtension.class).setLanguageLevel(level);
    rootModel.commit();
  }
  else {
    LanguageLevelProjectExtension.getInstance(myProject).setLanguageLevel(level);
    ProjectRootManagerEx.getInstanceEx(myProject).makeRootsChange(EmptyRunnable.INSTANCE, false, true);
  }
  return Promise.DONE;
}
 
Example 19
Project: intellij-ce-playground   File: DirectoryIndexTest.java   Source Code and License 5 votes vote down vote up
private void fireRootsChanged() {
  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    @Override
    public void run() {
      ProjectRootManagerEx.getInstanceEx(getProject()).makeRootsChange(EmptyRunnable.getInstance(), false, true);
    }
  });
}
 
Example 20
Project: intellij-ce-playground   File: CodeFragmentsTest.java   Source Code and License 5 votes vote down vote up
public void testDontRecreateFragmentPsi() {
  PsiExpressionCodeFragment fragment = JavaCodeFragmentFactory.getInstance(myProject).createExpressionCodeFragment("a", null, null, true);
  VirtualFile file = fragment.getViewProvider().getVirtualFile();
  assertInstanceOf(file, LightVirtualFile.class);

  ProjectRootManagerEx.getInstanceEx(getProject()).makeRootsChange(EmptyRunnable.getInstance(), false, true);

  assertSame(fragment, PsiManager.getInstance(myProject).findFile(file));
  assertTrue(fragment.isValid());
}
 
Example 21
Project: intellij-ce-playground   File: PutSourceItemIntoParentAndLinkViaManifestAction.java   Source Code and License 5 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
  final List<PackagingSourceItem> items = mySourceItemsTree.getSelectedItems();
  ParentElementsInfo parentsInfo = findParentAndGrandParent(myArtifactEditor.getArtifact());
  if (parentsInfo == null) {
    return;
  }

  final Artifact artifact = parentsInfo.getGrandparentArtifact();
  final ArtifactEditorContext context = myArtifactEditor.getContext();
  //todo[nik] improve
  final Runnable emptyRunnable = EmptyRunnable.getInstance();
  context.editLayout(artifact, emptyRunnable);
  context.editLayout(parentsInfo.getParentArtifact(), emptyRunnable);
  parentsInfo = findParentAndGrandParent(myArtifactEditor.getArtifact());//find elements under modifiable root
  if (parentsInfo == null) {
    return;
  }

  final CompositePackagingElement<?> grandParent = parentsInfo.getGrandparentElement();
  final List<String> classpath = new ArrayList<String>();
  context.editLayout(artifact, new Runnable() {
    @Override
    public void run() {
      for (PackagingSourceItem item : items) {
        final List<? extends PackagingElement<?>> elements = item.createElements(context);
        grandParent.addOrFindChildren(elements);
        classpath.addAll(ManifestFileUtil.getClasspathForElements(elements, context, artifact.getArtifactType()));
      }
    }
  });

  final ArtifactEditor parentArtifactEditor = context.getOrCreateEditor(parentsInfo.getParentArtifact());
  parentArtifactEditor.addToClasspath(parentsInfo.getParentElement(), classpath);
  ((ArtifactEditorImpl)context.getOrCreateEditor(parentsInfo.getGrandparentArtifact())).rebuildTries();
}
 
Example 22
Project: intellij-ce-playground   File: ProjectRootManagerImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void rootSetChanged(final RootProvider wrapper) {
  if (myInsideRootsChange) return;
  myInsideRootsChange = true;
  try {
    makeRootsChange(EmptyRunnable.INSTANCE, false, true);
  }
  finally {
    myInsideRootsChange = false;
  }
}
 
Example 23
Project: intellij-ce-playground   File: GraphTableModel.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
public final Object getValueAt(int rowIndex, int columnIndex) {
  if (rowIndex >= getRowCount() - 1 && canRequestMore()) {
    requestToLoadMore(EmptyRunnable.INSTANCE);
  }

  VcsShortCommitDetails data = getShortDetails(rowIndex);
  switch (columnIndex) {
    case ROOT_COLUMN:
      return getRoot(rowIndex);
    case COMMIT_COLUMN:
      return getCommitColumnCell(rowIndex, data);
    case AUTHOR_COLUMN:
      if (data == null) {
        return "";
      }
      else {
        String authorString = data.getAuthor().getName();
        if (authorString.isEmpty()) authorString = data.getAuthor().getEmail();
        return authorString + (data.getAuthor().equals(data.getCommitter()) ? "" : "*");
      }
    case DATE_COLUMN:
      if (data == null || data.getAuthorTime() < 0) {
        return "";
      }
      else {
        return DateFormatUtil.formatDateTime(data.getAuthorTime());
      }
    default:
      throw new IllegalArgumentException("columnIndex is " + columnIndex + " > " + (COLUMN_COUNT - 1));
  }
}
 
Example 24
Project: intellij-ce-playground   File: LightPlatformTestCase.java   Source Code and License 5 votes vote down vote up
@Override
public final void runBare() throws Throwable {
  if (!shouldRunTest()) {
    return;
  }

  TestRunnerUtil.replaceIdeEventQueueSafely();
  EdtTestUtil.runInEdtAndWait(new ThrowableRunnable<Throwable>() {
    @Override
    public void run() throws Throwable {
      try {
        ourTestThread = Thread.currentThread();
        startRunAndTear();
      }
      finally {
        ourTestThread = null;
        try {
          Application application = ApplicationManager.getApplication();
          if (application instanceof ApplicationEx) {
            PlatformTestCase.cleanupApplicationCaches(ourProject);
          }
          resetAllFields();
        }
        catch (Throwable e) {
          e.printStackTrace();
        }
      }
    }
  });

  // just to make sure all deferred Runnables to finish
  SwingUtilities.invokeAndWait(EmptyRunnable.getInstance());

  if (IdeaLogger.ourErrorsOccurred != null) {
    throw IdeaLogger.ourErrorsOccurred;
  }
}
 
Example 25
Project: intellij-ce-playground   File: ProgressWindow.java   Source Code and License 5 votes vote down vote up
@Override
public synchronized void stop() {
  LOG.assertTrue(!myStoppedAlready);

  super.stop();

  if (isDialogShowing()) {
    if (myFocusTrackback != null) {
      myFocusTrackback.setWillBeSheduledForRestore();
    }
  }

  UIUtil.invokeLaterIfNeeded(new Runnable() {
    @Override
    public void run() {
      boolean wasShowing = isDialogShowing();
      if (myDialog != null) {
        myDialog.hide();
      }

      if (myFocusTrackback != null) {
        if (wasShowing) {
          myFocusTrackback.restoreFocus();
        }
        else {
          myFocusTrackback.consume();
        }
      }

      synchronized (ProgressWindow.this) {
        myStoppedAlready = true;
      }

      Disposer.dispose(ProgressWindow.this);
    }
  });

  SwingUtilities.invokeLater(EmptyRunnable.INSTANCE); // Just to give blocking dispatching a chance to go out.
}
 
Example 26
Project: intellij-ce-playground   File: CustomizeDesktopEntryStep.java   Source Code and License 5 votes vote down vote up
public CustomizeDesktopEntryStep(String iconPath) {
  setLayout(new BorderLayout());

  JPanel panel = createBigButtonPanel(createSmallBorderLayout(), myCreateEntryCheckBox, EmptyRunnable.INSTANCE);
  panel.setBorder(createSmallEmptyBorder());

  JPanel buttonPanel = new JPanel(new GridBagLayout());
  buttonPanel.setOpaque(false);

  GridBag gbc =
    new GridBag().setDefaultAnchor(GridBagConstraints.WEST).setDefaultFill(GridBagConstraints.HORIZONTAL).setDefaultWeightX(1);

  myCreateEntryCheckBox.setOpaque(false);
  buttonPanel.add(myCreateEntryCheckBox, gbc.nextLine());

  myGlobalEntryCheckBox.setOpaque(false);
  gbc.nextLine().insets.left = UIUtil.PANEL_REGULAR_INSETS.left;
  buttonPanel.add(myGlobalEntryCheckBox, gbc);

  panel.add(buttonPanel, BorderLayout.NORTH);

  JLabel label = new JLabel(IconLoader.getIcon(iconPath));
  label.setVerticalAlignment(JLabel.TOP);
  panel.add(label, BorderLayout.CENTER);

  add(panel, BorderLayout.CENTER);

  myCreateEntryCheckBox.addChangeListener(new ChangeListener() {
    @Override
    public void stateChanged(ChangeEvent e) {
      myGlobalEntryCheckBox.setEnabled(myCreateEntryCheckBox.isSelected());
      myGlobalEntryCheckBox.setSelected(myCreateEntryCheckBox.isSelected() && !PathManager.getHomePath().startsWith("/home"));
    }
  });

  myCreateEntryCheckBox.setSelected(true);
}
 
Example 27
Project: intellij-ce-playground   File: ApplicationImplTest.java   Source Code and License 5 votes vote down vote up
public void testRunProcessWithProgressSynchronouslyInReadActionWithPendingWriteAction() throws Throwable {
  SwingUtilities.invokeLater(() -> ApplicationManager.getApplication().runWriteAction(EmptyRunnable.getInstance()));
  boolean result = ((ApplicationEx)ApplicationManager.getApplication())
    .runProcessWithProgressSynchronouslyInReadAction(getProject(), "title", true, "cancel", null, () -> TimeoutUtil.sleep(10000));
  assertTrue(result);
  UIUtil.dispatchAllInvocationEvents();
  if (exception != null) throw exception;
}
 
Example 28
Project: intellij-ce-playground   File: ProgressIndicatorTest.java   Source Code and License 5 votes vote down vote up
public void testProgressPerformance() {
  PlatformTestUtil.startPerformanceTest("progress", 100, new ThrowableRunnable() {
    @Override
    public void run() throws Throwable {
      EmptyProgressIndicator indicator = new EmptyProgressIndicator();
      for (int i=0;i<100000;i++) {
        ProgressManager.getInstance().executeProcessUnderProgress(EmptyRunnable.getInstance(), indicator);
      }
    }
  }).assertTiming();
}
 
Example 29
Project: intellij-ce-playground   File: NewMappings.java   Source Code and License 5 votes vote down vote up
public void activateActiveVcses() {
  synchronized (myLock) {
    if (myActivated) return;
    myActivated = true;
  }
  keepActiveVcs(EmptyRunnable.getInstance());
  mappingsChanged();
}
 
Example 30
Project: intellij-ce-playground   File: AbstractVcsTestCase.java   Source Code and License 5 votes vote down vote up
protected void tearDownProject() throws Exception {
  if (myProject != null) {
    ((ChangeListManagerImpl)ChangeListManager.getInstance(myProject)).stopEveryThingIfInTestMode();
    CommittedChangesCache.getInstance(myProject).clearCaches(EmptyRunnable.INSTANCE);
    myProject = null;
  }
  if (myProjectFixture != null) {
    myProjectFixture.tearDown();
    myProjectFixture = null;
  }
}
 
Example 31
Project: intellij-ce-playground   File: OptimizeImportsProcessor.java   Source Code and License 5 votes vote down vote up
private void retrieveAndStoreNotificationInfo(@NotNull Runnable runnable) {
  if (runnable instanceof ImportOptimizer.CollectingInfoRunnable) {
    String optimizerMessage = ((ImportOptimizer.CollectingInfoRunnable)runnable).getUserNotificationInfo();
    myOptimizerNotifications.add(optimizerMessage != null ? new NotificationInfo(optimizerMessage) : NOTHING_CHANGED_NOTIFICATION);
  }
  else if (runnable == EmptyRunnable.getInstance()) {
    myOptimizerNotifications.add(NOTHING_CHANGED_NOTIFICATION);
  }
  else {
    myOptimizerNotifications.add(SOMETHING_CHANGED_WITHOUT_MESSAGE_NOTIFICATION);
  }
}
 
Example 32
Project: intellij   File: PluginUtils.java   Source Code and License 5 votes vote down vote up
/** Install and/or enable the given plugins. Does nothing for plugins already enabled. */
public static void installOrEnablePlugins(Set<String> pluginIds) {
  Set<String> toInstall = new HashSet<>();
  for (String id : pluginIds) {
    if (isPluginInstalled(id)) {
      PluginManager.enablePlugin(id);
    } else {
      toInstall.add(id);
    }
  }
  if (!toInstall.isEmpty()) {
    PluginsAdvertiser.installAndEnablePlugins(toInstall, EmptyRunnable.INSTANCE);
  }
}
 
Example 33
Project: tools-idea   File: TimingLog.java   Source Code and License 5 votes vote down vote up
public static Runnable startActivity(final String name) {
  if (!LOG.isDebugEnabled()) {
    return EmptyRunnable.INSTANCE;
  }
  final long start = System.currentTimeMillis();
  return new Runnable() {
    @Override
    public void run() {
      LOG.debug(name + " in " + (System.currentTimeMillis() - start) + "ms");
    }
  };
}
 
Example 34
Project: tools-idea   File: PutSourceItemIntoParentAndLinkViaManifestAction.java   Source Code and License 5 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
  final List<PackagingSourceItem> items = mySourceItemsTree.getSelectedItems();
  ParentElementsInfo parentsInfo = findParentAndGrandParent(myArtifactEditor.getArtifact());
  if (parentsInfo == null) {
    return;
  }

  final Artifact artifact = parentsInfo.getGrandparentArtifact();
  final ArtifactEditorContext context = myArtifactEditor.getContext();
  //todo[nik] improve
  final Runnable emptyRunnable = EmptyRunnable.getInstance();
  context.editLayout(artifact, emptyRunnable);
  context.editLayout(parentsInfo.getParentArtifact(), emptyRunnable);
  parentsInfo = findParentAndGrandParent(myArtifactEditor.getArtifact());//find elements under modifiable root
  if (parentsInfo == null) {
    return;
  }

  final CompositePackagingElement<?> grandParent = parentsInfo.getGrandparentElement();
  final List<String> classpath = new ArrayList<String>();
  context.editLayout(artifact, new Runnable() {
    @Override
    public void run() {
      for (PackagingSourceItem item : items) {
        final List<? extends PackagingElement<?>> elements = item.createElements(context);
        grandParent.addOrFindChildren(elements);
        classpath.addAll(ManifestFileUtil.getClasspathForElements(elements, context, artifact.getArtifactType()));
      }
    }
  });

  final ArtifactEditor parentArtifactEditor = context.getOrCreateEditor(parentsInfo.getParentArtifact());
  parentArtifactEditor.addToClasspath(parentsInfo.getParentElement(), classpath);
  ((ArtifactEditorImpl)context.getOrCreateEditor(parentsInfo.getGrandparentArtifact())).rebuildTries();
}
 
Example 35
Project: tools-idea   File: ProjectConfigurable.java   Source Code and License 5 votes vote down vote up
private void createUIComponents() {
  myLanguageLevelCombo = new LanguageLevelCombo();
  final JTextField textField = new JTextField();
  final FileChooserDescriptor outputPathsChooserDescriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor();
  InsertPathAction.addTo(textField, outputPathsChooserDescriptor);
  outputPathsChooserDescriptor.setHideIgnored(false);
  BrowseFilesListener listener = new BrowseFilesListener(textField, "", ProjectBundle.message("project.compiler.output"), outputPathsChooserDescriptor);
  myProjectCompilerOutput = new FieldPanel(textField, null, null, listener, EmptyRunnable.getInstance());
  FileChooserFactory.getInstance().installFileCompletion(myProjectCompilerOutput.getTextField(), outputPathsChooserDescriptor, true, null);
}
 
Example 36
Project: tools-idea   File: ProjectRootManagerImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void rootSetChanged(final RootProvider wrapper) {
  if (myInsideRootsChange) return;
  myInsideRootsChange = true;
  try {
    makeRootsChange(EmptyRunnable.INSTANCE, false, true);
  }
  finally {
    myInsideRootsChange = false;
  }
}
 
Example 37
Project: tools-idea   File: NewMappings.java   Source Code and License 5 votes vote down vote up
public void activateActiveVcses() {
  synchronized (myLock) {
    if (myActivated) return;
    myActivated = true;
  }
  keepActiveVcs(EmptyRunnable.getInstance());
  mappingsChanged();
}
 
Example 38
Project: tools-idea   File: ProjectFileExclusionManagerImpl.java   Source Code and License 5 votes vote down vote up
private static void fireRootsChange(final Project project) {
  ApplicationManager.getApplication().runWriteAction(new Runnable(){
    @Override
    public void run() {
      ProjectRootManagerEx.getInstanceEx(project).makeRootsChange(EmptyRunnable.getInstance(), false, true);
    }
  });
}
 
Example 39
Project: tools-idea   File: SkeletonBuilderTest.java   Source Code and License 5 votes vote down vote up
public void testTwoReposStart() throws Exception {
  final BigTableTableModel model = new BigTableTableModel(Collections.<ColumnInfo>emptyList(), EmptyRunnable.getInstance());
  model.setCommitIdxInterval(2);
  model.setNumEventsInGroup(2);
  final VirtualFile[] arr = new VirtualFile[] {new MyVf(), new MyVf()};
  model.setRootsHolder(new RootsHolder(Arrays.asList(arr)));
  model.clear(true, true);

  final List<List<AbstractHash>> parentsOne = new ArrayList<List<AbstractHash>>();
  final List<List<AbstractHash>> parentsTwo = new ArrayList<List<AbstractHash>>();
  final List<CommitI> one = new ArrayList<CommitI>(2);
  final List<CommitI> two = new ArrayList<CommitI>(2);
  CommitI first = new MultipleRepositoryCommitDecorator(new Commit("1", 1, new Ref<Integer>(-1)), 0);
  one.add(first);

  CommitI second = new MultipleRepositoryCommitDecorator(new Commit("0", 2, new Ref<Integer>(-1)), 1);
  two.add(second);

  parentsOne.add(Collections.singletonList(AbstractHash.create("2")));

  parentsTwo.add(Collections.singletonList(AbstractHash.create("1")));

  model.setStrategy(new CommitGroupingStrategy() {
    @Override
    public String getGroupName(CommitI commit) {
      if ("1".equals(commit.getHash().toString())) return "Header 1";
      return "Header 2";
    }

    @Override
    public void beforeStart() {
    }
  });

  model.appendData(one, parentsOne);
  model.appendData(two, parentsTwo);
  System.out.println("2");
}
 
Example 40
Project: intellij-haxe   File: HaxeImportOptimizer.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
public Runnable processFile(final PsiFile file) {
  VirtualFile vFile = file.getVirtualFile();
  if (vFile instanceof VirtualFileWindow) vFile = ((VirtualFileWindow)vFile).getDelegate();
  if (vFile == null || !ProjectRootManager.getInstance(file.getProject()).getFileIndex().isInSourceContent(vFile)) {
    return EmptyRunnable.INSTANCE;
  }

  return () -> optimizeImports(file);
}
 
Example 41
Project: consulo   File: ProjectRootManagerImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void rootSetChanged(final RootProvider wrapper) {
  if (myInsideRootsChange) return;
  myInsideRootsChange = true;
  try {
    makeRootsChange(EmptyRunnable.INSTANCE, false, true);
  }
  finally {
    myInsideRootsChange = false;
  }
}
 
Example 42
Project: consulo   File: ServersTreeStructure.java   Source Code and License 5 votes vote down vote up
@Override
public void startServer(@Nonnull Executor executor) {
  ServerConnection<?> connection = getConnection();
  if (connection != null) {
    connection.computeDeployments(EmptyRunnable.INSTANCE);
  }
}
 
Example 43
Project: consulo   File: GraphTableModel.java   Source Code and License 5 votes vote down vote up
@Nonnull
@Override
public final Object getValueAt(int rowIndex, int columnIndex) {
  if (rowIndex >= getRowCount() - 1 && canRequestMore()) {
    requestToLoadMore(EmptyRunnable.INSTANCE);
  }

  VcsShortCommitDetails data = getShortDetails(rowIndex);
  switch (columnIndex) {
    case ROOT_COLUMN:
      return getRoot(rowIndex);
    case COMMIT_COLUMN:
      return new GraphCommitCell(data.getSubject(), getRefsAtRow(rowIndex),
                                 myDataPack.getVisibleGraph().getRowInfo(rowIndex).getPrintElements());
    case AUTHOR_COLUMN:
      String authorString = VcsUserUtil.getShortPresentation(data.getAuthor());
      return authorString + (VcsUserUtil.isSamePerson(data.getAuthor(), data.getCommitter()) ? "" : "*");
    case DATE_COLUMN:
      if (data.getAuthorTime() < 0) {
        return "";
      }
      else {
        return DateFormatUtil.formatDateTime(data.getAuthorTime());
      }
    default:
      throw new IllegalArgumentException("columnIndex is " + columnIndex + " > " + (COLUMN_COUNT - 1));
  }
}
 
Example 44
Project: consulo   File: AsyncEditorLoader.java   Source Code and License 5 votes vote down vote up
private Future<Runnable> scheduleLoading() {
  PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(myProject);
  long startStamp = myEditor.getDocument().getModificationStamp();
  return ourExecutor.submit(() -> {
    Ref<Runnable> ref = new Ref<>();
    try {
      while (!myEditorComponent.isDisposed()) {
        ProgressIndicatorUtils.runWithWriteActionPriority(
                () -> ref.set(psiDocumentManager.commitAndRunReadAction(() -> myProject.isDisposed() ? EmptyRunnable.INSTANCE
                                                                                                     : myTextEditor.loadEditorInBackground())),
                new ProgressIndicatorBase()
        );
        Runnable continuation = ref.get();
        if (continuation != null) {
          invokeLater(() -> {
            if (startStamp == myEditor.getDocument().getModificationStamp()) loadingFinished(continuation);
            else if (!myProject.isDisposed() && !myEditorComponent.isDisposed()) scheduleLoading();
          });
          return continuation;
        }
        ProgressIndicatorUtils.yieldToPendingWriteActions();
      }
    }
    finally {
      if (ref.isNull()) invokeLater(() -> loadingFinished(null));
    }
    return null;
  });
}
 
Example 45
Project: consulo   File: NewMappings.java   Source Code and License 5 votes vote down vote up
public void activateActiveVcses() {
  synchronized (myLock) {
    if (myActivated) return;
    myActivated = true;
  }
  keepActiveVcs(EmptyRunnable.getInstance());
  mappingsChanged();
}
 
Example 46
Project: consulo   File: CallbackData.java   Source Code and License 5 votes vote down vote up
@Nonnull
private static CallbackData createSilent(@Nonnull Project project, @Nonnull InvokeAfterUpdateMode mode, @Nonnull Runnable afterUpdate) {
  Consumer<Runnable> callbackCaller = mode.isCallbackOnAwt()
                                      ? ApplicationManager.getApplication()::invokeLater
                                      : ApplicationManager.getApplication()::executeOnPooledThread;
  Runnable callback = () -> {
    logUpdateFinished(project, mode);
    if (!project.isDisposed()) afterUpdate.run();
  };
  return new CallbackData(() -> callbackCaller.accept(callback), EmptyRunnable.INSTANCE);
}
 
Example 47
Project: consulo   File: OptimizeImportsProcessor.java   Source Code and License 5 votes vote down vote up
private void retrieveAndStoreNotificationInfo(@Nonnull Runnable runnable) {
  if (runnable instanceof ImportOptimizer.CollectingInfoRunnable) {
    String optimizerMessage = ((ImportOptimizer.CollectingInfoRunnable)runnable).getUserNotificationInfo();
    myOptimizerNotifications.add(optimizerMessage != null ? new NotificationInfo(optimizerMessage) : NOTHING_CHANGED_NOTIFICATION);
  }
  else if (runnable == EmptyRunnable.getInstance()) {
    myOptimizerNotifications.add(NOTHING_CHANGED_NOTIFICATION);
  }
  else {
    myOptimizerNotifications.add(SOMETHING_CHANGED_WITHOUT_MESSAGE_NOTIFICATION);
  }
}
 
Example 48
Project: intellij-ce-playground   File: ThreesideBinaryDiffViewer.java   Source Code and License 4 votes vote down vote up
@Override
@NotNull
protected Runnable performRediff(@NotNull final ProgressIndicator indicator) {
  return EmptyRunnable.INSTANCE;
}
 
Example 49
Project: intellij-ce-playground   File: RemoteServerConnectAction.java   Source Code and License 4 votes vote down vote up
@Override
protected void doActionPerformed(ServersTreeStructure.RemoteServerNode node) {
  ServerConnectionManager.getInstance().getOrCreateConnection(node.getValue()).connect(EmptyRunnable.INSTANCE);
}
 
Example 50
Project: intellij-ce-playground   File: PlatformTestCase.java   Source Code and License 4 votes vote down vote up
private static void waitForAllLaters() throws InterruptedException, InvocationTargetException {
  for (int i = 0; i < 3; i++) {
    SwingUtilities.invokeAndWait(EmptyRunnable.getInstance());
  }
}
 
Example 51
Project: intellij-ce-playground   File: ProgressWindow.java   Source Code and License 4 votes vote down vote up
@Override
public void startBlocking() {
  startBlocking(EmptyRunnable.getInstance());
}
 
Example 52
Project: intellij-ce-playground   File: UndoManagerImpl.java   Source Code and License 4 votes vote down vote up
@TestOnly
private void flushMergers() {
  // Run dummy command in order to flush all mergers...
  CommandProcessor.getInstance()
    .executeCommand(myProject, EmptyRunnable.getInstance(), CommonBundle.message("drop.undo.history.command.name"), null);
}
 
Example 53
Project: intellij-ce-playground   File: PopupFactoryImpl.java   Source Code and License 4 votes vote down vote up
@NotNull
@Override
public ListPopup createConfirmation(String title, final String yesText, String noText, final Runnable onYes, int defaultOptionIndex) {
  return createConfirmation(title, yesText, noText, onYes, EmptyRunnable.getInstance(), defaultOptionIndex);
}
 
Example 54
Project: intellij-ce-playground   File: PushedFilePropertiesUpdaterImpl.java   Source Code and License 4 votes vote down vote up
private void doPushAll(final FilePropertyPusher[] pushers) {
  Module[] modules = ApplicationManager.getApplication().runReadAction(new Computable<Module[]>() {
    @Override
    public Module[] compute() {
      return ModuleManager.getInstance(myProject).getModules();
    }
  });

  List<Runnable> tasks = new ArrayList<Runnable>();

  for (final Module module : modules) {
    Runnable iteration = ApplicationManager.getApplication().runReadAction(new Computable<Runnable>() {
      @Override
      public Runnable compute() {
        if (module.isDisposed()) return EmptyRunnable.INSTANCE;
        ProgressManager.checkCanceled();

        final Object[] moduleValues = new Object[pushers.length];
        for (int i = 0; i < moduleValues.length; i++) {
          moduleValues[i] = pushers[i].getImmediateValue(module);
        }

        final ModuleFileIndex fileIndex = ModuleRootManager.getInstance(module).getFileIndex();
        return new Runnable() {
          @Override
          public void run() {
            fileIndex.iterateContent(new ContentIterator() {
              @Override
              public boolean processFile(final VirtualFile fileOrDir) {
                applyPushersToFile(fileOrDir, pushers, moduleValues);
                return true;
              }
            });
          }
        };
      }
    });
    tasks.add(iteration);
  }

  invoke2xConcurrentlyIfPossible(tasks);
}
 
Example 55
Project: intellij-ce-playground   File: SafeDeleteRefactoringImpl.java   Source Code and License 4 votes vote down vote up
SafeDeleteRefactoringImpl(Project project, PsiElement[] elements) {
  super(SafeDeleteProcessor.createInstance(project, EmptyRunnable.INSTANCE, elements, true, true));
}
 
Example 56
Project: intellij-ce-playground   File: JavaFxImportsOptimizer.java   Source Code and License 4 votes vote down vote up
@NotNull
@Override
public Runnable processFile(final PsiFile file) {
  VirtualFile vFile = file.getVirtualFile();
  if (vFile instanceof VirtualFileWindow) vFile = ((VirtualFileWindow)vFile).getDelegate();
  final Project project = file.getProject();
  if (vFile == null || !ProjectRootManager.getInstance(project).getFileIndex().isInSourceContent(vFile)) {
    return EmptyRunnable.INSTANCE;
  }
  final List<Pair<String, Boolean>> names = new ArrayList<Pair<String, Boolean>>();
  collectNamesToImport(names, (XmlFile)file);
  Collections.sort(names, new Comparator<Pair<String, Boolean>>() {
    @Override
    public int compare(Pair<String, Boolean> o1, Pair<String, Boolean> o2) {
      return StringUtil.compare(o1.first, o2.first, true);
    }
  });
  final CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(project);
  final List<Pair<String, Boolean>> sortedNames = ImportHelper.sortItemsAccordingToSettings(names, settings);
  final HashSet<String> onDemand = new HashSet<String>();
  ImportHelper.collectOnDemandImports(sortedNames, onDemand, settings);
  final Set<String> imported = new HashSet<String>();
  final List<String> imports = new ArrayList<String>();
  for (Pair<String, Boolean> pair : sortedNames) {
    final String qName = pair.first;
    final String packageName = StringUtil.getPackageName(qName);
    if (imported.contains(packageName) || imported.contains(qName)) {
      continue;
    }
    if (onDemand.contains(packageName)) {
      imported.add(packageName);
      imports.add("<?import " + packageName + ".*?>");
    } else {
      imported.add(qName);
      imports.add("<?import " + qName + "?>");
    }
  }
  final PsiFileFactory factory = PsiFileFactory.getInstance(file.getProject());
  
  final XmlFile dummyFile = (XmlFile)factory.createFileFromText("_Dummy_.fxml", StdFileTypes.XML, StringUtil.join(imports, "\n"));
  final XmlDocument document = dummyFile.getDocument();
  final XmlProlog newImportList = document.getProlog();
  if (newImportList == null) return EmptyRunnable.getInstance();
  return new Runnable() {
    @Override
    public void run() {
      final XmlDocument xmlDocument = ((XmlFile)file).getDocument();
      final XmlProlog prolog = xmlDocument.getProlog();
      if (prolog != null) {
        final Collection<XmlProcessingInstruction> instructions = PsiTreeUtil.findChildrenOfType(prolog, XmlProcessingInstruction.class);
        for (final XmlProcessingInstruction instruction : instructions) {
          final ASTNode node = instruction.getNode();
          final ASTNode nameNode = node.findChildByType(XmlTokenType.XML_NAME);
          if (nameNode != null && nameNode.getText().equals("import")) {
            instruction.delete();
          }
        }
        prolog.add(newImportList);
      } else {
        document.addBefore(newImportList, document.getRootTag());
      }
    }
  };
}
 
Example 57
Project: intellij-ce-playground   File: UpdateCopyrightAction.java   Source Code and License 4 votes vote down vote up
@Override
protected void analyze(@NotNull final Project project, @NotNull final AnalysisScope scope) {
  PropertiesComponent.getInstance().setValue(UPDATE_EXISTING_COPYRIGHTS, String.valueOf(myUpdateExistingCopyrightsCb.isSelected()), "true");
  final Map<PsiFile, Runnable> preparations = new LinkedHashMap<PsiFile, Runnable>();
  Task.Backgroundable task = new Task.Backgroundable(project, "Prepare Copyright...", true) {
    @Override
    public void run(@NotNull final ProgressIndicator indicator) {
      scope.accept(new PsiElementVisitor() {
        @Override
        public void visitFile(final PsiFile file) {
          if (indicator.isCanceled()) {
            return;
          }
          final Module module = ModuleUtilCore.findModuleForPsiElement(file);
          final UpdateCopyrightProcessor processor = new UpdateCopyrightProcessor(project, module, file);
          final Runnable runnable = processor.preprocessFile(file, myUpdateExistingCopyrightsCb.isSelected());
          if (runnable != EmptyRunnable.getInstance()) {
            preparations.put(file, runnable);
          }
        }
      });
    }

    @Override
    public void onSuccess() {
      if (!preparations.isEmpty()) {
        if (!FileModificationService.getInstance().preparePsiElementsForWrite(preparations.keySet())) return;
        final SequentialModalProgressTask progressTask = new SequentialModalProgressTask(project, UpdateCopyrightProcessor.TITLE, true);
        progressTask.setMinIterationTime(200);
        progressTask.setTask(new UpdateCopyrightSequentialTask(preparations, progressTask));
        CommandProcessor.getInstance().executeCommand(project, new Runnable() {
          @Override
          public void run() {
            CommandProcessor.getInstance().markCurrentCommandAsGlobal(project);
            ApplicationManager.getApplication().runWriteAction(new Runnable() {
              @Override
              public void run() {
                ProgressManager.getInstance().run(progressTask);
              }
            });
          }
        }, getTemplatePresentation().getText(), null);
      }
    }
  };

  ProgressManager.getInstance().run(task);
}
 
Example 58
Project: intellij-ce-playground   File: UpdateCopyrightProcessor.java   Source Code and License 4 votes vote down vote up
protected Runnable preprocessFile(final PsiFile file, final boolean allowReplacement) throws IncorrectOperationException
{
    VirtualFile vfile = file.getVirtualFile();
    if (vfile == null) return EmptyRunnable.getInstance();
    final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
    if (progressIndicator != null) {
        progressIndicator.setText2(vfile.getPresentableUrl());
    }
    Module mod = module;
    if (module == null)
    {
        mod = ProjectRootManager.getInstance(project).getFileIndex().getModuleForFile(vfile);
    }

    if (mod == null) return EmptyRunnable.getInstance();

    CopyrightProfile opts = CopyrightManager.getInstance(project).getCopyrightOptions(file);

    if (opts != null && FileTypeUtil.isSupportedFile(file))
    {
        logger.debug("process " + file);
        final UpdateCopyright update = UpdateCopyrightFactory.createUpdateCopyright(project, mod, file, opts);
        if (update == null) return EmptyRunnable.getInstance();
        update.prepare();

        if (update instanceof UpdatePsiFileCopyright && !((UpdatePsiFileCopyright)update).hasUpdates()) return EmptyRunnable.getInstance();

        return new Runnable() {
            public void run()
            {
                try
                {
                  if (update instanceof UpdatePsiFileCopyright) {
                    ((UpdatePsiFileCopyright)update).complete(allowReplacement);
                  } else {
                    update.complete();
                  }
                }
                catch (Exception e)
                {
                    logger.error(e);
                }
            }
        };
    }
    else
    {
        return EmptyRunnable.getInstance();
    }
}
 
Example 59
Project: intellij   File: BlazeJavaAbstractTestCaseConfigurationProducerTest.java   Source Code and License 4 votes vote down vote up
@Test
public void testConfigurationCreatedFromAbstractClass() {
  workspace.createPsiDirectory(new WorkspacePath("java/com/google/test"));
  PsiFile abstractClassFile =
      createAndIndexFile(
          new WorkspacePath("java/com/google/test/AbstractTestCase.java"),
          "package com.google.test;",
          "public abstract class AbstractTestCase {}");

  createAndIndexFile(
      new WorkspacePath("java/com/google/test/TestClass.java"),
      "package com.google.test;",
      "import com.google.test.AbstractTestCase;",
      "@org.junit.runner.RunWith(org.junit.runners.JUnit4.class)",
      "public class TestClass extends AbstractTestCase {",
      "  @org.junit.Test",
      "  public void testMethod1() {}",
      "  @org.junit.Test",
      "  public void testMethod2() {}",
      "}");

  PsiClass javaClass = ((PsiClassOwner) abstractClassFile).getClasses()[0];
  assertThat(javaClass).isNotNull();

  ConfigurationContext context = createContextFromPsi(abstractClassFile);
  List<ConfigurationFromContext> configurations = context.getConfigurationsFromContext();
  assertThat(configurations).hasSize(1);

  ConfigurationFromContext fromContext = configurations.get(0);
  assertThat(fromContext.isProducedBy(BlazeJavaAbstractTestCaseConfigurationProducer.class))
      .isTrue();
  assertThat(fromContext.getSourceElement()).isEqualTo(javaClass);

  RunConfiguration config = fromContext.getConfiguration();
  assertThat(config).isInstanceOf(BlazeCommandRunConfiguration.class);
  BlazeCommandRunConfiguration blazeConfig = (BlazeCommandRunConfiguration) config;
  assertThat(blazeConfig.getTarget()).isNull();
  assertThat(blazeConfig.getName()).isEqualTo("Choose subclass for AbstractTestCase");

  MockBlazeProjectDataBuilder builder = MockBlazeProjectDataBuilder.builder(workspaceRoot);
  builder.setTargetMap(
      TargetMapBuilder.builder()
          .addTarget(
              TargetIdeInfo.builder()
                  .setKind("java_test")
                  .setLabel("//java/com/google/test:TestClass")
                  .addSource(sourceRoot("java/com/google/test/TestClass.java"))
                  .build())
          .build());
  registerProjectService(
      BlazeProjectDataManager.class, new MockBlazeProjectDataManager(builder.build()));

  BlazeJavaAbstractTestCaseConfigurationProducer.chooseSubclass(
      fromContext, context, EmptyRunnable.INSTANCE);

  assertThat(blazeConfig.getTarget())
      .isEqualTo(TargetExpression.fromStringSafe("//java/com/google/test:TestClass"));
  assertThat(getTestFilterContents(blazeConfig))
      .isEqualTo(BlazeFlags.TEST_FILTER + "=com.google.test.TestClass#");
}
 
Example 60
Project: intellij   File: BlazeJavaAbstractTestCaseConfigurationProducerTest.java   Source Code and License 4 votes vote down vote up
@Test
public void testConfigurationCreatedFromMethodInAbstractClass() {
  PsiFile abstractClassFile =
      createAndIndexFile(
          new WorkspacePath("java/com/google/test/AbstractTestCase.java"),
          "package com.google.test;",
          "public abstract class AbstractTestCase {",
          "  @org.junit.Test",
          "  public void testMethod() {}",
          "}");

  createAndIndexFile(
      new WorkspacePath("java/com/google/test/TestClass.java"),
      "package com.google.test;",
      "import com.google.test.AbstractTestCase;",
      "import org.junit.runner.RunWith;",
      "import org.junit.runners.JUnit4;",
      "@org.junit.runner.RunWith(org.junit.runners.JUnit4.class)",
      "public class TestClass extends AbstractTestCase {}");

  PsiClass javaClass = ((PsiClassOwner) abstractClassFile).getClasses()[0];
  PsiMethod method = PsiUtils.findFirstChildOfClassRecursive(javaClass, PsiMethod.class);
  assertThat(method).isNotNull();

  ConfigurationContext context = createContextFromPsi(method);
  List<ConfigurationFromContext> configurations = context.getConfigurationsFromContext();
  assertThat(configurations).hasSize(1);

  ConfigurationFromContext fromContext = configurations.get(0);
  assertThat(fromContext.isProducedBy(BlazeJavaAbstractTestCaseConfigurationProducer.class))
      .isTrue();
  assertThat(fromContext.getSourceElement()).isEqualTo(method);

  RunConfiguration config = fromContext.getConfiguration();
  assertThat(config).isInstanceOf(BlazeCommandRunConfiguration.class);
  BlazeCommandRunConfiguration blazeConfig = (BlazeCommandRunConfiguration) config;
  assertThat(blazeConfig.getTarget()).isNull();
  assertThat(blazeConfig.getName()).isEqualTo("Choose subclass for AbstractTestCase.testMethod");

  MockBlazeProjectDataBuilder builder = MockBlazeProjectDataBuilder.builder(workspaceRoot);
  builder.setTargetMap(
      TargetMapBuilder.builder()
          .addTarget(
              TargetIdeInfo.builder()
                  .setKind("java_test")
                  .setLabel("//java/com/google/test:TestClass")
                  .addSource(sourceRoot("java/com/google/test/TestClass.java"))
                  .build())
          .build());
  registerProjectService(
      BlazeProjectDataManager.class, new MockBlazeProjectDataManager(builder.build()));

  BlazeJavaAbstractTestCaseConfigurationProducer.chooseSubclass(
      fromContext, context, EmptyRunnable.INSTANCE);

  assertThat(blazeConfig.getTarget())
      .isEqualTo(TargetExpression.fromStringSafe("//java/com/google/test:TestClass"));
  assertThat(getTestFilterContents(blazeConfig))
      .isEqualTo(BlazeFlags.TEST_FILTER + "=com.google.test.TestClass#testMethod$");
}