private void sendModuleList(HttpExchange exchange) {
    StringBuilder response = new StringBuilder();
    response.append(
        "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n");
    response.append("<html>\n");
    response.append("<head>\n");
    response.append("<title>Web View</title>\n");
    response.append("</head>\n");
    response.append("<body>\n");
    response.append("<div>\n");

    Project[] projects = ProjectManager.getInstance().getOpenProjects();
    if (projects.length > 0) {
      response.append("Please, choose the project:<br/>");
      for (Project project : projects) {
        String projectName = project.getName();
        response.append("<a href=\"/project=");
        response.append(projectName);
        response.append("/\">");
        response.append(projectName);
        response.append("</a><br/>");
      }
    } else {
      response.append("There is no open project in Intellij IDEA");
    }

    response.append("</div>\n");
    response.append("</body>\n");
    response.append("</html>\n");
    writeResponse(exchange, response.toString(), 200);
  }
예제 #2
0
  private static String getPresentableName(final Project project) {
    if (project.isDefault()) {
      return project.getName();
    }

    String location = project.getLocation();
    if (location == null) return null;
    String projectName = FileUtil.toSystemIndependentName(location);
    if (projectName.endsWith("/")) {
      projectName = projectName.substring(0, projectName.length() - 1);
    }

    final int lastSlash = projectName.lastIndexOf('/');
    if (lastSlash >= 0 && lastSlash + 1 < projectName.length()) {
      projectName = projectName.substring(lastSlash + 1);
    }

    if (StringUtil.endsWithIgnoreCase(projectName, ProjectFileType.DOT_DEFAULT_EXTENSION)) {
      projectName =
          projectName.substring(
              0, projectName.length() - ProjectFileType.DOT_DEFAULT_EXTENSION.length());
    }

    projectName = projectName.toLowerCase(Locale.US);
    return projectName;
  }
  @Override
  public void importData(
      @NotNull Collection<DataNode<ProjectData>> toImport,
      @Nullable ProjectData projectData,
      @NotNull final Project project,
      @NotNull IdeModifiableModelsProvider modelsProvider) {
    // root project can be marked as ignored
    if (toImport.isEmpty()) return;

    if (toImport.size() != 1) {
      throw new IllegalArgumentException(
          String.format(
              "Expected to get a single project but got %d: %s", toImport.size(), toImport));
    }
    DataNode<ProjectData> node = toImport.iterator().next();
    assert projectData == node.getData();

    if (!ExternalSystemApiUtil.isOneToOneMapping(project, node)) {
      return;
    }

    if (!project.getName().equals(projectData.getInternalName())) {
      renameProject(projectData.getInternalName(), projectData.getOwner(), project);
    }
  }
 public static Project getProjectByProjectName(String projectName) {
   for (Project p : ProjectManager.getInstance().getOpenProjects()) {
     if (p.getName().equals(projectName)) {
       return p;
     }
   }
   return null;
 }
 private static String generateUniqueName(String prefix, Project project) {
   return prefix
       + "_"
       + project.getName().replaceAll("[^\\p{Alnum}]", "_")
       + "_"
       + SystemProperties.getUserName().replaceAll("[^\\p{Alnum}]", "_")
       + ".cfc";
 }
 private JBZipFile getTasksArchive(String postfix) throws IOException {
   String configPath = PathManager.getConfigPath(true);
   File tasksFolder = new File(configPath, TASKS_FOLDER);
   if (!tasksFolder.exists()) {
     //noinspection ResultOfMethodCallIgnored
     tasksFolder.mkdir();
   }
   String projectName = myProject.getName();
   return new JBZipFile(new File(tasksFolder, projectName + postfix));
 }
 @NotNull
 public static String baseTestDiscoveryPathForProject(Project project) {
   return PathManager.getSystemPath()
       + File.separator
       + "testDiscovery"
       + File.separator
       + project.getName()
       + "."
       + project.getLocationHash();
 }
 private static void checkName(
     @NotNull GradleProject gradleProject,
     @NotNull Project intellijProject,
     @NotNull Set<GradleProjectStructureChange> currentChanges) {
   String gradleName = gradleProject.getName();
   String intellijName = intellijProject.getName();
   if (!gradleName.equals(intellijName)) {
     currentChanges.add(new GradleProjectRenameChange(gradleName, intellijName));
   }
 }
예제 #9
0
  public void closeGrammar(VirtualFile grammarFile) {
    String grammarFileName = grammarFile.getPath();
    LOG.info("closeGrammar " + grammarFileName + " " + project.getName());

    inputPanel.resetStartRuleLabel();
    inputPanel.clearErrorConsole();
    clearParseTree(); // wipe tree

    ANTLRv4PluginController controller = ANTLRv4PluginController.getInstance(project);
    PreviewState previewState = controller.getPreviewState(grammarFile);
    inputPanel.releaseEditor(previewState);
  }
  public boolean validateConfiguration(CompileScope scope) {

    // Check for project sdk only if experimental make system is enabled (for now)
    Sdk projectSdk = ProjectRootManager.getInstance(project).getProjectSdk();
    if (projectSdk == null) {
      Messages.showErrorDialog(
          project,
          GoBundle.message("cannot.compile.no.go.project.sdk", project.getName()),
          GoBundle.message("cannot.compile"));
      return false;

    } else if (!(projectSdk.getSdkAdditionalData() instanceof GoSdkData)) {
      Messages.showErrorDialog(
          project,
          GoBundle.message("cannot.compile.invalid.project.sdk", project.getName()),
          GoBundle.message("cannot.compile"));
      return false;
    }

    return true;
  }
예제 #11
0
  public JTabbedPane createParseTreeAndProfileTabbedPanel() {
    JBTabbedPane tabbedPane = new JBTabbedPane();

    LOG.info("createParseTreePanel" + " " + project.getName());
    Pair<UberTreeViewer, JPanel> pair = createParseTreePanel();
    treeViewer = pair.a;
    tabbedPane.addTab("Parse tree", pair.b);

    profilerPanel = new ProfilerPanel(project);
    tabbedPane.addTab("Profiler", profilerPanel.$$$getRootComponent$$$());

    return tabbedPane;
  }
  /**
   * Returns the index of the project that has the given name, the project name is searched in the
   * list of opened projects
   *
   * @param name name of the project
   * @return the index of the project in the list of opened projects, 0 if not found
   */
  public int getProjectIndexWithName(String name) {
    int index = 0;
    Project projects[] = ProjectManager.getInstance().getOpenProjects();

    for (Project project : projects) {
      if (project.getName().equals(name)) {
        return index;
      }
      index++;
    }

    return 0;
  }
예제 #13
0
 private VirtualFile getTempDir(Module module) throws IOException {
   VirtualFile tempDir = myModuleToTempDirMap.get(module);
   if (tempDir == null) {
     final String projectName = myProject.getName();
     final String moduleName = module.getName();
     File tempDirectory = FileUtil.createTempDirectory(projectName, moduleName);
     tempDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory);
     if (tempDir == null) {
       LOG.error("Cannot locate temp directory " + tempDirectory.getPath());
     }
     myModuleToTempDirMap.put(module, tempDir);
   }
   return tempDir;
 }
  /**
   * Returns a list of Strings containing the names of the opened projects
   *
   * @return list of opened projects names
   */
  public String[] getOpenedProjectsNames() {

    Project[] projects = getOpenedProjects();

    String[] projectsNames = new String[projects.length];

    int index = 0;
    for (Project project : projects) {
      projectsNames[index] = project.getName();
      index++;
    }

    return projectsNames;
  }
  /**
   * Returns the project object that has the given name
   *
   * @param name project name to search for in the list of opened projects
   * @return project object or null if no project was found with the given name
   */
  public Project getProjectByName(String name) {

    if (name == null) {
      return null;
    }

    Project projects[] = ProjectManager.getInstance().getOpenProjects();

    for (Project project : projects) {
      if (project.getName().equals(name)) {
        return project;
      }
    }

    return null;
  }
  @Nullable
  private static PsiDirectory tryNotNullizeDirectory(
      @NotNull Project project, @Nullable PsiDirectory defaultTargetDirectory) {
    if (defaultTargetDirectory == null) {
      VirtualFile root =
          ArrayUtil.getFirstElement(ProjectRootManager.getInstance(project).getContentRoots());
      if (root == null) root = project.getBaseDir();
      if (root == null) root = VfsUtil.getUserHomeDir();
      defaultTargetDirectory =
          root != null ? PsiManager.getInstance(project).findDirectory(root) : null;

      if (defaultTargetDirectory == null) {
        LOG.warn("No directory found for project: " + project.getName() + ", root: " + root);
      }
    }
    return defaultTargetDirectory;
  }
 private static String replacePlaceHolders(String template, Project project) {
   String processedTemplate = template;
   String projectName = "";
   String projectBaseDir = "";
   String projectBaseDirName = "";
   if (null != project) {
     projectName = project.getName();
     projectBaseDir = project.getBasePath();
     projectBaseDirName = project.getBaseDir().getName();
   }
   processedTemplate = processedTemplate.replace(PROJECT_NAME.getVariableName(), projectName);
   processedTemplate =
       processedTemplate.replace(PROJECT_BASE_DIR_NAME.getVariableName(), projectBaseDirName);
   processedTemplate =
       processedTemplate.replace(PROJECT_BASE_DIR.getVariableName(), projectBaseDir);
   return processedTemplate;
 }
예제 #18
0
  public static String getProjectName() {
    DataContext dataContext = DataManager.getInstance().getDataContext();
    if (dataContext != null) {
      Project project = null;

      try {
        project = CommonDataKeys.PROJECT.getData(dataContext);
      } catch (NoClassDefFoundError e) {
        try {
          project = DataKeys.PROJECT.getData(dataContext);
        } catch (NoClassDefFoundError ex) {
        }
      }
      if (project != null) {
        return project.getName();
      }
    }
    return null;
  }
예제 #19
0
  /** Notify the preview tool window contents that the grammar file has changed */
  public void grammarFileSaved(VirtualFile grammarFile) {
    String grammarFileName = grammarFile.getPath();
    LOG.info("grammarFileSaved " + grammarFileName + " " + project.getName());
    ANTLRv4PluginController controller = ANTLRv4PluginController.getInstance(project);
    PreviewState previewState = controller.getPreviewState(grammarFile);

    ensureStartRuleExists(grammarFile);
    inputPanel.grammarFileSaved(grammarFile);

    // if the saved grammar is not a pure lexer and there is a start rule, reparse
    // means that switching grammars must refresh preview
    if (previewState.g != null && previewState.startRuleName != null) {
      updateParseTreeFromDoc(previewState.grammarFile);
    } else {
      setParseTree(Collections.<String>emptyList(), null); // blank tree
    }

    profilerPanel.grammarFileSaved(previewState, grammarFile);
  }
 private static void renameProject(
     @NotNull final String newName,
     @NotNull final ProjectSystemId externalSystemId,
     @NotNull final Project project) {
   if (!(project instanceof ProjectEx) || newName.equals(project.getName())) {
     return;
   }
   ExternalSystemApiUtil.executeProjectChangeAction(
       true,
       new DisposeAwareProjectChange(project) {
         @Override
         public void execute() {
           String oldName = project.getName();
           ((ProjectEx) project).setProjectName(newName);
           ExternalSystemApiUtil.getSettings(project, externalSystemId)
               .getPublisher()
               .onProjectRenamed(oldName, newName);
         }
       });
 }
  @NotNull
  private static Course getCourse(
      @NotNull Project project,
      @NotNull String name,
      @NotNull String[] authors,
      @NotNull String description) {
    final Course course = new Course();
    course.setName(name);
    course.setAuthors(authors);
    course.setDescription(description);
    course.setLanguage(PythonLanguage.getInstance().getID());
    course.setCourseMode(CCUtils.COURSE_MODE);

    File coursesDir = new File(PathManager.getConfigPath(), "courses");
    File courseDir = new File(coursesDir, name + "-" + project.getName());
    course.setCourseDirectory(courseDir.getPath());

    StudyTaskManager.getInstance(project).setCourse(course);
    StudyProjectComponent.getInstance(project).registerStudyToolWindow(course);
    return course;
  }
예제 #22
0
  /** Load grammars and set editor component. */
  public void switchToGrammar(VirtualFile oldFile, VirtualFile grammarFile) {
    String grammarFileName = grammarFile.getPath();
    LOG.info("switchToGrammar " + grammarFileName + " " + project.getName());
    ANTLRv4PluginController controller = ANTLRv4PluginController.getInstance(project);
    PreviewState previewState = controller.getPreviewState(grammarFile);

    inputPanel.switchToGrammar(grammarFile);

    if (previewState.startRuleName != null) {
      updateParseTreeFromDoc(grammarFile);
    } else {
      setParseTree(Collections.<String>emptyList(), null); // blank tree
    }

    profilerPanel.switchToGrammar(previewState, grammarFile);

    if (previewState.g == null && previewState.lg != null) {
      setEnabled(false);
    } else {
      setEnabled(true);
    }
  }
 public void checkWorkingDirectoryExist(
     CommonProgramRunConfigurationParameters configuration, Project project, Module module)
     throws RuntimeConfigurationWarning {
   final String workingDir = getWorkingDir(configuration, project, module);
   if (workingDir == null) {
     throw new RuntimeConfigurationWarning(
         "Working directory is null for "
             + "project '"
             + project.getName()
             + "' ("
             + project.getBasePath()
             + ")"
             + ", module '"
             + module.getName()
             + "' ("
             + module.getModuleFilePath()
             + ")");
   }
   if (!new File(workingDir).exists()) {
     throw new RuntimeConfigurationWarning("Working directory '" + workingDir + "' doesn't exist");
   }
 }
  public void bindModuleSettings() {

    myNamePathComponent
        .getNameComponent()
        .getDocument()
        .addDocumentListener(
            new DocumentAdapter() {
              protected void textChanged(final DocumentEvent e) {
                if (!myModuleNameChangedByUser) {
                  setModuleName(myNamePathComponent.getNameValue());
                }
              }
            });

    myModuleContentRoot.addBrowseFolderListener(
        ProjectBundle.message("project.new.wizard.module.content.root.chooser.title"),
        ProjectBundle.message("project.new.wizard.module.content.root.chooser.description"),
        myWizardContext.getProject(),
        BrowseFilesListener.SINGLE_DIRECTORY_DESCRIPTOR);

    myNamePathComponent
        .getPathComponent()
        .getDocument()
        .addDocumentListener(
            new DocumentAdapter() {
              protected void textChanged(final DocumentEvent e) {
                if (!myContentRootChangedByUser) {
                  setModuleContentRoot(myNamePathComponent.getPath());
                }
              }
            });
    myModuleName
        .getDocument()
        .addDocumentListener(
            new DocumentAdapter() {
              protected void textChanged(final DocumentEvent e) {
                if (myModuleNameDocListenerEnabled) {
                  myModuleNameChangedByUser = true;
                }
                String path = getDefaultBaseDir(myWizardContext);
                final String moduleName = getModuleName();
                if (path.length() > 0
                    && !Comparing.strEqual(moduleName, myNamePathComponent.getNameValue())) {
                  path += "/" + moduleName;
                }
                if (!myContentRootChangedByUser) {
                  final boolean f = myModuleNameChangedByUser;
                  myModuleNameChangedByUser = true;
                  setModuleContentRoot(path);
                  myModuleNameChangedByUser = f;
                }
                if (!myImlLocationChangedByUser) {
                  setImlFileLocation(path);
                }
              }
            });
    myModuleContentRoot
        .getTextField()
        .getDocument()
        .addDocumentListener(
            new DocumentAdapter() {
              protected void textChanged(final DocumentEvent e) {
                if (myContentRootDocListenerEnabled) {
                  myContentRootChangedByUser = true;
                }
                if (!myImlLocationChangedByUser) {
                  setImlFileLocation(getModuleContentRoot());
                }
                if (!myModuleNameChangedByUser) {
                  final String path = FileUtil.toSystemIndependentName(getModuleContentRoot());
                  final int idx = path.lastIndexOf("/");

                  boolean f = myContentRootChangedByUser;
                  myContentRootChangedByUser = true;

                  boolean i = myImlLocationChangedByUser;
                  myImlLocationChangedByUser = true;

                  setModuleName(idx >= 0 ? path.substring(idx + 1) : "");

                  myContentRootChangedByUser = f;
                  myImlLocationChangedByUser = i;
                }
              }
            });

    myModuleFileLocation.addBrowseFolderListener(
        ProjectBundle.message("project.new.wizard.module.file.chooser.title"),
        ProjectBundle.message("project.new.wizard.module.file.description"),
        myWizardContext.getProject(),
        BrowseFilesListener.SINGLE_DIRECTORY_DESCRIPTOR);
    myModuleFileLocation
        .getTextField()
        .getDocument()
        .addDocumentListener(
            new DocumentAdapter() {
              protected void textChanged(final DocumentEvent e) {
                if (myImlLocationDocListenerEnabled) {
                  myImlLocationChangedByUser = true;
                }
              }
            });
    myNamePathComponent
        .getPathComponent()
        .getDocument()
        .addDocumentListener(
            new DocumentAdapter() {
              protected void textChanged(final DocumentEvent e) {
                if (!myImlLocationChangedByUser) {
                  setImlFileLocation(myNamePathComponent.getPath());
                }
              }
            });
    if (myWizardContext.isCreatingNewProject()) {
      setModuleName(myNamePathComponent.getNameValue());
      setModuleContentRoot(myNamePathComponent.getPath());
      setImlFileLocation(myNamePathComponent.getPath());
    } else {
      final Project project = myWizardContext.getProject();
      assert project != null;
      VirtualFile baseDir = project.getBaseDir();
      if (baseDir != null) { // e.g. was deleted
        final String baseDirPath = baseDir.getPath();
        String moduleName = ProjectWizardUtil.findNonExistingFileName(baseDirPath, "untitled", "");
        String contentRoot = baseDirPath + "/" + moduleName;
        if (!Comparing.strEqual(project.getName(), myWizardContext.getProjectName())
            && !myWizardContext.isCreatingNewProject()
            && myWizardContext.getProjectName() != null) {
          moduleName =
              ProjectWizardUtil.findNonExistingFileName(
                  myWizardContext.getProjectFileDirectory(), myWizardContext.getProjectName(), "");
          contentRoot = myWizardContext.getProjectFileDirectory();
        }
        setModuleName(moduleName);
        setModuleContentRoot(contentRoot);
        setImlFileLocation(contentRoot);
        myModuleName.select(0, moduleName.length());
      }
    }
  }
  public static void runCheck(@NotNull final Project project) {
    List<DependencyOnPlugin> dependencies =
        ExternalDependenciesManager.getInstance(project).getDependencies(DependencyOnPlugin.class);
    if (dependencies.isEmpty()) return;

    List<String> customRepositories = UpdateSettings.getInstance().getStoredPluginHosts();

    final List<String> errorMessages = new ArrayList<String>();
    final List<String> missingCustomRepositories = new ArrayList<String>();
    final List<IdeaPluginDescriptor> disabled = new ArrayList<IdeaPluginDescriptor>();
    final List<PluginId> notInstalled = new ArrayList<PluginId>();
    for (DependencyOnPlugin dependency : dependencies) {
      PluginId pluginId = PluginId.getId(dependency.getPluginId());
      String channel = dependency.getChannel();
      String customRepository = getCustomRepository(pluginId, channel);
      if (!StringUtil.isEmpty(channel)
          && customRepositoryNotSpecified(customRepositories, customRepository)) {
        errorMessages.add(
            "Custom repository '"
                + customRepository
                + "' required for '"
                + project.getName()
                + "' project isn't installed.");
        missingCustomRepositories.add(customRepository);
      }
      IdeaPluginDescriptor plugin = PluginManager.getPlugin(pluginId);
      if (plugin == null) {
        errorMessages.add(
            "Plugin '"
                + dependency.getPluginId()
                + "' required for '"
                + project.getName()
                + "' project isn't installed.");
        notInstalled.add(pluginId);
        continue;
      }
      if (!plugin.isEnabled()) {
        errorMessages.add(
            "Plugin '"
                + plugin.getName()
                + "' required for '"
                + project.getName()
                + "' project is disabled.");
        disabled.add(plugin);
        continue;
      }
      String minVersion = dependency.getMinVersion();
      if (minVersion != null
          && VersionComparatorUtil.compare(plugin.getVersion(), minVersion) < 0) {
        errorMessages.add(
            "Project '"
                + project.getName()
                + "' requires plugin  '"
                + plugin.getName()
                + "' version '"
                + minVersion
                + "' or higher, but '"
                + plugin.getVersion()
                + "' is installed.");
      }
      String maxVersion = dependency.getMaxVersion();
      if (maxVersion != null
          && VersionComparatorUtil.compare(plugin.getVersion(), maxVersion) > 0) {
        errorMessages.add(
            "Project '"
                + project.getName()
                + "' requires plugin  '"
                + plugin.getName()
                + "' version '"
                + minVersion
                + "' or lower, but '"
                + plugin.getVersion()
                + "' is installed.");
      }
    }

    if (!errorMessages.isEmpty()) {
      if (!missingCustomRepositories.isEmpty()) {
        errorMessages.add(
            "<a href=\"addRepositories\">Add custom repositories and install required plugins</a>");
      } else if (!disabled.isEmpty() && notInstalled.isEmpty()) {
        String plugins = disabled.size() == 1 ? disabled.get(0).getName() : "required plugins";
        errorMessages.add("<a href=\"enable\">Enable " + plugins + "</a>");
      } else if (!disabled.isEmpty() || !notInstalled.isEmpty()) {
        errorMessages.add("<a href=\"install\">Install required plugins</a>");
      }
      NOTIFICATION_GROUP
          .createNotification(
              "Required plugins weren't loaded",
              StringUtil.join(errorMessages, "<br>"),
              NotificationType.ERROR,
              new NotificationListener() {
                @Override
                public void hyperlinkUpdate(
                    @NotNull final Notification notification, @NotNull HyperlinkEvent event) {
                  if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                    if ("addRepositories".equals(event.getDescription())) {
                      UpdateSettings.getInstance()
                          .getStoredPluginHosts()
                          .addAll(missingCustomRepositories);
                    }
                    if ("enable".equals(event.getDescription())) {
                      notification.expire();
                      for (IdeaPluginDescriptor descriptor : disabled) {
                        PluginManagerCore.enablePlugin(descriptor.getPluginId().getIdString());
                      }
                      PluginManagerMain.notifyPluginsUpdated(project);
                    } else if ("install".equals(event.getDescription())
                        || "addRepositories".equals(event.getDescription())) {
                      Set<String> pluginIds = new HashSet<String>();
                      for (IdeaPluginDescriptor descriptor : disabled) {
                        pluginIds.add(descriptor.getPluginId().getIdString());
                      }
                      for (PluginId pluginId : notInstalled) {
                        pluginIds.add(pluginId.getIdString());
                      }
                      PluginsAdvertiser.installAndEnablePlugins(
                          pluginIds, () -> notification.expire());
                    }
                  }
                }
              })
          .notify(project);
    }
  }
  @Nullable
  public static String findResourcesCacheDirectory(
      @NotNull Module module, boolean createIfNotFound, @Nullable CompileContext context) {
    final Project project = module.getProject();

    final CompilerProjectExtension extension = CompilerProjectExtension.getInstance(project);
    if (extension == null) {
      if (context != null) {
        context.addMessage(
            CompilerMessageCategory.ERROR,
            "Cannot get compiler settings for project " + project.getName(),
            null,
            -1,
            -1);
      }
      return null;
    }

    final String projectOutputDirUrl = extension.getCompilerOutputUrl();
    if (projectOutputDirUrl == null) {
      if (context != null) {
        context.addMessage(
            CompilerMessageCategory.ERROR,
            "Cannot find output directory for project " + project.getName(),
            null,
            -1,
            -1);
      }
      return null;
    }

    final String pngCacheDirPath =
        VfsUtil.urlToPath(projectOutputDirUrl)
            + '/'
            + RESOURCES_CACHE_DIR_NAME
            + '/'
            + module.getName();
    final String pngCacheDirOsPath = FileUtil.toSystemDependentName(pngCacheDirPath);

    final File pngCacheDir = new File(pngCacheDirOsPath);
    if (pngCacheDir.exists()) {
      if (pngCacheDir.isDirectory()) {
        return pngCacheDirOsPath;
      } else {
        if (context != null) {
          context.addMessage(
              CompilerMessageCategory.ERROR,
              "Cannot create directory " + pngCacheDirOsPath + " because file already exists",
              null,
              -1,
              -1);
        }
        return null;
      }
    }

    if (!createIfNotFound) {
      return null;
    }

    if (!pngCacheDir.mkdirs()) {
      if (context != null) {
        context.addMessage(
            CompilerMessageCategory.ERROR,
            "Cannot create directory " + pngCacheDirOsPath,
            null,
            -1,
            -1);
      }
      return null;
    }

    return pngCacheDirOsPath;
  }
  public ProjectNameWithTypeStep(
      final WizardContext wizardContext, StepSequence sequence, final WizardMode mode) {
    super(wizardContext, mode);
    mySequence = sequence;
    myAdditionalContentPanel.add(
        myModulePanel,
        new GridBagConstraints(
            0,
            GridBagConstraints.RELATIVE,
            1,
            1,
            1,
            1,
            GridBagConstraints.NORTHWEST,
            GridBagConstraints.BOTH,
            new Insets(0, 0, 0, 0),
            0,
            0));
    myHeader.setVisible(myWizardContext.isCreatingNewProject() && !isCreateFromTemplateMode());
    myCreateModuleCb.addActionListener(
        new ActionListener() {
          public void actionPerformed(final ActionEvent e) {
            UIUtil.setEnabled(myInternalPanel, myCreateModuleCb.isSelected(), true);
            fireStateChanged();
          }
        });
    myCreateModuleCb.setSelected(true);
    if (!myWizardContext.isCreatingNewProject()) {
      myInternalPanel.setBorder(null);
    }
    myModuleDescriptionPane.setContentType(UIUtil.HTML_MIME);
    myModuleDescriptionPane.addHyperlinkListener(
        new HyperlinkListener() {
          public void hyperlinkUpdate(HyperlinkEvent e) {
            if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
              try {
                BrowserUtil.launchBrowser(e.getURL().toString());
              } catch (IllegalThreadStateException ex) {
                // it's nnot a problem
              }
            }
          }
        });
    myModuleDescriptionPane.setEditable(false);

    final DefaultListModel defaultListModel = new DefaultListModel();
    for (ModuleBuilder builder : ModuleBuilder.getAllBuilders()) {
      defaultListModel.addElement(builder);
    }
    myTypesList.setModel(defaultListModel);
    myTypesList.setSelectionModel(new PermanentSingleSelectionModel());
    myTypesList.setCellRenderer(
        new DefaultListCellRenderer() {
          public Component getListCellRendererComponent(
              final JList list,
              final Object value,
              final int index,
              final boolean isSelected,
              final boolean cellHasFocus) {
            final Component rendererComponent =
                super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            final ModuleBuilder builder = (ModuleBuilder) value;
            setIcon(builder.getBigIcon());
            setDisabledIcon(builder.getBigIcon());
            setText(builder.getPresentableName());
            return rendererComponent;
          }
        });
    myTypesList.addListSelectionListener(
        new ListSelectionListener() {
          @SuppressWarnings({"HardCodedStringLiteral"})
          public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting()) {
              return;
            }

            final ModuleBuilder typeSelected = (ModuleBuilder) myTypesList.getSelectedValue();

            final StringBuilder sb = new StringBuilder("<html><body><font face=\"Verdana\" ");
            sb.append(SystemInfo.isMac ? "" : "size=\"-1\"").append('>');
            sb.append(typeSelected.getDescription()).append("</font></body></html>");

            myModuleDescriptionPane.setText(sb.toString());

            boolean focusOwner = myTypesList.isFocusOwner();
            fireStateChanged();
            if (focusOwner) {
              SwingUtilities.invokeLater(
                  new Runnable() {
                    public void run() {
                      myTypesList.requestFocusInWindow();
                    }
                  });
            }
          }
        });
    myTypesList.setSelectedIndex(0);
    new DoubleClickListener() {
      @Override
      protected boolean onDoubleClick(MouseEvent e) {
        myWizardContext.requestNextStep();
        return true;
      }
    }.installOn(myTypesList);

    final Dimension preferredSize = calcTypeListPreferredSize(ModuleBuilder.getAllBuilders());
    final JBScrollPane pane = IJSwingUtilities.findParentOfType(myTypesList, JBScrollPane.class);
    pane.setPreferredSize(preferredSize);
    pane.setMinimumSize(preferredSize);

    myNamePathComponent
        .getNameComponent()
        .getDocument()
        .addDocumentListener(
            new DocumentAdapter() {
              protected void textChanged(final DocumentEvent e) {
                if (!myModuleNameChangedByUser) {
                  setModuleName(myNamePathComponent.getNameValue());
                }
              }
            });

    myModuleContentRoot.addBrowseFolderListener(
        ProjectBundle.message("project.new.wizard.module.content.root.chooser.title"),
        ProjectBundle.message("project.new.wizard.module.content.root.chooser.description"),
        myWizardContext.getProject(),
        BrowseFilesListener.SINGLE_DIRECTORY_DESCRIPTOR);

    myNamePathComponent
        .getPathComponent()
        .getDocument()
        .addDocumentListener(
            new DocumentAdapter() {
              protected void textChanged(final DocumentEvent e) {
                if (!myContentRootChangedByUser) {
                  setModuleContentRoot(myNamePathComponent.getPath());
                }
              }
            });
    myModuleName
        .getDocument()
        .addDocumentListener(
            new DocumentAdapter() {
              protected void textChanged(final DocumentEvent e) {
                if (myModuleNameDocListenerEnabled) {
                  myModuleNameChangedByUser = true;
                }
                String path = getDefaultBaseDir(wizardContext);
                final String moduleName = getModuleName();
                if (path.length() > 0
                    && !Comparing.strEqual(moduleName, myNamePathComponent.getNameValue())) {
                  path += "/" + moduleName;
                }
                if (!myContentRootChangedByUser) {
                  final boolean f = myModuleNameChangedByUser;
                  myModuleNameChangedByUser = true;
                  setModuleContentRoot(path);
                  myModuleNameChangedByUser = f;
                }
                if (!myImlLocationChangedByUser) {
                  setImlFileLocation(path);
                }
              }
            });
    myModuleContentRoot
        .getTextField()
        .getDocument()
        .addDocumentListener(
            new DocumentAdapter() {
              protected void textChanged(final DocumentEvent e) {
                if (myContentRootDocListenerEnabled) {
                  myContentRootChangedByUser = true;
                }
                if (!myImlLocationChangedByUser) {
                  setImlFileLocation(myModuleContentRoot.getText());
                }
                if (!myModuleNameChangedByUser) {
                  final String path =
                      FileUtil.toSystemIndependentName(myModuleContentRoot.getText());
                  final int idx = path.lastIndexOf("/");

                  boolean f = myContentRootChangedByUser;
                  myContentRootChangedByUser = true;

                  boolean i = myImlLocationChangedByUser;
                  myImlLocationChangedByUser = true;

                  setModuleName(idx >= 0 ? path.substring(idx + 1) : "");

                  myContentRootChangedByUser = f;
                  myImlLocationChangedByUser = i;
                }
              }
            });

    myModuleFileLocation.addBrowseFolderListener(
        ProjectBundle.message("project.new.wizard.module.file.chooser.title"),
        ProjectBundle.message("project.new.wizard.module.file.description"),
        myWizardContext.getProject(),
        BrowseFilesListener.SINGLE_DIRECTORY_DESCRIPTOR);
    myModuleFileLocation
        .getTextField()
        .getDocument()
        .addDocumentListener(
            new DocumentAdapter() {
              protected void textChanged(final DocumentEvent e) {
                if (myImlLocationDocListenerEnabled) {
                  myImlLocationChangedByUser = true;
                }
              }
            });
    myNamePathComponent
        .getPathComponent()
        .getDocument()
        .addDocumentListener(
            new DocumentAdapter() {
              protected void textChanged(final DocumentEvent e) {
                if (!myImlLocationChangedByUser) {
                  setImlFileLocation(myNamePathComponent.getPath());
                }
              }
            });
    if (wizardContext.isCreatingNewProject()) {
      setModuleName(myNamePathComponent.getNameValue());
      setModuleContentRoot(myNamePathComponent.getPath());
      setImlFileLocation(myNamePathComponent.getPath());
    } else {
      final Project project = wizardContext.getProject();
      assert project != null;
      VirtualFile baseDir = project.getBaseDir();
      if (baseDir != null) { // e.g. was deleted
        final String baseDirPath = baseDir.getPath();
        String moduleName = ProjectWizardUtil.findNonExistingFileName(baseDirPath, "untitled", "");
        String contentRoot = baseDirPath + "/" + moduleName;
        if (!Comparing.strEqual(project.getName(), wizardContext.getProjectName())
            && !wizardContext.isCreatingNewProject()
            && wizardContext.getProjectName() != null) {
          moduleName =
              ProjectWizardUtil.findNonExistingFileName(
                  wizardContext.getProjectFileDirectory(), wizardContext.getProjectName(), "");
          contentRoot = wizardContext.getProjectFileDirectory();
        }
        setModuleName(moduleName);
        setModuleContentRoot(contentRoot);
        setImlFileLocation(contentRoot);
        myModuleName.select(0, moduleName.length());
      }
    }

    if (isCreateFromTemplateMode()) {
      replaceModuleTypeOptions(new JPanel());
    } else {
      final AnAction arrow =
          new AnAction() {
            @Override
            public void actionPerformed(AnActionEvent e) {
              if (e.getInputEvent() instanceof KeyEvent) {
                final int code = ((KeyEvent) e.getInputEvent()).getKeyCode();
                if (!myCreateModuleCb.isSelected()) return;
                int i = myTypesList.getSelectedIndex();
                if (code == KeyEvent.VK_DOWN) {
                  if (++i == myTypesList.getModel().getSize()) return;
                } else if (code == KeyEvent.VK_UP) {
                  if (--i == -1) return;
                }
                myTypesList.setSelectedIndex(i);
              }
            }
          };
      CustomShortcutSet shortcutSet = new CustomShortcutSet(KeyEvent.VK_UP, KeyEvent.VK_DOWN);
      arrow.registerCustomShortcutSet(shortcutSet, myNamePathComponent.getNameComponent());
      arrow.registerCustomShortcutSet(shortcutSet, myModuleName);
    }
  }
예제 #28
0
 // TODO remove in IDEA 15
 private static void cleanupOldNaming(
     @NotNull Project project, @NotNull Map<VirtualFile, VcsLogProvider> providers) {
   int hashcode = calcLogProvidersHash(providers);
   String oldLogId = project.getName() + "." + hashcode;
   FileUtil.delete(new File(new File(PathManager.getSystemPath(), "vcs-log"), oldLogId));
 }
 @NotNull
 @Override
 public Object getIntellijKey(@NotNull Project entity) {
   return entity.getName();
 }
 protected Module createMainModule() throws IOException {
   return createModule(myProject.getName());
 }