@NotNull
 public static String getLibraryName(@NotNull Library library) {
   final String result = library.getName();
   if (result != null) {
     return result;
   }
   String[] endingsToStrip = {"/", "!", ".jar"};
   StringBuilder buffer = new StringBuilder();
   for (OrderRootType type : OrderRootType.getAllTypes()) {
     for (String url : library.getUrls(type)) {
       buffer.setLength(0);
       buffer.append(url);
       for (String ending : endingsToStrip) {
         if (buffer.lastIndexOf(ending) == buffer.length() - ending.length()) {
           buffer.setLength(buffer.length() - ending.length());
         }
       }
       final int i = buffer.lastIndexOf(PATH_SEPARATOR);
       if (i < 0 || i >= buffer.length() - 1) {
         continue;
       }
       String candidate = buffer.substring(i + 1);
       if (!StringUtil.isEmpty(candidate)) {
         return candidate;
       }
     }
   }
   assert false;
   return "unknown-lib";
 }
Esempio n. 2
1
  /** 選択されている行をコピーする。 */
  public void copyRow() {

    StringBuilder sb = new StringBuilder();
    int numRows = view.getTable().getSelectedRowCount();
    int[] rowsSelected = view.getTable().getSelectedRows();
    int numColumns = view.getTable().getColumnCount();

    for (int i = 0; i < numRows; i++) {
      if (tableModel.getObject(rowsSelected[i]) != null) {
        StringBuilder s = new StringBuilder();
        for (int col = 0; col < numColumns; col++) {
          Object o = view.getTable().getValueAt(rowsSelected[i], col);
          if (o != null) {
            s.append(o.toString());
          }
          s.append(",");
        }
        if (s.length() > 0) {
          s.setLength(s.length() - 1);
        }
        sb.append(s.toString()).append("\n");
      }
    }
    if (sb.length() > 0) {
      StringSelection stsel = new StringSelection(sb.toString());
      Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stsel, stsel);
    }
  }
  private static void formatStyle(
      final StringBuilder builder, final SimpleTextAttributes attributes) {
    final Color fgColor = attributes.getFgColor();
    final Color bgColor = attributes.getBgColor();
    final int style = attributes.getStyle();

    final int pos = builder.length();
    if (fgColor != null) {
      builder
          .append("color:#")
          .append(Integer.toString(fgColor.getRGB() & 0xFFFFFF, 16))
          .append(';');
    }
    if (bgColor != null) {
      builder
          .append("background-color:#")
          .append(Integer.toString(bgColor.getRGB() & 0xFFFFFF, 16))
          .append(';');
    }
    if ((style & SimpleTextAttributes.STYLE_BOLD) != 0) {
      builder.append("font-weight:bold;");
    }
    if ((style & SimpleTextAttributes.STYLE_ITALIC) != 0) {
      builder.append("font-style:italic;");
    }
    if ((style & SimpleTextAttributes.STYLE_UNDERLINE) != 0) {
      builder.append("text-decoration:underline;");
    } else if ((style & SimpleTextAttributes.STYLE_STRIKEOUT) != 0) {
      builder.append("text-decoration:line-through;");
    }
    if (builder.length() > pos) {
      builder.insert(pos, " style=\"");
      builder.append('"');
    }
  }
  /**
   * Returns date in the format: neededDatePattern, in case if year or month isn't entered, current
   * year/month is put.
   *
   * @return correct date.
   */
  private Date getCorrectedDate(String enteredDate) {
    Queue<String> dateParts = new ArrayDeque<>(3);
    StringBuilder number = new StringBuilder();
    for (char symbol : enteredDate.toCharArray()) {
      if (Character.isDigit(symbol)) {
        number.append(symbol);
      } else if (number.length() > 0) {
        dateParts.add(number.toString());
        number = new StringBuilder();
      }
    }
    if (number.length() > 0) {
      dateParts.add(number.toString());
    }

    Calendar currentDate = Calendar.getInstance();
    switch (dateParts.size()) {
      case 1:
        dateParts.add(Integer.toString(currentDate.get(Calendar.MONTH) + 1));
      case 2:
        dateParts.add(Integer.toString(currentDate.get(Calendar.YEAR)));
    }

    try {
      return new SimpleDateFormat("dd.MM.yyyy")
          .parse(dateParts.remove() + '.' + dateParts.remove() + '.' + dateParts.remove());

    } catch (ParseException e) {
      throw new RuntimeException(e); // todo change exception
    }
  }
Esempio n. 5
1
  @Override
  protected void updateTitle(@Nullable final PsiVariable variable, final String value) {
    final PsiElement declarationScope =
        variable != null ? ((PsiParameter) variable).getDeclarationScope() : null;
    if (declarationScope instanceof PsiMethod) {
      final PsiMethod psiMethod = (PsiMethod) declarationScope;
      final StringBuilder buf = new StringBuilder();
      buf.append(psiMethod.getName()).append(" (");
      boolean frst = true;
      final List<TextRange> ranges2Remove = new ArrayList<>();
      TextRange addedRange = null;
      for (PsiParameter parameter : psiMethod.getParameterList().getParameters()) {
        if (frst) {
          frst = false;
        } else {
          buf.append(", ");
        }
        int startOffset = buf.length();
        if (myMustBeFinal || myPanel.isGenerateFinal()) {
          buf.append("final ");
        }
        buf.append(parameter.getType().getPresentableText())
            .append(" ")
            .append(variable == parameter ? value : parameter.getName());
        int endOffset = buf.length();
        if (variable == parameter) {
          addedRange = new TextRange(startOffset, endOffset);
        } else if (myPanel.isParamToRemove(parameter)) {
          ranges2Remove.add(new TextRange(startOffset, endOffset));
        }
      }

      buf.append(")");
      setPreviewText(buf.toString());
      final MarkupModel markupModel =
          DocumentMarkupModel.forDocument(getPreviewEditor().getDocument(), myProject, true);
      markupModel.removeAllHighlighters();
      for (TextRange textRange : ranges2Remove) {
        markupModel.addRangeHighlighter(
            textRange.getStartOffset(),
            textRange.getEndOffset(),
            0,
            getTestAttributesForRemoval(),
            HighlighterTargetArea.EXACT_RANGE);
      }
      markupModel.addRangeHighlighter(
          addedRange.getStartOffset(),
          addedRange.getEndOffset(),
          0,
          getTextAttributesForAdd(),
          HighlighterTargetArea.EXACT_RANGE);
      revalidate();
    }
  }
Esempio n. 6
1
  // Communications
  public void updateStatus(InputStream in) throws IOException {
    DataInputStream din = new DataInputStream(in);
    if (builder.length() != 0) {
      builder.delete(0, builder.length());
    }

    eventTotal.setText(form.format(new Long(din.readLong())));
    dataTotal.setText(Util.convertBytes(builder, din.readLong(), true).toString());
    builder.delete(0, builder.length());
    dataRate.setText(Util.convertBytesRate(builder, din.readDouble(), true).toString());
    eventRate.setText(form.format(new Integer((int) din.readDouble())) + "e/s");
  }
Esempio n. 7
1
 String getEnabledCiphers() {
   StringBuilder sb = new StringBuilder();
   for (Entry e : data) {
     if (e.enabled) {
       sb.append(e.cipher);
       sb.append(',');
     }
   }
   if (sb.length() == 0) {
     return sb.toString();
   } else {
     return sb.substring(0, sb.length() - 1);
   }
 }
Esempio n. 8
1
 /**
  * @param source Source string
  * @param chars  Symbols to be trimmed
  * @return string without all specified chars at the end. For example,
  *         <code>chopTrailingChars("c:\\my_directory\\//\\",new char[]{'\\'}) is <code>"c:\\my_directory\\//"</code>,
  *         <code>chopTrailingChars("c:\\my_directory\\//\\",new char[]{'\\','/'}) is <code>"c:\my_directory"</code>.
  *         Actually this method can be used to normalize file names to chop trailing separator chars.
  */
 public static String chopTrailingChars(String source, char[] chars) {
   StringBuilder sb = new StringBuilder(source);
   while (true) {
     boolean atLeastOneCharWasChopped = false;
     for (int i = 0; i < chars.length && sb.length() > 0; i++) {
       if (sb.charAt(sb.length() - 1) == chars[i]) {
         sb.deleteCharAt(sb.length() - 1);
         atLeastOneCharWasChopped = true;
       }
     }
     if (!atLeastOneCharWasChopped) {
       break;
     }
   }
   return sb.toString();
 }
 private void replaceIteratorNext(
     PsiElement element,
     String contentVariableName,
     String iteratorName,
     PsiElement childToSkip,
     StringBuilder out,
     PsiType contentType) {
   if (isIteratorNext(element, iteratorName, contentType)) {
     out.append(contentVariableName);
   } else {
     final PsiElement[] children = element.getChildren();
     if (children.length == 0) {
       final String text = element.getText();
       if (PsiKeyword.INSTANCEOF.equals(text) && out.charAt(out.length() - 1) != ' ') {
         out.append(' ');
       }
       out.append(text);
     } else {
       boolean skippingWhiteSpace = false;
       for (final PsiElement child : children) {
         if (child.equals(childToSkip)) {
           skippingWhiteSpace = true;
         } else if (child instanceof PsiWhiteSpace && skippingWhiteSpace) {
           // don't do anything
         } else {
           skippingWhiteSpace = false;
           replaceIteratorNext(
               child, contentVariableName, iteratorName, childToSkip, out, contentType);
         }
       }
     }
   }
 }
 private void replaceCollectionGetAccess(
     PsiElement element,
     String contentVariableName,
     PsiVariable listVariable,
     String indexName,
     PsiElement childToSkip,
     StringBuilder out) {
   if (isListGetLookup(element, indexName, listVariable)) {
     out.append(contentVariableName);
   } else {
     final PsiElement[] children = element.getChildren();
     if (children.length == 0) {
       final String text = element.getText();
       if (PsiKeyword.INSTANCEOF.equals(text) && out.charAt(out.length() - 1) != ' ') {
         out.append(' ');
       }
       out.append(text);
     } else {
       boolean skippingWhiteSpace = false;
       for (final PsiElement child : children) {
         if (child.equals(childToSkip)) {
           skippingWhiteSpace = true;
         } else if (child instanceof PsiWhiteSpace && skippingWhiteSpace) {
           // don't do anything
         } else {
           skippingWhiteSpace = false;
           replaceCollectionGetAccess(
               child, contentVariableName, listVariable, indexName, childToSkip, out);
         }
       }
     }
   }
 }
Esempio n. 11
1
 /**
  * Writes the <code>shape</code>, <code>coords</code>, <code>href</code>,
  * <code>nohref</code> Attribute for the specified figure and shape.
  *
  * @return Returns true, if the polygon is inside of the image bounds.
  */
 private boolean writePolyAttributes(IXMLElement elem, SVGFigure f, Shape shape) {
     AffineTransform t = TRANSFORM.getClone(f);
     if (t == null) {
         t = drawingTransform;
     } else {
         t.preConcatenate(drawingTransform);
     }
     
     StringBuilder buf = new StringBuilder();
     float[] coords = new float[6];
     GeneralPath path = new GeneralPath();
     for (PathIterator i = shape.getPathIterator(t, 1.5f);
     ! i.isDone(); i.next()) {
         switch (i.currentSegment(coords)) {
             case PathIterator.SEG_MOVETO :
                 if (buf.length() != 0) {
                     throw new IllegalArgumentException("Illegal shape "+shape);
                 }
                 if (buf.length() != 0) {
                     buf.append(',');
                 }
                 buf.append((int) coords[0]);
                 buf.append(',');
                 buf.append((int) coords[1]);
                 path.moveTo(coords[0], coords[1]);
                 break;
             case PathIterator.SEG_LINETO :
                 if (buf.length() != 0) {
                     buf.append(',');
                 }
                 buf.append((int) coords[0]);
                 buf.append(',');
                 buf.append((int) coords[1]);
                 path.lineTo(coords[0], coords[1]);
                 break;
             case PathIterator.SEG_CLOSE :
                 path.closePath();
                 break;
             default :
                 throw new InternalError("Illegal segment type "+i.currentSegment(coords));
         }
     }
     elem.setAttribute("shape", "poly");
     elem.setAttribute("coords", buf.toString());
     writeHrefAttribute(elem, f);
     return path.intersects(new Rectangle2D.Float(bounds.x, bounds.y, bounds.width, bounds.height));
 }
 // 过滤整数字符,把所有非0~9的字符全部删除
 private void filterInt(StringBuilder builder) {
   for (int i = builder.length() - 1; i >= 0; i--) {
     int cp = builder.codePointAt(i);
     if (cp > '9' || cp < '0') {
       builder.deleteCharAt(i);
     }
   }
 }
 @Override
 protected void textChanged(DocumentEvent e) {
   myBuffer.delete(0, myBuffer.length());
   try {
     myBuffer.append(e.getDocument().getText(0, e.getDocument().getLength()));
   } catch (BadLocationException exception) {
     LOG.warn(exception);
   }
 }
Esempio n. 14
1
 public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
     throws BadLocationException {
   StringBuilder builder = new StringBuilder(string);
   for (int i = builder.length() - 1; i >= 0; i--) {
     int cp = builder.codePointAt(i);
     if (!Character.isDigit(cp) && cp != '-') {
       builder.deleteCharAt(i);
       if (Character.isSupplementaryCodePoint(cp)) {
         i--;
         builder.deleteCharAt(i);
       }
     }
   }
   super.insertString(fb, offset, builder.toString(), attr);
 }
  private void updateText() {
    StringBuilder sb = new StringBuilder();

    if (myShowSettingsBeforeRunCheckBox.isSelected()) {
      sb.append(ExecutionBundle.message("configuration.edit.before.run")).append(", ");
    }

    List<BeforeRunTask> tasks = myModel.getItems();
    if (!tasks.isEmpty()) {
      LinkedHashMap<BeforeRunTaskProvider, Integer> counter =
          new LinkedHashMap<BeforeRunTaskProvider, Integer>();
      for (BeforeRunTask task : tasks) {
        BeforeRunTaskProvider<BeforeRunTask> provider =
            BeforeRunTaskProvider.getProvider(
                myRunConfiguration.getProject(), task.getProviderId());
        if (provider != null) {
          Integer count = counter.get(provider);
          if (count == null) {
            count = task.getItemsCount();
          } else {
            count += task.getItemsCount();
          }
          counter.put(provider, count);
        }
      }
      for (Iterator<Map.Entry<BeforeRunTaskProvider, Integer>> iterator =
              counter.entrySet().iterator();
          iterator.hasNext(); ) {
        Map.Entry<BeforeRunTaskProvider, Integer> entry = iterator.next();
        BeforeRunTaskProvider provider = entry.getKey();
        String name = provider.getName();
        if (name.startsWith("Run ")) {
          name = name.substring(4);
        }
        sb.append(name);
        if (entry.getValue() > 1) {
          sb.append(" (").append(entry.getValue().intValue()).append(")");
        }
        if (iterator.hasNext()) sb.append(", ");
      }
    }
    if (sb.length() > 0) {
      sb.insert(0, ": ");
    }
    sb.insert(0, ExecutionBundle.message("before.launch.panel.title"));
    myListener.titleChanged(sb.toString());
  }
Esempio n. 16
1
        @Override
        protected Transferable createTransferable(JComponent c) {
          if (!(c instanceof XDebuggerTree)) {
            return null;
          }
          XDebuggerTree tree = (XDebuggerTree) c;
          //noinspection deprecation
          TreePath[] selectedPaths = tree.getSelectionPaths();
          if (selectedPaths == null || selectedPaths.length == 0) {
            return null;
          }

          StringBuilder plainBuf = new StringBuilder();
          StringBuilder htmlBuf = new StringBuilder();
          htmlBuf.append("<html>\n<body>\n<ul>\n");
          TextTransferable.ColoredStringBuilder coloredTextContainer =
              new TextTransferable.ColoredStringBuilder();
          for (TreePath path : selectedPaths) {
            htmlBuf.append("  <li>");
            Object node = path.getLastPathComponent();
            if (node != null) {
              if (node instanceof XDebuggerTreeNode) {
                ((XDebuggerTreeNode) node).appendToComponent(coloredTextContainer);
                coloredTextContainer.appendTo(plainBuf, htmlBuf);
              } else {
                String text = node.toString();
                plainBuf.append(text);
                htmlBuf.append(text);
              }
            }
            plainBuf.append('\n');
            htmlBuf.append("</li>\n");
          }

          // remove the last newline
          plainBuf.setLength(plainBuf.length() - 1);
          htmlBuf.append("</ul>\n</body>\n</html>");
          return new TextTransferable(htmlBuf.toString(), plainBuf.toString());
        }
  @Override
  public final void customize(
      final JList list,
      final T value,
      final int index,
      final boolean selected,
      final boolean hasFocus) {
    myText = StringBuilderSpinAllocator.alloc();
    try {
      doCustomize(list, value, index, selected, hasFocus);

      if (myText.length() == 0) {
        setText(null);
      } else {
        myText.insert(0, "<html><body style=\"white-space:nowrap\">");
        myText.append("</body></html>");
        setText(myText.toString());
      }
    } finally {
      StringBuilderSpinAllocator.dispose(myText);
      myText = null;
    }
  }
  public void showItem() {

    if (!this.editorPanel.getViewer().isLanguageFunctionAvailable()) {

      return;
    }

    this.highlight =
        this.editorPanel
            .getEditor()
            .addHighlight(this.position, this.position + this.word.length(), null, true);

    final FindSynonymsActionHandler _this = this;

    QTextEditor editor = this.editorPanel.getEditor();

    Rectangle r = null;

    try {

      r = editor.modelToView(this.position);

    } catch (Exception e) {

      // BadLocationException!
      Environment.logError("Location: " + this.position + " is not valid", e);

      UIUtils.showErrorMessage(this.editorPanel, "Unable to display synonyms.");

      return;
    }

    int y = r.y;

    // Show a panel of all the items.
    final QPopup p = this.popup;

    p.setOpaque(false);

    Synonyms syns = null;

    try {

      syns = this.projectViewer.getSynonymProvider().getSynonyms(this.word);

    } catch (Exception e) {

      UIUtils.showErrorMessage(this.editorPanel, "Unable to display synonyms.");

      Environment.logError("Unable to lookup synonyms for: " + word, e);

      return;
    }

    if ((syns.words.size() == 0) && (this.word.toLowerCase().endsWith("ed"))) {

      // Trim off the ed and try again.
      try {

        syns = this.projectViewer.getSynonyms(this.word.substring(0, this.word.length() - 2));

      } catch (Exception e) {

        UIUtils.showErrorMessage(this.editorPanel, "Unable to display synonyms.");

        Environment.logError("Unable to lookup synonyms for: " + word, e);

        return;
      }
    }

    if ((syns.words.size() == 0) && (this.word.toLowerCase().endsWith("s"))) {

      // Trim off the ed and try again.
      try {

        syns = this.projectViewer.getSynonyms(this.word.substring(0, this.word.length() - 1));

      } catch (Exception e) {

        UIUtils.showErrorMessage(this.editorPanel, "Unable to display synonyms.");

        Environment.logError("Unable to lookup synonyms for: " + word, e);

        return;
      }
    }

    StringBuilder sb = new StringBuilder();

    if (syns.words.size() > 0) {

      sb.append("6px");

      for (int i = 0; i < syns.words.size(); i++) {

        if (sb.length() > 0) {

          sb.append(", ");
        }

        sb.append("p, 3px, [p,90px], 5px");
      }
      /*
                if (syns.words.size () > 0)
                {

                    sb.append (",5px");

                }
      */
    } else {

      sb.append("6px, p, 6px");
    }

    FormLayout summOnly = new FormLayout("3px, fill:380px:grow, 3px", sb.toString());
    PanelBuilder pb = new PanelBuilder(summOnly);

    CellConstraints cc = new CellConstraints();

    int ind = 2;

    Map<String, String> names = new HashMap();
    names.put(Synonyms.ADJECTIVE + "", "Adjectives");
    names.put(Synonyms.NOUN + "", "Nouns");
    names.put(Synonyms.VERB + "", "Verbs");
    names.put(Synonyms.ADVERB + "", "Adverbs");
    names.put(Synonyms.OTHER + "", "Other");

    if (syns.words.size() == 0) {

      JLabel l = new JLabel("No synonyms found.");
      l.setFont(l.getFont().deriveFont(Font.ITALIC));

      pb.add(l, cc.xy(2, 2));
    }

    // Determine what type of word we are looking for.
    for (Synonyms.Part i : syns.words) {

      JLabel l = new JLabel(names.get(i.type + ""));

      l.setFont(l.getFont().deriveFont(Font.ITALIC));
      l.setFont(l.getFont().deriveFont((float) UIUtils.getEditorFontSize(10)));
      l.setBorder(
          new CompoundBorder(
              new MatteBorder(0, 0, 1, 0, Environment.getBorderColor()),
              new EmptyBorder(0, 0, 3, 0)));

      pb.add(l, cc.xy(2, ind));

      ind += 2;

      HTMLEditorKit kit = new HTMLEditorKit();
      HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();

      JTextPane t = new JTextPane(doc);
      t.setEditorKit(kit);
      t.setEditable(false);
      t.setOpaque(false);

      StringBuilder buf =
          new StringBuilder(
              "<style>a { text-decoration: none; } a:hover { text-decoration: underline; }</style><span style='color: #000000; font-size: "
                  + ((int) UIUtils.getEditorFontSize(10) /*t.getFont ().getSize () + 2*/)
                  + "pt; font-family: "
                  + t.getFont().getFontName()
                  + ";'>");

      for (int x = 0; x < i.words.size(); x++) {

        String w = (String) i.words.get(x);

        buf.append("<a class='x' href='http://" + w + "'>" + w + "</a>");

        if (x < (i.words.size() - 1)) {

          buf.append(", ");
        }
      }

      buf.append("</span>");

      t.setText(buf.toString());

      t.addHyperlinkListener(
          new HyperlinkAdapter() {

            public void hyperlinkUpdate(HyperlinkEvent ev) {

              if (ev.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {

                QTextEditor ed = _this.editorPanel.getEditor();

                ed.replaceText(
                    _this.position, _this.position + _this.word.length(), ev.getURL().getHost());

                ed.removeHighlight(_this.highlight);

                _this.popup.setVisible(false);

                _this.projectViewer.fireProjectEvent(
                    ProjectEvent.SYNONYM, ProjectEvent.REPLACE, ev.getURL().getHost());
              }
            }
          });

      // Annoying that we have to do this but it prevents the text from being too small.

      t.setSize(new Dimension(380, Short.MAX_VALUE));

      JScrollPane sp = new JScrollPane(t);

      t.setCaretPosition(0);

      sp.setOpaque(false);
      sp.getVerticalScrollBar().setValue(0);
      /*
                  sp.setPreferredSize (t.getPreferredSize ());
                  sp.setMaximumSize (new Dimension (380,
                                                    75));
      */
      sp.getViewport().setOpaque(false);
      sp.setOpaque(false);
      sp.setBorder(null);
      sp.getViewport().setBackground(Color.WHITE);
      sp.setAlignmentX(Component.LEFT_ALIGNMENT);

      pb.add(sp, cc.xy(2, ind));

      ind += 2;
    }

    JPanel pan = pb.getPanel();
    pan.setOpaque(true);
    pan.setBackground(Color.WHITE);

    this.popup.setContent(pan);

    // r.y -= this.editorPanel.getScrollPane ().getVerticalScrollBar ().getValue ();

    Point po = SwingUtilities.convertPoint(editor, r.x, r.y, this.editorPanel);

    r.x = po.x;
    r.y = po.y;

    // Subtract the insets of the editorPanel.
    Insets ins = this.editorPanel.getInsets();

    r.x -= ins.left;
    r.y -= ins.top;

    this.editorPanel.showPopupAt(this.popup, r, "above", true);
  }
  protected String doCalculateSignature(PsiMethod method) {
    final StringBuilder buffer = new StringBuilder();
    final PsiModifierList modifierList = method.getModifierList();
    String modifiers = modifierList.getText();
    final String oldModifier = VisibilityUtil.getVisibilityModifier(modifierList);
    final String newModifier = getVisibility();
    String newModifierStr = VisibilityUtil.getVisibilityString(newModifier);
    if (!newModifier.equals(oldModifier)) {
      int index = modifiers.indexOf(oldModifier);
      if (index >= 0) {
        final StringBuilder buf = new StringBuilder(modifiers);
        buf.replace(
            index,
            index + oldModifier.length() + ("".equals(newModifierStr) ? 1 : 0),
            newModifierStr);
        modifiers = buf.toString();
      } else {
        if (!StringUtil.isEmpty(newModifierStr)) {
          newModifierStr += " ";
        }
        modifiers = newModifierStr + modifiers;
      }
    }

    buffer.append(modifiers);
    if (modifiers.length() > 0
        && !StringUtil.endsWithChar(modifiers, '\n')
        && !StringUtil.endsWithChar(modifiers, '\r')
        && !StringUtil.endsWithChar(modifiers, ' ')) {
      buffer.append(" ");
    }

    if (!method.isConstructor()) {
      final CanonicalTypes.Type type = getReturnType();
      if (type != null) {
        buffer.append(type.getTypeText());
      }
      buffer.append(" ");
    }
    buffer.append(getMethodName());
    buffer.append("(");

    final int lineBreakIdx = buffer.lastIndexOf("\n");
    String indent =
        StringUtil.repeatSymbol(
            ' ', lineBreakIdx >= 0 ? buffer.length() - lineBreakIdx - 1 : buffer.length());
    List<ParameterTableModelItemBase<ParameterInfoImpl>> items = myParametersTableModel.getItems();
    int curIndent = indent.length();
    for (int i = 0; i < items.size(); i++) {
      final ParameterTableModelItemBase<ParameterInfoImpl> item = items.get(i);
      if (i > 0) {
        buffer.append(",");
        buffer.append("\n");
        buffer.append(indent);
      }
      final String text = item.typeCodeFragment.getText();
      buffer.append(text).append(" ");
      final String name = item.parameter.getName();
      buffer.append(name);
      curIndent = indent.length() + text.length() + 1 + name.length();
    }
    // if (!items.isEmpty()) {
    //  buffer.append("\n");
    // }
    buffer.append(")");
    PsiTypeCodeFragment[] thrownExceptionsFragments = myExceptionsModel.getTypeCodeFragments();
    if (thrownExceptionsFragments.length > 0) {
      // buffer.append("\n");
      buffer.append(" throws ");
      curIndent += 9; // ") throws ".length()
      indent = StringUtil.repeatSymbol(' ', curIndent);
      for (int i = 0; i < thrownExceptionsFragments.length; i++) {
        String text = thrownExceptionsFragments[i].getText();
        if (i != 0) buffer.append(indent);
        buffer.append(text);
        if (i < thrownExceptionsFragments.length - 1) {
          buffer.append(",");
        }
        buffer.append("\n");
      }
    }

    return buffer.toString();
  }
Esempio n. 20
0
  @SuppressWarnings({"StringConcatenationInsideStringBufferAppend"})
  private static String formatMessage(Exception e, Object message, Object[] args) {
    StringBuilder sb = new StringBuilder();

    if (message != null) sb.append(message.toString());

    if (e != null) sb.append((sb.length() > 0 ? "\n" : "") + e.toString());

    for (Object o : args) {
      if (o != null) sb.append((sb.length() > 0 ? "\n" : "") + o.toString());
    }

    return sb.toString();
  }
  void log(@NonNls String msg, Document document, boolean synchronously, @NonNls Object... args) {
    if (debug()) {
      @NonNls
      String s =
          (SwingUtilities.isEventDispatchThread() ? "-    " : "-")
              + msg
              + (synchronously ? " (sync)" : "")
              + (document == null
                  ? ""
                  : "; Document: "
                      + System.identityHashCode(document)
                      + "; stage: "
                      + getCommitStage(document))
              + "; my indic="
              + myProgressIndicator
              + " ||";

      for (Object arg : args) {
        s += "; " + arg;
      }
      System.out.println(s);
      synchronized (log) {
        log.append(s).append("\n");
        if (log.length() > 1000000) {
          log.delete(0, 1000000);
        }
      }
    }
  }
 private static String formatBuildTime(long seconds) {
   if (seconds == 0) {
     return "0s";
   }
   final StringBuilder sb = new StringBuilder();
   if (seconds >= 3600) {
     sb.append(seconds / 3600).append("h ");
     seconds %= 3600;
   }
   if (seconds >= 60 || sb.length() > 0) {
     sb.append(seconds / 60).append("m ");
     seconds %= 60;
   }
   if (seconds > 0 || sb.length() > 0) {
     sb.append(seconds).append("s");
   }
   return sb.toString();
 }
 private static void addPropertyPresentation(
     final SVNPropertyData property, final StringBuilder sb) {
   if (sb.length() != 0) {
     sb.append(ourPropertiesDelimiter);
   }
   sb.append(property.getName())
       .append("=")
       .append(
           (property.getValue() == null)
               ? ""
               : SVNPropertyValue.getPropertyAsString(property.getValue()));
 }
  private void runAction(final EvaluationContextImpl context, LocatableEvent event) {
    if (LOG_ENABLED || LOG_EXPRESSION_ENABLED) {
      final StringBuilder buf = StringBuilderSpinAllocator.alloc();
      try {
        if (LOG_ENABLED) {
          buf.append(getEventMessage(event));
          buf.append("\n");
        }
        final DebugProcessImpl debugProcess = context.getDebugProcess();
        final TextWithImports expressionToEvaluate = getLogMessage();
        if (LOG_EXPRESSION_ENABLED
            && expressionToEvaluate != null
            && !"".equals(expressionToEvaluate.getText())) {
          if (!debugProcess.isAttached()) {
            return;
          }

          try {
            ExpressionEvaluator evaluator =
                DebuggerInvocationUtil.commitAndRunReadAction(
                    getProject(),
                    new EvaluatingComputable<ExpressionEvaluator>() {
                      public ExpressionEvaluator compute() throws EvaluateException {
                        return EvaluatorBuilderImpl.build(
                            expressionToEvaluate,
                            ContextUtil.getContextElement(context),
                            ContextUtil.getSourcePosition(context));
                      }
                    });
            final Value eval = evaluator.evaluate(context);
            final String result =
                eval instanceof VoidValue ? "void" : DebuggerUtils.getValueAsString(context, eval);
            buf.append(result);
          } catch (EvaluateException e) {
            buf.append(DebuggerBundle.message("error.unable.to.evaluate.expression"));
            buf.append(" \"");
            buf.append(expressionToEvaluate);
            buf.append("\"");
            buf.append(" : ");
            buf.append(e.getMessage());
          }
          buf.append("\n");
        }
        if (buf.length() > 0) {
          debugProcess.printToConsole(buf.toString());
        }
      } finally {
        StringBuilderSpinAllocator.dispose(buf);
      }
    }
  }
 public void printToHistory(@NotNull final List<Pair<String, TextAttributes>> attributedText) {
   ApplicationManager.getApplication().assertIsDispatchThread();
   if (LOG.isDebugEnabled()) {
     LOG.debug("printToHistory(): " + attributedText.size());
   }
   final boolean scrollToEnd = shouldScrollHistoryToEnd();
   final int[] offsets = new int[attributedText.size() + 1];
   int i = 0;
   offsets[i] = 0;
   final StringBuilder sb = new StringBuilder();
   for (final Pair<String, TextAttributes> pair : attributedText) {
     sb.append(StringUtil.convertLineSeparators(pair.getFirst()));
     offsets[++i] = sb.length();
   }
   final DocumentEx history = myHistoryViewer.getDocument();
   final int oldHistoryLength = history.getTextLength();
   appendToHistoryDocument(history, sb.toString());
   assert oldHistoryLength + offsets[i] == history.getTextLength()
       : "unexpected history length "
           + oldHistoryLength
           + " "
           + offsets[i]
           + " "
           + history.getTextLength();
   LOG.debug("printToHistory(): text processed");
   final MarkupModel markupModel = DocumentMarkupModel.forDocument(history, myProject, true);
   i = 0;
   for (final Pair<String, TextAttributes> pair : attributedText) {
     markupModel.addRangeHighlighter(
         oldHistoryLength + offsets[i],
         oldHistoryLength + offsets[i + 1],
         HighlighterLayer.SYNTAX,
         pair.getSecond(),
         HighlighterTargetArea.EXACT_RANGE);
     ++i;
   }
   LOG.debug("printToHistory(): markup added");
   if (scrollToEnd) {
     scrollHistoryToEnd();
   }
   queueUiUpdate(scrollToEnd);
   LOG.debug("printToHistory(): completed");
 }
Esempio n. 26
0
  private static String getNodePathString(final MyNode node) {
    StringBuilder path = new StringBuilder();
    MyNode current = node;
    while (current != null) {
      final Object userObject = current.getUserObject();
      if (!(userObject instanceof NamedConfigurable)) break;
      final String displayName = current.getDisplayName();
      if (StringUtil.isEmptyOrSpaces(displayName)) break;
      if (path.length() > 0) {
        path.append('|');
      }
      path.append(displayName);

      final TreeNode parent = current.getParent();
      if (!(parent instanceof MyNode)) break;
      current = (MyNode) parent;
    }
    return path.toString();
  }
 public String getText(final VcsFileRevision value) {
   if (!(value instanceof SvnFileRevision)) return "";
   final SvnFileRevision revision = (SvnFileRevision) value;
   final List<SvnFileRevision> mergeSources = revision.getMergeSources();
   if (mergeSources.isEmpty()) {
     return "";
   }
   final StringBuilder sb = new StringBuilder();
   for (SvnFileRevision source : mergeSources) {
     if (sb.length() != 0) {
       sb.append(", ");
     }
     sb.append(source.getRevisionNumber().asString());
     if (!source.getMergeSources().isEmpty()) {
       sb.append("*");
     }
   }
   return sb.toString();
 }
  private static boolean askForClosingDebugSessions(@NotNull Project project) {
    final List<Pair<ProcessHandler, RunContentDescriptor>> pairs =
        new ArrayList<Pair<ProcessHandler, RunContentDescriptor>>();

    for (Project p : ProjectManager.getInstance().getOpenProjects()) {
      final ProcessHandler[] processes = ExecutionManager.getInstance(p).getRunningProcesses();

      for (ProcessHandler process : processes) {
        if (!process.isProcessTerminated()) {
          final AndroidSessionInfo info =
              process.getUserData(AndroidDebugRunner.ANDROID_SESSION_INFO);
          if (info != null) {
            pairs.add(Pair.create(process, info.getDescriptor()));
          }
        }
      }
    }

    if (pairs.size() == 0) {
      return true;
    }

    final StringBuilder s = new StringBuilder();

    for (Pair<ProcessHandler, RunContentDescriptor> pair : pairs) {
      if (s.length() > 0) {
        s.append('\n');
      }
      s.append(pair.getSecond().getDisplayName());
    }

    final int r =
        Messages.showYesNoDialog(
            project,
            AndroidBundle.message("android.debug.sessions.will.be.closed", s),
            AndroidBundle.message("android.disable.adb.service.title"),
            Messages.getQuestionIcon());
    return r == Messages.YES;
  }
  /** Updates all UI controls */
  private void updatePreviewAndConflicts() {
    if (myButton == -1 || myModifiers == -1) {
      return;
    }

    myTarConflicts.setText(null);

    // Set text into preview area

    // empty string should have same height
    myLblPreview.setText(
        KeymapUtil.getMouseShortcutText(myButton, myModifiers, myRbSingleClick.isSelected() ? 1 : 2)
            + " ");

    // Detect conflicts

    final MouseShortcut mouseShortcut;
    if (myRbSingleClick.isSelected()) {
      mouseShortcut = new MouseShortcut(myButton, myModifiers, 1);
    } else {
      mouseShortcut = new MouseShortcut(myButton, myModifiers, 2);
    }

    StringBuilder buffer = new StringBuilder();
    String[] actionIds = myKeymap.getActionIds(mouseShortcut);
    for (String actionId : actionIds) {
      if (actionId.equals(myActionId)) {
        continue;
      }

      String actionPath = myMainGroup.getActionQualifiedPath(actionId);
      // actionPath == null for editor actions having corresponding $-actions
      if (actionPath == null) {
        continue;
      }

      Shortcut[] shortcuts = myKeymap.getShortcuts(actionId);
      for (Shortcut shortcut1 : shortcuts) {
        if (!(shortcut1 instanceof MouseShortcut)) {
          continue;
        }

        MouseShortcut shortcut = (MouseShortcut) shortcut1;

        if (shortcut.getButton() != mouseShortcut.getButton()
            || shortcut.getModifiers() != mouseShortcut.getModifiers()) {
          continue;
        }

        if (buffer.length() > 1) {
          buffer.append('\n');
        }
        buffer.append('[');
        buffer.append(actionPath);
        buffer.append(']');
        break;
      }
    }

    if (buffer.length() == 0) {
      myTarConflicts.setForeground(UIUtil.getTextAreaForeground());
      myTarConflicts.setText(KeyMapBundle.message("mouse.shortcut.dialog.no.conflicts.area"));
    } else {
      myTarConflicts.setForeground(Color.red);
      myTarConflicts.setText(
          KeyMapBundle.message("mouse.shortcut.dialog.assigned.to.area", buffer.toString()));
    }
  }
  private static boolean userApprovesStopForIncompatibleConfigurations(
      Project project,
      String configName,
      List<RunContentDescriptor> runningIncompatibleDescriptors) {
    RunManagerImpl runManager = RunManagerImpl.getInstanceImpl(project);
    final RunManagerConfig config = runManager.getConfig();
    if (!config.isStopIncompatibleRequiresConfirmation()) return true;

    DialogWrapper.DoNotAskOption option =
        new DialogWrapper.DoNotAskOption() {
          @Override
          public boolean isToBeShown() {
            return config.isStopIncompatibleRequiresConfirmation();
          }

          @Override
          public void setToBeShown(boolean value, int exitCode) {
            config.setStopIncompatibleRequiresConfirmation(value);
          }

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

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

          @NotNull
          @Override
          public String getDoNotShowMessage() {
            return CommonBundle.message("dialog.options.do.not.show");
          }
        };

    final StringBuilder names = new StringBuilder();
    for (final RunContentDescriptor descriptor : runningIncompatibleDescriptors) {
      String name = descriptor.getDisplayName();
      if (names.length() > 0) {
        names.append(", ");
      }
      names.append(
          StringUtil.isEmpty(name)
              ? ExecutionBundle.message("run.configuration.no.name")
              : String.format("'%s'", name));
    }

    //noinspection DialogTitleCapitalization
    return Messages.showOkCancelDialog(
            project,
            ExecutionBundle.message(
                "stop.incompatible.confirmation.message",
                configName,
                names.toString(),
                runningIncompatibleDescriptors.size()),
            ExecutionBundle.message(
                "incompatible.configuration.is.running.dialog.title",
                runningIncompatibleDescriptors.size()),
            ExecutionBundle.message("stop.incompatible.confirmation.button.text"),
            CommonBundle.message("button.cancel"),
            Messages.getQuestionIcon(),
            option)
        == Messages.OK;
  }