bebddea58e963fb5eedddf98ee6b92bd3249d5ed
[debian/jabref.git] / src / java / net / sf / jabref / BasePanel.java
1 /*
2 Copyright (C) 2003 Morten O. Alver and Nizar N. Batada
3
4 All programs in this directory and
5 subdirectories are published under the GNU General Public License as
6 described below.
7
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or (at
11 your option) any later version.
12
13 This program is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
21 USA
22
23 Further information about the GNU GPL is available at:
24 http://www.gnu.org/copyleft/gpl.ja.html
25
26
27 */
28
29 package net.sf.jabref;
30
31 import java.awt.*;
32 import java.awt.datatransfer.*;
33 import java.awt.event.*;
34 import java.io.*;
35 import java.util.*;
36 import java.util.List;
37 import java.nio.charset.UnsupportedCharsetException;
38 import javax.swing.*;
39 import javax.swing.tree.TreePath;
40 import javax.swing.undo.*;
41 import net.sf.jabref.collab.*;
42 import net.sf.jabref.export.*;
43 import net.sf.jabref.external.AutoSetExternalFileForEntries;
44 import net.sf.jabref.groups.*;
45 import net.sf.jabref.imports.*;
46 import net.sf.jabref.labelPattern.LabelPatternUtil;
47 import net.sf.jabref.undo.*;
48 import net.sf.jabref.wizard.text.gui.TextInputDialog;
49 import net.sf.jabref.journals.AbbreviateAction;
50 import net.sf.jabref.journals.UnabbreviateAction;
51 import net.sf.jabref.gui.*;
52 import net.sf.jabref.search.NoSearchMatcher;
53 import net.sf.jabref.search.SearchMatcher;
54 import com.jgoodies.uif_lite.component.UIFSplitPane;
55 import com.jgoodies.forms.builder.DefaultFormBuilder;
56 import com.jgoodies.forms.layout.FormLayout;
57 import ca.odell.glazedlists.FilterList;
58 import ca.odell.glazedlists.matchers.Matcher;
59 import ca.odell.glazedlists.event.ListEventListener;
60 import ca.odell.glazedlists.event.ListEvent;
61
62 public class BasePanel extends JPanel implements ClipboardOwner, FileUpdateListener {
63
64     public final static int SHOWING_NOTHING=0, SHOWING_PREVIEW=1, SHOWING_EDITOR=2, WILL_SHOW_EDITOR=3;
65     private int mode=0;
66     private EntryEditor currentEditor = null;
67     private PreviewPanel currentPreview = null;
68
69   boolean tmp = true;
70
71     private MainTableSelectionListener selectionListener = null;
72     private ListEventListener groupsHighlightListener;
73     UIFSplitPane contentPane = new UIFSplitPane();
74
75     JSplitPane splitPane;
76     //BibtexEntry testE = new BibtexEntry("tt");
77     //boolean previewActive = true;
78
79     JabRefFrame frame;
80     BibtexDatabase database;
81     // The database shown in this panel.
82     File file = null,
83         fileToOpen = null; // The filename of the database.
84     String fileMonitorHandle = null;
85     boolean saving = false, updatedExternally = false;
86     private String encoding;
87
88     GridBagLayout gbl = new GridBagLayout();
89     GridBagConstraints con = new GridBagConstraints();
90
91     //Hashtable autoCompleters = new Hashtable();
92     // Hashtable that holds as keys the names of the fields where
93     // autocomplete is active, and references to the autocompleter objects.
94
95     // The undo manager.
96     public CountingUndoManager undoManager = new CountingUndoManager(this);
97     UndoAction undoAction = new UndoAction();
98     RedoAction redoAction = new RedoAction();
99
100     //ExampleFileFilter fileFilter;
101     // File filter for .bib files.
102
103     boolean baseChanged = false, nonUndoableChange = false;
104     // Used to track whether the base has changed since last save.
105
106     //EntryTableModel tableModel = null;
107     //public EntryTable entryTable = null;
108     public MainTable mainTable = null;
109     public FilterList searchFilterList = null, groupFilterList = null;
110
111     public RightClickMenu rcm;
112
113     BibtexEntry showing = null;
114     // To indicate which entry is currently shown.
115     public HashMap entryEditors = new HashMap();
116     // To contain instantiated entry editors. This is to save time
117     // in switching between entries.
118
119     //HashMap entryTypeForms = new HashMap();
120     // Hashmap to keep track of which entries currently have open
121     // EntryTypeForm dialogs.
122
123     PreambleEditor preambleEditor = null;
124     // Keeps track of the preamble dialog if it is open.
125
126     StringDialog stringDialog = null;
127     // Keeps track of the string dialog if it is open.
128
129     /**
130      * The group selector component for this database. Instantiated by the
131      * SidePaneManager if necessary, or from this class if merging groups from a
132      * different database.
133      */
134     //GroupSelector groupSelector;
135
136     public boolean sortingBySearchResults = false,
137         coloringBySearchResults = false,
138     hidingNonHits = false,
139         sortingByGroup = false,
140         sortingByCiteSeerResults = false,
141         coloringByGroup = false;
142         //previewEnabled = Globals.prefs.getBoolean("previewEnabled");
143     int lastSearchHits = -1; // The number of hits in the latest search.
144     // Potential use in hiding non-hits completely.
145
146     // MetaData parses, keeps and writes meta data.
147     MetaData metaData;
148     HashMap fieldExtras = new HashMap();
149     //## keep track of all keys for duplicate key warning and unique key generation
150     //private HashMap allKeys  = new HashMap(); // use a map instead of a set since i need to know how many of each key is inthere
151
152     private boolean suppressOutput = false;
153
154     private HashMap actions = new HashMap();
155     private SidePaneManager sidePaneManager;
156
157     /**
158      * Create a new BasePanel with an empty database.
159      * @param frame The application window.
160      */
161     public BasePanel(JabRefFrame frame) {
162       this.sidePaneManager = Globals.sidePaneManager;
163       database = new BibtexDatabase();
164       metaData = new MetaData();
165         metaData.initializeNewDatabase();
166       this.frame = frame;
167       setupActions();
168       setupMainPanel();
169         encoding = Globals.prefs.get("defaultEncoding");
170         //System.out.println("Default: "+encoding);
171     }
172
173     public BasePanel(JabRefFrame frame, BibtexDatabase db, File file,
174                      HashMap meta, String encoding) {
175
176         this.encoding = encoding;
177        // System.out.println(encoding);
178      //super(JSplitPane.HORIZONTAL_SPLIT, true);
179       this.sidePaneManager = Globals.sidePaneManager;
180       this.frame = frame;
181       database = db;
182       if (meta != null)
183         parseMetaData(meta);
184       else {
185         metaData = new MetaData();
186         metaData.initializeNewDatabase();   
187       }
188       setupActions();
189       setupMainPanel();
190       /*if (Globals.prefs.getBoolean("autoComplete")) {
191             db.setCompleters(autoCompleters);
192             }*/
193
194       this.file = file;
195
196       // Register so we get notifications about outside changes to the file.
197       if (file != null)
198         try {
199           fileMonitorHandle = Globals.fileUpdateMonitor.addUpdateListener(this,
200               file);
201         } catch (IOException ex) {
202         }
203     }
204
205     public int getMode() {
206         return mode;
207     }
208
209     public BibtexDatabase database() { return database; }
210     public MetaData metaData() { return metaData; }
211     public File file() { return file; }
212     public JabRefFrame frame() { return frame; }
213     public JabRefPreferences prefs() { return Globals.prefs; }
214
215     public String getEncoding() { return encoding; }
216     public void setEncoding(String encoding) {
217     this.encoding = encoding;
218     }
219
220     public void output(String s) {
221     //Util.pr("\""+s+"\""+(SwingUtilities.isEventDispatchThread()));
222         if (!suppressOutput)
223             frame.output(s);
224     }
225
226     private void setupActions() {
227
228         actions.put("undo", undoAction);
229         actions.put("redo", redoAction);
230
231         // The action for opening an entry editor.
232         actions.put("edit", new BaseAction() {
233             public void action() {
234                 selectionListener.editSignalled();
235             }
236                 /*
237                   if (isShowingEditor()) {
238                       new FocusRequester(splitPane.getBottomComponent());
239                       return;
240                   }
241
242                   frame.block();
243                 //(new Thread() {
244                 //public void run() {
245                 int clickedOn = -1;
246                 // We demand that one and only one row is selected.
247                 if (entryTable.getSelectedRowCount() == 1) {
248                   clickedOn = entryTable.getSelectedRow();
249                 }
250                 if (clickedOn >= 0) {
251                   String id = tableModel.getIdForRow(clickedOn);
252                   BibtexEntry be = database.getEntryById(id);
253                   showEntry(be);
254
255                   if (splitPane.getBottomComponent() != null) {
256                       new FocusRequester(splitPane.getBottomComponent());
257                   }
258
259                 }
260         frame.unblock();
261               }
262                 */
263             });
264
265
266         actions.put("test", new BaseAction () {
267                 public void action() throws Throwable {
268
269
270
271
272                 }
273             });
274
275
276         // The action for saving a database.
277         actions.put("save", new AbstractWorker() {
278             private boolean success = false;
279             public void init() throws Throwable {
280                 success = false;
281                 if (file == null)
282                     runCommand("saveAs");
283                 else {
284
285                     if (updatedExternally || Globals.fileUpdateMonitor.hasBeenModified(fileMonitorHandle)) {
286                         String[] opts = new String[]{Globals.lang("Review changes"), Globals.lang("Save"),
287                                 Globals.lang("Cancel")};
288                         int answer = JOptionPane.showOptionDialog(frame, Globals.lang("File has been updated externally. "
289                                 + "What do you want to do?"), Globals.lang("File updated externally"),
290                                 JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
291                                 null, opts, opts[0]);
292                         /*  int choice = JOptionPane.showConfirmDialog(frame, Globals.lang("File has been updated externally. "
293 +"Are you sure you want to save?"), Globals.lang("File updated externally"),
294                        JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);*/
295
296                         if (answer == JOptionPane.CANCEL_OPTION)
297                             return;
298                         else if (answer == JOptionPane.YES_OPTION) {
299                             ChangeScanner scanner = new ChangeScanner(frame, BasePanel.this); //, panel.database(), panel.metaData());
300                             //try {
301                             scanner.changeScan(file());
302                             setUpdatedExternally(false);
303                             SwingUtilities.invokeLater(new Runnable() {
304                                 public void run() {
305                                     sidePaneManager.hideAway("fileUpdate");
306                                 }
307                             });
308
309                             //} catch (IOException ex) {
310                             //    ex.printStackTrace();
311                             //}
312
313                             return;
314                         }
315                     }
316
317                     frame.output(Globals.lang("Saving database") + "...");
318                     saving = true;
319                 }
320             }
321
322             public void update() {
323                 if (success) {
324                     frame.setTabTitle(BasePanel.this, file.getName());
325                     frame.output(Globals.lang("Saved database")+" '"
326                              +file.getPath()+"'.");
327                 } else {
328                     frame.output(Globals.lang("Save failed"));
329                 }
330             }
331
332             public void run() {
333                 try {
334                     // If the option is set, autogenerate keys for all entries that are
335                     // lacking keys, before saving:
336                     if (Globals.prefs.getBoolean("generateKeysBeforeSaving")) {
337                         BibtexEntry bes;
338                         NamedCompound ce = new NamedCompound(Globals.lang("autogenerate keys"));
339                         boolean any = false;
340                         for (Iterator i=database.getKeySet().iterator(); i.hasNext();) {
341                             bes = database.getEntryById((String)i.next());
342                             String oldKey = bes.getCiteKey();
343                             if ((oldKey == null) || (oldKey.equals(""))) {
344                                 LabelPatternUtil.makeLabel(Globals.prefs.getKeyPattern(), database, bes);
345                                 ce.addEdit(new UndoableKeyChange(database, bes.getId(), null,
346                                     (String)bes.getField(BibtexFields.KEY_FIELD)));
347                                 any = true;
348                             }
349                         }
350                         // Store undo information, if any:
351                         if (any) {
352                             ce.end();
353                             undoManager.addEdit(ce);
354                         }
355                     }
356                     // Done with autosetting keys. Now save the database:
357
358                     success = saveDatabase(file, false, encoding);
359
360                     //Util.pr("Testing resolve string... BasePanel line 237");
361                     //Util.pr("Resolve aq: "+database.resolveString("aq"));
362                     //Util.pr("Resolve text: "+database.resolveForStrings("A text which refers to the string #aq# and #billball#, hurra."));
363
364                     try {
365                         Globals.fileUpdateMonitor.updateTimeStamp(fileMonitorHandle);
366                     } catch (IllegalArgumentException ex) {
367                         // This means the file has not yet been registered, which is the case
368                         // when doing a "Save as". Maybe we should change the monitor so no
369                         // exception is cast.
370                     }
371                     saving = false;
372                     if (success) {
373                         undoManager.markUnchanged();
374                         // (Only) after a successful save the following
375                         // statement marks that the base is unchanged
376                         // since last save:
377                         nonUndoableChange = false;
378                         baseChanged = false;
379                         updatedExternally = false;
380                     }
381                 } catch (SaveException ex2) {
382                     ex2.printStackTrace();
383                 }
384             }
385         });
386
387         actions.put("saveAs", new BaseAction () {
388                 public void action() throws Throwable {
389
390                   String chosenFile = Globals.getNewFile(frame, new File(Globals.prefs.get("workingDirectory")), ".bib",
391                                                          JFileChooser.SAVE_DIALOG, false);
392
393                   if (chosenFile != null) {
394                     file = new File(chosenFile);
395                     if (!file.exists() ||
396                         (JOptionPane.showConfirmDialog
397                          (frame, "'"+file.getName()+"' "+Globals.lang("exists. Overwrite file?"),
398                           Globals.lang("Save database"), JOptionPane.OK_CANCEL_OPTION)
399                          == JOptionPane.OK_OPTION)) {
400
401                       runCommand("save");
402
403                       // Register so we get notifications about outside changes to the file.
404                       try {
405                         fileMonitorHandle = Globals.fileUpdateMonitor.addUpdateListener(BasePanel.this,file);
406                       } catch (IOException ex) {
407                         ex.printStackTrace();
408                       }
409
410                       Globals.prefs.put("workingDirectory", file.getParent());
411                       frame.getFileHistory().newFile(file.getPath());
412                     }
413                     else
414                       file = null;
415                     }
416                 }
417             });
418
419         actions.put("saveSelectedAs", new BaseAction () {
420                 public void action() throws Throwable {
421
422                   String chosenFile = Globals.getNewFile(frame, new File(Globals.prefs.get("workingDirectory")), ".bib",
423                                                          JFileChooser.SAVE_DIALOG, false);
424                   if (chosenFile != null) {
425                     File expFile = new File(chosenFile);
426                     if (!expFile.exists() ||
427                         (JOptionPane.showConfirmDialog
428                          (frame, "'"+expFile.getName()+"' "+
429                           Globals.lang("exists. Overwrite file?"),
430                           Globals.lang("Save database"), JOptionPane.OK_CANCEL_OPTION)
431                          == JOptionPane.OK_OPTION)) {
432                       saveDatabase(expFile, true, Globals.prefs.get("defaultEncoding"));
433                       //runCommand("save");
434                       frame.getFileHistory().newFile(expFile.getPath());
435                       frame.output(Globals.lang("Saved selected to")+" '"
436                                    +expFile.getPath()+"'.");
437                         }
438                     }
439                 }
440             });
441
442         // The action for copying selected entries.
443         actions.put("copy", new BaseAction() {
444                 public void action() {
445                     BibtexEntry[] bes = mainTable.getSelectedEntries();
446
447                     if ((bes != null) && (bes.length > 0)) {
448                         TransferableBibtexEntry trbe
449                             = new TransferableBibtexEntry(bes);
450                         // ! look at ClipBoardManager
451                         Toolkit.getDefaultToolkit().getSystemClipboard()
452                             .setContents(trbe, BasePanel.this);
453                         output(Globals.lang("Copied")+" "+(bes.length>1 ? bes.length+" "
454                                                            +Globals.lang("entries")
455                                                            : "1 "+Globals.lang("entry")+"."));
456                     } else {
457                         // The user maybe selected a single cell.
458                         int[] rows = mainTable.getSelectedRows(),
459                             cols = mainTable.getSelectedColumns();
460                         if ((cols.length == 1) && (rows.length == 1)) {
461                             // Copy single value.
462                             Object o = mainTable.getValueAt(rows[0], cols[0]);
463                             if (o != null) {
464                                 StringSelection ss = new StringSelection(o.toString());
465                                 Toolkit.getDefaultToolkit().getSystemClipboard()
466                                     .setContents(ss, BasePanel.this);
467
468                                 output(Globals.lang("Copied cell contents")+".");
469                             }
470                         }
471                     }
472                 }
473             });
474
475         actions.put("cut", new BaseAction() {
476                 public void action() throws Throwable {
477                     runCommand("copy");
478                     BibtexEntry[] bes = mainTable.getSelectedEntries();
479                     //int row0 = mainTable.getSelectedRow();
480                     if ((bes != null) && (bes.length > 0)) {
481                         // Create a CompoundEdit to make the action undoable.
482                         NamedCompound ce = new NamedCompound
483                         (Globals.lang(bes.length > 1 ? "cut entries" : "cut entry"));
484                         // Loop through the array of entries, and delete them.
485                         for (int i=0; i<bes.length; i++) {
486                             database.removeEntry(bes[i].getId());
487                             ensureNotShowing(bes[i]);
488                             ce.addEdit(new UndoableRemoveEntry
489                                        (database, bes[i], BasePanel.this));
490                         }
491                         //entryTable.clearSelection();
492                         frame.output(Globals.lang("Cut_pr")+" "+
493                                      (bes.length>1 ? bes.length
494                                       +" "+ Globals.lang("entries")
495                                       : Globals.lang("entry"))+".");
496                         ce.end();
497                         undoManager.addEdit(ce);
498                         markBaseChanged();
499
500                         // Reselect the entry in the first prev. selected position:
501                         /*if (row0 >= entryTable.getRowCount())
502                             row0 = entryTable.getRowCount()-1;
503                         if (row0 >= 0)
504                             entryTable.addRowSelectionInterval(row0, row0);*/
505                     }
506                 }
507             });
508
509         actions.put("delete", new BaseAction() {
510                 public void action() {
511                   boolean cancelled = false;
512                   BibtexEntry[] bes = mainTable.getSelectedEntries();
513                   int row0 = mainTable.getSelectedRow();
514                   if ((bes != null) && (bes.length > 0)) {
515
516                       boolean goOn = showDeleteConfirmationDialog(bes.length);
517                       if (!goOn) {
518                           return;
519                       }
520                       else {
521                           // Create a CompoundEdit to make the action undoable.
522                           NamedCompound ce = new NamedCompound
523                               (Globals.lang(bes.length > 1 ? "delete entries" : "delete entry"));
524                           // Loop through the array of entries, and delete them.
525                           for (int i = 0; i < bes.length; i++) {
526                               database.removeEntry(bes[i].getId());
527                               ensureNotShowing(bes[i]);
528                               ce.addEdit(new UndoableRemoveEntry(database, bes[i], BasePanel.this));
529                           }
530                           markBaseChanged();
531                           frame.output(Globals.lang("Deleted") + " " +
532                                        (bes.length > 1 ? bes.length
533                                         + " " + Globals.lang("entries")
534                                         : Globals.lang("entry")) + ".");
535                           ce.end();
536                           undoManager.addEdit(ce);
537                           //entryTable.clearSelection();
538                       }
539
540
541                           // Reselect the entry in the first prev. selected position:
542                           /*if (row0 >= entryTable.getRowCount())
543                               row0 = entryTable.getRowCount()-1;
544                           if (row0 >= 0) {
545                              final int toSel = row0;
546                             //
547                               SwingUtilities.invokeLater(new Runnable() {
548                                 public void run() {
549                                     entryTable.addRowSelectionInterval(toSel, toSel);
550                                     //entryTable.ensureVisible(toSel);
551                                 }
552                               });
553                             */
554                           }
555
556                       }
557
558             });
559
560         // The action for pasting entries or cell contents.
561         // Edited by Seb Wills <saw27@mrao.cam.ac.uk> on 14-Apr-04:
562         //  - more robust detection of available content flavors (doesn't only look at first one offered)
563         //  - support for parsing string-flavor clipboard contents which are bibtex entries.
564         //    This allows you to (a) paste entire bibtex entries from a text editor, web browser, etc
565         //                       (b) copy and paste entries between multiple instances of JabRef (since
566         //         only the text representation seems to get as far as the X clipboard, at least on my system)
567         actions.put("paste", new BaseAction() {
568                 public void action() {
569                     // Get clipboard contents, and see if TransferableBibtexEntry is among the content flavors offered
570                     Transferable content = Toolkit.getDefaultToolkit()
571                         .getSystemClipboard().getContents(null);
572                     if (content != null) {
573                         BibtexEntry[] bes = null;
574                         if (content.isDataFlavorSupported(TransferableBibtexEntry.entryFlavor)) {
575                             // We have determined that the clipboard data is a set of entries.
576                             try {
577                                 bes = (BibtexEntry[])(content.getTransferData(TransferableBibtexEntry.entryFlavor));
578
579                             } catch (UnsupportedFlavorException ex) {
580                                 ex.printStackTrace();
581                             } catch (IOException ex) {
582                                 ex.printStackTrace();
583                             }
584                         } else if (content.isDataFlavorSupported(DataFlavor.stringFlavor)) {
585                             // We have determined that no TransferableBibtexEntry is available, but
586                             // there is a string, which we will handle according to context:
587                             int[] rows = mainTable.getSelectedRows();
588                                 //cols = entryTable.getSelectedColumns();
589                             //Util.pr(rows.length+" x "+cols.length);
590                             /*if ((cols != null) && (cols.length == 1) && (cols[0] != 0)
591                                 && (rows != null) && (rows.length == 1)) {
592                                 // A single cell is highlighted, so paste the string straight into it without parsing
593                                 try {
594                                     tableModel.setValueAt((String)(content.getTransferData(DataFlavor.stringFlavor)), rows[0], cols[0]);
595                                     refreshTable();
596                                     markBaseChanged();
597                                     output("Pasted cell contents");
598                                 } catch (UnsupportedFlavorException ex) {
599                                     ex.printStackTrace();
600                                 } catch (IOException ex) {
601                                     ex.printStackTrace();
602                                 } catch (IllegalArgumentException ex) {
603                                     output("Can't paste.");
604                                 }
605                             } else {*/
606                               // no single cell is selected, so try parsing the clipboard contents as bibtex entries instead
607                               try {
608                                   BibtexParser bp = new BibtexParser
609                                       (new java.io.StringReader( (String) (content.getTransferData(
610                                       DataFlavor.stringFlavor))));
611                                   BibtexDatabase db = bp.parse().getDatabase();
612                                   Util.pr("Parsed " + db.getEntryCount() + " entries from clipboard text");
613                                   if(db.getEntryCount()>0) {
614                                       Set keySet = db.getKeySet();
615                                       if (keySet != null) {
616                                           // Copy references to the entries into a BibtexEntry array.
617                                           // Could import directly from db, but going via bes allows re-use
618                                           // of the same pasting code as used for TransferableBibtexEntries
619                                           bes = new BibtexEntry[db.getEntryCount()];
620                                           Iterator it = keySet.iterator();
621                                           for (int i=0; it.hasNext();i++) {
622                                               bes[i]=db.getEntryById((String) (it.next()));
623                                           }
624                                       }
625                                   } /*else {
626                                     String cont = (String)(content.getTransferData(DataFlavor.stringFlavor));
627                                     Util.pr("----------------\n"+cont+"\n---------------------");
628                                     TextAnalyzer ta = new TextAnalyzer(cont);
629                                       output(Globals.lang("Unable to parse clipboard text as Bibtex entries."));
630                                       }*/
631                               } catch (UnsupportedFlavorException ex) {
632                                   ex.printStackTrace();
633                               } catch (Throwable ex) {
634                                   ex.printStackTrace();
635                               }
636
637                         }
638
639                         // finally we paste in the entries (if any), which either came from TransferableBibtexEntries
640                         // or were parsed from a string
641                         if ((bes != null) && (bes.length > 0)) {
642
643                           NamedCompound ce = new NamedCompound
644                               (Globals.lang(bes.length > 1 ? "paste entries" : "paste entry"));
645                           for (int i=0; i<bes.length; i++) {
646                             try {
647                               BibtexEntry be = (BibtexEntry)(bes[i].clone());
648                                 Util.setAutomaticFields(be);
649
650                               // We have to clone the
651                               // entries, since the pasted
652                               // entries must exist
653                               // independently of the copied
654                               // ones.
655                               be.setId(Util.createNeutralId());
656                               database.insertEntry(be);
657                               ce.addEdit(new UndoableInsertEntry
658                                          (database, be, BasePanel.this));
659                             } catch (KeyCollisionException ex) {
660                               Util.pr("KeyCollisionException... this shouldn't happen.");
661                             }
662                           }
663                           ce.end();
664                           undoManager.addEdit(ce);
665                           //entryTable.clearSelection();
666                           //entryTable.revalidate();
667                           output(Globals.lang("Pasted")+" "+
668                                  (bes.length>1 ? bes.length+" "+
669                                   Globals.lang("entries") : "1 "+Globals.lang("entry"))
670                                  +".");
671                           markBaseChanged();
672                         }
673                       }
674
675                     }
676
677 });
678
679         actions.put("selectAll", new BaseAction() {
680                 public void action() {
681                     mainTable.selectAll();
682                 }
683             });
684
685         // The action for opening the preamble editor
686         actions.put("editPreamble", new BaseAction() {
687                 public void action() {
688                     if (preambleEditor == null) {
689                         PreambleEditor form = new PreambleEditor
690                             (frame, BasePanel.this, database, Globals.prefs);
691                         Util.placeDialog(form, frame);
692                         form.setVisible(true);
693                         preambleEditor = form;
694                     } else {
695                         preambleEditor.setVisible(true);
696                     }
697
698                 }
699             });
700
701         // The action for opening the string editor
702         actions.put("editStrings", new BaseAction() {
703                 public void action() {
704                     if (stringDialog == null) {
705                         StringDialog form = new StringDialog
706                             (frame, BasePanel.this, database, Globals.prefs);
707                         Util.placeDialog(form, frame);
708                         form.setVisible(true);
709                         stringDialog = form;
710                     } else {
711                         stringDialog.setVisible(true);
712                     }
713
714                 }
715             });
716
717         // The action for toggling the groups interface
718         actions.put("toggleGroups", new BaseAction() {
719             public void action() {
720               sidePaneManager.togglePanel("groups");
721               frame.groupToggle.setSelected(sidePaneManager.isPanelVisible("groups"));
722             }
723         });
724
725
726         // The action for auto-generating keys.
727         actions.put("makeKey", new AbstractWorker() {
728         //int[] rows;
729         List entries;
730         int numSelected;
731         boolean cancelled = false;
732
733         // Run first, in EDT:
734         public void init() {
735
736                     entries = new ArrayList(Arrays.asList(getSelectedEntries()));
737                     //rows = entryTable.getSelectedRows() ;
738                     numSelected = entries.size();
739
740                     if (entries.size() == 0) { // None selected. Inform the user to select entries first.
741                         JOptionPane.showMessageDialog(frame, Globals.lang("First select the entries you want keys to be generated for."),
742                                                       Globals.lang("Autogenerate BibTeX key"), JOptionPane.INFORMATION_MESSAGE);
743                         return ;
744                     }
745             frame.block();
746             output(Globals.lang("Generating BibTeX key for")+" "+
747                            numSelected+" "+(numSelected>1 ? Globals.lang("entries")
748                                             : Globals.lang("entry"))+"...");
749         }
750
751         // Run second, on a different thread:
752                 public void run() {
753                     BibtexEntry bes = null ;
754                     NamedCompound ce = new NamedCompound(Globals.lang("autogenerate keys"));
755                     //BibtexEntry be;
756                     Object oldValue;
757                     boolean hasShownWarning = false;
758                     // First check if any entries have keys set already. If so, possibly remove
759                     // them from consideration, or warn about overwriting keys.
760                     loop: for (Iterator i=entries.iterator(); i.hasNext();) {
761                         bes = (BibtexEntry)i.next();
762                         if (bes.getField(BibtexFields.KEY_FIELD) != null) {
763                             if (Globals.prefs.getBoolean("avoidOverwritingKey"))
764                                 // Rmove the entry, because its key is already set:
765                                 i.remove();
766                             else if (Globals.prefs.getBoolean("warnBeforeOverwritingKey")) {
767                                 // Ask if the user wants to cancel the operation:
768                                 CheckBoxMessage cbm = new CheckBoxMessage(Globals.lang("One or more keys will be overwritten. Continue?"),
769                                         Globals.lang("Disable this confirmation dialog"), false);
770                                 int answer = JOptionPane.showConfirmDialog(frame, cbm, Globals.lang("Overwrite keys"),
771                                         JOptionPane.YES_NO_OPTION);
772                                 if (cbm.isSelected())
773                                     Globals.prefs.putBoolean("warnBeforeOverwritingKey", false);
774                                 if (answer == JOptionPane.NO_OPTION) {
775                                     // Ok, break off the operation.
776                                     cancelled = true;
777                                     return;
778                                 }
779                                 // No need to check more entries, because the user has already confirmed
780                                 // that it's ok to overwrite keys:
781                                 break loop;
782                             }
783                         }
784                     }
785
786                     HashMap oldvals = new HashMap();
787                     // Iterate again, removing already set keys. This is skipped if overwriting
788                     // is disabled, since all entries with keys set will have been removed.
789                     if (!Globals.prefs.getBoolean("avoidOverwritingKey")) for (Iterator i=entries.iterator(); i.hasNext();) {
790                         bes = (BibtexEntry)i.next();
791                         // Store the old value:
792                         oldvals.put(bes, bes.getField(BibtexFields.KEY_FIELD));
793                         database.setCiteKeyForEntry(bes.getId(), null);
794                     }
795
796                     // Finally, set the new keys:
797                     for (Iterator i=entries.iterator(); i.hasNext();) {
798                         bes = (BibtexEntry)i.next();
799                         bes = LabelPatternUtil.makeLabel(Globals.prefs.getKeyPattern(), database, bes);
800                         ce.addEdit(new UndoableKeyChange
801                                    (database, bes.getId(), (String)oldvals.get(bes),
802                                     (String)bes.getField(BibtexFields.KEY_FIELD)));
803                     }
804                     ce.end();
805                     undoManager.addEdit(ce);
806         }
807
808         // Run third, on EDT:
809         public void update() {
810             if (cancelled) {
811                 frame.unblock();
812                 return;
813             }
814             markBaseChanged() ;
815             numSelected = entries.size();
816             output(Globals.lang("Generated BibTeX key for")+" "+
817                numSelected+" "+(numSelected!=1 ? Globals.lang("entries")
818                                     : Globals.lang("entry")));
819             frame.unblock();
820         }
821     });
822
823         actions.put("search", new BaseAction() {
824                 public void action() {
825                     //sidePaneManager.togglePanel("search");
826                     sidePaneManager.ensureVisible("search");
827                     //boolean on = sidePaneManager.isPanelVisible("search");
828                     frame.searchToggle.setSelected(true);
829                     if (true)
830                       frame.searchManager.startSearch();
831                 }
832             });
833
834         actions.put("toggleSearch", new BaseAction() {
835                 public void action() {
836                     //sidePaneManager.togglePanel("search");
837                     sidePaneManager.togglePanel("search");
838                     boolean on = sidePaneManager.isPanelVisible("search");
839                     frame.searchToggle.setSelected(on);
840                     if (on)
841                       frame.searchManager.startSearch();
842                 }
843             });
844
845         actions.put("incSearch", new BaseAction() {
846                 public void action() {
847                     sidePaneManager.ensureVisible("search");
848                     frame.searchToggle.setSelected(true);
849                     frame.searchManager.startIncrementalSearch();
850                 }
851             });
852
853         // The action for copying the selected entry's key.
854         actions.put("copyKey", new BaseAction() {
855                 public void action() {
856                     BibtexEntry[] bes = mainTable.getSelectedEntries();
857                     if ((bes != null) && (bes.length > 0)) {
858                         storeCurrentEdit();
859                         //String[] keys = new String[bes.length];
860                         Vector keys = new Vector();
861                         // Collect all non-null keys.
862                         for (int i=0; i<bes.length; i++)
863                             if (bes[i].getField(BibtexFields.KEY_FIELD) != null)
864                                 keys.add(bes[i].getField(BibtexFields.KEY_FIELD));
865                         if (keys.size() == 0) {
866                             output("None of the selected entries have BibTeX keys.");
867                             return;
868                         }
869                         StringBuffer sb = new StringBuffer((String)keys.elementAt(0));
870                         for (int i=1; i<keys.size(); i++) {
871                             sb.append(',');
872                             sb.append((String)keys.elementAt(i));
873                         }
874
875                         StringSelection ss = new StringSelection(sb.toString());
876                         Toolkit.getDefaultToolkit().getSystemClipboard()
877                             .setContents(ss, BasePanel.this);
878
879                         if (keys.size() == bes.length)
880                             // All entries had keys.
881                             output(Globals.lang((bes.length > 1) ? "Copied keys"
882                                                 : "Copied key")+".");
883                         else
884                             output(Globals.lang("Warning")+": "+(bes.length-keys.size())
885                                    +" "+Globals.lang("out of")+" "+bes.length+" "+
886                                    Globals.lang("entries have undefined BibTeX key")+".");
887                     }
888                 }
889             });
890
891         // The action for copying a cite for the selected entry.
892         actions.put("copyCiteKey", new BaseAction() {
893                 public void action() {
894                     BibtexEntry[] bes = mainTable.getSelectedEntries();
895                     if ((bes != null) && (bes.length > 0)) {
896                         storeCurrentEdit();
897                         //String[] keys = new String[bes.length];
898                         Vector keys = new Vector();
899                         // Collect all non-null keys.
900                         for (int i=0; i<bes.length; i++)
901                             if (bes[i].getField(BibtexFields.KEY_FIELD) != null)
902                                 keys.add(bes[i].getField(BibtexFields.KEY_FIELD));
903                         if (keys.size() == 0) {
904                             output("None of the selected entries have BibTeX keys.");
905                             return;
906                         }
907                         StringBuffer sb = new StringBuffer((String)keys.elementAt(0));
908                         for (int i=1; i<keys.size(); i++) {
909                             sb.append(',');
910                             sb.append((String)keys.elementAt(i));
911                         }
912
913                         StringSelection ss = new StringSelection
914                             ("\\cite{"+sb.toString()+"}");
915                         Toolkit.getDefaultToolkit().getSystemClipboard()
916                             .setContents(ss, BasePanel.this);
917
918                         if (keys.size() == bes.length)
919                             // All entries had keys.
920                             output(Globals.lang((bes.length > 1) ? "Copied keys"
921                                                 : "Copied key")+".");
922                         else
923                             output(Globals.lang("Warning")+": "+(bes.length-keys.size())
924                                    +" "+Globals.lang("out of")+" "+bes.length+" "+
925                                    Globals.lang("entries have undefined BibTeX key")+".");
926                     }
927                 }
928             });
929
930           actions.put("mergeDatabase", new AppendDatabaseAction(frame, this));
931
932          actions.put("openFile", new BaseAction() {
933            public void action() {
934              (new Thread() {
935                public void run() {
936                  BibtexEntry[] bes = mainTable.getSelectedEntries();
937                  String field = "ps";
938                  if ( (bes != null) && (bes.length == 1)) {
939                    Object link = bes[0].getField("ps");
940                    if (bes[0].getField("pdf") != null) {
941                      link = bes[0].getField("pdf");
942                      field = "pdf";
943                    }
944                    String filepath = null;
945                    if (link != null) {
946                      filepath = link.toString();
947                    }
948                    else {
949
950                      // see if we can fall back to a filename based on the bibtex key
951                      String basefile;
952                      Object key = bes[0].getField(BibtexFields.KEY_FIELD);
953                      if (key != null) {
954                        basefile = key.toString();
955                         final String[] types = new String[] {"pdf", "ps"};
956                         final String sep = System.getProperty("file.separator");
957                         for (int i = 0; i < types.length; i++) {
958                             String dir = Globals.prefs.get(types[i]+"Directory");
959                             if (dir.endsWith(sep)) {
960                                 dir = dir.substring(0, dir.length()-sep.length());
961                             }
962                             String found = Util.findPdf(basefile, types[i], dir, new OpenFileFilter("."+types[i]));
963                             if (found != null) {
964                                 filepath = dir+sep+found;
965                                 break;
966                             }
967                         }
968                      }
969                    }
970
971
972                    if (filepath != null) {
973                      //output(Globals.lang("Calling external viewer..."));
974                      try {
975                        Util.openExternalViewer(metaData(), filepath, field);
976                        output(Globals.lang("External viewer called") + ".");
977                      }
978                      catch (IOException ex) {
979                        output(Globals.lang("Error") + ": " + ex.getMessage());
980                      }
981                    }
982                    else
983                      output(Globals.lang(
984                          "No pdf or ps defined, and no file matching Bibtex key found") +
985                             ".");
986                  }
987                  else
988                    output(Globals.lang("No entries or multiple entries selected."));
989                }
990              }).start();
991            }
992          });
993
994
995               actions.put("openUrl", new BaseAction() {
996                       public void action() {
997                           BibtexEntry[] bes = mainTable.getSelectedEntries();
998                           String field = "doi";
999                           if ((bes != null) && (bes.length == 1)) {
1000                               Object link = bes[0].getField("doi");
1001                               if (bes[0].getField("url") != null) {
1002                                 link = bes[0].getField("url");
1003                                 field = "url";
1004                               }
1005                               if (link != null) {
1006                                 //output(Globals.lang("Calling external viewer..."));
1007                                 try {
1008                                   Util.openExternalViewer(metaData(), link.toString(), field);
1009                                   output(Globals.lang("External viewer called")+".");
1010                                 } catch (IOException ex) {
1011                                     output(Globals.lang("Error") + ": " + ex.getMessage());
1012                                 }
1013                               }
1014                               else
1015                                   output(Globals.lang("No url defined")+".");
1016                           } else
1017                             output(Globals.lang("No entries or multiple entries selected."));
1018                       }
1019               });
1020
1021           actions.put("replaceAll", new BaseAction() {
1022                     public void action() {
1023                       ReplaceStringDialog rsd = new ReplaceStringDialog(frame);
1024                       rsd.setVisible(true);
1025                       if (!rsd.okPressed())
1026                           return;
1027                       int counter = 0;
1028                       NamedCompound ce = new NamedCompound(Globals.lang("Replace string"));
1029                       if (!rsd.selOnly()) {
1030                           for (Iterator i=database.getKeySet().iterator();
1031                                i.hasNext();)
1032                               counter += rsd.replace(database.getEntryById((String)i.next()), ce);
1033                       } else {
1034                           BibtexEntry[] bes = mainTable.getSelectedEntries();
1035                           for (int i=0; i<bes.length; i++)
1036                               counter += rsd.replace(bes[i], ce);
1037                       }
1038
1039                       output(Globals.lang("Replaced")+" "+counter+" "+
1040                              Globals.lang(counter==1?"occurence":"occurences")+".");
1041                       if (counter > 0) {
1042                           ce.end();
1043                           undoManager.addEdit(ce);
1044                           markBaseChanged();
1045                       }
1046                   }
1047               });
1048
1049               actions.put("dupliCheck", new BaseAction() {
1050                 public void action() {
1051                   DuplicateSearch ds = new DuplicateSearch(BasePanel.this);
1052                   ds.start();
1053                 }
1054               });
1055
1056               actions.put("strictDupliCheck", new BaseAction() {
1057                 public void action() {
1058                   StrictDuplicateSearch ds = new StrictDuplicateSearch(BasePanel.this);
1059                   ds.start();
1060                 }
1061               });
1062
1063               actions.put("plainTextImport", new BaseAction() {
1064                 public void action()
1065                 {
1066                   // get Type of new entry
1067                   EntryTypeDialog etd = new EntryTypeDialog(frame);
1068                   Util.placeDialog(etd, BasePanel.this);
1069                   etd.setVisible(true);
1070                   BibtexEntryType tp = etd.getChoice();
1071                   if (tp == null)
1072                     return;
1073
1074                   String id = Util.createNeutralId();
1075                   BibtexEntry bibEntry = new BibtexEntry(id, tp) ;
1076                   TextInputDialog tidialog = new TextInputDialog(frame, BasePanel.this,
1077                                                                  "import", true,
1078                                                                  bibEntry) ;
1079                   Util.placeDialog(tidialog, BasePanel.this);
1080                   tidialog.setVisible(true);
1081
1082                   if (tidialog.okPressed())
1083                   {
1084                       Util.setAutomaticFields(Arrays.asList(new BibtexEntry[] {bibEntry}));
1085                     insertEntry(bibEntry) ;
1086                   }
1087                 }
1088               });
1089
1090               // The action starts the "import from plain text" dialog
1091               /*actions.put("importPlainText", new BaseAction() {
1092                       public void action()
1093                       {
1094                         BibtexEntry bibEntry = null ;
1095                         // try to get the first marked entry
1096                         BibtexEntry[] bes = entryTable.getSelectedEntries();
1097                         if ((bes != null) && (bes.length > 0))
1098                           bibEntry = bes[0] ;
1099
1100                         if (bibEntry != null)
1101                         {
1102                           // Create an UndoableInsertEntry object.
1103                           undoManager.addEdit(new UndoableInsertEntry(database, bibEntry, BasePanel.this));
1104
1105                           TextInputDialog tidialog = new TextInputDialog(frame, BasePanel.this,
1106                                                                          "import", true,
1107                                                                          bibEntry) ;
1108                           Util.placeDialog(tidialog, BasePanel.this);
1109                           tidialog.setVisible(true);
1110
1111                           if (tidialog.okPressed())
1112                           {
1113                             output(Globals.lang("changed ")+" '"
1114                                    +bibEntry.getType().getName().toLowerCase()+"' "
1115                                    +Globals.lang("entry")+".");
1116                             refreshTable();
1117                             int row = tableModel.getNumberFromName(bibEntry.getId());
1118
1119                             entryTable.clearSelection();
1120                             entryTable.scrollTo(row);
1121                             markBaseChanged(); // The database just changed.
1122                             if (Globals.prefs.getBoolean("autoOpenForm"))
1123                             {
1124                                   showEntry(bibEntry);
1125                             }
1126                           }
1127                         }
1128                       }
1129                   });
1130                 */
1131               actions.put("markEntries", new AbstractWorker() {
1132                   private int besLength = -1;
1133                 public void run() {
1134
1135                   NamedCompound ce = new NamedCompound(Globals.lang("Mark entries"));
1136                   BibtexEntry[] bes = mainTable.getSelectedEntries();
1137                   besLength = bes.length;
1138           if (bes == null)
1139               return;
1140                   for (int i=0; i<bes.length; i++) {
1141                       Util.markEntry(bes[i], ce);
1142                   }
1143                   ce.end();
1144                   undoManager.addEdit(ce);
1145                 }
1146
1147                 public void update() {
1148                   markBaseChanged();
1149                   output(Globals.lang("Marked selected")+" "+Globals.lang(besLength>0?"entry":"entries"));
1150
1151                 }
1152               });
1153
1154               actions.put("unmarkEntries", new BaseAction() {
1155                 public void action() {
1156                     try {
1157                   NamedCompound ce = new NamedCompound(Globals.lang("Unmark entries"));
1158                   BibtexEntry[] bes = mainTable.getSelectedEntries();
1159           if (bes == null)
1160               return;
1161                   for (int i=0; i<bes.length; i++) {
1162                       Util.unmarkEntry(bes[i], database, ce);
1163                   }
1164                   ce.end();
1165                   undoManager.addEdit(ce);
1166                   markBaseChanged();
1167                   output(Globals.lang("Unmarked selected")+" "+Globals.lang(bes.length>0?"entry":"entries"));
1168                     } catch (Throwable ex) { ex.printStackTrace(); }
1169                 }
1170               });
1171
1172               actions.put("unmarkAll", new BaseAction() {
1173                 public void action() {
1174                   NamedCompound ce = new NamedCompound(Globals.lang("Unmark all"));
1175                   Set keySet = database.getKeySet();
1176                   for (Iterator i = keySet.iterator(); i.hasNext(); ) {
1177                     BibtexEntry be = database.getEntryById( (String) i.next());
1178                     Util.unmarkEntry(be, database, ce);
1179
1180                   }
1181                   ce.end();
1182                   undoManager.addEdit(ce);
1183                   markBaseChanged();
1184                 }
1185               });
1186
1187               actions.put("togglePreview", new BaseAction() {
1188                       public void action() {
1189                           boolean enabled = !Globals.prefs.getBoolean("previewEnabled");
1190                           Globals.prefs.putBoolean("previewEnabled", enabled);
1191                           frame.setPreviewActive(enabled);
1192                           frame.previewToggle.setSelected(enabled);
1193                       }
1194                   });
1195
1196               actions.put("toggleHighlightGroupsMatchingAny", new BaseAction() {
1197                 public void action() {
1198                     boolean enabled = !Globals.prefs.getBoolean("highlightGroupsMatchingAny");
1199                     Globals.prefs.putBoolean("highlightGroupsMatchingAny", enabled);
1200                     frame.highlightAny.setSelected(enabled);
1201                     if (enabled) {
1202                         frame.highlightAll.setSelected(false);
1203                         Globals.prefs.putBoolean("highlightGroupsMatchingAll", false);
1204                     }
1205                     // ping the listener so it updates:
1206                     groupsHighlightListener.listChanged(null);
1207                 }
1208               });
1209
1210               actions.put("toggleHighlightGroupsMatchingAll", new BaseAction() {
1211                   public void action() {
1212                       boolean enabled = !Globals.prefs.getBoolean("highlightGroupsMatchingAll");
1213                       Globals.prefs.putBoolean("highlightGroupsMatchingAll", enabled);
1214                       frame.highlightAll.setSelected(enabled);
1215                       if (enabled) {
1216                           frame.highlightAny.setSelected(false);
1217                           Globals.prefs.putBoolean("highlightGroupsMatchingAny", false);
1218                       }
1219                       // ping the listener so it updates:
1220                       groupsHighlightListener.listChanged(null);
1221                   }
1222                 });
1223
1224               actions.put("switchPreview", new BaseAction() {
1225                       public void action() {
1226                           selectionListener.switchPreview();
1227                       }
1228                   });
1229
1230               actions.put("manageSelectors", new BaseAction() {
1231                       public void action() {
1232                           ContentSelectorDialog2 csd = new ContentSelectorDialog2
1233                               (frame, frame, BasePanel.this, false, metaData, null);
1234                           Util.placeDialog(csd, frame);
1235                           csd.setVisible(true);
1236                       }
1237                   });
1238
1239
1240               actions.put("exportToClipboard", new AbstractWorker() {
1241               String message = null;
1242               public void run() {
1243               if (mainTable.getSelected().size() == 0) {
1244                   message = Globals.lang("No entries selected")+".";
1245                   getCallBack().update();
1246                   return;
1247               }
1248
1249               // Make a list of possible formats:
1250               Map formats = new HashMap();
1251               formats.put("BibTeXML", "bibtexml");
1252               formats.put("DocBook", "docbook");
1253               formats.put("HTML", "html");
1254                           formats.put("RTF (Harvard)", "harvard/harvard");
1255               formats.put("Simple HTML", "simplehtml");
1256               for (int i = 0; i < Globals.prefs.customExports.size(); i++) {
1257                   Object o = (Globals.prefs.customExports.getElementAt(i))[0];
1258                   formats.put(o, o);
1259               }
1260                           Object[] array = formats.keySet().toArray();
1261                           Arrays.sort(array);
1262               JList list = new JList(array);
1263               list.setBorder(BorderFactory.createEtchedBorder());
1264               list.setSelectionInterval(0,0);
1265               list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
1266               int answer =
1267                   JOptionPane.showOptionDialog(frame, list, Globals.lang("Select format"),
1268                                JOptionPane.YES_NO_OPTION,
1269                                JOptionPane.QUESTION_MESSAGE, null,
1270                                new String[] {Globals.lang("Ok"), Globals.lang("Cancel")},
1271                                Globals.lang("Ok"));
1272
1273               if (answer == JOptionPane.NO_OPTION)
1274                   return;
1275
1276               String lfName = (String)(formats.get(list.getSelectedValue()));
1277               final boolean custom = (list.getSelectedIndex() >= Globals.STANDARD_EXPORT_COUNT);
1278               String dir = null;
1279               if (custom) {
1280                   int index = list.getSelectedIndex()-Globals.STANDARD_EXPORT_COUNT;
1281                   dir = (String)(Globals.prefs.customExports.getElementAt(index)[1]);
1282                   File f = new File(dir);
1283                   lfName = f.getName();
1284                   lfName = lfName.substring(0, lfName.indexOf("."));
1285                   // Remove file name - we want the directory only.
1286                   dir = f.getParent()+System.getProperty("file.separator");
1287               }
1288               final String format = lfName,
1289                   directory = dir;
1290
1291               try {
1292                   BibtexEntry[] bes = mainTable.getSelectedEntries();
1293                   StringWriter sw = new StringWriter();
1294                   FileActions.exportEntries(database, bes, format, custom, directory, sw);
1295                   ClipboardOwner owner = new ClipboardOwner() {
1296                     public void lostOwnership(Clipboard clipboard, Transferable content) {}
1297                   };
1298                   //StringSelection ss = new StringSelection(sw.toString());
1299                   RtfSelection rs = new RtfSelection(sw.toString());
1300                      Toolkit.getDefaultToolkit().getSystemClipboard()
1301                         .setContents(rs, owner);
1302                   message = Globals.lang("Entries exported to clipboard")+": "+bes.length;
1303               } catch (Exception ex) {
1304                   ex.printStackTrace();
1305               }
1306               }
1307
1308               public void update() {
1309               output(message);
1310               }
1311
1312           });
1313
1314
1315
1316         actions.put("abbreviateIso", new AbbreviateAction(this, true));
1317         actions.put("abbreviateMedline", new AbbreviateAction(this, false));
1318         actions.put("unabbreviate", new UnabbreviateAction(this));
1319         actions.put("autoSetPdf", new AutoSetExternalFileForEntries(this, "pdf"));
1320         actions.put("autoSetPs", new AutoSetExternalFileForEntries(this, "ps"));
1321
1322     }
1323
1324     /**
1325      * This method is called from JabRefFrame is a database specific
1326      * action is requested by the user. Runs the command if it is
1327      * defined, or prints an error message to the standard error
1328      * stream.
1329      *
1330      * @param _command The name of the command to run.
1331     */
1332     public void runCommand(String _command) {
1333       final String command = _command;
1334       //(new Thread() {
1335       //  public void run() {
1336           if (actions.get(command) == null)
1337             Util.pr("No action defined for'" + command + "'");
1338             else {
1339         Object o = actions.get(command);
1340         try {
1341             if (o instanceof BaseAction)
1342             ((BaseAction)o).action();
1343             else {
1344             // This part uses Spin's features:
1345             Worker wrk = ((AbstractWorker)o).getWorker();
1346             // The Worker returned by getWorker() has been wrapped
1347             // by Spin.off(), which makes its methods be run in
1348             // a different thread from the EDT.
1349             CallBack clb = ((AbstractWorker)o).getCallBack();
1350
1351             ((AbstractWorker)o).init(); // This method runs in this same thread, the EDT.
1352             // Useful for initial GUI actions, like printing a message.
1353
1354             // The CallBack returned by getCallBack() has been wrapped
1355             // by Spin.over(), which makes its methods be run on
1356             // the EDT.
1357             wrk.run(); // Runs the potentially time-consuming action
1358             // without freezing the GUI. The magic is that THIS line
1359             // of execution will not continue until run() is finished.
1360             clb.update(); // Runs the update() method on the EDT.
1361             }
1362         } catch (Throwable ex) {
1363             // If the action has blocked the JabRefFrame before crashing, we need to unblock it.
1364             // The call to unblock will simply hide the glasspane, so there is no harm in calling
1365             // it even if the frame hasn't been blocked.
1366             frame.unblock();
1367             ex.printStackTrace();
1368         }
1369         }
1370       //  }
1371       //}).start();
1372     }
1373
1374     private boolean saveDatabase(File file, boolean selectedOnly, String encoding) throws SaveException {
1375         SaveSession session;
1376         frame.block();
1377         try {
1378             if (!selectedOnly)
1379                 session = FileActions.saveDatabase(database, metaData, file,
1380                                            Globals.prefs, false, false, encoding);
1381             else
1382                 session = FileActions.savePartOfDatabase(database, metaData, file,
1383                                                Globals.prefs, mainTable.getSelectedEntries(), encoding);
1384
1385         } catch (UnsupportedCharsetException ex2) {
1386             JOptionPane.showMessageDialog(frame, Globals.lang("Could not save file. "
1387                 +"Character encoding '%0' is not supported.", encoding),
1388                     Globals.lang("Save database"), JOptionPane.ERROR_MESSAGE);
1389             throw new SaveException("rt");
1390         } catch (SaveException ex) {
1391             if (ex.specificEntry()) {
1392                 // Error occured during processing of
1393                 // be. Highlight it:
1394                 int row = mainTable.findEntry(ex.getEntry()),
1395                     topShow = Math.max(0, row-3);
1396                 mainTable.setRowSelectionInterval(row, row);
1397                 mainTable.scrollTo(topShow);
1398                 showEntry(ex.getEntry());
1399             }
1400             else ex.printStackTrace();
1401
1402             JOptionPane.showMessageDialog
1403                 (frame, Globals.lang("Could not save file")
1404                  +".\n"+ex.getMessage(),
1405                  Globals.lang("Save database"),
1406                  JOptionPane.ERROR_MESSAGE);
1407             throw new SaveException("rt");
1408
1409         } finally {
1410             frame.unblock();
1411         }
1412
1413         boolean commit = true;
1414         if (!session.getWriter().couldEncodeAll()) {
1415             DefaultFormBuilder builder = new DefaultFormBuilder(new FormLayout("left:pref, 4dlu, fill:pref", ""));
1416             JTextArea ta = new JTextArea(session.getWriter().getProblemCharacters());
1417             ta.setEditable(false);
1418             builder.append(Globals.lang("The chosen encoding '%0' could not encode the following characters: ",
1419                       session.getEncoding()));
1420             builder.append(ta);
1421             builder.append(Globals.lang("What do you want to do?"));
1422             String tryDiff = Globals.lang("Try different encoding");
1423             int answer = JOptionPane.showOptionDialog(frame, builder.getPanel(), Globals.lang("Save database"),
1424                     JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null,
1425                     new String[] {Globals.lang("Save"), tryDiff, Globals.lang("Cancel")}, tryDiff);
1426
1427             if (answer == JOptionPane.NO_OPTION) {
1428                 // The user wants to use another encoding.
1429                 Object choice = JOptionPane.showInputDialog(frame, Globals.lang("Select encoding"), Globals.lang("Save database"),
1430                         JOptionPane.QUESTION_MESSAGE, null, Globals.ENCODINGS, encoding);
1431                 if (choice != null) {
1432                     String newEncoding = (String)choice;
1433                     return saveDatabase(file, selectedOnly, newEncoding);
1434                 } else
1435                     commit = false;
1436             } else if (answer == JOptionPane.CANCEL_OPTION)
1437                     commit = false;
1438
1439
1440           }
1441
1442         try {
1443             if (commit) {
1444                 session.commit();
1445                 this.encoding = encoding; // Make sure to remember which encoding we used.
1446             }
1447             else
1448                 session.cancel();
1449         } catch (IOException e) {
1450             e.printStackTrace();
1451         }
1452
1453         return commit;
1454     }
1455
1456
1457     /**
1458      * This method is called from JabRefFrame when the user wants to
1459      * create a new entry. If the argument is null, the user is
1460      * prompted for an entry type.
1461      *
1462      * @param type The type of the entry to create.
1463      */
1464     public void newEntry(BibtexEntryType type) {
1465         if (type == null) {
1466             // Find out what type is wanted.
1467             EntryTypeDialog etd = new EntryTypeDialog(frame);
1468             // We want to center the dialog, to make it look nicer.
1469             Util.placeDialog(etd, frame);
1470             etd.setVisible(true);
1471             type = etd.getChoice();
1472         }
1473         if (type != null) { // Only if the dialog was not cancelled.
1474             String id = Util.createNeutralId();
1475             final BibtexEntry be = new BibtexEntry(id, type);
1476             try {
1477                 database.insertEntry(be);
1478
1479                 // Set owner/timestamp if options are enabled:
1480                 ArrayList list = new ArrayList();
1481                 list.add(be);
1482                 Util.setAutomaticFields(list);
1483
1484                 // Create an UndoableInsertEntry object.
1485                 undoManager.addEdit(new UndoableInsertEntry(database, be, BasePanel.this));
1486                 output(Globals.lang("Added new")+" '"+type.getName().toLowerCase()+"' "
1487                        +Globals.lang("entry")+".");
1488                 final int row = mainTable.findEntry(be);
1489
1490                 // We are going to select the new entry. Before that, make sure that we are in
1491                 // show-entry mode. If we aren't already in that mode, enter the WILL_SHOW_EDITOR
1492                 // mode which makes sure the selection will trigger display of the entry editor
1493                 // and adjustment of the splitter.
1494                 if (mode != SHOWING_EDITOR) {
1495                     mode = WILL_SHOW_EDITOR;
1496                 }
1497
1498                 highlightEntry(be);  // Selects the entry. The selection listener will open the editor.
1499
1500                 markBaseChanged(); // The database just changed.
1501                 new FocusRequester(getEntryEditor(be));
1502             } catch (KeyCollisionException ex) {
1503                 Util.pr(ex.getMessage());
1504             }
1505         }
1506     }
1507
1508
1509
1510     /**
1511      * This method is called from JabRefFrame when the user wants to
1512      * create a new entry.
1513      * @param bibEntry The new entry.
1514      */
1515     public void insertEntry(BibtexEntry bibEntry)
1516     {
1517       if (bibEntry != null)
1518       {
1519         try
1520         {
1521           database.insertEntry(bibEntry) ;
1522           if (Globals.prefs.getBoolean("useOwner"))
1523             // Set owner field to default value
1524             bibEntry.setField(BibtexFields.OWNER, Globals.prefs.get("defaultOwner") );
1525             // Create an UndoableInsertEntry object.
1526             undoManager.addEdit(new UndoableInsertEntry(database, bibEntry, BasePanel.this));
1527             output(Globals.lang("Added new")+" '"
1528                    +bibEntry.getType().getName().toLowerCase()+"' "
1529                    +Globals.lang("entry")+".");
1530             int row = mainTable.findEntry(bibEntry);
1531
1532             mainTable.clearSelection();
1533             mainTable.scrollTo(row);
1534             markBaseChanged(); // The database just changed.
1535             if (Globals.prefs.getBoolean("autoOpenForm"))
1536             {
1537                   showEntry(bibEntry);
1538             }
1539         } catch (KeyCollisionException ex) { Util.pr(ex.getMessage()); }
1540       }
1541     }
1542
1543     public void createMainTable() {
1544         //Comparator comp = new FieldComparator("author");
1545
1546         GlazedEntrySorter eventList = new GlazedEntrySorter(database.getEntryMap(), null);
1547         // Must initialize sort columns somehow:
1548
1549         database.addDatabaseChangeListener(eventList);
1550         groupFilterList = new FilterList(eventList.getTheList(), NoSearchMatcher.INSTANCE);
1551         searchFilterList = new FilterList(groupFilterList, NoSearchMatcher.INSTANCE);
1552         //final SortedList sortedList = new SortedList(searchFilterList, null);
1553         MainTableFormat tableFormat = new MainTableFormat(this);
1554         tableFormat.updateTableFormat();
1555         //EventTableModel tableModel = new EventTableModel(sortedList, tableFormat);
1556         mainTable = new MainTable(/*tableModel, */tableFormat, searchFilterList);
1557         selectionListener = new MainTableSelectionListener(this, mainTable);
1558         mainTable.updateFont();
1559         mainTable.addSelectionListener(selectionListener);
1560         mainTable.addMouseListener(selectionListener);
1561
1562         // Add the listener that will take care of highlighting groups as the selection changes:
1563         groupsHighlightListener = new ListEventListener() {
1564             public void listChanged(ListEvent listEvent) {
1565                 if (Globals.prefs.getBoolean("highlightGroupsMatchingAny"))
1566                     getGroupSelector().showMatchingGroups(
1567                             mainTable.getSelectedEntries(), false);
1568                 else if (Globals.prefs.getBoolean("highlightGroupsMatchingAll"))
1569                     getGroupSelector().showMatchingGroups(
1570                             mainTable.getSelectedEntries(), true);
1571                 else // no highlight
1572                     getGroupSelector().showMatchingGroups(null, true);
1573             }
1574         };
1575         mainTable.addSelectionListener(groupsHighlightListener);
1576
1577         mainTable.getActionMap().put("cut", new AbstractAction() {
1578                 public void actionPerformed(ActionEvent e) {
1579                     try { runCommand("cut");
1580                     } catch (Throwable ex) {
1581                         ex.printStackTrace();
1582                     }
1583                 }
1584             });
1585         mainTable.getActionMap().put("copy", new AbstractAction() {
1586                 public void actionPerformed(ActionEvent e) {
1587                     try { runCommand("copy");
1588                     } catch (Throwable ex) {
1589                         ex.printStackTrace();
1590                     }
1591                 }
1592             });
1593         mainTable.getActionMap().put("paste", new AbstractAction() {
1594                 public void actionPerformed(ActionEvent e) {
1595                     try { runCommand("paste");
1596                     } catch (Throwable ex) {
1597                         ex.printStackTrace();
1598                     }
1599                 }
1600             });
1601
1602         mainTable.addKeyListener(new KeyAdapter() {
1603
1604                 public void keyPressed(KeyEvent e) {
1605                     final int keyCode = e.getKeyCode();
1606                     final TreePath path = frame.groupSelector.getSelectionPath();
1607                     final GroupTreeNode node = path == null ? null : (GroupTreeNode) path.getLastPathComponent();
1608
1609                     if (e.isControlDown()) {
1610                         switch (keyCode) {
1611                         // The up/down/left/rightkeystrokes are displayed in the
1612                         // GroupSelector's popup menu, so if they are to be changed,
1613                         // edit GroupSelector.java accordingly!
1614                         case KeyEvent.VK_UP:
1615                             e.consume();
1616                             if (node != null)
1617                                 frame.groupSelector.moveNodeUp(node, true);
1618                             break;
1619                         case KeyEvent.VK_DOWN:
1620                             e.consume();
1621                             if (node != null)
1622                                 frame.groupSelector.moveNodeDown(node, true);
1623                             break;
1624                         case KeyEvent.VK_LEFT:
1625                             e.consume();
1626                             if (node != null)
1627                                 frame.groupSelector.moveNodeLeft(node, true);
1628                             break;
1629                         case KeyEvent.VK_RIGHT:
1630                             e.consume();
1631                             if (node != null)
1632                                 frame.groupSelector.moveNodeRight(node, true);
1633                             break;
1634                         case KeyEvent.VK_PAGE_DOWN:
1635                             frame.nextTab.actionPerformed(null);
1636                             e.consume();
1637                             break;
1638                         case KeyEvent.VK_PAGE_UP:
1639                             frame.prevTab.actionPerformed(null);
1640                             e.consume();
1641                             break;
1642                         }
1643                     } else if (keyCode == KeyEvent.VK_ENTER){
1644                         e.consume();
1645                         try { runCommand("edit");
1646                         } catch (Throwable ex) {
1647                             ex.printStackTrace();
1648                         }
1649                     }
1650                 }
1651         });
1652     }
1653
1654     public void setupMainPanel() {
1655         //System.out.println("setupMainPanel");
1656         //splitPane = new com.jgoodies.uif_lite.component.UIFSplitPane(JSplitPane.VERTICAL_SPLIT);
1657         splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
1658         splitPane.setDividerSize(GUIGlobals.SPLIT_PANE_DIVIDER_SIZE);
1659         // We replace the default FocusTraversalPolicy with a subclass
1660         // that only allows FieldEditor components to gain keyboard focus,
1661         // if there is an entry editor open.
1662         /*splitPane.setFocusTraversalPolicy(new LayoutFocusTraversalPolicy() {
1663                 protected boolean accept(Component c) {
1664                     Util.pr("jaa");
1665                     if (showing == null)
1666                         return super.accept(c);
1667                     else
1668                         return (super.accept(c) &&
1669                                 (c instanceof FieldEditor));
1670                 }
1671                 });*/
1672
1673         createMainTable();
1674
1675         splitPane.setTopComponent(mainTable.getPane());
1676
1677         //setupTable();
1678         // If an entry is currently being shown, make sure it stays shown,
1679         // otherwise set the bottom component to null.
1680         if (mode == SHOWING_PREVIEW) {
1681             mode = SHOWING_NOTHING;
1682             int row = mainTable.findEntry(currentPreview.entry);
1683             if (row >= 0)
1684                 mainTable.setRowSelectionInterval(row, row);
1685
1686         }
1687         else if (mode == SHOWING_EDITOR) {
1688             mode = SHOWING_NOTHING;
1689             /*int row = mainTable.findEntry(currentEditor.entry);
1690             if (row >= 0)
1691                 mainTable.setRowSelectionInterval(row, row);
1692             */
1693             //showEntryEditor(currentEditor);
1694         } else
1695             splitPane.setBottomComponent(null);
1696
1697
1698         setLayout(new BorderLayout());
1699         removeAll();
1700         add(splitPane, BorderLayout.CENTER);
1701         //add(contentPane, BorderLayout.CENTER);
1702
1703         //add(sidePaneManager.getPanel(), BorderLayout.WEST);
1704         //add(splitPane, BorderLayout.CENTER);
1705
1706     //setLayout(gbl);
1707     //con.fill = GridBagConstraints.BOTH;
1708     //con.weighty = 1;
1709     //con.weightx = 0;
1710     //gbl.setConstraints(sidePaneManager.getPanel(), con);
1711     //con.weightx = 1;
1712     //gbl.setConstraints(splitPane, con);
1713         //mainPanel.setDividerLocation(GUIGlobals.SPLIT_PANE_DIVIDER_LOCATION);
1714         //setDividerSize(GUIGlobals.SPLIT_PANE_DIVIDER_SIZE);
1715         //setResizeWeight(0);
1716         splitPane.revalidate();
1717         revalidate();
1718         repaint();
1719     }
1720
1721
1722     /**
1723      * This method is called after a database has been parsed. The
1724      * hashmap contains the contents of all comments in the .bib file
1725      * that started with the meta flag (GUIGlobals.META_FLAG).
1726      * In this method, the meta data are input to their respective
1727      * handlers.
1728      *
1729      * @param meta Metadata to input.
1730      */
1731     public void parseMetaData(HashMap meta) {
1732         metaData = new MetaData(meta,database());
1733
1734     }
1735
1736     /*
1737     public void refreshTable() {
1738         //System.out.println("hiding="+hidingNonHits+"\tlastHits="+lastSearchHits);
1739         // This method is called by EntryTypeForm when a field value is
1740         // stored. The table is scheduled for repaint.
1741         entryTable.assureNotEditing();
1742         //entryTable.invalidate();
1743         BibtexEntry[] bes = entryTable.getSelectedEntries();
1744     if (hidingNonHits)
1745         tableModel.update(lastSearchHits);
1746     else
1747         tableModel.update();
1748     //tableModel.remap();
1749         if ((bes != null) && (bes.length > 0))
1750             selectEntries(bes, 0);
1751
1752     //long toc = System.currentTimeMillis();
1753     //  Util.pr("Refresh took: "+(toc-tic)+" ms");
1754     } */
1755
1756     public void updatePreamble() {
1757         if (preambleEditor != null)
1758             preambleEditor.updatePreamble();
1759     }
1760
1761     public void assureStringDialogNotEditing() {
1762         if (stringDialog != null)
1763             stringDialog.assureNotEditing();
1764     }
1765
1766     public void updateStringDialog() {
1767         if (stringDialog != null)
1768             stringDialog.refreshTable();
1769     }
1770
1771     public void updateEntryPreviewToRow(BibtexEntry e) {
1772
1773     }
1774
1775     public void adjustSplitter() {
1776         int mode = getMode();
1777         if (mode == SHOWING_PREVIEW) {
1778             splitPane.setDividerLocation(splitPane.getHeight()-GUIGlobals.PREVIEW_PANEL_HEIGHT);
1779         } else {
1780             splitPane.setDividerLocation(GUIGlobals.VERTICAL_DIVIDER_LOCATION);
1781
1782         }
1783     }
1784
1785
1786
1787     /**
1788      * Stores the source view in the entry editor, if one is open, has the source view
1789      * selected and the source has been edited.
1790      * @return boolean false if there is a validation error in the source panel, true otherwise.
1791      */
1792     public boolean entryEditorAllowsChange() {
1793       Component c = splitPane.getBottomComponent();
1794       if ((c != null) && (c instanceof EntryEditor)) {
1795         return ((EntryEditor)c).lastSourceAccepted();
1796       }
1797       else
1798         return true;
1799     }
1800
1801     public void moveFocusToEntryEditor() {
1802       Component c = splitPane.getBottomComponent();
1803       if ((c != null) && (c instanceof EntryEditor)) {
1804         new FocusRequester(c);
1805       }
1806     }
1807
1808     /**
1809      * Ensure that no preview is shown. Called when preview is turned off. Must chech if
1810      * a preview is in fact visible before doing anything rash.
1811      */
1812     public void hidePreview() {
1813         Globals.prefs.putBoolean("previewEnabled", false);
1814
1815       Component c = splitPane.getBottomComponent();
1816       if ((c != null) && !(c instanceof EntryEditor))
1817         splitPane.setBottomComponent(null);
1818     }
1819
1820     public boolean isShowingEditor() {
1821       return ((splitPane.getBottomComponent() != null)
1822               && (splitPane.getBottomComponent() instanceof EntryEditor));
1823     }
1824
1825     public void showEntry(final BibtexEntry be) {
1826         if (showing == be) {
1827             if (splitPane.getBottomComponent() == null) {
1828                 // This is the special occasion when showing is set to an
1829                 // entry, but no entry editor is in fact shown. This happens
1830                 // after Preferences dialog is closed, and it means that we
1831                 // must make sure the same entry is shown again. We do this by
1832                 // setting showing to null, and recursively calling this method.
1833                 showing = null;
1834                 showEntry(be);
1835             } else {
1836               // The correct entry is already being shown. Make sure the editor
1837               // is updated.
1838               ((EntryEditor)splitPane.getBottomComponent()).updateAllFields();
1839
1840             }
1841             return;
1842
1843         }
1844
1845         EntryEditor form;
1846         int divLoc = -1;
1847         String visName = null;
1848         if (showing != null) {
1849             visName = ((EntryEditor)splitPane.getBottomComponent()).
1850                 getVisiblePanelName();
1851         }
1852         if (showing != null)
1853             divLoc = splitPane.getDividerLocation();
1854
1855         if (entryEditors.containsKey(be.getType().getName())) {
1856             // We already have an editor for this entry type.
1857             form = (EntryEditor)entryEditors.get
1858                 ((be.getType().getName()));
1859             form.switchTo(be);
1860             if (visName != null)
1861                 form.setVisiblePanel(visName);
1862             splitPane.setBottomComponent(form);
1863             //highlightEntry(be);
1864         } else {
1865             // We must instantiate a new editor for this type.
1866             form = new EntryEditor(frame, BasePanel.this, be);
1867             if (visName != null)
1868                 form.setVisiblePanel(visName);
1869             splitPane.setBottomComponent(form);
1870
1871             //highlightEntry(be);
1872             entryEditors.put(be.getType().getName(), form);
1873
1874         }
1875         if (divLoc > 0) {
1876           splitPane.setDividerLocation(divLoc);
1877         }
1878         else
1879             splitPane.setDividerLocation
1880                 (GUIGlobals.VERTICAL_DIVIDER_LOCATION);
1881         //new FocusRequester(form);
1882         //form.requestFocus();
1883
1884         showing = be;
1885         setEntryEditorEnabled(true); // Make sure it is enabled.
1886     }
1887
1888     /**
1889      * Get an entry editor ready to edit the given entry. If an appropriate editor is already
1890      * cached, it will be updated and returned.
1891      * @param entry The entry to be edited.
1892      * @return A suitable entry editor.
1893      */
1894     public EntryEditor getEntryEditor(BibtexEntry entry) {
1895         EntryEditor form;
1896         if (entryEditors.containsKey(entry.getType().getName())) {
1897             EntryEditor visibleNow = currentEditor;
1898             // We already have an editor for this entry type.
1899             form = (EntryEditor)entryEditors.get
1900                 ((entry.getType().getName()));
1901
1902             form.switchTo(entry);
1903             //if (visName != null)
1904             //    form.setVisiblePanel(visName);
1905         } else {
1906             // We must instantiate a new editor for this type.
1907             form = new EntryEditor(frame, BasePanel.this, entry);
1908             //if (visName != null)
1909             //    form.setVisiblePanel(visName);
1910
1911             entryEditors.put(entry.getType().getName(), form);
1912         }
1913         return form;
1914     }
1915
1916     public EntryEditor getCurrentEditor() {
1917         return currentEditor;
1918     }
1919
1920     /**
1921      * Sets the given entry editor as the bottom component in the split pane. If an entry editor already
1922      * was shown, makes sure that the divider doesn't move.
1923      * Updates the mode to SHOWING_EDITOR.
1924      * @param editor The entry editor to add.
1925      */
1926     public void showEntryEditor(EntryEditor editor) {
1927         int oldSplitterLocation = -1;
1928         if (mode == SHOWING_EDITOR)
1929             oldSplitterLocation = splitPane.getDividerLocation();
1930         boolean adjustSplitter = (mode == WILL_SHOW_EDITOR);
1931         mode = SHOWING_EDITOR;
1932         currentEditor = editor;
1933         splitPane.setBottomComponent(editor);
1934         if (oldSplitterLocation > 0)
1935             splitPane.setDividerLocation(oldSplitterLocation);
1936         if (adjustSplitter) {
1937             adjustSplitter();
1938             //new FocusRequester(editor);
1939         }
1940     }
1941
1942     /**
1943      * Sets the given preview panel as the bottom component in the split panel.
1944      * Updates the mode to SHOWING_PREVIEW.
1945      * @param preview The preview to show.
1946      */
1947     public void showPreview(PreviewPanel preview) {
1948         mode = SHOWING_PREVIEW;
1949         currentPreview = preview;
1950         splitPane.setBottomComponent(preview.getPane());
1951     }
1952
1953     /**
1954      * Removes the bottom component.
1955      */
1956     public void hideBottomComponent() {
1957         mode = SHOWING_NOTHING;
1958         splitPane.setBottomComponent(null);
1959     }
1960
1961     /**
1962      * This method selects the given entry, and scrolls it into view in the table.
1963      * If an entryEditor is shown, it is given focus afterwards.
1964      */
1965     public void highlightEntry(final BibtexEntry be) {
1966         //SwingUtilities.invokeLater(new Thread() {
1967         //     public void run() {
1968                  final int row = mainTable.findEntry(be);
1969                  if (row >= 0) {
1970                     mainTable.setRowSelectionInterval(row, row);
1971                     //entryTable.setActiveRow(row);
1972                     mainTable.ensureVisible(row);
1973                  }
1974         //     }
1975         //});
1976     }
1977
1978
1979     /**
1980      * This method is called from an EntryEditor when it should be closed. We relay
1981      * to the selection listener, which takes care of the rest.
1982      * @param editor The entry editor to close.
1983      */
1984     public void entryEditorClosing(EntryEditor editor) {
1985         selectionListener.entryEditorClosing(editor);
1986     }
1987
1988     /**
1989      * This method selects the given enties.
1990      * If an entryEditor is shown, it is given focus afterwards.
1991      */
1992     /*public void selectEntries(final BibtexEntry[] bes, final int toScrollTo) {
1993
1994         SwingUtilities.invokeLater(new Thread() {
1995              public void run() {
1996                  int rowToScrollTo = 0;
1997                  entryTable.revalidate();
1998                  entryTable.clearSelection();
1999                  loop: for (int i=0; i<bes.length; i++) {
2000                     if (bes[i] == null)
2001                         continue loop;
2002                     int row = tableModel.getNumberFromName(bes[i].getId());
2003                     if (i==toScrollTo)
2004                     rowToScrollTo = row;
2005                     if (row >= 0)
2006                         entryTable.addRowSelectionIntervalQuietly(row, row);
2007                  }
2008                  entryTable.ensureVisible(rowToScrollTo);
2009                  Component comp = splitPane.getBottomComponent();
2010                  //if (comp instanceof EntryEditor)
2011                  //    comp.requestFocus();
2012              }
2013         });
2014     } */
2015
2016     /**
2017      * Closes the entry editor if it is showing the given entry.
2018      *
2019      * @param be a <code>BibtexEntry</code> value
2020      */
2021     public void ensureNotShowing(BibtexEntry be) {
2022         if ((mode == SHOWING_EDITOR) && (currentEditor.getEntry() == be)) {
2023             selectionListener.entryEditorClosing(currentEditor);
2024         }
2025     }
2026
2027     public void updateEntryEditorIfShowing() {
2028         if (mode == SHOWING_EDITOR) {
2029             if (currentEditor.getType() != currentEditor.getEntry().getType()) {
2030                 // The entry has changed type, so we must get a new editor.
2031                 showing = null;
2032                 EntryEditor newEditor = getEntryEditor(currentEditor.getEntry());
2033                 showEntryEditor(newEditor);
2034             } else {
2035                 currentEditor.updateAllFields();
2036                 currentEditor.updateSource();
2037             }
2038         }
2039     }
2040
2041     /**
2042      * If an entry editor is showing, make sure its currently focused field
2043      * stores its changes, if any.
2044      */
2045     public void storeCurrentEdit() {
2046         if (isShowingEditor()) {
2047             EntryEditor editor = (EntryEditor)splitPane.getBottomComponent();
2048             editor.storeCurrentEdit();
2049         }
2050
2051     }
2052
2053     /**
2054      * This method iterates through all existing entry editors in this
2055      * BasePanel, telling each to update all its instances of
2056      * FieldContentSelector. This is done to ensure that the list of words
2057      * in each selector is up-to-date after the user has made changes in
2058      * the Manage dialog.
2059      */
2060     public void updateAllContentSelectors() {
2061         for (Iterator i=entryEditors.keySet().iterator(); i.hasNext();) {
2062             EntryEditor ed = (EntryEditor)entryEditors.get(i.next());
2063             ed.updateAllContentSelectors();
2064         }
2065     }
2066
2067     public void rebuildAllEntryEditors() {
2068         for (Iterator i=entryEditors.keySet().iterator(); i.hasNext();) {
2069             EntryEditor ed = (EntryEditor)entryEditors.get(i.next());
2070             ed.rebuildPanels();
2071         }
2072
2073     }
2074
2075     public void markBaseChanged() {
2076         baseChanged = true;
2077
2078         // Put an asterix behind the file name to indicate the
2079         // database has changed.
2080         String oldTitle = frame.getTabTitle(this);
2081         if (!oldTitle.endsWith("*"))
2082             frame.setTabTitle(this, oldTitle+"*");
2083
2084         // If the status line states that the base has been saved, we
2085         // remove this message, since it is no longer relevant. If a
2086         // different message is shown, we leave it.
2087         if (frame.statusLine.getText().startsWith("Saved database"))
2088             frame.output(" ");
2089     }
2090
2091     public void markNonUndoableBaseChanged() {
2092         nonUndoableChange = true;
2093         markBaseChanged();
2094     }
2095
2096     public synchronized void markChangedOrUnChanged() {
2097         if (undoManager.hasChanged()) {
2098             if (!baseChanged)
2099                 markBaseChanged();
2100         }
2101         else if (baseChanged && !nonUndoableChange) {
2102             baseChanged = false;
2103             if (file != null)
2104                 frame.setTabTitle(BasePanel.this, file.getName());
2105             else
2106                 frame.setTabTitle(BasePanel.this, Globals.lang("untitled"));
2107         }
2108     }
2109
2110     /**
2111      * Selects a single entry, and scrolls the table to center it.
2112      *
2113      * @param pos Current position of entry to select.
2114      *
2115      */
2116     public void selectSingleEntry(int pos) {
2117         mainTable.clearSelection();
2118         mainTable.addRowSelectionInterval(pos, pos);
2119         mainTable.scrollToCenter(pos, 0);
2120     }
2121
2122     /* *
2123      * Selects all entries with a non-zero value in the field
2124      * @param field <code>String</code> field name.
2125      */
2126 /*    public void selectResults(String field) {
2127       LinkedList intervals = new LinkedList();
2128       int prevStart = -1, prevToSel = 0;
2129       // First we build a list of intervals to select, without touching the table.
2130       for (int i = 0; i < entryTable.getRowCount(); i++) {
2131         String value = (String) (database.getEntryById
2132                                  (tableModel.getIdForRow(i)))
2133             .getField(field);
2134         if ( (value != null) && !value.equals("0")) {
2135           if (prevStart < 0)
2136             prevStart = i;
2137           prevToSel = i;
2138         }
2139         else if (prevStart >= 0) {
2140           intervals.add(new int[] {prevStart, prevToSel});
2141           prevStart = -1;
2142         }
2143       }
2144       // Then select those intervals, if any.
2145       if (intervals.size() > 0) {
2146         entryTable.setSelectionListenerEnabled(false);
2147         entryTable.clearSelection();
2148         for (Iterator i=intervals.iterator(); i.hasNext();) {
2149           int[] interval = (int[])i.next();
2150           entryTable.addRowSelectionInterval(interval[0], interval[1]);
2151         }
2152         entryTable.setSelectionListenerEnabled(true);
2153       }
2154   */
2155
2156     public void setSearchMatcher(SearchMatcher matcher) {
2157         searchFilterList.setMatcher(matcher);
2158     }
2159
2160     public void setGroupMatcher(Matcher matcher) {
2161         groupFilterList.setMatcher(matcher);
2162     }
2163
2164     public void stopShowingSearchResults() {
2165         searchFilterList.setMatcher(NoSearchMatcher.INSTANCE);
2166     }
2167
2168     public void stopShowingGroup() {
2169         groupFilterList.setMatcher(NoSearchMatcher.INSTANCE);
2170
2171      }
2172
2173      public BibtexDatabase getDatabase(){
2174         return database ;
2175     }
2176
2177     public void preambleEditorClosing() {
2178         preambleEditor = null;
2179     }
2180
2181     public void stringsClosing() {
2182         stringDialog = null;
2183     }
2184
2185     public void changeType(BibtexEntry entry, BibtexEntryType type) {
2186       changeType(new BibtexEntry[] {entry}, type);
2187     }
2188
2189     public void changeType(BibtexEntryType type) {
2190       BibtexEntry[] bes = mainTable.getSelectedEntries();
2191       changeType(bes, type);
2192     }
2193
2194     public void changeType(BibtexEntry[] bes, BibtexEntryType type) {
2195
2196         if ((bes == null) || (bes.length == 0)) {
2197             output("First select the entries you wish to change type "+
2198                    "for.");
2199             return;
2200         }
2201         if (bes.length > 1) {
2202             int choice = JOptionPane.showConfirmDialog
2203                 (this, "Multiple entries selected. Do you want to change"
2204                  +"\nthe type of all these to '"+type.getName()+"'?",
2205                  "Change type", JOptionPane.YES_NO_OPTION,
2206                  JOptionPane.WARNING_MESSAGE);
2207             if (choice == JOptionPane.NO_OPTION)
2208                 return;
2209         }
2210
2211         NamedCompound ce = new NamedCompound(Globals.lang("change type"));
2212         for (int i=0; i<bes.length; i++) {
2213             ce.addEdit(new UndoableChangeType(bes[i],
2214                                               bes[i].getType(),
2215                                               type));
2216             bes[i].setType(type);
2217         }
2218
2219         output(Globals.lang("Changed type to")+" '"+type.getName()+"' "
2220                +Globals.lang("for")+" "+bes.length
2221                +" "+Globals.lang("entries")+".");
2222         ce.end();
2223         undoManager.addEdit(ce);
2224         markBaseChanged();
2225         updateEntryEditorIfShowing();
2226     }
2227
2228     public boolean showDeleteConfirmationDialog(int numberOfEntries) {
2229         if (Globals.prefs.getBoolean("confirmDelete")) {
2230             String msg = Globals.lang("Really delete the selected")
2231                 + " " + Globals.lang("entry") + "?",
2232                 title = Globals.lang("Delete entry");
2233             if (numberOfEntries > 1) {
2234                 msg = Globals.lang("Really delete the selected")
2235                     + " " + numberOfEntries + " " + Globals.lang("entries") + "?";
2236                 title = Globals.lang("Delete multiple entries");
2237             }
2238
2239             CheckBoxMessage cb = new CheckBoxMessage
2240                 (msg, Globals.lang("Disable this confirmation dialog"), false);
2241
2242             int answer = JOptionPane.showConfirmDialog(frame, cb, title,
2243                                                        JOptionPane.YES_NO_OPTION,
2244                                                        JOptionPane.QUESTION_MESSAGE);
2245             if (cb.isSelected())
2246                 Globals.prefs.putBoolean("confirmDelete", false);
2247             return (answer == JOptionPane.YES_OPTION);
2248         } else return true;
2249
2250     }
2251
2252     /**
2253      * Activates or deactivates the entry preview, depending on the argument.
2254      * When deactivating, makes sure that any visible preview is hidden.
2255      * @param enabled
2256      */
2257     public void setPreviewActive(boolean enabled) {
2258         selectionListener.setPreviewActive(enabled);
2259     }
2260
2261
2262     class UndoAction extends BaseAction {
2263         public void action() {
2264             try {
2265                 String name = undoManager.getUndoPresentationName();
2266                 undoManager.undo();
2267                 markBaseChanged();
2268                 frame.output(name);
2269             } catch (CannotUndoException ex) {
2270                 frame.output(Globals.lang("Nothing to undo")+".");
2271             }
2272             // After everything, enable/disable the undo/redo actions
2273             // appropriately.
2274             //updateUndoState();
2275             //redoAction.updateRedoState();
2276             markChangedOrUnChanged();
2277         }
2278     }
2279
2280     class RedoAction extends BaseAction {
2281         public void action() {
2282             try {
2283                 String name = undoManager.getRedoPresentationName();
2284                 undoManager.redo();
2285                 markBaseChanged();
2286                 frame.output(name);
2287             } catch (CannotRedoException ex) {
2288                 frame.output(Globals.lang("Nothing to redo")+".");
2289             }
2290             // After everything, enable/disable the undo/redo actions
2291             // appropriately.
2292             //updateRedoState();
2293             //undoAction.updateUndoState();
2294             markChangedOrUnChanged();
2295         }
2296     }
2297
2298     // Method pertaining to the ClipboardOwner interface.
2299     public void lostOwnership(Clipboard clipboard, Transferable contents) {}
2300
2301
2302   public void setEntryEditorEnabled(boolean enabled) {
2303     if ((showing != null) && (splitPane.getBottomComponent() instanceof EntryEditor)) {
2304           EntryEditor ed = (EntryEditor)splitPane.getBottomComponent();
2305           if (ed.isEnabled() != enabled)
2306             ed.setEnabled(enabled);
2307     }
2308   }
2309
2310   public String fileMonitorHandle() { return fileMonitorHandle; }
2311
2312     public void fileUpdated() {
2313       if (saving)
2314         return; // We are just saving the file, so this message is most likely due
2315       // to bad timing. If not, we'll handle it on the next polling.
2316       //Util.pr("File '"+file.getPath()+"' has been modified.");
2317       updatedExternally = true;
2318
2319       // Adding the sidepane component is Swing work, so we must do this in the Swing
2320       // thread:
2321       Thread t = new Thread() {
2322         public void run() {
2323             // Test: running scan automatically in background
2324             ChangeScanner scanner = new ChangeScanner(frame, BasePanel.this);
2325             scanner.changeScan(BasePanel.this.file());
2326             try {
2327                 scanner.join();
2328             } catch (InterruptedException e) {
2329                 e.printStackTrace();
2330             }
2331
2332             if (scanner.changesFound()) {
2333                 FileUpdatePanel pan = new FileUpdatePanel(frame, BasePanel.this, sidePaneManager, file, scanner);
2334           sidePaneManager.add("fileUpdate", pan);
2335                 setUpdatedExternally(false);
2336                 //scanner.displayResult();
2337             } else {
2338                 setUpdatedExternally(false);
2339                 //System.out.println("No changes found.");
2340         }
2341
2342         }
2343       };
2344       SwingUtilities.invokeLater(t);
2345
2346     }
2347
2348       public void fileRemoved() {
2349         Util.pr("File '"+file.getPath()+"' has been deleted.");
2350       }
2351
2352
2353       public void cleanUp() {
2354         if (fileMonitorHandle != null)
2355           Globals.fileUpdateMonitor.removeUpdateListener(fileMonitorHandle);
2356       }
2357
2358   public void setUpdatedExternally(boolean b) {
2359     updatedExternally = b;
2360   }
2361
2362     /**
2363      * Get an array containing the currently selected entries.
2364      *
2365      * @return An array containing the selected entries.
2366      */
2367     public BibtexEntry[] getSelectedEntries() {
2368         return mainTable.getSelectedEntries();
2369     }
2370
2371     /**
2372      * Get a String containing a comma-separated list of the bibtex keys
2373      * of the selected entries.
2374      *
2375      * @return A comma-separated list of the keys of the selected entries.
2376      */
2377     public String getKeysForSelection() {
2378         List entries = mainTable.getSelected();
2379         StringBuffer result = new StringBuffer();
2380         String citeKey = "";//, message = "";
2381         boolean first = true;
2382         for (Iterator i = entries.iterator(); i.hasNext();) {
2383             BibtexEntry bes = (BibtexEntry) i.next();
2384             citeKey = (String) bes.getField(BibtexFields.KEY_FIELD);
2385             // if the key is empty we give a warning and ignore this entry
2386             if (citeKey == null || citeKey.equals(""))
2387                 continue;
2388             if (first) {
2389                 result.append(citeKey);
2390                 first = false;
2391             } else {
2392                 result.append(",").append(citeKey);
2393             }
2394         }
2395         return result.toString();
2396     }
2397
2398     public GroupSelector getGroupSelector() {
2399         return frame.groupSelector;
2400     }
2401
2402 }