edfbd36ac2d348ebe25f330cba69755d1472f2d6
[debian/jabref.git] / src / java / net / sf / jabref / JabRef.java
1 /*
2  * Copyright (C) 2003 Morten O. Alver, Nizar N. Batada
3  * 
4  * All programs in this directory and subdirectories are published under the GNU
5  * General Public License as described below.
6  *
7  * This program is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU General Public License as published by the Free Software
9  * Foundation; either version 2 of the License, or (at your option) any later
10  * version.
11  *
12  * This program is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
15  * details.
16  *
17  * You should have received a copy of the GNU General Public License along with
18  * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
19  * Place, Suite 330, Boston, MA 02111-1307 USA
20  *
21  * Further information about the GNU GPL is available at:
22  * http://www.gnu.org/copyleft/gpl.ja.html
23  *
24  */
25 package net.sf.jabref;
26
27 import net.sf.jabref.export.*;
28 import net.sf.jabref.imports.*;
29 import net.sf.jabref.wizard.auximport.*;
30 import net.sf.jabref.remote.RemoteListener;
31
32 import gnu.dtools.ritopt.*;
33 import java.awt.*;
34 import java.awt.event.KeyEvent;
35
36 import java.io.*;
37 import java.io.File;
38
39 import java.util.*;
40 import java.util.List;
41 import java.lang.reflect.Method;
42 import java.lang.reflect.InvocationTargetException;
43
44 import javax.swing.*;
45 import javax.swing.plaf.metal.MetalLookAndFeel;
46
47 import com.jgoodies.looks.plastic.Plastic3DLookAndFeel;
48 import com.jgoodies.looks.plastic.PlasticLookAndFeel;
49 import com.jgoodies.looks.windows.WindowsLookAndFeel;
50 import com.jgoodies.looks.FontSet;
51 import com.jgoodies.looks.FontSets;
52 import com.jgoodies.looks.FontPolicy;
53 import com.jgoodies.looks.FontPolicies;
54
55 //import javax.swing.UIManager;
56 //import javax.swing.UIDefaults;
57 //import javax.swing.UnsupportedLookAndFeelException;
58 public class JabRef {
59     public static JabRef ths;
60     public static RemoteListener remoteListener = null;
61     public JabRefFrame jrf;
62     public Options options;
63     public Frame splashScreen = null;
64
65     boolean graphicFailure = false;
66
67     StringOption importFile, exportFile, exportPrefs, importPrefs, auxImExport, importToOpenBase;
68     BooleanOption helpO, disableGui, blank, loadSess, showVersion, disableSplash;
69     /*
70     * class StringArrayOption extends ArrayOption { public public void
71     * modify(String value) { } public void modify(String[] value) { } public
72     * Object[] getObjectArray() { return null; } public String getTypeName() {
73     * return "Strings"; } public String getStringValue() { return ""; } public
74     * Object getObject() { return null; } }
75     */
76     public static void main(String[] args) {
77         new JabRef(args);
78     }
79
80     public JabRef(String[] args) {
81
82         ths = this;
83
84         System.setProperty("swing.aatext", "true");
85
86         // The following two lines signal that the system proxy settings should be used:
87         System.setProperty("java.net.useSystemProxies", "true");
88         System.getProperties().put( "proxySet", "true" );
89
90         JabRefPreferences prefs = JabRefPreferences.getInstance();
91         Globals.prefs = prefs;
92         Globals.setLanguage(prefs.get("language"), "");
93                 
94         Globals.importFormatReader.resetImportFormats();
95         BibtexEntryType.loadCustomEntryTypes(prefs);
96         // Build the list of available export formats:
97         ExportFormats.initAllExports();
98
99         // Read list(s) of journal names and abbreviations:
100         //Globals.turnOnFileLogging();
101
102         Globals.initializeJournalNames();
103
104         if (Globals.prefs.getBoolean("useRemoteServer")) {
105             remoteListener = RemoteListener.openRemoteListener(this);
106             if (remoteListener != null) {
107                 remoteListener.start();
108             }
109
110         // Unless we are alone, try to contact already running JabRef:
111             if (remoteListener == null) {
112                     if (RemoteListener.sendToActiveJabRefInstance(args)) {
113                 // We have successfully sent our command line options through the socket to
114                 // another JabRef instance. So we assume it's all taken care of, and quit.
115                 System.out.println(Globals.lang("Arguments passed on to running JabRef instance. Shutting down."));
116                 System.exit(0);
117             }
118         }
119         }
120
121       /**
122        * See if the user has a personal journal list set up. If so, add these
123        * journal names and abbreviations to the list:
124        */
125       String personalJournalList = prefs.get("personalJournalList");
126       if (personalJournalList != null) {
127           try {
128               Globals.journalAbbrev.readJournalList(new File(personalJournalList));
129           } catch (FileNotFoundException e) {
130               e.printStackTrace();
131           }
132       }
133
134         
135         //System.setProperty("sun.awt.noerasebackground", "true");
136         
137         //System.out.println(java.awt.Toolkit.getDefaultToolkit().getDesktopProperty("awt.dynamicLayoutSupported"));
138         // Make sure of a proper cleanup when quitting (e.g. deleting temporary
139         // files).
140         System.runFinalizersOnExit(true);
141
142         Vector loaded = processArguments(args, true);
143         openWindow(loaded);
144         //System.out.println("1");
145     }
146
147     private void setupOptions() {
148
149         importFile = new StringOption("");
150         exportFile = new StringOption("");
151         helpO = new BooleanOption();
152         disableGui = new BooleanOption();
153         disableSplash = new BooleanOption();
154         blank = new BooleanOption();
155         loadSess = new BooleanOption();
156         showVersion = new BooleanOption();
157         exportPrefs = new StringOption("jabref_prefs.xml");
158         importPrefs = new StringOption("jabref_prefs.xml");
159         auxImExport = new StringOption("");
160         importToOpenBase = new StringOption("");
161
162         options = new Options("JabRef "); // Create an options repository.
163         options.setVersion(GUIGlobals.version);
164
165         importFile.setDescription("imopoepuoeu"); //Globals.lang);
166         options.register("version", 'v',
167                 Globals.lang("Display version"), showVersion);
168         options.register("nogui", 'n',
169             Globals.lang("No GUI. Only process command line options."), disableGui);
170         options.register("nosplash", 's',
171                 Globals.lang("Do not show splash window at startup"), disableSplash);
172         options.register("import", 'i',
173             Globals.lang("Import file") + ": " + Globals.lang("filename")
174             + "[,import format]", importFile);
175         options.register("output", 'o',
176             Globals.lang("Output or export file") + ": " + Globals.lang("filename")
177             + "[,export format]", exportFile);
178         options.register("help", 'h',
179             Globals.lang("Display help on command line options"), helpO);
180         options.register("loads", 'l', Globals.lang("Load session"), loadSess);
181         options.register("prexp", 'x', Globals.lang("Export preferences to file"),
182             exportPrefs);
183         options.register("primp", 'p', Globals.lang("Import preferences from file"),
184             importPrefs);
185         options.register("aux", 'a',
186             Globals.lang("Subdatabase from aux") + ": " + Globals.lang("file")+"[.aux]" + ","+Globals.lang("new")+"[.bib]",
187             auxImExport);
188         options.register("blank", 'b', Globals.lang("Do not open any files at startup"), blank);
189
190         options.register("importToOpen", '\0', Globals.lang("Import to open tab"), importToOpenBase);
191
192         options.setUseMenu(false);
193     }
194
195     public Vector processArguments(String[] args, boolean initialStartup) {
196
197         setupOptions();
198         String[] leftOver = options.process(args);
199
200
201
202         //Util.pr(": Options processed");
203
204         if (initialStartup && showVersion.isInvoked()) {
205             options.displayVersion();
206             disableGui.setInvoked(true);
207         }
208
209         if (initialStartup && helpO.isInvoked()) {
210             System.out.println("jabref [options] [bibtex-file]\n");
211             System.out.println(options.getHelp());
212
213             String importFormats = Globals.importFormatReader.getImportFormatList();
214             System.out.println(Globals.lang("Available import formats") + ":\n"
215                 + importFormats);
216
217             String outFormats = ExportFormats.getConsoleExportList(70, 20, "\t");
218             System.out.println(Globals.lang("Available export formats") + ": " + outFormats
219                 + ".");
220             System.exit(0);
221         }
222
223         // First we quickly scan the command line parameters for any that signal
224         // that the GUI
225         // should not be opened. This is used to decide whether we should show the
226         // splash screen or not.
227         if (initialStartup && !disableGui.isInvoked() && !disableSplash.isInvoked()) {
228             try {
229
230                 splashScreen = SplashScreen.splash();
231
232             } catch (Throwable ex) {
233                 graphicFailure = true;
234                 System.err.println(Globals.lang("Unable to create graphical interface")
235                     + ".");
236             }
237         }
238
239         //Util.pr("JabRef "+GUIGlobals.version);
240         // Vector to put imported/loaded database(s) in.
241         Vector loaded = new Vector();
242         Vector toImport = new Vector();
243         if (!blank.isInvoked() && (leftOver.length > 0))  {
244             for (int i = 0; i < leftOver.length; i++) {
245                 // Leftover arguments that have a "bib" extension are interpreted as
246                 // bib files to open. Other files, and files that could not be opened
247                 // as bib, we try to import instead.
248                 boolean bibExtension = leftOver[i].toLowerCase().endsWith("bib");
249                 ParserResult pr = null;
250                 if (bibExtension)
251                     pr = openBibFile(leftOver[i]);
252
253                 if ((pr == null) || (pr == ParserResult.INVALID_FORMAT)) {
254                     // We will try to import this file. Normally we
255                     // will import it into a new tab, but if this import has
256                     // been initiated by another instance through the remote
257                     // listener, we will instead import it into the current database.
258                     // This will enable easy integration with web browers that can
259                     // open a reference file in JabRef.
260                     if (initialStartup) {
261                         toImport.add(leftOver[i]);
262                     } else {
263                         ParserResult res = importToOpenBase(leftOver[i]);
264                         if (res != null)
265                             loaded.add(res);
266                     }
267                 }
268                 else
269                     loaded.add(pr);
270
271             }
272         }
273
274         //Util.pr(": Checked blank");
275
276         if (!blank.isInvoked() && importFile.isInvoked()) {
277             toImport.add(importFile.getStringValue());
278         }
279
280         if (toImport.size() > 0) for (int i = 0; i < toImport.size(); i++) {
281             String[] data = ((String) toImport.elementAt(i)).split(",");
282
283             try {
284
285                 if ((data.length > 1) && !"*".equals(data[1])) {
286                     System.out.println(Globals.lang("Importing") + ": " + data[0]);
287                     List entries =
288                             Globals.importFormatReader.importFromFile(data[1],
289                                     data[0].replaceAll("~", System.getProperty("user.home")));
290                     BibtexDatabase base = ImportFormatReader.createDatabase(entries);
291                     ParserResult pr = new ParserResult(base, null, new HashMap());
292                     loaded.add(pr);
293
294                 } else {
295                     // * means "guess the format":
296                     System.out.println(Globals.lang("Importing in unknown format")
297                             + ": " + data[0]);
298
299                     Object[] o =
300                             Globals.importFormatReader.importUnknownFormat(data[0]
301                                     .replaceAll("~", System.getProperty("user.home")));
302                     String formatName = (String) o[0];
303
304                     if (formatName == null) {
305                         System.err.println(Globals.lang("Error opening file") + " '" + data[0] + "'");
306                     } else if (formatName.equals(ImportFormatReader.BIBTEX_FORMAT)) {
307                         ParserResult pr = (ParserResult) o[1];
308                         loaded.add(pr);
309
310                     } else {
311                         List entries = (java.util.List) o[1];
312                         if (entries != null)
313                             System.out.println(Globals.lang("Format used") + ": "
314                                     + formatName);
315                         else
316                             System.out.println(Globals.lang(
317                                     "Could not find a suitable import format."));
318
319                         if (entries != null) {
320                             BibtexDatabase base = ImportFormatReader.createDatabase(entries);
321                             ParserResult pr = new ParserResult(base, null, new HashMap());
322
323                             //pr.setFile(new File(data[0]));
324                             loaded.add(pr);
325                         }
326                     }
327                 }
328             } catch (IOException ex) {
329                 System.err.println(Globals.lang("Error opening file") + " '"
330                         + data[0] + "': " + ex.getMessage());
331             }
332
333
334         }
335
336
337         if (!blank.isInvoked() && importToOpenBase.isInvoked()) {
338             ParserResult res = importToOpenBase(importToOpenBase.getStringValue());
339             if (res != null)
340                 loaded.add(res);
341         }
342
343         if (exportFile.isInvoked()) {
344             if (loaded.size() > 0) {
345                 String[] data = exportFile.getStringValue().split(",");
346
347                 if (data.length == 1) {
348                     // This signals that the latest import should be stored in BibTeX
349                     // format to the given file.
350                     if (loaded.size() > 0) {
351                         ParserResult pr =
352                             (ParserResult) loaded.elementAt(loaded.size() - 1);
353
354                         try {
355                             System.out.println(Globals.lang("Saving") + ": " + data[0]);
356                             SaveSession session = FileActions.saveDatabase(pr.getDatabase(),
357                                 new MetaData(pr.getMetaData(),pr.getDatabase()), new File(data[0]), Globals.prefs,
358                                 false, false, Globals.prefs.get("defaultEncoding"));
359                             // Show just a warning message if encoding didn't work for all characters:
360                             if (!session.getWriter().couldEncodeAll())
361                                 System.err.println(Globals.lang("Warning")+": "+
362                                     Globals.lang("The chosen encoding '%0' could not encode the following characters: ",
363                                     session.getEncoding())+session.getWriter().getProblemCharacters());
364                             session.commit();
365                         } catch (SaveException ex) {
366                             System.err.println(Globals.lang("Could not save file") + " '"
367                                 + data[0] + "': " + ex.getMessage());
368                         }
369                     } else
370                         System.err.println(Globals.lang(
371                                 "The output option depends on a valid import option."));
372                 } else if (data.length == 2) {
373                     // This signals that the latest import should be stored in the given
374                     // format to the given file.
375                     ParserResult pr = (ParserResult) loaded.elementAt(loaded.size() - 1);
376
377                     // Set the global variable for this database's file directory before exporting,
378                     // so formatters can resolve linked files correctly.
379                     // (This is an ugly hack!)
380                     MetaData metaData = new MetaData(pr.getMetaData(), pr.getDatabase());
381                     metaData.setFile(pr.getFile());
382                     Globals.prefs.fileDirForDatabase = metaData.getFileDirectory(GUIGlobals.FILE_FIELD);
383                     System.out.println(Globals.lang("Exporting") + ": " + data[0]);
384                     ExportFormat format = ExportFormats.getExportFormat(data[1]);
385                     if (format != null) {
386                         // We have an ExportFormat instance:
387                         try {
388                             format.performExport(pr.getDatabase(), data[0], pr.getEncoding(), null);
389                         } catch (Exception ex) {
390                             System.err.println(Globals.lang("Could not export file")
391                                 + " '" + data[0] + "': " + ex.getMessage());
392                         }
393                     }
394                     else
395                         System.err.println(Globals.lang("Unknown export format")
396                                 + ": " + data[1]);
397
398                 }
399             } else
400                 System.err.println(Globals.lang(
401                         "The output option depends on a valid import option."));
402         }
403
404         //Util.pr(": Finished export");
405
406         if (exportPrefs.isInvoked()) {
407             try {
408                 Globals.prefs.exportPreferences(exportPrefs.getStringValue());
409             } catch (IOException ex) {
410                 Util.pr(ex.getMessage());
411             }
412         }
413
414
415         if (importPrefs.isInvoked()) {
416             try {
417                 Globals.prefs.importPreferences(importPrefs.getStringValue());
418                 BibtexEntryType.loadCustomEntryTypes(Globals.prefs);
419             }
420             catch (IOException ex) {
421                 Util.pr(ex.getMessage());
422             }
423         }
424
425         if (!blank.isInvoked() && auxImExport.isInvoked()) {
426             boolean usageMsg = false;
427
428             if (loaded.size() > 0) // bibtex file loaded
429              {
430                 String[] data = auxImExport.getStringValue().split(",");
431
432                 if (data.length == 2) {
433                     ParserResult pr = (ParserResult) loaded.firstElement();
434                     AuxCommandLine acl = new AuxCommandLine(data[0], pr.getDatabase());
435                     BibtexDatabase newBase = acl.perform();
436
437                     boolean notSavedMsg = false;
438
439                     // write an output, if something could be resolved
440                     if (newBase != null) {
441                         if (newBase.getEntryCount() > 0) {
442                             String subName = Util.getCorrectFileName(data[1], "bib");
443
444                             try {
445                                 System.out.println(Globals.lang("Saving") + ": "
446                                     + subName);
447                                 SaveSession session = FileActions.saveDatabase(newBase, new MetaData(), // no Metadata
448                                     new File(subName), Globals.prefs, false, false,
449                                     Globals.prefs.get("defaultEncoding"));
450                                 // Show just a warning message if encoding didn't work for all characters:
451                                 if (!session.getWriter().couldEncodeAll())
452                                     System.err.println(Globals.lang("Warning")+": "+
453                                         Globals.lang("The chosen encoding '%0' could not encode the following characters: ",
454                                         session.getEncoding())+session.getWriter().getProblemCharacters());
455                                 session.commit();
456                             } catch (SaveException ex) {
457                                 System.err.println(Globals.lang("Could not save file")
458                                     + " '" + subName + "': " + ex.getMessage());
459                             }
460
461                             notSavedMsg = true;
462                         }
463                     }
464
465                     if (!notSavedMsg)
466                         System.out.println(Globals.lang("no database generated"));
467                 } else
468                     usageMsg = true;
469             } else
470                 usageMsg = true;
471
472             if (usageMsg) {
473                 System.out.println(Globals.lang("no base-bibtex-file specified"));
474                 System.out.println(Globals.lang("usage") + " :");
475                 System.out.println(
476                     "jabref --aux infile[.aux],outfile[.bib] base-bibtex-file");
477             }
478         }
479
480         return loaded;
481     }
482
483     ParserResult importFiletypeUnknown(String fname) {
484         Object[] o =
485                 Globals.importFormatReader.importUnknownFormat(fname
486                         .replaceAll("~", System.getProperty("user.home")));
487         String formatName = (String) o[0];
488
489         if (formatName == null) {
490             System.err.println(Globals.lang("Error opening file") + " '" + fname + "'");
491         } else if (formatName.equals(ImportFormatReader.BIBTEX_FORMAT)) {
492             ParserResult pr = (ParserResult) o[1];
493             return pr;
494         } else {
495             List entries = (java.util.List) o[1];
496             if (entries != null)
497                 System.out.println(Globals.lang("Format used") + ": "
498                         + formatName);
499             else
500                 System.out.println(Globals.lang(
501                         "Could not find a suitable import format."));
502
503             if (entries != null) {
504                 BibtexDatabase base = ImportFormatReader.createDatabase(entries);
505                 ParserResult pr = new ParserResult(base, null, new HashMap());
506                 return pr;
507             }
508         }
509         
510         // not reached
511         return null;
512     }
513
514     public void openWindow(Vector loaded) {
515         if (!graphicFailure && !disableGui.isInvoked()) {
516             // Call the method performCompatibilityUpdate(), which does any
517             // necessary changes for users with a preference set from an older
518             // Jabref version.
519             Util.performCompatibilityUpdate();
520
521
522             // Set up custom or default icon theme:
523             GUIGlobals.setUpIconTheme();
524
525             // TODO: remove temporary registering of external file types?
526             Globals.prefs.updateExternalFileTypes();
527
528            // This property is set to make the Mac OSX Java VM move the menu bar to
529             // the top
530             // of the screen, where Mac users expect it to be.
531             System.setProperty("apple.laf.useScreenMenuBar", "true");
532
533             // Set antialiasing on everywhere. This only works in JRE >= 1.5.
534             // Or... it doesn't work, period.
535             //System.setProperty("swing.aatext", "true");
536             // If we are not on Mac, deal with font sizes and LookAndFeels:
537             if (!Globals.ON_MAC) {
538                 int fontSizes = Globals.prefs.getInt("menuFontSize");
539                 boolean overrideDefaultFonts = Globals.prefs.getBoolean("overrideDefaultFonts");
540                 String defaultLookAndFeel;
541
542                 if (Globals.ON_WIN)
543                     defaultLookAndFeel = GUIGlobals.windowsDefaultLookAndFeel;
544                 else
545                     defaultLookAndFeel = GUIGlobals.linuxDefaultLookAndFeel;
546
547                 String lookAndFeel = null;
548
549                 if (!Globals.prefs.getBoolean("useDefaultLookAndFeel"))
550                     lookAndFeel = Globals.prefs.get("lookAndFeel");
551                 else
552                     lookAndFeel = defaultLookAndFeel;
553
554                 LookAndFeel lnf = null;
555                 Object objLnf = null;
556
557
558                 try {
559                     if (lookAndFeel != null)
560                         objLnf = Class.forName(lookAndFeel).newInstance();
561                     else
562                         objLnf = Class.forName(defaultLookAndFeel).newInstance();
563                 } catch (Exception ex) {
564                     ex.printStackTrace();
565
566                     try {
567                         objLnf = Class.forName(defaultLookAndFeel).newInstance();
568                     } catch (Exception ex2) {
569                     }
570                 }
571
572                 if (objLnf != null)
573                     lnf = (LookAndFeel) objLnf;
574
575                 // Set font sizes if we are using a JGoodies look and feel.
576                 if ((lnf != null) && (lnf instanceof Plastic3DLookAndFeel)) {
577
578                     //UIManager.put("jgoodies.popupDropShadowEnabled", Boolean.TRUE);
579                     MetalLookAndFeel.setCurrentTheme(new
580                      com.jgoodies.looks.plastic.theme.SkyBluer());
581
582                     // Set a "model" icon size, so menu items are evenly spaced even though
583                     // only some items have icons. We load an arbitrary icon and look at
584                     // its size to determine what size to use:
585                     int defaultIconSize = GUIGlobals.getImage("open").getIconWidth();
586                     com.jgoodies.looks.Options.setDefaultIconSize
587                             (new Dimension(defaultIconSize, defaultIconSize));
588
589
590                     if (overrideDefaultFonts) {
591                         FontSet fontSet = FontSets.createDefaultFontSet(
592                             new Font("Tahoma", Font.PLAIN, fontSizes),    // control font
593                             new Font("Tahoma", Font.PLAIN, fontSizes),    // menu font
594                             new Font("Tahoma", Font.BOLD, fontSizes)     // title font
595                             );
596                         FontPolicy fixedPolicy = FontPolicies.createFixedPolicy(fontSet);
597                         Plastic3DLookAndFeel.setFontPolicy(fixedPolicy);
598                     }
599
600                     //Plastic3DLookAndFeel plLnf = (Plastic3DLookAndFeel) lnf;
601                 }
602                 else if ((lnf != null) && (lnf instanceof WindowsLookAndFeel)) {
603
604                     // Set a "model" icon size, so menu items are evenly spaced even though
605                     // only some items have icons. We load an arbitrary icon and look at
606                     // its size to determine what size to use:
607                     int defaultIconSize = GUIGlobals.getImage("open").getIconWidth();
608                     com.jgoodies.looks.Options.setDefaultIconSize
609                         (new Dimension(defaultIconSize, defaultIconSize));
610
611                     if (overrideDefaultFonts) {
612                         FontSet fontSet = FontSets.createDefaultFontSet(
613                             new Font("Tahoma", Font.PLAIN, fontSizes),    // control font
614                             new Font("Tahoma", Font.PLAIN, fontSizes),    // menu font
615                             new Font("Tahoma", Font.BOLD, fontSizes)     // title font
616                             );
617                         FontPolicy fixedPolicy = FontPolicies.createFixedPolicy(fontSet);
618                         WindowsLookAndFeel.setFontPolicy(fixedPolicy);
619                     }
620
621                     //WindowsLookAndFeel plLnf = (WindowsLookAndFeel) lnf;
622                 }
623
624                 if (lnf != null) {
625                     try {
626
627                         UIManager.setLookAndFeel(lnf);
628
629                         if (!Globals.ON_WIN) {
630                             UIManager.put("SimpleInternalFrame.activeTitleBackground", GUIGlobals.gradientBlue);
631                         }
632
633                         if (!Globals.ON_WIN && !Globals.ON_MAC) {
634                             // For Linux, add Enter as button click key:
635                             UIDefaults def = UIManager.getDefaults();
636                             InputMap im = (InputMap)def.get("Button.focusInputMap");
637                             im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false), "pressed");
638                             im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true), "released");
639                         }
640                     } catch (Throwable ex) {
641                         ex.printStackTrace();
642                         System.err.println("Trying to set system default Look&Feel...");
643
644                         // if desired lnf could not be set, try system default
645                         try {
646                             UIManager.setLookAndFeel(UIManager
647                                 .getSystemLookAndFeelClassName());
648                         } catch (Throwable e) {
649                             e.printStackTrace();
650                         }
651                     }
652
653                     //LookAndFeel lnf = new com.sun.java.swing.plaf.gtk.GTKLookAndFeel();
654                     //Look1AndFeel lnf = new
655                     // com.incors.plaf.kunststoff.KunststoffLookAndFeel();
656                     //com.incors.plaf.kunststoff.KunststoffLookAndFeel.setCurrentTheme(new
657                     // com.incors.plaf.kunststoff.themes.KunststoffDesktopTheme());
658                 }
659
660             }
661
662
663             // If the option is enabled, open the last edited databases, if any.
664             if (!blank.isInvoked() && Globals.prefs.getBoolean("openLastEdited") && (Globals.prefs.get("lastEdited") != null)) {
665                 // How to handle errors in the databases to open?
666                 String[] names = Globals.prefs.getStringArray("lastEdited");
667 lastEdLoop: 
668                 for (int i = 0; i < names.length; i++) {
669                     File fileToOpen = new File(names[i]);
670
671                     for (int j = 0; j < loaded.size(); j++) {
672                         ParserResult pr = (ParserResult) loaded.elementAt(j);
673
674                         if ((pr.getFile() != null) &&pr.getFile().equals(fileToOpen))
675                             continue lastEdLoop;
676                     }
677
678                     if (fileToOpen.exists()) {
679                         ParserResult pr = openBibFile(names[i]);
680
681                         if (pr != null) {
682
683                             if (pr == ParserResult.INVALID_FORMAT) {
684                                 System.out.println(Globals.lang("Error opening file")+" '"+fileToOpen.getPath()+"'");
685                             }
686                             else
687                                 loaded.add(pr);
688
689                         }
690                     }
691                 }
692             }
693
694             GUIGlobals.init();
695             GUIGlobals.CURRENTFONT =
696                 new Font(Globals.prefs.get("fontFamily"), Globals.prefs.getInt("fontStyle"),
697                     Globals.prefs.getInt("fontSize"));
698
699             //Util.pr(": Initializing frame");
700             jrf = new JabRefFrame();
701
702             // Add all loaded databases to the frame:
703             boolean first = true;
704             if (loaded.size() > 0) {
705                 for (Iterator i=loaded.iterator(); i.hasNext();) {
706                     ParserResult pr = (ParserResult)i.next();
707                             BasePanel panel = jrf.addTab(pr.getDatabase(), pr.getFile(),
708                             pr.getMetaData(), pr.getEncoding(), first);
709                     first = false;
710                 }
711             }
712
713             if (loadSess.isInvoked())
714                 jrf.loadSessionAction.actionPerformed(new java.awt.event.ActionEvent(
715                         jrf, 0, ""));
716
717             if (splashScreen != null) {// do this only if splashscreen was actually created
718                 splashScreen.dispose();
719                 splashScreen = null;
720             }
721
722             /*JOptionPane.showMessageDialog(null, Globals.lang("Please note that this "
723                 +"is an early beta version. Do not use it without backing up your files!"),
724                     Globals.lang("Beta version"), JOptionPane.WARNING_MESSAGE);*/
725
726             //Util.pr(": Showing frame");
727             jrf.setVisible(true);
728
729             // TEST TEST TEST TEST TEST TEST
730             startOOPlugin(jrf);
731
732             for (int i = 0; i < loaded.size(); i++) {
733                 ParserResult pr = (ParserResult) loaded.elementAt(i);
734                 if (Globals.prefs.getBoolean("displayKeyWarningDialogAtStartup") && pr.hasWarnings()) {
735                     String[] wrns = pr.warnings();
736                     StringBuffer wrn = new StringBuffer();
737                     for (int j = 0; j<wrns.length; j++)
738                         wrn.append(j + 1).append(". ").append(wrns[j]).append("\n");
739                     if (wrn.length() > 0)
740                         wrn.deleteCharAt(wrn.length() - 1);
741                     jrf.showBaseAt(i);
742                     JOptionPane.showMessageDialog(jrf, wrn.toString(),
743                         Globals.lang("Warnings"),
744                         JOptionPane.WARNING_MESSAGE);
745                 }
746             }
747
748             // After adding the databases, go through each and see if
749             // any post open actions need to be done. For instance, checking
750             // if we found new entry types that can be imported, or checking
751             // if the database contents should be modified due to new features
752             // in this version of JabRef:
753             for (int i = 0; i < loaded.size(); i++) {
754                 ParserResult pr = (ParserResult) loaded.elementAt(i);
755                 BasePanel panel = jrf.baseAt(i);
756                 OpenDatabaseAction.performPostOpenActions(panel, pr, true);
757             }
758
759             //Util.pr(": Finished adding panels");
760
761             if (loaded.size() > 0) {
762                 jrf.tabbedPane.setSelectedIndex(0);
763                 new FocusRequester(((BasePanel) jrf.tabbedPane.getComponentAt(0)).mainTable);
764             }
765         } else
766             System.exit(0);
767     }
768
769     /**
770      * Morten Alver (sept. 06): I'm adding this to run the functionality for
771      * OpenOffice integration. I'm not sure yet how to handle deployment issues,
772      * because the OO stuff requires several OO jars on the classpath, which we
773      * shouldn't distribute because OO installations already have them.
774      *
775      * To avoid introducing dependencies on these jars for the time being,
776      * I'm keeping OO "plugin" files separate, only invoking them through reflection.
777      *
778      * @param jrf The JabRefFrame.
779      */
780     private void startOOPlugin(JabRefFrame jrf) {
781
782
783         try {
784             Class c = Class.forName("net.sf.jabref.oo.OOTestPanel");
785             Method m = c.getDeclaredMethod("open",
786                     new Class[] {JabRefFrame.class});
787             Object i = c.newInstance();
788             Object r = m.invoke(i, new Object[] {jrf});
789         } catch (Exception e) {
790             // Do nothing.
791             //System.out.println("OO plugin not found.");
792             //e.printStackTrace();
793         }
794         
795     }
796
797     public static ParserResult openBibFile(String name) {
798         System.out.println(Globals.lang("Opening") + ": " + name);
799
800         try {
801             File file = new File(name);
802             String encoding = Globals.prefs.get("defaultEncoding");
803             ParserResult pr = OpenDatabaseAction.loadDatabase(file, encoding);
804             if (pr == null)
805                 return ParserResult.INVALID_FORMAT;
806             pr.setFile(file);
807             if (pr.hasWarnings()) {
808                 String[] warn = pr.warnings();
809                 for (int i=0; i<warn.length; i++)
810                     System.out.println(Globals.lang("Warning")+": "+warn[i]);
811
812             }
813             return pr;
814         } catch (Throwable ex) {
815             //System.err.println(Globals.lang("Error opening file")+" '"+ name+"':
816             // "+ex.getMessage());
817             System.err.println(Globals.lang("Error opening file") + ": "
818                 + ex.getMessage());
819         }
820
821         return null;
822     }
823
824     public static ParserResult importToOpenBase(String argument) {
825         String[] data = argument.split(",");
826         try {
827             if ((data.length > 1) && !"*".equals(data[1])) {
828                 System.out.println(Globals.lang("Importing") + ": " + data[0]);
829                 List entries =
830                     Globals.importFormatReader.importFromFile(data[1],
831                         data[0].replaceAll("~", System.getProperty("user.home")));
832                 BibtexDatabase base = ImportFormatReader.createDatabase(entries);
833                 ParserResult pr = new ParserResult(base, null, new HashMap());
834                 pr.setToOpenTab(true);
835                 //loaded.add(pr);
836                 return pr;
837             } else {
838                 // * means "guess the format":
839                 System.out.println(Globals.lang("Importing in unknown format")
840                     + ": " + data[0]);
841
842                 Object[] o =
843                     Globals.importFormatReader.importUnknownFormat(data[0]
844                         .replaceAll("~", System.getProperty("user.home")));
845                 String formatName = (String) o[0];
846
847                 if (formatName.equals(ImportFormatReader.BIBTEX_FORMAT)) {
848                     ParserResult pr = (ParserResult)o[1];
849                     pr.setToOpenTab(true);
850                     //loaded.add(pr);
851                     return pr;
852                 }
853                 else {
854                     List entries = (java.util.List) o[1];
855                     if (entries != null)
856                         System.out.println(Globals.lang("Format used") + ": "
857                             + formatName);
858                     else
859                         System.out.println(Globals.lang(
860                                 "Could not find a suitable import format."));
861
862                     if (entries != null) {
863                         BibtexDatabase base = ImportFormatReader.createDatabase(entries);
864                         ParserResult pr = new ParserResult(base, null, new HashMap());
865
866                         //pr.setFile(new File(data[0]));
867                         pr.setToOpenTab(true);
868                         //loaded.add(pr);
869                         return pr;
870                     }
871                 }
872
873             }
874         } catch (IOException ex) {
875             System.err.println(Globals.lang("Error opening file") + " '"
876                 + data[0] + "': " + ex.getMessage());
877         }
878
879         return null;
880     }
881 }