com.intellij.openapi.project.Project Java Examples

The following examples show how to use com.intellij.openapi.project.Project. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: GitToolBox   Author: zielu   File: BlameDetailsAction.java    License: Apache License 2.0 7 votes vote down vote up
private boolean isEnabled(@NotNull AnActionEvent e) {
  GitToolBoxConfig2 config = AppConfig.get();
  if (!config.getShowBlameWidget() && !config.getShowEditorInlineBlame()) {
    return false;
  }
  Project project = e.getData(CommonDataKeys.PROJECT);
  if (project == null) {
    return false;
  }
  Editor editor = e.getData(CommonDataKeys.EDITOR);
  if (editor != null) {
    Document document = editor.getDocument();
    if (!BlameUi.isDocumentInBulkUpdate(document)) {
      VirtualFile editorFile = FileDocumentManager.getInstance().getFile(document);
      if (editorFile != null) {
        return VirtualFileRepoCache.getInstance(project).isUnderGitRoot(editorFile);
      }
    }
  }
  return false;
}
 
Example #2
Source Project: intellij   Author: bazelbuild   File: ExternalLibraryManager.java    License: Apache License 2.0 6 votes vote down vote up
ExternalLibraryManager(Project project) {
  this.project = project;
  this.duringBlazeSync = false;
  this.libraries = ImmutableMap.of();
  AsyncVfsEventsPostProcessor.getInstance()
      .addListener(
          events -> {
            if (duringBlazeSync || libraries.isEmpty()) {
              return;
            }
            ImmutableList<VirtualFile> deletedFiles =
                events.stream()
                    .filter(VFileDeleteEvent.class::isInstance)
                    .map(VFileEvent::getFile)
                    .collect(toImmutableList());
            if (!deletedFiles.isEmpty()) {
              libraries.values().forEach(library -> library.removeInvalidFiles(deletedFiles));
            }
          },
          project);
}
 
Example #3
Source Project: idea-php-symfony2-plugin   Author: Haehnchen   File: TwigTypeResolveUtil.java    License: MIT License 6 votes vote down vote up
@NotNull
private static Collection<String> collectForArrayScopeVariablesFoo(@NotNull Project project, @NotNull Collection<String> typeName, @NotNull PsiVariable psiVariable) {
    Collection<String> previousElements = psiVariable.getTypes();

    String[] strings = typeName.toArray(new String[typeName.size()]);

    for (int i = 1; i <= strings.length - 1; i++ ) {
        previousElements = resolveTwigMethodName(project, previousElements, strings[i]);

        // we can stop on empty list
        if(previousElements.size() == 0) {
            return Collections.emptyList();
        }
    }

    return previousElements;
}
 
Example #4
Source Project: idea-php-symfony2-plugin   Author: Haehnchen   File: DotEnvUtil.java    License: MIT License 6 votes vote down vote up
/**
 * Provide targets for "%env(FOOBAR)%"
 *
 * @param parameter "%env(FOOBAR)%", "%env(resolve:DB)%"
 */
@NotNull
public static Collection<PsiElement> getEnvironmentVariableTargetsForParameter(@NotNull Project project, @NotNull String parameter) {
    if(parameter.length() < 7 || !parameter.startsWith("%env(") || !parameter.endsWith(")%")) {
        return Collections.emptyList();
    }

    String parameterName = parameter.substring(5, parameter.length() - 2);

    // https://github.com/symfony/symfony/pull/23901 => RegisterEnvVarProcessorsPass
    // '%env(int:DATABASE_PORT)%'
    // '%env(resolve:int:foo:DB)%'
    Matcher matcher = Pattern.compile("^[\\w-_^:]+:(.*)$", Pattern.MULTILINE).matcher(parameterName);
    if(matcher.find()){
        parameterName = matcher.group(1);
    }

    return DotEnvUtil.getEnvironmentVariableTargets(project, parameterName);
}
 
Example #5
Source Project: consulo-csharp   Author: consulo   File: OperatorsProvider.java    License: Apache License 2.0 6 votes vote down vote up
private static void buildOperatorsForDelegates(Consumer<PsiElement> consumer, Project project, CSharpTypeDeclaration typeDeclaration, DotNetTypeRef selfTypeRef)
{
	for(IElementType elementType : new IElementType[]{
			CSharpTokens.PLUS,
			CSharpTokens.MINUS
	})
	{
		CSharpLightMethodDeclarationBuilder builder = new CSharpLightMethodDeclarationBuilder(project);
		builder.setOperator(elementType);

		builder.withParent(typeDeclaration);

		builder.withReturnType(selfTypeRef);

		for(int i = 0; i < 2; i++)
		{
			CSharpLightParameterBuilder parameterBuilder = new CSharpLightParameterBuilder(project);
			parameterBuilder.withName("p" + i);
			parameterBuilder.withTypeRef(selfTypeRef);
			builder.addParameter(parameterBuilder);
		}

		consumer.consume(builder);
	}
}
 
Example #6
Source Project: consulo   Author: consulo   File: SetShortcutAction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void update(@Nonnull AnActionEvent e) {
  Presentation presentation = e.getPresentation();

  Project project = e.getProject();
  JBPopup seDialog = project == null ? null : project.getUserData(SearchEverywhereManager.SEARCH_EVERYWHERE_POPUP);
  if (seDialog == null) {
    presentation.setEnabled(false);
    return;
  }

  KeymapManager km = KeymapManager.getInstance();
  Keymap activeKeymap = km != null ? km.getActiveKeymap() : null;
  if (activeKeymap == null) {
    presentation.setEnabled(false);
    return;
  }

  AnAction action = e.getData(SELECTED_ACTION);
  Component component = e.getData(PlatformDataKeys.CONTEXT_COMPONENT);
  presentation.setEnabled(action != null && component != null);
}
 
Example #7
Source Project: idea-php-symfony2-plugin   Author: Haehnchen   File: DoctrineMetadataLineMarkerProvider.java    License: MIT License 6 votes vote down vote up
@Override
public void collectSlowLineMarkers(@NotNull List<PsiElement> psiElements, @NotNull Collection<LineMarkerInfo> results) {
    // we need project element; so get it from first item
    if(psiElements.size() == 0) {
        return;
    }

    Project project = psiElements.get(0).getProject();
    if(!Symfony2ProjectComponent.isEnabled(project)) {
        return;
    }

    for(PsiElement psiElement: psiElements) {
        if(psiElement.getNode().getElementType() != XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN) {
            continue;
        }

        PsiElement xmlAttributeValue = psiElement.getParent();
        if(xmlAttributeValue instanceof XmlAttributeValue && (DoctrineMetadataPattern.getXmlTargetDocumentClass().accepts(xmlAttributeValue) || DoctrineMetadataPattern.getXmlTargetEntityClass().accepts(xmlAttributeValue) || DoctrineMetadataPattern.getEmbeddableNameClassPattern().accepts(xmlAttributeValue))) {
            attachXmlRelationMarker(psiElement, (XmlAttributeValue) xmlAttributeValue, results);
        }
    }
}
 
Example #8
Source Project: otto-intellij-plugin   Author: square   File: ShowUsagesAction.java    License: Apache License 2.0 6 votes vote down vote up
static void chooseAmbiguousTargetAndPerform(@NotNull final Project project,
    final Editor editor,
    @NotNull PsiElementProcessor<PsiElement> processor) {
  if (editor == null) {
    Messages.showMessageDialog(project, FindBundle.message("find.no.usages.at.cursor.error"),
        CommonBundle.getErrorTitle(), Messages.getErrorIcon());
  }
  else {
    int offset = editor.getCaretModel().getOffset();
    boolean chosen = GotoDeclarationAction.chooseAmbiguousTarget(editor, offset, processor,
        FindBundle.message("find.usages.ambiguous.title", "crap"), null);
    if (!chosen) {
      ApplicationManager.getApplication().invokeLater(new Runnable() {
        @Override
        public void run() {
          if (editor.isDisposed() || !editor.getComponent().isShowing()) return;
          HintManager.getInstance().showErrorHint(editor, FindBundle.message("find.no.usages.at.cursor.error"));
        }
      }, project.getDisposed());
    }
  }
}
 
Example #9
Source Project: consulo   Author: consulo   File: DiffUtil.java    License: Apache License 2.0 6 votes vote down vote up
@Nonnull
public static EditorEx createEditor(@Nonnull Document document, @Nullable Project project, boolean isViewer, boolean enableFolding) {
  EditorFactory factory = EditorFactory.getInstance();
  EditorEx editor = (EditorEx)(isViewer ? factory.createViewer(document, project) : factory.createEditor(document, project));

  editor.putUserData(DiffManagerImpl.EDITOR_IS_DIFF_KEY, Boolean.TRUE);

  editor.getSettings().setShowIntentionBulb(false);
  ((EditorMarkupModel)editor.getMarkupModel()).setErrorStripeVisible(true);
  editor.getGutterComponentEx().setShowDefaultGutterPopup(false);

  if (enableFolding) {
    setFoldingModelSupport(editor);
  } else {
    editor.getSettings().setFoldingOutlineShown(false);
    editor.getFoldingModel().setFoldingEnabled(false);
  }

  UIUtil.removeScrollBorder(editor.getComponent());

  return editor;
}
 
Example #10
Source Project: consulo   Author: consulo   File: SurroundWithHandler.java    License: Apache License 2.0 6 votes vote down vote up
private static void invokeSurrounderInTests(Project project,
                                            Editor editor,
                                            PsiFile file,
                                            Surrounder surrounder,
                                            int startOffset,
                                            int endOffset, List<SurroundDescriptor> surroundDescriptors) {
  assert ApplicationManager.getApplication().isUnitTestMode();
  for (SurroundDescriptor descriptor : surroundDescriptors) {
    final PsiElement[] elements = descriptor.getElementsToSurround(file, startOffset, endOffset);
    if (elements.length > 0) {
      for (Surrounder descriptorSurrounder : descriptor.getSurrounders()) {
        if (surrounder.getClass().equals(descriptorSurrounder.getClass())) {
          doSurround(project, editor, surrounder, elements);
          return;
        }
      }
    }
  }
}
 
Example #11
Source Project: consulo   Author: consulo   File: PathsVerifier.java    License: Apache License 2.0 6 votes vote down vote up
public PathsVerifier(final Project project, final VirtualFile baseDirectory, final List<FilePatch> patches, BaseMapper baseMapper) {
  myProject = project;
  myBaseDirectory = baseDirectory;
  myPatches = patches;
  myBaseMapper = baseMapper;

  myMovedFiles = new HashMap<>();
  myBeforePaths = new ArrayList<>();
  myCreatedDirectories = new ArrayList<>();
  myTextPatches = new ArrayList<>();
  myBinaryPatches = new ArrayList<>();
  myWritableFiles = new ArrayList<>();
  myVcsManager = ProjectLevelVcsManager.getInstance(myProject);
  mySkipped = new ArrayList<>();

  myAddedPaths = new ArrayList<>();
  myDeletedPaths = new ArrayList<>();
}
 
Example #12
Source Project: vue-for-idea   Author: henjue   File: ValidationUtils.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static boolean validatePath(Project project, String path, boolean allowEmpty) {
    if (StringUtils.isEmpty(path)) {
        return allowEmpty;
    }
    File filePath = new File(path);
    if (filePath.isAbsolute()) {
        if (!filePath.exists() || !filePath.isFile()) {
            return false;
        }
    } else {
        if (project == null || project.getBaseDir() == null) {
            return true;
        }
        VirtualFile child = project.getBaseDir().findFileByRelativePath(path);
        if (child == null || !child.exists() || child.isDirectory()) {
            return false;
        }
    }
    return true;
}
 
Example #13
Source Project: consulo   Author: consulo   File: TestErrorViewAction.java    License: Apache License 2.0 5 votes vote down vote up
protected void openView(Project project, JComponent component) {
  final MessageView messageView = MessageView.SERVICE.getInstance(project);
  final Content content = ContentFactory.getInstance().createContent(component, getContentName(), true);
  messageView.getContentManager().addContent(content);
  messageView.getContentManager().setSelectedContent(content);
  ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.MESSAGES_WINDOW);
  if (toolWindow != null) {
    toolWindow.activate(null);
  }
}
 
Example #14
Source Project: consulo   Author: consulo   File: LanguageFileTypeStructureViewBuilderProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@Nullable
public StructureViewBuilder getStructureViewBuilder(@Nonnull final FileType fileType, @Nonnull final VirtualFile file, @Nonnull final Project project) {
  if (!(fileType instanceof LanguageFileType)) return null;

  final PsiFile psiFile = PsiManager.getInstance(project).findFile(file);
  if (psiFile == null) return null;

  final PsiStructureViewFactory factory = LanguageStructureViewBuilder.INSTANCE.forLanguage(psiFile.getLanguage());
  return factory == null ?  null : factory.getStructureViewBuilder(psiFile);
}
 
Example #15
Source Project: consulo   Author: consulo   File: SelectWordHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void execute(@Nonnull Editor editor, DataContext dataContext) {
  if (LOG.isDebugEnabled()) {
    LOG.debug("enter: execute(editor='" + editor + "')");
  }
  Project project = DataManager.getInstance().getDataContext(editor.getComponent()).getData(CommonDataKeys.PROJECT);
  if (project == null) {
    if (myOriginalHandler != null) {
      myOriginalHandler.execute(editor, dataContext);
    }
    return;
  }
  PsiDocumentManager.getInstance(project).commitAllDocuments();

  TextRange range = selectWord(editor, project);
  if (editor instanceof EditorWindow) {
    if (range == null || !isInsideEditableInjection((EditorWindow)editor, range, project) || TextRange.from(0, editor.getDocument().getTextLength()).equals(
            new TextRange(editor.getSelectionModel().getSelectionStart(), editor.getSelectionModel().getSelectionEnd()))) {
      editor = ((EditorWindow)editor).getDelegate();
      range = selectWord(editor, project);
    }
  }
  if (range == null) {
    if (myOriginalHandler != null) {
      myOriginalHandler.execute(editor, dataContext);
    }
  }
  else {
    editor.getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset());
  }
}
 
Example #16
Source Project: consulo   Author: consulo   File: PatchApplier.java    License: Apache License 2.0 5 votes vote down vote up
@CalledInAwt
public static void refreshPassedFilesAndMoveToChangelist(@Nonnull final Project project,
                                                         final Collection<FilePath> directlyAffected,
                                                         final Collection<VirtualFile> indirectlyAffected,
                                                         final Consumer<Collection<FilePath>> targetChangelistMover) {
  final LocalFileSystem lfs = LocalFileSystem.getInstance();
  for (FilePath filePath : directlyAffected) {
    lfs.refreshAndFindFileByIoFile(filePath.getIOFile());
  }
  if (project.isDisposed()) return;

  final ChangeListManager changeListManager = ChangeListManager.getInstance(project);
  if (! directlyAffected.isEmpty() && targetChangelistMover != null) {
    changeListManager.invokeAfterUpdate(new Runnable() {
                                          @Override
                                          public void run() {
                                            targetChangelistMover.consume(directlyAffected);
                                          }
                                        }, InvokeAfterUpdateMode.SYNCHRONOUS_CANCELLABLE,
                                        VcsBundle.message("change.lists.manager.move.changes.to.list"),
                                        new Consumer<VcsDirtyScopeManager>() {
                                          @Override
                                          public void consume(final VcsDirtyScopeManager vcsDirtyScopeManager) {
                                            markDirty(vcsDirtyScopeManager, directlyAffected, indirectlyAffected);
                                          }
                                        }, null);
  } else {
    markDirty(VcsDirtyScopeManager.getInstance(project), directlyAffected, indirectlyAffected);
  }
}
 
Example #17
Source Project: consulo   Author: consulo   File: GotoInspectionModel.java    License: Apache License 2.0 5 votes vote down vote up
public GotoInspectionModel(Project project) {
  super(project, IdeBundle.message("prompt.goto.inspection.enter.name"), "goto.inspection.help.id");
  final InspectionProfileImpl rootProfile = (InspectionProfileImpl)InspectionProfileManager.getInstance().getRootProfile();
  for (ScopeToolState state : rootProfile.getAllTools(project)) {
    InspectionToolWrapper tool = state.getTool();
    InspectionToolWrapper workingTool = tool;
    if (tool instanceof LocalInspectionToolWrapper) {
      workingTool = LocalInspectionToolWrapper.findTool2RunInBatch(project, null, tool.getShortName());
      if (workingTool == null) {
        continue;
      }
    }
    myToolNames.put(tool.getDisplayName(), workingTool);
    final String groupName = tool.getGroupDisplayName();
    Set<InspectionToolWrapper> toolsInGroup = myGroupNames.get(groupName);
    if (toolsInGroup == null) {
      toolsInGroup = new HashSet<InspectionToolWrapper>();
      myGroupNames.put(groupName, toolsInGroup);
    }
    toolsInGroup.add(workingTool);
    myToolShortNames.put(tool.getShortName(), workingTool);
  }

  final Set<String> nameIds = new HashSet<String>();
  nameIds.addAll(myToolNames.keySet());
  nameIds.addAll(myGroupNames.keySet());
  myNames = ArrayUtil.toStringArray(nameIds);
}
 
Example #18
Source Project: consulo   Author: consulo   File: MoveHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * called by an Action in AtomicAction
 */
@Override
public void invoke(@Nonnull Project project, @Nonnull PsiElement[] elements, DataContext dataContext) {
  final PsiElement targetContainer = dataContext == null ? null : dataContext.getData(LangDataKeys.TARGET_PSI_ELEMENT);
  final Set<PsiElement> filesOrDirs = new HashSet<PsiElement>();
  for(MoveHandlerDelegate delegate: Extensions.getExtensions(MoveHandlerDelegate.EP_NAME)) {
    if (delegate.canMove(dataContext) && delegate.isValidTarget(targetContainer, elements)) {
      delegate.collectFilesOrDirsFromContext(dataContext, filesOrDirs);
    }
  }
  if (!filesOrDirs.isEmpty()) {
    for (PsiElement element : elements) {
      if (element instanceof PsiDirectory) {
        filesOrDirs.add(element);
      }
      else {
        final PsiFile containingFile = element.getContainingFile();
        if (containingFile != null) {
          filesOrDirs.add(containingFile);
        }
      }
    }
    MoveFilesOrDirectoriesUtil
      .doMove(project, PsiUtilBase.toPsiElementArray(filesOrDirs), new PsiElement[]{targetContainer}, null);
    return;
  }
  doMove(project, elements, targetContainer, dataContext, null);
}
 
Example #19
Source Project: intellij   Author: bazelbuild   File: ScalaBinaryContextProvider.java    License: Apache License 2.0 5 votes vote down vote up
/** Returns all scala_binary targets reachable from the given source file. */
private static Collection<TargetIdeInfo> findScalaBinaryTargets(
    Project project, File mainClassFile) {
  FilteredTargetMap map =
      SyncCache.getInstance(project)
          .get(SCALA_BINARY_MAP_KEY, ScalaBinaryContextProvider::computeTargetMap);
  return map != null ? map.targetsForSourceFile(mainClassFile) : ImmutableList.of();
}
 
Example #20
Source Project: buck   Author: facebook   File: ClearTreeViewPanelAction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent anActionEvent) {
  Project project = anActionEvent.getProject();
  if (project != null) {
    BuckUIManager buckUIManager = BuckUIManager.getInstance(project);
    buckUIManager
        .getBuckTreeViewPanel()
        .getModifiableModel()
        .removeAllChildren(buckUIManager.getBuckTreeViewPanel().getRoot());
  }
}
 
Example #21
Source Project: consulo   Author: consulo   File: ExecutionHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static Collection<RunContentDescriptor> findRunningConsoleByTitle(final Project project,
                                                                         @Nonnull final NotNullFunction<String, Boolean> titleMatcher) {
  return findRunningConsole(project, new NotNullFunction<RunContentDescriptor, Boolean>() {
    @Nonnull
    @Override
    public Boolean fun(RunContentDescriptor selectedContent) {
      return titleMatcher.fun(selectedContent.getDisplayName());
    }
  });
}
 
Example #22
Source Project: consulo   Author: consulo   File: SelectionQuotingTypedHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Result beforeCharTyped(final char charTyped, final Project project, final Editor editor, final PsiFile file, final FileType fileType) {
  // TODO[oleg] remove this hack when API changes
  if (myReplacedTextRange != null) {
    if (myReplacedTextRange.getEndOffset() <= editor.getDocument().getTextLength()) {
      if (myRestoreStickySelection && editor instanceof EditorEx) {
        EditorEx editorEx = (EditorEx)editor;
        CaretModel caretModel = editorEx.getCaretModel();
        caretModel.moveToOffset(myLtrSelection ? myReplacedTextRange.getStartOffset() : myReplacedTextRange.getEndOffset());
        editorEx.setStickySelection(true);
        caretModel.moveToOffset(myLtrSelection ? myReplacedTextRange.getEndOffset() : myReplacedTextRange.getStartOffset());
      }
      else {
        if (myLtrSelection || editor instanceof EditorWindow) {
          editor.getSelectionModel().setSelection(myReplacedTextRange.getStartOffset(), myReplacedTextRange.getEndOffset());
        }
        else {
          editor.getSelectionModel().setSelection(myReplacedTextRange.getEndOffset(), myReplacedTextRange.getStartOffset());
        }
        if (Registry.is("editor.smarterSelectionQuoting")) {
          editor.getCaretModel().moveToOffset(myLtrSelection ? myReplacedTextRange.getEndOffset() : myReplacedTextRange.getStartOffset());
        }
      }
    }
    myReplacedTextRange = null;
    return Result.STOP;
  }
  return Result.CONTINUE;
}
 
Example #23
Source Project: IntelliJDeodorant   Author: JetBrains-Research   File: PolymorphismRefactoring.java    License: MIT License 5 votes vote down vote up
public PolymorphismRefactoring(PsiFile sourceFile,
                               Project project,
                               PsiClass sourceTypeDeclaration,
                               TypeCheckElimination typeCheckElimination) {
    this.sourceFile = sourceFile;
    this.sourceTypeDeclaration = sourceTypeDeclaration;
    this.typeCheckElimination = typeCheckElimination;
    elementFactory = PsiElementFactory.getInstance(project);
    codeStyleManager = CodeStyleManager.getInstance(project);
    this.project = project;
    semicolon = (PsiJavaToken) elementFactory.createStatementFromText(";", null).getFirstChild();
}
 
Example #24
Source Project: consulo   Author: consulo   File: PlatformOrPluginUpdateChecker.java    License: Apache License 2.0 5 votes vote down vote up
public static AsyncResult<Void> checkAndNotifyForUpdates(@Nullable Project project, boolean showResults, @Nullable ProgressIndicator indicator) {
  AsyncResult<Void> actionCallback = AsyncResult.undefined();
  PlatformOrPluginUpdateResult updateResult = checkForUpdates(showResults, indicator);
  if (updateResult == PlatformOrPluginUpdateResult.CANCELED) {
    actionCallback.setDone();
    return actionCallback;
  }

  UIUtil.invokeLaterIfNeeded(() -> {
    actionCallback.setDone();

    showUpdateResult(project, updateResult, showResults);
  });
  return actionCallback;
}
 
Example #25
Source Project: flutter-intellij   Author: flutter   File: FlutterProjectCreator.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void disableUserConfig(Project project) {
  if (FlutterModuleUtils.declaresFlutter(project)) {
    for (Module module : ModuleManager.getInstance(project).getModules()) {
      final AndroidFacet facet = AndroidFacet.getInstance(module);
      if (facet == null) {
        continue;
      }
      facet.getProperties().ALLOW_USER_CONFIGURATION = false;
    }
  }
}
 
Example #26
Source Project: consulo   Author: consulo   File: PsiFileReferenceHelper.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public Collection<PsiFileSystemItem> getContexts(final Project project, @Nonnull final VirtualFile file) {
  final PsiFileSystemItem item = getPsiFileSystemItem(project, file);
  if (item != null) {
    final PsiFileSystemItem parent = item.getParent();
    if (parent != null) {
      final ProjectFileIndex index = ProjectRootManager.getInstance(project).getFileIndex();
      final VirtualFile parentFile = parent.getVirtualFile();
      assert parentFile != null;
      VirtualFile root = index.getSourceRootForFile(parentFile);
      if (root != null) {
        String path = VfsUtilCore.getRelativePath(parentFile, root, '.');

        if (path != null) {
          final Module module = ModuleUtilCore.findModuleForFile(file, project);

          if (module != null) {
            return getContextsForModule(module, path, GlobalSearchScope.moduleWithDependenciesScope(module));
          }
        }

        // TODO: content root
      }
      return Collections.singleton(parent);
    }
  }
  return Collections.emptyList();
}
 
Example #27
Source Project: intellij   Author: bazelbuild   File: BlazeMenuGroup.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public final void update(AnActionEvent e) {
  // Don't hide the menu if project is null: it will be null temporarily while loading a
  // Blaze project, and sometimes stays hidden permanently if we hide it during loading.
  Project project = e.getProject();
  if (project != null && !Blaze.isBlazeProject(project)) {
    e.getPresentation().setEnabledAndVisible(false);
    return;
  }

  e.getPresentation().setEnabledAndVisible(true);
  e.getPresentation().setText(menuName(Blaze.getBuildSystem(e.getProject())));
}
 
Example #28
Source Project: consulo   Author: consulo   File: GlobalInspectionContextBase.java    License: Apache License 2.0 5 votes vote down vote up
public GlobalInspectionContextBase(@Nonnull Project project) {
  myProject = project;

  for (InspectionExtensionsFactory factory : InspectionExtensionsFactory.EP_NAME.getExtensionList()) {
    final GlobalInspectionContextExtension extension = factory.createGlobalInspectionContextExtension();
    myExtensions.put(extension.getID(), extension);
  }
}
 
Example #29
Source Project: consulo   Author: consulo   File: MessageBusUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static <T> void invokeLaterIfNeededOnSyncPublisher(final Project project, final Topic<T> topic, final Consumer<T> listener) {
  final Application application = ApplicationManager.getApplication();
  final Runnable runnable = createPublisherRunnable(project, topic, listener);
  if (application.isDispatchThread()) {
    runnable.run();
  } else {
    application.invokeLater(runnable);
  }
}
 
Example #30
Source Project: consulo   Author: consulo   File: RenameFileFix.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void invoke(@Nonnull Project project, Editor editor, PsiFile file) {
  VirtualFile vFile = file.getVirtualFile();
  Document document = PsiDocumentManager.getInstance(project).getDocument(file);
  FileDocumentManager.getInstance().saveDocument(document);
  try {
    vFile.rename(file.getManager(), myNewFileName);
  }
  catch(IOException e){
    MessagesEx.error(project, e.getMessage()).showLater();
  }
}