private void loadApplicationComponents() {
   final IdeaPluginDescriptor[] plugins = PluginManager.getPlugins();
   for (IdeaPluginDescriptor plugin : plugins) {
     if (PluginManager.shouldSkipPlugin(plugin)) continue;
     loadComponentsConfiguration(plugin.getAppComponents(), plugin, false);
   }
 }
  public static void prepareToUninstall(PluginId pluginId) throws IOException {
    synchronized (PluginManager.lock) {
      if (PluginManager.isPluginInstalled(pluginId)) {
        // add command to delete the 'action script' file
        IdeaPluginDescriptor pluginDescriptor = PluginManager.getPlugin(pluginId);

        StartupActionScriptManager.ActionCommand deleteOld =
            new StartupActionScriptManager.DeleteCommand(pluginDescriptor.getPath());
        StartupActionScriptManager.addActionCommand(deleteOld);
      }
    }
  }
  private static void updateExistingPluginInfo(
      IdeaPluginDescriptor descr, IdeaPluginDescriptor existing) {
    int state = StringUtil.compareVersionNumbers(descr.getVersion(), existing.getVersion());
    final PluginId pluginId = existing.getPluginId();
    final String idString = pluginId.getIdString();
    final JDOMExternalizableStringList installedPlugins =
        PluginManagerUISettings.getInstance().getInstalledPlugins();
    if (!installedPlugins.contains(idString)
        && !((IdeaPluginDescriptorImpl) existing).isDeleted()) {
      installedPlugins.add(idString);
    }
    final PluginManagerUISettings updateSettings = PluginManagerUISettings.getInstance();
    if (state > 0
        && !PluginManager.isIncompatible(descr)
        && !updatedPlugins.contains(descr.getPluginId())) {
      NewVersions2Plugins.put(pluginId, 1);
      if (!updateSettings.myOutdatedPlugins.contains(idString)) {
        updateSettings.myOutdatedPlugins.add(idString);
      }

      final IdeaPluginDescriptorImpl plugin = (IdeaPluginDescriptorImpl) existing;
      plugin.setDownloadsCount(descr.getDownloads());
      plugin.setVendor(descr.getVendor());
      plugin.setVendorEmail(descr.getVendorEmail());
      plugin.setVendorUrl(descr.getVendorUrl());
      plugin.setUrl(descr.getUrl());

    } else {
      updateSettings.myOutdatedPlugins.remove(idString);
      if (NewVersions2Plugins.remove(pluginId) != null) {
        updatedPlugins.add(pluginId);
      }
    }
  }
  @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;
    }
  }
 public void doDispose() {
   PluginId debuggerPlugin =
       PluginManager.getPluginByClassName("jetbrains.mps.debug.api.DebugInfoManager");
   if (debuggerPlugin == null) {
     return;
   }
   final DebugInfoManager manager = DebugInfoManager.getInstance();
   if (manager == null) {
     return;
   }
   manager.removeConceptBreakpointCreator("jetbrains.mps.baseLanguage.structure.Statement");
   manager.removeConceptBreakpointCreator("jetbrains.mps.baseLanguage.structure.FieldDeclaration");
   manager.removeConceptBreakpointCreator(
       "jetbrains.mps.baseLanguage.structure.StaticFieldDeclaration");
   SetSequence.fromSet(DebugInfoProvider_CustomApplicationPlugin.this.myCreators)
       .visitAll(
           new IVisitor<
               Tuples._2<
                   _FunctionTypes._return_P1_E0<? extends Boolean, ? super SNode>,
                   _FunctionTypes._return_P2_E0<
                       ? extends ILocationBreakpoint, ? super SNode, ? super Project>>>() {
             public void visit(
                 Tuples._2<
                         _FunctionTypes._return_P1_E0<? extends Boolean, ? super SNode>,
                         _FunctionTypes._return_P2_E0<
                             ? extends ILocationBreakpoint, ? super SNode, ? super Project>>
                     it) {
               manager.removeBreakpointCreator(it);
             }
           });
   SetSequence.fromSet(DebugInfoProvider_CustomApplicationPlugin.this.myCreators).clear();
 }
  private void updatePluginDependencies() {
    myDependentToRequiredListMap.clear();

    final int rowCount = getRowCount();
    for (int i = 0; i < rowCount; i++) {
      final IdeaPluginDescriptor descriptor = getObjectAt(i);
      final PluginId pluginId = descriptor.getPluginId();
      myDependentToRequiredListMap.remove(pluginId);
      if (descriptor instanceof IdeaPluginDescriptorImpl
          && ((IdeaPluginDescriptorImpl) descriptor).isDeleted()) continue;
      final Boolean enabled = myEnabled.get(pluginId);
      if (enabled == null || enabled.booleanValue()) {
        PluginManager.checkDependants(
            descriptor,
            new Function<PluginId, IdeaPluginDescriptor>() {
              @Nullable
              public IdeaPluginDescriptor fun(final PluginId pluginId) {
                return PluginManager.getPlugin(pluginId);
              }
            },
            new Condition<PluginId>() {
              public boolean value(final PluginId dependantPluginId) {
                final Boolean enabled = myEnabled.get(dependantPluginId);
                if (enabled == null || !enabled.booleanValue()) {
                  Set<PluginId> required = myDependentToRequiredListMap.get(pluginId);
                  if (required == null) {
                    required = new HashSet<PluginId>();
                    myDependentToRequiredListMap.put(pluginId, required);
                  }

                  required.add(dependantPluginId);
                  // return false;
                }

                return true;
              }
            });
        if (enabled == null
            && !myDependentToRequiredListMap.containsKey(pluginId)
            && !PluginManager.isIncompatible(descriptor)) {
          myEnabled.put(pluginId, true);
        }
      }
    }
  }
 private void setEnabled(IdeaPluginDescriptor ideaPluginDescriptor, final boolean enabled) {
   final Collection<String> disabledPlugins = PluginManager.getDisabledPlugins();
   final PluginId pluginId = ideaPluginDescriptor.getPluginId();
   if (!enabled && !disabledPlugins.contains(pluginId.toString())) {
     myEnabled.put(pluginId, null);
   } else {
     myEnabled.put(pluginId, enabled);
   }
 }
 @Override
 protected void handleInitComponentError(
     final Throwable ex, final boolean fatal, final String componentClassName) {
   if (PluginManager.isPluginClass(componentClassName)) {
     LOG.error(ex);
     PluginId pluginId = PluginManager.getPluginByClassName(componentClassName);
     @NonNls
     final String errorMessage =
         "Plugin "
             + pluginId.getIdString()
             + " failed to initialize and will be disabled:\n"
             + ex.getMessage()
             + "\nPlease restart "
             + ApplicationNamesInfo.getInstance().getFullProductName()
             + ".";
     PluginManager.disablePlugin(pluginId.getIdString());
     if (!myHeadlessMode) {
       JOptionPane.showMessageDialog(null, errorMessage);
     } else {
       //noinspection UseOfSystemOutOrSystemErr
       System.out.println(errorMessage);
       System.exit(1);
     }
     return; // do not call super
   }
   if (fatal) {
     LOG.error(ex);
     @NonNls
     final String errorMessage =
         "Fatal error initializing class "
             + componentClassName
             + ":\n"
             + ex.toString()
             + "\nComplete error stacktrace was written to idea.log";
     if (!myHeadlessMode) {
       JOptionPane.showMessageDialog(null, errorMessage);
     } else {
       //noinspection UseOfSystemOutOrSystemErr
       System.out.println(errorMessage);
     }
   }
   super.handleInitComponentError(ex, fatal, componentClassName);
 }
 static void runStartupWizard() {
   final List<ApplicationInfoEx.PluginChooserPage> pages =
       ApplicationInfoImpl.getShadowInstance().getPluginChooserPages();
   if (!pages.isEmpty()) {
     final StartupWizard startupWizard = new StartupWizard(pages);
     startupWizard.setCancelText("Skip");
     startupWizard.show();
     PluginManager.invalidatePlugins();
   }
 }
 public void appendOrUpdateDescriptor(IdeaPluginDescriptor descriptor) {
   final PluginId descrId = descriptor.getPluginId();
   final IdeaPluginDescriptor existing = PluginManager.getPlugin(descrId);
   if (existing != null) {
     updateExistingPlugin(descriptor, existing);
   } else {
     myInstalled.add(descriptor);
     view.add(descriptor);
     setEnabled(descriptor, true);
     fireTableDataChanged();
   }
 }
Example #11
0
  @Nullable
  public static VirtualFile getPluginVirtualDirectory() {
    IdeaPluginDescriptor descriptor = PluginManager.getPlugin(PluginId.getId("Lua"));
    if (descriptor != null) {
      File pluginPath = descriptor.getPath();

      String url = VfsUtil.pathToUrl(pluginPath.getAbsolutePath());

      return VirtualFileManager.getInstance().findFileByUrl(url);
    }

    return null;
  }
  /** Should be called whenever a new plugin is installed or an existing one is updated. */
  public void onPluginInstall(@NotNull IdeaPluginDescriptor descriptor) {
    PluginId id = descriptor.getPluginId();
    boolean existing = PluginManager.isPluginInstalled(id);

    synchronized (myLock) {
      myOutdatedPlugins.remove(id.getIdString());
      if (existing) {
        myUpdatedPlugins.put(id, descriptor);
      } else {
        myInstalledPlugins.put(id, descriptor);
      }
    }
  }
 public void doInit() {
   PluginId debuggerPlugin =
       PluginManager.getPluginByClassName("jetbrains.mps.debug.api.DebugInfoManager");
   if (debuggerPlugin == null) {
     return;
   }
   DebugInfoManager manager = DebugInfoManager.getInstance();
   if (manager == null) {
     return;
   }
   {
     Mapper2<SNode, Project, ILocationBreakpoint> creator =
         new Mapper2<SNode, Project, ILocationBreakpoint>() {
           public ILocationBreakpoint value(SNode debuggableNode, Project project) {
             try {
               return Debuggers.getInstance()
                   .getDebuggerByNameSafe("Java")
                   .createBreakpoint(debuggableNode, "JAVA_LINE_BREAKPOINT", project);
             } catch (DebuggerNotPresentException e) {
               if (log.isWarnEnabled()) {
                 log.warn("Exception while creating breakpoint for node" + debuggableNode, e);
               }
               return null;
             }
           }
         };
     manager.addConceptBreakpointCreator(
         "jetbrains.mps.baseLanguage.structure.Statement", creator);
   }
   {
     Mapper2<SNode, Project, ILocationBreakpoint> creator =
         new Mapper2<SNode, Project, ILocationBreakpoint>() {
           public ILocationBreakpoint value(SNode debuggableNode, Project project) {
             try {
               return Debuggers.getInstance()
                   .getDebuggerByNameSafe("Java")
                   .createBreakpoint(debuggableNode, "JAVA_FIELD_BREAKPOINT", project);
             } catch (DebuggerNotPresentException e) {
               if (log.isWarnEnabled()) {
                 log.warn("Exception while creating breakpoint for node" + debuggableNode, e);
               }
               return null;
             }
           }
         };
     manager.addConceptBreakpointCreator(
         "jetbrains.mps.baseLanguage.structure.FieldDeclaration", creator);
     manager.addConceptBreakpointCreator(
         "jetbrains.mps.baseLanguage.structure.StaticFieldDeclaration", creator);
   }
 }
  public InstalledPluginsTableModel() {
    super.columns = new ColumnInfo[] {new EnabledPluginInfo(), new MyPluginManagerColumnInfo()};
    view = new ArrayList<IdeaPluginDescriptor>(Arrays.asList(PluginManager.getPlugins()));
    view.addAll(myInstalled);
    reset(view);

    ApplicationInfoEx applicationInfo = ApplicationInfoEx.getInstanceEx();
    for (Iterator<IdeaPluginDescriptor> iterator = view.iterator(); iterator.hasNext(); ) {
      @NonNls final String s = iterator.next().getPluginId().getIdString();
      if ("com.intellij".equals(s) || applicationInfo.isEssentialPlugin(s)) iterator.remove();
    }

    setSortKey(new RowSorter.SortKey(getNameColumn(), SortOrder.ASCENDING));
  }
Example #15
0
  private void mergeWithDefaultConfiguration() {
    final ArrayList<Configuration> cfgList = new ArrayList<Configuration>();
    for (LanguageInjectionSupport support : InjectorUtils.getActiveInjectionSupports()) {
      final String config = support.getDefaultConfigUrl();
      final URL url = config == null ? null : support.getClass().getResource(config);
      if (url != null) {
        try {
          cfgList.add(load(url.openStream()));
        } catch (Exception e) {
          LOG.warn(e);
        }
      }
    }
    final THashSet<Object> visited = new THashSet<Object>();
    for (IdeaPluginDescriptor pluginDescriptor : PluginManager.getPlugins()) {
      if (pluginDescriptor instanceof IdeaPluginDescriptorImpl
          && !((IdeaPluginDescriptorImpl) pluginDescriptor).isEnabled()) continue;
      final ClassLoader loader = pluginDescriptor.getPluginClassLoader();
      if (!visited.add(loader)) continue;
      if (loader instanceof PluginClassLoader && ((PluginClassLoader) loader).getUrls().isEmpty())
        continue;
      try {
        final Enumeration<URL> enumeration = loader.getResources("META-INF/languageInjections.xml");
        if (enumeration == null) continue;
        while (enumeration.hasMoreElements()) {
          URL url = enumeration.nextElement();
          if (!visited.add(url.getFile())) continue; // for DEBUG mode
          try {
            cfgList.add(load(url.openStream()));
          } catch (Exception e) {
            LOG.warn(e);
          }
        }
      } catch (Exception e) {
        LOG.warn(e);
      }
    }

    final ArrayList<BaseInjection> originalInjections = new ArrayList<BaseInjection>();
    final ArrayList<BaseInjection> newInjections = new ArrayList<BaseInjection>();
    myDefaultInjections = new ArrayList<BaseInjection>();
    for (String supportId : InjectorUtils.getActiveInjectionSupportIds()) {
      for (Configuration cfg : cfgList) {
        final List<BaseInjection> imported = cfg.getInjections(supportId);
        myDefaultInjections.addAll(imported);
        importInjections(getInjections(supportId), imported, originalInjections, newInjections);
      }
    }
    replaceInjections(newInjections, originalInjections);
  }
  IdeRootPane(
      ActionManagerEx actionManager,
      UISettings uiSettings,
      DataManager dataManager,
      final Application application,
      final String[] commandLineArgs,
      IdeFrame frame) {
    myActionManager = actionManager;
    myUISettings = uiSettings;

    updateToolbar();
    myContentPane.add(myNorthPanel, BorderLayout.NORTH);

    myStatusBarCustomComponentFactories =
        application.getExtensions(StatusBarCustomComponentFactory.EP_NAME);
    myApplication = application;

    createStatusBar(frame);

    updateStatusBarVisibility();

    myContentPane.add(myStatusBar, BorderLayout.SOUTH);

    myUISettingsListener = new MyUISettingsListenerImpl();
    setJMenuBar(new IdeMenuBar(actionManager, dataManager));

    final Ref<Boolean> willOpenProject = new Ref<Boolean>(Boolean.FALSE);
    final AppLifecycleListener lifecyclePublisher =
        application.getMessageBus().syncPublisher(AppLifecycleListener.TOPIC);
    lifecyclePublisher.appFrameCreated(commandLineArgs, willOpenProject);
    LOG.info(
        "App initialization took "
            + (System.nanoTime() - PluginManager.startupStart) / 1000000
            + " ms");
    PluginManager.dumpPluginClassStatistics();
    if (!willOpenProject.get()) {
      showWelcomeScreen();
      lifecyclePublisher.welcomeScreenDisplayed();
    }

    myGlassPane = new IdeGlassPaneImpl(this);
    setGlassPane(myGlassPane);
    myGlassPaneInitialized = true;

    myGlassPane.setVisible(false);
    Disposer.register(application, myDisposable);
  }
  @Override
  public void setDefaultParameters(
      @NotNull Project project,
      @NotNull VirtualFile virtualFile,
      @NotNull BackgroundTaskByVfsParameters backgroundTaskByVfsParameters) {
    Sdk sdk = null;
    Module module = ModuleUtilCore.findModuleForFile(virtualFile, project);
    if (module != null) {
      sdk = ModuleUtilCore.getSdk(module, JavaModuleExtension.class);
    }

    if (sdk == null) {
      sdk = SdkTable.getInstance().findPredefinedSdkByType(JavaSdk.getInstance());
    }

    if (sdk == null) {
      sdk = SdkTable.getInstance().findMostRecentSdkOfType(JavaSdk.getInstance());
    }

    List<String> parameters = new ArrayList<String>();
    if (sdk != null) {
      GeneralCommandLine generalCommandLine = new GeneralCommandLine();

      ((JavaSdkType) sdk.getSdkType()).setupCommandLine(generalCommandLine, sdk);
      backgroundTaskByVfsParameters.setExePath(generalCommandLine.getExePath());
      parameters.addAll(generalCommandLine.getParametersList().getList());
    } else {
      backgroundTaskByVfsParameters.setExePath(SystemInfo.isWindows ? "java.exe" : "java");
    }

    PluginClassLoader classLoader =
        (PluginClassLoader) JFlexBackgroundTaskProvider.class.getClassLoader();
    IdeaPluginDescriptor plugin = PluginManager.getPlugin(classLoader.getPluginId());
    assert plugin != null;
    parameters.add("-jar");
    parameters.add(new File(plugin.getPath(), "jflex/jflex.jar").getAbsolutePath());
    parameters.add("--charat");
    parameters.add("--noconstr");
    parameters.add("--nobak");
    parameters.add("--skel");
    parameters.add(new File(plugin.getPath(), "jflex/idea-flex.skeleton").getAbsolutePath());
    parameters.add("$FilePath$");

    backgroundTaskByVfsParameters.setProgramParameters(StringUtil.join(parameters, " "));
    backgroundTaskByVfsParameters.setWorkingDirectory("$FileParentPath$");
    backgroundTaskByVfsParameters.setOutPath("$FileParentPath$");
  }
 public void updatePluginsList(List<IdeaPluginDescriptor> list) {
   //  For each downloadable plugin we need to know whether its counterpart
   //  is already installed, and if yes compare the difference in versions:
   //  availability of newer versions will be indicated separately.
   for (IdeaPluginDescriptor descr : list) {
     PluginId descrId = descr.getPluginId();
     IdeaPluginDescriptor existing = PluginManager.getPlugin(descrId);
     if (existing != null) {
       if (descr instanceof PluginNode) {
         updateExistingPluginInfo(descr, existing);
       } else {
         view.add(descr);
         setEnabled(descr);
       }
     }
   }
   for (IdeaPluginDescriptor descriptor : myInstalled) {
     if (!view.contains(descriptor)) {
       view.add(descriptor);
     }
   }
   fireTableDataChanged();
 }
  @Override
  public void initComponent() {
    IdeaPluginDescriptor pluginDescriptor = PluginManager.getPlugin(getId("IntelliJEval"));
    if (pluginDescriptor != null && pluginDescriptor.isEnabled()) {
      livePluginNotificationGroup
          .createNotification(
              "It seems that you have IntelliJEval plugin enabled.<br/>Please disable it to use LivePlugin.",
              NotificationType.ERROR)
          .notify(null);
      return;
    }
    checkThatGroovyIsOnClasspath();

    Settings settings = Settings.getInstance();
    if (settings.justInstalled) {
      installHelloWorldPlugin();
      settings.justInstalled = false;
    }
    if (settings.runAllPluginsOnIDEStartup) {
      runAllPlugins();
    }

    new PluginToolWindowManager().init();
  }
  /**
   * Should be called whenever a list of plugins is loaded from a repository to check if there is an
   * updated version.
   */
  public void onDescriptorDownload(@NotNull IdeaPluginDescriptor descriptor) {
    PluginId id = descriptor.getPluginId();
    IdeaPluginDescriptor existing = PluginManager.getPlugin(id);
    if (existing == null
        || (existing.isBundled() && !existing.allowBundledUpdate())
        || wasUpdated(id)) {
      return;
    }

    boolean supersedes =
        !PluginManagerCore.isIncompatible(descriptor)
            && (PluginDownloader.compareVersionsSkipBroken(existing, descriptor.getVersion()) > 0
                || PluginManagerCore.isIncompatible(existing));

    String idString = id.getIdString();

    synchronized (myLock) {
      if (supersedes) {
        myOutdatedPlugins.add(idString);
      } else {
        myOutdatedPlugins.remove(idString);
      }
    }
  }
  @NotNull
  protected String[] getSystemLibraryUrlsImpl(
      @NotNull Sdk sdk, String name, OrderRootType orderRootType) {
    if (orderRootType == BinariesOrderRootType.getInstance()) {
      File libraryByAssemblyName = getLibraryByAssemblyName(name, null);
      if (libraryByAssemblyName == null) {
        return ArrayUtil.EMPTY_STRING_ARRAY;
      }

      return new String[] {
        VirtualFileManager.constructUrl(
                DotNetModuleFileType.PROTOCOL, libraryByAssemblyName.getPath())
            + ArchiveFileSystem.ARCHIVE_SEPARATOR
      };
    } else if (orderRootType == DocumentationOrderRootType.getInstance()) {
      String[] systemLibraryUrls = getSystemLibraryUrls(name, BinariesOrderRootType.getInstance());
      if (systemLibraryUrls.length != 1) {
        return ArrayUtil.EMPTY_STRING_ARRAY;
      }
      VirtualFile libraryFile =
          VirtualFileManager.getInstance().findFileByUrl(systemLibraryUrls[0]);
      if (libraryFile == null) {
        return ArrayUtil.EMPTY_STRING_ARRAY;
      }
      VirtualFile localFile = ArchiveVfsUtil.getVirtualFileForArchive(libraryFile);
      if (localFile == null) {
        return ArrayUtil.EMPTY_STRING_ARRAY;
      }
      VirtualFile docFile =
          localFile.getParent().findChild(localFile.getNameWithoutExtension() + ".xml");
      if (docFile != null) {
        return new String[] {docFile.getUrl()};
      }
      return ArrayUtil.EMPTY_STRING_ARRAY;
    } else if (orderRootType == ExternalAttributesRootOrderType.getInstance()) {
      try {
        final Ref<Couple<String>> ref = Ref.create();
        File libraryFile = getLibraryByAssemblyName(name, ref);
        if (libraryFile == null) {
          return ArrayUtil.EMPTY_STRING_ARRAY;
        }

        assert ref.get() != null;

        PluginClassLoader classLoader = (PluginClassLoader) getClass().getClassLoader();
        IdeaPluginDescriptor plugin = PluginManager.getPlugin(classLoader.getPluginId());
        assert plugin != null;
        File dir = new File(plugin.getPath(), "externalAttributes");

        val urls = new SmartList<String>();
        val requiredFileName = name + ".xml";
        FileUtil.visitFiles(
            dir,
            new Processor<File>() {
              @Override
              public boolean process(File file) {
                if (file.isDirectory()) {
                  return true;
                }
                if (Comparing.equal(requiredFileName, file.getName(), false)
                    && isValidExternalFile(ref.get().getSecond(), file)) {
                  urls.add(VfsUtil.pathToUrl(file.getPath()));
                }
                return true;
              }
            });

        return ArrayUtil.toStringArray(urls);
      } catch (Exception e) {
        LOGGER.error(e);
      }
    }
    return ArrayUtil.EMPTY_STRING_ARRAY;
  }
    @Override
    public Component getTableCellRendererComponent(
        JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
      final Component orig =
          super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
      if (myPluginDescriptor != null) {
        myNameLabel.setText(myPluginDescriptor.getName());
        final PluginId pluginId = myPluginDescriptor.getPluginId();
        final String idString = pluginId.getIdString();
        if (myPluginDescriptor.isBundled()) {
          myBundledLabel.setText("Bundled");
        } else {
          final String host = myPlugin2host.get(idString);
          if (host != null) {
            String presentableUrl = VfsUtil.urlToPath(host);
            final int idx = presentableUrl.indexOf('/');
            if (idx > -1) {
              presentableUrl = presentableUrl.substring(0, idx);
            }
            myBundledLabel.setText("From " + presentableUrl);
          } else {
            if (PluginManagerUISettings.getInstance().getInstalledPlugins().contains(idString)) {
              myBundledLabel.setText("From repository");
            } else {
              myBundledLabel.setText("Custom");
            }
          }
        }
        if (myPluginDescriptor instanceof IdeaPluginDescriptorImpl
            && ((IdeaPluginDescriptorImpl) myPluginDescriptor).isDeleted()) {
          myNameLabel.setIcon(AllIcons.Actions.Clean);
        } else if (hasNewerVersion(pluginId)) {
          myNameLabel.setIcon(AllIcons.Nodes.Pluginobsolete);
          myPanel.setToolTipText("Newer version of the plugin is available");
        } else {
          myNameLabel.setIcon(AllIcons.Nodes.Plugin);
        }

        final Color fg = orig.getForeground();
        final Color bg = orig.getBackground();
        final Color grayedFg = isSelected ? fg : Color.GRAY;

        myPanel.setBackground(bg);
        myNameLabel.setBackground(bg);
        myBundledLabel.setBackground(bg);

        myNameLabel.setForeground(fg);
        final boolean wasUpdated = wasUpdated(pluginId);
        if (wasUpdated || PluginManager.getPlugin(pluginId) == null) {
          if (!isSelected) {
            myNameLabel.setForeground(FileStatus.COLOR_ADDED);
          }
          if (wasUpdated) {
            myPanel.setToolTipText(
                "Plugin was updated to the newest version. Changes will be available after restart");
          } else {
            myPanel.setToolTipText("Plugin will be activated after restart.");
          }
        }
        myBundledLabel.setForeground(grayedFg);

        final Set<PluginId> required = myDependentToRequiredListMap.get(pluginId);
        if (required != null && required.size() > 0) {
          myNameLabel.setForeground(Color.RED);

          final StringBuilder s = new StringBuilder();
          if (myEnabled.get(pluginId) == null) {
            s.append("Plugin was not loaded.\n");
          }
          if (required.contains(PluginId.getId("com.intellij.modules.ultimate"))) {
            s.append("The plugin requires IntelliJ IDEA Ultimate");
          } else {
            s.append("Required plugin").append(required.size() == 1 ? " \"" : "s \"");
            s.append(
                StringUtil.join(
                    required,
                    new Function<PluginId, String>() {
                      @Override
                      public String fun(final PluginId id) {
                        final IdeaPluginDescriptor plugin = PluginManager.getPlugin(id);
                        return plugin == null ? id.getIdString() : plugin.getName();
                      }
                    },
                    ","));

            s.append(required.size() == 1 ? "\" is not enabled!" : "\" are not enabled!");
          }
          myPanel.setToolTipText(s.toString());
        }

        if (PluginManager.isIncompatible(myPluginDescriptor)) {
          myPanel.setToolTipText(
              IdeBundle.message(
                  "plugin.manager.incompatible.tooltip.warning",
                  ApplicationNamesInfo.getInstance().getFullProductName()));
          myNameLabel.setForeground(Color.red);
        }
      }

      return myPanel;
    }
  private void warnAboutMissedDependencies(
      final Boolean newVal, final IdeaPluginDescriptor... ideaPluginDescriptors) {
    final Set<PluginId> deps = new HashSet<PluginId>();
    final List<IdeaPluginDescriptor> descriptorsToCheckDependencies =
        new ArrayList<IdeaPluginDescriptor>();
    if (newVal) {
      Collections.addAll(descriptorsToCheckDependencies, ideaPluginDescriptors);
    } else {
      descriptorsToCheckDependencies.addAll(view);
      descriptorsToCheckDependencies.addAll(filtered);
      descriptorsToCheckDependencies.removeAll(Arrays.asList(ideaPluginDescriptors));

      for (Iterator<IdeaPluginDescriptor> iterator = descriptorsToCheckDependencies.iterator();
          iterator.hasNext(); ) {
        IdeaPluginDescriptor descriptor = iterator.next();
        final Boolean enabled = myEnabled.get(descriptor.getPluginId());
        if (enabled == null || !enabled.booleanValue()) {
          iterator.remove();
        }
      }
    }

    for (final IdeaPluginDescriptor ideaPluginDescriptor : descriptorsToCheckDependencies) {
      PluginManager.checkDependants(
          ideaPluginDescriptor,
          new Function<PluginId, IdeaPluginDescriptor>() {
            @Nullable
            public IdeaPluginDescriptor fun(final PluginId pluginId) {
              return PluginManager.getPlugin(pluginId);
            }
          },
          new Condition<PluginId>() {
            public boolean value(final PluginId pluginId) {
              Boolean enabled = myEnabled.get(pluginId);
              if (enabled == null) {
                return false;
              }
              if (newVal && !enabled.booleanValue()) {
                deps.add(pluginId);
              }

              if (!newVal) {
                final PluginId pluginDescriptorId = ideaPluginDescriptor.getPluginId();
                for (IdeaPluginDescriptor descriptor : ideaPluginDescriptors) {
                  if (pluginId.equals(descriptor.getPluginId())) {
                    deps.add(pluginDescriptorId);
                    break;
                  }
                }
              }
              return true;
            }
          });
    }
    if (!deps.isEmpty()) {
      final String listOfSelectedPlugins =
          StringUtil.join(
              ideaPluginDescriptors,
              new Function<IdeaPluginDescriptor, String>() {
                @Override
                public String fun(IdeaPluginDescriptor pluginDescriptor) {
                  return pluginDescriptor.getName();
                }
              },
              ", ");
      final Set<IdeaPluginDescriptor> pluginDependencies = new HashSet<IdeaPluginDescriptor>();
      final String listOfDependencies =
          StringUtil.join(
              deps,
              new Function<PluginId, String>() {
                public String fun(final PluginId pluginId) {
                  final IdeaPluginDescriptor pluginDescriptor = PluginManager.getPlugin(pluginId);
                  assert pluginDescriptor != null;
                  pluginDependencies.add(pluginDescriptor);
                  return pluginDescriptor.getName();
                }
              },
              "<br>");
      final String message =
          !newVal
              ? "<html>The following plugins <br>"
                  + listOfDependencies
                  + "<br>are enabled and depend"
                  + (deps.size() == 1 ? "s" : "")
                  + " on selected plugins. "
                  + "<br>Would you like to disable them too?</html>"
              : "<html>The following plugins on which "
                  + listOfSelectedPlugins
                  + " depend"
                  + (ideaPluginDescriptors.length == 1 ? "s" : "")
                  + " are disabled:<br>"
                  + listOfDependencies
                  + "<br>Would you like to enable them?</html>";
      if (Messages.showOkCancelDialog(
              message,
              newVal ? "Enable Dependant Plugins" : "Disable Plugins with Dependency on this",
              Messages.getQuestionIcon())
          == DialogWrapper.OK_EXIT_CODE) {
        for (PluginId pluginId : deps) {
          myEnabled.put(pluginId, newVal);
        }

        updatePluginDependencies();
        hideNotApplicablePlugins(
            newVal,
            pluginDependencies.toArray(new IdeaPluginDescriptor[pluginDependencies.size()]));
      }
    }
  }
 /**
  * @deprecated if more settings are needed for this plugin, you should create a {@link
  *     com.intellij.openapi.components.PersistentStateComponent} and store all the settings in a
  *     separate file without the prefix on the property name.
  */
 @Deprecated
 private static String getSettingsPrefix() {
   PluginId pluginId = PluginManager.getPluginByClassName(MTTheme.class.getName());
   return pluginId == null ? "com.chrisrm.idea.MaterialThemeUI" : pluginId.getIdString();
 }
  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;
  }
  private static boolean prepareToInstall(
      final PluginNode pluginNode,
      final List<PluginId> pluginIds,
      List<IdeaPluginDescriptor> allPlugins)
      throws IOException {
    // check for dependent plugins at first.
    if (pluginNode.getDepends() != null && pluginNode.getDepends().size() > 0) {
      // prepare plugins list for install

      final PluginId[] optionalDependentPluginIds = pluginNode.getOptionalDependentPluginIds();
      final List<PluginNode> depends = new ArrayList<PluginNode>();
      final List<PluginNode> optionalDeps = new ArrayList<PluginNode>();
      for (int i = 0; i < pluginNode.getDepends().size(); i++) {
        PluginId depPluginId = pluginNode.getDepends().get(i);

        if (PluginManager.isPluginInstalled(depPluginId)
            || PluginManager.isModuleDependency(depPluginId)
            || (pluginIds != null && pluginIds.contains(depPluginId))) {
          //  ignore installed or installing plugins
          continue;
        }

        PluginNode depPlugin = new PluginNode(depPluginId);
        depPlugin.setSize("-1");
        depPlugin.setName(depPluginId.getIdString()); // prevent from exceptions

        if (optionalDependentPluginIds != null
            && ArrayUtil.indexOf(optionalDependentPluginIds, depPluginId) != -1) {
          if (isPluginInRepo(depPluginId, allPlugins)) {
            optionalDeps.add(depPlugin);
          }
        } else {
          depends.add(depPlugin);
        }
      }

      if (depends.size() > 0) { // has something to install prior installing the plugin
        final boolean[] proceed = new boolean[1];
        final StringBuffer buf = new StringBuffer();
        for (PluginNode depend : depends) {
          buf.append(depend.getName()).append(",");
        }
        try {
          GuiUtils.runOrInvokeAndWait(
              new Runnable() {
                public void run() {
                  proceed[0] =
                      Messages.showYesNoDialog(
                              IdeBundle.message(
                                  "plugin.manager.dependencies.detected.message",
                                  depends.size(),
                                  buf.substring(0, buf.length() - 1)),
                              IdeBundle.message("plugin.manager.dependencies.detected.title"),
                              Messages.getWarningIcon())
                          == DialogWrapper.OK_EXIT_CODE;
                }
              });
        } catch (Exception e) {
          return false;
        }
        if (proceed[0]) {
          if (!prepareToInstall(depends, allPlugins)) {
            return false;
          }
        } else {
          return false;
        }
      }

      if (optionalDeps.size() > 0) {
        final StringBuffer buf = new StringBuffer();
        for (PluginNode depend : optionalDeps) {
          buf.append(depend.getName()).append(",");
        }
        final boolean[] proceed = new boolean[1];
        try {
          GuiUtils.runOrInvokeAndWait(
              new Runnable() {
                public void run() {
                  proceed[0] =
                      Messages.showYesNoDialog(
                              IdeBundle.message(
                                  "plugin.manager.optional.dependencies.detected.message",
                                  optionalDeps.size(),
                                  buf.substring(0, buf.length() - 1)),
                              IdeBundle.message("plugin.manager.dependencies.detected.title"),
                              Messages.getWarningIcon())
                          == DialogWrapper.OK_EXIT_CODE;
                }
              });
        } catch (Exception e) {
          return false;
        }
        if (proceed[0]) {
          if (!prepareToInstall(optionalDeps, allPlugins)) {
            return false;
          }
        }
      }
    }

    synchronized (PluginManager.lock) {
      final PluginDownloader downloader = PluginDownloader.createDownloader(pluginNode);
      if (downloader.prepareToInstall(ProgressManager.getInstance().getProgressIndicator())) {
        downloader.install();
        pluginNode.setStatus(PluginNode.STATUS_DOWNLOADED);
      } else {
        return false;
      }
    }

    return true;
  }
 // Get version info of our Plugin
 private String getPluginVersion() {
   final IdeaPluginDescriptor plugin =
       PluginManager.getPlugin(PluginId.getId("com.microsoft.vso.idea"));
   final String v = plugin != null ? plugin.getVersion() : DEFAULT_VERSION;
   return StringUtils.isNotEmpty(v) ? v : DEFAULT_VERSION;
 }
  @Override
  public void initComponent() {
    ProjectJdkTable jdkTable = ProjectJdkTable.getInstance();
    List<Sdk> sdkList = new ArrayList<Sdk>();

    sdkList.addAll(GoSdkUtil.getSdkOfType(GoSdkType.getInstance(), jdkTable));

    for (Sdk sdk : sdkList) {
      GoSdkData sdkData = (GoSdkData) sdk.getSdkAdditionalData();

      boolean needsUpgrade = sdkData == null;
      try {
        if (!needsUpgrade) {
          sdkData.checkValid();
        }
      } catch (ConfigurationException ex) {
        needsUpgrade = true;
      }

      if (!needsUpgrade) continue;

      needsUpgrade = false;
      GoSdkData data = GoSdkUtil.testGoogleGoSdk(sdk.getHomePath());

      if (data == null) needsUpgrade = true;

      try {
        if (data != null) {
          data.checkValid();
        }
      } catch (ConfigurationException ex) {
        needsUpgrade = true;
      }

      if (needsUpgrade) {
        Notifications.Bus.notify(
            new Notification(
                "Go SDK validator",
                "Corrupt Go SDK",
                getContent("Go", sdk.getName()),
                NotificationType.WARNING),
            myProject);
      }

      SdkModificator sdkModificator = sdk.getSdkModificator();
      sdkModificator.setSdkAdditionalData(data);
      sdkModificator.commitChanges();
    }

    sdkList.clear();
    sdkList.addAll(GoSdkUtil.getSdkOfType(GoAppEngineSdkType.getInstance(), jdkTable));

    Boolean hasGAESdk = sdkList.size() > 0;

    for (Sdk sdk : sdkList) {
      GoAppEngineSdkData sdkData = (GoAppEngineSdkData) sdk.getSdkAdditionalData();

      if (sdkData == null || sdkData.TARGET_ARCH == null || sdkData.TARGET_OS == null) {
        Notifications.Bus.notify(
            new Notification(
                "Go AppEngine SDK validator",
                "Corrupt Go App Engine SDK",
                getContent("Go App Engine", sdk.getName()),
                NotificationType.WARNING),
            myProject);

        continue;
      }

      boolean needsUpgrade = false;
      try {
        sdkData.checkValid();
      } catch (ConfigurationException ex) {
        needsUpgrade = true;
      }

      if (!needsUpgrade) continue;

      needsUpgrade = false;
      GoAppEngineSdkData data = GoSdkUtil.testGoAppEngineSdk(sdk.getHomePath());

      if (data == null) needsUpgrade = true;

      try {
        if (data != null) {
          data.checkValid();
        }
      } catch (ConfigurationException ex) {
        needsUpgrade = true;
      }

      // GAE SDK auto-update needs a bit more love
      if (data != null && !(new File(data.GOAPP_BIN_PATH)).exists()) {
        needsUpgrade = true;
      }

      if (needsUpgrade) {
        Notifications.Bus.notify(
            new Notification(
                "Go AppEngine SDK validator",
                "Corrupt Go App Engine SDK",
                getContent("Go AppEngine", sdk.getName()),
                NotificationType.WARNING),
            myProject);
      }

      SdkModificator sdkModificator = sdk.getSdkModificator();
      sdkModificator.setSdkAdditionalData(data);
      sdkModificator.commitChanges();
    }

    if (hasGAESdk) {
      String sysAppEngineDevServerPath = GoSdkUtil.getAppEngineDevServer();
      if (sysAppEngineDevServerPath.isEmpty())
        Notifications.Bus.notify(
            new Notification(
                "Go AppEngine SDK validator",
                "Problem with env variables",
                getInvalidAPPENGINE_DEV_APPSERVEREnvMessage(),
                NotificationType.WARNING,
                NotificationListener.URL_OPENING_LISTENER),
            myProject);
    }

    PluginDescriptor pluginDescriptor =
        PluginManager.getPlugin(PluginId.getId("ro.redeul.google.go"));
    if (pluginDescriptor != null) {
      String version = ((IdeaPluginDescriptorImpl) pluginDescriptor).getVersion();

      if (version.endsWith("-dev")
          && !System.getProperty("go.skip.dev.warn", "false").equals("true")) {
        Notifications.Bus.notify(
            new Notification(
                "Go plugin notice",
                "Development version detected",
                getDevVersionMessage(),
                NotificationType.WARNING,
                null),
            myProject);
      }
    }

    super.initComponent();
  }
  @NotNull
  @SuppressWarnings("ConstantConditions")
  public static IdeaPluginDescriptor getPlugin() {

    return PluginManager.getPlugin(PluginId.getId(PLUGIN_ID));
  }
  public void install(@Nullable final Runnable onSuccess, boolean confirmed) {
    IdeaPluginDescriptor[] selection = getPluginTable().getSelectedObjects();

    if (confirmed || userConfirm(selection)) {
      final List<PluginNode> list = new ArrayList<PluginNode>();
      for (IdeaPluginDescriptor descr : selection) {
        PluginNode pluginNode = null;
        if (descr instanceof PluginNode) {
          pluginNode = (PluginNode) descr;
        } else if (descr instanceof IdeaPluginDescriptorImpl) {
          PluginId pluginId = descr.getPluginId();
          pluginNode = new PluginNode(pluginId);
          pluginNode.setName(descr.getName());
          pluginNode.setDepends(
              Arrays.asList(descr.getDependentPluginIds()), descr.getOptionalDependentPluginIds());
          pluginNode.setSize("-1");
          pluginNode.setRepositoryName(PluginInstaller.UNKNOWN_HOST_MARKER);
        }

        if (pluginNode != null) {
          list.add(pluginNode);
          ourInstallingNodes.add(pluginNode);
        }
      }

      final InstalledPluginsTableModel installedModel =
          (InstalledPluginsTableModel) myInstalled.getPluginsModel();
      final Set<IdeaPluginDescriptor> disabled = new HashSet<IdeaPluginDescriptor>();
      final Set<IdeaPluginDescriptor> disabledDependants = new HashSet<IdeaPluginDescriptor>();
      for (PluginNode node : list) {
        final PluginId pluginId = node.getPluginId();
        if (installedModel.isDisabled(pluginId)) {
          disabled.add(node);
        }
        final List<PluginId> depends = node.getDepends();
        if (depends != null) {
          final Set<PluginId> optionalDeps =
              new HashSet<PluginId>(Arrays.asList(node.getOptionalDependentPluginIds()));
          for (PluginId dependantId : depends) {
            if (optionalDeps.contains(dependantId)) continue;
            final IdeaPluginDescriptor pluginDescriptor = PluginManager.getPlugin(dependantId);
            if (pluginDescriptor != null && installedModel.isDisabled(dependantId)) {
              disabledDependants.add(pluginDescriptor);
            }
          }
        }
      }

      if (suggestToEnableInstalledPlugins(installedModel, disabled, disabledDependants, list)) {
        myInstalled.setRequireShutdown(true);
      }

      try {
        Runnable onInstallRunnable =
            new Runnable() {
              @Override
              public void run() {
                for (PluginNode node : list) {
                  installedModel.appendOrUpdateDescriptor(node);
                }
                if (!myInstalled.isDisposed()) {
                  getPluginTable().updateUI();
                  myInstalled.setRequireShutdown(true);
                } else {
                  boolean needToRestart = false;
                  for (PluginNode node : list) {
                    final IdeaPluginDescriptor pluginDescriptor =
                        PluginManager.getPlugin(node.getPluginId());
                    if (pluginDescriptor == null || pluginDescriptor.isEnabled()) {
                      needToRestart = true;
                      break;
                    }
                  }

                  if (needToRestart) {
                    PluginManagerMain.notifyPluginsUpdated(null);
                  }
                }
                if (onSuccess != null) {
                  onSuccess.run();
                }
              }
            };
        Runnable cleanupRunnable =
            new Runnable() {
              @Override
              public void run() {
                ourInstallingNodes.removeAll(list);
              }
            };
        PluginManagerMain.downloadPlugins(
            list, myHost.getPluginsModel().getAllPlugins(), onInstallRunnable, cleanupRunnable);
      } catch (final IOException e1) {
        ourInstallingNodes.removeAll(list);
        PluginManagerMain.LOG.error(e1);
        //noinspection SSBasedInspection
        SwingUtilities.invokeLater(
            new Runnable() {
              @Override
              public void run() {
                IOExceptionDialog.showErrorDialog(
                    IdeBundle.message("action.download.and.install.plugin"),
                    IdeBundle.message("error.plugin.download.failed"));
              }
            });
      }
    }
  }