Example #1
0
 @Override
 public void update() {
   if (cancelled) {
     frame.unblock();
     return;
   }
   if (unsuccessfulRenames > 0) { // Rename failed for at least one entry
     JOptionPane.showMessageDialog(
         frame,
         Localization.lang(
             "File rename failed for %0 entries.", Integer.toString(unsuccessfulRenames)),
         Localization.lang("Autogenerate PDF Names"),
         JOptionPane.INFORMATION_MESSAGE);
   }
   if (modifiedEntriesCount > 0) {
     panel.updateEntryEditorIfShowing();
     panel.markBaseChanged();
   }
   String message;
   switch (modifiedEntriesCount) {
     case 0:
       message = Localization.lang("No entry needed a clean up");
       break;
     case 1:
       message = Localization.lang("One entry needed a clean up");
       break;
     default:
       message =
           Localization.lang(
               "%0 entries needed a clean up", Integer.toString(modifiedEntriesCount));
       break;
   }
   panel.output(message);
   frame.unblock();
 }
Example #2
0
  private Optional<BibEntry> createNewEntry() {
    // Find out what type is desired
    EntryTypeDialog etd = new EntryTypeDialog(frame);
    // We want to center the dialog, to make it look nicer.
    etd.setLocationRelativeTo(frame);
    etd.setVisible(true);
    EntryType type = etd.getChoice();

    if (type != null) { // Only if the dialog was not canceled.
      String id = IdGenerator.next();
      final BibEntry bibEntry = new BibEntry(id, type.getName());
      try {
        panel.getDatabase().insertEntry(bibEntry);

        // Set owner/timestamp if options are enabled:
        List<BibEntry> list = new ArrayList<>();
        list.add(bibEntry);
        UpdateField.setAutomaticFields(list, true, true, Globals.prefs.getUpdateFieldPreferences());

        // Create an UndoableInsertEntry object.
        panel
            .getUndoManager()
            .addEdit(new UndoableInsertEntry(panel.getDatabase(), bibEntry, panel));
        panel.output(
            Localization.lang("Added new")
                + " '"
                + type.getName().toLowerCase()
                + "' "
                + Localization.lang("entry")
                + ".");

        // We are going to select the new entry. Before that, make sure that we are in
        // show-entry mode. If we aren't already in that mode, enter the WILL_SHOW_EDITOR
        // mode which makes sure the selection will trigger display of the entry editor
        // and adjustment of the splitter.
        if (panel.getMode() != BasePanelMode.SHOWING_EDITOR) {
          panel.setMode(BasePanelMode.WILL_SHOW_EDITOR);
        }

        SwingUtilities.invokeLater(() -> panel.showEntry(bibEntry));

        // The database just changed.
        panel.markBaseChanged();

        return Optional.of(bibEntry);
      } catch (KeyCollisionException ex) {
        LOGGER.info("Key collision occurred", ex);
      }
    }
    return Optional.empty();
  }
  @Override
  public void update() {
    if (!goOn) {
      return;
    }

    panel.output(
        Localization.lang(
            "Finished synchronizing file links. Entries changed: %0.",
            String.valueOf(entriesChangedCount)));
    panel.frame().setProgressBarVisible(false);
    if (entriesChangedCount > 0) {
      panel.markBaseChanged();
    }
  }
Example #4
0
 @Override
 public void update() {
   if (databases == null) {
     return;
   }
   for (DBImporterResult res : databases) {
     databaseContext = res.getDatabaseContext();
     if (databaseContext != null) {
       BasePanel pan = frame.addTab(databaseContext, true);
       pan.getBibDatabaseContext().getMetaData().setDBStrings(dbs);
       frame.setTabTitle(pan, res.getName() + "(Imported)", "Imported DB");
       pan.markBaseChanged();
     }
   }
   frame.output(
       Localization.lang(
           "Imported %0 databases successfully", Integer.toString(databases.size())));
 }
Example #5
0
  private void doContentImport(String fileName, List<BibEntry> res) {

    PdfContentImporter contentImporter =
        new PdfContentImporter(Globals.prefs.getImportFormatPreferences());
    Path filePath = Paths.get(fileName);
    ParserResult result =
        contentImporter.importDatabase(filePath, Globals.prefs.getDefaultEncoding());
    if (result.hasWarnings()) {
      frame.showMessage(result.getErrorMessage());
    }

    if (!result.getDatabase().hasEntries()) {
      // import failed -> generate default entry
      createNewBlankEntry(fileName).ifPresent(res::add);
      return;
    }

    // only one entry is imported
    BibEntry entry = result.getDatabase().getEntries().get(0);

    // insert entry to database and link file
    panel.getDatabase().insertEntry(entry);
    panel.markBaseChanged();
    BibtexKeyPatternUtil.makeLabel(
        panel
            .getBibDatabaseContext()
            .getMetaData()
            .getCiteKeyPattern(Globals.prefs.getBibtexKeyPatternPreferences().getKeyPattern()),
        panel.getDatabase(),
        entry,
        Globals.prefs.getBibtexKeyPatternPreferences());
    DroppedFileHandler dfh = new DroppedFileHandler(frame, panel);
    dfh.linkPdfToEntry(fileName, entry);
    panel.highlightEntry(entry);
    if (Globals.prefs.getBoolean(JabRefPreferences.AUTO_OPEN_FORM)) {
      EntryEditor editor = panel.getEntryEditor(entry);
      panel.showEntryEditor(editor);
    }
    res.add(entry);
  }
  /**
   * This method performs the actual changes.
   *
   * @param panel
   * @param pr
   * @param fileDir The path to the file directory to set, or null if it should not be set.
   */
  private void makeChanges(
      BasePanel panel,
      ParserResult pr,
      boolean upgradePrefs,
      boolean upgradeDatabase,
      String fileDir) {

    if (upgradeDatabase) {
      // Update file links links in the database:
      NamedCompound ce =
          Util.upgradePdfPsToFile(pr.getDatabase(), FileLinksUpgradeWarning.FIELDS_TO_LOOK_FOR);
      panel.undoManager.addEdit(ce);
      panel.markBaseChanged();
    }

    if (fileDir != null) {
      Globals.prefs.put(Globals.FILE_FIELD + Globals.DIR_SUFFIX, fileDir);
    }

    if (upgradePrefs) {
      // Exchange table columns:
      Globals.prefs.putBoolean(JabRefPreferences.FILE_COLUMN, Boolean.TRUE);

      // Modify General fields if necessary:
      // If we don't find the file field, insert it at the bottom of the first tab:
      if (!showsFileInGenFields()) {
        String gfs = Globals.prefs.get(JabRefPreferences.CUSTOM_TAB_FIELDS + "0");
        StringBuilder sb = new StringBuilder(gfs);
        if (!gfs.isEmpty()) {
          sb.append(";");
        }
        sb.append(Globals.FILE_FIELD);
        Globals.prefs.put(JabRefPreferences.CUSTOM_TAB_FIELDS + "0", sb.toString());
        Globals.prefs.updateEntryEditorTabList();
        panel.frame().removeCachedEntryEditors();
      }
      panel.frame().setupAllTables();
    }
  }
Example #7
0
  private void doXMPImport(String fileName, List<BibEntry> res) {
    List<BibEntry> localRes = new ArrayList<>();
    PdfXmpImporter importer = new PdfXmpImporter(Globals.prefs.getXMPPreferences());
    Path filePath = Paths.get(fileName);
    ParserResult result = importer.importDatabase(filePath, Globals.prefs.getDefaultEncoding());
    if (result.hasWarnings()) {
      frame.showMessage(result.getErrorMessage());
    }
    localRes.addAll(result.getDatabase().getEntries());

    BibEntry entry;
    if (localRes.isEmpty()) {
      // import failed -> generate default entry
      LOGGER.info("Import failed");
      createNewBlankEntry(fileName).ifPresent(res::add);
      return;
    }

    // only one entry is imported
    entry = localRes.get(0);

    // insert entry to database and link file
    panel.getDatabase().insertEntry(entry);
    panel.markBaseChanged();
    FileListTableModel tm = new FileListTableModel();
    File toLink = new File(fileName);
    // Get a list of file directories:
    List<String> dirsS =
        panel.getBibDatabaseContext().getFileDirectory(Globals.prefs.getFileDirectoryPreferences());

    tm.addEntry(
        0,
        new FileListEntry(
            toLink.getName(),
            FileUtil.shortenFileName(toLink, dirsS).getPath(),
            ExternalFileTypes.getInstance().getExternalFileTypeByName("PDF")));
    entry.setField(FieldName.FILE, tm.getStringRepresentation());
    res.add(entry);
  }
Example #8
0
  @Override
  public void actionPerformed(ActionEvent evt) {
    final List<BibEntry> entries = panel.getSelectedEntries();

    // if an editor is showing, its fields must be updated after the assignment,
    // and before that, the current edit has to be stored:
    panel.storeCurrentEdit();

    NamedCompound undoAll = new NamedCompound(Localization.lang("change assignment of entries"));

    if (move) {
      moveToGroup(entries, undoAll);
    } else {
      addToGroup(entries, undoAll);
    }

    undoAll.end();

    panel.getUndoManager().addEdit(undoAll);
    panel.markBaseChanged();
    panel.updateEntryEditorIfShowing();
    panel.getGroupSelector().valueChanged(null);
  }
Example #9
0
  @Override
  public void run() {
    if (cancelled) {
      return;
    }
    int choice = showCleanUpDialog();
    if (choice != JOptionPane.OK_OPTION) {
      cancelled = true;
      return;
    }
    storeSettings();
    boolean choiceCleanUpSuperscripts = cleanUpSuperscripts.isSelected();
    boolean choiceCleanUpDOI = cleanUpDOI.isSelected();
    boolean choiceCleanUpMonth = cleanUpMonth.isSelected();
    boolean choiceCleanUpPageNumbers = cleanUpPageNumbers.isSelected();
    boolean choiceCleanUpDate = cleanUpDate.isSelected();
    boolean choiceCleanUpUpgradeExternalLinks = cleanUpUpgradeExternalLinks.isSelected();
    boolean choiceMakePathsRelative = cleanUpMakePathsRelative.isSelected();
    boolean choiceRenamePDF = cleanUpRenamePDF.isSelected();
    boolean choiceConvertHTML = cleanUpHTML.isSelected();
    boolean choiceConvertCase = cleanUpCase.isSelected();
    boolean choiceConvertLaTeX = cleanUpLaTeX.isSelected();
    boolean choiceConvertUnits = cleanUpUnits.isSelected();
    boolean choiceConvertUnicode = cleanUpUnicode.isSelected();
    boolean choiceConvertToBiblatex = cleanUpBibLatex.isSelected();

    if (choiceRenamePDF && Globals.prefs.getBoolean(CleanUpAction.AKS_AUTO_NAMING_PDFS_AGAIN)) {
      CheckBoxMessage cbm =
          new CheckBoxMessage(
              Localization.lang("Auto-generating PDF-Names does not support undo. Continue?"),
              Localization.lang("Disable this confirmation dialog"),
              false);
      int answer =
          JOptionPane.showConfirmDialog(
              frame, cbm, Localization.lang("Autogenerate PDF Names"), JOptionPane.YES_NO_OPTION);
      if (cbm.isSelected()) {
        Globals.prefs.putBoolean(CleanUpAction.AKS_AUTO_NAMING_PDFS_AGAIN, false);
      }
      if (answer == JOptionPane.NO_OPTION) {
        cancelled = true;
        return;
      }
    }

    // first upgrade the external links
    // we have to use it separately as the Utils function generates a separate Named Compound
    if (choiceCleanUpUpgradeExternalLinks) {
      NamedCompound ce =
          Util.upgradePdfPsToFile(
              Arrays.asList(panel.getSelectedEntries()), new String[] {"pdf", "ps"});
      if (ce.hasEdits()) {
        panel.undoManager.addEdit(ce);
        panel.markBaseChanged();
        panel.updateEntryEditorIfShowing();
        panel.output(Localization.lang("Upgraded links."));
      }
    }

    for (BibtexEntry entry : panel.getSelectedEntries()) {
      // undo granularity is on entry level
      NamedCompound ce = new NamedCompound(Localization.lang("Cleanup entry"));

      if (choiceCleanUpSuperscripts) {
        doCleanUpSuperscripts(entry, ce);
      }
      if (choiceCleanUpDOI) {
        doCleanUpDOI(entry, ce);
      }
      if (choiceCleanUpMonth) {
        doCleanUpMonth(entry, ce);
      }
      if (choiceCleanUpPageNumbers) {
        doCleanUpPageNumbers(entry, ce);
      }
      if (choiceCleanUpDate) {
        doCleanUpDate(entry, ce);
      }

      fixWrongFileEntries(entry, ce);
      if (choiceMakePathsRelative) {
        doMakePathsRelative(entry, ce);
      }
      if (choiceRenamePDF) {
        doRenamePDFs(entry, ce);
      }
      if (choiceConvertHTML) {
        doConvertHTML(entry, ce);
      }
      if (choiceConvertUnits) {
        doConvertUnits(entry, ce);
      }
      if (choiceConvertCase) {
        doConvertCase(entry, ce);
      }
      if (choiceConvertLaTeX) {
        doConvertLaTeX(entry, ce);
      }
      if (choiceConvertUnicode) {
        doConvertUnicode(entry, ce);
      }
      if (choiceConvertToBiblatex) {
        convertToBiblatex(entry, ce);
      }

      ce.end();
      if (ce.hasEdits()) {
        modifiedEntriesCount++;
        panel.undoManager.addEdit(ce);
      }
    }
  }
  @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();
    }
  }