@Nullable(
     "null means no luck, otherwise it's tuple(guessed encoding, hint about content if was unable to guess, BOM)")
 public static Trinity<Charset, CharsetToolkit.GuessedEncoding, byte[]> guessFromContent(
     @NotNull VirtualFile virtualFile, @NotNull byte[] content, int length) {
   Charset defaultCharset =
       ObjectUtils.notNull(
           EncodingManager.getInstance().getEncoding(virtualFile, true),
           CharsetToolkit.getDefaultSystemCharset());
   CharsetToolkit toolkit = GUESS_UTF ? new CharsetToolkit(content, defaultCharset) : null;
   String detectedFromBytes = null;
   try {
     if (GUESS_UTF) {
       toolkit.setEnforce8Bit(true);
       Charset charset = toolkit.guessFromBOM();
       if (charset != null) {
         detectedFromBytes = AUTO_DETECTED_FROM_BOM;
         byte[] bom =
             ObjectUtils.notNull(CharsetToolkit.getMandatoryBom(charset), CharsetToolkit.UTF8_BOM);
         return Trinity.create(charset, null, bom);
       }
       CharsetToolkit.GuessedEncoding guessed = toolkit.guessFromContent(length);
       if (guessed == CharsetToolkit.GuessedEncoding.VALID_UTF8) {
         detectedFromBytes = "auto-detected from bytes";
         return Trinity.create(
             CharsetToolkit.UTF8_CHARSET, guessed, null); // UTF detected, ignore all directives
       }
       if (guessed == CharsetToolkit.GuessedEncoding.SEVEN_BIT) {
         return Trinity.create(null, guessed, null);
       }
     }
     return null;
   } finally {
     setCharsetWasDetectedFromBytes(virtualFile, detectedFromBytes);
   }
 }
Example #2
0
  @NotNull
  @Override
  public List<LightRef> getHierarchyRestrictedToLibraryScope(
      @NotNull LightRef baseRef,
      @NotNull PsiElement basePsi,
      @NotNull ByteArrayEnumerator names,
      @NotNull GlobalSearchScope libraryScope) {
    final PsiClass baseClass =
        ObjectUtils.notNull(
            basePsi instanceof PsiClass
                ? (PsiClass) basePsi
                : ReadAction.compute(() -> (PsiMember) basePsi).getContainingClass());

    final List<LightRef> overridden = new ArrayList<>();
    Processor<PsiClass> processor =
        c -> {
          if (c.hasModifierProperty(PsiModifier.PRIVATE)) return true;
          String qName = ReadAction.compute(() -> c.getQualifiedName());
          if (qName == null) return true;
          overridden.add(baseRef.override(id(qName, names)));
          return true;
        };

    ClassInheritorsSearch.search(
            baseClass,
            LibraryScopeCache.getInstance(baseClass.getProject()).getLibrariesOnlyScope(),
            true)
        .forEach(processor);
    return overridden;
  }
Example #3
0
 @NotNull
 public static GitRemoteBranch findOrCreateRemoteBranch(
     @NotNull GitRepository repository, @NotNull GitRemote remote, @NotNull String branchName) {
   GitRemoteBranch remoteBranch = findRemoteBranch(repository, remote, branchName);
   return ObjectUtils.notNull(
       remoteBranch, new GitStandardRemoteBranch(remote, branchName, GitBranch.DUMMY_HASH));
 }
 private static void fillJsTestFileStructure(
     @NotNull JstdTestFileStructure jsTestFileStructure, @NotNull JSStatement statement) {
   if (statement instanceof JSExpressionStatement) {
     JSExpressionStatement jsExpressionStatement = (JSExpressionStatement) statement;
     JSExpression expressionOfStatement = jsExpressionStatement.getExpression();
     if (expressionOfStatement instanceof JSCallExpression) {
       // TestCase("testCaseName", { test1: function() {} });
       JSCallExpression callExpression = (JSCallExpression) expressionOfStatement;
       createTestCaseStructure(jsTestFileStructure, callExpression);
     } else if (expressionOfStatement instanceof JSAssignmentExpression) {
       // testCase = TestCase("testCaseName");
       JSAssignmentExpression jsAssignmentExpression =
           (JSAssignmentExpression) expressionOfStatement;
       JSCallExpression rOperandCallExpression =
           ObjectUtils.tryCast(jsAssignmentExpression.getROperand(), JSCallExpression.class);
       if (rOperandCallExpression != null) {
         JstdTestCaseStructure testCaseStructure =
             createTestCaseStructure(jsTestFileStructure, rOperandCallExpression);
         if (testCaseStructure != null) {
           JSDefinitionExpression jsDefinitionExpression =
               ObjectUtils.tryCast(
                   jsAssignmentExpression.getLOperand(), JSDefinitionExpression.class);
           if (jsDefinitionExpression != null) {
             JSReferenceExpression jsReferenceExpression =
                 ObjectUtils.tryCast(
                     jsDefinitionExpression.getExpression(), JSReferenceExpression.class);
             if (jsReferenceExpression != null) {
               String refName = jsReferenceExpression.getReferencedName();
               if (refName != null) {
                 addPrototypeTests(testCaseStructure, refName, jsExpressionStatement);
               }
             }
           }
         }
       }
     }
   }
   if (statement instanceof JSVarStatement) {
     // var testCase = TestCase("testCaseName");
     JSVarStatement jsVarStatement = (JSVarStatement) statement;
     JSVariable[] jsVariables =
         ObjectUtils.notNull(jsVarStatement.getVariables(), JSVariable.EMPTY_ARRAY);
     for (JSVariable jsVariable : jsVariables) {
       JSCallExpression jsCallExpression =
           ObjectUtils.tryCast(jsVariable.getInitializer(), JSCallExpression.class);
       if (jsCallExpression != null) {
         JstdTestCaseStructure testCaseStructure =
             createTestCaseStructure(jsTestFileStructure, jsCallExpression);
         if (testCaseStructure != null) {
           String refName = jsVariable.getQualifiedName();
           if (refName != null) {
             addPrototypeTests(testCaseStructure, refName, jsVarStatement);
           }
         }
       }
     }
   }
 }
 public static void requeueIfPossible(InferenceCapable element) {
   final Boolean userData =
       ObjectUtils.notNull(
           element.getContainingFile().getUserData(PsiFileEx.BATCH_REFERENCE_PROCESSING), false);
   if (!userData && !PsiTreeUtil.hasErrorElements(element)) {
     final Project project = element.getProject();
     if (project != null) LuaPsiManager.getInstance(project).queueInferences(element);
   }
 }
  @NotNull
  public ListMergeStatus check(
      @NotNull CommittedChangeList list, @NotNull MergeInfoCached state, boolean isCached) {
    SvnMergeInfoCache.MergeCheckResult mergeCheckResult = state.getMap().get(list.getNumber());
    ListMergeStatus result =
        state.copiedAfter(list) ? ListMergeStatus.COMMON : ListMergeStatus.from(mergeCheckResult);

    return ObjectUtils.notNull(
        result, isCached ? ListMergeStatus.REFRESHING : ListMergeStatus.ALIEN);
  }
 /**
  * Copies content of {@code fromDir} to {@code toDir}. It's equivalent to "cp -r fromDir/* toDir"
  * unix command.
  *
  * @param fromDir source directory
  * @param toDir destination directory
  * @throws IOException in case of any IO troubles
  */
 public static void copyDirContent(@NotNull File fromDir, @NotNull File toDir) throws IOException {
   File[] children = ObjectUtils.notNull(fromDir.listFiles(), ArrayUtil.EMPTY_FILE_ARRAY);
   for (File child : children) {
     File target = new File(toDir, child.getName());
     if (child.isFile()) {
       copy(child, target);
     } else {
       copyDir(child, target, true);
     }
   }
 }
  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);
    }
  }
  @NotNull
  private static Pair.NonNull<Charset, byte[]> getCharsetAndBOM(
      @NotNull byte[] content, @NotNull Charset charset) {
    if (charset.name().contains(CharsetToolkit.UTF8) && CharsetToolkit.hasUTF8Bom(content)) {
      return Pair.createNonNull(charset, CharsetToolkit.UTF8_BOM);
    }
    try {
      Charset fromBOM = CharsetToolkit.guessFromBOM(content);
      if (fromBOM != null) {
        return Pair.createNonNull(
            fromBOM,
            ObjectUtils.notNull(
                CharsetToolkit.getMandatoryBom(fromBOM), ArrayUtil.EMPTY_BYTE_ARRAY));
      }
    } catch (UnsupportedCharsetException ignore) {
    }

    return Pair.createNonNull(charset, ArrayUtil.EMPTY_BYTE_ARRAY);
  }
Example #10
0
 @NotNull
 public static Charset extractCharsetFromFileContent(
     @Nullable Project project, @NotNull VirtualFile virtualFile, @NotNull CharSequence text) {
   return ObjectUtils.notNull(
       charsetFromContentOrNull(project, virtualFile, text), virtualFile.getCharset());
 }
Example #11
0
  void doFlush(@NotNull DfaVariableValue varPlain, boolean markUnknown) {
    DfaVariableValue varNegated = varPlain.getNegatedValue();

    final int idPlain = varPlain.getID();
    final int idNegated = varNegated == null ? -1 : varNegated.getID();

    int[] classes = myIdToEqClassesIndices.get(idPlain);
    int[] negatedClasses = myIdToEqClassesIndices.get(idNegated);
    int[] result =
        ArrayUtil.mergeArrays(
            ObjectUtils.notNull(classes, ArrayUtil.EMPTY_INT_ARRAY),
            ObjectUtils.notNull(negatedClasses, ArrayUtil.EMPTY_INT_ARRAY));

    int interruptCount = 0;

    for (int varClassIndex : result) {
      EqClass varClass = myEqClasses.get(varClassIndex);
      if ((++interruptCount & 0xf) == 0) {
        ProgressManager.checkCanceled();
      }

      varClass = new EqClass(varClass);
      myEqClasses.set(varClassIndex, varClass);
      for (int id : varClass.toNativeArray()) {
        int idUnwrapped;
        if (id == idPlain
            || id == idNegated
            || (idUnwrapped = unwrap(myFactory.getValue(id)).getID()) == idPlain
            || idUnwrapped == idNegated) {
          varClass.removeValue(id);
        }
      }

      if (varClass.isEmpty()) {
        myEqClasses.set(varClassIndex, null);

        for (TLongIterator iterator = myDistinctClasses.iterator(); iterator.hasNext(); ) {
          long pair = iterator.next();
          if (low(pair) == varClassIndex || high(pair) == varClassIndex) {
            iterator.remove();
          }
        }
      } else if (varClass.containsConstantsOnly()) {
        for (TLongIterator iterator = myDistinctClasses.iterator(); iterator.hasNext(); ) {
          long pair = iterator.next();
          if (low(pair) == varClassIndex && myEqClasses.get(high(pair)).containsConstantsOnly()
              || high(pair) == varClassIndex
                  && myEqClasses.get(low(pair)).containsConstantsOnly()) {
            iterator.remove();
          }
        }
      }
    }

    removeAllFromMap(idPlain);
    removeAllFromMap(idNegated);
    myVariableStates.remove(varPlain);
    if (varNegated != null) {
      myVariableStates.remove(varNegated);
    }
    if (markUnknown) {
      myUnknownVariables.add(varPlain);
    }
    myCachedNonTrivialEqClasses = null;
    myCachedDistinctClassPairs = null;
    myCachedHash = null;
  }
  @NotNull
  private GitUpdateResult updateImpl(@NotNull UpdateMethod updateMethod) {
    Map<VirtualFile, GitUpdater> updaters;
    try {
      updaters = defineUpdaters(updateMethod);
    } catch (VcsException e) {
      LOG.info(e);
      notifyError(myProject, "Git update failed", e.getMessage(), true, e);
      return GitUpdateResult.ERROR;
    }

    if (updaters.isEmpty()) {
      return GitUpdateResult.NOTHING_TO_UPDATE;
    }

    updaters = tryFastForwardMergeForRebaseUpdaters(updaters);

    if (updaters.isEmpty()) {
      // everything was updated via the fast-forward merge
      return GitUpdateResult.SUCCESS;
    }

    if (myCheckRebaseOverMergeProblem) {
      Collection<VirtualFile> problematicRoots = findRootsRebasingOverMerge(updaters);
      if (!problematicRoots.isEmpty()) {
        GitRebaseOverMergeProblem.Decision decision = GitRebaseOverMergeProblem.showDialog();
        if (decision == GitRebaseOverMergeProblem.Decision.MERGE_INSTEAD) {
          for (VirtualFile root : problematicRoots) {
            updaters.put(
                root,
                new GitMergeUpdater(
                    myProject,
                    myGit,
                    root,
                    myTrackedBranches,
                    myProgressIndicator,
                    myUpdatedFiles));
          }
        } else if (decision == GitRebaseOverMergeProblem.Decision.CANCEL_OPERATION) {
          return GitUpdateResult.CANCEL;
        }
      }
    }

    // save local changes if needed (update via merge may perform without saving).
    final Collection<VirtualFile> myRootsToSave = ContainerUtil.newArrayList();
    LOG.info("updateImpl: identifying if save is needed...");
    for (Map.Entry<VirtualFile, GitUpdater> entry : updaters.entrySet()) {
      VirtualFile root = entry.getKey();
      GitUpdater updater = entry.getValue();
      if (updater.isSaveNeeded()) {
        myRootsToSave.add(root);
        LOG.info("update| root " + root + " needs save");
      }
    }

    LOG.info("updateImpl: saving local changes...");
    final Ref<Boolean> incomplete = Ref.create(false);
    final Ref<GitUpdateResult> compoundResult = Ref.create();
    final Map<VirtualFile, GitUpdater> finalUpdaters = updaters;

    new GitPreservingProcess(
            myProject,
            myGit,
            myRootsToSave,
            "Update",
            "Remote",
            GitVcsSettings.getInstance(myProject).updateChangesPolicy(),
            myProgressIndicator,
            new Runnable() {
              @Override
              public void run() {
                LOG.info("updateImpl: updating...");
                VirtualFile currentlyUpdatedRoot = null;
                try {
                  for (Map.Entry<VirtualFile, GitUpdater> entry : finalUpdaters.entrySet()) {
                    currentlyUpdatedRoot = entry.getKey();
                    GitUpdater updater = entry.getValue();
                    GitUpdateResult res = updater.update();
                    LOG.info("updating root " + currentlyUpdatedRoot + " finished: " + res);
                    if (res == GitUpdateResult.INCOMPLETE) {
                      incomplete.set(true);
                    }
                    compoundResult.set(joinResults(compoundResult.get(), res));
                  }
                } catch (VcsException e) {
                  String rootName =
                      (currentlyUpdatedRoot == null) ? "" : currentlyUpdatedRoot.getName();
                  LOG.info("Error updating changes for root " + currentlyUpdatedRoot, e);
                  notifyImportantError(
                      myProject,
                      "Error updating " + rootName,
                      "Updating " + rootName + " failed with an error: " + e.getLocalizedMessage());
                }
              }
            })
        .execute(
            new Computable<Boolean>() {
              @Override
              public Boolean compute() {
                // Note: compoundResult normally should not be null, because the updaters map was
                // checked for non-emptiness.
                // But if updater.update() fails with exception for the first root, then the value
                // would not be assigned.
                // In this case we don't restore local changes either, because update failed.
                return !incomplete.get()
                    && !compoundResult.isNull()
                    && compoundResult.get().isSuccess();
              }
            });
    // GitPreservingProcess#save may fail due index.lock presence
    return ObjectUtils.notNull(compoundResult.get(), GitUpdateResult.ERROR);
  }
 @Override
 public void applyTo(@NotNull JstdRunSettings.Builder runSettingsBuilder) {
   runSettingsBuilder.setConfigFile(
       ObjectUtils.notNull(myConfigFileTextFieldWithBrowseButton.getText(), ""));
 }
Example #14
0
  @Nullable
  public static List<LocalQuickFix> registerFixes(
      @NotNull final QuickFixActionRegistrar registrar, @NotNull final PsiReference reference) {
    final PsiElement psiElement = reference.getElement();
    @NonNls
    final String shortReferenceName = reference.getRangeInElement().substring(psiElement.getText());

    Project project = psiElement.getProject();
    PsiFile containingFile = psiElement.getContainingFile();
    if (containingFile == null) return null;

    final VirtualFile classVFile = containingFile.getVirtualFile();
    if (classVFile == null) return null;

    final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
    final Module currentModule = fileIndex.getModuleForFile(classVFile);
    if (currentModule == null) return null;

    final List<LocalQuickFix> providedFixes =
        findFixes(
            new Function<MissingDependencyFixProvider, List<LocalQuickFix>>() {
              @Override
              public List<LocalQuickFix> fun(MissingDependencyFixProvider provider) {
                return provider.registerFixes(registrar, reference);
              }
            });
    if (providedFixes != null) {
      return providedFixes;
    }

    List<LocalQuickFix> result = new ArrayList<LocalQuickFix>();
    JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
    String fullReferenceText = reference.getCanonicalText();
    for (ExternalLibraryResolver resolver : ExternalLibraryResolver.EP_NAME.getExtensions()) {
      final ExternalClassResolveResult resolveResult =
          resolver.resolveClass(shortReferenceName, isReferenceToAnnotation(psiElement));
      OrderEntryFix fix = null;
      if (resolveResult != null
          && psiFacade.findClass(
                  resolveResult.getQualifiedClassName(),
                  currentModule.getModuleWithDependenciesAndLibrariesScope(true))
              == null) {
        fix =
            new AddExternalLibraryToDependenciesQuickFix(
                currentModule,
                resolveResult.getLibrary(),
                reference,
                resolveResult.getQualifiedClassName());
      } else if (!fullReferenceText.equals(shortReferenceName)) {
        ExternalLibraryDescriptor descriptor = resolver.resolvePackage(fullReferenceText);
        if (descriptor != null) {
          fix =
              new AddExternalLibraryToDependenciesQuickFix(
                  currentModule, descriptor, reference, null);
        }
      }
      if (fix != null) {
        registrar.register(fix);
        result.add(fix);
      }
    }
    if (!result.isEmpty()) {
      return result;
    }

    Set<Object> librariesToAdd = new THashSet<Object>();
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(psiElement.getProject());
    PsiClass[] classes =
        PsiShortNamesCache.getInstance(project)
            .getClassesByName(shortReferenceName, GlobalSearchScope.allScope(project));
    List<PsiClass> allowedDependencies = filterAllowedDependencies(psiElement, classes);
    if (allowedDependencies.isEmpty()) {
      return result;
    }
    classes = allowedDependencies.toArray(new PsiClass[allowedDependencies.size()]);
    OrderEntryFix moduleDependencyFix =
        new AddModuleDependencyFix(currentModule, classVFile, classes, reference);

    final PsiClass[] finalClasses = classes;
    final OrderEntryFix finalModuleDependencyFix = moduleDependencyFix;
    final OrderEntryFix providedModuleDependencyFix =
        provideFix(
            new Function<MissingDependencyFixProvider, OrderEntryFix>() {
              @Override
              public OrderEntryFix fun(MissingDependencyFixProvider provider) {
                return provider.getAddModuleDependencyFix(
                    reference, finalModuleDependencyFix, currentModule, classVFile, finalClasses);
              }
            });
    moduleDependencyFix = ObjectUtils.notNull(providedModuleDependencyFix, moduleDependencyFix);

    registrar.register(moduleDependencyFix);
    result.add(moduleDependencyFix);
    for (final PsiClass aClass : classes) {
      if (!facade.getResolveHelper().isAccessible(aClass, psiElement, aClass)) continue;
      PsiFile psiFile = aClass.getContainingFile();
      if (psiFile == null) continue;
      VirtualFile virtualFile = psiFile.getVirtualFile();
      if (virtualFile == null) continue;
      ModuleFileIndex moduleFileIndex = ModuleRootManager.getInstance(currentModule).getFileIndex();
      for (OrderEntry orderEntry : fileIndex.getOrderEntriesForFile(virtualFile)) {
        if (orderEntry instanceof LibraryOrderEntry) {
          final LibraryOrderEntry libraryEntry = (LibraryOrderEntry) orderEntry;
          final Library library = libraryEntry.getLibrary();
          if (library == null) continue;
          VirtualFile[] files = library.getFiles(OrderRootType.CLASSES);
          if (files.length == 0) continue;
          final VirtualFile jar = files[0];

          if (jar == null
              || libraryEntry.isModuleLevel() && !librariesToAdd.add(jar)
              || !librariesToAdd.add(library)) continue;
          OrderEntry entryForFile = moduleFileIndex.getOrderEntryForFile(virtualFile);
          if (entryForFile != null
              && !(entryForFile instanceof ExportableOrderEntry
                  && ((ExportableOrderEntry) entryForFile).getScope() == DependencyScope.TEST
                  && !ModuleRootManager.getInstance(currentModule)
                      .getFileIndex()
                      .isInTestSourceContent(classVFile))) {
            continue;
          }
          final OrderEntryFix platformFix =
              new OrderEntryFix() {
                @Override
                @NotNull
                public String getText() {
                  return QuickFixBundle.message(
                      "orderEntry.fix.add.library.to.classpath", libraryEntry.getPresentableName());
                }

                @Override
                @NotNull
                public String getFamilyName() {
                  return QuickFixBundle.message("orderEntry.fix.family.add.library.to.classpath");
                }

                @Override
                public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
                  return !project.isDisposed()
                      && !currentModule.isDisposed()
                      && libraryEntry.isValid();
                }

                @Override
                public void invoke(
                    @NotNull final Project project, @Nullable final Editor editor, PsiFile file) {
                  OrderEntryUtil.addLibraryToRoots(libraryEntry, currentModule);
                  if (editor != null) {
                    DumbService.getInstance(project)
                        .withAlternativeResolveEnabled(
                            new Runnable() {
                              @Override
                              public void run() {
                                new AddImportAction(project, reference, editor, aClass).execute();
                              }
                            });
                  }
                }
              };

          final OrderEntryFix providedFix =
              provideFix(
                  new Function<MissingDependencyFixProvider, OrderEntryFix>() {
                    @Override
                    public OrderEntryFix fun(MissingDependencyFixProvider provider) {
                      return provider.getAddLibraryToClasspathFix(
                          reference, platformFix, currentModule, libraryEntry, aClass);
                    }
                  });
          final OrderEntryFix fix = ObjectUtils.notNull(providedFix, platformFix);
          registrar.register(fix);
          result.add(fix);
        }
      }
    }
    return result;
  }
 private String getPluginNameById(@NotNull String pluginId) {
   return ObjectUtils.notNull(getPluginNameByIdMap().get(pluginId), pluginId);
 }
  private ColorPicker(
      Disposable parent,
      @Nullable Color color,
      boolean restoreColors,
      boolean enableOpacity,
      List<ColorPickerListener> listeners,
      boolean opacityInPercent) {
    myUpdateQueue = new Alarm(Alarm.ThreadToUse.SWING_THREAD, parent);
    myRed = createColorField(false);
    myGreen = createColorField(false);
    myBlue = createColorField(false);
    myHex = createColorField(true);
    setLayout(new BorderLayout());
    setBorder(BorderFactory.createEmptyBorder(5, 5, 0, 5));
    myColorWheelPanel = new ColorWheelPanel(this, enableOpacity, opacityInPercent);

    myExternalListeners = listeners;
    myFormat.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            PropertiesComponent.getInstance()
                .setValue(HSB_PROPERTY, String.valueOf(!isRGBMode()), Boolean.FALSE.toString());
            myR.setText(isRGBMode() ? "R:" : "H:");
            myG.setText(isRGBMode() ? "G:" : "S:");
            myR_after.setText(isRGBMode() ? "" : "\u00B0");
            myG.setText(isRGBMode() ? "G:" : "S:");
            myG_after.setText(isRGBMode() ? "" : "%");
            myB_after.setText(isRGBMode() ? "" : "%");
            applyColor(myColor);
          }
        });

    myPicker =
        createPipette(
            new ColorListener() {
              @Override
              public void colorChanged(Color color, Object source) {
                setColor(color, source);
              }
            },
            parent);
    try {
      add(buildTopPanel(true), BorderLayout.NORTH);
      add(myColorWheelPanel, BorderLayout.CENTER);

      myRecentColorsComponent =
          new RecentColorsComponent(
              new ColorListener() {
                @Override
                public void colorChanged(Color color, Object source) {
                  setColor(color, source);
                }
              },
              restoreColors);

      add(myRecentColorsComponent, BorderLayout.SOUTH);
    } catch (ParseException ignore) {
    }

    //noinspection UseJBColor
    Color c =
        ObjectUtils.notNull(
            color == null ? myRecentColorsComponent.getMostRecentColor() : color, Color.WHITE);
    setColor(c, this);

    setSize(300, 350);

    final boolean hsb = PropertiesComponent.getInstance().getBoolean(HSB_PROPERTY);
    if (hsb) {
      myFormat.setSelectedIndex(1);
    }
  }
 @Override
 public void applyTo(@NotNull JstdRunSettings.Builder runSettingsBuilder) {
   myTestCaseRunSettingsSection.applyTo(runSettingsBuilder);
   runSettingsBuilder.setTestMethodName(ObjectUtils.notNull(myTestNameTextField.getText(), ""));
 }
  private void doImportAction(final DataContext dataContext) {
    final FileChooserDescriptor descriptor =
        new FileChooserDescriptor(true, false, true, false, true, false) {
          @Override
          public boolean isFileVisible(VirtualFile file, boolean showHiddenFiles) {
            return super.isFileVisible(file, showHiddenFiles)
                && (file.isDirectory()
                    || "xml".equals(file.getExtension())
                    || file.getFileType() == FileTypes.ARCHIVE);
          }

          @Override
          public boolean isFileSelectable(VirtualFile file) {
            return file.getFileType() == StdFileTypes.XML;
          }
        };
    descriptor.setDescription(
        "Please select the configuration file (usually named IntelliLang.xml) to import.");
    descriptor.setTitle("Import Configuration");

    descriptor.putUserData(LangDataKeys.MODULE_CONTEXT, LangDataKeys.MODULE.getData(dataContext));

    final SplitterProportionsData splitterData = new SplitterProportionsDataImpl();
    splitterData.externalizeFromDimensionService(
        "IntelliLang.ImportSettingsKey.SplitterProportions");

    final VirtualFile file = FileChooser.chooseFile(descriptor, myProject, null);
    if (file == null) return;
    try {
      final Configuration cfg = Configuration.load(file.getInputStream());
      if (cfg == null) {
        Messages.showWarningDialog(
            myProject,
            "The selected file does not contain any importable configuration.",
            "Nothing to Import");
        return;
      }
      final CfgInfo info = getDefaultCfgInfo();
      final Map<String, Set<InjInfo>> currentMap =
          ContainerUtil.classify(
              info.injectionInfos.iterator(),
              new Convertor<InjInfo, String>() {
                public String convert(final InjInfo o) {
                  return o.injection.getSupportId();
                }
              });
      final List<BaseInjection> originalInjections = new ArrayList<BaseInjection>();
      final List<BaseInjection> newInjections = new ArrayList<BaseInjection>();
      //// remove duplicates
      // for (String supportId : InjectorUtils.getActiveInjectionSupportIds()) {
      //  final Set<BaseInjection> currentInjections = currentMap.get(supportId);
      //  if (currentInjections == null) continue;
      //  for (BaseInjection injection : currentInjections) {
      //    Configuration.importInjections(newInjections, Collections.singleton(injection),
      // originalInjections, newInjections);
      //  }
      // }
      // myInjections.clear();
      // myInjections.addAll(newInjections);

      for (String supportId : InjectorUtils.getActiveInjectionSupportIds()) {
        ArrayList<InjInfo> list =
            new ArrayList<InjInfo>(
                ObjectUtils.notNull(currentMap.get(supportId), Collections.<InjInfo>emptyList()));
        final List<BaseInjection> currentInjections = getInjectionList(list);
        final List<BaseInjection> importingInjections = cfg.getInjections(supportId);
        if (currentInjections == null) {
          newInjections.addAll(importingInjections);
        } else {
          Configuration.importInjections(
              currentInjections, importingInjections, originalInjections, newInjections);
        }
      }
      info.replace(originalInjections, newInjections);
      myInjectionsTable.getListTableModel().setItems(getInjInfoList(myInfos));
      final int n = newInjections.size();
      if (n > 1) {
        Messages.showInfoMessage(
            myProject, n + " entries have been successfully imported", "Import Successful");
      } else if (n == 1) {
        Messages.showInfoMessage(
            myProject, "One entry has been successfully imported", "Import Successful");
      } else {
        Messages.showInfoMessage(myProject, "No new entries have been imported", "Import");
      }
    } catch (Exception ex) {
      Configuration.LOG.error(ex);

      final String msg = ex.getLocalizedMessage();
      Messages.showErrorDialog(
          myProject, msg != null && msg.length() > 0 ? msg : ex.toString(), "Import Failed");
    }
  }
Example #19
0
 @NotNull
 public static <T> Stream<T> notNullize(@Nullable Stream<T> items) {
   return ObjectUtils.notNull(items, Stream.empty());
 }