Пример #1
0
  // ##########################################
  //  usage:
  //  isDuplicate=checkForDuplicateKeyAndAdd( null, b.getKey() , issueDuplicateWarning);
  // ############################################
  // if the newkey already exists and is not the same as oldkey it will give a warning
  // else it will add the newkey to the to set and remove the oldkey
  public boolean checkForDuplicateKeyAndAdd(String oldKey, String newKey, boolean issueWarning) {
    // Globals.logger(" checkForDuplicateKeyAndAdd [oldKey = " + oldKey + "] [newKey = " + newKey +
    // "]");

    boolean duplicate = false;
    if (oldKey == null) { // this is a new entry so don't bother removing oldKey
      duplicate = addKeyToSet(newKey);
    } else {
      if (oldKey.equals(newKey)) { // were OK because the user did not change keys
        duplicate = false;
      } else { // user changed the key

        // removed the oldkey
        // But what if more than two have the same key?
        // this means that user can add another key and would not get a warning!
        // consider this: i add a key xxx, then i add another key xxx . I get a warning. I delete
        // the key xxx. JBM
        // removes this key from the allKey. then I add another key xxx. I don't get a warning!
        // i need a way to count the number of keys of each type
        // hashmap=>int (increment each time)

        removeKeyFromSet(oldKey);
        duplicate = addKeyToSet(newKey);
      }
    }
    if (duplicate && issueWarning) {
      JOptionPane.showMessageDialog(
          null,
          Globals.lang("Warning there is a duplicate key") + ":" + newKey,
          Globals.lang("Duplicate Key Warning"),
          JOptionPane.WARNING_MESSAGE); // , options);
    }
    return duplicate;
  }
Пример #2
0
 @Override
 public String getShortDescription() {
   StringBuilder sb = new StringBuilder();
   sb.append("<b>");
   if (Globals.prefs.getBoolean(JabRefPreferences.GROUP_SHOW_DYNAMIC)) {
     sb.append("<i>").append(StringUtil.quoteForHTML(getName())).append("</i>");
   } else {
     sb.append(StringUtil.quoteForHTML(getName()));
   }
   sb.append("</b> - ");
   sb.append(Globals.lang("dynamic group"));
   sb.append("<b>");
   sb.append(searchField);
   sb.append("</b>");
   sb.append(Globals.lang("contains"));
   sb.append(" <b>");
   sb.append(StringUtil.quoteForHTML(searchExpression));
   sb.append("</b>)");
   switch (getHierarchicalContext()) {
     case INCLUDING:
       sb.append(", ").append(Globals.lang("includes subgroups"));
       break;
     case REFINING:
       sb.append(", ").append(Globals.lang("refines supergroup"));
       break;
     default:
       break;
   }
   return sb.toString();
 }
  private void typeDeletion(String name) {
    BibtexEntryType type = BibtexEntryType.getType(name);

    if (type instanceof CustomEntryType) {
      if (BibtexEntryType.getStandardType(name) == null) {
        int reply =
            JOptionPane.showConfirmDialog(
                frame,
                Globals.lang(
                    "All entries of this " + "type will be declared " + "typeless. Continue?"),
                Globals.lang("Delete custom format") + " '" + StringUtil.nCase(name) + '\'',
                JOptionPane.YES_NO_OPTION,
                JOptionPane.WARNING_MESSAGE);
        if (reply != JOptionPane.YES_OPTION) {
          return;
        }
      }
      BibtexEntryType.removeType(name);
      updateTypesForEntries(StringUtil.nCase(name));
      changed.remove(name);
      reqLists.remove(name);
      optLists.remove(name);
      if (biblatexMode) {
        opt2Lists.remove(name);
      }
    }
    // messageLabel.setText("'"+type.getName()+"' "+
    //        Globals.lang("is a standard type."));

  }
Пример #4
0
 /** force the search button to be large enough for the longer of the two texts */
 private void setSearchButtonSizes() {
   search.setText(Globals.lang("Search specified field(s)"));
   Dimension size1 = search.getPreferredSize();
   search.setText(Globals.lang("Search all fields"));
   Dimension size2 = search.getPreferredSize();
   size2.width = Math.max(size1.width, size2.width);
   search.setMinimumSize(size2);
   search.setPreferredSize(size2);
 }
Пример #5
0
 /**
  * Find out how many hits were found.
  *
  * @param page
  */
 private int getNumberOfHits(String page, String marker, Pattern pattern) throws IOException {
   int ind = page.indexOf(marker);
   if (ind < 0) {
     System.out.println(page);
     throw new IOException(Globals.lang("Could not parse number of hits"));
   }
   String substring = page.substring(ind, page.length());
   Matcher m = pattern.matcher(substring);
   if (m.find()) {
     return Integer.parseInt(m.group(1));
   } else {
     throw new IOException(Globals.lang("Could not parse number of hits"));
   }
 }
Пример #6
0
  @Override
  public AbstractUndoableEdit add(BibtexEntry[] entries) {
    if (!supportsAdd()) {
      return null;
    }
    if (entries != null && entries.length > 0) {
      NamedCompound ce = new NamedCompound(Globals.lang("add entries to group"));
      boolean modified = false;
      for (BibtexEntry entry : entries) {
        if (!getSearchRule().applyRule(SearchRule.NULL_QUERY, entry)) {
          String oldContent = entry.getField(searchField);
          String pre = Globals.prefs.get(JabRefPreferences.GROUP_KEYWORD_SEPARATOR);
          String newContent = (oldContent == null ? "" : oldContent + pre) + searchExpression;
          entry.setField(searchField, newContent);

          // Store undo information.
          ce.addEdit(new UndoableFieldChange(entry, searchField, oldContent, newContent));
          modified = true;
        }
      }
      if (modified) {
        ce.end();
      }

      return modified ? ce : null;
    }

    return null;
  }
Пример #7
0
  @Override
  public AbstractUndoableEdit remove(BibtexEntry[] entries) {
    if (!supportsRemove()) {
      return null;
    }

    if (entries != null && entries.length > 0) {
      NamedCompound ce = new NamedCompound(Globals.lang("remove from group"));
      boolean modified = false;
      for (BibtexEntry entry : entries) {
        if (getSearchRule().applyRule(SearchRule.NULL_QUERY, entry)) {
          String oldContent = entry.getField(searchField);
          removeMatches(entry);
          // Store undo information.
          ce.addEdit(
              new UndoableFieldChange(entry, searchField, oldContent, entry.getField(searchField)));
          modified = true;
        }
      }
      if (modified) {
        ce.end();
      }

      return modified ? ce : null;
    }

    return null;
  }
  /**
   * @param owner the parent Window (Dialog or Frame)
   * @param frame the JabRef Frame
   * @param panel the currently selected BasePanel
   * @param modal should this dialog be modal?
   * @param metaData The metadata of the current database
   * @param fieldName the field this selector is initialized for. May be null.
   */
  public ContentSelectorDialog2(
      Window owner,
      JabRefFrame frame,
      BasePanel panel,
      boolean modal,
      MetaData metaData,
      String fieldName) {
    super(owner, Globals.lang("Setup selectors"));
    this.setModal(modal);
    this.metaData = metaData;
    this.frame = frame;
    this.panel = panel;
    this.currentField = fieldName;

    // help = new JButton(Globals.lang("Help"));
    // help.addActionListener(new HelpAction(frame.helpDiag, GUIGlobals.contentSelectorHelp,
    // "Help"));
    // help = new HelpAction(frame.helpDiag, GUIGlobals.contentSelectorHelp, "Help");
    initLayout();
    //  wordSelector.addItem(WORD_EMPTY_TEXT);

    setupFieldSelector();
    setupWordSelector();
    setupActions();
    Util.bindCloseDialogKeyToCancelAction(this.rootPane, cancel.getAction());
    int fieldInd = fieldListModel.indexOf(currentField);
    if (fieldInd >= 0) fieldList.setSelectedIndex(fieldInd);

    pack();
  }
Пример #9
0
  public void update() {
    if (!goOn) return;

    panel.output(
        Globals.lang(
            "Finished writing XMP for %0 file (%1 skipped, %2 errors).",
            String.valueOf(entriesChanged), String.valueOf(skipped), String.valueOf(errors)));
  }
Пример #10
0
  public void init() {

    // Get entries and check if it makes sense to perform this operation
    entries = panel.getSelectedEntries();

    if (entries.length == 0) {

      database = panel.getDatabase();
      entries = database.getEntries().toArray(new BibtexEntry[] {});

      if (entries.length == 0) {

        JOptionPane.showMessageDialog(
            panel,
            Globals.lang("This operation requires at least one entry."),
            Globals.lang("Write XMP-metadata"),
            JOptionPane.ERROR_MESSAGE);
        goOn = false;
        return;

      } else {

        int response =
            JOptionPane.showConfirmDialog(
                panel,
                Globals.lang("Write XMP-metadata for all PDFs in current database?"),
                Globals.lang("Write XMP-metadata"),
                JOptionPane.YES_NO_CANCEL_OPTION,
                JOptionPane.QUESTION_MESSAGE);

        if (response != JOptionPane.YES_OPTION) {
          goOn = false;
          return;
        }
      }
    }

    errors = entriesChanged = skipped = 0;

    if (optDiag == null) {
      optDiag = new OptionsDialog(panel.frame().getFrame());
    }
    optDiag.open();

    panel.output(Globals.lang("Writing XMP metadata..."));
  }
Пример #11
0
  @Override
  public void actionPerformed(ActionEvent e) {

    if (e.getSource() == escape) {
      incSearch = false;
      clearSearchLater();
    } else if (((e.getSource() == searchField) || (e.getSource() == search))
        && !increment.isSelected()
        && (panel != null)) {

      updatePrefs(); // Make sure the user's choices are recorded.
      if (searchField.getText().isEmpty()) {
        // An empty search field should cause the search to be cleared.
        clearSearchLater();
        return;
      }

      fireSearchlistenerEvent(searchField.getText());

      // Setup search parameters common to both normal and float.
      SearchRule searchRule;

      if (Globals.prefs.getBoolean(JabRefPreferences.REG_EXP_SEARCH)) {
        searchRule =
            new BasicRegexSearchRule(
                Globals.prefs.getBoolean(JabRefPreferences.CASE_SENSITIVE_SEARCH));
      } else {
        searchRule =
            new BasicSearchRule(Globals.prefs.getBoolean(JabRefPreferences.CASE_SENSITIVE_SEARCH));
      }

      try {
        // this searches specified fields if specified,
        // and all fields otherwise
        searchRule =
            new SearchExpression(
                Globals.prefs.getBoolean(JabRefPreferences.CASE_SENSITIVE_SEARCH),
                Globals.prefs.getBoolean(JabRefPreferences.REG_EXP_SEARCH));
      } catch (Exception ex) {
        // we'll do a search in all fields
      }

      if (!searchRule.validateSearchStrings(searchField.getText())) {
        panel.output(Globals.lang("Search failed: illegal search expression"));
        panel.stopShowingSearchResults();
        return;
      }
      SearchWorker worker = new SearchWorker(searchRule, searchField.getText());
      worker.getWorker().run();
      worker.getCallBack().update();
      escape.setEnabled(true);

      frame.basePanel().mainTable.setSelected(0);
    }
  }
Пример #12
0
  public static String getDescriptionForPreview(
      String field, String expr, boolean caseSensitive, boolean regExp) {
    String header =
        regExp
            ? Globals.lang(
                "This group contains entries whose <b>%0</b> field contains the regular expression <b>%1</b>",
                field, StringUtil.quoteForHTML(expr))
            : Globals.lang(
                "This group contains entries whose <b>%0</b> field contains the keyword <b>%1</b>",
                field, StringUtil.quoteForHTML(expr));
    String caseSensitiveText =
        caseSensitive ? Globals.lang("case sensitive") : Globals.lang("case insensitive");
    String footer =
        regExp
            ? Globals.lang("Entries cannot be manually assigned to or removed from this group.")
            : Globals.lang(
                "Additionally, entries whose <b>%0</b> field does not contain "
                    + "<b>%1</b> can be assigned manually to this group by selecting them "
                    + "then using either drag and drop or the context menu. "
                    + "This process adds the term <b>%1</b> to "
                    + "each entry's <b>%0</b> field. "
                    + "Entries can be removed manually from this group by selecting them "
                    + "then using the context menu. "
                    + "This process removes the term <b>%1</b> from "
                    + "each entry's <b>%0</b> field.",
                field, StringUtil.quoteForHTML(expr));

    return String.format("%s (%s). %s", header, caseSensitiveText, footer);
  }
Пример #13
0
  @Override
  public void actionPerformed(ActionEvent e) {
    BasePanel bp = frame.basePanel();
    if (bp == null) {
      return;
    }
    BibtexEntry[] entries = bp.getSelectedEntries();
    // Lazy creation of the dialog:
    if (diag == null) {
      createDialog();
    }
    cancelled = true;
    prepareDialog(entries.length > 0);
    Util.placeDialog(diag, frame);
    diag.setVisible(true);
    if (cancelled) {
      return;
    }

    Collection<BibtexEntry> entryList;
    // If all entries should be treated, change the entries array:
    if (all.isSelected()) {
      entryList = bp.database().getEntries();
    } else {
      entryList = Arrays.asList(entries);
    }
    String toSet = text.getText();
    if (toSet.isEmpty()) {
      toSet = null;
    }
    String[] fields = getFieldNames(field.getText().trim().toLowerCase());
    NamedCompound ce = new NamedCompound(Globals.lang("Set field"));
    if (rename.isSelected()) {
      if (fields.length > 1) {
        // TODO: message: can only rename a single field
      } else {
        ce.addEdit(
            Util.massRenameField(entryList, fields[0], renameTo.getText(), overwrite.isSelected()));
      }
    } else {
      for (String field1 : fields) {
        ce.addEdit(
            Util.massSetField(
                entryList, field1, set.isSelected() ? toSet : null, overwrite.isSelected()));
      }
    }
    ce.end();
    bp.undoManager.addEdit(ce);
    bp.markBaseChanged();
  }
Пример #14
0
  /** Creates a new instance of EntryCustomizationDialog2 */
  public EntryCustomizationDialog2(JabRefFrame frame) {
    super(frame, Globals.lang("Customize entry types"), false);

    this.frame = frame;
    initGui();
  }
Пример #15
0
public class SearchManager2 extends SidePaneComponent
    implements ActionListener, KeyListener, ItemListener, CaretListener {

  private final JabRefFrame frame;

  private final IncrementalSearcher incSearcher;
  private SearchResultsDialog searchDialog = null;

  private AutoCompleteListener autoCompleteListener = null;

  /** subscribed Objects */
  private final Vector<SearchTextListener> listeners = new Vector<SearchTextListener>();

  // private JabRefFrame frame;
  private final JTextField searchField = new JTextField("", 12);
  private final JPopupMenu settings = new JPopupMenu();
  private final JButton openset = new JButton(Globals.lang("Settings"));
  private final JButton escape = new JButton(Globals.lang("Clear"));
  /** This button's text will be set later. */
  private final JButton search = new JButton();

  private final JCheckBoxMenuItem searchReq;
  private final JCheckBoxMenuItem searchOpt;
  private final JCheckBoxMenuItem searchGen;
  private final JCheckBoxMenuItem searchAll;
  private final JCheckBoxMenuItem caseSensitive;
  private final JCheckBoxMenuItem regExpSearch;
  private final JCheckBoxMenuItem highLightWords;
  private final JCheckBoxMenuItem searchAutoComplete;

  private final JRadioButton increment;
  private final JRadioButton floatSearch;
  private final JRadioButton hideSearch;
  private final JRadioButton showResultsInDialog;
  private final JRadioButton searchAllBases;
  private final JCheckBoxMenuItem select;
  private boolean incSearch = false, startedFloatSearch = false, startedFilterSearch = false;

  private int incSearchPos = -1; // To keep track of where we are in

  // an incremental search. -1 means
  // that the search is inactive.

  public SearchManager2(JabRefFrame frame, SidePaneManager manager) {
    super(manager, GUIGlobals.getIconUrl("search"), Globals.lang("Search"));

    this.frame = frame;
    incSearcher = new IncrementalSearcher(Globals.prefs);

    // setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.magenta));

    searchReq =
        new JCheckBoxMenuItem(
            Globals.lang("Search required fields"),
            Globals.prefs.getBoolean(JabRefPreferences.SEARCH_REQ));
    searchOpt =
        new JCheckBoxMenuItem(
            Globals.lang("Search optional fields"),
            Globals.prefs.getBoolean(JabRefPreferences.SEARCH_OPT));
    searchGen =
        new JCheckBoxMenuItem(
            Globals.lang("Search general fields"),
            Globals.prefs.getBoolean(JabRefPreferences.SEARCH_GEN));
    searchAll =
        new JCheckBoxMenuItem(
            Globals.lang("Search all fields"),
            Globals.prefs.getBoolean(JabRefPreferences.SEARCH_ALL));
    regExpSearch =
        new JCheckBoxMenuItem(
            Globals.lang("Use regular expressions"),
            Globals.prefs.getBoolean(JabRefPreferences.REG_EXP_SEARCH));

    increment = new JRadioButton(Globals.lang("Incremental"), false);
    floatSearch = new JRadioButton(Globals.lang("Float"), true);
    hideSearch = new JRadioButton(Globals.lang("Filter"), true);
    showResultsInDialog = new JRadioButton(Globals.lang("Show results in dialog"), true);
    searchAllBases =
        new JRadioButton(
            Globals.lang("Global search"),
            Globals.prefs.getBoolean(JabRefPreferences.SEARCH_ALL_BASES));
    ButtonGroup types = new ButtonGroup();
    types.add(increment);
    types.add(floatSearch);
    types.add(hideSearch);
    types.add(showResultsInDialog);
    types.add(searchAllBases);

    select = new JCheckBoxMenuItem(Globals.lang("Select matches"), false);
    increment.setToolTipText(Globals.lang("Incremental search"));
    floatSearch.setToolTipText(Globals.lang("Gray out non-matching entries"));
    hideSearch.setToolTipText(Globals.lang("Hide non-matching entries"));
    showResultsInDialog.setToolTipText(Globals.lang("Show search results in a window"));

    // Add an item listener that makes sure we only listen for key events
    // when incremental search is turned on.
    increment.addItemListener(this);
    floatSearch.addItemListener(this);
    hideSearch.addItemListener(this);
    showResultsInDialog.addItemListener(this);
    // Add the global focus listener, so a menu item can see if this field was focused when
    // an action was called.
    searchField.addFocusListener(Globals.focusListener);

    if (searchAll.isSelected()) {
      searchReq.setEnabled(false);
      searchOpt.setEnabled(false);
      searchGen.setEnabled(false);
    }
    searchAll.addChangeListener(
        new ChangeListener() {

          @Override
          public void stateChanged(ChangeEvent event) {
            boolean state = !searchAll.isSelected();
            searchReq.setEnabled(state);
            searchOpt.setEnabled(state);
            searchGen.setEnabled(state);
          }
        });

    caseSensitive =
        new JCheckBoxMenuItem(
            Globals.lang("Case sensitive"),
            Globals.prefs.getBoolean(JabRefPreferences.CASE_SENSITIVE_SEARCH));

    highLightWords =
        new JCheckBoxMenuItem(
            Globals.lang("Highlight Words"),
            Globals.prefs.getBoolean(JabRefPreferences.HIGH_LIGHT_WORDS));

    searchAutoComplete =
        new JCheckBoxMenuItem(
            Globals.lang("Autocomplete names"),
            Globals.prefs.getBoolean(JabRefPreferences.SEARCH_AUTO_COMPLETE));
    settings.add(select);

    // 2005.03.29, trying to remove field category searches, to simplify
    // search usability.
    // settings.addSeparator();
    // settings.add(searchReq);
    // settings.add(searchOpt);
    // settings.add(searchGen);
    // settings.addSeparator();
    // settings.add(searchAll);
    // ---------------------------------------------------------------
    settings.addSeparator();
    settings.add(caseSensitive);
    settings.add(regExpSearch);
    settings.addSeparator();
    settings.add(highLightWords);
    settings.addSeparator();
    settings.add(searchAutoComplete);

    searchField.addActionListener(this);
    searchField.addCaretListener(this);
    search.addActionListener(this);
    searchField.addFocusListener(
        new FocusAdapter() {

          @Override
          public void focusGained(FocusEvent e) {
            if (increment.isSelected()) {
              searchField.setText("");
            }
          }

          @Override
          public void focusLost(FocusEvent e) {
            incSearch = false;
            incSearchPos = -1; // Reset incremental
            // search. This makes the
            // incremental search reset
            // once the user moves focus to
            // somewhere else.
            if (increment.isSelected()) {
              // searchField.setText("");
              // System.out.println("focuslistener");
            }
          }
        });
    escape.addActionListener(this);
    escape.setEnabled(false); // enabled after searching

    openset.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) {
            if (settings.isVisible()) {
              // System.out.println("oee");
              // settings.setVisible(false);
            } else {
              JButton src = (JButton) e.getSource();
              settings.show(src, 0, openset.getHeight());
            }
          }
        });

    searchAutoComplete.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent actionEvent) {
            Globals.prefs.putBoolean(
                JabRefPreferences.SEARCH_AUTO_COMPLETE, searchAutoComplete.isSelected());
            if (SearchManager2.this.frame.basePanel() != null) {
              SearchManager2.this.frame.basePanel().updateSearchManager();
            }
          }
        });
    Insets margin = new Insets(0, 2, 0, 2);
    // search.setMargin(margin);
    escape.setMargin(margin);
    openset.setMargin(margin);
    JButton help = new JButton(GUIGlobals.getImage("help"));
    int butSize = help.getIcon().getIconHeight() + 5;
    Dimension butDim = new Dimension(butSize, butSize);
    help.setPreferredSize(butDim);
    help.setMinimumSize(butDim);
    help.setMargin(margin);
    help.addActionListener(new HelpAction(Globals.helpDiag, GUIGlobals.searchHelp, "Help"));

    // Select the last used mode of search:
    if (Globals.prefs.getBoolean(JabRefPreferences.INCREMENT_S)) {
      increment.setSelected(true);
    } else if (Globals.prefs.getBoolean(JabRefPreferences.FLOAT_SEARCH)) {
      floatSearch.setSelected(true);
    } else if (Globals.prefs.getBoolean(JabRefPreferences.SHOW_SEARCH_IN_DIALOG)) {
      showResultsInDialog.setSelected(true);
    } else if (Globals.prefs.getBoolean(JabRefPreferences.SEARCH_ALL_BASES)) {
      searchAllBases.setSelected(true);
    } else {
      hideSearch.setSelected(true);
    }

    JPanel main = new JPanel();
    GridBagLayout gbl = new GridBagLayout();
    main.setLayout(gbl);
    GridBagConstraints con = new GridBagConstraints();
    con.gridwidth = GridBagConstraints.REMAINDER;
    con.fill = GridBagConstraints.BOTH;
    con.weightx = 1;

    gbl.setConstraints(searchField, con);
    main.add(searchField);
    // con.gridwidth = 1;
    gbl.setConstraints(search, con);
    main.add(search);
    con.gridwidth = GridBagConstraints.REMAINDER;
    gbl.setConstraints(escape, con);
    main.add(escape);
    con.insets = new Insets(0, 2, 0, 0);
    gbl.setConstraints(increment, con);
    main.add(increment);
    gbl.setConstraints(floatSearch, con);
    main.add(floatSearch);
    gbl.setConstraints(hideSearch, con);
    main.add(hideSearch);
    gbl.setConstraints(showResultsInDialog, con);
    main.add(showResultsInDialog);
    gbl.setConstraints(searchAllBases, con);
    main.add(searchAllBases);
    con.insets = new Insets(0, 0, 0, 0);
    JPanel pan = new JPanel();
    GridBagLayout gb = new GridBagLayout();
    gbl.setConstraints(pan, con);
    pan.setLayout(gb);
    con.weightx = 1;
    con.gridwidth = 1;
    gb.setConstraints(openset, con);
    pan.add(openset);
    con.weightx = 0;
    gb.setConstraints(help, con);
    pan.add(help);
    main.add(pan);
    main.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));

    setContentContainer(main);

    searchField.getInputMap().put(Globals.prefs.getKey("Repeat incremental search"), "repeat");

    searchField
        .getActionMap()
        .put(
            "repeat",
            new AbstractAction() {

              @Override
              public void actionPerformed(ActionEvent e) {
                if (increment.isSelected()) {
                  repeatIncremental();
                }
              }
            });
    searchField.getInputMap().put(Globals.prefs.getKey("Clear search"), "escape");
    searchField
        .getActionMap()
        .put(
            "escape",
            new AbstractAction() {

              @Override
              public void actionPerformed(ActionEvent e) {
                hideAway();
                // SearchManager2.this.actionPerformed(new ActionEvent(escape, 0, ""));
              }
            });
    setSearchButtonSizes();
    updateSearchButtonText();
  }

  public void setAutoCompleteListener(AutoCompleteListener listener) {
    this.autoCompleteListener = listener;
    updateKeyListeners();
  }

  /**
   * Add the correct key listeners to the search text field, depending on whether and autocomplete
   * listener has been set and whether incremental search is selected.
   */
  private void updateKeyListeners() {
    KeyListener[] listeners = searchField.getKeyListeners();
    for (KeyListener listener : listeners) {
      searchField.removeKeyListener(listener);
    }
    if (increment.isSelected()) {
      searchField.addKeyListener(this);
    } else {
      if (searchAutoComplete.isSelected() && (autoCompleteListener != null)) {
        searchField.addKeyListener(autoCompleteListener);
      }
    }
  }

  /**
   * Subscribe to the SearchListener and receive events, if the user searches for some thing. You
   * will receive a list of words
   *
   * @param l
   */
  public void addSearchListener(SearchTextListener l) {
    if (listeners.contains(l)) {
      return;
    } else {
      listeners.add(l);
    }
    // fire event for the new subscriber
    l.searchText(getSearchwords(searchField.getText()));
  }

  /**
   * Remove object from the SearchListener
   *
   * @param l
   */
  public void removeSearchListener(SearchTextListener l) {
    listeners.remove(l);
  }

  /**
   * parse the search string for valid words and return a list of words Like "The great Vikinger"
   * will be ["The","great","Vikinger"]
   *
   * @param t
   * @return
   */
  private ArrayList<String> getSearchwords(String t) {
    // for now ... just seperate words by whitespace
    String[] strings = t.split(" ");
    ArrayList<String> words = new ArrayList<String>(strings.length);
    Collections.addAll(words, strings);
    return words;
  }

  /**
   * Fires an event if a search was started / canceled
   *
   * @param t
   */
  private void fireSearchlistenerEvent(String t) {
    // parse the Search string to words
    ArrayList<String> words;
    if ((t == null) || (t.isEmpty())) {
      words = null;
    } else {
      words = getSearchwords(t);
    }

    // fire an event for every listener
    for (SearchTextListener s : listeners) {
      s.searchText(words);
    }
  }

  /** force the search button to be large enough for the longer of the two texts */
  private void setSearchButtonSizes() {
    search.setText(Globals.lang("Search specified field(s)"));
    Dimension size1 = search.getPreferredSize();
    search.setText(Globals.lang("Search all fields"));
    Dimension size2 = search.getPreferredSize();
    size2.width = Math.max(size1.width, size2.width);
    search.setMinimumSize(size2);
    search.setPreferredSize(size2);
  }

  /** Instantiate the search dialog, unless it has already been instantiated: */
  private void instantiateSearchDialog() {
    if (searchDialog == null) {
      searchDialog = new SearchResultsDialog(frame, Globals.lang("Search results"));
    }
  }

  public void updatePrefs() {
    Globals.prefs.putBoolean(JabRefPreferences.SEARCH_REQ, searchReq.isSelected());
    Globals.prefs.putBoolean(JabRefPreferences.SEARCH_OPT, searchOpt.isSelected());
    Globals.prefs.putBoolean(JabRefPreferences.SEARCH_GEN, searchGen.isSelected());
    Globals.prefs.putBoolean(JabRefPreferences.SEARCH_ALL, searchAll.isSelected());
    Globals.prefs.putBoolean(JabRefPreferences.INCREMENT_S, increment.isSelected());
    Globals.prefs.putBoolean(JabRefPreferences.SELECT_S, select.isSelected());
    Globals.prefs.putBoolean(JabRefPreferences.FLOAT_SEARCH, floatSearch.isSelected());
    Globals.prefs.putBoolean(JabRefPreferences.CASE_SENSITIVE_SEARCH, caseSensitive.isSelected());
    Globals.prefs.putBoolean(JabRefPreferences.REG_EXP_SEARCH, regExpSearch.isSelected());
    Globals.prefs.putBoolean(JabRefPreferences.HIGH_LIGHT_WORDS, highLightWords.isSelected());
    Globals.prefs.putBoolean(
        JabRefPreferences.SHOW_SEARCH_IN_DIALOG, showResultsInDialog.isSelected());
    Globals.prefs.putBoolean(JabRefPreferences.SEARCH_ALL_BASES, searchAllBases.isSelected());
  }

  public void startIncrementalSearch() {
    increment.setSelected(true);
    searchField.setText("");
    // System.out.println("startIncrementalSearch");
    searchField.requestFocus();
  }

  /**
   * Clears and focuses the search field if it is not focused. Otherwise, cycles to the next search
   * type.
   */
  public void startSearch() {
    if (increment.isSelected() && incSearch) {
      repeatIncremental();
      return;
    }
    if (!searchField.hasFocus()) {
      // searchField.setText("");
      searchField.selectAll();
      searchField.requestFocus();
    } else {
      if (increment.isSelected()) {
        floatSearch.setSelected(true);
      } else if (floatSearch.isSelected()) {
        hideSearch.setSelected(true);
      } else if (hideSearch.isSelected()) {
        showResultsInDialog.setSelected(true);
      } else if (showResultsInDialog.isSelected()) {
        searchAllBases.setSelected(true);
      } else {
        increment.setSelected(true);
      }
      increment.revalidate();
      increment.repaint();

      searchField.requestFocus();
    }
  }

  private void clearSearchLater() {
    if (panel == null) {
      return;
    }

    Runnable t =
        new Runnable() {

          @Override
          public void run() {
            clearSearch();
          }
        };
    // do this after the button action is over
    SwingUtilities.invokeLater(t);
  }

  @Override
  public void actionPerformed(ActionEvent e) {

    if (e.getSource() == escape) {
      incSearch = false;
      clearSearchLater();
    } else if (((e.getSource() == searchField) || (e.getSource() == search))
        && !increment.isSelected()
        && (panel != null)) {

      updatePrefs(); // Make sure the user's choices are recorded.
      if (searchField.getText().isEmpty()) {
        // An empty search field should cause the search to be cleared.
        clearSearchLater();
        return;
      }

      fireSearchlistenerEvent(searchField.getText());

      // Setup search parameters common to both normal and float.
      SearchRule searchRule;

      if (Globals.prefs.getBoolean(JabRefPreferences.REG_EXP_SEARCH)) {
        searchRule =
            new BasicRegexSearchRule(
                Globals.prefs.getBoolean(JabRefPreferences.CASE_SENSITIVE_SEARCH));
      } else {
        searchRule =
            new BasicSearchRule(Globals.prefs.getBoolean(JabRefPreferences.CASE_SENSITIVE_SEARCH));
      }

      try {
        // this searches specified fields if specified,
        // and all fields otherwise
        searchRule =
            new SearchExpression(
                Globals.prefs.getBoolean(JabRefPreferences.CASE_SENSITIVE_SEARCH),
                Globals.prefs.getBoolean(JabRefPreferences.REG_EXP_SEARCH));
      } catch (Exception ex) {
        // we'll do a search in all fields
      }

      if (!searchRule.validateSearchStrings(searchField.getText())) {
        panel.output(Globals.lang("Search failed: illegal search expression"));
        panel.stopShowingSearchResults();
        return;
      }
      SearchWorker worker = new SearchWorker(searchRule, searchField.getText());
      worker.getWorker().run();
      worker.getCallBack().update();
      escape.setEnabled(true);

      frame.basePanel().mainTable.setSelected(0);
    }
  }

  class SearchWorker extends AbstractWorker {

    private final SearchRule rule;
    private final String searchTerm;
    int hits = 0;

    public SearchWorker(SearchRule rule, String searchTerm) {
      this.rule = rule;
      this.searchTerm = searchTerm;
    }

    @Override
    public void run() {
      if (!searchAllBases.isSelected()) {
        // Search only the current database:
        for (BibtexEntry entry : panel.getDatabase().getEntries()) {

          boolean hit = rule.applyRule(searchTerm, entry) > 0;
          entry.setSearchHit(hit);
          if (hit) {
            hits++;
          }
        }
      } else {
        // Search all databases:
        for (int i = 0; i < frame.getTabbedPane().getTabCount(); i++) {
          BasePanel p = frame.baseAt(i);
          for (BibtexEntry entry : p.getDatabase().getEntries()) {

            boolean hit = rule.applyRule(searchTerm, entry) > 0;
            entry.setSearchHit(hit);
            if (hit) {
              hits++;
            }
          }
        }
      }
    }

    @Override
    public void update() {
      panel.output(Globals.lang("Searched database. Number of hits") + ": " + hits);

      // Show the result in the chosen way:
      if (searchAllBases.isSelected()) {
        // Search all databases. This means we need to use the search results dialog.
        // Turn off other search mode, if activated:
        if (startedFloatSearch) {
          panel.mainTable.stopShowingFloatSearch();
          startedFloatSearch = false;
        }
        if (startedFilterSearch) {
          panel.stopShowingSearchResults();
          startedFilterSearch = false;
        }
        // Make sure the search dialog is instantiated and cleared:
        instantiateSearchDialog();
        searchDialog.clear();
        for (int i = 0; i < frame.getTabbedPane().getTabCount(); i++) {
          BasePanel p = frame.baseAt(i);
          for (BibtexEntry entry : p.getDatabase().getEntries()) {
            if (entry.isSearchHit()) {
              searchDialog.addEntry(entry, p);
            }
          }
        }
        searchDialog.selectFirstEntry();
        searchDialog.setVisible(true);
      } else if (showResultsInDialog.isSelected()) {
        // Turn off other search mode, if activated:
        if (startedFloatSearch) {
          panel.mainTable.stopShowingFloatSearch();
          startedFloatSearch = false;
        }
        if (startedFilterSearch) {
          panel.stopShowingSearchResults();
          startedFilterSearch = false;
        }
        // Make sure the search dialog is instantiated and cleared:
        instantiateSearchDialog();
        searchDialog.clear();
        for (BibtexEntry entry : panel.getDatabase().getEntries()) {
          if (entry.isSearchHit()) {
            searchDialog.addEntry(entry, panel);
          }
        }
        searchDialog.selectFirstEntry();
        searchDialog.setVisible(true);
      } else if (hideSearch.isSelected()) {
        // Filtering search - removes non-hits from the table:
        if (startedFloatSearch) {
          panel.mainTable.stopShowingFloatSearch();
          startedFloatSearch = false;
        }
        startedFilterSearch = true;
        panel.setSearchMatcher(new SearchMatcher());

      } else {
        // Float search - floats hits to the top of the table:
        if (startedFilterSearch) {
          panel.stopShowingSearchResults();
          startedFilterSearch = false;
        }
        startedFloatSearch = true;
        panel.mainTable.showFloatSearch(new SearchMatcher());
      }

      // Afterwards, select all text in the search field.
      searchField.select(0, searchField.getText().length());
    }
  }

  private void clearSearch() {

    if (panel.isShowingFloatSearch()) {
      startedFloatSearch = false;
      panel.mainTable.stopShowingFloatSearch();
    } else if (panel.isShowingFilterSearch()) {
      startedFilterSearch = false;
      panel.stopShowingSearchResults();
    }

    // clear search means that nothing is searched for
    // even if a word is written in the text field,
    // nothing should be highlighted
    fireSearchlistenerEvent(null);

    // disable "Cancel" button to signal this to the user
    escape.setEnabled(false);
  }

  @Override
  public void itemStateChanged(ItemEvent e) {
    if (e.getSource() == increment) {
      if (startedFilterSearch || startedFloatSearch) {
        clearSearch();
      }
      updateSearchButtonText();

      // Make sure the correct key listener is activated:
      updateKeyListeners();

    } else /*if (e.getSource() == normal)*/ {
      updateSearchButtonText();

      // If this search type is disabled, remove reordering from
      // all databases.
      /*if ((panel != null) && increment.isSelected()) {
          clearSearch();
      } */
    }
  }

  private void repeatIncremental() {
    incSearchPos++;
    if (panel != null) {
      goIncremental();
    }
  }

  /**
   * Used for incremental search. Only activated when incremental is selected.
   *
   * <p>The variable incSearchPos keeps track of which entry was last checked.
   */
  @Override
  public void keyTyped(KeyEvent e) {
    if (e.isControlDown()) {
      return;
    }
    if (panel != null) {
      goIncremental();
    }
  }

  private void goIncremental() {
    incSearch = true;
    escape.setEnabled(true);
    SwingUtilities.invokeLater(
        new Runnable() {

          @Override
          public void run() {
            String text = searchField.getText();

            if (incSearchPos >= panel.getDatabase().getEntryCount()) {
              panel.output(
                  '\''
                      + text
                      + "' : "
                      + Globals.lang("Incremental search failed. Repeat to search from top.")
                      + '.');
              incSearchPos = -1;
              return;
            }

            if (searchField.getText().isEmpty()) {
              return;
            }
            if (incSearchPos < 0) {
              incSearchPos = 0;
            }
            BibtexEntry be = panel.mainTable.getEntryAt(incSearchPos);
            while (!incSearcher.search(text, be)) {
              incSearchPos++;
              if (incSearchPos < panel.getDatabase().getEntryCount()) {
                be = panel.mainTable.getEntryAt(incSearchPos);
              } else {
                panel.output(
                    '\''
                        + text
                        + "' : "
                        + Globals.lang("Incremental search failed. Repeat to search from top."));
                incSearchPos = -1;
                return;
              }
            }
            if (incSearchPos >= 0) {

              panel.selectSingleEntry(incSearchPos);
              panel.output('\'' + text + "' " + Globals.lang("found") + '.');
            }
          }
        });
  }

  @Override
  public void componentClosing() {
    frame.searchToggle.setSelected(false);
    if (panel != null) {
      if (startedFilterSearch || startedFloatSearch) {
        clearSearch();
      }
    }
  }

  @Override
  public void keyPressed(KeyEvent e) {}

  @Override
  public void keyReleased(KeyEvent e) {}

  @Override
  public void caretUpdate(CaretEvent e) {
    if (e.getSource() == searchField) {
      updateSearchButtonText();
    }
  }

  /**
   * Updates the text on the search button to reflect the type of search that will happen on click.
   */
  private void updateSearchButtonText() {
    search.setText(
        isSpecificSearch()
            ? Globals.lang("Search specified field(s)")
            : Globals.lang("Search all fields"));
  }

  private boolean isSpecificSearch() {
    return !increment.isSelected()
        && SearchExpression.isValid(
            caseSensitive.isSelected(), regExpSearch.isSelected(), searchField.getText());
  }

  @Override
  public void setActiveBasePanel(BasePanel panel) {
    super.setActiveBasePanel(panel);
    if (panel != null) {
      escape.setEnabled(panel.isShowingFloatSearch() || panel.isShowingFilterSearch());
    } else {
      escape.setEnabled(false);
    }
  }
}
Пример #16
0
public class IEEEXploreFetcher implements EntryFetcher {

  final CaseKeeperList caseKeeperList = new CaseKeeperList();
  private final CaseKeeper caseKeeper = new CaseKeeper();
  private final UnitFormatter unitFormatter = new UnitFormatter();

  private final HTMLConverter htmlConverter = new HTMLConverter();

  private final JCheckBox absCheckBox = new JCheckBox(Globals.lang("Include abstracts"), false);
  private final JRadioButton htmlButton = new JRadioButton(Globals.lang("HTML parser"));
  private final JRadioButton bibButton = new JRadioButton(Globals.lang("BibTeX importer"));

  private static final int MAX_FETCH = 100;
  private final int perPage = IEEEXploreFetcher.MAX_FETCH;
  private int hits = 0;
  private int unparseable = 0;
  private int parsed = 0;
  private int piv = 0;
  private boolean shouldContinue = false;
  private boolean includeAbstract = false;
  private boolean importBibtex = false;

  private String terms;
  private final String endUrl = "&rowsPerPage=" + Integer.toString(perPage) + "&pageNumber=";
  private String searchUrl;

  private final Pattern hitsPattern = Pattern.compile("([0-9,]+) Results");
  private final Pattern idPattern =
      Pattern.compile(
          "<input name=\'\' title=\'.*\' type=\'checkbox\'" + "value=\'\'\\s*id=\'([0-9]+)\'/>");
  private final Pattern typePattern = Pattern.compile("<span class=\"type\">\\s*(.+)");
  private final HashMap<String, String> fieldPatterns = new HashMap<String, String>();
  private final Pattern absPattern = Pattern.compile("<p>\\s*(.+)");

  Pattern stdEntryPattern = Pattern.compile(".*<strong>(.+)</strong><br>" + "\\s+(.+)");

  private final Pattern publicationPattern = Pattern.compile("(.*), \\d*\\.*\\s?(.*)");
  private final Pattern proceedingPattern = Pattern.compile("(.*?)\\.?\\s?Proceedings\\s?(.*)");
  Pattern abstractLinkPattern =
      Pattern.compile("<a href=\'(.+)\'>\\s*<span class=\"more\">View full.*</span> </a>");

  Pattern ieeeArticleNumberPattern = Pattern.compile("<a href=\".*arnumber=(\\d+).*\">");

  private final Pattern authorPattern =
      Pattern.compile("<span id=\"preferredName\" class=\"(.*)\">");
  private static final String IMPORT_URL = "http://ieeexplore.ieee.org/xpls/downloadCitations";
  private static final String START_URL =
      "http://ieeexplore.ieee.org/search/freesearchresult.jsp?queryText=";

  // Common words in IEEE Xplore that should always be

  public IEEEXploreFetcher() {
    super();
    CookieHandler.setDefault(new CookieManager());

    fieldPatterns.put("title", "<a\\s*href=[^<]+>\\s*(.+)\\s*</a>");
    // fieldPatterns.put("author", "</h3>\\s*(.+)");
    // fieldPatterns.put("author", "(?s)</h3>\\s*(.+)</br>");
    // fieldPatterns.put("author", "<span id=\"preferredName\" class=\"(.+)\">");
    fieldPatterns.put("volume", "Volume:\\s*([A-Za-z-]*\\d+)");
    fieldPatterns.put("number", "Issue:\\s*(\\d+)");
    // fieldPatterns.put("part", "Part (\\d+),&nbsp;(.+)");
    fieldPatterns.put("year", "(?:Copyright|Publication) Year:\\s*(\\d{4})");
    fieldPatterns.put("pages", "Page\\(s\\):\\s*(\\d+)\\s*-\\s*(\\d*)");
    // fieldPatterns.put("doi", "Digital Object Identifier:\\s*<a href=.*>(.+)</a>");
    fieldPatterns.put("doi", "<a href=\"http://dx.doi.org/(.+)\" target");
    fieldPatterns.put("url", "<a href=\"(/stamp/stamp[^\"]+)");
  }

  @Override
  public JPanel getOptionsPanel() {
    JPanel pan = new JPanel();
    pan.setLayout(new BorderLayout());
    htmlButton.setSelected(true);
    htmlButton.setEnabled(false);
    bibButton.setEnabled(false);

    ButtonGroup group = new ButtonGroup();
    group.add(htmlButton);
    group.add(bibButton);
    pan.add(absCheckBox, BorderLayout.NORTH);
    pan.add(htmlButton, BorderLayout.CENTER);
    pan.add(bibButton, BorderLayout.EAST);

    return pan;
  }

  @Override
  public boolean processQuery(String query, ImportInspector dialog, OutputPrinter status) {
    terms = query;
    piv = 0;
    shouldContinue = true;
    parsed = 0;
    unparseable = 0;
    int pageNumber = 1;

    searchUrl = makeUrl(pageNumber); // start at page 1

    try {
      URL url = new URL(searchUrl);
      String page = getResults(url);

      if (page.contains("You have entered an invalid search")) {
        status.showMessage(
            Globals.lang("You have entered an invalid search '%0'.", terms),
            Globals.lang("Search IEEEXplore"),
            JOptionPane.INFORMATION_MESSAGE);
        return false;
      }

      if (page.contains("Bad request")) {
        status.showMessage(
            Globals.lang("Bad Request '%0'.", terms),
            Globals.lang("Search IEEEXplore"),
            JOptionPane.INFORMATION_MESSAGE);
        return false;
      }

      if (page.contains("No results were found.")) {
        status.showMessage(
            Globals.lang("No entries found for the search string '%0'", terms),
            Globals.lang("Search IEEEXplore"),
            JOptionPane.INFORMATION_MESSAGE);
        return false;
      }

      if (page.contains("Error Page")) {
        status.showMessage(
            Globals.lang(
                "Intermittent errors on the IEEE Xplore server. Please try again in a while."),
            Globals.lang("Search IEEEXplore"),
            JOptionPane.INFORMATION_MESSAGE);
        return false;
      }

      hits = getNumberOfHits(page, "display-status", hitsPattern);

      includeAbstract = absCheckBox.isSelected();
      importBibtex = bibButton.isSelected();

      if (hits > IEEEXploreFetcher.MAX_FETCH) {
        status.showMessage(
            Globals.lang(
                "%0 entries found. To reduce server load, " + "only %1 will be downloaded.",
                new String[] {String.valueOf(hits), String.valueOf(IEEEXploreFetcher.MAX_FETCH)}),
            Globals.lang("Search IEEEXplore"),
            JOptionPane.INFORMATION_MESSAGE);
        hits = IEEEXploreFetcher.MAX_FETCH;
      }

      parse(dialog, page, 0, 1);
      int firstEntry = perPage;
      while (shouldContinue && firstEntry < hits) {
        pageNumber++;
        searchUrl = makeUrl(pageNumber);
        page = getResults(new URL(searchUrl));

        if (!shouldContinue) {
          break;
        }

        parse(dialog, page, 0, firstEntry + 1);
        firstEntry += perPage;
      }
      return true;
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (ConnectException e) {
      status.showMessage(
          Globals.lang("Connection to IEEEXplore failed"),
          Globals.lang("Search IEEEXplore"),
          JOptionPane.ERROR_MESSAGE);
    } catch (IOException e) {
      status.showMessage(
          Globals.lang(e.getMessage()),
          Globals.lang("Search IEEEXplore"),
          JOptionPane.ERROR_MESSAGE);
      e.printStackTrace();
    }
    return false;
  }

  @Override
  public String getTitle() {
    return "IEEEXplore";
  }

  @Override
  public String getHelpPage() {
    return "IEEEXploreHelp.html";
  }

  @Override
  public String getKeyName() {
    return "IEEEXplore";
  }

  /** This method is called by the dialog when the user has cancelled the import. */
  @Override
  public void stopFetching() {
    shouldContinue = false;
  }

  private String makeUrl(int startIndex) {
    return IEEEXploreFetcher.START_URL + terms.replaceAll(" ", "+") + endUrl + startIndex;
  }

  private void parse(ImportInspector dialog, String text, int startIndex, int firstEntryNumber) {
    piv = startIndex;
    int entryNumber = firstEntryNumber;

    if (importBibtex) {
      // TODO: Login
      ArrayList<String> idSelected = new ArrayList<String>();
      String id;
      while ((id = parseNextEntryId(text, piv)) != null && shouldContinue) {
        idSelected.add(id);
        entryNumber++;
      }
      try {
        BibtexDatabase dbase = parseBibtexDatabase(idSelected, includeAbstract);
        Collection<BibtexEntry> items = dbase.getEntries();
        for (BibtexEntry entry : items) {
          dialog.addEntry(cleanup(entry));
          dialog.setProgress(parsed + unparseable, hits);
          parsed++;
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
      // for
    } else {
      BibtexEntry entry;
      while ((entry = parseNextEntry(text, piv)) != null && shouldContinue) {
        if (entry.getField("title") != null) {
          dialog.addEntry(entry);
          dialog.setProgress(parsed + unparseable, hits);
          parsed++;
        }
        entryNumber++;
      }
    }
  }

  private BibtexDatabase parseBibtexDatabase(List<String> id, boolean abs) throws IOException {
    if (id.isEmpty()) {
      return null;
    }
    URLConnection conn;
    try {
      conn = new URL(IEEEXploreFetcher.IMPORT_URL).openConnection();
    } catch (MalformedURLException e) {
      e.printStackTrace();
      return null;
    }
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Referer", searchUrl);
    PrintWriter out = new PrintWriter(conn.getOutputStream());

    String recordIds = "";
    for (String anId : id) {
      recordIds += anId + " ";
    }
    recordIds = recordIds.trim();
    String citation = abs ? "citation-abstract" : "citation-only";

    String content =
        "recordIds="
            + recordIds.replaceAll(" ", "%20")
            + "&fromPageName=&citations-format="
            + citation
            + "&download-format=download-bibtex";
    System.out.println(content);
    out.write(content);
    out.flush();
    out.close();

    BufferedReader bufr = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuilder sb = new StringBuilder();
    char[] buffer = new char[256];
    while (true) {
      int bytesRead = bufr.read(buffer);
      if (bytesRead == -1) {
        break;
      }
      for (int i = 0; i < bytesRead; i++) {
        sb.append(buffer[i]);
      }
    }
    System.out.println(sb);

    ParserResult results = new BibtexParser(bufr).parse();
    bufr.close();
    return results.getDatabase();
  }

  private BibtexEntry cleanup(BibtexEntry entry) {
    if (entry == null) {
      return null;
    }

    // clean up title
    String title = entry.getField("title");
    if (title != null) {
      // USe the alt-text and replace image links
      title = title.replaceAll("[ ]?img src=[^ ]+ alt=\"([^\"]+)\">[ ]?", "\\$$1\\$");
      // Try to sort out most of the /spl / conversions
      // Deal with this specific nested type first
      title = title.replaceAll("/sub /spl infin//", "\\$_\\\\infty\\$");
      title = title.replaceAll("/sup /spl infin//", "\\$\\^\\\\infty\\$");
      // Replace general expressions
      title = title.replaceAll("/[sS]pl ([^/]+)/", "\\$\\\\$1\\$");
      // Deal with subscripts and superscripts
      if (Globals.prefs.getBoolean(JabRefPreferences.USE_CONVERT_TO_EQUATION)) {
        title = title.replaceAll("/sup ([^/]+)/", "\\$\\^\\{$1\\}\\$");
        title = title.replaceAll("/sub ([^/]+)/", "\\$_\\{$1\\}\\$");
        title = title.replaceAll("\\(sup\\)([^(]+)\\(/sup\\)", "\\$\\^\\{$1\\}\\$");
        title = title.replaceAll("\\(sub\\)([^(]+)\\(/sub\\)", "\\_\\{$1\\}\\$");
      } else {
        title = title.replaceAll("/sup ([^/]+)/", "\\\\textsuperscript\\{$1\\}");
        title = title.replaceAll("/sub ([^/]+)/", "\\\\textsubscript\\{$1\\}");
        title = title.replaceAll("\\(sup\\)([^(]+)\\(/sup\\)", "\\\\textsuperscript\\{$1\\}");
        title = title.replaceAll("\\(sub\\)([^(]+)\\(/sub\\)", "\\\\textsubscript\\{$1\\}");
      }

      // Replace \infin with \infty
      title = title.replaceAll("\\\\infin", "\\\\infty");

      // Unit formatting
      if (Globals.prefs.getBoolean(JabRefPreferences.USE_UNIT_FORMATTER_ON_SEARCH)) {
        title = unitFormatter.format(title);
      }

      // Automatic case keeping
      if (Globals.prefs.getBoolean(JabRefPreferences.USE_CASE_KEEPER_ON_SEARCH)) {
        title = caseKeeper.format(title);
      }
      // Write back
      entry.setField("title", title);
    }

    // clean up author
    /*   	String author = (String)entry.getField("author");
       	if (author != null) {
        if (author.indexOf("a href=") >= 0) {  // Author parsing failed because it was empty
    	entry.setField("author","");  // Maybe not needed anymore due to another change
        } else {
        	author = author.replaceAll("\\s+", " ");
        	author = author.replaceAll("\\.", ". ");
        	author = author.replaceAll("([^;]+),([^;]+),([^;]+)","$1,$3,$2"); // Change order in case of Jr. etc
        	author = author.replaceAll("  ", " ");
        	author = author.replaceAll("\\. -", ".-");
                   author = author.replaceAll("; ", " and ");
        	author = author.replaceAll(" ,", ",");
        	author = author.replaceAll("  ", " ");
        	author = author.replaceAll("[ ,;]+$", "");
        	entry.setField("author", author);
        }
    }*/
    // clean up month
    String month = entry.getField("month");
    if (month != null && !month.isEmpty()) {
      month = month.replaceAll("\\.", "");
      month = month.toLowerCase();

      Pattern monthPattern = Pattern.compile("(\\d*+)\\s*([a-z]*+)-*(\\d*+)\\s*([a-z]*+)");
      Matcher mm = monthPattern.matcher(month);
      String date = month;
      if (mm.find()) {
        if (mm.group(3).isEmpty()) {
          if (!mm.group(2).isEmpty()) {
            date = "#" + mm.group(2).substring(0, 3) + "#";
            if (!mm.group(1).isEmpty()) {
              date += " " + mm.group(1) + ",";
            }
          } else {
            date = mm.group(1) + ",";
          }
        } else if (mm.group(2).isEmpty()) {
          if (!mm.group(4).isEmpty()) {
            date =
                "#" + mm.group(4).substring(0, 3) + "# " + mm.group(1) + "--" + mm.group(3) + ",";
          } else {
            date += ",";
          }
        } else {
          date =
              "#"
                  + mm.group(2).substring(0, 3)
                  + "# "
                  + mm.group(1)
                  + "--#"
                  + mm.group(4).substring(0, 3)
                  + "# "
                  + mm.group(3)
                  + ",";
        }
      }
      // date = date.trim();
      // if (!date.isEmpty()) {
      entry.setField("month", date);
      // }
    }

    // clean up pages
    String field = "pages";
    String pages = entry.getField(field);
    if (pages != null) {
      String[] pageNumbers = pages.split("-");
      if (pageNumbers.length == 2) {
        if (pageNumbers[0].equals(pageNumbers[1])) { // single page
          entry.setField(field, pageNumbers[0]);
        } else {
          entry.setField(field, pages.replaceAll("-", "--"));
        }
      }
    }

    // clean up publication field
    BibtexEntryType type = entry.getType();
    String sourceField = "";
    if (type.getName().equals("Article")) {
      sourceField = "journal";
      entry.clearField("booktitle");
    } else if (type.getName().equals("Inproceedings")) {
      sourceField = "booktitle";
    }
    String fullName = entry.getField(sourceField);
    if (fullName != null) {
      if (type.getName().equals("Article")) {
        int ind = fullName.indexOf(": Accepted for future publication");
        if (ind > 0) {
          fullName = fullName.substring(0, ind);
          entry.setField("year", "to be published");
          entry.clearField("month");
          entry.clearField("pages");
          entry.clearField("number");
        }
        String[] parts = fullName.split("[\\[\\]]"); // [see also...], [legacy...]
        fullName = parts[0];
        if (parts.length == 3) {
          fullName += parts[2];
        }
        if (entry.getField("note").equals("Early Access")) {
          entry.setField("year", "to be published");
          entry.clearField("month");
          entry.clearField("pages");
          entry.clearField("number");
        }
      } else {
        fullName =
            fullName
                .replace("Conference Proceedings", "Proceedings")
                .replace("Proceedings of", "Proceedings")
                .replace("Proceedings.", "Proceedings");
        fullName = fullName.replaceAll("International", "Int.");
        fullName = fullName.replaceAll("Symposium", "Symp.");
        fullName = fullName.replaceAll("Conference", "Conf.");
        fullName = fullName.replaceAll(" on", " ").replace("  ", " ");
      }

      Matcher m1 = publicationPattern.matcher(fullName);
      String abrvPattern = ".*[^,] '?\\d+\\)?";
      if (m1.find()) {
        String prefix = m1.group(2).trim();
        String postfix = m1.group(1).trim();
        String abrv = "";
        String[] parts = prefix.split("\\. ", 2);
        if (parts.length == 2) {
          if (parts[0].matches(abrvPattern)) {
            prefix = parts[1];
            abrv = parts[0];
          } else {
            prefix = parts[0];
            abrv = parts[1];
          }
        }
        if (!prefix.matches(abrvPattern)) {
          fullName = prefix + " " + postfix + " " + abrv;
          fullName = fullName.trim();
        } else {
          fullName = postfix + " " + prefix;
        }
      }
      if (type.getName().equals("Article")) {
        fullName = fullName.replace(" - ", "-"); // IEE Proceedings-

        fullName = fullName.trim();
        if (Globals.prefs.getBoolean(JabRefPreferences.USE_IEEE_ABRV)) {
          fullName = Globals.journalAbbrev.getMedlineAbbreviation(fullName).orElse(fullName);
        }
      }
      if (type.getName().equals("Inproceedings")) {
        Matcher m2 = proceedingPattern.matcher(fullName);
        if (m2.find()) {
          String prefix = m2.group(2);
          String postfix = m2.group(1).replaceAll("\\.$", "");
          if (!prefix.matches(abrvPattern)) {
            String abrv = "";

            String[] parts = postfix.split("\\. ", 2);
            if (parts.length == 2) {
              if (parts[0].matches(abrvPattern)) {
                postfix = parts[1];
                abrv = parts[0];
              } else {
                postfix = parts[0];
                abrv = parts[1];
              }
            }
            fullName = prefix.trim() + " " + postfix.trim() + " " + abrv;

          } else {
            fullName = postfix.trim() + " " + prefix.trim();
          }
        }

        fullName = fullName.trim();

        fullName =
            fullName.replaceAll("^[tT]he ", "").replaceAll("^\\d{4} ", "").replaceAll("[,.]$", "");
        String year = entry.getField("year");
        fullName = fullName.replaceAll(", " + year + "\\.?", "");

        if (!fullName.contains("Abstract")
            && !fullName.contains("Summaries")
            && !fullName.contains("Conference Record")) {
          fullName = "Proc. " + fullName;
        }
      }
      entry.setField(sourceField, fullName);
    }

    // clean up abstract
    String abstr = entry.getField("abstract");
    if (abstr != null) {
      // Try to sort out most of the /spl / conversions
      // Deal with this specific nested type first
      abstr = abstr.replaceAll("/sub /spl infin//", "\\$_\\\\infty\\$");
      abstr = abstr.replaceAll("/sup /spl infin//", "\\$\\^\\\\infty\\$");
      // Replace general expressions
      abstr = abstr.replaceAll("/[sS]pl ([^/]+)/", "\\$\\\\$1\\$");
      // Deal with subscripts and superscripts
      if (Globals.prefs.getBoolean(JabRefPreferences.USE_CONVERT_TO_EQUATION)) {
        abstr = abstr.replaceAll("/sup ([^/]+)/", "\\$\\^\\{$1\\}\\$");
        abstr = abstr.replaceAll("/sub ([^/]+)/", "\\$_\\{$1\\}\\$");
        abstr = abstr.replaceAll("\\(sup\\)([^(]+)\\(/sup\\)", "\\$\\^\\{$1\\}\\$");
        abstr = abstr.replaceAll("\\(sub\\)([^(]+)\\(/sub\\)", "\\_\\{$1\\}\\$");
      } else {
        abstr = abstr.replaceAll("/sup ([^/]+)/", "\\\\textsuperscript\\{$1\\}");
        abstr = abstr.replaceAll("/sub ([^/]+)/", "\\\\textsubscript\\{$1\\}");
        abstr = abstr.replaceAll("\\(sup\\)([^(]+)\\(/sup\\)", "\\\\textsuperscript\\{$1\\}");
        abstr = abstr.replaceAll("\\(sub\\)([^(]+)\\(/sub\\)", "\\\\textsubscript\\{$1\\}");
      }
      // Replace \infin with \infty
      abstr = abstr.replaceAll("\\\\infin", "\\\\infty");
      // Write back
      entry.setField("abstract", abstr);
    }

    // Clean up url
    String url = entry.getField("url");
    if (url != null) {
      entry.setField("url", "http://ieeexplore.ieee.org" + url.replace("tp=&", ""));
    }
    return entry;
  }

  private String parseNextEntryId(String allText, int startIndex) {
    int index = allText.indexOf("<div class=\"select", startIndex);
    int endIndex = allText.indexOf("</div>", index);

    if (index >= 0 && endIndex > 0) {
      String text = allText.substring(index, endIndex);
      endIndex += 6;
      piv = endIndex;
      // parse id
      Matcher idMatcher = idPattern.matcher(text);
      // add id into a vector
      if (idMatcher.find()) {
        return idMatcher.group(1);
      }
    }
    return null;
  }

  private BibtexEntry parseNextEntry(String allText, int startIndex) {
    BibtexEntry entry = null;

    int index = allText.indexOf("<div class=\"detail", piv);
    int endIndex = allText.indexOf("</div>", index);

    if (index >= 0 && endIndex > 0) {
      endIndex += 6;
      piv = endIndex;
      String text = allText.substring(index, endIndex);

      BibtexEntryType type = null;
      String sourceField = null;

      String typeName = "";
      Matcher typeMatcher = typePattern.matcher(text);
      if (typeMatcher.find()) {
        typeName = typeMatcher.group(1);
        if (typeName.equalsIgnoreCase("IEEE Journals &amp; Magazines")
            || typeName.equalsIgnoreCase("IEEE Early Access Articles")
            || typeName.equalsIgnoreCase("IET Journals &amp; Magazines")
            || typeName.equalsIgnoreCase("AIP Journals &amp; Magazines")
            || typeName.equalsIgnoreCase("AVS Journals &amp; Magazines")
            || typeName.equalsIgnoreCase("IBM Journals &amp; Magazines")
            || typeName.equalsIgnoreCase("TUP Journals &amp; Magazines")
            || typeName.equalsIgnoreCase("BIAI Journals &amp; Magazines")) {
          type = BibtexEntryType.getType("article");
          sourceField = "journal";
        } else if (typeName.equalsIgnoreCase("IEEE Conference Publications")
            || typeName.equalsIgnoreCase("IET Conference Publications")
            || typeName.equalsIgnoreCase("VDE Conference Publications")) {
          type = BibtexEntryType.getType("inproceedings");
          sourceField = "booktitle";
        } else if (typeName.equalsIgnoreCase("IEEE Standards")
            || typeName.equalsIgnoreCase("Standards")) {
          type = BibtexEntryType.getType("standard");
          sourceField = "number";
        } else if (typeName.equalsIgnoreCase("IEEE eLearning Library Courses")) {
          type = BibtexEntryType.getType("Electronic");
          sourceField = "note";
        } else if (typeName.equalsIgnoreCase("Wiley-IEEE Press eBook Chapters")
            || typeName.equalsIgnoreCase("MIT Press eBook Chapters")
            || typeName.equalsIgnoreCase("IEEE USA Books &amp; eBooks")) {
          type = BibtexEntryType.getType("inCollection");
          sourceField = "booktitle";
        }
      }

      if (type == null) {
        type = BibtexEntryType.getType("misc");
        sourceField = "note";
        System.err.println("Type detection failed. Use MISC instead.");
        unparseable++;
        System.err.println(text);
      }

      entry = new BibtexEntry(IdGenerator.next(), type);

      if (typeName.equalsIgnoreCase("IEEE Standards")) {
        entry.setField("organization", "IEEE");
      }

      if (typeName.equalsIgnoreCase("Wiley-IEEE Press eBook Chapters")) {
        entry.setField("publisher", "Wiley-IEEE Press");
      } else if (typeName.equalsIgnoreCase("MIT Press eBook Chapters")) {
        entry.setField("publisher", "MIT Press");
      } else if (typeName.equalsIgnoreCase("IEEE USA Books &amp; eBooks")) {
        entry.setField("publisher", "IEEE USA");
      }

      if (typeName.equalsIgnoreCase("IEEE Early Access Articles")) {
        entry.setField("note", "Early Access");
      }

      Set<String> fields = fieldPatterns.keySet();
      for (String field : fields) {
        Matcher fieldMatcher = Pattern.compile(fieldPatterns.get(field)).matcher(text);
        if (fieldMatcher.find()) {
          entry.setField(field, htmlConverter.format(fieldMatcher.group(1)));
          if (field.equals("title") && fieldMatcher.find()) {
            String sec_title = htmlConverter.format(fieldMatcher.group(1));
            if (entry.getType() == BibtexEntryType.getStandardType("standard")) {
              sec_title = sec_title.replaceAll("IEEE Std ", "");
            }
            entry.setField(sourceField, sec_title);
          }
          if (field.equals("pages") && fieldMatcher.groupCount() == 2) {
            entry.setField(field, fieldMatcher.group(1) + "-" + fieldMatcher.group(2));
          }
        }
      }

      Matcher authorMatcher = authorPattern.matcher(text);
      // System.out.println(text);
      StringBuilder authorNames = new StringBuilder("");
      int authorCount = 0;
      while (authorMatcher.find()) {
        if (authorCount >= 1) {
          authorNames.append(" and ");
        }
        authorNames.append(htmlConverter.format(authorMatcher.group(1)));
        // System.out.println(authorCount + ": " + authorMatcher.group(1));
        authorCount++;
      }
      entry.setField("author", authorNames.toString());
      if (entry.getField("author") == null
          || entry.getField("author").startsWith("a href")
          || entry
              .getField("author")
              .startsWith("Topic(s)")) { // Fix for some documents without authors
        entry.setField("author", "");
      }
      if (entry.getType() == BibtexEntryType.getStandardType("inproceedings")
          && entry.getField("author").equals("")) {
        entry.setType(BibtexEntryType.getStandardType("proceedings"));
      }

      if (includeAbstract) {
        index = text.indexOf("id=\"abstract");
        if (index >= 0) {
          endIndex = text.indexOf("</div>", index) + 6;

          text = text.substring(index, endIndex);
          Matcher absMatcher = absPattern.matcher(text);
          if (absMatcher.find()) {
            // Clean-up abstract
            String abstr = absMatcher.group(1);
            abstr = abstr.replaceAll("<span class='snippet'>([\\w]+)</span>", "$1");

            entry.setField("abstract", htmlConverter.format(abstr));
          }
        }
      }
    }

    if (entry == null) {
      return null;
    } else {
      return cleanup(entry);
    }
  }

  /**
   * Find out how many hits were found.
   *
   * @param page
   */
  private int getNumberOfHits(String page, String marker, Pattern pattern) throws IOException {
    int ind = page.indexOf(marker);
    if (ind < 0) {
      System.out.println(page);
      throw new IOException(Globals.lang("Could not parse number of hits"));
    }
    String substring = page.substring(ind, page.length());
    Matcher m = pattern.matcher(substring);
    if (m.find()) {
      return Integer.parseInt(m.group(1));
    } else {
      throw new IOException(Globals.lang("Could not parse number of hits"));
    }
  }

  /**
   * Download the URL and return contents as a String.
   *
   * @param source
   * @return
   * @throws IOException
   */
  private String getResults(URL source) throws IOException {

    InputStream in = source.openStream();
    StringBuilder sb = new StringBuilder();
    byte[] buffer = new byte[256];
    while (true) {
      int bytesRead = in.read(buffer);
      if (bytesRead == -1) {
        break;
      }
      for (int i = 0; i < bytesRead; i++) {
        sb.append((char) buffer[i]);
      }
    }
    return sb.toString();
  }

  /**
   * Read results from a file instead of an URL. Just for faster debugging.
   *
   * @param f
   * @return
   * @throws IOException
   */
  public String getResultsFromFile(File f) throws IOException {
    InputStream in = new BufferedInputStream(new FileInputStream(f));
    StringBuilder sb = new StringBuilder();
    byte[] buffer = new byte[256];
    while (true) {
      int bytesRead = in.read(buffer);
      if (bytesRead == -1) {
        break;
      }
      for (int i = 0; i < bytesRead; i++) {
        sb.append((char) buffer[i]);
      }
    }
    return sb.toString();
  }
}
Пример #17
0
 /** Instantiate the search dialog, unless it has already been instantiated: */
 private void instantiateSearchDialog() {
   if (searchDialog == null) {
     searchDialog = new SearchResultsDialog(frame, Globals.lang("Search results"));
   }
 }
Пример #18
0
  /**
   * This method presents a dialog box explaining and offering to make the changes. If the user
   * confirms, the changes are performed.
   *
   * @param panel
   * @param pr
   */
  @Override
  public void performAction(BasePanel panel, ParserResult pr) {
    // Find out which actions should be offered:
    // Only offer to change Preferences if file column is not already visible:
    boolean offerChangeSettings =
        !Globals.prefs.getBoolean(JabRefPreferences.FILE_COLUMN) || !showsFileInGenFields();
    // Only offer to upgrade links if the pdf/ps fields are used:
    boolean offerChangeDatabase =
        linksFound(pr.getDatabase(), FileLinksUpgradeWarning.FIELDS_TO_LOOK_FOR);
    // If the "file" directory is not set, offer to migrate pdf/ps dir:
    boolean offerSetFileDir =
        !Globals.prefs.hasKey(GUIGlobals.FILE_FIELD + "Directory")
            && (Globals.prefs.hasKey("pdfDirectory") || Globals.prefs.hasKey("psDirectory"));

    if (!offerChangeDatabase && !offerChangeSettings && !offerSetFileDir) {
      return; // Nothing to do, just return.
    }

    JCheckBox changeSettings =
        new JCheckBox(
            Globals.lang("Change table column and General fields settings to use the new feature"),
            offerChangeSettings);
    JCheckBox changeDatabase =
        new JCheckBox(
            Globals.lang("Upgrade old external file links to use the new feature"),
            offerChangeDatabase);
    JCheckBox setFileDir =
        new JCheckBox(Globals.lang("Set main external file directory") + ":", offerSetFileDir);
    JTextField fileDir = new JTextField(30);
    JCheckBox doNotShowDialog =
        new JCheckBox(Globals.lang("Do not show these options in the future"), false);

    JPanel message = new JPanel();
    DefaultFormBuilder b = new DefaultFormBuilder(new FormLayout("left:pref", ""), message);
    // Keep the formatting of these lines. Otherwise, strings have to be translated again.
    // See updated JabRef_en.properties modifications by python syncLang.py -s -u
    b.append(
        new JLabel(
            "<html>"
                + Globals.lang("This database was written using an older version of JabRef.")
                + "<br>"
                + Globals.lang(
                    "The current version features a new way of handling links to external files.<br>To take advantage of this, your links must be changed into the new format, and<br>JabRef must be configured to show the new links.")
                + "<p>"
                + Globals.lang("Do you want JabRef to do the following operations?")
                + "</html>"));
    b.nextLine();
    if (offerChangeSettings) {
      b.append(changeSettings);
      b.nextLine();
    }
    if (offerChangeDatabase) {
      b.append(changeDatabase);
      b.nextLine();
    }
    if (offerSetFileDir) {
      if (Globals.prefs.hasKey("pdfDirectory")) {
        fileDir.setText(Globals.prefs.get("pdfDirectory"));
      } else {
        fileDir.setText(Globals.prefs.get("psDirectory"));
      }
      JPanel pan = new JPanel();
      pan.add(setFileDir);
      pan.add(fileDir);
      JButton browse = new JButton(Globals.lang("Browse"));
      browse.addActionListener(BrowseAction.buildForDir(fileDir));
      pan.add(browse);
      b.append(pan);
      b.nextLine();
    }
    b.append("");
    b.nextLine();
    b.append(doNotShowDialog);

    int answer =
        JOptionPane.showConfirmDialog(
            panel.frame(), message, Globals.lang("Upgrade file"), JOptionPane.YES_NO_OPTION);
    if (doNotShowDialog.isSelected()) {
      Globals.prefs.putBoolean(JabRefPreferences.SHOW_FILE_LINKS_UPGRADE_WARNING, false);
    }

    if (answer == JOptionPane.YES_OPTION) {
      makeChanges(
          panel,
          pr,
          changeSettings.isSelected(),
          changeDatabase.isSelected(),
          setFileDir.isSelected() ? fileDir.getText() : null);
    }
  }
Пример #19
0
  @Override
  public boolean processQuery(String query, ImportInspector dialog, OutputPrinter status) {
    terms = query;
    piv = 0;
    shouldContinue = true;
    parsed = 0;
    unparseable = 0;
    int pageNumber = 1;

    searchUrl = makeUrl(pageNumber); // start at page 1

    try {
      URL url = new URL(searchUrl);
      String page = getResults(url);

      if (page.contains("You have entered an invalid search")) {
        status.showMessage(
            Globals.lang("You have entered an invalid search '%0'.", terms),
            Globals.lang("Search IEEEXplore"),
            JOptionPane.INFORMATION_MESSAGE);
        return false;
      }

      if (page.contains("Bad request")) {
        status.showMessage(
            Globals.lang("Bad Request '%0'.", terms),
            Globals.lang("Search IEEEXplore"),
            JOptionPane.INFORMATION_MESSAGE);
        return false;
      }

      if (page.contains("No results were found.")) {
        status.showMessage(
            Globals.lang("No entries found for the search string '%0'", terms),
            Globals.lang("Search IEEEXplore"),
            JOptionPane.INFORMATION_MESSAGE);
        return false;
      }

      if (page.contains("Error Page")) {
        status.showMessage(
            Globals.lang(
                "Intermittent errors on the IEEE Xplore server. Please try again in a while."),
            Globals.lang("Search IEEEXplore"),
            JOptionPane.INFORMATION_MESSAGE);
        return false;
      }

      hits = getNumberOfHits(page, "display-status", hitsPattern);

      includeAbstract = absCheckBox.isSelected();
      importBibtex = bibButton.isSelected();

      if (hits > IEEEXploreFetcher.MAX_FETCH) {
        status.showMessage(
            Globals.lang(
                "%0 entries found. To reduce server load, " + "only %1 will be downloaded.",
                new String[] {String.valueOf(hits), String.valueOf(IEEEXploreFetcher.MAX_FETCH)}),
            Globals.lang("Search IEEEXplore"),
            JOptionPane.INFORMATION_MESSAGE);
        hits = IEEEXploreFetcher.MAX_FETCH;
      }

      parse(dialog, page, 0, 1);
      int firstEntry = perPage;
      while (shouldContinue && firstEntry < hits) {
        pageNumber++;
        searchUrl = makeUrl(pageNumber);
        page = getResults(new URL(searchUrl));

        if (!shouldContinue) {
          break;
        }

        parse(dialog, page, 0, firstEntry + 1);
        firstEntry += perPage;
      }
      return true;
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (ConnectException e) {
      status.showMessage(
          Globals.lang("Connection to IEEEXplore failed"),
          Globals.lang("Search IEEEXplore"),
          JOptionPane.ERROR_MESSAGE);
    } catch (IOException e) {
      status.showMessage(
          Globals.lang(e.getMessage()),
          Globals.lang("Search IEEEXplore"),
          JOptionPane.ERROR_MESSAGE);
      e.printStackTrace();
    }
    return false;
  }
Пример #20
0
  public void run() {

    if (!goOn) return;

    for (int i = 0; i < entries.length; i++) {

      BibtexEntry entry = entries[i];

      // Make a list of all PDFs linked from this entry:
      List<File> files = new ArrayList<File>();

      // First check the (legacy) "pdf" field:
      String pdf = entry.getField("pdf");
      String dir = panel.metaData().getFileDirectory("pdf");
      File f = Util.expandFilename(pdf, new String[] {dir, "."});
      if (f != null) files.add(f);

      // Then check the "file" field:
      dir = panel.metaData().getFileDirectory(GUIGlobals.FILE_FIELD);
      String field = entry.getField(GUIGlobals.FILE_FIELD);
      if (field != null) {
        FileListTableModel tm = new FileListTableModel();
        tm.setContent(field);
        for (int j = 0; j < tm.getRowCount(); j++) {
          FileListEntry flEntry = tm.getEntry(j);
          if ((flEntry.getType() != null)
              && (flEntry.getType().getName().toLowerCase().equals("pdf"))) {
            f = Util.expandFilename(flEntry.getLink(), new String[] {dir, "."});
            if (f != null) files.add(f);
          }
        }
      }

      optDiag.progressArea.append(entry.getCiteKey() + "\n");

      if (files.size() == 0) {
        skipped++;
        optDiag.progressArea.append("  " + Globals.lang("Skipped - No PDF linked") + ".\n");
      } else
        for (File file : files) {
          if (!file.exists()) {
            skipped++;
            optDiag.progressArea.append(
                "  " + Globals.lang("Skipped - PDF does not exist") + ":\n");
            optDiag.progressArea.append("    " + file.getPath() + "\n");

          } else {
            try {
              XMPUtil.writeXMP(file, entry, database);
              optDiag.progressArea.append("  " + Globals.lang("Ok") + ".\n");
              entriesChanged++;
            } catch (Exception e) {
              optDiag.progressArea.append(
                  "  " + Globals.lang("Error while writing") + " '" + file.getPath() + "':\n");
              optDiag.progressArea.append("    " + e.getLocalizedMessage() + "\n");
              errors++;
            }
          }
        }

      if (optDiag.canceled) {
        optDiag.progressArea.append("\n" + Globals.lang("Operation canceled.\n"));
        break;
      }
    }
    optDiag.progressArea.append(
        "\n"
            + Globals.lang(
                "Finished writing XMP for %0 file (%1 skipped, %2 errors).",
                String.valueOf(entriesChanged), String.valueOf(skipped), String.valueOf(errors)));
    optDiag.done();
  }
Пример #21
0
  private BibtexEntry createNewEntry() {

    // Find out what type is wanted.
    EntryTypeDialog etd = new EntryTypeDialog(frame);
    // We want to center the dialog, to make it look nicer.
    Util.placeDialog(etd, frame);
    etd.setVisible(true);
    BibtexEntryType type = etd.getChoice();

    if (type != null) { // Only if the dialog was not cancelled.
      String id = Util.createNeutralId();
      final BibtexEntry be = new BibtexEntry(id, type);
      try {
        panel.database().insertEntry(be);

        // Set owner/timestamp if options are enabled:
        ArrayList<BibtexEntry> list = new ArrayList<BibtexEntry>();
        list.add(be);
        Util.setAutomaticFields(list, true, true, false);

        // Create an UndoableInsertEntry object.
        panel.undoManager.addEdit(new UndoableInsertEntry(panel.database(), be, panel));
        panel.output(
            Globals.lang("Added new")
                + " '"
                + type.getName().toLowerCase()
                + "' "
                + Globals.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() != panel.SHOWING_EDITOR) {
          panel.setMode(panel.WILL_SHOW_EDITOR);
        }

        /*int row = entryTable.findEntry(be);
        if (row >= 0)
            // Selects the entry. The selection listener will open the editor.
             if (row >= 0) {
                try{
                    entryTable.setRowSelectionInterval(row, row);
                }catch(IllegalArgumentException e){
                    System.out.println("RowCount: " + entryTable.getRowCount());
                }

                //entryTable.setActiveRow(row);
                entryTable.ensureVisible(row);
             }
        else {
            // The entry is not visible in the table, perhaps due to a filtering search
            // or group selection. Show the entry editor anyway:
            panel.showEntry(be);
        }   */
        panel.showEntry(be);
        panel.markBaseChanged(); // The database just changed.
        new FocusRequester(panel.getEntryEditor(be));
        return be;
      } catch (KeyCollisionException ex) {
        Util.pr(ex.getMessage());
      }
    }
    return null;
  }
Пример #22
0
    public OptionsDialog(JFrame parent) {
      super(parent, Globals.lang("Writing XMP metadata for selected entries..."), false);
      okButton.setEnabled(false);

      okButton.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              dispose();
            }
          });

      AbstractAction cancel =
          new AbstractAction() {
            private static final long serialVersionUID = -338601477652815366L;

            public void actionPerformed(ActionEvent e) {
              canceled = true;
            }
          };
      cancelButton.addActionListener(cancel);

      InputMap im = cancelButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
      ActionMap am = cancelButton.getActionMap();
      im.put(Globals.prefs.getKey("Close dialog"), "close");
      am.put("close", cancel);

      progressArea = new JTextArea(15, 60);

      JScrollPane scrollPane =
          new JScrollPane(
              progressArea,
              JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
              JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
      Dimension d = progressArea.getPreferredSize();
      d.height += scrollPane.getHorizontalScrollBar().getHeight() + 15;
      d.width += scrollPane.getVerticalScrollBar().getWidth() + 15;

      panel.setSize(d);

      progressArea.setBackground(Color.WHITE);
      progressArea.setEditable(false);
      progressArea.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
      progressArea.setText("");

      JPanel panel = new JPanel();
      panel.setBorder(BorderFactory.createEmptyBorder(3, 2, 3, 2));
      panel.add(scrollPane);

      // progressArea.setPreferredSize(new Dimension(300, 300));

      ButtonBarBuilder bb = new ButtonBarBuilder();
      bb.addGlue();
      bb.addGridded(okButton);
      bb.addRelatedGap();
      bb.addGridded(cancelButton);
      bb.addGlue();
      JPanel bbPanel = bb.getPanel();
      bbPanel.setBorder(BorderFactory.createEmptyBorder(0, 3, 3, 3));
      getContentPane().add(panel, BorderLayout.CENTER);
      getContentPane().add(bbPanel, BorderLayout.SOUTH);

      pack();
      this.setResizable(false);
    }
Пример #23
0
    @Override
    public void update() {
      panel.output(Globals.lang("Searched database. Number of hits") + ": " + hits);

      // Show the result in the chosen way:
      if (searchAllBases.isSelected()) {
        // Search all databases. This means we need to use the search results dialog.
        // Turn off other search mode, if activated:
        if (startedFloatSearch) {
          panel.mainTable.stopShowingFloatSearch();
          startedFloatSearch = false;
        }
        if (startedFilterSearch) {
          panel.stopShowingSearchResults();
          startedFilterSearch = false;
        }
        // Make sure the search dialog is instantiated and cleared:
        instantiateSearchDialog();
        searchDialog.clear();
        for (int i = 0; i < frame.getTabbedPane().getTabCount(); i++) {
          BasePanel p = frame.baseAt(i);
          for (BibtexEntry entry : p.getDatabase().getEntries()) {
            if (entry.isSearchHit()) {
              searchDialog.addEntry(entry, p);
            }
          }
        }
        searchDialog.selectFirstEntry();
        searchDialog.setVisible(true);
      } else if (showResultsInDialog.isSelected()) {
        // Turn off other search mode, if activated:
        if (startedFloatSearch) {
          panel.mainTable.stopShowingFloatSearch();
          startedFloatSearch = false;
        }
        if (startedFilterSearch) {
          panel.stopShowingSearchResults();
          startedFilterSearch = false;
        }
        // Make sure the search dialog is instantiated and cleared:
        instantiateSearchDialog();
        searchDialog.clear();
        for (BibtexEntry entry : panel.getDatabase().getEntries()) {
          if (entry.isSearchHit()) {
            searchDialog.addEntry(entry, panel);
          }
        }
        searchDialog.selectFirstEntry();
        searchDialog.setVisible(true);
      } else if (hideSearch.isSelected()) {
        // Filtering search - removes non-hits from the table:
        if (startedFloatSearch) {
          panel.mainTable.stopShowingFloatSearch();
          startedFloatSearch = false;
        }
        startedFilterSearch = true;
        panel.setSearchMatcher(new SearchMatcher());

      } else {
        // Float search - floats hits to the top of the table:
        if (startedFilterSearch) {
          panel.stopShowingSearchResults();
          startedFilterSearch = false;
        }
        startedFloatSearch = true;
        panel.mainTable.showFloatSearch(new SearchMatcher());
      }

      // Afterwards, select all text in the search field.
      searchField.select(0, searchField.getText().length());
    }
Пример #24
0
  public SearchManager2(JabRefFrame frame, SidePaneManager manager) {
    super(manager, GUIGlobals.getIconUrl("search"), Globals.lang("Search"));

    this.frame = frame;
    incSearcher = new IncrementalSearcher(Globals.prefs);

    // setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.magenta));

    searchReq =
        new JCheckBoxMenuItem(
            Globals.lang("Search required fields"),
            Globals.prefs.getBoolean(JabRefPreferences.SEARCH_REQ));
    searchOpt =
        new JCheckBoxMenuItem(
            Globals.lang("Search optional fields"),
            Globals.prefs.getBoolean(JabRefPreferences.SEARCH_OPT));
    searchGen =
        new JCheckBoxMenuItem(
            Globals.lang("Search general fields"),
            Globals.prefs.getBoolean(JabRefPreferences.SEARCH_GEN));
    searchAll =
        new JCheckBoxMenuItem(
            Globals.lang("Search all fields"),
            Globals.prefs.getBoolean(JabRefPreferences.SEARCH_ALL));
    regExpSearch =
        new JCheckBoxMenuItem(
            Globals.lang("Use regular expressions"),
            Globals.prefs.getBoolean(JabRefPreferences.REG_EXP_SEARCH));

    increment = new JRadioButton(Globals.lang("Incremental"), false);
    floatSearch = new JRadioButton(Globals.lang("Float"), true);
    hideSearch = new JRadioButton(Globals.lang("Filter"), true);
    showResultsInDialog = new JRadioButton(Globals.lang("Show results in dialog"), true);
    searchAllBases =
        new JRadioButton(
            Globals.lang("Global search"),
            Globals.prefs.getBoolean(JabRefPreferences.SEARCH_ALL_BASES));
    ButtonGroup types = new ButtonGroup();
    types.add(increment);
    types.add(floatSearch);
    types.add(hideSearch);
    types.add(showResultsInDialog);
    types.add(searchAllBases);

    select = new JCheckBoxMenuItem(Globals.lang("Select matches"), false);
    increment.setToolTipText(Globals.lang("Incremental search"));
    floatSearch.setToolTipText(Globals.lang("Gray out non-matching entries"));
    hideSearch.setToolTipText(Globals.lang("Hide non-matching entries"));
    showResultsInDialog.setToolTipText(Globals.lang("Show search results in a window"));

    // Add an item listener that makes sure we only listen for key events
    // when incremental search is turned on.
    increment.addItemListener(this);
    floatSearch.addItemListener(this);
    hideSearch.addItemListener(this);
    showResultsInDialog.addItemListener(this);
    // Add the global focus listener, so a menu item can see if this field was focused when
    // an action was called.
    searchField.addFocusListener(Globals.focusListener);

    if (searchAll.isSelected()) {
      searchReq.setEnabled(false);
      searchOpt.setEnabled(false);
      searchGen.setEnabled(false);
    }
    searchAll.addChangeListener(
        new ChangeListener() {

          @Override
          public void stateChanged(ChangeEvent event) {
            boolean state = !searchAll.isSelected();
            searchReq.setEnabled(state);
            searchOpt.setEnabled(state);
            searchGen.setEnabled(state);
          }
        });

    caseSensitive =
        new JCheckBoxMenuItem(
            Globals.lang("Case sensitive"),
            Globals.prefs.getBoolean(JabRefPreferences.CASE_SENSITIVE_SEARCH));

    highLightWords =
        new JCheckBoxMenuItem(
            Globals.lang("Highlight Words"),
            Globals.prefs.getBoolean(JabRefPreferences.HIGH_LIGHT_WORDS));

    searchAutoComplete =
        new JCheckBoxMenuItem(
            Globals.lang("Autocomplete names"),
            Globals.prefs.getBoolean(JabRefPreferences.SEARCH_AUTO_COMPLETE));
    settings.add(select);

    // 2005.03.29, trying to remove field category searches, to simplify
    // search usability.
    // settings.addSeparator();
    // settings.add(searchReq);
    // settings.add(searchOpt);
    // settings.add(searchGen);
    // settings.addSeparator();
    // settings.add(searchAll);
    // ---------------------------------------------------------------
    settings.addSeparator();
    settings.add(caseSensitive);
    settings.add(regExpSearch);
    settings.addSeparator();
    settings.add(highLightWords);
    settings.addSeparator();
    settings.add(searchAutoComplete);

    searchField.addActionListener(this);
    searchField.addCaretListener(this);
    search.addActionListener(this);
    searchField.addFocusListener(
        new FocusAdapter() {

          @Override
          public void focusGained(FocusEvent e) {
            if (increment.isSelected()) {
              searchField.setText("");
            }
          }

          @Override
          public void focusLost(FocusEvent e) {
            incSearch = false;
            incSearchPos = -1; // Reset incremental
            // search. This makes the
            // incremental search reset
            // once the user moves focus to
            // somewhere else.
            if (increment.isSelected()) {
              // searchField.setText("");
              // System.out.println("focuslistener");
            }
          }
        });
    escape.addActionListener(this);
    escape.setEnabled(false); // enabled after searching

    openset.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) {
            if (settings.isVisible()) {
              // System.out.println("oee");
              // settings.setVisible(false);
            } else {
              JButton src = (JButton) e.getSource();
              settings.show(src, 0, openset.getHeight());
            }
          }
        });

    searchAutoComplete.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent actionEvent) {
            Globals.prefs.putBoolean(
                JabRefPreferences.SEARCH_AUTO_COMPLETE, searchAutoComplete.isSelected());
            if (SearchManager2.this.frame.basePanel() != null) {
              SearchManager2.this.frame.basePanel().updateSearchManager();
            }
          }
        });
    Insets margin = new Insets(0, 2, 0, 2);
    // search.setMargin(margin);
    escape.setMargin(margin);
    openset.setMargin(margin);
    JButton help = new JButton(GUIGlobals.getImage("help"));
    int butSize = help.getIcon().getIconHeight() + 5;
    Dimension butDim = new Dimension(butSize, butSize);
    help.setPreferredSize(butDim);
    help.setMinimumSize(butDim);
    help.setMargin(margin);
    help.addActionListener(new HelpAction(Globals.helpDiag, GUIGlobals.searchHelp, "Help"));

    // Select the last used mode of search:
    if (Globals.prefs.getBoolean(JabRefPreferences.INCREMENT_S)) {
      increment.setSelected(true);
    } else if (Globals.prefs.getBoolean(JabRefPreferences.FLOAT_SEARCH)) {
      floatSearch.setSelected(true);
    } else if (Globals.prefs.getBoolean(JabRefPreferences.SHOW_SEARCH_IN_DIALOG)) {
      showResultsInDialog.setSelected(true);
    } else if (Globals.prefs.getBoolean(JabRefPreferences.SEARCH_ALL_BASES)) {
      searchAllBases.setSelected(true);
    } else {
      hideSearch.setSelected(true);
    }

    JPanel main = new JPanel();
    GridBagLayout gbl = new GridBagLayout();
    main.setLayout(gbl);
    GridBagConstraints con = new GridBagConstraints();
    con.gridwidth = GridBagConstraints.REMAINDER;
    con.fill = GridBagConstraints.BOTH;
    con.weightx = 1;

    gbl.setConstraints(searchField, con);
    main.add(searchField);
    // con.gridwidth = 1;
    gbl.setConstraints(search, con);
    main.add(search);
    con.gridwidth = GridBagConstraints.REMAINDER;
    gbl.setConstraints(escape, con);
    main.add(escape);
    con.insets = new Insets(0, 2, 0, 0);
    gbl.setConstraints(increment, con);
    main.add(increment);
    gbl.setConstraints(floatSearch, con);
    main.add(floatSearch);
    gbl.setConstraints(hideSearch, con);
    main.add(hideSearch);
    gbl.setConstraints(showResultsInDialog, con);
    main.add(showResultsInDialog);
    gbl.setConstraints(searchAllBases, con);
    main.add(searchAllBases);
    con.insets = new Insets(0, 0, 0, 0);
    JPanel pan = new JPanel();
    GridBagLayout gb = new GridBagLayout();
    gbl.setConstraints(pan, con);
    pan.setLayout(gb);
    con.weightx = 1;
    con.gridwidth = 1;
    gb.setConstraints(openset, con);
    pan.add(openset);
    con.weightx = 0;
    gb.setConstraints(help, con);
    pan.add(help);
    main.add(pan);
    main.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));

    setContentContainer(main);

    searchField.getInputMap().put(Globals.prefs.getKey("Repeat incremental search"), "repeat");

    searchField
        .getActionMap()
        .put(
            "repeat",
            new AbstractAction() {

              @Override
              public void actionPerformed(ActionEvent e) {
                if (increment.isSelected()) {
                  repeatIncremental();
                }
              }
            });
    searchField.getInputMap().put(Globals.prefs.getKey("Clear search"), "escape");
    searchField
        .getActionMap()
        .put(
            "escape",
            new AbstractAction() {

              @Override
              public void actionPerformed(ActionEvent e) {
                hideAway();
                // SearchManager2.this.actionPerformed(new ActionEvent(escape, 0, ""));
              }
            });
    setSearchButtonSizes();
    updateSearchButtonText();
  }
Пример #25
0
 /**
  * Updates the text on the search button to reflect the type of search that will happen on click.
  */
 private void updateSearchButtonText() {
   search.setText(
       isSpecificSearch()
           ? Globals.lang("Search specified field(s)")
           : Globals.lang("Search all fields"));
 }
Пример #26
0
class PreviewPrefsTab extends JPanel implements PrefsTab {

  private final JabRefPreferences prefs;

  JPanel pan = new JPanel();

  private final JTextArea layout1 = new JTextArea("", 1, 1);
  private final JTextArea layout2 = new JTextArea("", 1, 1);

  JButton help;

  private final JCheckBox pdfPreview = new JCheckBox(Globals.lang("Enable PDF preview"));

  private static BibtexEntry entry;

  public PreviewPrefsTab(JabRefPreferences prefs) {
    this.prefs = prefs;

    JPanel firstPanel = new JPanel();
    GridBagLayout layout = new GridBagLayout();
    firstPanel.setLayout(layout);
    JPanel secondPanel = new JPanel();
    secondPanel.setLayout(layout);

    setLayout(layout);
    JLabel lab;
    lab = new JLabel(Globals.lang("Preview") + " 1");
    GridBagConstraints layoutConstraints = new GridBagConstraints();
    layoutConstraints.anchor = GridBagConstraints.WEST;
    layoutConstraints.gridwidth = GridBagConstraints.REMAINDER;
    layoutConstraints.fill = GridBagConstraints.BOTH;
    layoutConstraints.weightx = 1;
    layoutConstraints.weighty = 0;
    layoutConstraints.insets = new Insets(2, 2, 2, 2);
    layout.setConstraints(lab, layoutConstraints);
    layoutConstraints.weighty = 1;
    JScrollPane firstScrollPane = new JScrollPane(layout1);
    layout.setConstraints(firstScrollPane, layoutConstraints);
    firstPanel.add(firstScrollPane);
    layoutConstraints.weighty = 0;
    layoutConstraints.gridwidth = 1;
    layoutConstraints.weightx = 0;
    layoutConstraints.fill = GridBagConstraints.NONE;
    layoutConstraints.anchor = GridBagConstraints.WEST;
    JButton testButton = new JButton(Globals.lang("Test"));
    layout.setConstraints(testButton, layoutConstraints);
    firstPanel.add(testButton);
    JButton defaultButton = new JButton(Globals.lang("Default"));
    layout.setConstraints(defaultButton, layoutConstraints);
    firstPanel.add(defaultButton);
    layoutConstraints.gridwidth = GridBagConstraints.REMAINDER;
    JPanel pan = new JPanel();
    layoutConstraints.weightx = 1;
    layout.setConstraints(pan, layoutConstraints);
    firstPanel.add(pan);
    lab = new JLabel(Globals.lang("Preview") + " 2");
    layout.setConstraints(lab, layoutConstraints);
    // p2.add(lab);
    layoutConstraints.weighty = 1;
    layoutConstraints.fill = GridBagConstraints.BOTH;
    JScrollPane secondScrollPane = new JScrollPane(layout2);
    layout.setConstraints(secondScrollPane, layoutConstraints);
    secondPanel.add(secondScrollPane);
    layoutConstraints.weighty = 0;
    layoutConstraints.weightx = 0;
    layoutConstraints.fill = GridBagConstraints.NONE;
    layoutConstraints.gridwidth = 1;
    JButton testButton2 = new JButton(Globals.lang("Test"));
    layout.setConstraints(testButton2, layoutConstraints);
    secondPanel.add(testButton2);
    JButton defaultButton2 = new JButton(Globals.lang("Default"));
    layout.setConstraints(defaultButton2, layoutConstraints);
    secondPanel.add(defaultButton2);
    layoutConstraints.gridwidth = 1;
    pan = new JPanel();
    layoutConstraints.weightx = 1;
    layout.setConstraints(pan, layoutConstraints);
    secondPanel.add(pan);

    layoutConstraints.weightx = 1;
    layoutConstraints.weighty = 0;
    layoutConstraints.fill = GridBagConstraints.BOTH;
    layoutConstraints.gridwidth = GridBagConstraints.REMAINDER;
    lab = new JLabel(Globals.lang("Preview") + " 1");
    layout.setConstraints(lab, layoutConstraints);
    add(lab);
    layoutConstraints.weighty = 1;
    layout.setConstraints(firstPanel, layoutConstraints);
    add(firstPanel);
    lab = new JLabel(Globals.lang("Preview") + " 2");
    layoutConstraints.weighty = 0;
    JSeparator sep = new JSeparator(SwingConstants.HORIZONTAL);
    layout.setConstraints(sep, layoutConstraints);
    add(sep);
    layout.setConstraints(lab, layoutConstraints);
    add(lab);
    layoutConstraints.weighty = 1;
    layout.setConstraints(secondPanel, layoutConstraints);
    add(secondPanel);

    // PDF Preview button
    JPanel pdfPreviewPanel = new JPanel(new BorderLayout());
    pdfPreviewPanel.add(pdfPreview, BorderLayout.WEST);

    { // Help Button
      HelpAction helpAction =
          new HelpAction(
              Globals.helpDiag,
              GUIGlobals.previewHelp,
              Globals.lang("Help on Preview Settings"),
              GUIGlobals.getIconUrl("helpSmall"));
      JButton help = helpAction.getIconButton();
      pdfPreviewPanel.add(help, BorderLayout.EAST);
    }

    layoutConstraints.weighty = 0;
    layout.setConstraints(pdfPreviewPanel, layoutConstraints);
    add(pdfPreviewPanel);

    defaultButton.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) {
            String tmp = layout1.getText().replaceAll("\n", "__NEWLINE__");
            PreviewPrefsTab.this.prefs.remove(JabRefPreferences.PREVIEW_0);
            layout1.setText(
                PreviewPrefsTab.this
                    .prefs
                    .get(JabRefPreferences.PREVIEW_0)
                    .replaceAll("__NEWLINE__", "\n"));
            PreviewPrefsTab.this.prefs.put(JabRefPreferences.PREVIEW_0, tmp);
          }
        });
    defaultButton2.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) {
            String tmp = layout2.getText().replaceAll("\n", "__NEWLINE__");
            PreviewPrefsTab.this.prefs.remove(JabRefPreferences.PREVIEW_1);
            layout2.setText(
                PreviewPrefsTab.this
                    .prefs
                    .get(JabRefPreferences.PREVIEW_1)
                    .replaceAll("__NEWLINE__", "\n"));
            PreviewPrefsTab.this.prefs.put(JabRefPreferences.PREVIEW_1, tmp);
          }
        });

    testButton.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) {
            PreviewPrefsTab.getTestEntry();
            try {
              PreviewPanel testPanel =
                  new PreviewPanel(
                      null, PreviewPrefsTab.entry, null, new MetaData(), layout1.getText());
              testPanel.setPreferredSize(new Dimension(800, 350));
              JOptionPane.showMessageDialog(
                  null, testPanel, Globals.lang("Preview"), JOptionPane.PLAIN_MESSAGE);
            } catch (StringIndexOutOfBoundsException ex) {
              ex.printStackTrace();
              JOptionPane.showMessageDialog(
                  null,
                  Globals.lang("Parsing error")
                      + ": "
                      + Globals.lang("illegal backslash expression")
                      + ".\n"
                      + ex.getMessage()
                      + '\n'
                      + Globals.lang("Look at stderr for details")
                      + '.',
                  Globals.lang("Parsing error"),
                  JOptionPane.ERROR_MESSAGE);
            }
          }
        });

    testButton2.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) {
            PreviewPrefsTab.getTestEntry();
            try {
              PreviewPanel testPanel =
                  new PreviewPanel(
                      null, PreviewPrefsTab.entry, null, new MetaData(), layout2.getText());
              testPanel.setPreferredSize(new Dimension(800, 350));
              JOptionPane.showMessageDialog(
                  null,
                  new JScrollPane(testPanel),
                  Globals.lang("Preview"),
                  JOptionPane.PLAIN_MESSAGE);
            } catch (StringIndexOutOfBoundsException ex) {
              ex.printStackTrace();
              JOptionPane.showMessageDialog(
                  null,
                  "Parsing error: illegal backslash expression.\n"
                      + ex.getMessage()
                      + "\nLook at stderr for details.",
                  "Parsing error",
                  JOptionPane.ERROR_MESSAGE);
            }
          }
        });
  }

  private static BibtexEntry getTestEntry() {
    if (PreviewPrefsTab.entry != null) {
      return PreviewPrefsTab.entry;
    }
    PreviewPrefsTab.entry = new BibtexEntry(IdGenerator.next(), BibtexEntryType.getType("article"));
    PreviewPrefsTab.entry.setField(BibtexFields.KEY_FIELD, "conceicao1997");
    PreviewPrefsTab.entry.setField(
        "author",
        "Luis E. C. Conceic{\\~a}o and Terje van der Meeren and Johan A. J. Verreth and M S. Evjen and D. F. Houlihan and H. J. Fyhn");
    PreviewPrefsTab.entry.setField(
        "title",
        "Amino acid metabolism and protein turnover in larval turbot (Scophthalmus maximus) fed natural zooplankton or Artemia");
    PreviewPrefsTab.entry.setField("year", "1997");
    PreviewPrefsTab.entry.setField("journal", "Marine Biology");
    PreviewPrefsTab.entry.setField("month", "January");
    PreviewPrefsTab.entry.setField("number", "2");
    PreviewPrefsTab.entry.setField("volume", "123");
    PreviewPrefsTab.entry.setField("pdf", "conceicao1997.pdf");
    PreviewPrefsTab.entry.setField("pages", "255--265");
    PreviewPrefsTab.entry.setField(
        "keywords", "energetics, artemia, metabolism, amino acid, turbot");
    PreviewPrefsTab.entry.setField(
        "url", "http://ejournals.ebsco.com/direct.asp?ArticleID=TYY4NT82XA9H7R8PFPPV");
    PreviewPrefsTab.entry.setField(
        "abstract",
        "Abstract The present paper studied the influence of different food regimes "
            + "on the free amino acid (FAA) pool, the rate of protein turnover, the flux of amino acids, and "
            + "their relation to growth of larval turbot (Scophthalmus maximus L.) from first feeding until "
            + "metamorphosis. The amino acid profile of protein was stable during the larval period although "
            + "some small, but significant, differences were found. Turbot larvae had proteins which were rich "
            + "in leucine and aspartate, and poor in glutamate, suggesting a high leucine requirement. The "
            + "profile of the FAA pool was highly variable and quite different from the amino acid profile in "
            + "protein. The proportion of essential FAA decreased with development. High contents of free tyrosine "
            + "and phenylalanine were found on Day 3, while free taurine was present at high levels throughout "
            + "the experimental period. Larval growth rates were positively correlated with taurine levels, "
            + "suggesting a dietary dependency for taurine and/or sulphur amino acids.\n\nReduced growth rates in "
            + "Artemia-fed larvae were associated with lower levels of free methionine, indicating that this diet "
            + "is deficient in methionine for turbot larvae. Leucine might also be limiting turbot growth as the "
            + "different diet organisms had lower levels of this amino acid in the free pool than was found in the "
            + "larval protein. A previously presented model was used to describe the flux of amino acids in growing "
            + "turbot larvae. The FAA pool was found to be small and variable. It was estimated that the daily dietary "
            + "amino acid intake might be up to ten times the larval FAA pool. In addition, protein synthesis and "
            + "protein degradation might daily remove and return, respectively, the equivalent of up to 20 and 10 "
            + "times the size of the FAA pool. In an early phase (Day 11) high growth rates were associated with a "
            + "relatively low protein turnover, while at a later stage (Day 17), a much higher turnover was observed.");
    return PreviewPrefsTab.entry;
  }

  @Override
  public void setValues() {
    layout1.setText(prefs.get(JabRefPreferences.PREVIEW_0).replaceAll("__NEWLINE__", "\n"));
    layout2.setText(prefs.get(JabRefPreferences.PREVIEW_1).replaceAll("__NEWLINE__", "\n"));
    pdfPreview.setSelected(prefs.getBoolean(JabRefPreferences.PDF_PREVIEW));
  }

  @Override
  public void storeSettings() {
    prefs.put(JabRefPreferences.PREVIEW_0, layout1.getText().replaceAll("\n", "__NEWLINE__"));
    prefs.put(JabRefPreferences.PREVIEW_1, layout2.getText().replaceAll("\n", "__NEWLINE__"));
    prefs.putBoolean(JabRefPreferences.PDF_PREVIEW, pdfPreview.isSelected());
  }

  @Override
  public boolean readyToClose() {
    return true;
  }

  @Override
  public String getTabName() {
    return Globals.lang("Entry preview");
  }
}
Пример #27
0
 @Override
 public String getTabName() {
   return Globals.lang("Entry preview");
 }
Пример #28
0
  public PreviewPrefsTab(JabRefPreferences prefs) {
    this.prefs = prefs;

    JPanel firstPanel = new JPanel();
    GridBagLayout layout = new GridBagLayout();
    firstPanel.setLayout(layout);
    JPanel secondPanel = new JPanel();
    secondPanel.setLayout(layout);

    setLayout(layout);
    JLabel lab;
    lab = new JLabel(Globals.lang("Preview") + " 1");
    GridBagConstraints layoutConstraints = new GridBagConstraints();
    layoutConstraints.anchor = GridBagConstraints.WEST;
    layoutConstraints.gridwidth = GridBagConstraints.REMAINDER;
    layoutConstraints.fill = GridBagConstraints.BOTH;
    layoutConstraints.weightx = 1;
    layoutConstraints.weighty = 0;
    layoutConstraints.insets = new Insets(2, 2, 2, 2);
    layout.setConstraints(lab, layoutConstraints);
    layoutConstraints.weighty = 1;
    JScrollPane firstScrollPane = new JScrollPane(layout1);
    layout.setConstraints(firstScrollPane, layoutConstraints);
    firstPanel.add(firstScrollPane);
    layoutConstraints.weighty = 0;
    layoutConstraints.gridwidth = 1;
    layoutConstraints.weightx = 0;
    layoutConstraints.fill = GridBagConstraints.NONE;
    layoutConstraints.anchor = GridBagConstraints.WEST;
    JButton testButton = new JButton(Globals.lang("Test"));
    layout.setConstraints(testButton, layoutConstraints);
    firstPanel.add(testButton);
    JButton defaultButton = new JButton(Globals.lang("Default"));
    layout.setConstraints(defaultButton, layoutConstraints);
    firstPanel.add(defaultButton);
    layoutConstraints.gridwidth = GridBagConstraints.REMAINDER;
    JPanel pan = new JPanel();
    layoutConstraints.weightx = 1;
    layout.setConstraints(pan, layoutConstraints);
    firstPanel.add(pan);
    lab = new JLabel(Globals.lang("Preview") + " 2");
    layout.setConstraints(lab, layoutConstraints);
    // p2.add(lab);
    layoutConstraints.weighty = 1;
    layoutConstraints.fill = GridBagConstraints.BOTH;
    JScrollPane secondScrollPane = new JScrollPane(layout2);
    layout.setConstraints(secondScrollPane, layoutConstraints);
    secondPanel.add(secondScrollPane);
    layoutConstraints.weighty = 0;
    layoutConstraints.weightx = 0;
    layoutConstraints.fill = GridBagConstraints.NONE;
    layoutConstraints.gridwidth = 1;
    JButton testButton2 = new JButton(Globals.lang("Test"));
    layout.setConstraints(testButton2, layoutConstraints);
    secondPanel.add(testButton2);
    JButton defaultButton2 = new JButton(Globals.lang("Default"));
    layout.setConstraints(defaultButton2, layoutConstraints);
    secondPanel.add(defaultButton2);
    layoutConstraints.gridwidth = 1;
    pan = new JPanel();
    layoutConstraints.weightx = 1;
    layout.setConstraints(pan, layoutConstraints);
    secondPanel.add(pan);

    layoutConstraints.weightx = 1;
    layoutConstraints.weighty = 0;
    layoutConstraints.fill = GridBagConstraints.BOTH;
    layoutConstraints.gridwidth = GridBagConstraints.REMAINDER;
    lab = new JLabel(Globals.lang("Preview") + " 1");
    layout.setConstraints(lab, layoutConstraints);
    add(lab);
    layoutConstraints.weighty = 1;
    layout.setConstraints(firstPanel, layoutConstraints);
    add(firstPanel);
    lab = new JLabel(Globals.lang("Preview") + " 2");
    layoutConstraints.weighty = 0;
    JSeparator sep = new JSeparator(SwingConstants.HORIZONTAL);
    layout.setConstraints(sep, layoutConstraints);
    add(sep);
    layout.setConstraints(lab, layoutConstraints);
    add(lab);
    layoutConstraints.weighty = 1;
    layout.setConstraints(secondPanel, layoutConstraints);
    add(secondPanel);

    // PDF Preview button
    JPanel pdfPreviewPanel = new JPanel(new BorderLayout());
    pdfPreviewPanel.add(pdfPreview, BorderLayout.WEST);

    { // Help Button
      HelpAction helpAction =
          new HelpAction(
              Globals.helpDiag,
              GUIGlobals.previewHelp,
              Globals.lang("Help on Preview Settings"),
              GUIGlobals.getIconUrl("helpSmall"));
      JButton help = helpAction.getIconButton();
      pdfPreviewPanel.add(help, BorderLayout.EAST);
    }

    layoutConstraints.weighty = 0;
    layout.setConstraints(pdfPreviewPanel, layoutConstraints);
    add(pdfPreviewPanel);

    defaultButton.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) {
            String tmp = layout1.getText().replaceAll("\n", "__NEWLINE__");
            PreviewPrefsTab.this.prefs.remove(JabRefPreferences.PREVIEW_0);
            layout1.setText(
                PreviewPrefsTab.this
                    .prefs
                    .get(JabRefPreferences.PREVIEW_0)
                    .replaceAll("__NEWLINE__", "\n"));
            PreviewPrefsTab.this.prefs.put(JabRefPreferences.PREVIEW_0, tmp);
          }
        });
    defaultButton2.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) {
            String tmp = layout2.getText().replaceAll("\n", "__NEWLINE__");
            PreviewPrefsTab.this.prefs.remove(JabRefPreferences.PREVIEW_1);
            layout2.setText(
                PreviewPrefsTab.this
                    .prefs
                    .get(JabRefPreferences.PREVIEW_1)
                    .replaceAll("__NEWLINE__", "\n"));
            PreviewPrefsTab.this.prefs.put(JabRefPreferences.PREVIEW_1, tmp);
          }
        });

    testButton.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) {
            PreviewPrefsTab.getTestEntry();
            try {
              PreviewPanel testPanel =
                  new PreviewPanel(
                      null, PreviewPrefsTab.entry, null, new MetaData(), layout1.getText());
              testPanel.setPreferredSize(new Dimension(800, 350));
              JOptionPane.showMessageDialog(
                  null, testPanel, Globals.lang("Preview"), JOptionPane.PLAIN_MESSAGE);
            } catch (StringIndexOutOfBoundsException ex) {
              ex.printStackTrace();
              JOptionPane.showMessageDialog(
                  null,
                  Globals.lang("Parsing error")
                      + ": "
                      + Globals.lang("illegal backslash expression")
                      + ".\n"
                      + ex.getMessage()
                      + '\n'
                      + Globals.lang("Look at stderr for details")
                      + '.',
                  Globals.lang("Parsing error"),
                  JOptionPane.ERROR_MESSAGE);
            }
          }
        });

    testButton2.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) {
            PreviewPrefsTab.getTestEntry();
            try {
              PreviewPanel testPanel =
                  new PreviewPanel(
                      null, PreviewPrefsTab.entry, null, new MetaData(), layout2.getText());
              testPanel.setPreferredSize(new Dimension(800, 350));
              JOptionPane.showMessageDialog(
                  null,
                  new JScrollPane(testPanel),
                  Globals.lang("Preview"),
                  JOptionPane.PLAIN_MESSAGE);
            } catch (StringIndexOutOfBoundsException ex) {
              ex.printStackTrace();
              JOptionPane.showMessageDialog(
                  null,
                  "Parsing error: illegal backslash expression.\n"
                      + ex.getMessage()
                      + "\nLook at stderr for details.",
                  "Parsing error",
                  JOptionPane.ERROR_MESSAGE);
            }
          }
        });
  }
Пример #29
0
  public void actionPerformed(ActionEvent event) {
    int selected = editor.getSelectedRow();
    if (selected == -1) return;
    FileListEntry flEntry = editor.getTableModel().getEntry(selected);
    // Check if the current file exists:
    String ln = flEntry.getLink();
    boolean httpLink = ln.toLowerCase().startsWith("http");
    if (httpLink) {
      // TODO: notify that this operation cannot be done on remote links

    }

    // Get an absolute path representation:
    String dir = frame.basePanel().metaData().getFileDirectory(GUIGlobals.FILE_FIELD);
    if ((dir == null) || (dir.trim().length() == 0) || !(new File(dir)).exists()) {
      JOptionPane.showMessageDialog(
          frame,
          Globals.lang("File_directory_is_not_set_or_does_not_exist!"),
          Globals.lang("Move/Rename file"),
          JOptionPane.ERROR_MESSAGE);
      return;
    }
    File file = new File(ln);
    if (!file.isAbsolute()) {
      file = Util.expandFilename(ln, new String[] {dir});
    }
    if ((file != null) && file.exists()) {
      // Ok, we found the file. Now get a new name:
      String extension = null;
      if (flEntry.getType() != null) extension = "." + flEntry.getType().getExtension();

      File newFile = null;
      boolean repeat = true;
      while (repeat) {
        repeat = false;
        String chosenFile;
        if (toFileDir) {
          String suggName = eEditor.getEntry().getCiteKey() + extension;
          CheckBoxMessage cbm =
              new CheckBoxMessage(
                  Globals.lang("Move file to file directory?"),
                  Globals.lang("Rename to '%0'", suggName),
                  Globals.prefs.getBoolean("renameOnMoveFileToFileDir"));
          int answer;
          // Only ask about renaming file if the file doesn't have the proper name already:
          if (!suggName.equals(file.getName()))
            answer =
                JOptionPane.showConfirmDialog(
                    frame, cbm, Globals.lang("Move/Rename file"), JOptionPane.YES_NO_OPTION);
          else
            answer =
                JOptionPane.showConfirmDialog(
                    frame,
                    Globals.lang("Move file to file directory?"),
                    Globals.lang("Move/Rename file"),
                    JOptionPane.YES_NO_OPTION);
          if (answer != JOptionPane.YES_OPTION) return;
          Globals.prefs.putBoolean("renameOnMoveFileToFileDir", cbm.isSelected());
          StringBuilder sb = new StringBuilder(dir);
          if (!dir.endsWith(File.separator)) sb.append(File.separator);
          if (cbm.isSelected()) {
            // Rename:
            sb.append(suggName);
          } else {
            // Do not rename:
            sb.append(file.getName());
          }
          chosenFile = sb.toString();
        } else {
          chosenFile =
              FileDialogs.getNewFile(frame, file, extension, JFileChooser.SAVE_DIALOG, false);
        }
        if (chosenFile == null) {
          return; // cancelled
        }
        newFile = new File(chosenFile);
        // Check if the file already exists:
        if (newFile.exists()
            && (JOptionPane.showConfirmDialog(
                    frame,
                    "'" + newFile.getName() + "' " + Globals.lang("exists. Overwrite file?"),
                    Globals.lang("Move/Rename file"),
                    JOptionPane.OK_CANCEL_OPTION)
                != JOptionPane.OK_OPTION)) {
          if (!toFileDir) repeat = true;
          else return;
        }
      }

      if (!newFile.equals(file)) {
        try {
          boolean success = file.renameTo(newFile);
          if (!success) {
            success = Util.copyFile(file, newFile, true);
          }
          if (success) {
            // Remove the original file:
            file.delete();
            // Relativise path, if possible.
            String canPath = (new File(dir)).getCanonicalPath();
            if (newFile.getCanonicalPath().startsWith(canPath)) {
              if ((newFile.getCanonicalPath().length() > canPath.length())
                  && (newFile.getCanonicalPath().charAt(canPath.length()) == File.separatorChar))
                flEntry.setLink(newFile.getCanonicalPath().substring(1 + canPath.length()));
              else flEntry.setLink(newFile.getCanonicalPath().substring(canPath.length()));

            } else flEntry.setLink(newFile.getCanonicalPath());
            eEditor.updateField(editor);
            JOptionPane.showMessageDialog(
                frame,
                Globals.lang("File moved"),
                Globals.lang("Move/Rename file"),
                JOptionPane.INFORMATION_MESSAGE);
          } else {
            JOptionPane.showMessageDialog(
                frame,
                Globals.lang("Move file failed"),
                Globals.lang("Move/Rename file"),
                JOptionPane.ERROR_MESSAGE);
          }

        } catch (SecurityException ex) {
          ex.printStackTrace();
          JOptionPane.showMessageDialog(
              frame,
              Globals.lang("Could not move file") + ": " + ex.getMessage(),
              Globals.lang("Move/Rename file"),
              JOptionPane.ERROR_MESSAGE);
        } catch (IOException ex) {
          ex.printStackTrace();
          JOptionPane.showMessageDialog(
              frame,
              Globals.lang("Could not move file") + ": " + ex.getMessage(),
              Globals.lang("Move/Rename file"),
              JOptionPane.ERROR_MESSAGE);
        }
      }
    } else {

      // File doesn't exist, so we can't move it.
      JOptionPane.showMessageDialog(
          frame,
          Globals.lang("Could not find file '%0'.", flEntry.getLink()),
          Globals.lang("File not found"),
          JOptionPane.ERROR_MESSAGE);
    }
  }
Пример #30
0
  private void initGui() {
    Container pane = getContentPane();
    pane.setLayout(new BorderLayout());

    biblatexMode = Globals.prefs.getBoolean("biblatexMode");

    JPanel main = new JPanel(), buttons = new JPanel(), right = new JPanel();
    main.setLayout(new BorderLayout());
    right.setLayout(new GridLayout(biblatexMode ? 2 : 1, 2));

    java.util.List<String> entryTypes = new ArrayList<String>();
    for (String s : BibtexEntryType.ALL_TYPES.keySet()) {
      entryTypes.add(s);
    }

    typeComp = new EntryTypeList(entryTypes);
    typeComp.addListSelectionListener(this);
    typeComp.addAdditionActionListener(this);
    typeComp.addDefaultActionListener(new DefaultListener());
    typeComp.setListSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    // typeComp.setEnabled(false);
    reqComp =
        new FieldSetComponent(
            Globals.lang("Required fields"), new ArrayList<String>(), preset, true, true);
    reqComp.setEnabled(false);
    reqComp.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
    ListDataListener dataListener = new DataListener();
    reqComp.addListDataListener(dataListener);
    optComp =
        new FieldSetComponent(
            Globals.lang("Optional fields"), new ArrayList<String>(), preset, true, true);
    optComp.setEnabled(false);
    optComp.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
    optComp.addListDataListener(dataListener);
    right.add(reqComp);
    right.add(optComp);

    if (biblatexMode) {
      optComp2 =
          new FieldSetComponent(
              Globals.lang("Optional fields") + " 2", new ArrayList<String>(), preset, true, true);
      optComp2.setEnabled(false);
      optComp2.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
      optComp2.addListDataListener(dataListener);
      right.add(new JPanel());
      right.add(optComp2);
    }

    // right.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),
    // Globals.lang("Fields")));
    right.setBorder(BorderFactory.createEtchedBorder());
    ok = new JButton("Ok");
    cancel = new JButton(Globals.lang("Cancel"));
    apply = new JButton(Globals.lang("Apply"));
    ok.addActionListener(this);
    apply.addActionListener(this);
    cancel.addActionListener(this);
    ButtonBarBuilder bb = new ButtonBarBuilder(buttons);
    buttons.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
    bb.addGlue();
    bb.addButton(ok);
    bb.addButton(apply);
    bb.addButton(cancel);
    bb.addGlue();

    AbstractAction closeAction =
        new AbstractAction() {

          @Override
          public void actionPerformed(ActionEvent e) {
            dispose();
          }
        };
    ActionMap am = main.getActionMap();
    InputMap im = main.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    im.put(Globals.prefs.getKey("Close dialog"), "close");
    am.put("close", closeAction);

    // con.fill = GridBagConstraints.BOTH;
    // con.weightx = 0.3;
    // con.weighty = 1;
    // gbl.setConstraints(typeComp, con);
    main.add(typeComp, BorderLayout.WEST);
    main.add(right, BorderLayout.CENTER);
    main.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    pane.add(main, BorderLayout.CENTER);
    pane.add(buttons, BorderLayout.SOUTH);
    pack();
  }