Java Code Examples for com.intellij.psi.PsiDirectory

The following are top voted examples for showing how to use com.intellij.psi.PsiDirectory. 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: educational-plugin   File: LessonDirectoryNode.java   Source Code and License 6 votes vote down vote up
@Nullable
@Override
public AbstractTreeNode modifyChildNode(AbstractTreeNode childNode) {
  Object value = childNode.getValue();
  if (value instanceof PsiDirectory) {
    PsiDirectory directory = (PsiDirectory)value;
    Task task = myLesson.getTask(directory.getName());
    if (task == null) {
      return null;
    }
    VirtualFile srcDir = directory.getVirtualFile().findChild(EduNames.SRC);
    if (srcDir != null) {
      directory = PsiManager.getInstance(myProject).findDirectory(srcDir);
      if (directory == null) {
        return null;
      }
    }
    return createChildDirectoryNode(task, directory);
  }
  return null;
}
 
Example 2
Project: educational-plugin   File: CCLessonMoveHandlerDelegate.java   Source Code and License 6 votes vote down vote up
@Override
public boolean canMove(DataContext dataContext) {
  if (CommonDataKeys.PSI_FILE.getData(dataContext) != null) {
    return false;
  }
  IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext);
  if (view == null) {
    return false;
  }

  final PsiDirectory[] directories = view.getDirectories();
  if (directories.length == 0 || directories.length > 1) {
    return false;
  }

  final PsiDirectory sourceDirectory = directories[0];
  return CCUtils.isLessonDir(sourceDirectory);
}
 
Example 3
Project: educational-plugin   File: CCTaskMoveHandlerDelegate.java   Source Code and License 6 votes vote down vote up
@Override
public boolean canMove(DataContext dataContext) {
  if (CommonDataKeys.PSI_FILE.getData(dataContext) != null) {
    return false;
  }
  IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext);
  if (view == null) {
    return false;
  }
  final PsiDirectory[] directories = view.getDirectories();
  if (directories.length == 0 || directories.length > 1) {
    return false;
  }

  final PsiDirectory sourceDirectory = directories[0];
  return isTaskDir(sourceDirectory);
}
 
Example 4
Project: GravSupport   File: NewThemeConfigurationFileAction.java   Source Code and License 6 votes vote down vote up
@Override
protected boolean isAvailable(DataContext dataContext) {
    final Project project = CommonDataKeys.PROJECT.getData(dataContext);
    final Module module = LangDataKeys.MODULE.getData(dataContext);
    final ModuleType moduleType = module == null ? null : ModuleType.get(module);
    final boolean isGravModule = moduleType instanceof GravModuleType || moduleType instanceof WebModuleTypeBase;
    final boolean pluginEnabled = GravProjectComponent.isEnabled(project);
    if (!pluginEnabled) return false;
    if (dataContext.getData(PlatformDataKeys.NAVIGATABLE) instanceof PsiDirectory) {
        PsiDirectory psiDirectory = (PsiDirectory) dataContext.getData(PlatformDataKeys.NAVIGATABLE);
        String themeFolder = psiDirectory.getParent().getVirtualFile().getName();
        themeName = psiDirectory.getName();
        GravFileTypes.setModuleName(themeName);
        boolean isThemeFolder = themeFolder.equalsIgnoreCase("themes");
        return super.isAvailable(dataContext) && isGravModule && isThemeFolder;
    } else {
        return false;
    }
}
 
Example 5
Project: yii2support   File: ObjectFactoryReference.java   Source Code and License 6 votes vote down vote up
@Nullable
@Override
public PsiElement resolve() {
    PsiElement possibleArrayCreation = myElement.getParent().getParent().getParent();
    if (possibleArrayCreation instanceof ArrayCreationExpression) {
        ArrayCreationExpression  arrayCreation = (ArrayCreationExpression)possibleArrayCreation;
        PsiDirectory dir = myElement.getContainingFile().getContainingDirectory();
        PhpClass phpClass = ObjectFactoryUtils.findClassByArrayCreation(arrayCreation, dir);

        if (phpClass != null) {
            PsiElement field = ClassUtils.findWritableField(phpClass, myElement.getText());
            return field;
        }

    }
    return null;
}
 
Example 6
Project: educational-plugin   File: CCCreateStudyItemActionBase.java   Source Code and License 6 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
  final IdeView view = e.getData(LangDataKeys.IDE_VIEW);
  final Project project = e.getProject();
  if (view == null || project == null) {
    return;
  }
  final PsiDirectory[] directories = view.getDirectories();
  if (directories.length == 0 || directories.length > 1) {
    return;
  }

  final PsiDirectory directory = directories[0];
  if (directory == null) return;
  final Course course = StudyTaskManager.getInstance(project).getCourse();
  if (course == null) {
    return;
  }
  createItem(view, project, directory, course);
}
 
Example 7
Project: idea-php-class-templates   File: PhpNewClassDialog.java   Source Code and License 6 votes vote down vote up
public PhpNewClassDialog(@NotNull Project project, @Nullable PsiDirectory directory) {
    super(project);

    this.myAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD);

    Disposer.register(this.getDisposable(), new Disposable() {
        public void dispose() {
            PhpNewClassDialog.this.myAlarm.cancelAllRequests();
            PhpNewClassDialog.this.myDisposed = true;
        }
    });

    this.myProperties = new Properties();

    this.myProject = project;
    this.myDirectory = directory;

    init();
}
 
Example 8
Project: GravSupport   File: LanguageTreeStructureProvider.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public Collection<AbstractTreeNode> modify(@NotNull AbstractTreeNode parent, @NotNull Collection<AbstractTreeNode> children, ViewSettings settings) {
    ArrayList<AbstractTreeNode> nodes = new ArrayList<AbstractTreeNode>();

    if (isLanguageFolder(parent)) {
        if (children.size() > 0 && parent.getValue() instanceof PsiDirectory) {
            Collection<PsiFileNode> childrenPsi2 = new ArrayList<>();
            for (AbstractTreeNode eachChild : children) {
                if (!(eachChild.getValue() instanceof PsiFile)) continue;
                PsiFile psiFile = (PsiFile) eachChild.getValue();
                LanguageNodeFile nodeFile = new LanguageNodeFile(parent.getProject(), psiFile, settings);
                childrenPsi2.add(nodeFile);
            }
            LanguageNestingNode languageFormNode = new LanguageNestingNode(childrenPsi2.iterator().next(), childrenPsi2);
            nodes.add(languageFormNode);
        }
    } else {
        nodes.addAll(children);
    }
    return nodes;
}
 
Example 9
Project: idea-php-typo3-plugin   File: ExtensionUtility.java   Source Code and License 6 votes vote down vote up
public static PsiDirectory getExtensionDirectory(@NotNull AnActionEvent event) {
    Project project = event.getData(PlatformDataKeys.PROJECT);
    if (project == null) {
        return null;
    }

    DataContext dataContext = event.getDataContext();
    IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext);
    if (view == null) {
        return null;
    }

    PsiDirectory[] directories = view.getDirectories();
    if (directories.length == 0) {
        return null;
    }

    return FilesystemUtil.findParentExtensionDirectory(directories[0]);
}
 
Example 10
Project: OpenInExplorer-idea   File: RightAction.java   Source Code and License 6 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent event) {
    // TODO: insert action logic here
    Project project = event.getData(PlatformDataKeys.PROJECT);
    Object nav = event.getData(CommonDataKeys.NAVIGATABLE);
    String path;
    try {
        if (nav instanceof PsiDirectory) {
            PsiDirectory directory = (PsiDirectory) nav;
            path = directory.getVirtualFile().getPath();
        } else {
            PsiFile file = (PsiFile) nav;
            path = file.getVirtualFile().getPath();
        }
        Toast.make(project, MessageType.INFO, "Open: " + path);
        Runtime.getRuntime().exec("cmd /c start " + path);
    } catch (Exception e) {
        e.printStackTrace();
        if (nav instanceof PsiClass) {
            Toast.make(project, MessageType.ERROR, "Could not open the java file, double-click to open.");
            return;
        }

        Toast.make(project, MessageType.ERROR, e.getMessage());
    }
}
 
Example 11
Project: CodeGen   File: AbstractFileProvider.java   Source Code and License 6 votes vote down vote up
/**
 * 根据选择的package目录,找到resources目录
 * @param psiDirectory
 * @return
 */
private PsiDirectory findResourcesDirectory(PsiDirectory psiDirectory) {

    PsiDirectory parentDirectory = psiDirectory.getParentDirectory();
    PsiDirectory iterator = psiDirectory.getParentDirectory();

    while (iterator != null && !iterator.getName().equals("main")) {
        iterator = iterator.getParentDirectory();
    }

    PsiDirectory resourcesDirectory = iterator == null ? null : iterator.findSubdirectory("resources");
    if (resourcesDirectory == null) {
        resourcesDirectory = parentDirectory.findSubdirectory("resources");
        if (resourcesDirectory == null) {
            resourcesDirectory = parentDirectory.createSubdirectory("resources");
        }
    }
    return resourcesDirectory;
}
 
Example 12
Project: manifold-ij   File: MoveTypeManifoldFileProcessor.java   Source Code and License 6 votes vote down vote up
@Nullable
@Override
public List<UsageInfo> findUsages( PsiFile psiFile, PsiDirectory newParent, boolean searchInComments, boolean searchInNonJavaFiles )
{
  Module mod = ModuleUtilCore.findModuleForPsiElement( psiFile );
  ManModule module = ManProject.getModule( mod );
  PsiClass psiClass = findPsiClass( psiFile );
  if( psiClass == null )
  {
    return Collections.emptyList();
  }

  Query<PsiReference> search = ReferencesSearch.search( psiClass, GlobalSearchScope.moduleWithDependenciesAndLibrariesScope( module.getIjModule() ) );
  List<UsageInfo> usages = new ArrayList<>();
  for( PsiReference ref: search.findAll() )
  {
    usages.add( new MoveRenameUsageInfo( ref.getElement(), ref, ref.getRangeInElement().getStartOffset(),
      ref.getRangeInElement().getEndOffset(), psiClass,
      ref.resolve() == null && !(ref instanceof PsiPolyVariantReference && ((PsiPolyVariantReference)ref).multiResolve( true ).length > 0) ) );
  }
  return usages;
}
 
Example 13
Project: manifold-ij   File: ManTypeFinder.java   Source Code and License 6 votes vote down vote up
@Override
public boolean processPackageDirectories(@NotNull PsiPackage psiPackage,
                                         @NotNull final GlobalSearchScope scope,
                                         @NotNull final Processor<PsiDirectory> consumer,
                                         boolean includeLibrarySources) {
  //System.out.println( "processDirectories() : " + psiPackage + " : " + scope );

  final PsiManager psiManager = PsiManager.getInstance( _project );
  return PackageIndex.getInstance( _project )
    .getDirsByPackageName(psiPackage.getQualifiedName(), includeLibrarySources)
    .forEach(new ReadActionProcessor<VirtualFile>() {
      @Override
      public boolean processInReadAction(final VirtualFile dir) {
        if (!scope.contains(dir)) return true;
        PsiDirectory psiDir = psiManager.findDirectory(dir);
        return psiDir == null || consumer.process(psiDir);
      }
    });
}
 
Example 14
Project: magento2-phpstorm-plugin   File: MagentoComponentManager.java   Source Code and License 6 votes vote down vote up
@Override
public String getMagentoName() {
    if (moduleName != null) {
        return moduleName;
    }

    PsiDirectory configurationDir = directory.findSubdirectory(CONFIGURATION_PATH);
    if (configurationDir != null) {
        PsiFile configurationFile = configurationDir.findFile("module.xml");

        if (configurationFile != null && configurationFile instanceof XmlFile) {
            XmlTag rootTag = ((XmlFile) configurationFile).getRootTag();
            if (rootTag != null) {
                XmlTag module = rootTag.findFirstSubTag("module");
                if (module != null && module.getAttributeValue("name") != null) {
                    moduleName = module.getAttributeValue("name");
                    return moduleName;
                }
            }
        }
    }

    return DEFAULT_MODULE_NAME;
}
 
Example 15
Project: json2java4idea   File: NewClassAction.java   Source Code and License 6 votes vote down vote up
@CheckReturnValue
@VisibleForTesting
@SuppressWarnings("WeakerAccess")
static boolean isAvailable(@Nonnull AnActionEvent event) {
    final Project project = event.getProject();
    if (project == null) {
        return false;
    }

    final IdeView view = event.getData(LangDataKeys.IDE_VIEW);
    if (view == null) {
        return false;
    }

    final ProjectRootManager rootManager = ProjectRootManager.getInstance(project);
    final ProjectFileIndex fileIndex = rootManager.getFileIndex();
    final Optional<PsiDirectory> sourceDirectory = Stream.of(view.getDirectories())
            .filter(directory -> {
                final VirtualFile virtualFile = directory.getVirtualFile();
                return fileIndex.isUnderSourceRootOfType(virtualFile, JavaModuleSourceRootTypes.SOURCES);
            })
            .findFirst();
    return sourceDirectory.isPresent();
}
 
Example 16
Project: chocolate-cakephp   File: ControllerMethodLineMarker.java   Source Code and License 6 votes vote down vote up
@Nullable
private LineMarkerInfo getRelatedFiles(@NotNull PsiFile file, @NotNull String controllerName, @NotNull PsiElement element) {
    if (!(element instanceof Method)) {
        return null;
    }
    Method method = (Method)element;
    if (!method.getAccess().isPublic()) {
        return null;
    }
    String methodName = method.getName();
    PsiDirectory appDir = PsiUtil.getAppDirectoryFromFile(file);
    String templatePath = String.format("View/%s/%s.ctp", controllerName, methodName);
    VirtualFile relativeFile = VfsUtil.findRelativeFile(appDir, templatePath);
    if (relativeFile == null) {
        return null;
    }

    PsiFile targetFile = PsiUtil.convertVirtualFileToPsiFile(method.getProject(), relativeFile);
    if (targetFile == null) {
        return null;
    }
    PsiElement targetElement = targetFile.getFirstChild();
    NavigationGutterIconBuilder<PsiElement> builder = NavigationGutterIconBuilder.create(CakeIcons.LOGO).setTarget(targetElement);
    return builder.createLineMarkerInfo(method);
}
 
Example 17
Project: chocolate-cakephp   File: ElementGotoDeclarationHandler.java   Source Code and License 6 votes vote down vote up
@Nullable
@Override
public PsiElement[] getGotoDeclarationTargets(@Nullable PsiElement psiElement, int i, Editor editor) {
    if (psiElement == null) {
        return PsiElement.EMPTY_ARRAY;
    }
    Project project = psiElement.getProject();
    if (!PlatformPatterns
            .psiElement(StringLiteralExpression.class)
            .withLanguage(PhpLanguage.INSTANCE)
            .accepts(psiElement.getContext())
    ) {
        return PsiElement.EMPTY_ARRAY;
    }
    PsiFile containingFile = psiElement.getContainingFile();
    PsiDirectory appDir = PsiUtil.getAppDirectoryFromFile(containingFile);
    String elementFilename = String.format("View/Elements/%s.ctp", psiElement.getText());
    VirtualFile relativeFile = VfsUtil.findRelativeFile(appDir, elementFilename);
    if (relativeFile != null) {
        Collection<VirtualFile> files = new HashSet<>();
        files.add(relativeFile);
        return PsiUtil.convertVirtualFilesToPsiFiles(project, files).toArray(new PsiElement[files.size()]);
    }
    return PsiElement.EMPTY_ARRAY;
}
 
Example 18
Project: educational-plugin   File: PyEduPluginConfigurator.java   Source Code and License 6 votes vote down vote up
@Override
public PsiDirectory createTaskContent(@NotNull Project project,
                                      @NotNull Task task,
                                      @Nullable IdeView view,
                                      @NotNull PsiDirectory parentDirectory,
                                      @NotNull Course course) {
  final Ref<PsiDirectory> taskDirectory = new Ref<>();
  ApplicationManager.getApplication().runWriteAction(() -> {
    String taskDirName = EduNames.TASK + task.getIndex();
    taskDirectory.set(DirectoryUtil.createSubdirectories(taskDirName, parentDirectory, "\\/"));
    if (taskDirectory.isNull()) return;

    if (course.isAdaptive() && !task.getTaskFiles().isEmpty()) {
      createTaskFilesFromText(task, taskDirectory.get());
    }
    else {
      createFilesFromTemplates(project, view, taskDirectory.get());
    }
  });
  return taskDirectory.get();
}
 
Example 19
Project: RIBs   File: GenerateAction.java   Source Code and License 6 votes vote down vote up
/**
 * Checked whether or not this action can be enabled.
 *
 * <p>Requirements to be enabled: * User must be in a Java source folder.
 *
 * @param dataContext to figure out where the user is.
 * @return {@code true} when the action is available, {@code false} when the action is not
 *     available.
 */
private boolean isAvailable(DataContext dataContext) {
  final Project project = CommonDataKeys.PROJECT.getData(dataContext);
  if (project == null) {
    return false;
  }

  final IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext);
  if (view == null || view.getDirectories().length == 0) {
    return false;
  }

  ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex();
  for (PsiDirectory dir : view.getDirectories()) {
    if (projectFileIndex.isUnderSourceRootOfType(
            dir.getVirtualFile(), JavaModuleSourceRootTypes.SOURCES)
        && checkPackageExists(dir)) {
      return true;
    }
  }

  return false;
}
 
Example 20
Project: educational-plugin   File: PyEduPluginConfigurator.java   Source Code and License 6 votes vote down vote up
@Override
public void createTestsForNewSubtask(@NotNull Project project, @NotNull TaskWithSubtasks task) {
  VirtualFile taskDir = task.getTaskDir(project);
  if (taskDir == null) {
    return;
  }
  int nextSubtaskIndex = task.getLastSubtaskIndex() + 1;
  String nextSubtaskTestsFileName = getSubtaskTestsFileName(nextSubtaskIndex);
  ApplicationManager.getApplication().runWriteAction(() -> {
    try {
      PsiDirectory taskPsiDir = PsiManager.getInstance(project).findDirectory(taskDir);
      FileTemplate testsTemplate = FileTemplateManager.getInstance(project).getInternalTemplate(TESTS_PY);
      if (taskPsiDir == null || testsTemplate == null) {
        return;
      }
      FileTemplateUtil.createFromTemplate(testsTemplate, nextSubtaskTestsFileName, null, taskPsiDir);
    }
    catch (Exception e) {
      LOG.error(e);
    }
  });
}
 
Example 21
Project: educational-plugin   File: PyEduPluginConfigurator.java   Source Code and License 6 votes vote down vote up
@Override
public void configureModule(@NotNull Module module) {
  final Project project = module.getProject();
  StartupManager.getInstance(project).runWhenProjectIsInitialized(() -> {
    final VirtualFile baseDir = project.getBaseDir();
    final String testHelper = EduNames.TEST_HELPER;
    if (baseDir.findChild(testHelper) != null) return;
    final FileTemplate template = FileTemplateManager.getInstance(project).getInternalTemplate("test_helper");
    final PsiDirectory projectDir = PsiManager.getInstance(project).findDirectory(baseDir);
    if (projectDir == null) return;
    try {
      FileTemplateUtil.createFromTemplate(template, testHelper, null, projectDir);
    }
    catch (Exception exception) {
      LOG.error("Can't copy test_helper.py " + exception.getMessage());
    }
  });
}
 
Example 22
Project: educational-plugin   File: StudyUtils.java   Source Code and License 6 votes vote down vote up
public static void createFromTemplate(@NotNull Project project,
                                      @NotNull PsiDirectory taskDirectory,
                                      @NotNull String name,
                                      @Nullable IdeView view,
                                      boolean open) {
  FileTemplate template = FileTemplateManager.getInstance(project).getInternalTemplate(name);
  if (template == null) {
    LOG.info("Template " + name + " wasn't found");
    return;
  }
  try {
    final PsiElement file = FileTemplateUtil.createFromTemplate(template, name, null, taskDirectory);
    if (view != null && open) {
      EditorHelper.openInEditor(file, false);
      view.selectElement(file);
    }
  }
  catch (Exception e) {
    LOG.error(e);
  }
}
 
Example 23
Project: educational-plugin   File: CCCreateStudyItemActionBase.java   Source Code and License 6 votes vote down vote up
@Nullable
public PsiDirectory createItem(@Nullable final IdeView view, @NotNull final Project project,
                               @NotNull final PsiDirectory sourceDirectory, @NotNull final Course course) {
  StudyItem parentItem = getParentItem(course, sourceDirectory);
  final StudyItem item = getItem(sourceDirectory, project, course, view, parentItem);
  if (item == null) {
    return null;
  }
  final PsiDirectory parentDir = getParentDir(project, course, sourceDirectory);
  if (parentDir == null) {
    return null;
  }
  CCUtils.updateHigherElements(parentDir.getVirtualFile().getChildren(), getStudyOrderable(item),
                               item.getIndex() - 1, getItemName(), 1);
  addItem(course, item);
  sortSiblings(course, parentItem);
  return createItemDir(project, item, view, parentDir, course);
}
 
Example 24
Project: educational-plugin   File: EduAdaptiveStepicConnector.java   Source Code and License 6 votes vote down vote up
private static void createFilesForNewTask(@NotNull Project project,
                                          @NotNull Task task,
                                          @NotNull String lessonName,
                                          @NotNull Language language) {
  final VirtualFile lessonDir = project.getBaseDir().findChild(lessonName);
  if (lessonDir == null) {
    return;
  }

  ApplicationManager.getApplication().invokeLater(() -> ApplicationManager.getApplication().runWriteAction(() -> {
    PsiDirectory directory = PsiManager.getInstance(project).findDirectory(lessonDir);
    if (directory == null) {
      return;
    }

    EduPluginConfigurator.INSTANCE.forLanguage(language).createTaskContent(project, task, null, directory, task.getLesson().getCourse());
  }));
}
 
Example 25
Project: educational-plugin   File: EduPluginConfigurator.java   Source Code and License 6 votes vote down vote up
/**
 * Creates content (including its directory or module) of new lesson in project
 *
 * @param project Parameter is used in Java and Kotlin plugins
 * @param lesson  Lesson to create content for. It's already properly initialized and added to course.
 * @return PsiDirectory of created lesson
 */
default PsiDirectory createLessonContent(@NotNull Project project,
                                         @NotNull Lesson lesson,
                                         @Nullable IdeView view,
                                         @NotNull PsiDirectory parentDirectory) {
  final PsiDirectory[] lessonDirectory = new PsiDirectory[1];
  ApplicationManager.getApplication().runWriteAction(() -> {
    String lessonDirName = EduNames.LESSON + lesson.getIndex();
    lessonDirectory[0] = DirectoryUtil.createSubdirectories(lessonDirName, parentDirectory, "\\/");
  });
  if (lessonDirectory[0] != null) {
    if (view != null) {
      view.selectElement(lessonDirectory[0]);
    }
  }
  return lessonDirectory[0];
}
 
Example 26
Project: educational-plugin   File: CourseDirectoryNode.java   Source Code and License 6 votes vote down vote up
@Override
public PsiDirectoryNode createChildDirectoryNode(StudyItem item, PsiDirectory directory) {
  final List<Lesson> lessons = myCourse.getLessons();
  final Lesson lesson = (Lesson)item;
  if (directory.getChildren().length > 0 && lessons.size() == 1) {
    final List<Task> tasks = lesson.getTaskList();
    if (tasks.size() == 1) {
      PsiDirectory taskDirectory = (PsiDirectory)directory.getChildren()[0];
      PsiDirectory srcDir = taskDirectory.findSubdirectory(EduNames.SRC);
      if (srcDir != null) {
        taskDirectory = srcDir;
      }
      return new TaskDirectoryNode(myProject, taskDirectory, myViewSettings, tasks.get(0));
    }
  }
  return new LessonDirectoryNode(myProject, directory, myViewSettings, lesson);
}
 
Example 27
Project: educational-plugin   File: TaskDirectoryNode.java   Source Code and License 6 votes vote down vote up
@Nullable
@Override
public AbstractTreeNode modifyChildNode(AbstractTreeNode childNode) {
  Object value = childNode.getValue();
  if (value instanceof PsiDirectory && !((PsiDirectory)value).getName().equals(EduNames.SRC)) {
    return createChildDirectoryNode(null, (PsiDirectory)value);
  }
  if (value instanceof PsiElement) {
    PsiFile psiFile = ((PsiElement) value).getContainingFile();
    if (psiFile == null) return null;
    VirtualFile virtualFile = psiFile.getVirtualFile();
    if (virtualFile == null) {
      return null;
    }
    return StudyUtils.getTaskFile(myProject, virtualFile) != null ? childNode : null;
  }
  return null;
}
 
Example 28
Project: yii2support   File: ViewsUtil.java   Source Code and License 5 votes vote down vote up
public static PsiDirectory getContextDirectory(PsiElement element) {
    final PsiFile file = element.getContainingFile();

    if (file.getUserData(VIEWS_CONTEXT_DIRECTORY) != null) {
        Long modified = file.getUserData(VIEWS_DIRECTORY_MODIFIED);
        if (modified != null && modified == file.getModificationStamp()) {
            return file.getUserData(VIEWS_CONTEXT_DIRECTORY);
        }
    }

    findDirectory(element);

    return file.getUserData(VIEWS_CONTEXT_DIRECTORY);
}
 
Example 29
Project: educational-plugin   File: CCCreateTask.java   Source Code and License 5 votes vote down vote up
@Nullable
@Override
protected StudyItem getParentItem(@NotNull Course course, @NotNull PsiDirectory directory) {
  Task task = (Task)getThresholdItem(course, directory);
  if (task == null) {
    return course.getLesson(directory.getName());
  }
  return task.getLesson();
}
 
Example 30
Project: yii2support   File: ObjectFactoryMissedFieldInspection.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder problemsHolder, boolean isOnTheFly) {
    return new PhpElementVisitor() {
        @Override
        public void visitPhpArrayCreationExpression(ArrayCreationExpression expression) {
            PsiDirectory dir = expression.getContainingFile().getContainingDirectory();
            PhpClass phpClass = ObjectFactoryUtils.findClassByArrayCreation(expression, dir);
            if (phpClass != null && !phpClass.getFQN().equals("\\" + phpClass.getName())) { // Avoid System Classes: \Closure, \ArrayAccess
                for (ArrayHashElement elem: expression.getHashElements()) {
                    PsiElement key = elem.getKey();
                    if (key != null) {
                        String keyName = (key instanceof ClassConstantReference || key instanceof ConstantReference) ?
                                ClassUtils.getConstantValue(key) : key.getText();
                        if (keyName != null) {
                            keyName = ClassUtils.removeQuotes(keyName);
                            if (keyName != null
                                    && !keyName.equals("class")
                                    && !keyName.startsWith("as ")
                                    && !keyName.startsWith("on ")
                                    && ClassUtils.findWritableField(phpClass, keyName) == null) {
                                final String descriptionTemplate = "Field '" + keyName + "' not exists in referenced class " + phpClass.getFQN();
                                problemsHolder.registerProblem(elem, descriptionTemplate);
                            }
                        }
                    }
                }


            }
            super.visitPhpArrayCreationExpression(expression);
        }
    };
}
 
Example 31
Project: yii2support   File: ObjectFactoryUtils.java   Source Code and License 5 votes vote down vote up
@Nullable
static PhpClass findClassByArrayCreation(ArrayCreationExpression arrayCreation, PsiDirectory dir) {
    if (arrayCreation == null)
        return null;
    PhpClass phpClass;
    phpClass = findClassByArray(arrayCreation);
    if (phpClass == null) {
        phpClass = getClassByInstatiation(arrayCreation);
    }
    if (phpClass == null) {
        phpClass = getPhpClassByYiiCreateObject(arrayCreation);
    }
    if (phpClass == null) {
        phpClass = getPhpClassInWidget(arrayCreation);
    }
    if (phpClass == null) {
        phpClass = getPhpClassInGridColumns(arrayCreation);
    }
    if (phpClass == null) {
        phpClass = getClassByParameterType(arrayCreation);
    }
    if (phpClass == null && arrayCreation.getParent().getParent() instanceof ArrayHashElement) {
        phpClass = getPhpClassByHash((ArrayHashElement) arrayCreation.getParent().getParent(), dir);
    }
    if (phpClass == null) {
        phpClass = getPhpClassInConfig(dir, arrayCreation);
    }
    return phpClass;
}
 
Example 32
Project: yii2support   File: Util.java   Source Code and License 5 votes vote down vote up
@NotNull
static PsiElement[] getCategories(PhpPsiElement element) {
    ArrayList<PsiElement> categories = new ArrayList<>();

    PsiDirectory directory = getDirectory(element);
    if (directory != null) {
        Collections.addAll(categories, directory.getFiles());
    }

    return categories.toArray(new PsiElement[categories.size()]);
}
 
Example 33
Project: yii2support   File: Util.java   Source Code and License 5 votes vote down vote up
@NotNull
static ArrayHashElement[] getMessages(PhpPsiElement element, String category) {
    ArrayList<ArrayHashElement> messages = new ArrayList<>();

    PsiDirectory directory = getDirectory(element);
    if (directory != null) {
        PsiFile file = directory.findFile(category.concat(".php"));
        if (file != null) {
            messages.addAll(loadMessagesFromFile(file));
        }
    }

    return messages.toArray(new ArrayHashElement[messages.size()]);
}
 
Example 34
Project: educational-plugin   File: CCLessonRenameHandler.java   Source Code and License 5 votes vote down vote up
@Override
protected void rename(@NotNull Project project, @NotNull Course course, @NotNull PsiDirectory directory) {
  Lesson lesson = course.getLesson(directory.getName());
  if (lesson != null) {
    processRename(lesson, EduNames.LESSON, project);
  }
}
 
Example 35
Project: educational-plugin   File: CCTaskMoveHandlerDelegate.java   Source Code and License 5 votes vote down vote up
@Override
public boolean canMove(PsiElement[] elements, @Nullable PsiElement targetContainer) {
  if (elements.length > 0 && elements[0] instanceof PsiDirectory) {
    return isTaskDir(((PsiDirectory)elements[0]));
  }
  return false;
}
 
Example 36
Project: AppleScript-IDEA   File: LoadDictionaryAction.java   Source Code and License 5 votes vote down vote up
public void actionPerformed(final AnActionEvent e) {
  DataContext dataContext = e.getDataContext();
  final IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext);
  if (view == null) return;
  final PsiDirectory[] directories = view.getDirectories();

  PsiDirectory currentDirectory = directories.length > 0 ? directories[0] : null;
  final Project project = e.getData(CommonDataKeys.PROJECT);
  if (project == null) return;

  VirtualFile directoryFile = currentDirectory != null ? currentDirectory.getVirtualFile() : project.getBaseDir();
  openLoadDirectoryDialog(project, directoryFile, null);
}
 
Example 37
Project: idea-php-class-templates   File: PhpNewClassDialog.java   Source Code and License 5 votes vote down vote up
@Nullable
protected PsiDirectory getDirectory() {
    VirtualFile directory = this.myDirectoryCombobox.getExistingParent();
    if(directory != null) {
        PsiDirectory psiDirectory = PsiManager.getInstance(this.myProject).findDirectory(directory);
        if(psiDirectory != null) {
            return psiDirectory;
        }
    }

    return null;
}
 
Example 38
Project: idea-php-class-templates   File: PhpNewClassDialog.java   Source Code and License 5 votes vote down vote up
@NotNull
public Properties getProperties(@NotNull PsiDirectory directory) {

    this.myProperties.setProperty("NAME", this.getName());
    String namespace = this.getNamespace();
    if(StringUtil.isNotEmpty(namespace)) {
        this.myProperties.setProperty("NAMESPACE", namespace);
    }

    return this.myProperties;
}
 
Example 39
Project: idea-php-class-templates   File: PhpNewClassDialog.java   Source Code and License 5 votes vote down vote up
protected ValidationInfo doValidate() {
    String name = this.getName();
    if(!PhpNameUtil.isValidClassName(name)) {
        return new ValidationInfo(
            PhpBundle.message(
                "validation.class.not.valid.name",
                    name),
            this.myNameTextField
        );
    } else {
        String namespace = this.getNamespace();
        if(StringUtil.isNotEmpty(namespace) && !PhpNameUtil.isValidNamespaceFullName(namespace)) {
            return new ValidationInfo(
                PhpBundle.message(
                    "validation.namespace.not.valid.name",
                        namespace),
                this.myNamespaceCombobox
            );
        } else {
            PsiDirectory directory = this.getDirectory();
            if(directory == null) {
                return new ValidationInfo(
                    PhpBundle.message(
                        "validation.value.is.not.specified.or.invalid",
                            "directory")
                );
            } else {
                String errorMessage = this.isValidFilePath(this.getFilePath(), directory);
                return errorMessage != null?new ValidationInfo(errorMessage, this.myFileNameTextField):null;
            }
        }
    }
}
 
Example 40
Project: manifold-ij   File: CreateExtensionMethodsClassAction.java   Source Code and License 5 votes vote down vote up
@Override
public void update( AnActionEvent e )
{
  super.update( e );

  boolean enabled;
  final DataContext dataContext = e.getDataContext();

  final IdeView view = LangDataKeys.IDE_VIEW.getData( dataContext );
  if( view == null )
  {
    enabled = false;
  }
  else
  {
    final Project project = PlatformDataKeys.PROJECT.getData( dataContext );

    final PsiDirectory dir = view.getOrChooseDirectory();
    if( dir == null || project == null )
    {
      enabled = false;
    }
    else
    {
      PsiPackage pkg = JavaDirectoryService.getInstance().getPackage( dir );
      ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance( project).getFileIndex();
      enabled = pkg != null && projectFileIndex.isUnderSourceRootOfType( dir.getVirtualFile(), JavaModuleSourceRootTypes.SOURCES );
    }
  }
  e.getPresentation().setEnabled( enabled );
}