public void testHardLinks() throws Exception {
    if (!SystemInfo.isWindows && !SystemInfo.isUnix) {
      System.err.println(getName() + " skipped: " + SystemInfo.OS_NAME);
      return;
    }

    final boolean safeWrite = GeneralSettings.getInstance().isUseSafeWrite();
    final File dir = FileUtil.createTempDirectory("hardlinks.", ".dir", false);
    final SafeWriteRequestor requestor = new SafeWriteRequestor() {};
    try {
      GeneralSettings.getInstance().setUseSafeWrite(false);

      final File targetFile = new File(dir, "targetFile");
      assertTrue(targetFile.createNewFile());
      final File hardLinkFile =
          IoTestUtil.createHardLink(targetFile.getAbsolutePath(), "hardLinkFile");

      final VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(targetFile);
      assertNotNull(file);
      file.setBinaryContent("hello".getBytes("UTF-8"), 0, 0, requestor);
      assertTrue(file.getLength() > 0);

      final VirtualFile check =
          LocalFileSystem.getInstance().refreshAndFindFileByIoFile(hardLinkFile);
      assertNotNull(check);
      assertEquals(file.getLength(), check.getLength());
      assertEquals("hello", VfsUtilCore.loadText(check));
    } finally {
      GeneralSettings.getInstance().setUseSafeWrite(safeWrite);
      FileUtil.delete(dir);
    }
  }
 /**
  * @return {@link com.intellij.ide.GeneralSettings#OPEN_PROJECT_SAME_WINDOW} {@link
  *     com.intellij.ide.GeneralSettings#OPEN_PROJECT_NEW_WINDOW} {@link
  *     com.intellij.openapi.ui.Messages#CANCEL} - if user canceled the dialog
  * @param isNewProject
  */
 public static int confirmOpenNewProject(boolean isNewProject) {
   final GeneralSettings settings = GeneralSettings.getInstance();
   int confirmOpenNewProject =
       ApplicationManager.getApplication().isUnitTestMode()
           ? GeneralSettings.OPEN_PROJECT_NEW_WINDOW
           : settings.getConfirmOpenNewProject();
   if (confirmOpenNewProject == GeneralSettings.OPEN_PROJECT_ASK) {
     if (isNewProject) {
       int exitCode =
           Messages.showYesNoDialog(
               IdeBundle.message("prompt.open.project.in.new.frame"),
               IdeBundle.message("title.new.project"),
               IdeBundle.message("button.existingframe"),
               IdeBundle.message("button.newframe"),
               Messages.getQuestionIcon(),
               new ProjectNewWindowDoNotAskOption());
       return exitCode == Messages.YES
           ? GeneralSettings.OPEN_PROJECT_SAME_WINDOW
           : GeneralSettings.OPEN_PROJECT_NEW_WINDOW;
     } else {
       int exitCode =
           Messages.showYesNoCancelDialog(
               IdeBundle.message("prompt.open.project.in.new.frame"),
               IdeBundle.message("title.open.project"),
               IdeBundle.message("button.existingframe"),
               IdeBundle.message("button.newframe"),
               CommonBundle.getCancelButtonText(),
               Messages.getQuestionIcon(),
               new ProjectNewWindowDoNotAskOption());
       return exitCode == Messages.YES
           ? GeneralSettings.OPEN_PROJECT_SAME_WINDOW
           : exitCode == Messages.NO ? GeneralSettings.OPEN_PROJECT_NEW_WINDOW : Messages.CANCEL;
     }
   }
   return confirmOpenNewProject;
 }
  @Override
  protected void browseUsingNotSystemDefaultBrowserPolicy(
      @NotNull URI uri, @NotNull GeneralSettings settings, @Nullable Project project) {
    WebBrowserManager browserManager = WebBrowserManager.getInstance();
    if (browserManager.getDefaultBrowserPolicy() == DefaultBrowserPolicy.FIRST
        || (SystemInfo.isMac && "open".equals(settings.getBrowserPath()))) {
      WebBrowser browser = browserManager.getFirstActiveBrowser();
      if (browser != null) {
        browseUsingPath(uri.toString(), null, browser, project, ArrayUtil.EMPTY_STRING_ARRAY);
        return;
      }
    }

    super.browseUsingNotSystemDefaultBrowserPolicy(uri, settings, project);
  }
 @Nullable
 public static WebBrowser findUsingBrowser() {
   WebBrowserManager browserManager = WebBrowserManager.getInstance();
   DefaultBrowserPolicy defaultBrowserPolicy = browserManager.getDefaultBrowserPolicy();
   if (defaultBrowserPolicy == DefaultBrowserPolicy.FIRST
       || (defaultBrowserPolicy == DefaultBrowserPolicy.SYSTEM
           && !BrowserLauncherAppless.canUseSystemDefaultBrowserPolicy())) {
     return browserManager.getFirstActiveBrowser();
   } else if (defaultBrowserPolicy == DefaultBrowserPolicy.ALTERNATIVE) {
     String path = GeneralSettings.getInstance().getBrowserPath();
     if (!StringUtil.isEmpty(path)) {
       WebBrowser browser = browserManager.findBrowserById(path);
       if (browser == null) {
         for (WebBrowser item : browserManager.getActiveBrowsers()) {
           if (path.equals(item.getPath())) {
             return item;
           }
         }
       }
     }
   }
   return null;
 }
  /** @noinspection UnusedParameters */
  public PyCharmEduInitialConfigurator(
      MessageBus bus,
      CodeInsightSettings codeInsightSettings,
      final PropertiesComponent propertiesComponent,
      FileTypeManager fileTypeManager,
      final ProjectManagerEx projectManager) {
    if (!propertiesComponent.getBoolean(CONFIGURED, false)) {
      propertiesComponent.setValue(CONFIGURED, "true");
      propertiesComponent.setValue("toolwindow.stripes.buttons.info.shown", "true");
      UISettings uiSettings = UISettings.getInstance();
      uiSettings.HIDE_TOOL_STRIPES = false;
      uiSettings.SHOW_MEMORY_INDICATOR = false;
      uiSettings.SHOW_DIRECTORY_FOR_NON_UNIQUE_FILENAMES = true;
      uiSettings.SHOW_MAIN_TOOLBAR = false;
      uiSettings.SHOW_NAVIGATION_BAR = false;
      codeInsightSettings.REFORMAT_ON_PASTE = CodeInsightSettings.NO_REFORMAT;

      Registry.get("ide.new.settings.dialog").setValue(true);

      GeneralSettings.getInstance().setShowTipsOnStartup(false);

      EditorSettingsExternalizable.getInstance().setVirtualSpace(false);
      EditorSettingsExternalizable.getInstance().getOptions().ARE_LINE_NUMBERS_SHOWN = true;
      final CodeStyleSettings settings =
          CodeStyleSettingsManager.getInstance().getCurrentSettings();
      settings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS = true;
      settings.getCommonSettings(PythonLanguage.getInstance()).ALIGN_MULTILINE_PARAMETERS_IN_CALLS =
          true;
      uiSettings.SHOW_DIRECTORY_FOR_NON_UNIQUE_FILENAMES = true;
      uiSettings.SHOW_MEMORY_INDICATOR = false;
      final String ignoredFilesList = fileTypeManager.getIgnoredFilesList();
      ApplicationManager.getApplication()
          .invokeLater(
              new Runnable() {
                @Override
                public void run() {
                  ApplicationManager.getApplication()
                      .runWriteAction(
                          new Runnable() {
                            @Override
                            public void run() {
                              FileTypeManager.getInstance()
                                  .setIgnoredFilesList(ignoredFilesList + ";*$py.class");
                            }
                          });
                }
              });
      PyCodeInsightSettings.getInstance().SHOW_IMPORT_POPUP = false;
    }

    if (!propertiesComponent.isValueSet(DISPLAYED_PROPERTY)) {

      bus.connect()
          .subscribe(
              AppLifecycleListener.TOPIC,
              new AppLifecycleListener.Adapter() {
                @Override
                public void welcomeScreenDisplayed() {

                  ApplicationManager.getApplication()
                      .invokeLater(
                          new Runnable() {
                            @Override
                            public void run() {
                              if (!propertiesComponent.isValueSet(DISPLAYED_PROPERTY)) {
                                GeneralSettings.getInstance().setShowTipsOnStartup(false);
                                propertiesComponent.setValue(DISPLAYED_PROPERTY, "true");

                                patchKeymap();
                              }
                            }
                          });
                }
              });
    }

    bus.connect()
        .subscribe(
            ProjectManager.TOPIC,
            new ProjectManagerAdapter() {
              @Override
              public void projectOpened(final Project project) {
                if (project.isDefault()) return;
                if (FileChooserUtil.getLastOpenedFile(project) == null) {
                  FileChooserUtil.setLastOpenedFile(project, VfsUtil.getUserHomeDir());
                }

                patchProjectAreaExtensions(project);

                StartupManager.getInstance(project)
                    .runWhenProjectIsInitialized(
                        new DumbAwareRunnable() {
                          @Override
                          public void run() {
                            if (project.isDisposed()) return;

                            ToolWindowManager.getInstance(project)
                                .invokeLater(
                                    new Runnable() {
                                      int count = 0;

                                      public void run() {
                                        if (project.isDisposed()) return;
                                        if (count++
                                            < 3) { // we need to call this after
                                                   // ToolWindowManagerImpl.registerToolWindowsFromBeans
                                          ToolWindowManager.getInstance(project).invokeLater(this);
                                          return;
                                        }
                                        ToolWindow toolWindow =
                                            ToolWindowManager.getInstance(project)
                                                .getToolWindow("Project");
                                        if (toolWindow.getType() != ToolWindowType.SLIDING) {
                                          toolWindow.activate(null);
                                        }
                                      }
                                    });
                          }
                        });
              }
            });
  }
  public void actionPerformed(final AnActionEvent e) {
    Project project = e.getData(PlatformDataKeys.PROJECT);
    NewDirectoryProjectDialog dlg = new NewDirectoryProjectDialog(project);
    dlg.show();
    if (dlg.getExitCode() != DialogWrapper.OK_EXIT_CODE) return;
    final DirectoryProjectGenerator generator = dlg.getProjectGenerator();
    final File location = new File(dlg.getNewProjectLocation());
    if (!location.exists() && !location.mkdirs()) {
      Messages.showErrorDialog(
          project, "Cannot create directory '" + location + "'", "Create Project");
      return;
    }

    final VirtualFile baseDir =
        ApplicationManager.getApplication()
            .runWriteAction(
                new Computable<VirtualFile>() {
                  public VirtualFile compute() {
                    return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(location);
                  }
                });
    baseDir.refresh(false, true);

    if (baseDir.getChildren().length > 0) {
      int rc =
          Messages.showYesNoDialog(
              project,
              "The directory '"
                  + location
                  + "' is not empty. Would you like to create a project from existing sources instead?",
              "Create New Project",
              Messages.getQuestionIcon());
      if (rc == 0) {
        PlatformProjectOpenProcessor.getInstance().doOpenProject(baseDir, null, false);
        return;
      }
    }

    Object settings = null;
    if (generator != null) {
      try {
        settings = generator.showGenerationSettings(baseDir);
      } catch (ProcessCanceledException e1) {
        return;
      }
    }
    GeneralSettings.getInstance().setLastProjectLocation(location.getParent());
    final Object finalSettings = settings;
    PlatformProjectOpenProcessor.doOpenProject(
        baseDir,
        null,
        false,
        -1,
        new ProjectOpenedCallback() {
          @Override
          public void projectOpened(Project project, Module module) {
            if (generator != null) {
              generator.generateProject(project, baseDir, finalSettings, module);
            }
          }
        },
        true);
  }
  /** @noinspection UnusedParameters */
  public PyCharmEduInitialConfigurator(
      MessageBus bus,
      CodeInsightSettings codeInsightSettings,
      final PropertiesComponent propertiesComponent,
      FileTypeManager fileTypeManager,
      final ProjectManagerEx projectManager) {
    final UISettings uiSettings = UISettings.getInstance();
    if (!propertiesComponent.getBoolean(CONFIGURED_V2)) {
      EditorSettingsExternalizable editorSettings = EditorSettingsExternalizable.getInstance();
      editorSettings.setEnsureNewLineAtEOF(true);

      propertiesComponent.setValue(CONFIGURED_V2, true);
    }
    if (!propertiesComponent.getBoolean(CONFIGURED_V1)) {
      patchMainMenu();
      uiSettings.SHOW_NAVIGATION_BAR = false;
      propertiesComponent.setValue(CONFIGURED_V1, true);
      propertiesComponent.setValue("ShowDocumentationInToolWindow", true);
    }

    if (!propertiesComponent.getBoolean(CONFIGURED)) {
      propertiesComponent.setValue(CONFIGURED, "true");
      propertiesComponent.setValue("toolwindow.stripes.buttons.info.shown", "true");

      uiSettings.HIDE_TOOL_STRIPES = false;
      uiSettings.SHOW_MEMORY_INDICATOR = false;
      uiSettings.SHOW_DIRECTORY_FOR_NON_UNIQUE_FILENAMES = true;
      uiSettings.SHOW_MAIN_TOOLBAR = false;

      codeInsightSettings.REFORMAT_ON_PASTE = CodeInsightSettings.NO_REFORMAT;

      GeneralSettings.getInstance().setShowTipsOnStartup(false);

      EditorSettingsExternalizable.getInstance().setVirtualSpace(false);
      EditorSettingsExternalizable.getInstance().getOptions().ARE_LINE_NUMBERS_SHOWN = true;
      final CodeStyleSettings settings =
          CodeStyleSettingsManager.getInstance().getCurrentSettings();
      settings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS = true;
      settings.getCommonSettings(PythonLanguage.getInstance()).ALIGN_MULTILINE_PARAMETERS_IN_CALLS =
          true;
      uiSettings.SHOW_DIRECTORY_FOR_NON_UNIQUE_FILENAMES = true;
      uiSettings.SHOW_MEMORY_INDICATOR = false;
      final String ignoredFilesList = fileTypeManager.getIgnoredFilesList();
      ApplicationManager.getApplication()
          .invokeLater(
              () ->
                  ApplicationManager.getApplication()
                      .runWriteAction(
                          () ->
                              FileTypeManager.getInstance()
                                  .setIgnoredFilesList(ignoredFilesList + ";*$py.class")));
      PyCodeInsightSettings.getInstance().SHOW_IMPORT_POPUP = false;
    }
    final EditorColorsScheme editorColorsScheme =
        EditorColorsManager.getInstance().getScheme(EditorColorsScheme.DEFAULT_SCHEME_NAME);
    editorColorsScheme.setEditorFontSize(14);

    if (!propertiesComponent.isValueSet(DISPLAYED_PROPERTY)) {

      bus.connect()
          .subscribe(
              AppLifecycleListener.TOPIC,
              new AppLifecycleListener() {
                @Override
                public void welcomeScreenDisplayed() {

                  ApplicationManager.getApplication()
                      .invokeLater(
                          () -> {
                            if (!propertiesComponent.isValueSet(DISPLAYED_PROPERTY)) {
                              GeneralSettings.getInstance().setShowTipsOnStartup(false);
                              propertiesComponent.setValue(DISPLAYED_PROPERTY, "true");

                              patchKeymap();
                            }
                          });
                }
              });
    }

    bus.connect()
        .subscribe(
            ProjectManager.TOPIC,
            new ProjectManagerAdapter() {
              @Override
              public void projectOpened(final Project project) {
                if (project.isDefault()) return;
                if (FileChooserUtil.getLastOpenedFile(project) == null) {
                  FileChooserUtil.setLastOpenedFile(project, VfsUtil.getUserHomeDir());
                }

                patchProjectAreaExtensions(project);

                StartupManager.getInstance(project)
                    .runWhenProjectIsInitialized(
                        new DumbAwareRunnable() {
                          @Override
                          public void run() {
                            if (project.isDisposed()) return;
                            updateInspectionsProfile();
                            openProjectStructure();
                          }

                          private void openProjectStructure() {
                            ToolWindowManager.getInstance(project)
                                .invokeLater(
                                    new Runnable() {
                                      int count = 0;

                                      public void run() {
                                        if (project.isDisposed()) return;
                                        if (count++
                                            < 3) { // we need to call this after
                                                   // ToolWindowManagerImpl.registerToolWindowsFromBeans
                                          ToolWindowManager.getInstance(project).invokeLater(this);
                                          return;
                                        }
                                        ToolWindow toolWindow =
                                            ToolWindowManager.getInstance(project)
                                                .getToolWindow("Project");
                                        if (toolWindow != null
                                            && toolWindow.getType() != ToolWindowType.SLIDING) {
                                          toolWindow.activate(null);
                                        }
                                      }
                                    });
                          }

                          private void updateInspectionsProfile() {
                            final String[] codes = new String[] {"W29", "E501"};
                            final VirtualFile baseDir = project.getBaseDir();
                            final PsiDirectory directory =
                                PsiManager.getInstance(project).findDirectory(baseDir);
                            if (directory != null) {
                              InspectionProjectProfileManager.getInstance(project)
                                  .getInspectionProfile()
                                  .modifyToolSettings(
                                      Key.<PyPep8Inspection>create(
                                          PyPep8Inspection.INSPECTION_SHORT_NAME),
                                      directory,
                                      inspection ->
                                          Collections.addAll(inspection.ignoredErrors, codes));
                            }
                          }
                        });
              }
            });
  }
  @Nullable
  private Project generateProject(
      @NotNull final Project project, @NotNull final AbstractProjectSettingsStep settings) {
    final DirectoryProjectGenerator generator = settings.getProjectGenerator();
    final File location = new File(settings.getProjectLocation());
    if (!location.exists() && !location.mkdirs()) {
      Messages.showErrorDialog(
          project, "Cannot create directory '" + location + "'", "Create Project");
      return null;
    }

    final VirtualFile baseDir =
        ApplicationManager.getApplication()
            .runWriteAction(
                new Computable<VirtualFile>() {
                  public VirtualFile compute() {
                    return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(location);
                  }
                });
    LOG.assertTrue(baseDir != null, "Couldn't find '" + location + "' in VFS");
    baseDir.refresh(false, true);

    if (baseDir.getChildren().length > 0) {
      int rc =
          Messages.showYesNoDialog(
              project,
              "The directory '"
                  + location
                  + "' is not empty. Would you like to create a project from existing sources instead?",
              "Create New Project",
              Messages.getQuestionIcon());
      if (rc == Messages.YES) {
        return PlatformProjectOpenProcessor.getInstance().doOpenProject(baseDir, null, false);
      }
    }

    String generatorName =
        generator == null ? "empty" : ConvertUsagesUtil.ensureProperKey(generator.getName());
    UsageTrigger.trigger("NewDirectoryProjectAction." + generatorName);

    GeneralSettings.getInstance().setLastProjectCreationLocation(location.getParent());

    return PlatformProjectOpenProcessor.doOpenProject(
        baseDir,
        null,
        false,
        -1,
        new ProjectOpenedCallback() {
          @Override
          public void projectOpened(Project project, Module module) {
            if (generator != null) {
              Object projectSettings = null;
              if (generator instanceof PythonProjectGenerator) {
                projectSettings = ((PythonProjectGenerator) generator).getProjectSettings();
              } else if (generator instanceof WebProjectTemplate) {
                projectSettings = ((WebProjectTemplate) generator).getPeer().getSettings();
              }
              if (projectSettings instanceof PyNewProjectSettings) {
                ((PyNewProjectSettings) projectSettings).setSdk(settings.getSdk());
                ((PyNewProjectSettings) projectSettings)
                    .setInstallFramework(settings.installFramework());
              }
              //noinspection unchecked
              generator.generateProject(project, baseDir, projectSettings, module);
            }
          }
        },
        false);
  }
  /**
   * Constructs new dialog. Loads settings, registers listeners.
   *
   * @param project the project
   * @param vcsRoots the vcs roots
   * @param roots the loaded information about roots
   */
  private GitPushActiveBranchesDialog(
      final Project project, List<VirtualFile> vcsRoots, List<Root> roots) {
    super(project, true);
    myVcs = GitVcs.getInstance(project);
    myProject = project;
    myVcsRoots = vcsRoots;
    myGeneralSettings = GeneralSettings.getInstance();
    myProjectManager = ProjectManagerEx.getInstanceEx();

    updateTree(roots, null);
    updateUI();

    final GitVcsSettings settings = GitVcsSettings.getInstance(project);
    if (settings != null) {
      UpdatePolicyUtils.updatePolicyItem(
          settings.getPushActiveBranchesRebaseSavePolicy(),
          myStashRadioButton,
          myShelveRadioButton);
    }
    ChangeListener listener =
        new ChangeListener() {
          public void stateChanged(ChangeEvent e) {
            if (settings != null) {
              settings.setPushActiveBranchesRebaseSavePolicy(
                  UpdatePolicyUtils.getUpdatePolicy(myStashRadioButton, myShelveRadioButton));
            }
          }
        };
    myStashRadioButton.addChangeListener(listener);
    myShelveRadioButton.addChangeListener(listener);
    myCommitTree
        .getSelectionModel()
        .addTreeSelectionListener(
            new TreeSelectionListener() {
              public void valueChanged(TreeSelectionEvent e) {
                TreePath path = myCommitTree.getSelectionModel().getSelectionPath();
                if (path == null) {
                  myViewButton.setEnabled(false);
                  return;
                }
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
                myViewButton.setEnabled(
                    node != null
                        && myCommitTree.getSelectionCount() == 1
                        && node.getUserObject() instanceof Commit);
              }
            });
    myViewButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            TreePath path = myCommitTree.getSelectionModel().getSelectionPath();
            if (path == null) {
              return;
            }
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
            if (node == null || !(node.getUserObject() instanceof Commit)) {
              return;
            }
            Commit c = (Commit) node.getUserObject();
            GitShowAllSubmittedFilesAction.showSubmittedFiles(
                project, c.revision.asString(), c.root.root);
          }
        });
    myFetchButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            fetch();
          }
        });
    myRebaseButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            rebase();
          }
        });

    myPushButton.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            push();
          }
        });

    setTitle(GitBundle.getString("push.active.title"));
    setOKButtonText(GitBundle.getString("push.active.rebase.and.push"));
    setCancelButtonText(GitBundle.getString("git.push.active.close"));
    init();
  }