Exemplo n.º 1
0
  /**
   * @return the clipboard content as a String (DataFlavor.stringFlavor) Code snippet adapted from
   *     jEdit (Registers.java), http://www.jedit.org. Returns null if clipboard is empty.
   */
  public static String getClipboardStringContent(Clipboard clipboard) {
    // Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    try {
      String selection =
          (String) (clipboard.getContents(null).getTransferData(DataFlavor.stringFlavor));
      if (selection == null) return null;

      boolean trailingEOL =
          (selection.endsWith("\n") || selection.endsWith(System.getProperty("line.separator")));

      // Some Java versions return the clipboard contents using the native line separator,
      // so have to convert it here , see jEdit's "registers.java"
      BufferedReader in = new BufferedReader(new StringReader(selection));
      StringBuffer buf = new StringBuffer();
      String line;
      while ((line = in.readLine()) != null) {
        buf.append(line);
        buf.append('\n');
      }
      // remove trailing \n
      if (!trailingEOL) buf.setLength(buf.length() - 1);
      return buf.toString();
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
Exemplo n.º 2
0
  /**
   * Return the number of characters that will be printed when the specified character is echoed to
   * the screen. Adapted from cat by Torbjorn Granlund, as repeated in stty by David MacKenzie.
   */
  StringBuffer getPrintableCharacters(char ch) {
    StringBuffer sbuff = new StringBuffer();

    if (ch >= 32) {
      if (ch < 127) {
        sbuff.append(ch);
      } else if (ch == 127) {
        sbuff.append('^');
        sbuff.append('?');
      } else {
        sbuff.append('M');
        sbuff.append('-');

        if (ch >= (128 + 32)) {
          if (ch < (128 + 127)) {
            sbuff.append((char) (ch - 128));
          } else {
            sbuff.append('^');
            sbuff.append('?');
          }
        } else {
          sbuff.append('^');
          sbuff.append((char) (ch - 128 + 64));
        }
      }
    } else {
      sbuff.append('^');
      sbuff.append((char) (ch + 64));
    }

    return sbuff;
  }
Exemplo n.º 3
0
    /**
     * Create a Transferable to use as the source for a data transfer.
     *
     * @param c The component holding the data to be transfered. This argument is provided to enable
     *     sharing of TransferHandlers by multiple components.
     * @return The representation of the data to be transfered.
     */
    protected Transferable createTransferable(JComponent c) {
      Object[] values = null;
      if (c instanceof JList) {
        values = ((JList) c).getSelectedValues();
      } else if (c instanceof JTable) {
        JTable table = (JTable) c;
        int[] rows = table.getSelectedRows();
        if (rows != null) {
          values = new Object[rows.length];
          for (int i = 0; i < rows.length; i++) {
            values[i] = table.getValueAt(rows[i], 0);
          }
        }
      }
      if (values == null || values.length == 0) {
        return null;
      }

      StringBuffer plainBuf = new StringBuffer();
      StringBuffer htmlBuf = new StringBuffer();

      htmlBuf.append("<html>\n<body>\n<ul>\n");

      for (Object obj : values) {
        String val = ((obj == null) ? "" : obj.toString());
        plainBuf.append(val + "\n");
        htmlBuf.append("  <li>" + val + "\n");
      }

      // remove the last newline
      plainBuf.deleteCharAt(plainBuf.length() - 1);
      htmlBuf.append("</ul>\n</body>\n</html>");

      return new FileTransferable(plainBuf.toString(), htmlBuf.toString(), values);
    }
Exemplo n.º 4
0
 public String getStringreprasentation() {
   StringBuffer sb = new StringBuffer();
   Vector<RowContainer> vec = getFilevector();
   for (RowContainer c : vec) {
     sb.append(c.getFile().getAbsolutePath()).append('\n');
   }
   return sb.toString();
 }
Exemplo n.º 5
0
 private String bigIntToHexString(BigInteger bi) {
   StringBuffer buf = new StringBuffer();
   buf.append("0x");
   String val = bi.toString(16);
   for (int i = 0; i < ((2 * addressSize) - val.length()); i++) {
     buf.append('0');
   }
   buf.append(val);
   return buf.toString();
 }
Exemplo n.º 6
0
 public String getSelectionText() {
   RenderablePoint start = this.startSelection;
   RenderablePoint end = this.endSelection;
   if (start != null && end != null) {
     StringBuffer buffer = new StringBuffer();
     this.rblock.extractSelectionText(buffer, false, start, end);
     return buffer.toString();
   } else {
     return null;
   }
 }
Exemplo n.º 7
0
 /**
  * This method is activated on the Keystrokes we are listening to in this implementation. Here it
  * listens for Copy and Paste ActionCommands. Selections comprising non-adjacent cells result in
  * invalid selection and then copy action cannot be performed. Paste is done by aligning the upper
  * left corner of the selection with the 1st element in the current selection of the JTable.
  */
 public void actionPerformed(ActionEvent e) {
   if (e.getActionCommand().compareTo("Copy") == 0) {
     StringBuffer sbf = new StringBuffer();
     // Check to ensure we have selected only a contiguous block of
     // cells
     int numcols = jTable1.getSelectedColumnCount();
     int numrows = jTable1.getSelectedRowCount();
     int[] rowsselected = jTable1.getSelectedRows();
     int[] colsselected = jTable1.getSelectedColumns();
     if (!((numrows - 1 == rowsselected[rowsselected.length - 1] - rowsselected[0]
             && numrows == rowsselected.length)
         && (numcols - 1 == colsselected[colsselected.length - 1] - colsselected[0]
             && numcols == colsselected.length))) {
       JOptionPane.showMessageDialog(
           null, "Invalid Copy Selection", "Invalid Copy Selection", JOptionPane.ERROR_MESSAGE);
       return;
     }
     for (int i = 0; i < numrows; i++) {
       for (int j = 0; j < numcols; j++) {
         sbf.append(jTable1.getValueAt(rowsselected[i], colsselected[j]));
         if (j < numcols - 1) sbf.append("\t");
       }
       sbf.append("\n");
     }
     stsel = new StringSelection(sbf.toString());
     system = Toolkit.getDefaultToolkit().getSystemClipboard();
     system.setContents(stsel, stsel);
   }
   if (e.getActionCommand().compareTo("Paste") == 0) {
     System.out.println("Trying to Paste");
     int startRow = (jTable1.getSelectedRows())[0];
     int startCol = (jTable1.getSelectedColumns())[0];
     try {
       String trstring =
           (String) (system.getContents(this).getTransferData(DataFlavor.stringFlavor));
       System.out.println("String is:" + trstring);
       StringTokenizer st1 = new StringTokenizer(trstring, "\n");
       for (int i = 0; st1.hasMoreTokens(); i++) {
         rowstring = st1.nextToken();
         StringTokenizer st2 = new StringTokenizer(rowstring, "\t");
         for (int j = 0; st2.hasMoreTokens(); j++) {
           value = (String) st2.nextToken();
           if (startRow + i < jTable1.getRowCount() && startCol + j < jTable1.getColumnCount())
             jTable1.setValueAt(value, startRow + i, startCol + j);
           System.out.println(
               "Putting " + value + "at row = " + startRow + i + "column = " + startCol + j);
         }
       }
     } catch (Exception ex) {
       ex.printStackTrace();
     }
   }
 }
Exemplo n.º 8
0
  /** Places the selected text into the clipboard. */
  public void copy() {
    if (selectionStart != selectionEnd) {
      Clipboard clipboard = getToolkit().getSystemClipboard();

      String selection = getSelectedText();

      int repeatCount = inputHandler.getRepeatCount();
      StringBuffer buf = new StringBuffer();
      for (int i = 0; i < repeatCount; i++) buf.append(selection);

      clipboard.setContents(new StringSelection(buf.toString()), null);
    }
  }
Exemplo n.º 9
0
  /** Import the given stream data into the text component. */
  protected void handleReaderImport(Reader in, JTextComponent c)
      throws BadLocationException, IOException {

    char[] buff = new char[1024];
    int nch;
    boolean lastWasCR = false;
    int last;
    StringBuffer sbuff = null;

    // Read in a block at a time, mapping \r\n to \n, as well as single
    // \r to \n.
    while ((nch = in.read(buff, 0, buff.length)) != -1) {

      if (sbuff == null) {
        sbuff = new StringBuffer(nch);
      }
      last = 0;

      for (int counter = 0; counter < nch; counter++) {

        switch (buff[counter]) {
          case '\r':
            if (lastWasCR) {
              if (counter == 0) sbuff.append('\n');
              else buff[counter - 1] = '\n';
            } else lastWasCR = true;
            break;
          case '\n':
            if (lastWasCR) {
              if (counter > (last + 1)) sbuff.append(buff, last, counter - last - 1);
              // else nothing to do, can skip \r, next write will
              // write \n
              lastWasCR = false;
              last = counter;
            }
            break;
          default:
            if (lastWasCR) {
              if (counter == 0) sbuff.append('\n');
              else buff[counter - 1] = '\n';
              lastWasCR = false;
            }
            break;
        } // End fo switch (buff[counter]).
      } // End of for (int counter = 0; counter < nch; counter++).

      if (last < nch) {
        if (lastWasCR) {
          if (last < (nch - 1)) sbuff.append(buff, last, nch - last - 1);
        } else sbuff.append(buff, last, nch - last);
      }
    } // End of while ((nch = in.read(buff, 0, buff.length)) != -1).

    if (withinSameComponent) {
      ((RTextArea) c).beginAtomicEdit();
    }

    if (lastWasCR) sbuff.append('\n');
    c.replaceSelection(sbuff != null ? sbuff.toString() : "");
  }
Exemplo n.º 10
0
  /**
   * format a given Font to a string, following "Font.decode()" format, ie fontname-style-pointsize,
   * fontname-pointsize, fontname-style or fontname, where style is one of "BOLD", "ITALIC",
   * "BOLDITALIC" (default being PLAIN)
   */
  public static String formatFontAsProperties(Font font) {
    // jpicedt.Log.debug(new MiscUtilities(),"formatFontAsProperties","font="+font);
    String family = font.getFamily();
    /*
    System.out.println("family="+family);
    String faceName = font.getFontName();
    System.out.println("faceName="+faceName);
    String logicalName = font.getName();
    System.out.println("logicalName"+logicalName);
    String psName = font.getPSName();
    System.out.println("PSName="+psName);
    */

    StringBuffer buf = new StringBuffer(20);
    buf.append(family);
    buf.append("-");
    switch (font.getStyle()) {
      case Font.ITALIC:
        buf.append("ITALIC-");
        break;
      case Font.BOLD:
        buf.append("BOLD-");
        break;
      case Font.BOLD | Font.ITALIC:
        buf.append("BOLDITALIC-");
        break;
      default: // PLAIN -> nothing
    }
    buf.append(Integer.toString(font.getSize()));
    return buf.toString();
  }
Exemplo n.º 11
0
  private String readLine(InputStream in) throws IOException {
    StringBuffer buf = new StringBuffer();

    while (true) {
      int i = in.read();

      if ((i == -1) || (i == '\n') || (i == '\r')) {
        return buf.toString();
      }

      buf.append((char) i);
    }

    // return new BufferedReader (new InputStreamReader (in)).readLine ();
  }
Exemplo n.º 12
0
 public synchronized void insertChar(char c) {
   if (c == KeyEvent.CHAR_UNDEFINED) return;
   if (selectionActivated) deleteSelection();
   text.insert(getCaretLocation().toIndex(getLines()), c);
   clearCache();
   setCaretLocation(getCaretLocation().moved(getLines(), 1));
 }
Exemplo n.º 13
0
  public TextLocation findWordsRightEdge(TextLocation location) {

    for (int i = location.toIndex(getLines()); i <= text.length() - 1; i++) {
      if (i == 0) i = 1;
      if (isAtEndOfWord(i)) return TextLocation.fromIndex(getLines(), i);
    }
    return getEndLocation();
  }
Exemplo n.º 14
0
  public String getSelectedText() {
    if (!hasSelection()) return "";

    int startIndex = getSelectionStart().toIndex(getLines());
    int endIndex = getSelectionEnd().toIndex(getLines());

    return text.substring(startIndex, endIndex);
  }
Exemplo n.º 15
0
  public synchronized void setText(String newText) {
    if (newText == null) newText = "";

    if (newText.length() == text.length() && newText.equals(getText())) return;

    text = new StringBuffer(newText);
    clearCache();
    setCaretLocation(getEndLocation());
  }
Exemplo n.º 16
0
 public void pasteClipboard() {
   String clipboard = getClipboardContents();
   if (clipboard != null && clipboard.length() > 0) {
     int caretIndex = caretLocation.toIndex(getLines());
     synchronized (this) {
       text.insert(caretIndex, clipboard);
       clearCache();
     }
     setCaretLocation(TextLocation.fromIndex(getLines(), caretIndex + clipboard.length()));
   }
 }
Exemplo n.º 17
0
 public void deleteEnclosedText(TextLocation start, TextLocation end) {
   ArrayList<TypedLayout> lines = getLines();
   int startIndex = start.toIndex(lines);
   int endIndex = end.toIndex(lines);
   synchronized (this) {
     text.delete(startIndex, endIndex);
     clearCache();
   }
   setCaretLocation(start);
   setSelectionLocation(start);
 }
Exemplo n.º 18
0
  /** Returns the selected text, or null if no selection is active. */
  public final String getSelectedText() {
    if (selectionStart == selectionEnd) return null;

    if (rectSelect) {
      // Return each row of the selection on a new line

      Element map = document.getDefaultRootElement();

      int start = selectionStart - map.getElement(selectionStartLine).getStartOffset();
      int end = selectionEnd - map.getElement(selectionEndLine).getStartOffset();

      // Certain rectangles satisfy this condition...
      if (end < start) {
        int tmp = end;
        end = start;
        start = tmp;
      }

      StringBuffer buf = new StringBuffer();
      Segment seg = new Segment();

      for (int i = selectionStartLine; i <= selectionEndLine; i++) {
        Element lineElement = map.getElement(i);
        int lineStart = lineElement.getStartOffset();
        int lineEnd = lineElement.getEndOffset() - 1;
        int lineLen = lineEnd - lineStart;

        lineStart = Math.min(lineStart + start, lineEnd);
        lineLen = Math.min(end - start, lineEnd - lineStart);

        getText(lineStart, lineLen, seg);
        buf.append(seg.array, seg.offset, seg.count);

        if (i != selectionEndLine) buf.append('\n');
      }

      return buf.toString();
    } else {
      return getText(selectionStart, selectionEnd - selectionStart);
    }
  }
Exemplo n.º 19
0
  /** Inserts the clipboard contents into the text. */
  public void paste() {
    if (editable) {
      Clipboard clipboard = getToolkit().getSystemClipboard();
      try {
        // The MacOS MRJ doesn't convert \r to \n,
        // so do it here
        String selection =
            ((String) clipboard.getContents(this).getTransferData(DataFlavor.stringFlavor))
                .replace('\r', '\n');

        int repeatCount = inputHandler.getRepeatCount();
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < repeatCount; i++) buf.append(selection);
        selection = buf.toString();
        setSelectedText(selection);
      } catch (Exception e) {
        getToolkit().beep();
        System.err.println("Clipboard does not" + " contain a string");
      }
    }
  }
Exemplo n.º 20
0
  private StringBuffer getDataFromReader(Reader br) {
    StringBuffer xferData = null;
    char[] buf = new char[513];
    int charsRead;

    try {
      do {
        charsRead = br.read(buf, 0, 512);
        if (charsRead != -1) {
          JConfig.log().logVerboseDebug("Read: " + charsRead + " characters.");
          if (xferData == null) {
            xferData = new StringBuffer();
          }
          xferData.append(buf, 0, charsRead);
        }
      } while (charsRead != -1);
      br.close();
    } catch (IOException e) {
      JConfig.log().logDebug("Caught an IO Exception trying to read the drag/drop data!");
      return null;
    }

    return xferData;
  }
Exemplo n.º 21
0
  /**
   * Output the specified {@link Collection} in proper columns.
   *
   * @param stuff the stuff to print
   */
  public void printColumns(final Collection stuff) throws IOException {
    if ((stuff == null) || (stuff.size() == 0)) {
      return;
    }

    int width = getTermwidth();
    int maxwidth = 0;

    for (Iterator i = stuff.iterator();
        i.hasNext();
        maxwidth = Math.max(maxwidth, i.next().toString().length())) {;
    }

    StringBuffer line = new StringBuffer();

    int showLines;

    if (usePagination) showLines = getTermheight() - 1; // page limit
    else showLines = Integer.MAX_VALUE;

    for (Iterator i = stuff.iterator(); i.hasNext(); ) {
      String cur = (String) i.next();

      if ((line.length() + maxwidth) > width) {
        printString(line.toString().trim());
        printNewline();
        line.setLength(0);
        if (--showLines == 0) { // Overflow
          printString(loc.getString("display-more"));
          flushConsole();
          int c = readVirtualKey();
          if (c == '\r' || c == '\n') showLines = 1; // one step forward
          else if (c != 'q') showLines = getTermheight() - 1; // page forward

          back(loc.getString("display-more").length());
          if (c == 'q') break; // cancel
        }
      }

      pad(cur, maxwidth + 3, line);
    }

    if (line.length() > 0) {
      printString(line.toString().trim());
      printNewline();
      line.setLength(0);
    }
  }
Exemplo n.º 22
0
  /**
   * Append <i>toPad</i> to the specified <i>appendTo</i>, as well as (<i>toPad.length () - len</i>)
   * spaces.
   *
   * @param toPad the {@link String} to pad
   * @param len the target length
   * @param appendTo the {@link StringBuffer} to which to append the padded {@link String}.
   */
  private final void pad(final String toPad, final int len, final StringBuffer appendTo) {
    appendTo.append(toPad);

    for (int i = 0; i < (len - toPad.length()); i++, appendTo.append(' ')) {;
    }
  }
Exemplo n.º 23
0
 public boolean isAtEndOfWord(int i) {
   return text.charAt(i - 1) != ' '
       && text.charAt(i - 1) != '\n'
       && (text.charAt(i) == ' ' || text.charAt(i) == '\n');
 }
Exemplo n.º 24
0
 public boolean isAtStartOfWord(int i) {
   if (i < 0 || i > getText().length()) return true;
   return (text.charAt(i - 1) == ' ' || text.charAt(i - 1) == '\n')
       && (text.charAt(i) != ' ' && text.charAt(i) != '\n');
 }
Exemplo n.º 25
0
 public String getText() {
   return text.toString();
 }
Exemplo n.º 26
0
 private String fixLinuxString(String s) {
   StringBuffer sb = new StringBuffer(200);
   for (int i = 0; i < s.length(); i += 2) sb.append(s.charAt(i));
   return new String(sb);
 }
Exemplo n.º 27
0
 protected TextLocation findNextWordSkippingSpacesOrNewLines(TextLocation startLocation) {
   for (int i = startLocation.toIndex(getLines()); i <= text.length() - 1; i++) {
     if (isAtStartOfWord(i)) return TextLocation.fromIndex(getLines(), i);
   }
   return getEndLocation();
 }
Exemplo n.º 28
0
 public TextLocation getEndLocation() {
   return TextLocation.fromIndex(getLines(), text.length());
 }