コード例 #1
0
  private void processClose() {
    if (Registry.getInstance().isRestartNeeded()) {
      final ApplicationEx app = (ApplicationEx) ApplicationManager.getApplication();
      final ApplicationInfo info = ApplicationInfo.getInstance();

      final int r =
          Messages.showOkCancelDialog(
              myContent,
              "You need to restart " + info.getVersionName() + " for the changes to take effect",
              "Restart Required",
              (app.isRestartCapable() ? "Restart Now" : "Shutdown Now"),
              (app.isRestartCapable() ? "Restart Later" : "Shutdown Later"),
              Messages.getQuestionIcon());

      if (r == 0) {
        LaterInvocator.invokeLater(
            new Runnable() {
              public void run() {
                if (app.isRestartCapable()) {
                  app.restart();
                } else {
                  app.exit(true);
                }
              }
            },
            ModalityState.NON_MODAL);
      }
    }
  }
コード例 #2
0
  @Nullable
  public static String getDownloadVersions() {

    String userAgent =
        String.format(
            "%s / %s / Symfony Plugin %s",
            ApplicationInfo.getInstance().getVersionName(),
            ApplicationInfo.getInstance().getBuild(),
            PluginManager.getPlugin(PluginId.getId("fr.adrienbrault.idea.symfony2plugin"))
                .getVersion());

    try {

      // @TODO: PhpStorm9:
      // simple replacement for: com.intellij.util.io.HttpRequests
      URL url = new URL("http://symfony.com/versions.json");
      URLConnection conn = url.openConnection();
      conn.setRequestProperty("User-Agent", userAgent);
      conn.connect();

      BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

      String content = "";
      String line;
      while ((line = in.readLine()) != null) {
        content += line;
      }

      in.close();

      return content;
    } catch (IOException e) {
      return null;
    }
  }
コード例 #3
0
  public static void openTipInBrowser(@Nullable TipAndTrickBean tip, JEditorPane browser) {
    if (tip == null) return;
    try {
      PluginDescriptor pluginDescriptor = tip.getPluginDescriptor();
      ClassLoader tipLoader =
          pluginDescriptor == null
              ? TipUIUtil.class.getClassLoader()
              : ObjectUtils.notNull(
                  pluginDescriptor.getPluginClassLoader(), TipUIUtil.class.getClassLoader());

      URL url = ResourceUtil.getResource(tipLoader, "/tips/", tip.fileName);

      if (url == null) {
        setCantReadText(browser, tip);
        return;
      }

      StringBuffer text = new StringBuffer(ResourceUtil.loadText(url));
      updateShortcuts(text);
      updateImages(text, tipLoader);
      String replaced =
          text.toString()
              .replace("&productName;", ApplicationNamesInfo.getInstance().getFullProductName());
      String major = ApplicationInfo.getInstance().getMajorVersion();
      replaced = replaced.replace("&majorVersion;", major);
      String minor = ApplicationInfo.getInstance().getMinorVersion();
      replaced = replaced.replace("&minorVersion;", minor);
      replaced =
          replaced.replace("&majorMinorVersion;", major + ("0".equals(minor) ? "" : ("." + minor)));
      replaced = replaced.replace("&settingsPath;", CommonBundle.settingsActionPath());
      replaced =
          replaced.replaceFirst(
              "<link rel=\"stylesheet\".*tips\\.css\">", ""); // don't reload the styles
      if (browser.getUI() == null) {
        browser.updateUI();
        boolean succeed = browser.getUI() != null;
        String message =
            "reinit JEditorPane.ui: "
                + (succeed ? "OK" : "FAIL")
                + ", laf="
                + LafManager.getInstance().getCurrentLookAndFeel();
        if (succeed) LOG.warn(message);
        else LOG.error(message);
      }
      adjustFontSize(((HTMLEditorKit) browser.getEditorKit()).getStyleSheet());
      browser.read(new StringReader(replaced), url);
    } catch (IOException e) {
      setCantReadText(browser, tip);
    }
  }
コード例 #4
0
  /**
   * #172 Gets OVERRIDE_STRIP_TRAILING_SPACES_KEY from the TrailingSpacesStripper class. Since the
   * package in which the class is located depends on api version, some checks are required.
   *
   * @return a key for "strip trailing white space" setting
   */
  @Nullable
  private static Key<String> getOverrideStripTrailingSpacesKey() {
    final String apiVersion = ApplicationInfo.getInstance().getApiVersion();
    final Pattern apiVersionPattern = Pattern.compile("^[A-Z]+-(\\d+\\.\\d+)$");
    final Matcher matcher = apiVersionPattern.matcher(apiVersion);

    if (!matcher.matches()) {
      return null;
    }

    String buildVersion = matcher.group(1);

    final String classPath;
    if (buildVersion.compareTo("138") >= 0) {
      classPath = "com.intellij.openapi.editor.impl.TrailingSpacesStripper";
    } else {
      classPath = "com.intellij.openapi.fileEditor.impl.TrailingSpacesStripper";
    }

    try {
      //noinspection unchecked
      return (Key<String>)
          Class.forName(classPath).getDeclaredField("OVERRIDE_STRIP_TRAILING_SPACES_KEY").get(null);
    } catch (Exception e) {
      return null;
    }
  }
コード例 #5
0
  private void initializeProperties(final Map<String, String> properties) {
    properties.put(TfsTelemetryConstants.CONTEXT_PROPERTY_USER_ID, getUserId());

    // Get IntelliJ IDEA version info
    ApplicationInfoEx appInfo = (ApplicationInfoEx) ApplicationInfo.getInstance();
    properties.put(TfsTelemetryConstants.CONTEXT_PROPERTY_MAJOR_VERSION, appInfo.getMajorVersion());
    properties.put(TfsTelemetryConstants.CONTEXT_PROPERTY_MINOR_VERSION, appInfo.getMinorVersion());
    properties.put(
        TfsTelemetryConstants.CONTEXT_PROPERTY_BUILD_NUMBER, appInfo.getBuild().asString());
    properties.put(
        TfsTelemetryConstants.CONTEXT_PROPERTY_EXE_NAME, appInfo.getFullApplicationName());

    // Get our plugin version
    properties.put(TfsTelemetryConstants.CONTEXT_PROPERTY_PLUGIN_VERSION, getPluginVersion());

    properties.put(
        TfsTelemetryConstants.CONTEXT_PROPERTY_PROCESSOR_ARCHITECTURE, getProcessorArchitecture());
    properties.put(TfsTelemetryConstants.CONTEXT_PROPERTY_LOCALE_NAME, getLocaleName());

    properties.put(
        TfsTelemetryConstants.CONTEXT_PROPERTY_OS_MAJOR_VERSION, getPlatformMajorVersion());
    properties.put(
        TfsTelemetryConstants.CONTEXT_PROPERTY_OS_MINOR_VERSION, getPlatformMinorVersion());
    properties.put(TfsTelemetryConstants.CONTEXT_PROPERTY_OS_NAME, getPlatformName());
    properties.put(TfsTelemetryConstants.CONTEXT_PROPERTY_OS_SHORT_NAME, getPlatformShortName());
    properties.put(TfsTelemetryConstants.CONTEXT_PROPERTY_OS_FULL_NAME, getPlatformFullName());

    properties.put(TfsTelemetryConstants.CONTEXT_PROPERTY_JAVA_RUNTIME_NAME, getJavaName());
    properties.put(TfsTelemetryConstants.CONTEXT_PROPERTY_JAVA_RUNTIME_VERSION, getJavaVersion());

    // TODO do we need this information (Eclipse plugin provides it)
    // properties.put(TfsTelemetryConstants.CONTEXT_PROPERTY_FRAMEWORK_NAME, getFrameworkName());
    // properties.put(TfsTelemetryConstants.CONTEXT_PROPERTY_FRAMEWORK_VERSION,
    // getFrameworkVersion());
  }
コード例 #6
0
  public final IdeFrameImpl allocateFrame(final Project project) {
    LOG.assertTrue(!myProject2Frame.containsKey(project));

    final IdeFrameImpl frame;
    if (myProject2Frame.containsKey(null)) {
      frame = myProject2Frame.get(null);
      myProject2Frame.remove(null);
      myProject2Frame.put(project, frame);
      frame.setProject(project);
    } else {
      frame =
          new IdeFrameImpl(
              (ApplicationInfoEx) ApplicationInfo.getInstance(),
              ActionManagerEx.getInstanceEx(),
              UISettings.getInstance(),
              DataManager.getInstance(),
              ApplicationManager.getApplication());
      final Rectangle bounds = ProjectFrameBounds.getInstance(project).getBounds();
      if (bounds != null) {
        frame.setBounds(bounds);
      } else if (myFrameBounds != null) {
        frame.setBounds(myFrameBounds);
      }
      frame.setExtendedState(myFrameExtendedState);
      frame.setProject(project);
      myProject2Frame.put(project, frame);
      frame.setVisible(true);
    }

    frame.addWindowListener(myActivationListener);

    myEventDispatcher.getMulticaster().frameCreated(frame);

    return frame;
  }
コード例 #7
0
  public void initComponent() {
    log.info("Initializing WakaTime plugin v" + VERSION + " (https://wakatime.com/)");
    // System.out.println("Initializing WakaTime plugin v" + VERSION + " (https://wakatime.com/)");

    // Set runtime constants
    IDE_NAME = PlatformUtils.getPlatformPrefix();
    IDE_VERSION = ApplicationInfo.getInstance().getFullVersion();

    if (!Dependencies.isCLIInstalled()) {
      log.info("Downloading and installing wakatime-cli ...");
      Dependencies.installCLI();
    } else if (Dependencies.isCLIOld()) {
      log.info("Upgrading wakatime-cli ...");
      Dependencies.upgradeCLI();
    }

    if (Dependencies.isPythonInstalled()) {

      WakaTime.DEBUG = WakaTime.isDebugEnabled();
      if (WakaTime.DEBUG) {
        log.setLevel(Level.DEBUG);
        log.debug("Logging level set to DEBUG");
      }

      log.debug("Python location: " + Dependencies.getPythonLocation());
      log.debug("CLI location: " + Dependencies.getCLILocation());

      // prompt for apiKey if it does not already exist
      if (ApiKey.getApiKey().equals("")) {
        Project project = ProjectManager.getInstance().getDefaultProject();
        ApiKey apiKey = new ApiKey(project);
        apiKey.promptForApiKey();
      }
      log.debug("Api Key: " + ApiKey.getApiKey());

      // add WakaTime item to File menu
      ActionManager am = ActionManager.getInstance();
      PluginMenu action = new PluginMenu();
      am.registerAction("WakaTimeApiKey", action);
      DefaultActionGroup fileMenu = (DefaultActionGroup) am.getAction("FileMenu");
      fileMenu.addSeparator();
      fileMenu.add(action);

      // Setup message listeners
      MessageBus bus = ApplicationManager.getApplication().getMessageBus();
      connection = bus.connect();
      connection.subscribe(AppTopics.FILE_DOCUMENT_SYNC, new CustomSaveListener());
      EditorFactory.getInstance()
          .getEventMulticaster()
          .addDocumentListener(new CustomDocumentListener());

      log.debug("Finished initializing WakaTime plugin");

    } else {
      Messages.showErrorDialog(
          "WakaTime requires Python to be installed.\nYou can install it from https://www.python.org/downloads/\nAfter installing Python, restart your IDE.",
          "Error");
    }
  }
コード例 #8
0
    public UpdateInfoPanel() {
      ApplicationInfo appInfo = ApplicationInfo.getInstance();
      myBuildNumber.setText(appInfo.getBuild().asString() + ")");
      final String version = appInfo.getFullVersion();

      myVersionNumber.setText(version);
      myNewBuildNumber.setText(myLatestBuild.getNumber().asString() + ")");
      myNewVersionNumber.setText(myLatestBuild.getVersion());
      myUpdateMessageLabel.setBackground(UIUtil.getLabelBackground());
      myScrollPane.setBackground(UIUtil.getLabelBackground());
      myScrollPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
      if (myLatestBuild.getMessage() != null) {
        StringBuilder builder = new StringBuilder();
        builder
            .append("<html><head>")
            .append(UIUtil.getCssFontDeclaration(UIUtil.getLabelFont()))
            .append("</head><body>")
            .append(StringUtil.formatLinks(myLatestBuild.getMessage()))
            .append("</body></html>");
        myUpdateMessageLabel.setText(builder.toString());
        myUpdateMessageLabel.addHyperlinkListener(BrowserHyperlinkListener.INSTANCE);
      } else {
        myUpdateMessageLabel.setVisible(false);
      }

      PatchInfo patch = myLatestBuild.findPatchForCurrentBuild();
      if (patch == null) {
        myPatchAvailableLabel.setVisible(false);
        myPatchSizeLabel.setVisible(false);
      } else {
        myPatchSizeLabel.setText(patch.getSize() + "MB");
      }

      if (SystemInfo.isMac) {
        myManualCheckLabel.setText(
            "<html><br>To check for new updates manually, use the <b>"
                + ApplicationNamesInfo.getInstance().getProductName()
                + " | Check for Updates</b> command.</html>");
      }

      LabelTextReplacingUtil.replaceText(myPanel);
    }
コード例 #9
0
 private static void checkForUpdates() {
   PropertiesComponent propertiesComponent = PropertiesComponent.getInstance();
   long lastUpdate = propertiesComponent.getOrInitLong(KEY, 0);
   if (lastUpdate == 0 || System.currentTimeMillis() - lastUpdate > TimeUnit.DAYS.toMillis(1)) {
     ApplicationManager.getApplication()
         .executeOnPooledThread(
             () -> {
               try {
                 String buildNumber = ApplicationInfo.getInstance().getBuild().asString();
                 IdeaPluginDescriptor plugin = getPlugin();
                 String pluginVersion = plugin.getVersion();
                 String pluginId = plugin.getPluginId().getIdString();
                 String os =
                     URLEncoder.encode(
                         SystemInfo.OS_NAME + " " + SystemInfo.OS_VERSION, CharsetToolkit.UTF8);
                 String uid = PermanentInstallationID.get();
                 String url =
                     "https://plugins.jetbrains.com/plugins/list"
                         + "?pluginId="
                         + pluginId
                         + "&build="
                         + buildNumber
                         + "&pluginVersion="
                         + pluginVersion
                         + "&os="
                         + os
                         + "&uuid="
                         + uid;
                 PropertiesComponent.getInstance()
                     .setValue(KEY, String.valueOf(System.currentTimeMillis()));
                 HttpRequests.request(url)
                     .connect(
                         request -> {
                           try {
                             JDOMUtil.load(request.getReader());
                             LOG.info(
                                 (request.isSuccessful() ? "Successful" : "Unsuccessful")
                                     + " update: "
                                     + url);
                           } catch (JDOMException e) {
                             LOG.warn(e);
                           }
                           return null;
                         });
               } catch (UnknownHostException ignored) {
               } catch (IOException e) {
                 LOG.warn(e);
               }
             });
   }
 }
コード例 #10
0
 public NoUpdatesPanel() {
   myNothingToUpdateLabel.setText(
       IdeBundle.message(
           "updates.no.updates.message", ApplicationInfo.getInstance().getVersionName()));
   configureMessageArea(myMessageArea);
 }
コード例 #11
0
 /** Value for "User Agent" HTTP header in form: PyCharm/2016.2 EAP */
 @NotNull
 private static String getUserAgent() {
   return ApplicationNamesInfo.getInstance().getProductName()
       + "/"
       + ApplicationInfo.getInstance().getFullVersion();
 }
コード例 #12
0
  protected JComponent createSouthPanel() {
    JPanel panel = new JPanel(new BorderLayout());
    panel.setBorder(BorderFactory.createEmptyBorder(8, 0, 0, 0));

    JPanel buttonPanel = new JPanel();

    if (SystemInfo.isMac) {
      panel.add(buttonPanel, BorderLayout.EAST);
      buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));

      if (!UIUtil.isUnderDarcula()) {
        myHelpButton.putClientProperty("JButton.buttonType", "help");
      }
      if (UIUtil.isUnderAquaLookAndFeel()) {
        myHelpButton.setText("");
      }

      JPanel leftPanel = new JPanel();
      if (ApplicationInfo.contextHelpAvailable()) {
        leftPanel.add(myHelpButton);
      }
      leftPanel.add(myCancelButton);
      panel.add(leftPanel, BorderLayout.WEST);

      if (mySteps.size() > 1) {
        buttonPanel.add(Box.createHorizontalStrut(5));
        buttonPanel.add(myPreviousButton);
      }
      buttonPanel.add(Box.createHorizontalStrut(5));
      buttonPanel.add(myNextButton);
    } else {
      panel.add(buttonPanel, BorderLayout.CENTER);
      GroupLayout layout = new GroupLayout(buttonPanel);
      buttonPanel.setLayout(layout);
      layout.setAutoCreateGaps(true);

      final GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup();
      final GroupLayout.ParallelGroup vGroup = layout.createParallelGroup();
      final Collection<Component> buttons = ContainerUtil.newArrayListWithExpectedSize(5);
      final boolean helpAvailable = ApplicationInfo.contextHelpAvailable();

      if (helpAvailable && UIUtil.isUnderGTKLookAndFeel()) {
        add(hGroup, vGroup, buttons, myHelpButton);
      }
      add(hGroup, vGroup, null, Box.createHorizontalGlue());
      if (mySteps.size() > 1) {
        add(hGroup, vGroup, buttons, myPreviousButton);
      }
      add(hGroup, vGroup, buttons, myNextButton, myCancelButton);
      if (helpAvailable && !UIUtil.isUnderGTKLookAndFeel()) {
        add(hGroup, vGroup, buttons, myHelpButton);
      }

      layout.setHorizontalGroup(hGroup);
      layout.setVerticalGroup(vGroup);
      layout.linkSize(buttons.toArray(new Component[buttons.size()]));
    }

    myPreviousButton.setEnabled(false);
    myPreviousButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(final ActionEvent e) {
            doPreviousAction();
          }
        });
    myNextButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(final ActionEvent e) {
            if (isLastStep()) {
              // Commit data of current step and perform OK action
              final Step currentStep = mySteps.get(myCurrentStep);
              LOG.assertTrue(currentStep != null);
              try {
                currentStep._commit(true);
                doOKAction();
              } catch (final CommitStepException exc) {
                String message = exc.getMessage();
                if (message != null) {
                  Messages.showErrorDialog(myContentPanel, message);
                }
              }
            } else {
              doNextAction();
            }
          }
        });

    myCancelButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(final ActionEvent e) {
            doCancelAction();
          }
        });
    myHelpButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(final ActionEvent e) {
            helpAction();
          }
        });

    return panel;
  }
コード例 #13
0
  private static boolean doSubmit(
      final IdeaLoggingEvent event,
      final Component parentComponent,
      final Consumer<SubmittedReportInfo> callback,
      final ErrorBean bean,
      final String description) {
    final DataContext dataContext = DataManager.getInstance().getDataContext(parentComponent);

    bean.setDescription(description);
    bean.setMessage(event.getMessage());

    Throwable throwable = event.getThrowable();
    if (throwable != null) {
      final PluginId pluginId = IdeErrorsDialog.findPluginId(throwable);
      if (pluginId != null) {
        final IdeaPluginDescriptor ideaPluginDescriptor = PluginManager.getPlugin(pluginId);
        if (ideaPluginDescriptor != null && !ideaPluginDescriptor.isBundled()) {
          bean.setPluginName(ideaPluginDescriptor.getName());
          bean.setPluginVersion(ideaPluginDescriptor.getVersion());
        }
      }
    }

    Object data = event.getData();

    if (data instanceof LogMessageEx) {
      bean.setAttachments(((LogMessageEx) data).getAttachments());
    }

    LinkedHashMap<String, String> reportValues =
        IdeaITNProxy.getKeyValuePairs(
            bean,
            ApplicationManager.getApplication(),
            (ApplicationInfoEx) ApplicationInfo.getInstance(),
            ApplicationNamesInfo.getInstance());

    final Project project = CommonDataKeys.PROJECT.getData(dataContext);

    Consumer<String> successCallback =
        new Consumer<String>() {
          @Override
          public void consume(String token) {
            final SubmittedReportInfo reportInfo =
                new SubmittedReportInfo(
                    null, "Issue " + token, SubmittedReportInfo.SubmissionStatus.NEW_ISSUE);
            callback.consume(reportInfo);

            ReportMessages.GROUP
                .createNotification(
                    ReportMessages.ERROR_REPORT, "Submitted", NotificationType.INFORMATION, null)
                .setImportant(false)
                .notify(project);
          }
        };

    Consumer<Exception> errorCallback =
        new Consumer<Exception>() {
          @Override
          public void consume(Exception e) {
            String message = GoBundle.message("go.error.report.message", e.getMessage());
            ReportMessages.GROUP
                .createNotification(
                    ReportMessages.ERROR_REPORT,
                    message,
                    NotificationType.ERROR,
                    NotificationListener.URL_OPENING_LISTENER)
                .setImportant(false)
                .notify(project);
          }
        };
    AnonymousFeedbackTask task =
        new AnonymousFeedbackTask(
            project, "Submitting error report", true, reportValues, successCallback, errorCallback);
    if (project == null) {
      task.run(new EmptyProgressIndicator());
    } else {
      ProgressManager.getInstance().run(task);
    }
    return true;
  }
コード例 #14
0
  @SuppressWarnings("unchecked")
  private static void registerIntellijApiModules() {
    ApplicationInfo applicationInfo = ApplicationInfo.getInstance();
    ClassLoader cl = applicationInfo.getClass().getClassLoader();
    final String version = applicationInfo.getMajorVersion();
    Class<? extends ClassLoader> loaderClass = cl.getClass();

    List<URL> urls = Collections.emptyList();
    try {
      Method method = loaderClass.getMethod("getUrls");
      Object result = method.invoke(cl);
      if (result instanceof List) {
        urls = (List<URL>) result;
      }
    } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e) {
      e.printStackTrace();
    }

    File importedIdeaModulesFile =
        new File(CeylonIdePlugin.getClassesDir(), "IdeaModuleToImport.properties");
    if (!importedIdeaModulesFile.exists()) {
      throw new RuntimeException(
          "The file 'IdeaModuleToImport.properties' was not found at the root of the Ceylon  IDE plugin folder.\n"
              + "The Ceylon IDE plugin will not work propertly.");
    }
    Properties importedIdeaModules = new Properties();
    try {
      importedIdeaModules.load(new FileReader(importedIdeaModulesFile));
    } catch (IOException ioe) {
      throw new RuntimeException(
          "The file 'IdeaModuleToImport.properties' at the root of the Ceylon  IDE plugin folder could not be parsed.\n"
              + "The Ceylon IDE plugin will not work propertly.",
          ioe);
    }

    for (final URL url : urls) {
      File file;
      try {
        file = new File(url.toURI());
      } catch (URISyntaxException e) {
        file = new File(url.getPath());
      }
      if (!file.exists()) {
        continue;
      }
      final String fileName = file.getName();
      final String moduleName = importedIdeaModules.getProperty(fileName);
      final File finalFile = file;
      if (moduleName != null) {
        ArtifactResult artifactResult =
            new ArtifactResult() {
              @Override
              public String name() {
                return moduleName;
              }

              @Override
              public String namespace() {
                return null;
              }

              @Override
              public String version() {
                return version;
              }

              @Override
              public boolean optional() {
                return false;
              }

              @Override
              public boolean exported() {
                return true;
              }

              @Override
              public ModuleScope moduleScope() {
                return ModuleScope.COMPILE;
              }

              @Override
              public List<Exclusion> getExclusions() {
                return null;
              }

              @Override
              public ArtifactResultType type() {
                return ArtifactResultType.CEYLON;
              }

              @Override
              public VisibilityType visibilityType() {
                return VisibilityType.STRICT;
              }

              @Override
              public File artifact() throws RepositoryException {
                return finalFile;
              }

              @Override
              public PathFilter filter() {
                return null;
              }

              @Override
              public List<ArtifactResult> dependencies() throws RepositoryException {
                return Collections.emptyList();
              }

              @Override
              public String repositoryDisplayString() {
                return null;
              }

              @Override
              public Repository repository() {
                return null;
              }
            };
        registerModule(artifactResult, cl);
      }
    }
  }