Ejemplo n.º 1
2
 /**
  * This function is used to re-run the analyser, and re-create the rows corresponding the its
  * results.
  */
 private void refreshReviewTable() {
   reviewPanel.removeAll();
   rows.clear();
   GridBagLayout gbl = new GridBagLayout();
   reviewPanel.setLayout(gbl);
   GridBagConstraints gbc = new GridBagConstraints();
   gbc.fill = GridBagConstraints.HORIZONTAL;
   gbc.gridy = 0;
   try {
     Map<String, Long> sums =
         analyser.processLogFile(config.getLogFilename(), fromDate.getDate(), toDate.getDate());
     for (Entry<String, Long> entry : sums.entrySet()) {
       String project = entry.getKey();
       double hours = 1.0 * entry.getValue() / (1000 * 3600);
       addRow(gbl, gbc, project, hours);
     }
     for (String project : main.getProjectsTree().getTopLevelProjects())
       if (!rows.containsKey(project)) addRow(gbl, gbc, project, 0);
     gbc.insets = new Insets(10, 0, 0, 0);
     addLeftLabel(gbl, gbc, "TOTAL");
     gbc.gridx = 1;
     gbc.weightx = 1;
     totalLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 3));
     gbl.setConstraints(totalLabel, gbc);
     reviewPanel.add(totalLabel);
     gbc.weightx = 0;
     addRightLabel(gbl, gbc);
   } catch (IOException e) {
     e.printStackTrace();
   }
   recomputeTotal();
   pack();
 }
Ejemplo n.º 2
1
  /**
   * Handles the move put from a Client.
   *
   * @param params is a String array containing the blocks to place
   */
  public void doMovePut(String[] params) {
    Map<Point, Block> moves = new HashMap<>();

    for (String move : params) {
      String[] moveArg = move.split("@");
      int blockId = Integer.parseInt(moveArg[0]);
      int moveX = Integer.parseInt(moveArg[1].split(",")[0]);
      int moveY = Integer.parseInt(moveArg[1].split(",")[1]);

      moves.put(new Point(moveX, moveY), new Block(blockId));
    }

    try {
      game.doMovePut(moves);
      System.out.println("[Server] (ClientHandler) - Current game situation:");
      System.out.println(game.getBoard().toString());
    } catch (InvalidMoveException e) {
      sendError(IProtocol.Error.MOVE_INVALID.ordinal() + " Invalid move");
      game.sendPlayerTurn();
    } catch (TilesUnownedException e) {
      sendError(
          IProtocol.Error.MOVE_TILES_UNOWNED.ordinal() + " Player tried to place unowned tile");
      game.sendPlayerTurn();
    } catch (NullPointerException e) {
      System.out.println("[Server] ClientHandler - Game ended during turn.");
    }
  }
  /** Start the background thread. */
  public void start() {
    // create a random list of cities

    cities = new City[TravelingSalesman.CITY_COUNT];
    for (int i = 0; i < TravelingSalesman.CITY_COUNT; i++) {
      cities[i] =
          new City(
              (int) (Math.random() * (getBounds().width - 10)),
              (int) (Math.random() * (getBounds().height - 60)));
    }

    // create the initial chromosomes

    chromosomes = new Chromosome[TravelingSalesman.POPULATION_SIZE];
    for (int i = 0; i < TravelingSalesman.POPULATION_SIZE; i++) {
      chromosomes[i] = new Chromosome(cities);
      chromosomes[i].setCut(cutLength);
      chromosomes[i].setMutation(TravelingSalesman.MUTATION_PERCENT);
    }
    Chromosome.sortChromosomes(chromosomes, TravelingSalesman.POPULATION_SIZE);

    // start up the background thread
    started = true;
    map.update(map.getGraphics());

    generation = 0;

    if (worker != null) worker = null;
    worker = new Thread(this);
    // worker.setPriority(Thread.MIN_PRIORITY);
    worker.start();
  }
  public void addSelection(Point p) {
    ExprPoint ep = null;
    int minDist = -1;

    for (ExprPoint ex : points) {
      int sd = ex.screenDist(p);
      if (ep == null || sd < minDist) {
        ep = ex;
        minDist = sd;
      }
    }

    if (ep != null) {
      Set<Point> remove = new HashSet<Point>();
      for (Point rp : selections.keySet()) {
        if (selections.get(rp).equals(ep)) {
          remove.add(rp);
        }
      }

      selections.put(p, ep);

      for (Point rp : remove) {
        selections.remove(rp);
      }
    }
  }
 private synchronized void startAnimation(
     JComponent component, Part part, State startState, State endState, long millis) {
   boolean isForwardAndReverse = false;
   if (endState == State.DEFAULTED) {
     isForwardAndReverse = true;
   }
   Map<Part, AnimationState> map = animationStateMap.get(component);
   if (millis <= 0) {
     if (map != null) {
       map.remove(part);
       if (map.size() == 0) {
         animationStateMap.remove(component);
       }
     }
     return;
   }
   if (map == null) {
     map = new EnumMap<Part, AnimationState>(Part.class);
     animationStateMap.put(component, map);
   }
   map.put(part, new AnimationState(startState, millis, isForwardAndReverse));
   if (!timer.isRunning()) {
     timer.start();
   }
 }
  @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);
    }
  }
  /**
   * Returns the set of data that user has entered through this wizard.
   *
   * @return Iterator
   */
  public Iterator<Map.Entry<String, String>> getSummary() {
    Map<String, String> summaryTable = new Hashtable<String, String>();

    summaryTable.put("User ID", registration.getUserID());

    return summaryTable.entrySet().iterator();
  }
  public static JBPopup createPopup(
      final List<? extends GotoRelatedItem> items, final String title) {
    Object[] elements = new Object[items.size()];
    // todo[nik] move presentation logic to GotoRelatedItem class
    final Map<PsiElement, GotoRelatedItem> itemsMap = new HashMap<PsiElement, GotoRelatedItem>();
    for (int i = 0; i < items.size(); i++) {
      GotoRelatedItem item = items.get(i);
      elements[i] = item.getElement() != null ? item.getElement() : item;
      itemsMap.put(item.getElement(), item);
    }

    return getPsiElementPopup(
        elements,
        itemsMap,
        title,
        new Processor<Object>() {
          @Override
          public boolean process(Object element) {
            if (element instanceof PsiElement) {
              //noinspection SuspiciousMethodCalls
              itemsMap.get(element).navigate();
            } else {
              ((GotoRelatedItem) element).navigate();
            }
            return true;
          }
        });
  }
Ejemplo n.º 9
0
    private Jp2File getOpenJ2pFile(File outputFile) throws IOException {
      Jp2File jp2File = openFiles.get(outputFile);
      if (jp2File == null) {
        jp2File = new Jp2File();
        jp2File.file = outputFile;
        jp2File.stream = new FileImageInputStream(outputFile);
        jp2File.header = jp2File.stream.readLine();
        jp2File.dataPos = jp2File.stream.getStreamPosition();

        final String[] tokens = jp2File.header.split(" ");
        if (tokens.length != 6) {
          throw new IOException("Unexpected tile format");
        }

        // String pg = tokens[0];   // PG
        // String ml = tokens[1];   // ML
        // String plus = tokens[2]; // +
        int jp2Width;
        int jp2Height;
        try {
          // int jp2File.nbits = Integer.parseInt(tokens[3]);
          jp2File.width = Integer.parseInt(tokens[4]);
          jp2File.height = Integer.parseInt(tokens[5]);
        } catch (NumberFormatException e) {
          throw new IOException("Unexpected tile format");
        }

        openFiles.put(outputFile, jp2File);
      }

      return jp2File;
    }
 public void checkInfos() {
   highlightingTypes.put(
       INFO_MARKER, new ExpectedHighlightingSet(HighlightSeverity.INFORMATION, false, true));
   highlightingTypes.put(
       "inject",
       new ExpectedHighlightingSet(HighlightInfoType.INJECTED_FRAGMENT_SEVERITY, false, true));
 }
Ejemplo n.º 11
0
    @Override
    public synchronized void dispose() {

      for (Map.Entry<File, Jp2File> entry : openFiles.entrySet()) {
        System.out.println("closing " + entry.getKey());
        try {
          final Jp2File jp2File = entry.getValue();
          if (jp2File.stream != null) {
            jp2File.stream.close();
            jp2File.stream = null;
          }
        } catch (IOException e) {
          // warn
        }
      }

      for (File file : openFiles.keySet()) {
        System.out.println("deleting " + file);
        if (!file.delete()) {
          // warn
        }
      }

      openFiles.clear();

      if (!cacheDir.delete()) {
        // warn
      }
    }
 public void checkWarnings() {
   highlightingTypes.put(
       WARNING_MARKER, new ExpectedHighlightingSet(HighlightSeverity.WARNING, false, true));
   highlightingTypes.put(
       END_LINE_WARNING_MARKER,
       new ExpectedHighlightingSet(HighlightSeverity.WARNING, true, true));
 }
Ejemplo n.º 13
0
    public Component getListCellRendererComponent(
        JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
      // #93658: GTK needs name to render cell renderer "natively"
      setName("ComboBox.listRenderer"); // NOI18N

      String config = (String) value;
      String label;
      if (config == null) {
        // uninitialized?
        label = null;
      } else if (config.length() > 0) {
        Map<String, String> m = configs.get(config);
        label = m != null ? m.get("$label") : /* temporary? */ null; // NOI18N
        if (label == null) {
          label = config;
        }
      } else {
        label =
            NbBundle.getBundle("org.netbeans.modules.java.j2seproject.Bundle")
                .getString("J2SEConfigurationProvider.default.label"); // NOI18N
      }
      setText(label);

      if (isSelected) {
        setBackground(list.getSelectionBackground());
        setForeground(list.getSelectionForeground());
      } else {
        setBackground(list.getBackground());
        setForeground(list.getForeground());
      }

      return this;
    }
Ejemplo n.º 14
0
  /**
   * Arena consturctor.
   *
   * @param parent The component where the arena will be displayed in.
   */
  public Arena(Component parent) {
    super();
    this.parent = parent;
    this.isVisible = false;
    if (parent == null) {
      this.isVisible = false;
    } else {
      parent.addKeyListener(this);
    }

    FrictionBuffer get = frictionBufferCache.get(this.svgFileName);
    if (get == null) { // if not in cache, create new instance and
      frictionBuffer = new FrictionBuffer(this);
      frictionBufferCache.put(this.svgFileName, frictionBuffer);
      if (DEBUG_FRICTION_CACHE) {
        System.out.println(
            "Cached friction buffer not found, I have created new instance and cached it.");
      }
    } else {
      frictionBuffer = get;
      if (DEBUG_FRICTION_CACHE) {
        System.out.println("Cached friction buffer found.");
      }
    }
  }
 @NotNull
 private InspectionTreeNode getToolParentNode(
     @NotNull String groupName, HighlightDisplayLevel errorLevel, boolean groupedBySeverity) {
   if (groupName.isEmpty()) {
     return getRelativeRootNode(groupedBySeverity, errorLevel);
   }
   ConcurrentMap<String, InspectionGroupNode> map = myGroups.get(errorLevel);
   if (map == null) {
     map =
         ConcurrencyUtil.cacheOrGet(
             myGroups, errorLevel, ContainerUtil.<String, InspectionGroupNode>newConcurrentMap());
   }
   InspectionGroupNode group;
   if (groupedBySeverity) {
     group = map.get(groupName);
   } else {
     group = null;
     for (Map<String, InspectionGroupNode> groupMap : myGroups.values()) {
       if ((group = groupMap.get(groupName)) != null) break;
     }
   }
   if (group == null) {
     group = ConcurrencyUtil.cacheOrGet(map, groupName, new InspectionGroupNode(groupName));
     addChildNodeInEDT(getRelativeRootNode(groupedBySeverity, errorLevel), group);
   }
   return group;
 }
Ejemplo n.º 16
0
  void install() {
    Vector components = new Vector();
    Vector indicies = new Vector();
    int size = 0;

    JPanel comp = selectComponents.comp;
    Vector ids = selectComponents.filesets;

    for (int i = 0; i < comp.getComponentCount(); i++) {
      if (((JCheckBox) comp.getComponent(i)).getModel().isSelected()) {
        size += installer.getIntegerProperty("comp." + ids.elementAt(i) + ".real-size");
        components.addElement(installer.getProperty("comp." + ids.elementAt(i) + ".fileset"));
        indicies.addElement(new Integer(i));
      }
    }

    String installDir = chooseDirectory.installDir.getText();

    Map osTaskDirs = chooseDirectory.osTaskDirs;
    Iterator keys = osTaskDirs.keySet().iterator();
    while (keys.hasNext()) {
      OperatingSystem.OSTask osTask = (OperatingSystem.OSTask) keys.next();
      String dir = ((JTextField) osTaskDirs.get(osTask)).getText();
      if (dir != null && dir.length() != 0) {
        osTask.setEnabled(true);
        osTask.setDirectory(dir);
      } else osTask.setEnabled(false);
    }

    InstallThread thread =
        new InstallThread(installer, progress, installDir, osTasks, size, components, indicies);
    progress.setThread(thread);
    thread.start();
  }
Ejemplo n.º 17
0
  private static void patchGtkDefaults(UIDefaults defaults) {
    if (!UIUtil.isUnderGTKLookAndFeel()) return;

    Map<String, Icon> map =
        ContainerUtil.newHashMap(
            Arrays.asList(
                "OptionPane.errorIcon",
                "OptionPane.informationIcon",
                "OptionPane.warningIcon",
                "OptionPane.questionIcon"),
            Arrays.asList(
                AllIcons.General.ErrorDialog,
                AllIcons.General.InformationDialog,
                AllIcons.General.WarningDialog,
                AllIcons.General.QuestionDialog));
    // GTK+ L&F keeps icons hidden in style
    SynthStyle style = SynthLookAndFeel.getStyle(new JOptionPane(""), Region.DESKTOP_ICON);
    for (String key : map.keySet()) {
      if (defaults.get(key) != null) continue;

      Object icon = style == null ? null : style.get(null, key);
      defaults.put(key, icon instanceof Icon ? icon : map.get(key));
    }

    Color fg = defaults.getColor("Label.foreground");
    Color bg = defaults.getColor("Label.background");
    if (fg != null && bg != null) {
      defaults.put("Label.disabledForeground", UIUtil.mix(fg, bg, 0.5));
    }
  }
 /**
  * Prepare branch descriptors for existing configuration
  *
  * @param target the target
  * @param roots the vcs root
  * @return the list of branch descriptors
  * @throws VcsException in case of error
  */
 private List<BranchDescriptor> prepareBranchDescriptors(
     BranchConfiguration target, List<VirtualFile> roots) throws VcsException {
   Map<String, String> map =
       target == null ? Collections.<String, String>emptyMap() : target.getReferences();
   List<BranchDescriptor> rc = new ArrayList<BranchDescriptor>();
   for (VirtualFile root : roots) {
     BranchDescriptor d = new BranchDescriptor();
     d.root = root;
     d.storedReference = map.remove(root.getPath());
     if (d.storedReference != null) {
       d.storedRoot = d.root.getPath();
     }
     d.currentReference = myConfig.describeRoot(root);
     if (d.storedReference != null && !myModify) {
       d.referenceToCheckout = d.storedReference;
     } else {
       d.referenceToCheckout = d.currentReference;
     }
     Branch.listAsStrings(myProject, root, false, true, d.existingBranches, null);
     Branch.listAsStrings(myProject, root, true, true, d.referencesToSelect, null);
     d.updateStatus();
     rc.add(d);
   }
   for (Map.Entry<String, String> m : map.entrySet()) {
     String root = m.getKey();
     String ref = m.getValue();
     BranchDescriptor d = new BranchDescriptor();
     d.storedReference = ref;
     d.storedRoot = root;
     d.referenceToCheckout = ref;
     d.updateStatus();
     rc.add(d);
   }
   return rc;
 }
Ejemplo n.º 19
0
 /**
  * Sets the selected elements.
  *
  * @param elements sets the select elements. All the rows that have the value in the Vector will
  *     be checked.
  */
 public void setSelectedObjects(Vector<?> elements) {
   Map<Object, String> selected = new HashMap<Object, String>();
   for (Object element : elements) {
     selected.put(element, "");
   }
   setSelectedObjects(selected);
 }
Ejemplo n.º 20
0
 // Note: this comparator imposes orderings that are inconsistent with equals.
 public int compare(String a, String b) {
   if (base.get(a) >= base.get(b)) {
     return -1;
   } else {
     return 1;
   } // returning 0 would merge keys
 }
  public void checkLineMarkers(
      @NotNull Collection<LineMarkerInfo> markerInfos, @NotNull String text) {
    String fileName = myFile == null ? "" : myFile.getName() + ": ";
    String failMessage = "";

    for (LineMarkerInfo info : markerInfos) {
      if (!containsLineMarker(info, myLineMarkerInfos.values())) {
        if (!failMessage.isEmpty()) failMessage += '\n';
        failMessage +=
            fileName
                + "Extra line marker highlighted "
                + rangeString(text, info.startOffset, info.endOffset)
                + ": '"
                + info.getLineMarkerTooltip()
                + "'";
      }
    }

    for (LineMarkerInfo expectedLineMarker : myLineMarkerInfos.values()) {
      if (!markerInfos.isEmpty() && !containsLineMarker(expectedLineMarker, markerInfos)) {
        if (!failMessage.isEmpty()) failMessage += '\n';
        failMessage +=
            fileName
                + "Line marker was not highlighted "
                + rangeString(text, expectedLineMarker.startOffset, expectedLineMarker.endOffset)
                + ": '"
                + expectedLineMarker.getLineMarkerTooltip()
                + "'";
      }
    }

    if (!failMessage.isEmpty()) Assert.fail(failMessage);
  }
Ejemplo n.º 22
0
  private void ListSubDirectorySizes(File file) {
    File[] files;
    files =
        file.listFiles(
            new FileFilter() {
              @Override
              public boolean accept(File file) {
                //                if (!file.isDirectory()){
                //                    return false;  //To change body of implemented methods use
                // File | Settings | File Templates.
                //                }else{
                //                    return true;
                //                }
                return true;
              }
            });
    Map<String, Long> dirListing = new HashMap<String, Long>();
    for (File dir : files) {
      DiskUsage diskUsage = new DiskUsage();
      diskUsage.accept(dir);
      //            long size = diskUsage.getSize() / (1024 * 1024);
      long size = diskUsage.getSize();
      dirListing.put(dir.getName(), size);
    }

    ValueComparator bvc = new ValueComparator(dirListing);
    TreeMap<String, Long> sorted_map = new TreeMap<String, Long>(bvc);
    sorted_map.putAll(dirListing);

    PrettyPrint(file, sorted_map);
  }
  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);
      }
    }
  }
  private Collection<FrameworkSupportNodeBase> createNodes(
      List<FrameworkSupportInModuleProvider> providers,
      Set<String> associated,
      final Set<String> preselected) {
    Map<String, FrameworkSupportNode> nodes = new HashMap<String, FrameworkSupportNode>();
    Map<FrameworkGroup<?>, FrameworkGroupNode> groups =
        new HashMap<FrameworkGroup<?>, FrameworkGroupNode>();
    List<FrameworkSupportNodeBase> roots = new ArrayList<FrameworkSupportNodeBase>();
    Map<String, FrameworkSupportNodeBase> associatedNodes =
        new LinkedHashMap<String, FrameworkSupportNodeBase>();
    for (FrameworkSupportInModuleProvider provider : providers) {
      createNode(provider, nodes, groups, roots, providers, associated, associatedNodes);
    }

    FrameworkSupportNodeBase.sortByName(
        roots,
        new Comparator<FrameworkSupportNodeBase>() {
          @Override
          public int compare(FrameworkSupportNodeBase o1, FrameworkSupportNodeBase o2) {
            return Comparing.compare(
                preselected.contains(o2.getId()), preselected.contains(o1.getId()));
          }
        });
    myRoots = roots;
    return associatedNodes.values();
  }
Ejemplo n.º 25
0
 public Map<String, ValidationResult.Option> getResult() {
   Map<String, ValidationResult.Option> result = new HashMap<String, ValidationResult.Option>();
   for (Item each : myItems) {
     result.put(each.validationResult.path, each.option);
   }
   return result;
 }
Ejemplo n.º 26
0
 public IconListRenderer(Config config, TokenLabUI ui) throws IOException {
   this.ui = ui;
   this.config = config;
   icons = new HashMap<Object, Icon>();
   icons.put(OK, IconCreator.createImageIcon(CHECK_ICON, OK));
   icons.put(NOTOK, IconCreator.createImageIcon(X_ICON, NOTOK));
 }
Ejemplo n.º 27
0
  /**
   * ** Returns an I18N instance based on the specified package name and Locale ** @param pkgName
   * The resource package name ** @param loc The Locale resource from with the localized text is
   * loaded
   */
  public static I18N getI18N(String pkgName, Locale loc) {
    if (pkgName != null) {
      loc = I18N.getLocale(loc);

      /* get package map for specific Locale */
      Map<String, I18N> packageMap = localeMap.get(loc);
      if (packageMap == null) {
        packageMap = new HashMap<String, I18N>();
        localeMap.put(loc, packageMap);
      }

      /* get I18N instance for package */
      I18N i18n = packageMap.get(pkgName);
      if (i18n == null) {
        i18n = new I18N(pkgName, loc);
        packageMap.put(pkgName, i18n);
      }
      return i18n;

    } else {

      /* no package specified */
      return null;
    }
  }
Ejemplo n.º 28
0
    @Override
    public Component getListCellRendererComponent(
        JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {

      // Get the renderer component from parent class

      JLabel label =
          (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

      // Get icon to use for the list item value
      Character character = (Character) value;
      Config.ConfigEntry ce = config.get(character.getName());
      Icon icon = null;

      if (ce == null) {
        icon = icons.get(NOTOK);
        label.setToolTipText(
            "Double-click to enter configuration information for this character, right-click for more options");
      } else {
        if (ce.isOk()) {
          icon = icons.get(OK);
          ui.exportAllButton.setEnabled(true);
        } else {
          icon = icons.get(NOTOK);
        }
      }
      // Set icon to display for value

      label.setIcon(icon);
      return label;
    }
Ejemplo n.º 29
0
 /**
  * Tries to calculate given line's indent column assuming that there might be a comment at the
  * given indent offset (see {@link #getCommentPrefix(IElementType)}).
  *
  * @param line target line
  * @param indentOffset start indent offset to use for the given line
  * @param lineEndOffset given line's end offset
  * @param fallbackColumn column to return if it's not possible to apply comment-specific indent
  *     calculation rules
  * @return given line's indent column to use
  */
 private int calcIndent(int line, int indentOffset, int lineEndOffset, int fallbackColumn) {
   final HighlighterIterator it = myEditor.getHighlighter().createIterator(indentOffset);
   IElementType tokenType = it.getTokenType();
   Language language = tokenType.getLanguage();
   TokenSet comments = myComments.get(language);
   if (comments == null) {
     ParserDefinition definition = LanguageParserDefinitions.INSTANCE.forLanguage(language);
     if (definition != null) {
       comments = definition.getCommentTokens();
     }
     if (comments == null) {
       return fallbackColumn;
     } else {
       myComments.put(language, comments);
     }
   }
   if (comments.contains(tokenType) && indentOffset == it.getStart()) {
     String prefix = COMMENT_PREFIXES.get(tokenType);
     if (prefix == null) {
       prefix = getCommentPrefix(tokenType);
     }
     if (!NO_COMMENT_INFO_MARKER.equals(prefix)) {
       final int indentInsideCommentOffset =
           CharArrayUtil.shiftForward(
               myChars, indentOffset + prefix.length(), lineEndOffset, " \t");
       if (indentInsideCommentOffset < lineEndOffset) {
         int indent = myEditor.calcColumnNumber(indentInsideCommentOffset, line);
         indentAfterUncomment.put(line, indent - prefix.length());
         return indent;
       }
     }
   }
   return fallbackColumn;
 }
  private Color getThreadBlockColor(BumpThread bt) {
    if (bt == null) return Color.BLACK;

    synchronized (thread_colors) {
      Color c = thread_colors.get(bt);
      if (c == null) {
        double v;
        int ct = thread_colors.size();
        if (ct == 0) v = 0;
        else if (ct == 1) v = 1;
        else {
          v = 0.5;
          int p0 = ct - 1;
          int p1 = 1;
          for (int p = p0; p > 1; p /= 2) {
            v /= 2.0;
            p0 -= p1;
            p1 *= 2;
          }
          if ((p0 & 1) == 0) p0 = 2 * p1 - p0 + 1;
          v = v * p0;
        }
        float h = (float) (v * 0.8);
        float s = 0.7f;
        float b = 1.0f;
        int rgb = Color.HSBtoRGB(h, s, b);
        rgb |= 0xc0000000;
        c = new Color(rgb, true);
        thread_colors.put(bt, c);
      }
      return c;
    }
  }