예제 #1
0
  public boolean openLink() {
    frame.output(Localization.lang("External viewer called") + ".");
    try {
      ExternalFileType type = fileType;
      if (this.fileType == null) {
        if (this.fieldName == null) {
          // We don't already know the file type, so we try to deduce it from the extension:
          File file = new File(link);
          // We try to check the extension for the file:
          String name = file.getName();
          int pos = name.indexOf('.');
          String extension =
              (pos >= 0) && (pos < (name.length() - 1))
                  ? name.substring(pos + 1).trim().toLowerCase()
                  : null;
          // Now we know the extension, check if it is one we know about:
          type = ExternalFileTypes.getInstance().getExternalFileTypeByExt(extension);
          fileType = type;
        } else {
          JabRefDesktop.openExternalViewer(
              frame.getCurrentBasePanel().getBibDatabaseContext().getMetaData(), link, fieldName);
          return true;
        }
      }

      if (type instanceof UnknownExternalFileType) {
        return JabRefDesktop.openExternalFileUnknown(
            frame, entry, metaData, link, (UnknownExternalFileType) type);
      } else {
        return JabRefDesktop.openExternalFileAnyFormat(metaData, link, type);
      }

    } catch (IOException e1) {
      // See if we should show an error message concerning the application to open the
      // link with. We check if the file type is set, and if the file type has a non-empty
      // application link. If that link is referred by the error message, we can assume
      // that the problem is in the open-with-application setting:
      if ((fileType != null)
          && (fileType.getOpenWith() != null)
          && !fileType.getOpenWith().isEmpty()
          && e1.getMessage().contains(fileType.getOpenWith())) {

        JOptionPane.showMessageDialog(
            frame,
            Localization.lang(
                "Unable to open link. "
                    + "The application '%0' associated with the file type '%1' could not be called.",
                fileType.getOpenWith(), fileType.getName()),
            Localization.lang("Could not open link"),
            JOptionPane.ERROR_MESSAGE);
        return false;
      }

      LOGGER.warn("Unable to open link", e1);
    }
    return false;
  }
예제 #2
0
 /** Update the editor to show the current settings in Preferences. */
 private void setValues() {
   fileTypes.clear();
   Collection<ExternalFileType> types =
       ExternalFileTypes.getInstance().getExternalFileTypeSelection();
   for (ExternalFileType type : types) {
     fileTypes.add(type.copy());
   }
   Collections.sort(fileTypes);
 }
예제 #3
0
  @Override
  public void run() {
    if (!goOn) {
      panel.output(
          Localization.lang("This operation requires one or more entries to be selected."));
      return;
    }
    entriesChangedCount = 0;
    panel.frame().setProgressBarValue(0);
    panel.frame().setProgressBarVisible(true);
    int weightAutoSet = 10; // autoSet takes 10 (?) times longer than checkExisting
    int progressBarMax =
        (autoSet ? weightAutoSet * sel.size() : 0) + (checkExisting ? sel.size() : 0);
    panel.frame().setProgressBarMaximum(progressBarMax);
    int progress = 0;
    final NamedCompound ce = new NamedCompound(Localization.lang("Automatically set file links"));

    Set<BibEntry> changedEntries = new HashSet<>();

    // First we try to autoset fields
    if (autoSet) {
      Collection<BibEntry> entries = new ArrayList<>(sel);

      // Start the automatically setting process:
      Runnable r =
          AutoSetLinks.autoSetLinks(
              entries, ce, changedEntries, null, panel.getBibDatabaseContext(), null, null);
      JabRefExecutorService.INSTANCE.executeAndWait(r);
    }
    progress += sel.size() * weightAutoSet;
    panel.frame().setProgressBarValue(progress);
    // The following loop checks all external links that are already set.
    if (checkExisting) {
      boolean removeAllBroken = false;
      mainLoop:
      for (BibEntry aSel : sel) {
        panel.frame().setProgressBarValue(progress++);
        final String old = aSel.getField(Globals.FILE_FIELD);
        // Check if a extension is set:
        if ((old != null) && !(old.isEmpty())) {
          FileListTableModel tableModel = new FileListTableModel();
          tableModel.setContentDontGuessTypes(old);

          // We need to specify which directories to search in for Util.expandFilename:
          List<String> dirsS = panel.getBibDatabaseContext().getFileDirectory();
          List<File> dirs = new ArrayList<>();
          for (String dirs1 : dirsS) {
            dirs.add(new File(dirs1));
          }

          for (int j = 0; j < tableModel.getRowCount(); j++) {
            FileListEntry flEntry = tableModel.getEntry(j);
            // See if the link looks like an URL:
            boolean httpLink = flEntry.link.toLowerCase(Locale.ENGLISH).startsWith("http");
            if (httpLink) {
              continue; // Don't check the remote file.
              // TODO: should there be an option to check remote links?
            }

            // A variable to keep track of whether this link gets deleted:
            boolean deleted = false;

            // Get an absolute path representation:
            Optional<File> file = FileUtil.expandFilename(flEntry.link, dirsS);
            if ((!file.isPresent()) || !file.get().exists()) {
              int answer;
              if (removeAllBroken) {
                answer = 2; // We should delete this link.
              } else {
                answer =
                    JOptionPane.showOptionDialog(
                        panel.frame(),
                        Localization.lang(
                            "<HTML>Could not find file '%0'<BR>linked from entry '%1'</HTML>",
                            flEntry.link, aSel.getCiteKey()),
                        Localization.lang("Broken link"),
                        JOptionPane.YES_NO_CANCEL_OPTION,
                        JOptionPane.QUESTION_MESSAGE,
                        null,
                        brokenLinkOptions,
                        brokenLinkOptions[0]);
              }
              switch (answer) {
                case 1:
                  // Assign new file.
                  FileListEntryEditor flEditor =
                      new FileListEntryEditor(
                          panel.frame(), flEntry, false, true, panel.getBibDatabaseContext());
                  flEditor.setVisible(true, true);
                  break;
                case 2:
                  // Clear field:
                  tableModel.removeEntry(j);
                  deleted = true; // Make sure we don't investigate this link further.
                  j--; // Step back in the iteration, because we removed an entry.
                  break;
                case 3:
                  // Clear field:
                  tableModel.removeEntry(j);
                  deleted = true; // Make sure we don't investigate this link further.
                  j--; // Step back in the iteration, because we removed an entry.
                  removeAllBroken = true; // Notify for further cases.
                  break;
                default:
                  // Cancel
                  break mainLoop;
              }
            }

            // Unless we deleted this link, see if its file type is recognized:
            if (!deleted
                && flEntry.type.isPresent()
                && (flEntry.type.get() instanceof UnknownExternalFileType)) {
              String[] options =
                  new String[] {
                    Localization.lang("Define '%0'", flEntry.type.get().getName()),
                    Localization.lang("Change file type"),
                    Localization.lang("Cancel")
                  };
              String defOption = options[0];
              int answer =
                  JOptionPane.showOptionDialog(
                      panel.frame(),
                      Localization.lang(
                          "One or more file links are of the type '%0', which is undefined. What do you want to do?",
                          flEntry.type.get().getName()),
                      Localization.lang("Undefined file type"),
                      JOptionPane.YES_NO_CANCEL_OPTION,
                      JOptionPane.QUESTION_MESSAGE,
                      null,
                      options,
                      defOption);
              if (answer == JOptionPane.CANCEL_OPTION) {
                // User doesn't want to handle this unknown link type.
              } else if (answer == JOptionPane.YES_OPTION) {
                // User wants to define the new file type. Show the dialog:
                ExternalFileType newType =
                    new ExternalFileType(
                        flEntry.type.get().getName(),
                        "",
                        "",
                        "",
                        "new",
                        IconTheme.JabRefIcon.FILE.getSmallIcon());
                ExternalFileTypeEntryEditor editor =
                    new ExternalFileTypeEntryEditor(panel.frame(), newType);
                editor.setVisible(true);
                if (editor.okPressed()) {
                  // Get the old list of types, add this one, and update the list in prefs:
                  List<ExternalFileType> fileTypes =
                      new ArrayList<>(
                          ExternalFileTypes.getInstance().getExternalFileTypeSelection());
                  fileTypes.add(newType);
                  Collections.sort(fileTypes);
                  ExternalFileTypes.getInstance().setExternalFileTypes(fileTypes);
                  panel.getMainTable().repaint();
                }
              } else {
                // User wants to change the type of this link.
                // First get a model of all file links for this entry:
                FileListEntryEditor editor =
                    new FileListEntryEditor(
                        panel.frame(), flEntry, false, true, panel.getBibDatabaseContext());
                editor.setVisible(true, false);
              }
            }
          }

          if (!tableModel.getStringRepresentation().equals(old)) {
            // The table has been modified. Store the change:
            String toSet = tableModel.getStringRepresentation();
            if (toSet.isEmpty()) {
              ce.addEdit(new UndoableFieldChange(aSel, Globals.FILE_FIELD, old, null));
              aSel.clearField(Globals.FILE_FIELD);
            } else {
              ce.addEdit(new UndoableFieldChange(aSel, Globals.FILE_FIELD, old, toSet));
              aSel.setField(Globals.FILE_FIELD, toSet);
            }
            changedEntries.add(aSel);
          }
        }
      }
    }

    if (!changedEntries.isEmpty()) {
      // Add the undo edit:
      ce.end();
      panel.getUndoManager().addEdit(ce);
      panel.markBaseChanged();
      entriesChangedCount = changedEntries.size();
    }
  }
예제 #4
0
  private void init() {

    ok.addActionListener(
        e -> {
          storeSettings();
          dispose();
        });
    Action cancelAction =
        new AbstractAction() {

          @Override
          public void actionPerformed(ActionEvent e) {
            dispose();
          }
        };
    cancel.addActionListener(cancelAction);
    // The toDefaults resets the entire list to its default values.
    toDefaults.addActionListener(
        e -> {
          /*int reply = JOptionPane.showConfirmDialog(ExternalFileTypeEditor.this,
          Globals.lang("All custom file types will be lost. Proceed?"),
          Globals.lang("Reset file type definitions"), JOptionPane.YES_NO_OPTION,
          JOptionPane.QUESTION_MESSAGE);*/
          // if (reply == JOptionPane.YES_OPTION) {
          List<ExternalFileType> list = ExternalFileTypes.getDefaultExternalFileTypes();
          fileTypes.clear();
          fileTypes.addAll(list);
          Collections.sort(fileTypes);
          // Globals.prefs.resetExternalFileTypesToDefault();
          // setValues();
          tableModel.fireTableDataChanged();
          // }
        });

    add.addActionListener(
        e -> {
          // Generate a new file type:
          ExternalFileType type =
              new ExternalFileType("", "", "", "", "new", IconTheme.JabRefIcon.FILE.getSmallIcon());
          // Show the file type editor:
          getEditor(type).setVisible(true);
          if (entryEditor.okPressed()) {
            // Ok was pressed. Add the new file type and update the table:
            fileTypes.add(type);
            tableModel.fireTableDataChanged();
          }
        });

    remove.addActionListener(
        e -> {
          int[] rows = table.getSelectedRows();
          if (rows.length == 0) {
            return;
          }
          for (int i = rows.length - 1; i >= 0; i--) {
            fileTypes.remove(rows[i]);
          }
          tableModel.fireTableDataChanged();
          if (!fileTypes.isEmpty()) {
            int row = Math.min(rows[0], fileTypes.size() - 1);
            table.setRowSelectionInterval(row, row);
          }
        });

    edit.addActionListener(editListener);
    fileTypes = new ArrayList<>();
    setValues();

    tableModel = new FileTypeTableModel();
    table = new JTable(tableModel);
    table.setDefaultRenderer(ImageIcon.class, new IconRenderer());
    table.addMouseListener(new TableClickListener());

    table.getColumnModel().getColumn(0).setMaxWidth(24);
    table.getColumnModel().getColumn(0).setMinWidth(24);
    table.getColumnModel().getColumn(1).setMinWidth(170);
    table.getColumnModel().getColumn(2).setMinWidth(60);
    table.getColumnModel().getColumn(3).setMinWidth(100);
    table.getColumnModel().getColumn(0).setResizable(false);

    GUIUtil.correctRowHeight(table);

    JScrollPane sp = new JScrollPane(table);

    JPanel upper = new JPanel();
    upper.setLayout(new BorderLayout());
    upper.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    upper.add(sp, BorderLayout.CENTER);
    getContentPane().add(upper, BorderLayout.CENTER);

    ButtonStackBuilder bs = new ButtonStackBuilder();
    bs.addButton(add);
    bs.addButton(remove);
    bs.addButton(edit);
    bs.addRelatedGap();
    bs.addButton(toDefaults);
    upper.add(bs.getPanel(), BorderLayout.EAST);

    ButtonBarBuilder bb = new ButtonBarBuilder();
    bb.addGlue();
    bb.addButton(ok);
    bb.addButton(cancel);
    bb.addGlue();
    bb.getPanel().setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    getContentPane().add(bb.getPanel(), BorderLayout.SOUTH);
    pack();

    // Key bindings:
    ActionMap am = upper.getActionMap();
    InputMap im = upper.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    im.put(Globals.getKeyPrefs().getKey(KeyBinding.CLOSE_DIALOG), "close");
    am.put("close", cancelAction);
    am = bb.getPanel().getActionMap();
    im = bb.getPanel().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    im.put(Globals.getKeyPrefs().getKey(KeyBinding.CLOSE_DIALOG), "close");
    am.put("close", cancelAction);

    if (frame == null) {
      setLocationRelativeTo(dialog);
    } else {
      setLocationRelativeTo(frame);
    }
  }
예제 #5
0
 /** Store the list of external entry types to Preferences. */
 private void storeSettings() {
   ExternalFileTypes.getInstance().setExternalFileTypes(fileTypes);
 }