Пример #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();
 }
Пример #2
0
 @Override
 public void action() {
   try {
     NamedCompound ce = new NamedCompound(undoText);
     BibtexEntry[] bes = frame.basePanel().getSelectedEntries();
     if (bes == null) {
       return;
     }
     for (BibtexEntry be : bes) {
       // if (value==null) and then call nullField has been ommited as updatefield also handles
       // value==null
       SpecialFieldsUtils.updateField(c, value, be, ce, nullFieldIfValueIsTheSame);
     }
     ce.end();
     if (ce.hasEdits()) {
       frame.basePanel().undoManager.addEdit(ce);
       frame.basePanel().markBaseChanged();
       frame.basePanel().updateEntryEditorIfShowing();
       String outText;
       if (nullFieldIfValueIsTheSame) {
         outText = Localization.lang(doneTextPattern, Integer.toString(bes.length));
       } else {
         outText = Localization.lang(doneTextPattern, value, Integer.toString(bes.length));
       }
       frame.output(outText);
     } else {
       // if user does not change anything with his action, we do not do anything either
       // even no output message
     }
   } catch (Throwable ex) {
     ex.printStackTrace();
   }
 }
Пример #3
0
 @Override
 public void actionPerformed(ActionEvent e) {
   databases = frame.getTabbedPane().getTabCount();
   saved = 0;
   frame.output(Localization.lang("Saving all databases..."));
   Spin.off(this);
   run();
   frame.output(Localization.lang("Save all finished."));
 }
Пример #4
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;
  }
  private void storeSettings() throws FileNotFoundException {
    File f = null;
    if (newFile.isSelected()) {
      if (!newNameTf.getText().isEmpty()) {
        f = new File(newNameTf.getText());
      } // else {
      //    return; // Nothing to do.
      // }
    } else {
      f = new File(personalFile.getText());
    }

    if (f != null) {
      if (!f.exists()) {
        throw new FileNotFoundException(f.getAbsolutePath());
      }
      try (FileWriter fw = new FileWriter(f, false)) {
        for (JournalEntry entry : tableModel.getJournals()) {
          fw.write(entry.name);
          fw.write(" = ");
          fw.write(entry.abbreviation);
          fw.write(Globals.NEWLINE);
        }
      } catch (IOException e) {
        LOGGER.warn("Problem writing abbreviation file", e);
      }
      String filename = f.getPath();
      if ("".equals(filename)) {
        filename = null;
      }
      Globals.prefs.put(JabRefPreferences.PERSONAL_JOURNAL_LIST, filename);
    }

    // Store the list of external files set up:
    List<String> extFiles = new ArrayList<>();
    for (ExternalFileEntry efe : externals) {
      if (!"".equals(efe.getValue())) {
        extFiles.add(efe.getValue());
      }
    }
    Globals.prefs.putStringList(JabRefPreferences.EXTERNAL_JOURNAL_LISTS, extFiles);

    Abbreviations.initializeJournalNames(Globals.prefs);

    // Update the autocompleter for the "journal" field in all base panels,
    // so added journal names are available:
    for (int i = 0; i < frame.getBasePanelCount(); i++) {
      frame.getBasePanelAt(i).getAutoCompleters().addJournalListToAutoCompleter();
    }
  }
Пример #6
0
 @Override
 public void actionPerformed(ActionEvent e) {
   if (editor == null) {
     if (frame == null) {
       editor = new ExternalFileTypeEditor(dialog);
     } else {
       editor = new ExternalFileTypeEditor(frame);
     }
   }
   editor.setValues();
   editor.setVisible(true);
   if ((frame != null) && (frame.getCurrentBasePanel() != null)) {
     frame.getCurrentBasePanel().getMainTable().repaint();
   }
 }
Пример #7
0
 @Override
 public void run() {
   for (int i = 0; i < databases; i++) {
     if (i < frame.getTabbedPane().getTabCount()) {
       // System.out.println("Base "+i);
       BasePanel panel = frame.baseAt(i);
       if (panel.getFile() == null) {
         frame.showBaseAt(i);
       }
       panel.runCommand("save");
       // TODO: can we find out whether the save was actually done or not?
       saved++;
     }
   }
 }
Пример #8
0
 @Override
 public void actionPerformed(ActionEvent e) {
   boolean success = openLink();
   if (!success) {
     frame.output(Localization.lang("Unable to open link."));
   }
 }
Пример #9
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())));
 }
Пример #10
0
  /**
   * Opens a new shared database tab with the given {@link DBMSConnectionProperties}.
   *
   * @param dbmsConnectionProperties Connection data
   * @param raiseTab If <code>true</code> the new tab gets selected.
   */
  private void openNewSharedDatabaseTab(
      DBMSConnectionProperties dbmsConnectionProperties, boolean raiseTab)
      throws SQLException, DatabaseNotSupportedException {
    JabRefFrame frame = JabRefGUI.getMainFrame();
    BibDatabaseMode selectedMode = Globals.prefs.getDefaultBibDatabaseMode();
    BibDatabaseContext bibDatabaseContext =
        new BibDatabaseContext(
            new Defaults(selectedMode),
            DatabaseLocation.SHARED,
            Globals.prefs.getKeywordDelimiter());

    dbmsSynchronizer = bibDatabaseContext.getDBMSSynchronizer();
    dbmsSynchronizer.openSharedDatabase(dbmsConnectionProperties);
    frame.addTab(bibDatabaseContext, raiseTab);
    dbmsSynchronizer.registerListener(this);
    frame.output(
        Localization.lang(
            "Connection_to_%0_server_established.", dbmsConnectionProperties.getType().toString()));
  }
Пример #11
0
  @Subscribe
  public void listen(ConnectionLostEvent connectionLostEvent) {

    jabRefFrame.output(Localization.lang("Connection lost."));

    String[] options = {
      Localization.lang("Reconnect"),
      Localization.lang("Work offline"),
      Localization.lang("Close database")
    };

    int answer =
        JOptionPane.showOptionDialog(
            jabRefFrame,
            Localization.lang("The connection to the server has been terminated.") + "\n\n",
            Localization.lang("Connection lost"),
            JOptionPane.YES_NO_CANCEL_OPTION,
            JOptionPane.WARNING_MESSAGE,
            null,
            options,
            options[0]);

    if (answer == 0) {
      jabRefFrame.closeCurrentTab();
      OpenSharedDatabaseDialog openSharedDatabaseDialog = new OpenSharedDatabaseDialog(jabRefFrame);
      openSharedDatabaseDialog.setVisible(true);
    } else if (answer == 1) {
      connectionLostEvent.getBibDatabaseContext().convertToLocalDatabase();
      jabRefFrame.refreshTitleAndTabs();
      jabRefFrame.updateEnabledState();
      jabRefFrame.output(Localization.lang("Working offline."));
    } else {
      jabRefFrame.closeCurrentTab();
    }
  }
Пример #12
0
  @Subscribe
  public void listen(UpdateRefusedEvent updateRefusedEvent) {

    jabRefFrame.output(Localization.lang("Update refused."));

    new MergeSharedEntryDialog(
            jabRefFrame,
            dbmsSynchronizer,
            updateRefusedEvent.getLocalBibEntry(),
            updateRefusedEvent.getSharedBibEntry(),
            updateRefusedEvent.getBibDatabaseContext().getMode())
        .showMergeDialog();
  }
Пример #13
0
 @Override
 public void init() {
   cancelled = false;
   modifiedEntriesCount = 0;
   int numSelected = panel.getSelectedEntries().length;
   if (numSelected == 0) { // None selected. Inform the user to select entries first.
     JOptionPane.showMessageDialog(
         frame,
         Localization.lang("First select entries to clean up."),
         Localization.lang("Cleanup entry"),
         JOptionPane.INFORMATION_MESSAGE);
     cancelled = true;
     return;
   }
   frame.block();
   panel.output(
       Localization.lang("Doing a cleanup for %0 entries...", Integer.toString(numSelected)));
 }
Пример #14
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);
  }
Пример #15
0
  @Subscribe
  public void listen(SharedEntryNotPresentEvent event) {
    BasePanel panel = jabRefFrame.getCurrentBasePanel();
    EntryEditor entryEditor = panel.getCurrentEditor();

    panel
        .getUndoManager()
        .addEdit(new UndoableRemoveEntry(panel.getDatabase(), event.getBibEntry(), panel));

    if (Objects.nonNull(entryEditor) && (entryEditor.getEntry() == event.getBibEntry())) {
      JOptionPane.showMessageDialog(
          jabRefFrame,
          Localization.lang(
                  "The BibEntry you currently work on has been deleted on the shared side.")
              + "\n"
              + Localization.lang("You can restore the entry using the \"Undo\" operation."),
          Localization.lang("Shared entry is no longer present"),
          JOptionPane.INFORMATION_MESSAGE);

      SwingUtilities.invokeLater(() -> panel.hideBottomComponent());
    }
  }
Пример #16
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);
  }
  @Override
  public void actionPerformed(ActionEvent e) {
    panel = frame.getCurrentBasePanel();

    // Check if a BasePanel exists:
    if (panel == null) {
      return;
    }

    // Check if any entries are selected:
    entries = panel.getSelectedEntries();
    if (entries.length == 0) {
      JOptionPane.showMessageDialog(
          frame,
          Localization.lang("This operation requires one or more entries to be selected."),
          (String) getValue(Action.NAME),
          JOptionPane.ERROR_MESSAGE);
      return;
    }

    // If required, check that all entries have BibTeX keys defined:
    if (operation.requiresBibtexKeys()) {
      for (BibEntry entry : entries) {
        if ((entry.getCiteKey() == null) || entry.getCiteKey().trim().isEmpty()) {
          JOptionPane.showMessageDialog(
              frame,
              Localization.lang(
                  "This operation requires all selected entries to have BibTex keys defined."),
              (String) getValue(Action.NAME),
              JOptionPane.ERROR_MESSAGE);
          return;
        }
      }
    }

    // All set, call the operation in a new thread:
    JabRefExecutorService.INSTANCE.execute(this);
  }
Пример #18
0
  public RightClickMenu(JabRefFrame frame, BasePanel panel) {
    this.panel = panel;
    JMenu typeMenu = new ChangeEntryTypeMenu().getChangeEntryTypeMenu(panel);
    // Are multiple entries selected?
    boolean multiple = areMultipleEntriesSelected();

    // If only one entry is selected, get a reference to it for adapting the menu.
    BibEntry be = null;
    if (panel.getMainTable().getSelectedRowCount() == 1) {
      be = panel.getMainTable().getSelected().get(0);
    }

    addPopupMenuListener(this);

    JMenu copySpecialMenu = new JMenu(Localization.lang("Copy") + "...");
    copySpecialMenu.add(new GeneralAction(Actions.COPY_KEY, Localization.lang("Copy BibTeX key")));
    copySpecialMenu.add(
        new GeneralAction(Actions.COPY_CITE_KEY, Localization.lang("Copy \\cite{BibTeX key}")));
    copySpecialMenu.add(
        new GeneralAction(
            Actions.COPY_KEY_AND_TITLE, Localization.lang("Copy BibTeX key and title")));
    copySpecialMenu.add(
        new GeneralAction(
            Actions.EXPORT_TO_CLIPBOARD,
            Localization.lang("Export to clipboard"),
            IconTheme.JabRefIcon.EXPORT_TO_CLIPBOARD.getSmallIcon()));

    add(
        new GeneralAction(
            Actions.COPY, Localization.lang("Copy"), IconTheme.JabRefIcon.COPY.getSmallIcon()));
    add(copySpecialMenu);
    add(
        new GeneralAction(
            Actions.PASTE, Localization.lang("Paste"), IconTheme.JabRefIcon.PASTE.getSmallIcon()));
    add(
        new GeneralAction(
            Actions.CUT, Localization.lang("Cut"), IconTheme.JabRefIcon.CUT.getSmallIcon()));
    add(
        new GeneralAction(
            Actions.DELETE,
            Localization.lang("Delete"),
            IconTheme.JabRefIcon.DELETE_ENTRY.getSmallIcon()));
    add(
        new GeneralAction(
            Actions.PRINT_PREVIEW,
            Localization.lang("Print entry preview"),
            IconTheme.JabRefIcon.PRINTED.getSmallIcon()));
    addSeparator();

    add(
        new GeneralAction(
            Actions.SEND_AS_EMAIL,
            Localization.lang("Send as email"),
            IconTheme.JabRefIcon.EMAIL.getSmallIcon()));
    addSeparator();

    JMenu markSpecific = JabRefFrame.subMenu(Localization.menuTitle("Mark specific color"));
    for (int i = 0; i < EntryMarker.MAX_MARKING_LEVEL; i++) {
      markSpecific.add(new MarkEntriesAction(frame, i).getMenuItem());
    }

    if (multiple) {
      add(
          new GeneralAction(
              Actions.MARK_ENTRIES,
              Localization.lang("Mark entries"),
              IconTheme.JabRefIcon.MARK_ENTRIES.getSmallIcon()));
      add(markSpecific);
      add(
          new GeneralAction(
              Actions.UNMARK_ENTRIES,
              Localization.lang("Unmark entries"),
              IconTheme.JabRefIcon.UNMARK_ENTRIES.getSmallIcon()));
    } else if (be != null) {
      Optional<String> marked = be.getFieldOptional(FieldName.MARKED_INTERNAL);
      // We have to check for "" too as the marked field may be empty
      if ((!marked.isPresent()) || marked.get().isEmpty()) {
        add(
            new GeneralAction(
                Actions.MARK_ENTRIES,
                Localization.lang("Mark entry"),
                IconTheme.JabRefIcon.MARK_ENTRIES.getSmallIcon()));
        add(markSpecific);
      } else {
        add(markSpecific);
        add(
            new GeneralAction(
                Actions.UNMARK_ENTRIES,
                Localization.lang("Unmark entry"),
                IconTheme.JabRefIcon.UNMARK_ENTRIES.getSmallIcon()));
      }
    }

    if (Globals.prefs.getBoolean(JabRefPreferences.PREF_SPECIALFIELDSENABLED)) {
      if (Globals.prefs.getBoolean(JabRefPreferences.PREF_SHOWCOLUMN_RANKING)) {
        JMenu rankingMenu = new JMenu();
        RightClickMenu.populateSpecialFieldMenu(rankingMenu, Rank.getInstance(), frame);
        add(rankingMenu);
      }

      // TODO: multiple handling for relevance and quality-assurance
      // if multiple values are selected ("if (multiple)"), two options (set / clear) should be
      // offered
      // if one value is selected either set or clear should be offered
      if (Globals.prefs.getBoolean(JabRefPreferences.PREF_SHOWCOLUMN_RELEVANCE)) {
        add(Relevance.getInstance().getValues().get(0).getMenuAction(frame));
      }
      if (Globals.prefs.getBoolean(JabRefPreferences.PREF_SHOWCOLUMN_QUALITY)) {
        add(Quality.getInstance().getValues().get(0).getMenuAction(frame));
      }
      if (Globals.prefs.getBoolean(JabRefPreferences.PREF_SHOWCOLUMN_PRINTED)) {
        add(Printed.getInstance().getValues().get(0).getMenuAction(frame));
      }

      if (Globals.prefs.getBoolean(JabRefPreferences.PREF_SHOWCOLUMN_PRIORITY)) {
        JMenu priorityMenu = new JMenu();
        RightClickMenu.populateSpecialFieldMenu(priorityMenu, Priority.getInstance(), frame);
        add(priorityMenu);
      }

      if (Globals.prefs.getBoolean(JabRefPreferences.PREF_SHOWCOLUMN_READ)) {
        JMenu readStatusMenu = new JMenu();
        RightClickMenu.populateSpecialFieldMenu(readStatusMenu, ReadStatus.getInstance(), frame);
        add(readStatusMenu);
      }
    }

    addSeparator();

    add(
        new GeneralAction(Actions.OPEN_FOLDER, Localization.lang("Open folder")) {
          {
            if (!isFieldSetForSelectedEntry(FieldName.FILE)) {
              this.setEnabled(false);
            }
          }
        });

    add(
        new GeneralAction(
            Actions.OPEN_EXTERNAL_FILE,
            Localization.lang("Open file"),
            getFileIconForSelectedEntry()) {
          {
            if (!isFieldSetForSelectedEntry(FieldName.FILE)) {
              this.setEnabled(false);
            }
          }
        });

    add(
        new GeneralAction(
            Actions.OPEN_URL,
            Localization.lang("Open URL or DOI"),
            IconTheme.JabRefIcon.WWW.getSmallIcon()) {
          {
            if (!(isFieldSetForSelectedEntry(FieldName.URL)
                || isFieldSetForSelectedEntry(FieldName.DOI))) {
              this.setEnabled(false);
            }
          }
        });

    addSeparator();

    add(typeMenu);

    add(
        new GeneralAction(
            Actions.MERGE_WITH_FETCHED_ENTRY,
            Localization.lang(
                "Get BibTeX data from %0", FetchAndMergeEntry.getDisplayNameOfSupportedFields())) {
          {
            if (!(isAnyFieldSetForSelectedEntry(FetchAndMergeEntry.SUPPORTED_FIELDS))) {
              this.setEnabled(false);
            }
          }
        });
    add(frame.getMassSetField());
    add(
        new GeneralAction(
            Actions.ADD_FILE_LINK,
            Localization.lang("Attach file"),
            IconTheme.JabRefIcon.ATTACH_FILE.getSmallIcon()));
    add(frame.getManageKeywords());
    add(
        new GeneralAction(
            Actions.MERGE_ENTRIES,
            Localization.lang("Merge entries") + "...",
            IconTheme.JabRefIcon.MERGE_ENTRIES.getSmallIcon()) {

          {
            if (!(areExactlyTwoEntriesSelected())) {
              this.setEnabled(false);
            }
          }
        });

    addSeparator(); // for "add/move/remove to/from group" entries (appended here)

    groupAdd =
        new JMenuItem(new GeneralAction(Actions.ADD_TO_GROUP, Localization.lang("Add to group")));
    add(groupAdd);
    groupRemove =
        new JMenuItem(
            new GeneralAction(Actions.REMOVE_FROM_GROUP, Localization.lang("Remove from group")));
    add(groupRemove);

    groupMoveTo = add(new GeneralAction(Actions.MOVE_TO_GROUP, Localization.lang("Move to group")));
    add(groupMoveTo);

    // create disabledIcons for all menu entries
    frame.createDisabledIconsForMenuEntries(this);
  }
 @Override
 public void actionPerformed(ActionEvent evt) {
   frame.getCurrentBasePanel().runCommand(actionName);
 }
Пример #20
0
  /**
   * @param groupsRoot The original set of groups, which is required as undo information when all
   *     groups are cleared.
   */
  public AutoGroupDialog(
      JabRefFrame jabrefFrame,
      BasePanel basePanel,
      GroupSelector groupSelector,
      GroupTreeNode groupsRoot,
      String defaultField,
      String defaultRemove,
      String defaultDeliminator) {
    super(jabrefFrame, Localization.lang("Automatically create groups"), true);
    frame = jabrefFrame;
    gs = groupSelector;
    panel = basePanel;
    m_groupsRoot = groupsRoot;
    field.setText(defaultField);
    remove.setText(defaultRemove);
    deliminator.setText(defaultDeliminator);
    nd.setSelected(true);
    ActionListener okListener =
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) {
            dispose();

            GroupTreeNode autoGroupsRoot =
                new GroupTreeNode(
                    new ExplicitGroup(
                        Localization.lang("Automatically created groups"),
                        GroupHierarchyType.INCLUDING));
            Set<String> hs = null;
            String fieldText = field.getText();
            if (keywords.isSelected()) {
              if (nd.isSelected()) {
                hs =
                    Util.findDeliminatedWordsInField(
                        panel.getDatabase(),
                        field.getText().toLowerCase().trim(),
                        deliminator.getText());
              } else {
                hs =
                    Util.findAllWordsInField(
                        panel.getDatabase(),
                        field.getText().toLowerCase().trim(),
                        remove.getText());
              }
            } else if (authors.isSelected()) {
              List<String> fields = new ArrayList<>(2);
              fields.add("author");
              hs = Util.findAuthorLastNames(panel.getDatabase(), fields);
              fieldText = "author";
            } else if (editors.isSelected()) {
              List<String> fields = new ArrayList<>(2);
              fields.add("editor");
              hs = Util.findAuthorLastNames(panel.getDatabase(), fields);
              fieldText = "editor";
            }

            for (String keyword : hs) {
              KeywordGroup group =
                  new KeywordGroup(
                      keyword, fieldText, keyword, false, false, GroupHierarchyType.INDEPENDENT);
              autoGroupsRoot.add(new GroupTreeNode(group));
            }

            m_groupsRoot.add(autoGroupsRoot);
            NamedCompound ce = new NamedCompound(Localization.lang("Autogenerate groups"));
            UndoableAddOrRemoveGroup undo =
                new UndoableAddOrRemoveGroup(
                    gs, m_groupsRoot, autoGroupsRoot, UndoableAddOrRemoveGroup.ADD_NODE);
            undo.setRevalidate(true);
            ce.addEdit(undo);

            panel.markBaseChanged(); // a change always occurs
            gs.revalidateGroups();
            frame.output(Localization.lang("Created groups."));
            ce.end();
            panel.undoManager.addEdit(ce);
          }
        };
    remove.addActionListener(okListener);
    field.addActionListener(okListener);
    field.addCaretListener(this);
    AbstractAction cancelAction =
        new AbstractAction() {

          @Override
          public void actionPerformed(ActionEvent e) {
            dispose();
          }
        };
    JButton cancel = new JButton(Localization.lang("Cancel"));
    cancel.addActionListener(cancelAction);
    ok.addActionListener(okListener);
    // Key bindings:
    JPanel main = new JPanel();
    ActionMap am = main.getActionMap();
    InputMap im = main.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    im.put(frame.prefs().getKey(KeyBinds.CLOSE_DIALOG), "close");
    am.put("close", cancelAction);

    ButtonGroup bg = new ButtonGroup();
    bg.add(keywords);
    bg.add(authors);
    bg.add(editors);
    keywords.setSelected(true);

    FormBuilder b = FormBuilder.create();
    b.layout(
        new FormLayout(
            "left:20dlu, 4dlu, left:pref, 4dlu, fill:60dlu",
            "p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p"));
    b.add(keywords).xyw(1, 1, 5);
    b.add(Localization.lang("Field to group by") + ":").xy(3, 3);
    b.add(field).xy(5, 3);
    b.add(Localization.lang("Characters to ignore") + ":").xy(3, 5);
    b.add(remove).xy(5, 5);
    b.add(nd).xy(3, 7);
    b.add(deliminator).xy(5, 7);
    b.add(authors).xyw(1, 9, 5);
    b.add(editors).xyw(1, 11, 5);
    b.build();
    b.border(BorderFactory.createEmptyBorder(5, 5, 5, 5));

    JPanel opt = new JPanel();
    ButtonBarBuilder bb = new ButtonBarBuilder(opt);
    bb.addGlue();
    bb.addButton(ok);
    bb.addButton(cancel);
    bb.addGlue();

    main.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    opt.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    getContentPane().add(main, BorderLayout.CENTER);
    getContentPane().add(b.getPanel(), BorderLayout.CENTER);
    getContentPane().add(opt, BorderLayout.SOUTH);

    updateComponents();
    pack();
    PositionWindow.placeDialog(this, frame);
  }
Пример #21
0
 private void updateAfterPreferenceChanges() {
   setValues();
   ExportFormats.initAllExports(Globals.prefs.customExports.getCustomExportFormats(Globals.prefs));
   frame.removeCachedEntryEditors();
   Globals.prefs.updateEntryEditorTabList();
 }
Пример #22
0
  public PreferencesDialog(JabRefFrame parent) {
    super(parent, Localization.lang("JabRef preferences"), false);
    JabRefPreferences prefs = JabRefPreferences.getInstance();
    frame = parent;

    main = new JPanel();
    JPanel mainPanel = new JPanel();
    JPanel lower = new JPanel();

    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(mainPanel, BorderLayout.CENTER);
    getContentPane().add(lower, BorderLayout.SOUTH);

    final CardLayout cardLayout = new CardLayout();
    main.setLayout(cardLayout);

    List<PrefsTab> tabs = new ArrayList<>();
    tabs.add(new GeneralTab(prefs));
    tabs.add(new NetworkTab(prefs));
    tabs.add(new FileTab(frame, prefs));
    tabs.add(new FileSortTab(prefs));
    tabs.add(new EntryEditorPrefsTab(frame, prefs));
    tabs.add(new GroupsPrefsTab(prefs));
    tabs.add(new AppearancePrefsTab(prefs));
    tabs.add(new ExternalTab(frame, this, prefs));
    tabs.add(new TablePrefsTab(prefs));
    tabs.add(new TableColumnsTab(prefs, parent));
    tabs.add(new BibtexKeyPatternPrefTab(prefs, parent.getCurrentBasePanel()));
    tabs.add(new PreviewPrefsTab(prefs));
    tabs.add(new NameFormatterTab(prefs));
    tabs.add(new ImportSettingsTab(prefs));
    tabs.add(new XmpPrefsTab(prefs));
    tabs.add(new AdvancedTab(prefs));

    // add all tabs
    tabs.forEach(tab -> main.add((Component) tab, tab.getTabName()));

    mainPanel.setBorder(BorderFactory.createEtchedBorder());

    String[] tabNames = tabs.stream().map(PrefsTab::getTabName).toArray(String[]::new);
    JList<String> chooser = new JList<>(tabNames);
    chooser.setBorder(BorderFactory.createEtchedBorder());
    // Set a prototype value to control the width of the list:
    chooser.setPrototypeCellValue("This should be wide enough");
    chooser.setSelectedIndex(0);
    chooser.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    // Add the selection listener that will show the correct panel when
    // selection changes:
    chooser.addListSelectionListener(
        e -> {
          if (e.getValueIsAdjusting()) {
            return;
          }
          String o = chooser.getSelectedValue();
          cardLayout.show(main, o);
        });

    JPanel buttons = new JPanel();
    buttons.setLayout(new GridLayout(4, 1));
    buttons.add(importPreferences, 0);
    buttons.add(exportPreferences, 1);
    buttons.add(showPreferences, 2);
    buttons.add(resetPreferences, 3);

    JPanel westPanel = new JPanel();
    westPanel.setLayout(new BorderLayout());
    westPanel.add(chooser, BorderLayout.CENTER);
    westPanel.add(buttons, BorderLayout.SOUTH);
    mainPanel.setLayout(new BorderLayout());
    mainPanel.add(main, BorderLayout.CENTER);
    mainPanel.add(westPanel, BorderLayout.WEST);

    JButton ok = new JButton(Localization.lang("OK"));
    JButton cancel = new JButton(Localization.lang("Cancel"));
    ok.addActionListener(new OkAction());
    CancelAction cancelAction = new CancelAction();
    cancel.addActionListener(cancelAction);
    lower.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
    ButtonBarBuilder buttonBarBuilder = new ButtonBarBuilder(lower);
    buttonBarBuilder.addGlue();
    buttonBarBuilder.addButton(ok);
    buttonBarBuilder.addButton(cancel);
    buttonBarBuilder.addGlue();

    // Key bindings:
    KeyBinder.bindCloseDialogKeyToCancelAction(this.getRootPane(), cancelAction);

    // Import and export actions:
    exportPreferences.setToolTipText(Localization.lang("Export preferences to file"));
    exportPreferences.addActionListener(
        e -> {
          Optional<Path> path =
              new NewFileDialogs(frame, System.getProperty("user.home"))
                  .withExtension(FileExtensions.XML)
                  .saveNewFile();
          path.ifPresent(
              exportFile -> {
                try {
                  prefs.exportPreferences(exportFile.toString());
                } catch (JabRefException ex) {
                  LOGGER.warn(ex.getMessage(), ex);
                  JOptionPane.showMessageDialog(
                      PreferencesDialog.this,
                      ex.getLocalizedMessage(),
                      Localization.lang("Export preferences"),
                      JOptionPane.ERROR_MESSAGE);
                }
              });
        });

    importPreferences.setToolTipText(Localization.lang("Import preferences from file"));
    importPreferences.addActionListener(
        e -> {
          Optional<Path> fileName =
              new NewFileDialogs(frame, System.getProperty("user.home"))
                  .withExtension(FileExtensions.XML)
                  .openDlgAndGetSelectedFile();

          if (fileName.isPresent()) {
            try {
              prefs.importPreferences(fileName.get().toString());
              updateAfterPreferenceChanges();
              JOptionPane.showMessageDialog(
                  PreferencesDialog.this,
                  Localization.lang("You must restart JabRef for this to come into effect."),
                  Localization.lang("Import preferences"),
                  JOptionPane.WARNING_MESSAGE);
            } catch (JabRefException ex) {
              LOGGER.warn(ex.getMessage(), ex);
              JOptionPane.showMessageDialog(
                  PreferencesDialog.this,
                  ex.getLocalizedMessage(),
                  Localization.lang("Import preferences"),
                  JOptionPane.ERROR_MESSAGE);
            }
          }
        });

    showPreferences.addActionListener(
        e ->
            new PreferencesFilterDialog(new JabRefPreferencesFilter(Globals.prefs), frame)
                .setVisible(true));
    resetPreferences.addActionListener(
        e -> {
          if (JOptionPane.showConfirmDialog(
                  PreferencesDialog.this,
                  Localization.lang(
                      "Are you sure you want to reset all settings to default values?"),
                  Localization.lang("Reset preferences"),
                  JOptionPane.OK_CANCEL_OPTION)
              == JOptionPane.OK_OPTION) {
            try {
              prefs.clear();
              JOptionPane.showMessageDialog(
                  PreferencesDialog.this,
                  Localization.lang("You must restart JabRef for this to come into effect."),
                  Localization.lang("Reset preferences"),
                  JOptionPane.WARNING_MESSAGE);
            } catch (BackingStoreException ex) {
              LOGGER.warn(ex.getMessage(), ex);
              JOptionPane.showMessageDialog(
                  PreferencesDialog.this,
                  ex.getLocalizedMessage(),
                  Localization.lang("Reset preferences"),
                  JOptionPane.ERROR_MESSAGE);
            }
            updateAfterPreferenceChanges();
          }
        });

    setValues();

    pack();
  }
Пример #23
0
  private void performImport() {
    if (!connectedToDB) {
      return;
    }

    frame.output(Localization.lang("Attempting SQL import..."));
    DBExporterAndImporterFactory factory = new DBExporterAndImporterFactory();
    DatabaseImporter importer = factory.getImporter(dbs.getDbPreferences().getServerType());
    try {
      try (Connection conn = importer.connectToDB(dbs);
          Statement statement = conn.createStatement();
          ResultSet rs = statement.executeQuery(SQLUtil.queryAllFromTable("jabref_database"))) {

        Vector<Vector<String>> matrix = new Vector<>();

        while (rs.next()) {
          Vector<String> v = new Vector<>();
          v.add(rs.getString("database_name"));
          matrix.add(v);
        }

        if (matrix.isEmpty()) {
          JOptionPane.showMessageDialog(
              frame,
              Localization.lang("There are no available databases to be imported"),
              Localization.lang("Import from SQL database"),
              JOptionPane.INFORMATION_MESSAGE);
        } else {
          DBImportExportDialog dialogo =
              new DBImportExportDialog(frame, matrix, DBImportExportDialog.DialogType.IMPORTER);
          if (dialogo.removeAction) {
            String dbName = dialogo.selectedDB;
            DatabaseUtil.removeDB(dialogo, dbName, conn, databaseContext);
            performImport();
          } else if (dialogo.moreThanOne) {
            databases =
                importer.performImport(
                    dbs,
                    dialogo.listOfDBs,
                    frame.getCurrentBasePanel().getBibDatabaseContext().getMode());
            for (DBImporterResult res : databases) {
              databaseContext = res.getDatabaseContext();
              dbs.isConfigValid(true);
            }
            frame.output(
                Localization.lang(
                    "%0 databases will be imported", Integer.toString(databases.size())));
          } else {
            frame.output(Localization.lang("Importing canceled"));
          }
        }
      }
    } catch (Exception ex) {
      String preamble =
          Localization.lang("Could not import from SQL database for the following reason:");
      String errorMessage = SQLUtil.getExceptionMessage(ex);
      dbs.isConfigValid(false);
      JOptionPane.showMessageDialog(
          frame,
          preamble + '\n' + errorMessage,
          Localization.lang("Import from SQL database"),
          JOptionPane.ERROR_MESSAGE);
      frame.output(Localization.lang("Error importing from database"));
      LOGGER.error("Error importing from database", ex);
    }
  }