@Override
 protected void postProcess(Sector.Triangle[] triangles) {
   if (show.contains("triangles")) {
     int i = 0;
     for (Sector.Triangle t : triangles) {
       GeoPoint[] trianglePoints = t.getPoints('A');
       double x = 0, y = 0;
       int l = trianglePoints.length;
       double[] points = new double[l * 2 + 2];
       for (int j = 0; j <= l; j++) {
         Point p = trianglePoints[j % l].toPoint(1000.0);
         points[j * 2] = p.x;
         points[j * 2 + 1] = p.z;
         if (j < l) {
           x += p.x;
           y += p.z;
         }
       }
       x /= l;
       y /= l;
       for (int j = 0; j <= l; j++) {
         points[j * 2] = points[j * 2] * 0.95 + x * 0.05;
         points[j * 2 + 1] = points[j * 2 + 1] * 0.95 + y * 0.05;
       }
       Color color = t.inverted ? triangleInverted : triangleNormal;
       out.addLine(color, points);
       if (show.contains("labels")) {
         out.addLabel(color, "" + i, x, y);
       }
       i++;
     }
   }
   super.postProcess(triangles);
 }
 /**
  * Generate new configuration name basing on descriptor
  *
  * @return the generated configuration name
  */
 private String generateNewConfigurationName() {
   String name = null;
   for (BranchDescriptor d : myBranches) {
     if (d.newBranchName != null) {
       name = d.newBranchName;
       break;
     }
     if (d.existingBranches.contains(d.currentReference)) {
       name = d.currentReference;
     }
   }
   if (name == null) {
     name = "untitled";
   }
   if (myExistingConfigNames.contains(name)) {
     for (int i = 2; i < Integer.MAX_VALUE; i++) {
       String t = name + i;
       if (!myExistingConfigNames.contains(t)) {
         name = t;
         break;
       }
     }
   }
   return name;
 }
 @Nullable
 private FrameworkSupportNode createNode(
     final FrameworkSupportInModuleProvider provider,
     final Map<String, FrameworkSupportNode> nodes,
     final Map<FrameworkGroup<?>, FrameworkGroupNode> groupNodes,
     List<FrameworkSupportNodeBase> roots,
     List<FrameworkSupportInModuleProvider> providers,
     Set<String> associated,
     Map<String, FrameworkSupportNodeBase> associatedNodes) {
   String id = provider.getFrameworkType().getId();
   FrameworkSupportNode node = nodes.get(id);
   if (node != null || associatedNodes.containsKey(id)) {
     return node;
   }
   String underlyingTypeId = provider.getFrameworkType().getUnderlyingFrameworkTypeId();
   FrameworkSupportNodeBase parentNode = null;
   final FrameworkGroup<?> group = provider.getFrameworkType().getParentGroup();
   if (underlyingTypeId != null) {
     FrameworkSupportInModuleProvider parentProvider =
         FrameworkSupportUtil.findProvider(underlyingTypeId, providers);
     if (parentProvider == null) {
       LOG.info("Cannot find id = " + underlyingTypeId);
       return null;
     }
     parentNode =
         createNode(
             parentProvider, nodes, groupNodes, roots, providers, associated, associatedNodes);
   } else if (group != null) {
     parentNode = groupNodes.get(group);
     if (parentNode == null) {
       FrameworkGroupNode groupNode = new FrameworkGroupNode(group, null);
       if (associated.contains(groupNode.getId())) {
         associatedNodes.put(groupNode.getId(), groupNode);
       } else {
         groupNodes.put(group, groupNode);
         parentNode = groupNode;
         roots.add(groupNode);
       }
     }
   }
   node = new FrameworkSupportNode(provider, parentNode, myModel, this);
   if (associated.contains(id)) {
     associatedNodes.put(id, node);
   } else {
     nodes.put(id, node);
     if (parentNode == null) {
       roots.add(node);
     }
   }
   return node;
 }
  @Nullable
  public FilteringTreeStructure.FilteringNode selectPsiElement(PsiElement element) {
    Set<PsiElement> parents = getAllParents(element);

    FilteringTreeStructure.FilteringNode node =
        (FilteringTreeStructure.FilteringNode) myAbstractTreeBuilder.getRootElement();
    while (node != null) {
      boolean changed = false;
      for (FilteringTreeStructure.FilteringNode n : node.children()) {
        final PsiElement psiElement = getPsi(n);
        if (psiElement != null && parents.contains(psiElement)) {
          node = n;
          changed = true;
          break;
        }
      }
      if (!changed) {
        myAbstractTreeBuilder.select(node);
        if (myAbstractTreeBuilder.getSelectedElements().isEmpty()) {
          TreeUtil.selectFirstNode(myTree);
        }
        myInitialNodeIsLeaf = node.getChildren().length == 0;
        return node;
      }
    }
    TreeUtil.selectFirstNode(myTree);
    return null;
  }
  private void doSaveDocument(@NotNull final Document document)
      throws IOException, SaveVetoException {
    VirtualFile file = getFile(document);

    if (file == null
        || file instanceof LightVirtualFile
        || file.isValid() && !isFileModified(file)) {
      removeFromUnsaved(document);
      return;
    }

    if (file.isValid() && needsRefresh(file)) {
      file.refresh(false, false);
      if (!myUnsavedDocuments.contains(document)) return;
    }

    for (FileDocumentSynchronizationVetoer vetoer :
        Extensions.getExtensions(FileDocumentSynchronizationVetoer.EP_NAME)) {
      if (!vetoer.maySaveDocument(document)) {
        throw new SaveVetoException();
      }
    }

    final AccessToken token =
        ApplicationManager.getApplication().acquireWriteActionLock(getClass());
    try {
      doSaveDocumentInWriteAction(document, file);
    } finally {
      token.finish();
    }
  }
 /** Verify dialog state */
 private void verify() {
   String text = myNameTextField.getText().trim();
   if (text.length() == 0) {
     setError("Empty configuration name is not allowed.");
     return;
   } else if (myTarget != null && text.equals(myTarget.getName())) {
   } else if (myExistingConfigNames.contains(text)) {
     setError("There is another configuration with the same name");
     return;
   }
   for (BranchDescriptor d : myBranches) {
     switch (d.status) {
       case BRANCH_NAME_EXISTS:
         setError("Duplicate branch name for root " + d.getRoot());
         return;
       case INVALID_BRANCH_NAME:
         setError("Invalid branch name for root " + d.getRoot());
         return;
       case BAD_REVISION:
         setError("Invalid revision for root " + d.getRoot());
         return;
       case MISSING_REVISION:
         setError("The revision must be specified for root " + d.getRoot());
         return;
       case CHECKOUT_NEEDED:
       case NO_ACTION:
       case REMOVED_ROOT:
         break;
       default:
         throw new RuntimeException("Unexpected status: " + d.status);
     }
   }
   setError(null);
 }
  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);
      }
    }
  }
  @Override
  public void saveAllDocuments() {
    ApplicationManager.getApplication().assertIsDispatchThread();

    myMultiCaster.beforeAllDocumentsSaving();
    if (myUnsavedDocuments.isEmpty()) return;

    final Map<Document, IOException> failedToSave = new HashMap<Document, IOException>();
    final Set<Document> vetoed = new HashSet<Document>();
    while (true) {
      int count = 0;

      for (Document document : myUnsavedDocuments) {
        if (failedToSave.containsKey(document)) continue;
        if (vetoed.contains(document)) continue;
        try {
          doSaveDocument(document);
        } catch (IOException e) {
          //noinspection ThrowableResultOfMethodCallIgnored
          failedToSave.put(document, e);
        } catch (SaveVetoException e) {
          vetoed.add(document);
        }
        count++;
      }

      if (count == 0) break;
    }

    if (!failedToSave.isEmpty()) {
      handleErrorsOnSave(failedToSave);
    }
  }
  private void addCondition(@NotNull ArrangementUiComponent component) {
    mySkipStateChange = true;
    try {
      component.setSelected(true);
      Collection<Set<ArrangementSettingsToken>> mutexes = mySettingsManager.getMutexes();

      // Update 'mutex conditions', i.e. conditions which can't be active at the same time (e.g.
      // type 'field' and type 'method').
      for (Set<ArrangementSettingsToken> mutex : mutexes) {
        if (!mutex.contains(component.getToken())) {
          continue;
        }
        for (ArrangementSettingsToken key : mutex) {
          if (key.equals(component.getToken())) {
            continue;
          }
          ArrangementUiComponent c = myComponents.get(key);
          if (c != null && c.isEnabled()) {
            removeCondition(c);
          }
        }
      }
      refreshConditions();
    } finally {
      mySkipStateChange = false;
    }
  }
Esempio n. 10
0
    private void processOrphanModules() {
      if (myProject.isDisposed()) return;
      if (ExternalSystemDebugEnvironment.DEBUG_ORPHAN_MODULES_PROCESSING) {
        LOG.info(
            String.format(
                "Checking for orphan modules. External paths returned by external system: '%s'",
                myExternalModulePaths));
      }
      PlatformFacade platformFacade = ServiceManager.getService(PlatformFacade.class);
      List<Module> orphanIdeModules = ContainerUtilRt.newArrayList();
      String externalSystemIdAsString = myExternalSystemId.toString();

      for (Module module : platformFacade.getModules(myProject)) {
        String s = module.getOptionValue(ExternalSystemConstants.EXTERNAL_SYSTEM_ID_KEY);
        String p = module.getOptionValue(ExternalSystemConstants.LINKED_PROJECT_PATH_KEY);
        if (ExternalSystemDebugEnvironment.DEBUG_ORPHAN_MODULES_PROCESSING) {
          LOG.info(
              String.format(
                  "IDE module: EXTERNAL_SYSTEM_ID_KEY - '%s', LINKED_PROJECT_PATH_KEY - '%s'.",
                  s, p));
        }
        if (externalSystemIdAsString.equals(s) && !myExternalModulePaths.contains(p)) {
          orphanIdeModules.add(module);
          if (ExternalSystemDebugEnvironment.DEBUG_ORPHAN_MODULES_PROCESSING) {
            LOG.info(
                String.format(
                    "External paths doesn't contain IDE module LINKED_PROJECT_PATH_KEY anymore => add to orphan IDE modules."));
          }
        }
      }

      if (!orphanIdeModules.isEmpty()) {
        ruleOrphanModules(orphanIdeModules, myProject, myExternalSystemId);
      }
    }
Esempio n. 11
0
  private void checkForEmptyAndDuplicatedNames(
      MyNode rootNode,
      String prefix,
      String title,
      Class<? extends NamedConfigurable> configurableClass,
      boolean recursively)
      throws ConfigurationException {
    final Set<String> names = new HashSet<String>();
    for (int i = 0; i < rootNode.getChildCount(); i++) {
      final MyNode node = (MyNode) rootNode.getChildAt(i);
      final NamedConfigurable scopeConfigurable = node.getConfigurable();

      if (configurableClass.isInstance(scopeConfigurable)) {
        final String name = scopeConfigurable.getDisplayName();
        if (name.trim().length() == 0) {
          selectNodeInTree(node);
          throw new ConfigurationException("Name should contain non-space characters");
        }
        if (names.contains(name)) {
          final NamedConfigurable selectedConfigurable = getSelectedConfigurable();
          if (selectedConfigurable == null
              || !Comparing.strEqual(selectedConfigurable.getDisplayName(), name)) {
            selectNodeInTree(node);
          }
          throw new ConfigurationException(
              CommonBundle.message("smth.already.exist.error.message", prefix, name), title);
        }
        names.add(name);
      }

      if (recursively) {
        checkForEmptyAndDuplicatedNames(node, prefix, title, configurableClass, true);
      }
    }
  }
  void doAddAction(AnActionButton button) {
    if (isUnknown()) {
      return;
    }

    final JBPopupFactory popupFactory = JBPopupFactory.getInstance();
    final BeforeRunTaskProvider<BeforeRunTask>[] providers =
        Extensions.getExtensions(
            BeforeRunTaskProvider.EXTENSION_POINT_NAME, myRunConfiguration.getProject());
    Set<Key> activeProviderKeys = getActiveProviderKeys();

    DefaultActionGroup actionGroup = new DefaultActionGroup(null, false);
    for (final BeforeRunTaskProvider<BeforeRunTask> provider : providers) {
      if (provider.createTask(myRunConfiguration) == null) continue;
      if (activeProviderKeys.contains(provider.getId()) && provider.isSingleton()) continue;
      AnAction providerAction =
          new AnAction(provider.getName(), null, provider.getIcon()) {
            @Override
            public void actionPerformed(AnActionEvent e) {
              BeforeRunTask task = provider.createTask(myRunConfiguration);
              if (task != null) {
                provider.configureTask(myRunConfiguration, task);
                if (!provider.canExecuteTask(myRunConfiguration, task)) return;
              } else {
                return;
              }
              task.setEnabled(true);

              Set<RunConfiguration> configurationSet = new HashSet<RunConfiguration>();
              getAllRunBeforeRuns(task, configurationSet);
              if (configurationSet.contains(myRunConfiguration)) {
                JOptionPane.showMessageDialog(
                    BeforeRunStepsPanel.this,
                    ExecutionBundle.message(
                        "before.launch.panel.cyclic_dependency_warning",
                        myRunConfiguration.getName(),
                        provider.getDescription(task)),
                    ExecutionBundle.message("warning.common.title"),
                    JOptionPane.WARNING_MESSAGE);
                return;
              }
              addTask(task);
              myListener.fireStepsBeforeRunChanged();
            }
          };
      actionGroup.add(providerAction);
    }
    final ListPopup popup =
        popupFactory.createActionGroupPopup(
            ExecutionBundle.message("add.new.run.configuration.acrtion.name"),
            actionGroup,
            SimpleDataContext.getProjectContext(myRunConfiguration.getProject()),
            false,
            false,
            false,
            null,
            -1,
            Condition.TRUE);
    popup.show(button.getPreferredPopupPoint());
  }
Esempio n. 13
0
  /** Checks if a message should be passed up, or not */
  protected boolean shouldDropUpMessage(
      @SuppressWarnings("UnusedParameters") Message msg, Address sender) {
    if (discard_all && !sender.equals(localAddress())) return true;

    if (ignoredMembers.contains(sender)) {
      if (log.isTraceEnabled()) log.trace(localAddress + ": dropping message from " + sender);
      num_up++;
      return true;
    }

    if (up > 0) {
      double r = Math.random();
      if (r < up) {
        if (excludeItself && sender.equals(localAddress())) {
          if (log.isTraceEnabled()) log.trace("excluding myself");
        } else {
          if (log.isTraceEnabled()) log.trace(localAddress + ": dropping message from " + sender);
          num_up++;
          return true;
        }
      }
    }

    return false;
  }
 private void updateDocumentFromPropertyValue(
     final String value, final Document document, final PropertiesFile propertiesFile) {
   @NonNls String text = value;
   if (myBackSlashPressed.contains(propertiesFile)) {
     text += "\\";
   }
   document.replaceString(0, document.getTextLength(), text);
 }
 @Override
 protected void usingPoints(Point[] points) {
   if (show.contains("points")) {
     int i = 0;
     for (Point p : points) {
       out.addPoint(Color.white, String.valueOf(i++), p.x, p.z);
     }
   }
   super.usingPoints(points);
 }
Esempio n. 16
0
  public boolean postProcessKeyEvent(KeyEvent e) {
    // Processing events only if we are in the focused window but
    // we are not focus owner since otherwise we will get
    // duplicate shortcut events in the client - one is from
    // activate_accelerator, another from forwarded event
    // FIXME: This is probably an incompatibility, protocol
    // doesn't say anything about disable accelerators when client
    // is focused.

    XWindowPeer parent = getToplevelXWindow();
    if (parent == null || !((Window) parent.getTarget()).isFocused() || target.isFocusOwner()) {
      return false;
    }

    boolean result = false;

    if (xembedLog.isLoggable(PlatformLogger.FINER)) xembedLog.finer("Post-processing event " + e);

    // Process ACCELERATORS
    AWTKeyStroke stroke = AWTKeyStroke.getAWTKeyStrokeForEvent(e);
    long accel_id = 0;
    boolean exists = false;
    synchronized (ACCEL_LOCK) {
      exists = accel_lookup.containsKey(stroke);
      if (exists) {
        accel_id = accel_lookup.get(stroke).longValue();
      }
    }
    if (exists) {
      if (xembedLog.isLoggable(PlatformLogger.FINE))
        xembedLog.fine("Activating accelerator " + accel_id);
      xembed.sendMessage(
          xembed.handle,
          XEMBED_ACTIVATE_ACCELERATOR,
          accel_id,
          0,
          0); // FIXME: How about overloaded?
      result = true;
    }

    // Process Grabs, unofficial GTK feature
    exists = false;
    GrabbedKey key = new GrabbedKey(e);
    synchronized (GRAB_LOCK) {
      exists = grabbed_keys.contains(key);
    }
    if (exists) {
      if (xembedLog.isLoggable(PlatformLogger.FINE)) xembedLog.fine("Forwarding grabbed key " + e);
      forwardKeyEvent(e);
      result = true;
    }

    return result;
  }
Esempio n. 17
0
 private void collectNotIncludedReferences(
     final RasterDataNode rasterDataNode, final Set<String> notIncludedNames) {
   final RasterDataNode[] referencedNodes = getReferencedNodes(rasterDataNode);
   for (final RasterDataNode referencedNode : referencedNodes) {
     final String name = referencedNode.getName();
     if (!productSubsetDef.isNodeAccepted(name) && !notIncludedNames.contains(name)) {
       notIncludedNames.add(name);
       collectNotIncludedReferences(referencedNode, notIncludedNames);
     }
   }
 }
  @Override
  public void saveDocument(@NotNull final Document document) {
    ApplicationManager.getApplication().assertIsDispatchThread();
    if (!myUnsavedDocuments.contains(document)) return;

    try {
      doSaveDocument(document);
    } catch (IOException e) {
      handleErrorsOnSave(Collections.singletonMap(document, e));
    } catch (SaveVetoException ignored) {
    }
  }
  private void handleNotification(Project project) {
    final GerritSettings settings = GerritSettings.getInstance();

    if (!settings.getReviewNotifications()) {
      return;
    }

    String apiUrl = GerritApiUtil.getApiUrl();
    List<ChangeInfo> changes =
        GerritUtil.getChangesToReview(apiUrl, settings.getLogin(), settings.getPassword());

    boolean newChange = false;
    for (ChangeInfo change : changes) {
      if (!myNotifiedChanges.contains(change.getChangeId())) {
        newChange = true;
        break;
      }
    }
    if (newChange) {
      StringBuilder stringBuilder = new StringBuilder();
      stringBuilder.append("<ul>");
      for (ChangeInfo change : changes) {
        stringBuilder
            .append("<li>")
            .append(
                !myNotifiedChanges.contains(change.getChangeId()) ? "<strong>NEW: </strong>" : "")
            .append(change.getSubject())
            .append(" (Owner: ")
            .append(change.getOwner().getName())
            .append(')')
            .append("</li>");

        myNotifiedChanges.add(change.getChangeId());
      }
      stringBuilder.append("</ul>");
      GerritUtil.notifyInformation(
          project, "Gerrit Changes waiting for my review", stringBuilder.toString());
    }
  }
Esempio n. 20
0
 private static void netxsurgery() throws Exception {
   /* Force off NetX codebase classloading. */
   Class<?> nxc;
   try {
     nxc = Class.forName("net.sourceforge.jnlp.runtime.JNLPClassLoader");
   } catch (ClassNotFoundException e1) {
     try {
       nxc = Class.forName("netx.jnlp.runtime.JNLPClassLoader");
     } catch (ClassNotFoundException e2) {
       throw (new Exception("No known NetX on classpath"));
     }
   }
   ClassLoader cl = MainFrame.class.getClassLoader();
   if (!nxc.isInstance(cl)) {
     throw (new Exception("Not running from a NetX classloader"));
   }
   Field cblf, lf;
   try {
     cblf = nxc.getDeclaredField("codeBaseLoader");
     lf = nxc.getDeclaredField("loaders");
   } catch (NoSuchFieldException e) {
     throw (new Exception("JNLPClassLoader does not conform to its known structure"));
   }
   cblf.setAccessible(true);
   lf.setAccessible(true);
   Set<Object> loaders = new HashSet<Object>();
   Stack<Object> open = new Stack<Object>();
   open.push(cl);
   while (!open.empty()) {
     Object cur = open.pop();
     if (loaders.contains(cur)) continue;
     loaders.add(cur);
     Object curl;
     try {
       curl = lf.get(cur);
     } catch (IllegalAccessException e) {
       throw (new Exception("Reflection accessibility not available even though set"));
     }
     for (int i = 0; i < Array.getLength(curl); i++) {
       Object other = Array.get(curl, i);
       if (nxc.isInstance(other)) open.push(other);
     }
   }
   for (Object cur : loaders) {
     try {
       cblf.set(cur, null);
     } catch (IllegalAccessException e) {
       throw (new Exception("Reflection accessibility not available even though set"));
     }
   }
 }
  /**
   * Удаляет переданные значения атрибутов. Если данное значение есть хотябы у одной покупки, то оно
   * не будет удалено
   *
   * @param removeList Список значений атрибутов, которые нужно удалить.
   */
  public void removeTypes(List<TypeValue> removeList) {
    if (removeList == null || removeList.isEmpty()) return;

    Set<TypeValue> useRemoveTypeSet = new HashSet<>();
    if (!(removeList.get(0) instanceof DesiredPurchase))
      for (PayObject payObject : payObjects) {
        if (removeList.contains(payObject.getImportance())
            && !useRemoveTypeSet.contains(payObject.getImportance()))
          useRemoveTypeSet.add(payObject.getImportance());
        if (removeList.contains(payObject.getPayType())
            && !useRemoveTypeSet.contains(payObject.getPayType()))
          useRemoveTypeSet.add(payObject.getPayType());
        if (removeList.contains(payObject.getUser())
            && !useRemoveTypeSet.contains(payObject.getUser()))
          useRemoveTypeSet.add(payObject.getUser());
      }

    removeList
        .stream()
        .filter(importanceType -> !useRemoveTypeSet.contains(importanceType))
        .forEach(
            value -> {
              MonitoringMoney.addFrame.removeSelectElement(value);
              MonitoringMoney.mainFrame.removeSelectElement(value);

              if (value instanceof PayType) {
                if (payTypes.contains(value)) payTypes.remove(value);
              } else if (value instanceof ImportanceType) {
                if (importanceTypes.contains(value)) importanceTypes.remove(value);
              } else if (value instanceof Users) {
                if (users.contains(value)) users.remove(value);
              } else if (value instanceof DesiredPurchase) {
                if (desiredPurchases.contains(value)) desiredPurchases.remove(value);
              }
            });
    removeList.clear();
  }
Esempio n. 22
0
    // {{{ restoreSelection() method
    public void restoreSelection(Set<String> savedChecked, Set<String> savedSelection) {
      for (int i = 0, c = getRowCount(); i < c; i++) {
        Object obj = filteredEntries.get(i);
        String name = obj.toString();
        if (obj instanceof Entry) {
          name = ((Entry) obj).plugin.jar;
        }
        if (pluginSet.contains(name)) setValueAt(true, i, 0);
        else setValueAt(savedChecked.contains(name), i, 0);
      }
      if (table == null) return;

      table.setColumnSelectionInterval(0, 0);
      if (!savedSelection.isEmpty()) {
        int i = 0;
        int rowCount = getRowCount();
        for (; i < rowCount; i++) {
          String name = filteredEntries.get(i).toString();
          if (savedSelection.contains(name)) {
            table.setRowSelectionInterval(i, i);
            break;
          }
        }
        ListSelectionModel lsm = table.getSelectionModel();
        for (; i < rowCount; i++) {
          String name = filteredEntries.get(i).toString();
          if (savedSelection.contains(name)) {
            lsm.addSelectionInterval(i, i);
          }
        }
      } else {
        if (table.getRowCount() != 0) table.setRowSelectionInterval(0, 0);
        JScrollBar scrollbar = scrollpane.getVerticalScrollBar();
        scrollbar.setValue(scrollbar.getMinimum());
      }
    } // }}}
Esempio n. 23
0
  private void doAssert(Map<String, String> expected, PlaybackRunner.StatusCallback cb)
      throws AssertionError {
    final Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();

    if (owner == null) {
      throw new AssertionError("No component focused");
    }

    Component eachParent = owner;
    final LinkedHashMap<String, String> actual = new LinkedHashMap<String, String>();
    while (eachParent != null) {
      if (eachParent instanceof TestableUi) {
        ((TestableUi) eachParent).putInfo(actual);
      }

      eachParent = eachParent.getParent();
    }

    Set testedKeys = new LinkedHashSet<String>();
    for (String eachKey : expected.keySet()) {
      testedKeys.add(eachKey);

      final String actualValue = actual.get(eachKey);
      final String expectedValue = expected.get(eachKey);

      if (!expectedValue.equals(actualValue)) {
        throw new AssertionError(
            eachKey + " expected: " + expectedValue + " but was: " + actualValue);
      }
    }

    Map<String, String> untested = new HashMap<String, String>();
    for (String eachKey : actual.keySet()) {
      if (testedKeys.contains(eachKey)) continue;
      untested.put(eachKey, actual.get(eachKey));
    }

    StringBuffer untestedText = new StringBuffer();
    for (String each : untested.keySet()) {
      if (untestedText.length() > 0) {
        untestedText.append(",");
      }
      untestedText.append(each).append("=").append(untested.get(each));
    }

    cb.message("Untested info: " + untestedText.toString(), getLine());
  }
Esempio n. 24
0
  private RangeHighlighter doHightlightRange(
      final TextRange textRange,
      final TextAttributes attributes,
      Set<RangeHighlighter> highlighters) {
    HighlightManager highlightManager = HighlightManager.getInstance(mySearchResults.getProject());

    MarkupModelEx markupModel = (MarkupModelEx) mySearchResults.getEditor().getMarkupModel();

    final RangeHighlighter[] candidate = new RangeHighlighter[1];

    boolean notFound =
        markupModel.processRangeHighlightersOverlappingWith(
            textRange.getStartOffset(),
            textRange.getEndOffset(),
            new Processor<RangeHighlighterEx>() {
              @Override
              public boolean process(RangeHighlighterEx highlighter) {
                TextAttributes textAttributes = highlighter.getTextAttributes();
                if (highlighter.getUserData(SEARCH_MARKER) != null
                    && textAttributes != null
                    && textAttributes.equals(attributes)
                    && highlighter.getStartOffset() == textRange.getStartOffset()
                    && highlighter.getEndOffset() == textRange.getEndOffset()) {
                  candidate[0] = highlighter;
                  return false;
                }
                return true;
              }
            });

    if (!notFound && highlighters.contains(candidate[0])) {
      return candidate[0];
    }
    final ArrayList<RangeHighlighter> dummy = new ArrayList<RangeHighlighter>();
    highlightManager.addRangeHighlight(
        mySearchResults.getEditor(),
        textRange.getStartOffset(),
        textRange.getEndOffset(),
        attributes,
        false,
        dummy);
    final RangeHighlighter h = dummy.get(0);
    highlighters.add(h);
    h.putUserData(SEARCH_MARKER, YES);
    return h;
  }
  public void setProviders(
      List<FrameworkSupportInModuleProvider> providers,
      Set<String> associated,
      Set<String> preselected) {
    myProviders = providers;

    myAssociatedFrameworks = createNodes(myProviders, associated, preselected);
    for (FrameworkSupportNodeBase node : myRoots) {
      if (preselected.contains(node.getId())) {
        node.setChecked(true);
      }
    }
    setAssociatedFrameworks();

    myFrameworksTree.setRoots(myRoots);
    myFrameworksTree.setSelectionRow(0);
  }
Esempio n. 26
0
  private void resetSelection(@NotNull String[] selectedSerials) {
    MyDeviceTableModel model = (MyDeviceTableModel) myDeviceTable.getModel();
    Set<String> selectedSerialsSet = new HashSet<String>();
    Collections.addAll(selectedSerialsSet, selectedSerials);
    IDevice[] myDevices = model.myDevices;
    ListSelectionModel selectionModel = myDeviceTable.getSelectionModel();
    boolean cleared = false;

    for (int i = 0, n = myDevices.length; i < n; i++) {
      String serialNumber = myDevices[i].getSerialNumber();
      if (selectedSerialsSet.contains(serialNumber)) {
        if (!cleared) {
          selectionModel.clearSelection();
          cleared = true;
        }
        selectionModel.addSelectionInterval(i, i);
      }
    }
  }
Esempio n. 27
0
 public Object invoke(Object object, Method method, Object[] params) throws Throwable {
   final boolean needUpdate = myCheckedNames.contains(method.getName());
   try {
     final Object result = method.invoke(myDelegateModel, unwrapParams(params));
     if (result instanceof LibraryTable) {
       return Proxy.newProxyInstance(
           getClass().getClassLoader(),
           new Class[] {LibraryTable.class},
           new LibraryTableInvocationHandler((LibraryTable) result));
     }
     return result;
   } catch (InvocationTargetException e) {
     throw e.getCause();
   } finally {
     if (needUpdate) {
       updateOrderEntriesInEditors();
     }
   }
 }
 private boolean checkBeforeRunTasksAbility(boolean checkOnlyAddAction) {
   if (isUnknown()) {
     return false;
   }
   Set<Key> activeProviderKeys = getActiveProviderKeys();
   final BeforeRunTaskProvider<BeforeRunTask>[] providers =
       Extensions.getExtensions(
           BeforeRunTaskProvider.EXTENSION_POINT_NAME, myRunConfiguration.getProject());
   for (final BeforeRunTaskProvider<BeforeRunTask> provider : providers) {
     if (provider.createTask(myRunConfiguration) != null) {
       if (!checkOnlyAddAction) {
         return true;
       } else if (!provider.isSingleton() || !activeProviderKeys.contains(provider.getId())) {
         return true;
       }
     }
   }
   return false;
 }
Esempio n. 29
0
 public Object[] getElementsByName(
     final String id, final boolean checkBoxState, final String pattern) {
   final HashMap<AnAction, String> map = new HashMap<AnAction, String>();
   final ActionGroup mainMenu =
       (ActionGroup) myActionManager.getActionOrStub(IdeActions.GROUP_MAIN_MENU);
   collectActions(id, map, mainMenu, mainMenu.getTemplatePresentation().getText());
   if (checkBoxState) {
     final Set<String> ids = ((ActionManagerImpl) myActionManager).getActionIds();
     for (AnAction action : map.keySet()) { // do not add already included actions
       ids.remove(getActionId(action));
     }
     if (ids.contains(id)) {
       final AnAction anAction = myActionManager.getAction(id);
       if (!(anAction instanceof ActionGroup)) {
         map.put(anAction, null);
       }
     }
   }
   return map.entrySet().toArray(new Map.Entry[map.size()]);
 }
Esempio n. 30
0
 private void createPathsNeighbours() {
   Set<Path> neighbours;
   for (Path path : this) {
     neighbours = new FastSet<Path>();
     for (Road road : path) {
       for (EntityID entityID : road.getNeighbours()) {
         if (world.getEntity(entityID) instanceof Road) {
           for (Path p : this) {
             if (!path.equals(p) && p.contains((Road) world.getEntity(entityID))) {
               if (!neighbours.contains(p)) {
                 neighbours.add(p);
               }
             }
           }
         }
       }
     }
     path.setNeighbours(neighbours);
   }
 }