// {{{ updatePluginList() method
  private void updatePluginList() {
    if (jEdit.getSettingsDirectory() == null && jEdit.getJEditHome() == null) {
      GUIUtilities.error(this, "no-settings", null);
      return;
    }
    if (!shouldUpdatePluginList()) {
      return;
    }

    ThreadUtilities.runInBackground(
        new Task() {
          @Override
          public void _run() {
            try {
              downloadingPluginList = true;
              setStatus(jEdit.getProperty("plugin-manager.list-download-connect"));
              pluginList = new PluginList(this);
            } finally {
              downloadingPluginList = false;
            }
            ThreadUtilities.runInDispatchThread(
                new Runnable() {
                  public void run() {
                    pluginListUpdated();
                  }
                });
          }
        });
  } // }}}
  /**
   * Called when en-/decrypt button or Enter key is pressed.
   *
   * <p>Encrypts or decrypts the given files with the given parameters.
   *
   * @see org.gjt.sp.jedit.gui.EnhancedDialog#ok()
   */
  @Override
  public void ok() {
    try {
      GUIUtilities.saveGeometry(this, "cipher.file-crypter");

      if (overwriteRadioButton.isSelected()) {
        newFileHandling = NewFileHandling.OVERWRITE;
      } else if (otherDirectoryRadioButton.isSelected()) {
        newFileHandling = NewFileHandling.OTHER_DIRECTORY;
      } else {
        newFileHandling = NewFileHandling.SUFFIX;
      }

      jEdit.setProperty("options.cipher.file-crypter.new-file-handling", newFileHandling.name());
      jEdit.setProperty("options.cipher.file-crypter.directory", directoryTextField.getText());
      jEdit.setProperty("options.cipher.file-crypter.suffix", suffixTextField.getText());
      jEdit.propertiesChanged();
      jEdit.saveSettings();

      cipher = CipherPlugin.getCipher(cipherOptionPane.getCipherName());
      if (null == cipher) {
        return;
      }
      additionalInformation = CipherPlugin.getAdditionalInformation(cipher);
      if (null == additionalInformation) {
        return;
      }
      PasswordDialog passwordDialog = PasswordDialog.newInstance();
      password = passwordDialog.getPassword();
      if (null == password) {
        return;
      }

      if (!cryptFiles("", files)) {
        GUIUtilities.error(
            this,
            encrypt
                ? "cipher.error.error-while-encrypting-files"
                : "cipher.error.error-while-decrypting-files",
            null);
      }
    } finally {
      dispose();
    }
  }
  public static void error(final Component comp, final String error, final Object[] args) {

    if (SwingUtilities.isEventDispatchThread()) {
      GUIUtilities.error(comp, error, args);
      return;
    }

    VFSManager.error = true;

    runInAWTThread(
        new Runnable() {
          public void run() {
            VFSManager.error = false;

            if (comp == null || !comp.isShowing()) GUIUtilities.error(null, error, args);
            else GUIUtilities.error(comp, error, args);
          }
        });
  }
  /**
   * Recursively encrypts or decrypts all files given to the method and all files in directories
   * given to the method.
   *
   * @param relativePath The relative from the initial directory up to the current one, for
   *     encryption or decryption into another directory to be able to rebuild the directory
   *     structure
   * @param files The files and directories to encrypt or decrypt
   * @return Whether all encryption or decryption was fine
   */
  @CheckReturnValue(explanation = "If false is returned, something went wrong")
  private boolean cryptFiles(@NonNull String relativePath, @NonNull VFSFile... files) {
    for (VFSFile file : files) {
      VFS vfs = file.getVFS();
      VFS newVfs = null;
      String path = file.getPath();
      Object session = vfs.createVFSSession(path, this);
      Object sessionNew = null;
      Object sessionNewParent = null;
      InputStream in = null;
      ByteArrayInputStream bais = null;
      OutputStream out = null;
      ByteArrayOutputStream baos = null;
      try {
        if (FILE == file.getType()) {
          in = vfs._createInputStream(session, path, false, this);
          baos = new ByteArrayOutputStream();
          if (!IOUtilities.copyStream(null, in, baos, false)) {
            GUIUtilities.error(
                this,
                encrypt
                    ? "cipher.error.error-while-encrypting-file"
                    : "cipher.error.error-while-decrypting-file",
                new Object[] {path});
            continue;
          }
          baos.flush();
          byte[] cryptResult;
          synchronized (cipher) {
            if (encrypt) {
              cipher.setRawData(baos.toByteArray());
            } else {
              cipher.setEncryptedData(baos.toByteArray());
            }
            cipher.setEntropy(password);
            cipher.setAdditionalInformation(additionalInformation);
            if (encrypt) {
              cryptResult = cipher.encryptToByteArray();
            } else {
              cryptResult = cipher.decryptToByteArray();
            }
          }
          if (null == cryptResult) {
            GUIUtilities.error(
                this,
                encrypt
                    ? "cipher.error.error-while-encrypting-file"
                    : "cipher.error.error-while-decrypting-file",
                new Object[] {path});
            continue;
          }
          bais = new ByteArrayInputStream(cryptResult);
          String newPath;
          switch (newFileHandling) {
            case OVERWRITE:
              newPath = path;
              newVfs = vfs;
              break;

            case OTHER_DIRECTORY:
              if (0 < relativePath.length()) {
                newPath = MiscUtilities.constructPath(directoryTextField.getText(), relativePath);
              } else {
                newPath = directoryTextField.getText();
              }
              newPath = MiscUtilities.constructPath(newPath, file.getName());
              newVfs = VFSManager.getVFSForPath(newPath);
              break;

            case SUFFIX:
              newPath = path + suffixTextField.getText();
              newVfs = vfs;
              break;

            default:
              throw new InternalError(
                  "missing case branch for NewFileHandling: " + newFileHandling);
          }
          String newPathParent = MiscUtilities.getParentOfPath(newPath);
          sessionNewParent = newVfs.createVFSSession(newPathParent, this);
          newVfs._mkdir(sessionNewParent, newPathParent, this);
          sessionNew = newVfs.createVFSSession(newPath, this);
          out = newVfs._createOutputStream(sessionNew, newPath, this);
          if (!IOUtilities.copyStream(null, bais, out, false)) {
            GUIUtilities.error(
                this,
                encrypt
                    ? "cipher.error.error-while-encrypting-file"
                    : "cipher.error.error-while-decrypting-file",
                new Object[] {path});
            continue;
          }
          VFSManager.sendVFSUpdate(newVfs, newPath, true);
        } else {
          String newRelativePath;
          if (0 < relativePath.length()) {
            newRelativePath = MiscUtilities.concatPath(relativePath, file.getName());
          } else {
            newRelativePath = file.getName();
          }
          if (!cryptFiles(newRelativePath, vfs._listFiles(session, path, this))) {
            return false;
          }
        }
      } catch (IOException ioe) {
        Log.log(ERROR, this, ioe);
        new TextAreaDialog(
            this,
            encrypt
                ? "cipher.error.error-while-encrypting-files"
                : "cipher.error.error-while-decrypting-files",
            ioe);
        return false;
      } finally {
        try {
          vfs._endVFSSession(session, this);
        } catch (IOException ioe) {
          // just ignore it, we are not interested
        }
        try {
          if (null != newVfs) {
            newVfs._endVFSSession(sessionNew, this);
          }
        } catch (IOException ioe) {
          // just ignore it, we are not interested
        }
        try {
          if (null != newVfs) {
            newVfs._endVFSSession(sessionNewParent, this);
          }
        } catch (IOException ioe) {
          // just ignore it, we are not interested
        }
        try {
          if (null != out) {
            out.flush();
          }
        } catch (IOException ioe) {
          // just ignore it, we are not interested
        }
        IOUtilities.closeQuietly(in);
        IOUtilities.closeQuietly(bais);
        IOUtilities.closeQuietly(out);
        IOUtilities.closeQuietly(baos);
      }
    }
    return true;
  }
Exemple #5
0
  /**
   * Displays the specified URL in the HTML component.
   *
   * @param url The URL
   * @param addToHistory Should the URL be added to the back/forward history?
   * @param scrollPosition The vertical scrollPosition
   */
  public void gotoURL(String url, boolean addToHistory, final int scrollPosition) {
    // the TOC pane looks up user's guide URLs relative to the
    // doc directory...
    String shortURL;
    if (MiscUtilities.isURL(url)) {
      if (url.startsWith(baseURL)) {
        shortURL = url.substring(baseURL.length());
        if (shortURL.startsWith("/")) {
          shortURL = shortURL.substring(1);
        }
      } else {
        shortURL = url;
      }
    } else {
      shortURL = url;
      if (baseURL.endsWith("/")) {
        url = baseURL + url;
      } else {
        url = baseURL + '/' + url;
      }
    }

    // reset default cursor so that the hand cursor doesn't
    // stick around
    viewer.setCursor(Cursor.getDefaultCursor());

    try {
      URL _url = new URL(url);

      if (!_url.equals(viewer.getPage())) {
        title.setText(jEdit.getProperty("helpviewer.loading"));
      } else {
        /* don't show loading msg because we won't
        receive a propertyChanged */
      }

      historyModel.setCurrentScrollPosition(viewer.getPage(), getCurrentScrollPosition());
      viewer.setPage(_url);
      if (0 != scrollPosition) {
        SwingUtilities.invokeLater(
            new Runnable() {
              public void run() {
                viewerScrollPane.getVerticalScrollBar().setValue(scrollPosition);
              }
            });
      }
      if (addToHistory) {
        historyModel.addToHistory(url);
      }
    } catch (MalformedURLException mf) {
      Log.log(Log.ERROR, this, mf);
      String[] args = {url, mf.getMessage()};
      GUIUtilities.error(this, "badurl", args);
      return;
    } catch (IOException io) {
      Log.log(Log.ERROR, this, io);
      String[] args = {url, io.toString()};
      GUIUtilities.error(this, "read-error", args);
      return;
    }

    this.shortURL = shortURL;

    // select the appropriate tree node.
    if (shortURL != null) {
      toc.selectNode(shortURL);
    }

    viewer.requestFocus();
  } // }}}
  /**
   * Replaces all occurrences of the search string with the replacement string.
   *
   * @param view The view
   * @param dontOpenChangedFiles Whether to open changed files or to autosave them quietly
   * @return the number of modified files
   */
  public static boolean replaceAll(View view, boolean dontOpenChangedFiles) {
    // component that will parent any dialog boxes
    Component comp = SearchDialog.getSearchDialog(view);
    if (comp == null) comp = view;

    if (fileset.getFileCount(view) == 0) {
      GUIUtilities.error(comp, "empty-fileset", null);
      return false;
    }

    record(view, "replaceAll(view)", true, true);

    view.showWaitCursor();

    boolean smartCaseReplace = getSmartCaseReplace();

    int fileCount = 0;
    int occurCount = 0;
    try {
      SearchMatcher matcher = getSearchMatcher();
      if (matcher == null) return false;

      initReplace();

      String path = fileset.getFirstFile(view);
      loop:
      while (path != null) {
        Buffer buffer = jEdit.openTemporary(view, null, path, false);

        /* this is stupid and misleading.
         * but 'path' is not used anywhere except
         * the above line, and if this is done
         * after the 'continue', then we will
         * either hang, or be forced to duplicate
         * it inside the buffer == null, or add
         * a 'finally' clause. you decide which one's
         * worse. */
        path = fileset.getNextFile(view, path);

        if (buffer == null) continue loop;

        // Wait for buffer to finish loading
        if (buffer.isPerformingIO()) VFSManager.waitForRequests();

        if (!buffer.isEditable()) continue loop;

        // Leave buffer in a consistent state if
        // an error occurs
        int retVal = 0;

        try {
          buffer.beginCompoundEdit();
          retVal = _replace(view, buffer, matcher, 0, buffer.getLength(), smartCaseReplace);
        } finally {
          buffer.endCompoundEdit();
        }

        if (retVal != 0) {
          fileCount++;
          occurCount += retVal;
          if (dontOpenChangedFiles) {
            buffer.save(null, null);
          } else {
            jEdit.commitTemporary(buffer);
            jEdit.getBufferSetManager().addBuffer(view, buffer);
          }
        }
      }
    } catch (Exception e) {
      handleError(comp, e);
    } finally {
      view.hideWaitCursor();
    }

    /* Don't do this when playing a macro, cos it's annoying */
    if (!BeanShell.isScriptRunning()) {
      Object[] args = {Integer.valueOf(occurCount), Integer.valueOf(fileCount)};
      view.getStatus().setMessageAndClear(jEdit.getProperty("view.status.replace-all", args));
      if (occurCount == 0) view.getToolkit().beep();
    }

    return (fileCount != 0);
  } // }}}
  /**
   * Finds the next occurrence of the search string.
   *
   * @param view The view
   * @return True if the operation was successful, false otherwise
   */
  public static boolean find(View view) {
    // component that will parent any dialog boxes
    Component comp = SearchDialog.getSearchDialog(view);
    if (comp == null || !comp.isShowing()) comp = view;

    String path = fileset.getNextFile(view, null);
    if (path == null) {
      GUIUtilities.error(comp, "empty-fileset", null);
      return false;
    }

    try {
      view.showWaitCursor();

      SearchMatcher matcher = getSearchMatcher();
      if (matcher == null) {
        view.getToolkit().beep();
        return false;
      }

      record(view, "find(view)", false, true);

      boolean repeat = false;
      loop:
      for (; ; ) {
        while (path != null) {
          Buffer buffer = jEdit.openTemporary(view, null, path, false);

          /* this is stupid and misleading.
           * but 'path' is not used anywhere except
           * the above line, and if this is done
           * after the 'continue', then we will
           * either hang, or be forced to duplicate
           * it inside the buffer == null, or add
           * a 'finally' clause. you decide which one's
           * worse. */
          if (reverse) {
            path = fileset.getPrevFile(view, path);
          } else {
            path = fileset.getNextFile(view, path);
          }

          if (buffer == null) continue loop;

          // Wait for the buffer to load
          if (!buffer.isLoaded()) VFSManager.waitForRequests();

          int start;

          if (view.getBuffer() == buffer && !repeat) {
            JEditTextArea textArea = view.getTextArea();
            Selection s = textArea.getSelectionAtOffset(textArea.getCaretPosition());
            if (s == null) start = textArea.getCaretPosition();
            else if (reverse) start = s.getStart();
            else start = s.getEnd();
          } else if (reverse) start = buffer.getLength();
          else start = 0;

          if (find(view, buffer, start, repeat, reverse)) return true;
        }

        if (repeat) {
          if (!BeanShell.isScriptRunning()) {
            view.getStatus().setMessageAndClear(jEdit.getProperty("view.status.search-not-found"));

            view.getToolkit().beep();
          }
          return false;
        }

        boolean restart;

        // if auto wrap is on, always restart search.
        // if auto wrap is off, and we're called from
        // a macro, stop search. If we're called
        // interactively, ask the user what to do.
        if (wrap) {
          if (!BeanShell.isScriptRunning()) {
            view.getStatus().setMessageAndClear(jEdit.getProperty("view.status.auto-wrap"));
            // beep if beep property set
            if (jEdit.getBooleanProperty("search.beepOnSearchAutoWrap")) {
              view.getToolkit().beep();
            }
          }
          restart = true;
        } else if (BeanShell.isScriptRunning()) {
          restart = false;
        } else {
          Integer[] args = {Integer.valueOf(reverse ? 1 : 0)};
          int result =
              GUIUtilities.confirm(
                  comp,
                  "keepsearching",
                  args,
                  JOptionPane.YES_NO_OPTION,
                  JOptionPane.QUESTION_MESSAGE);
          restart = (result == JOptionPane.YES_OPTION);
        }

        if (restart) {
          // start search from beginning
          path = fileset.getFirstFile(view);
          repeat = true;
        } else break loop;
      }
    } catch (Exception e) {
      handleError(comp, e);
    } finally {
      view.hideWaitCursor();
    }

    return false;
  } // }}}