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."));

  }
Example #2
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);
 }
  /**
   * @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();
  }
Example #4
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)));
  }
Example #5
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..."));
  }
Example #6
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);
    }
  }
 /**
  * Method used by the SystemIO class to get interactive user input requested by a running MIPS
  * program (e.g. syscall #5 to read an integer). SystemIO knows whether simulator is being run at
  * command line by the user, or by the GUI. If run at command line, it gets input from System.in
  * rather than here.
  *
  * <p>This is an overloaded method. This version, with the String parameter, is used to get input
  * from a popup dialog.
  *
  * @param prompt Prompt to display to the user.
  * @return User input.
  */
 public String getInputString(String prompt) {
   String input;
   JOptionPane pane =
       new JOptionPane(prompt, JOptionPane.QUESTION_MESSAGE, JOptionPane.DEFAULT_OPTION);
   pane.setWantsInput(true);
   JDialog dialog = pane.createDialog(Globals.getGui(), "MIPS Keyboard Input");
   dialog.setVisible(true);
   input = (String) pane.getInputValue();
   this.postRunMessage(Globals.userInputAlert + input + "\n");
   return input;
 }
Example #8
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();
  }
 /**
  * Will select the specified line in an editor tab. If the file is open but not current, its tab
  * will be made current. If the file is not open, it will be opened in a new tab and made current,
  * however the line will not be selected (apparent apparent problem with JEditTextArea).
  *
  * @param fileName A String containing the file path name.
  * @param line Line number for error message
  * @param column Column number for error message
  */
 public void selectEditorTextLine(String fileName, int line, int column) {
   EditTabbedPane editTabbedPane =
       (EditTabbedPane) Globals.getGui().getMainPane().getEditTabbedPane();
   EditPane editPane, currentPane = null;
   editPane = editTabbedPane.getEditPaneForFile(new java.io.File(fileName).getPath());
   if (editPane != null) {
     if (editPane != editTabbedPane.getCurrentEditTab()) {
       editTabbedPane.setCurrentEditTab(editPane);
     }
     currentPane = editPane;
   } else { // file is not open.  Try to open it.
     if (editTabbedPane.openFile(new java.io.File(fileName))) {
       currentPane = editTabbedPane.getCurrentEditTab();
     }
   }
   // If editPane == null, it means the desired file was not open.  Line selection
   // does not properly with the JEditTextArea editor in this situation (it works
   // fine for the original generic editor).  So we just won't do it. DPS 9-Aug-2010
   if (editPane != null && currentPane != null) {
     currentPane.selectLine(line, column);
   }
 }
Example #10
0
  private void createDialog() {
    diag = new JDialog(frame, Globals.lang("Set/clear/rename fields"), true);

    field = new JTextField();
    text = new JTextField();
    text.setEnabled(false);
    renameTo = new JTextField();
    renameTo.setEnabled(false);

    JButton ok = new JButton(Globals.lang("Ok"));
    JButton cancel = new JButton(Globals.lang("Cancel"));

    all = new JRadioButton(Globals.lang("All entries"));
    selected = new JRadioButton(Globals.lang("Selected entries"));
    clear = new JRadioButton(Globals.lang("Clear fields"));
    set = new JRadioButton(Globals.lang("Set fields"));
    rename = new JRadioButton(Globals.lang("Rename field to:"));
    rename.setToolTipText(
        Globals.lang("Move contents of a field into a field with a different name"));
    set.addChangeListener(
        new ChangeListener() {

          @Override
          public void stateChanged(ChangeEvent e) {
            // Entering a text is only relevant if we are setting, not clearing:
            text.setEnabled(set.isSelected());
          }
        });
    clear.addChangeListener(
        new ChangeListener() {

          @Override
          public void stateChanged(ChangeEvent event) {
            // Overwrite protection makes no sense if we are clearing the field:
            overwrite.setEnabled(!clear.isSelected());
          }
        });
    rename.addChangeListener(
        new ChangeListener() {

          @Override
          public void stateChanged(ChangeEvent e) {
            // Entering a text is only relevant if we are renaming
            renameTo.setEnabled(rename.isSelected());
          }
        });
    overwrite = new JCheckBox(Globals.lang("Overwrite existing field values"), true);
    ButtonGroup bg = new ButtonGroup();
    bg.add(all);
    bg.add(selected);
    bg = new ButtonGroup();
    bg.add(clear);
    bg.add(set);
    bg.add(rename);
    DefaultFormBuilder builder =
        new DefaultFormBuilder(new FormLayout("left:pref, 4dlu, fill:100dlu", ""));
    builder.appendSeparator(Globals.lang("Field name"));
    builder.append(Globals.lang("Field name"));
    builder.append(field);
    builder.nextLine();
    builder.appendSeparator(Globals.lang("Include entries"));
    builder.append(all, 3);
    builder.nextLine();
    builder.append(selected, 3);
    builder.nextLine();
    builder.appendSeparator(Globals.lang("New field value"));
    builder.append(set);
    builder.append(text);
    builder.nextLine();
    builder.append(clear);
    builder.nextLine();
    builder.append(rename);
    builder.append(renameTo);
    builder.nextLine();
    builder.append(overwrite, 3);

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

    ok.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) {
            // Check if the user tries to rename multiple fields:
            if (rename.isSelected()) {
              String[] fields = getFieldNames(field.getText());
              if (fields.length > 1) {
                JOptionPane.showMessageDialog(
                    diag,
                    Globals.lang("You can only rename one field at a time"),
                    "",
                    JOptionPane.ERROR_MESSAGE);
                return; // Do not close the dialog.
              }
            }
            cancelled = false;
            diag.dispose();
          }
        });

    AbstractAction cancelAction =
        new AbstractAction() {

          @Override
          public void actionPerformed(ActionEvent e) {
            cancelled = true;
            diag.dispose();
          }
        };
    cancel.addActionListener(cancelAction);

    // Key bindings:
    ActionMap am = builder.getPanel().getActionMap();
    InputMap im = builder.getPanel().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    im.put(Globals.prefs.getKey("Close dialog"), "close");
    am.put("close", cancelAction);
  }
  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();
  }
  /** Creates a new instance of EntryCustomizationDialog2 */
  public EntryCustomizationDialog2(JabRefFrame frame) {
    super(frame, Globals.lang("Customize entry types"), false);

    this.frame = frame;
    initGui();
  }
 public void actionPerformed(ActionEvent e) {
   boolean usePopup = ((JCheckBoxMenuItem) e.getSource()).isSelected();
   Globals.getSettings().setBooleanSetting(Settings.POPUP_SYSCALL_INPUT, usePopup);
 }
Example #14
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);
            }
          }
        });
  }
Example #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);
    }
  }
}
Example #16
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();
  }
Example #17
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);
    }
  }
  /**
   * 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);
    }
  }
Example #19
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"));
 }
Example #20
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();
  }
Example #21
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());
    }
Example #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);
    }
Example #23
0
 public void update() {
   // pdfURL = new URL("http://geog-www.sbs.ohio-state.edu/faculty/bmark/abbott_etal_ppp03.pdf");
   if (result.url != null) {
     // System.out.println("PDF URL: "+result.url);
     String bibtexKey = entry.getCiteKey();
     String fileDir = basePanel.metaData().getFileDirectory(GUIGlobals.FILE_FIELD);
     if (fileDir == null) {
       // TODO: error message if file dir not defined
       // JOptionPane.showMessageDialog(frame, Globals.lang);
       return;
     }
     DownloadExternalFile def =
         new DownloadExternalFile(basePanel.frame(), basePanel.metaData(), bibtexKey);
     try {
       def.download(
           result.url,
           new DownloadExternalFile.DownloadCallback() {
             public void downloadComplete(FileListEntry file) {
               System.out.println("finished");
               FileListTableModel tm = new FileListTableModel();
               String oldValue = entry.getField(GUIGlobals.FILE_FIELD);
               tm.setContent(oldValue);
               tm.addEntry(tm.getRowCount(), file);
               String newValue = tm.getStringRepresentation();
               UndoableFieldChange edit =
                   new UndoableFieldChange(entry, GUIGlobals.FILE_FIELD, oldValue, newValue);
               entry.setField(GUIGlobals.FILE_FIELD, newValue);
               basePanel.undoManager.addEdit(edit);
               basePanel.markBaseChanged();
             }
           });
     } catch (IOException e) {
       e.printStackTrace();
     }
     basePanel.output(Globals.lang("Finished downloading full text document"));
   } else {
     String message = null;
     switch (result.status) {
       case FindFullText.UNKNOWN_DOMAIN:
         message =
             Globals.lang(
                 "Unable to find full text article. No search algorithm "
                     + "defined for the '%0' web site.",
                 result.host);
         break;
       case FindFullText.WRONG_MIME_TYPE:
         message =
             Globals.lang(
                 "Found pdf link, but received the wrong MIME type. "
                     + "This could indicate that you don't have access to the fulltext article.");
         break;
       case FindFullText.LINK_NOT_FOUND:
         message = Globals.lang("Unable to find full text document in the linked web page.");
         break;
       case FindFullText.IO_EXCEPTION:
         message = Globals.lang("Connection error when trying to find full text document.");
         break;
       case FindFullText.NO_URLS_DEFINED:
         message = Globals.lang("This entry provides no URL or DOI links.");
         break;
     }
     basePanel.output(Globals.lang("Full text article download failed"));
     JOptionPane.showMessageDialog(
         basePanel.frame(),
         message,
         Globals.lang("Full text article download failed"),
         JOptionPane.ERROR_MESSAGE);
   }
 }
Example #24
0
 @Override
 public String getTabName() {
   return Globals.lang("Entry preview");
 }
Example #25
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;
  }
Example #26
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"));
   }
 }
Example #27
0
  public static void main(final String[] args) {
    final JFrame frame = new JFrame();
    frame.setTitle(Globals.getLocalizedString("programName"));
    frame.setBackground(VComponentGlobals.BACKGROUND_COLOR);

    try {
      frame.setIconImage(
          ICODecoder.read(ClassLoader.getSystemResourceAsStream("Art Assets/Icons/Frame_Icon.ico"))
              .get(0));
    } catch (final IOException e) {
      Logger.writeLog(
          Globals.getLocalizedString("DC_error_UnableToLoadIcon"), Logger.LOG_TYPE_ERROR);
    }

    frame.addWindowListener(
        new WindowListener() {
          @Override
          public void windowOpened(WindowEvent e) {}

          @Override
          public void windowClosing(WindowEvent e) {
            System.exit(0);
          }

          @Override
          public void windowClosed(WindowEvent e) {
            System.exit(0);
          }

          @Override
          public void windowIconified(WindowEvent e) {}

          @Override
          public void windowDeiconified(WindowEvent e) {}

          @Override
          public void windowActivated(WindowEvent e) {}

          @Override
          public void windowDeactivated(WindowEvent e) {}
        });

    frame.addComponentListener(
        new ComponentAdapter() {
          public void componentResized(ComponentEvent e) {
            final Dimension currentDimensions = frame.getSize();
            final Dimension minimumDimensions = frame.getMinimumSize();

            if (currentDimensions.width < minimumDimensions.width) {
              currentDimensions.width = minimumDimensions.width;
            }

            if (currentDimensions.height < minimumDimensions.height) {
              currentDimensions.height = minimumDimensions.height;
            }

            frame.setSize(currentDimensions);
          }
        });

    frame.add(new ConnectionScreenController(frame).getView());
    frame.setResizable(false);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
 public void mousePressed(MouseEvent me) {
   super.mousePressed(me);
   Editor ce = Globals.curEditor();
   Selection sel = ce.getSelectionManager().findSelectionFor(this);
   if (sel instanceof SelectionComponentInstance) ((SelectionComponentInstance) sel).hideButtons();
 }
Example #29
0
  /**
   * Draws the GUI that allows a user to select assets to be updated.
   *
   * @return true if the user made a valid choice of assets to replace.
   * @throws PipelineException
   */
  private boolean buildUpdateGUI() throws PipelineException {
    Box finalBox = new Box(BoxLayout.Y_AXIS);
    top = new Box(BoxLayout.Y_AXIS);

    JScrollPane scroll;

    {
      scroll = new JScrollPane(finalBox);

      scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
      scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

      Dimension size = new Dimension(sVSize + sVSize + sTSize + 52, 500);
      scroll.setMinimumSize(size);
      scroll.setPreferredSize(size);
      scroll.getViewport().setScrollMode(JViewport.BACKINGSTORE_SCROLL_MODE);
    }

    /* query the user */
    diag = new JToolDialog("Propagate Asset", scroll, "Continue");

    areas = mclient.getWorkingAreas();
    {
      Box hbox = new Box(BoxLayout.X_AXIS);
      Component comps[] = UIFactory.createTitledPanels();
      JPanel tpanel = (JPanel) comps[0];
      JPanel vpanel = (JPanel) comps[1];
      {
        userField =
            UIFactory.createTitledCollectionField(
                tpanel,
                "User:"******"The user whose area the node is being created in.");
        userField.setActionCommand("user");
        userField.setSelected(PackageInfo.sUser);
        userField.addActionListener(this);
      }
      UIFactory.addVerticalSpacer(tpanel, vpanel, 3);
      {
        viewField =
            UIFactory.createTitledCollectionField(
                tpanel,
                "View:",
                sTSize,
                vpanel,
                areas.get(PackageInfo.sUser),
                diag,
                sVSize,
                "The working area to create the nodes in.");
        viewField.setActionCommand("wrap");
        viewField.addActionListener(this);
      }
      UIFactory.addVerticalSpacer(tpanel, vpanel, 3);
      {
        toolsetField =
            UIFactory.createTitledCollectionField(
                tpanel,
                "Toolset:",
                sTSize,
                vpanel,
                mclient.getActiveToolsetNames(),
                diag,
                sVSize,
                "The toolset to set on all the nodes.");
        toolsetField.setSelected(mclient.getDefaultToolsetName());
        toolsetField.setActionCommand("wrap");
        toolsetField.addActionListener(this);
      }
      UIFactory.addVerticalSpacer(tpanel, vpanel, 3);

      w =
          new Wrapper(
              userField.getSelected(),
              viewField.getSelected(),
              toolsetField.getSelected(),
              mclient);

      charList = SonyConstants.getAssetList(w, project, AssetType.CHARACTER);
      setsList = SonyConstants.getAssetList(w, project, AssetType.SET);
      propsList = SonyConstants.getAssetList(w, project, AssetType.PROP);

      {
        projectField =
            UIFactory.createTitledCollectionField(
                tpanel,
                "Project:",
                sTSize,
                vpanel,
                Globals.getChildrenDirs(w, "/projects"),
                diag,
                sVSize,
                "All the projects in pipeline.");
        projectField.setActionCommand("proj");
        projectField.addActionListener(this);
      }
      hbox.add(comps[2]);
      top.add(hbox);
    }

    {
      Box vbox = new Box(BoxLayout.Y_AXIS);
      Box hbox = new Box(BoxLayout.X_AXIS);
      JButton button = new JButton("Propagate Additional Asset");
      button.setName("ValuePanelButton");
      button.setRolloverEnabled(false);
      button.setFocusable(false);
      Dimension d = new Dimension(sVSize, 25);
      button.setPreferredSize(d);
      button.setMinimumSize(d);
      button.setMaximumSize(new Dimension(Integer.MAX_VALUE, 25));

      vbox.add(Box.createRigidArea(new Dimension(0, 5)));
      hbox.add(button);
      hbox.add(Box.createRigidArea(new Dimension(4, 0)));
      vbox.add(hbox);
      vbox.add(Box.createRigidArea(new Dimension(0, 5)));

      button.setActionCommand("add");
      button.addActionListener(this);

      top.add(vbox);
    }

    list = new Box(BoxLayout.Y_AXIS);
    test = new JDrawer("Propagate Additional Asset", list, false);

    top.add(test);
    list.add(assetChoiceBox());

    finalBox.add(top);

    {
      JPanel spanel = new JPanel();
      spanel.setName("Spacer");
      spanel.setMinimumSize(new Dimension(sTSize + sVSize, 7));
      spanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));
      spanel.setPreferredSize(new Dimension(sTSize + sVSize, 7));
      finalBox.add(spanel);
    }

    diag.setVisible(true);
    if (diag.wasConfirmed()) {
      // get list of things to change.
      for (Component comp : list.getComponents()) {
        if (comp instanceof Box) {
          Box can = (Box) comp;
          JCollectionField oldOne = (JCollectionField) can.getComponent(2);
          JCollectionField newOne = (JCollectionField) can.getComponent(4);

          TreeMap<String, String> assetList = new TreeMap<String, String>();
          assetList.putAll(charList);
          assetList.putAll(propsList);
          assetList.putAll(setsList);

          String key = assetList.get(oldOne.getSelected()) + lr;
          String value = assetList.get(newOne.getSelected()) + lr;
          if (!key.equals(value)) {
            potentialUpdates.add(key);
            pAssetManager.put(key, new AssetInfo(key, value));
          }
          // System.err.println("bUG: "+pAssetManager.get(key).getHiLoResShots());
        }
      }

      if (!pAssetManager.isEmpty()) return true;
    }
    return false;
  } // end buildReplacementGUI
Example #30
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");
  }
}