Esempio n. 1
0
  // {{{ getTargetName() method
  private String getTargetName(Object session, VFS vfs, String path, String baseName)
      throws IOException {
    if (behavior == Behavior.OVERWRITE) {
      // We want to overwrite, no need to check anything
      return baseName;
    }

    String s = MiscUtilities.constructPath(target, baseName);
    VFSFile file = vfs._getFile(session, s, comp);
    if (file == null) {
      // The target file do not exist, perfect
      return baseName;
    }
    if (behavior == Behavior.SKIP) return null;

    String extension = MiscUtilities.getFileExtension(baseName);
    String nameNoExtension = MiscUtilities.getBaseName(baseName);
    for (int i = 1; i < 1000; i++) {
      String name = nameNoExtension + "-copy-" + i;
      if (extension != null) name += extension;
      s = MiscUtilities.constructPath(path, name);
      file = vfs._getFile(session, s, comp);
      if (file == null) return name;
    }
    return null;
  } // }}}
Esempio n. 2
0
    @Override
    public void actionPerformed(ActionEvent evt) {
      if (pluginModel.isDownloadingList()) return;

      boolean downloadSource = jEdit.getBooleanProperty("plugin-manager.downloadSource");
      boolean installUser = jEdit.getBooleanProperty("plugin-manager.installUser");
      Roster roster = new Roster();
      String installDirectory;
      if (installUser) {
        installDirectory = MiscUtilities.constructPath(jEdit.getSettingsDirectory(), "jars");
      } else {
        installDirectory = MiscUtilities.constructPath(jEdit.getJEditHome(), "jars");
      }

      int length = pluginModel.entries.size();
      int instcount = 0;
      for (int i = 0; i < length; i++) {
        Entry entry = (Entry) pluginModel.entries.get(i);
        if (entry.install) {
          entry.plugin.install(roster, installDirectory, downloadSource);
          if (updates)
            entry
                .plugin
                .getCompatibleBranch()
                .satisfyDependencies(roster, installDirectory, downloadSource);
          instcount++;
        }
      }

      if (roster.isEmpty()) return;

      boolean cancel = false;
      if (updates && roster.getOperationCount() > instcount)
        if (GUIUtilities.confirm(
                window,
                "install-plugins.depend",
                null,
                JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.WARNING_MESSAGE)
            == JOptionPane.CANCEL_OPTION) cancel = true;

      if (!cancel) {
        new PluginManagerProgress(window, roster);

        roster.performOperationsInAWTThread(window);
        pluginModel.update();
      }
    }
Esempio n. 3
0
  // {{{ loadDirectory() method
  public void loadDirectory(
      final Object node, String path, final boolean addToHistory, final Runnable delayedAWTTask) {
    path = MiscUtilities.constructPath(browser.getDirectory(), path);
    VFS vfs = VFSManager.getVFSForPath(path);

    Object session = vfs.createVFSSession(path, this);
    if (session == null) {
      if (delayedAWTTask != null) ThreadUtilities.runInDispatchThread(delayedAWTTask);
      return;
    }

    if (node == null) {
      parentDirectories.setListData(new Object[] {new LoadingPlaceholder()});
    }

    final Object[] loadInfo = new Object[2];
    Runnable awtRunnable =
        new Runnable() {
          public void run() {
            browser.directoryLoaded(node, loadInfo, addToHistory);
            if (delayedAWTTask != null) delayedAWTTask.run();
          }
        };
    ThreadUtilities.runInBackground(
        new ListDirectoryBrowserTask(browser, session, vfs, path, loadInfo, awtRunnable));
  } // }}}
Esempio n. 4
0
  // {{{ getPrintJob() method
  private static PrinterJob getPrintJob(String jobName) {
    job = PrinterJob.getPrinterJob();

    format = new HashPrintRequestAttributeSet();

    String settings = jEdit.getSettingsDirectory();
    if (settings != null) {
      String printSpecPath = MiscUtilities.constructPath(settings, "printspec");
      File filePrintSpec = new File(printSpecPath);

      if (filePrintSpec.exists()) {
        try {
          FileInputStream fileIn = new FileInputStream(filePrintSpec);
          ObjectInputStream obIn = new ObjectInputStream(fileIn);
          format = (HashPrintRequestAttributeSet) obIn.readObject();
        } catch (Exception e) {
          Log.log(Log.ERROR, BufferPrinter1_4.class, e);
        }
        // for backwards compatibility, the color variable is stored also as a property
        if (jEdit.getBooleanProperty("print.color")) format.add(Chromaticity.COLOR);
        else format.add(Chromaticity.MONOCHROME);

        // no need to always keep the same job name for every printout.
        format.add(new JobName(jobName, null));
      }
    }

    return job;
  } // }}}
  // {{{ savePrintSpec() method
  private static void savePrintSpec() {
    // String settings = jEdit.getSettingsDirectory();
    // if(settings == null)
    // return;
    String settings = ".jedit"; // $NON-NLS-1$

    String printSpecPath = MiscUtilities.constructPath(settings, "printspec"); // $NON-NLS-1$
    File filePrintSpec = new File(printSpecPath);
    ObjectOutputStream obOut = null;
    try {
      FileOutputStream fileOut = new FileOutputStream(filePrintSpec);
      obOut = new ObjectOutputStream(fileOut);
      obOut.writeObject(format);
      // for backwards compatibility, the color variable is stored also as
      // a property
      Chromaticity cc = (Chromaticity) format.get(Chromaticity.class);
      if (cc != null) {
        jEdit.setBooleanProperty(
            "print.color", //$NON-NLS-1$
            cc.getValue() == Chromaticity.COLOR.getValue());
      }
    } catch (Exception e) {
      new Warning(Resources.get(WarningStrings.FAILED_PRINT_SETTINGS_SAVE), e);
    } finally {
      if (obOut != null) {
        try {
          obOut.close();
        } catch (IOException e) {
          new Warning(Resources.get(WarningStrings.FAILED_OUTSTREAM_CLOSE), e);
        }
      }
    }
  }
Esempio n. 6
0
 public void propertyChange(PropertyChangeEvent evt) {
   if ("page".equals(evt.getPropertyName())) {
     String titleStr = (String) viewer.getDocument().getProperty("title");
     if (titleStr == null) {
       titleStr = MiscUtilities.getFileName(viewer.getPage().toString());
     }
     title.setText(titleStr);
     historyModel.updateTitle(viewer.getPage().toString(), titleStr);
   }
 }
Esempio n. 7
0
 // {{{ copy() method
 private void copy(
     Object vfsSession, VFS vfs, String sourcePath, String sourceName, String targetPath)
     throws IOException, InterruptedException {
   String name = getTargetName(vfsSession, vfs, targetPath, sourceName);
   if (name == null) {
     return;
   }
   String targetName = MiscUtilities.constructPath(targetPath, name);
   CountDownLatch latch = new CountDownLatch(1);
   ThreadUtilities.runInBackground(new CopyFileWorker(comp, sourcePath, targetName, latch));
   latch.await();
 } // }}}
Esempio n. 8
0
  /**
   * Rebuild the parent view after a directory has been loaded.
   *
   * @param node
   * @param path
   * @param directory
   */
  public void directoryLoaded(Object node, String path, java.util.List<VFSFile> directory) {
    // {{{ If reloading root, update parent directory list
    if (node == null) {
      DefaultListModel parentList = new DefaultListModel();

      String parent = path;

      for (; ; ) {
        VFS _vfs = VFSManager.getVFSForPath(parent);
        VFSFile file = null;
        if (_vfs instanceof FileVFS) {
          Object session = _vfs.createVFSSession(path, browser);
          try {
            file = _vfs._getFile(session, parent, browser);
            if (file != null) {
              file.setName(_vfs.getFileName(parent));
            }
          } catch (IOException e) {
            Log.log(Log.ERROR, this, e, e);
          }
        }
        if (file == null) {
          // create a DirectoryEntry manually
          // instead of using _vfs._getFile()
          // since so many VFS's have broken
          // implementations of this method
          file =
              new VFSFile(_vfs.getFileName(parent), parent, parent, VFSFile.DIRECTORY, 0L, false);
        }

        /*parentList.insertElementAt(new VFSFile(
        _vfs.getFileName(parent),
        parent,parent,
        VFSFile.DIRECTORY,
        0L,false),0);*/
        parentList.insertElementAt(file, 0);
        String newParent = _vfs.getParentOfPath(parent);

        if (newParent == null || MiscUtilities.pathsEqual(parent, newParent)) break;
        else parent = newParent;
      }

      parentDirectories.setModel(parentList);
      int index = parentList.getSize() - 1;
      parentDirectories.setSelectedIndex(index);
      parentDirectories.ensureIndexIsVisible(index);
    } // }}}

    table.setDirectory(VFSManager.getVFSForPath(path), node, directory, tmpExpanded);
  } // }}}
    public void actionPerformed(ActionEvent evt) {
      Object source = evt.getSource();
      if (source instanceof JRadioButton) updateEnabled();
      if (source == ok) ok();
      else if (source == cancel) cancel();
      else if (source == combo) updateList();
      else if (source == fileButton) {
        String directory;
        if (fileIcon == null) directory = null;
        else directory = MiscUtilities.getParentOfPath(fileIcon);
        String paths[] =
            GUIUtilities.showVFSFileDialog(null, directory, VFSBrowser.OPEN_DIALOG, false);
        if (paths == null) return;

        fileIcon = "file:" + paths[0];

        try {
          fileButton.setIcon(new ImageIcon(new URL(fileIcon)));
        } catch (MalformedURLException mf) {
          Log.log(Log.ERROR, this, mf);
        }
        fileButton.setText(MiscUtilities.getFileName(fileIcon));
      }
    }
Esempio n. 10
0
  // {{{ maybeReloadDirectory() method
  public void maybeReloadDirectory(String path) {
    String browserDir = browser.getDirectory();
    String symlinkBrowserDir;
    if (MiscUtilities.isURL(browserDir)) {
      symlinkBrowserDir = browserDir;
    } else {
      symlinkBrowserDir = MiscUtilities.resolveSymlinks(browserDir);
    }

    if (MiscUtilities.pathsEqual(path, symlinkBrowserDir)) {
      saveExpansionState();
      loadDirectory(null, browserDir, false);
    }

    // because this method is called for *every* VFS update,
    // we don't want to scan the tree all the time. So we
    // use the following algorithm to determine if the path
    // might be part of the tree:
    // - if the path starts with the browser's current directory,
    //   we do the tree scan
    // - if the browser's directory is 'favorites:' -- we have to
    //   do the tree scan, as every path can appear under the
    //   favorites list
    // - if the browser's directory is 'roots:' and path is on
    //   the local filesystem, do a tree scan

    if (!browserDir.startsWith(FavoritesVFS.PROTOCOL)
        && !browserDir.startsWith(FileRootsVFS.PROTOCOL)
        && !path.startsWith(symlinkBrowserDir)) return;

    if (browserDir.startsWith(FileRootsVFS.PROTOCOL)
        && MiscUtilities.isURL(path)
        && !"file".equals(MiscUtilities.getProtocolOfURL(path))) return;

    table.maybeReloadDirectory(path);
  } // }}}
 private Vector getCompletions(String sel) {
   // TagsBinSearcher tbs;
   Vector tags = new Vector();
   ProjectBuffer currentTags = JumpPlugin.getActiveProjectBuffer();
   if (currentTags == null) return null;
   tags = currentTags.ctagsBuffer.getEntriesByStartPrefix(sel);
   Vector completions = new Vector();
   String entry;
   for (int i = 0; i < tags.size(); i++) {
     entry = (String) tags.get(i);
     completions.add(new Completion(entry, false));
   }
   MiscUtilities.quicksort(completions, new MiscUtilities.StringICaseCompare());
   return completions;
 }
Esempio n. 12
0
 // {{{ getSubstituteFor method
 public static String getSubstituteFor(View view, String key, XTreeNode node) {
   XTreeNode parentNode = node;
   String val = null;
   do {
     if (parentNode.hasVariables() && parentNode.containsVariable(key)) {
       val = parentNode.getVariable(key);
     }
   } while ((parentNode = (XTreeNode) parentNode.getParent()) != null);
   if (val == null && XInsertPlugin.containsVariable(key)) {
     val = XInsertPlugin.getVariable(key);
   }
   if (val == null && view != null) {
     val = XInsertPlugin.getViewSpecificVariable(view, key);
   }
   return val == null ? null : MiscUtilities.escapesToChars(val);
 } // }}}
Esempio n. 13
0
  private void updateList() {
    ActionSet actionSet = (ActionSet) combo.getSelectedItem();
    EditAction[] actions = actionSet.getActions();
    Vector listModel = new Vector(actions.length);

    for (int i = 0; i < actions.length; i++) {
      EditAction action = actions[i];
      String label = action.getLabel();
      if (label == null) continue;

      listModel.addElement(new ToolBarOptionPane.Button(action.getName(), null, null, label));
    }

    MiscUtilities.quicksort(listModel, new ToolBarOptionPane.ButtonCompare());
    list.setListData(listModel);
  }
Esempio n. 14
0
  // {{{ savePrintSpec() method
  private static void savePrintSpec() {
    String settings = jEdit.getSettingsDirectory();
    if (settings == null) return;

    String printSpecPath = MiscUtilities.constructPath(settings, "printspec");
    File filePrintSpec = new File(printSpecPath);

    try {
      FileOutputStream fileOut = new FileOutputStream(filePrintSpec);
      ObjectOutputStream obOut = new ObjectOutputStream(fileOut);
      obOut.writeObject(format);
      // for backwards compatibility, the color variable is stored also as a property
      Chromaticity cc = (Chromaticity) format.get(Chromaticity.class);
      if (cc != null)
        jEdit.setBooleanProperty("print.color", cc.getValue() == Chromaticity.COLOR.getValue());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  private static PrinterJob getPrintJob(String jobName) {
    job = PrinterJob.getPrinterJob();

    format = new HashPrintRequestAttributeSet();

    String settings = ".jedit"; // $NON-NLS-1$
    jEdit.getSettingsDirectory();
    if (settings != null) {
      String printSpecPath = MiscUtilities.constructPath(settings, "printspec"); // $NON-NLS-1$
      File filePrintSpec = new File(printSpecPath);

      if (filePrintSpec.exists()) {
        try {
          FileInputStream fileIn = new FileInputStream(filePrintSpec);
          ObjectInputStream obIn = new ObjectInputStream(fileIn);
          format = (HashPrintRequestAttributeSet) obIn.readObject();
          obIn.close();
        } catch (Exception e) {
          Log.log(Log.ERROR, ModifiedBufferPrinter1_4.class, e);
        }
        // for backwards compatibility, the color variable is stored
        // also as a property
        // disabled, getBooleanProperty seems not to work as
        // expected, probably because we don't have full jEdit here.

        // if(jEdit.getBooleanProperty("print.color"))
        // #trac 636
        Chromaticity cc = (Chromaticity) format.get(Chromaticity.class);
        if (cc != null) {
          jEdit.setBooleanProperty(
              "print.color", //$NON-NLS-1$
              cc.getValue() == Chromaticity.COLOR.getValue());
        } else {
          // default if no value was set before.
          jEdit.setBooleanProperty("print.color", true); // $NON-NLS-1$
        }
        // no need to always keep the same job label for every printout.
        format.add(new JobName(jobName, null));
      }
    }

    return job;
  } // }}}
Esempio n. 16
0
  // {{{ copyFileList() method
  private void copyFileList() {
    VFS vfs = VFSManager.getVFSForPath(target);
    Object targetSession = null;
    try {
      targetSession = vfs.createVFSSession(target, comp);
      if (targetSession == null) {
        Log.log(Log.ERROR, this, "Target VFS path cannot be reached");
        return;
      }
      VFSFile targetFile = vfs._getFile(targetSession, target, comp);
      if (targetFile == null) {
        Log.log(Log.ERROR, this, "Target is unreachable or do not exist");
        return;
      }

      if (targetFile.getType() != VFSFile.DIRECTORY) {
        Log.log(Log.ERROR, this, "Target is not a directory");
        return;
      }
      if (sources != null) {
        setMaximum(sources.size());
        for (int i = 0; i < sources.size(); i++) {
          setValue(i);
          String sourcePath = sources.get(i);
          String sourceName = MiscUtilities.getFileName(sourcePath);
          setLabel(sourceName);
          copy(targetSession, vfs, sourcePath, sourceName, target);
        }
      }
    } catch (IOException e) {
      Log.log(Log.ERROR, this, e);
    } catch (InterruptedException e) {
      Log.log(Log.WARNING, this, "Copy was interrupted");
    } finally {
      VFSManager.sendVFSUpdate(vfs, target, true);
      try {
        if (targetSession != null) vfs._endVFSSession(targetSession, comp);
      } catch (IOException e) {
      }
    }
  } // }}}
Esempio n. 17
0
  private void complete(boolean insertLongestPrefix) {
    String text = action.getText().trim();
    String[] completions = getCompletions(text);
    if (completions.length == 1) {
      if (insertLongestPrefix) action.setText(completions[0]);
    } else if (completions.length != 0) {
      if (insertLongestPrefix) {
        String prefix = MiscUtilities.getLongestPrefix(completions, true);
        if (prefix.contains(text)) action.setText(prefix);
      }

      if (popup != null) popup.setModel(completions);
      else popup = new CompletionPopup(completions);
      return;
    }

    if (popup != null) {
      popup.dispose();
      popup = null;
    }
  }
Esempio n. 18
0
  /**
   * Copy a file to another using VFS.
   *
   * @param progress the progress observer. It could be null if you don't want to monitor progress.
   *     If not null you should probably launch this command in a WorkThread
   * @param sourceVFS the source VFS
   * @param sourceSession the VFS session
   * @param sourcePath the source path
   * @param targetVFS the target VFS
   * @param targetSession the target session
   * @param targetPath the target path
   * @param comp comp The component that will parent error dialog boxes
   * @param canStop could this copy be stopped ?
   * @return true if the copy was successful
   * @throws IOException IOException If an I/O error occurs
   * @since jEdit 4.3pre3
   */
  public static boolean copy(
      ProgressObserver progress,
      VFS sourceVFS,
      Object sourceSession,
      String sourcePath,
      VFS targetVFS,
      Object targetSession,
      String targetPath,
      Component comp,
      boolean canStop)
      throws IOException {
    if (progress != null) progress.setStatus("Initializing");

    InputStream in = null;
    OutputStream out = null;
    try {
      VFSFile sourceVFSFile = sourceVFS._getFile(sourceSession, sourcePath, comp);
      if (sourceVFSFile == null) throw new FileNotFoundException(sourcePath);
      if (progress != null) {
        progress.setMaximum(sourceVFSFile.getLength());
      }
      VFSFile targetVFSFile = targetVFS._getFile(targetSession, targetPath, comp);
      if (targetVFSFile.getType() == VFSFile.DIRECTORY) {
        if (targetVFSFile.getPath().equals(sourceVFSFile.getPath())) return false;
        targetPath = MiscUtilities.constructPath(targetPath, sourceVFSFile.getName());
      }
      in =
          new BufferedInputStream(
              sourceVFS._createInputStream(sourceSession, sourcePath, false, comp));
      out =
          new BufferedOutputStream(targetVFS._createOutputStream(targetSession, targetPath, comp));
      boolean copyResult = IOUtilities.copyStream(IOBUFSIZE, progress, in, out, canStop);
      VFSManager.sendVFSUpdate(targetVFS, targetPath, true);
      return copyResult;
    } finally {
      IOUtilities.closeQuietly(in);
      IOUtilities.closeQuietly(out);
    }
  }
Esempio n. 19
0
  /**
   * 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;
  }
  // {{{ update() method
  public void update(JMenu menu) {
    final View view = GUIUtilities.getView(menu);

    // {{{ ActionListener...
    ActionListener actionListener =
        new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
            VFSBrowser.browseDirectory(view, evt.getActionCommand());

            view.getStatus().setMessage(null);
          }
        }; // }}}

    // {{{ MouseListener...
    MouseListener mouseListener =
        new MouseAdapter() {
          public void mouseEntered(MouseEvent evt) {
            view.getStatus().setMessage(((JMenuItem) evt.getSource()).getActionCommand());
          }

          public void mouseExited(MouseEvent evt) {
            view.getStatus().setMessage(null);
          }
        }; // }}}

    HistoryModel model = HistoryModel.getModel("vfs.browser.path");
    if (model.getSize() == 0) {
      JMenuItem menuItem = new JMenuItem(jEdit.getProperty("no-recent-dirs.label"));
      menuItem.setEnabled(false);
      menu.add(menuItem);
      return;
    }

    boolean sort = jEdit.getBooleanProperty("sortRecent");

    int maxItems = jEdit.getIntegerProperty("menu.spillover", 20);

    Vector menuItems = new Vector();

    for (int i = 0; i < model.getSize(); i++) {
      String path = model.getItem(i);
      JMenuItem menuItem = new JMenuItem(MiscUtilities.getFileName(path));
      menuItem.setActionCommand(path);
      menuItem.addActionListener(actionListener);
      menuItem.addMouseListener(mouseListener);
      menuItem.setIcon(FileCellRenderer.dirIcon);

      if (sort) menuItems.addElement(menuItem);
      else {
        if (menu.getMenuComponentCount() >= maxItems && i != model.getSize() - 1) {
          JMenu newMenu = new JMenu(jEdit.getProperty("common.more"));
          menu.add(newMenu);
          menu = newMenu;
        }

        menu.add(menuItem);
      }
    }

    if (sort) {
      Collections.sort(menuItems, new MiscUtilities.MenuItemCompare());
      for (int i = 0; i < menuItems.size(); i++) {
        if (menu.getMenuComponentCount() >= maxItems && i != 0) {
          JMenu newMenu = new JMenu(jEdit.getProperty("common.more"));
          menu.add(newMenu);
          menu = newMenu;
        }

        menu.add((JMenuItem) menuItems.elementAt(i));
      }
    }
  } // }}}
Esempio n. 21
0
 /**
  * Returns a temporary file name based on the given path.
  *
  * <p>By default jEdit first saves a file to <code>#<i>name</i>#save#</code> and then renames it
  * to the original file. However some virtual file systems might not support the <code>#</code>
  * character in filenames, so this method permits the VFS to override this behavior.
  *
  * <p>If this method returns <code>null</code>, two stage save will not be used for that
  * particular file (introduced in jEdit 4.3pre1).
  *
  * @param path The path name
  * @since jEdit 4.1pre7
  */
 public String getTwoStageSaveName(String path) {
   return MiscUtilities.constructPath(getParentOfPath(path), '#' + getFileName(path) + "#save#");
 } // }}}
Esempio n. 22
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();
  } // }}}
Esempio n. 23
0
  // {{{ run() method
  public void run() {
    /* if the VFS supports renaming files, we first
     * save to #<filename>#save#, then rename that
     * to <filename>, so that if the save fails,
     * data will not be lost.
     *
     * as of 4.1pre7 we now call vfs.getTwoStageSaveName()
     * instead of constructing the path directly
     * since some VFS's might not allow # in filenames.
     */

    boolean vfsRenameCap = (vfs.getCapabilities() & VFS.RENAME_CAP) != 0;

    boolean wantTwoStage = wantTwoStageSave(buffer);
    boolean twoStageSave = vfsRenameCap && wantTwoStage;

    try {
      String[] args = {vfs.getFileName(path)};
      setStatus(jEdit.getProperty("vfs.status.save", args));

      // the entire save operation can be aborted...
      setAbortable(true);

      path = vfs._canonPath(session, path, view);
      if (!MiscUtilities.isURL(path)) path = MiscUtilities.resolveSymlinks(path);

      String savePath;
      if (twoStageSave) {
        savePath = vfs.getTwoStageSaveName(path);
        if (savePath == null) {
          throw new IOException("Can't get a temporary path for two-stage save: " + path);
        }
      } else {
        makeBackup();
        savePath = path;
      }

      OutputStream out = vfs._createOutputStream(session, savePath, view);
      if (out == null) {
        buffer.setBooleanProperty(ERROR_OCCURRED, true);
        return;
      }
      try {
        // this must be after the stream is created or
        // we deadlock with SSHTools.
        buffer.readLock();
        try {
          // Can't use buffer.getName() here because
          // it is not changed until the save is
          // complete
          if (path.endsWith(".gz")) buffer.setBooleanProperty(Buffer.GZIPPED, true);
          else if (buffer.getName().endsWith(".gz")) {
            // The path do not ends with gz.
            // The buffer name was .gz.
            // So it means it's blabla.txt.gz -> blabla.txt, I remove
            // the gz property
            buffer.setBooleanProperty(Buffer.GZIPPED, false);
          }

          if (buffer.getBooleanProperty(Buffer.GZIPPED)) out = new GZIPOutputStream(out);

          write(buffer, out);
        } finally {
          buffer.readUnlock();
        }
      } finally {
        IOUtilities.closeQuietly(out);
      }

      if (twoStageSave) {
        makeBackup();
        if (!vfs._rename(session, savePath, path, view))
          throw new IOException("Rename failed: " + savePath);
      }

      if (!twoStageSave) VFSManager.sendVFSUpdate(vfs, path, true);
    } catch (FileNotFoundException e) {
      Log.log(Log.ERROR, this, "Unable to save buffer " + e);
      String[] pp = {e.getMessage()};
      VFSManager.error(view, path, "ioerror.write-error", pp);

      buffer.setBooleanProperty(ERROR_OCCURRED, true);
    } catch (UnsupportedCharsetException e) {
      Log.log(Log.ERROR, this, e, e);
      String[] pp = {e.getCharsetName()};
      VFSManager.error(view, path, "ioerror.unsupported-encoding-error", pp);

      buffer.setBooleanProperty(ERROR_OCCURRED, true);
    } catch (Exception e) {
      Log.log(Log.ERROR, this, e);
      String[] pp = {e.toString()};
      VFSManager.error(view, path, "ioerror.write-error", pp);

      buffer.setBooleanProperty(ERROR_OCCURRED, true);
    } catch (WorkThread.Abort a) {
      buffer.setBooleanProperty(ERROR_OCCURRED, true);
    } finally {
      try {
        vfs._saveComplete(session, buffer, path, view);
        if (twoStageSave) {
          vfs._finishTwoStageSave(session, buffer, path, view);
        }
        // clean up left-over markers file
        if (!jEdit.getBooleanProperty("persistentMarkers"))
          vfs._delete(session, Buffer.getMarkersPath(vfs, path), view);
        vfs._endVFSSession(session, view);
      } catch (Exception e) {
        Log.log(Log.ERROR, this, e);
        String[] pp = {e.toString()};
        VFSManager.error(view, path, "ioerror.write-error", pp);

        buffer.setBooleanProperty(ERROR_OCCURRED, true);
      } catch (WorkThread.Abort a) {
        buffer.setBooleanProperty(ERROR_OCCURRED, true);
      }
    }
  } // }}}
Esempio n. 24
0
 /**
  * Tries to detect if the stream is gzipped, and if it has an encoding specified with an XML PI.
  */
 protected Reader autodetect(InputStream in) throws IOException {
   return MiscUtilities.autodetect(in, buffer);
 } // }}}
Esempio n. 25
0
  /**
   * Creates a new help viewer for the specified URL.
   *
   * @param url The URL
   */
  public HelpViewer(String url) {
    super(jEdit.getProperty("helpviewer.title"));

    setIconImage(GUIUtilities.getEditorIcon());

    try {
      baseURL =
          new File(MiscUtilities.constructPath(jEdit.getJEditHome(), "doc")).toURL().toString();
    } catch (MalformedURLException mu) {
      Log.log(Log.ERROR, this, mu);
      // what to do?
    }

    ActionHandler actionListener = new ActionHandler();

    JTabbedPane tabs = new JTabbedPane();
    tabs.addTab(jEdit.getProperty("helpviewer.toc.label"), toc = new HelpTOCPanel(this));
    tabs.addTab(jEdit.getProperty("helpviewer.search.label"), new HelpSearchPanel(this));
    tabs.setMinimumSize(new Dimension(0, 0));

    JPanel rightPanel = new JPanel(new BorderLayout());

    Box toolBar = new Box(BoxLayout.X_AXIS);
    // toolBar.setFloatable(false);

    toolBar.add(title = new JLabel());
    toolBar.add(Box.createGlue());
    historyModel = new HelpHistoryModel(25);
    back = new HistoryButton(HistoryButton.BACK, historyModel);
    back.addActionListener(actionListener);
    toolBar.add(back);
    forward = new HistoryButton(HistoryButton.FORWARD, historyModel);
    forward.addActionListener(actionListener);
    toolBar.add(forward);
    back.setPreferredSize(forward.getPreferredSize());
    rightPanel.add(BorderLayout.NORTH, toolBar);

    viewer = new JEditorPane();
    viewer.setEditable(false);
    viewer.addHyperlinkListener(new LinkHandler());
    viewer.setFont(new Font("Monospaced", Font.PLAIN, 12));
    viewer.addPropertyChangeListener(new PropertyChangeHandler());
    viewer.addKeyListener(new KeyHandler());

    viewerScrollPane = new JScrollPane(viewer);

    rightPanel.add(BorderLayout.CENTER, viewerScrollPane);

    splitter =
        new JSplitPane(
            JSplitPane.HORIZONTAL_SPLIT,
            jEdit.getBooleanProperty("appearance.continuousLayout"),
            tabs,
            rightPanel);
    splitter.setBorder(null);

    getContentPane().add(BorderLayout.CENTER, splitter);

    historyModel.addHelpHistoryModelListener(this);
    historyUpdated();

    gotoURL(url, true, 0);

    setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    getRootPane().setPreferredSize(new Dimension(750, 500));

    pack();
    GUIUtilities.loadGeometry(this, "helpviewer");
    GUIUtilities.addSizeSaver(this, "helpviewer");

    EditBus.addToBus(this);

    setVisible(true);

    SwingUtilities.invokeLater(
        new Runnable() {
          public void run() {
            splitter.setDividerLocation(jEdit.getIntegerProperty("helpviewer.splitter", 250));
            viewer.requestFocus();
          }
        });
  } // }}}
Esempio n. 26
0
 public int compare(Object obj1, Object obj2) {
   return MiscUtilities.compareStrings(((Button) obj1).label, ((Button) obj2).label, true);
 }
Esempio n. 27
0
  public ToolBarEditDialog(
      Component comp, DefaultComboBoxModel iconListModel, ToolBarOptionPane.Button current) {
    super(
        GUIUtilities.getParentDialog(comp), jEdit.getProperty("options.toolbar.edit.title"), true);

    JPanel content = new JPanel(new BorderLayout());
    content.setBorder(new EmptyBorder(12, 12, 12, 12));
    setContentPane(content);

    ActionHandler actionHandler = new ActionHandler();
    ButtonGroup grp = new ButtonGroup();

    JPanel typePanel = new JPanel(new GridLayout(3, 1, 6, 6));
    typePanel.setBorder(new EmptyBorder(0, 0, 6, 0));
    typePanel.add(new JLabel(jEdit.getProperty("options.toolbar.edit.caption")));

    separator = new JRadioButton(jEdit.getProperty("options.toolbar" + ".edit.separator"));
    separator.addActionListener(actionHandler);
    grp.add(separator);
    typePanel.add(separator);

    action = new JRadioButton(jEdit.getProperty("options.toolbar" + ".edit.action"));
    action.addActionListener(actionHandler);
    grp.add(action);
    typePanel.add(action);

    content.add(BorderLayout.NORTH, typePanel);

    JPanel actionPanel = new JPanel(new BorderLayout(6, 6));

    ActionSet[] actionsList = jEdit.getActionSets();
    Vector vec = new Vector(actionsList.length);
    for (int i = 0; i < actionsList.length; i++) {
      ActionSet actionSet = actionsList[i];
      if (actionSet.getActionCount() != 0) vec.addElement(actionSet);
    }
    combo = new JComboBox(vec);
    combo.addActionListener(actionHandler);
    actionPanel.add(BorderLayout.NORTH, combo);

    list = new JList();
    list.setVisibleRowCount(8);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    actionPanel.add(BorderLayout.CENTER, new JScrollPane(list));

    JPanel iconPanel = new JPanel(new BorderLayout(0, 3));
    JPanel labelPanel = new JPanel(new GridLayout(2, 1));
    labelPanel.setBorder(new EmptyBorder(0, 0, 0, 12));
    JPanel compPanel = new JPanel(new GridLayout(2, 1));
    grp = new ButtonGroup();
    labelPanel.add(builtin = new JRadioButton(jEdit.getProperty("options.toolbar.edit.builtin")));
    builtin.addActionListener(actionHandler);
    grp.add(builtin);
    labelPanel.add(file = new JRadioButton(jEdit.getProperty("options.toolbar.edit.file")));
    grp.add(file);
    file.addActionListener(actionHandler);
    iconPanel.add(BorderLayout.WEST, labelPanel);
    builtinCombo = new JComboBox(iconListModel);
    builtinCombo.setRenderer(new ToolBarOptionPane.IconCellRenderer());
    compPanel.add(builtinCombo);

    fileButton = new JButton(jEdit.getProperty("options.toolbar.edit.no-icon"));
    fileButton.setMargin(new Insets(1, 1, 1, 1));
    fileButton.setIcon(GUIUtilities.loadIcon("Blank24.gif"));
    fileButton.setHorizontalAlignment(SwingConstants.LEFT);
    fileButton.addActionListener(actionHandler);
    compPanel.add(fileButton);
    iconPanel.add(BorderLayout.CENTER, compPanel);
    actionPanel.add(BorderLayout.SOUTH, iconPanel);

    content.add(BorderLayout.CENTER, actionPanel);

    JPanel southPanel = new JPanel();
    southPanel.setLayout(new BoxLayout(southPanel, BoxLayout.X_AXIS));
    southPanel.setBorder(new EmptyBorder(12, 0, 0, 0));
    southPanel.add(Box.createGlue());
    ok = new JButton(jEdit.getProperty("common.ok"));
    ok.addActionListener(actionHandler);
    getRootPane().setDefaultButton(ok);
    southPanel.add(ok);
    southPanel.add(Box.createHorizontalStrut(6));
    cancel = new JButton(jEdit.getProperty("common.cancel"));
    cancel.addActionListener(actionHandler);
    southPanel.add(cancel);
    southPanel.add(Box.createGlue());

    content.add(BorderLayout.SOUTH, southPanel);

    if (current == null) {
      action.setSelected(true);
      builtin.setSelected(true);
      updateList();
    } else {
      if (current.actionName.equals("-")) {
        separator.setSelected(true);
        builtin.setSelected(true);
      } else {
        action.setSelected(true);
        ActionSet set = jEdit.getActionSetForAction(current.actionName);
        combo.setSelectedItem(set);
        updateList();
        list.setSelectedValue(current, true);

        if (MiscUtilities.isURL(current.iconName)) {
          file.setSelected(true);
          fileIcon = current.iconName;
          try {
            fileButton.setIcon(new ImageIcon(new URL(fileIcon)));
          } catch (MalformedURLException mf) {
            Log.log(Log.ERROR, this, mf);
          }
          fileButton.setText(MiscUtilities.getFileName(fileIcon));
        } else {
          String iconName = MiscUtilities.getFileName(current.iconName);
          builtin.setSelected(true);
          ListModel model = builtinCombo.getModel();
          for (int i = 0; i < model.getSize(); i++) {
            ToolBarOptionPane.IconListEntry entry =
                (ToolBarOptionPane.IconListEntry) model.getElementAt(i);
            if (entry.name.equals(iconName)) {
              builtinCombo.setSelectedIndex(i);
              break;
            }
          }
        }
      }
    }

    updateEnabled();

    pack();
    setLocationRelativeTo(GUIUtilities.getParentDialog(comp));
    show();
  }
Esempio n. 28
0
  // {{{ recursive listFiles() method
  private void listFiles(
      Object session,
      Collection<String> stack,
      List<String> files,
      String directory,
      VFSFileFilter filter,
      boolean recursive,
      Component comp,
      boolean skipBinary,
      boolean skipHidden)
      throws IOException {
    String resolvedPath = directory;
    if (recursive && !MiscUtilities.isURL(directory)) {
      resolvedPath = MiscUtilities.resolveSymlinks(directory);
      /*
       * If looking at a symlink, do not traverse the
       * resolved path more than once.
       */
      if (!directory.equals(resolvedPath)) {
        if (stack.contains(resolvedPath)) {
          Log.log(Log.ERROR, this, "Recursion in listFiles(): " + directory);
          return;
        }
        stack.add(resolvedPath);
      }
    }

    Thread ct = Thread.currentThread();
    WorkThread wt = null;
    if (ct instanceof WorkThread) {
      wt = (WorkThread) ct;
    }

    VFSFile[] _files = _listFiles(session, directory, comp);
    if (_files == null || _files.length == 0) return;

    for (int i = 0; i < _files.length; i++) {
      if (wt != null && wt.isAborted()) break;
      VFSFile file = _files[i];
      if (skipHidden && (file.isHidden() || MiscUtilities.isBackup(file.getName()))) continue;
      if (!filter.accept(file)) continue;
      if (file.getType() == VFSFile.DIRECTORY || file.getType() == VFSFile.FILESYSTEM) {
        if (recursive) {
          String canonPath = _canonPath(session, file.getPath(), comp);
          listFiles(
              session, stack, files, canonPath, filter, recursive, comp, skipBinary, skipHidden);
        }
      } else // It's a regular file
      {
        if (skipBinary) {
          try {
            if (file.isBinary(session)) {
              Log.log(Log.NOTICE, this, file.getPath() + ": skipped as a binary file");
              continue;
            }
          } catch (IOException e) {
            Log.log(Log.ERROR, this, e);
            // may be not binary...
          }
        }
        files.add(file.getPath());
      }
    }
  } // }}}
Esempio n. 29
0
 public static VFS getVFSForPath(String path) {
   if (MiscUtilities.isURL(path)) return getVFSForProtocol(MiscUtilities.getProtocolOfURL(path));
   else return fileVFS;
 }
Esempio n. 30
0
  private void invoke() {
    String cmd;
    if (popup != null) cmd = popup.list.getSelectedValue().toString();
    else {
      cmd = action.getText().trim();
      int index = cmd.indexOf('=');
      if (index != -1) {
        action.addCurrentToHistory();
        String propName = cmd.substring(0, index).trim();
        String propValue = cmd.substring(index + 1).trim();
        String code;

        if (propName.startsWith("buffer.")) {
          if (propName.equals("buffer.mode")) {
            code = "buffer.setMode(\"" + MiscUtilities.charsToEscapes(propValue) + "\");";
          } else {
            code =
                "buffer.setStringProperty(\""
                    + MiscUtilities.charsToEscapes(propName.substring("buffer.".length()))
                    + "\",\""
                    + MiscUtilities.charsToEscapes(propValue)
                    + "\");";
          }

          code += "\nbuffer.propertiesChanged();";
        } else if (propName.startsWith("!buffer.")) {
          code =
              "jEdit.setProperty(\""
                  + MiscUtilities.charsToEscapes(propName.substring(1))
                  + "\",\""
                  + MiscUtilities.charsToEscapes(propValue)
                  + "\");\n"
                  + "jEdit.propertiesChanged();";
        } else {
          code =
              "jEdit.setProperty(\""
                  + MiscUtilities.charsToEscapes(propName)
                  + "\",\""
                  + MiscUtilities.charsToEscapes(propValue)
                  + "\");\n"
                  + "jEdit.propertiesChanged();";
        }

        Macros.Recorder recorder = view.getMacroRecorder();
        if (recorder != null) recorder.record(code);
        BeanShell.eval(view, namespace, code);
        cmd = null;
      } else if (cmd.length() != 0) {
        String[] completions = getCompletions(cmd);
        if (completions.length != 0) {
          cmd = completions[0];
        }
      } else cmd = null;
    }

    if (popup != null) {
      popup.dispose();
      popup = null;
    }

    final String finalCmd = cmd;
    final EditAction act = (finalCmd == null ? null : jEdit.getAction(finalCmd));
    if (temp) view.removeToolBar(this);

    SwingUtilities.invokeLater(
        new Runnable() {
          public void run() {
            view.getTextArea().requestFocus();
            if (act == null) {
              if (finalCmd != null) {
                view.getStatus()
                    .setMessageAndClear(jEdit.getProperty("view.action.no-completions"));
              }
            } else {
              view.getInputHandler().setRepeatCount(repeatCount);
              view.getInputHandler().invokeAction(act);
            }
          }
        });
  }