76aca033ee0836ff89276b8eb87c6e246bebee05
[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.Font;
34 import java.awt.Frame;
35
36 import java.io.*;
37 import java.io.File;
38
39 import java.util.*;
40
41 import javax.swing.*;
42
43 import com.jgoodies.looks.plastic.Plastic3DLookAndFeel;
44 import com.jgoodies.looks.windows.WindowsLookAndFeel;
45
46
47 //import javax.swing.UIManager;
48 //import javax.swing.UIDefaults;
49 //import javax.swing.UnsupportedLookAndFeelException;
50 public class JabRef {
51     public static JabRef ths;
52     public static RemoteListener remoteListener = null;
53     public JabRefFrame jrf;
54     public Options options;
55     public Frame splashScreen = null;
56
57     boolean graphicFailure = false;
58
59     StringOption importFile, exportFile, exportPrefs, importPrefs, auxImExport, importToOpenBase;
60     BooleanOption helpO, disableGui, blank, loadSess;
61     /*
62     * class StringArrayOption extends ArrayOption { public public void
63     * modify(String value) { } public void modify(String[] value) { } public
64     * Object[] getObjectArray() { return null; } public String getTypeName() {
65     * return "Strings"; } public String getStringValue() { return ""; } public
66     * Object getObject() { return null; } }
67     */
68     public static void main(String[] args) {
69         new JabRef(args);
70     }
71
72     public JabRef(String[] args) {
73
74
75         ths = this;
76         JabRefPreferences prefs = JabRefPreferences.getInstance();
77         Globals.prefs = prefs;
78         Globals.setLanguage(prefs.get("language"), "");
79                 
80         Globals.importFormatReader.resetImportFormats();
81         BibtexEntryType.loadCustomEntryTypes(prefs);
82         // Read list(s) of journal names and abbreviations:
83         //Globals.turnOnFileLogging();
84
85         Globals.initializeJournalNames();
86
87         if (Globals.prefs.getBoolean("useRemoteServer")) {
88             remoteListener = RemoteListener.openRemoteListener(this);
89             if (remoteListener != null) {
90                 remoteListener.start();
91             }
92
93         // Unless we are alone, try to contact already running JabRef:
94             if (remoteListener == null) {
95                     if (RemoteListener.sendToActiveJabRefInstance(args)) {
96                 // We have successfully sent our command line options through the socket to
97                 // another JabRef instance. So we assume it's all taken care of, and quit.
98                 System.out.println(Globals.lang("Arguments passed on to running JabRef instance. Shutting down."));
99                 System.exit(0);
100             }
101         }
102         }
103
104       /**
105        * See if the user has a personal journal list set up. If so, add these
106        * journal names and abbreviations to the list:
107        */
108       String personalJournalList = prefs.get("personalJournalList");
109       if (personalJournalList != null) {
110           try {
111               Globals.journalAbbrev.readJournalList(new File(personalJournalList));
112           } catch (FileNotFoundException e) {
113               e.printStackTrace();
114           }
115       }
116
117         
118         //System.setProperty("sun.awt.noerasebackground", "true");
119         
120         //System.out.println(java.awt.Toolkit.getDefaultToolkit().getDesktopProperty("awt.dynamicLayoutSupported"));
121         // Make sure of a proper cleanup when quitting (e.g. deleting temporary
122         // files).
123         System.runFinalizersOnExit(true);
124
125         Vector loaded = processArguments(args, true);
126         openWindow(loaded);
127         //System.out.println("1");
128     }
129
130     private void setupOptions() {
131
132         importFile = new StringOption("");
133         exportFile = new StringOption("");
134         helpO = new BooleanOption();
135         disableGui = new BooleanOption();
136         blank = new BooleanOption();
137         loadSess = new BooleanOption();
138         exportPrefs = new StringOption("jabref_prefs.xml");
139         importPrefs = new StringOption("jabref_prefs.xml");
140         auxImExport = new StringOption("");
141         importToOpenBase = new StringOption("");
142
143         options = new Options("JabRef "); // Create an options repository.
144         options.setVersion(GUIGlobals.version);
145
146         importFile.setDescription("imopoepuoeu"); //Globals.lang);
147         options.register("nogui", 'n',
148             Globals.lang("No GUI. Only process command line options."), disableGui);
149         options.register("import", 'i',
150             Globals.lang("Import file") + ": " + Globals.lang("filename")
151             + "[,import format]", importFile);
152         options.register("output", 'o',
153             Globals.lang("Output or export file") + ": " + Globals.lang("filename")
154             + "[,export format]", exportFile);
155         options.register("help", 'h',
156             Globals.lang("Display help on command line options"), helpO);
157         options.register("loads", 'l', Globals.lang("Load session"), loadSess);
158         options.register("prexp", 'x', Globals.lang("Export preferences to file"),
159             exportPrefs);
160         options.register("primp", 'p', Globals.lang("Import preferences from file"),
161             importPrefs);
162         options.register("aux", 'a',
163             Globals.lang("Subdatabase from aux") + ": " + Globals.lang("file")+"[.aux]" + ","+Globals.lang("new")+"[.bib]",
164             auxImExport);
165         options.register("blank", 'b', Globals.lang("Do not open any files at startup"), blank);
166
167         options.register("importToOpen", '\0', Globals.lang("Import to open tab"), importToOpenBase);
168
169         options.setUseMenu(false);
170     }
171
172     public Vector processArguments(String[] args, boolean initialStartup) {
173
174         setupOptions();
175         String[] leftOver = options.process(args);
176
177         //Util.pr(": Options processed");
178
179         if (initialStartup && helpO.isInvoked()) {
180             System.out.println("jabref [options] [bibtex-file]\n");
181             System.out.println(options.getHelp());
182
183             String importFormats = Globals.importFormatReader.getImportFormatList();
184             System.out.println(Globals.lang("Available import formats") + ":\n"
185                 + importFormats);
186
187             // + ": biblioscape, bibtexml, endnote, inspec,\n\tisi, medline, ovid,
188             // ris, scifinder, sixpack, jstor, silverplatter.");
189             // To specify export formats, we need to take the custom export formats
190             // into account.
191             // So we iterate through the custom formats and add them.
192             String outFormats = ": bibtexml, docbook, endnote, harvard, html, mods, ods, oocalc, simplehtml";
193             int length = outFormats.length();
194
195             for (int i = 0; i < Globals.prefs.customExports.size(); i++) {
196                 String[] format = Globals.prefs.customExports.getElementAt(i);
197
198                 if ((length + format[0].length()) > 50) {
199                     outFormats = outFormats + ",\n\t" + format[0];
200                     length = format[0].length();
201                 } else {
202                     outFormats = outFormats + ", " + format[0];
203                     length += (1 + format[0].length());
204                 }
205             }
206
207             System.out.println(Globals.lang("Available export formats") + outFormats
208                 + ".");
209             System.exit(0);
210         }
211
212         // First we quickly scan the command line parameters for any that signal
213         // that the GUI
214         // should not be opened. This is used to decide whether we should show the
215         // splash screen or not.
216         if (initialStartup && !disableGui.isInvoked()) {
217             try {
218
219                 splashScreen = SplashScreen.splash();
220
221             } catch (Throwable ex) {
222                 graphicFailure = true;
223                 System.err.println(Globals.lang("Unable to create graphical interface")
224                     + ".");
225             }
226         }
227
228         //Util.pr("JabRef "+GUIGlobals.version);
229         // Vector to put imported/loaded database(s) in.
230         Vector loaded = new Vector();
231         Vector toImport = new Vector();
232         if (!blank.isInvoked() && (leftOver.length > 0))  {
233             for (int i = 0; i < leftOver.length; i++) {
234                 // Leftover arguments that have a "bib" extension are interpreted as
235                 // bib files to open. Other files, and files that could not be opened
236                 // as bib, we try to import instead.
237                 boolean bibExtension = leftOver[i].toLowerCase().endsWith("bib");
238                 ParserResult pr = null;
239                 if (bibExtension)
240                     pr = openBibFile(leftOver[i]);
241
242                 if ((pr == null) || (pr == ParserResult.INVALID_FORMAT)) {
243                     // We will try to import this file. Normally we
244                     // will import it into a new tab, but if this import has
245                     // been initiated by another instance through the remote
246                     // listener, we will instead import it into the current database.
247                     // This will enable easy integration with web browers that can
248                     // open a reference file in JabRef.
249                     if (initialStartup) {
250                         toImport.add(leftOver[i]);
251                     } else {
252                         ParserResult res = importToOpenBase(leftOver[i]);
253                         if (res != null)
254                             loaded.add(res);
255                     }
256                 }
257                 else
258                     loaded.add(pr);
259
260             }
261         }
262
263         //Util.pr(": Checked blank");
264
265         if (!blank.isInvoked() && importFile.isInvoked()) {
266             toImport.add(importFile.getStringValue());
267         }
268
269         if (toImport.size() > 0) for (int i = 0; i < toImport.size(); i++) {
270             String[] data = ((String) toImport.elementAt(i)).split(",");
271
272             try {
273
274                 if ((data.length > 1) && !"*".equals(data[1])) {
275                     System.out.println(Globals.lang("Importing") + ": " + data[0]);
276                     List entries =
277                             Globals.importFormatReader.importFromFile(data[1],
278                                     data[0].replaceAll("~", System.getProperty("user.home")));
279                     BibtexDatabase base = ImportFormatReader.createDatabase(entries);
280                     ParserResult pr = new ParserResult(base, null, new HashMap());
281                     loaded.add(pr);
282
283                 } else {
284                     // * means "guess the format":
285                     System.out.println(Globals.lang("Importing in unknown format")
286                             + ": " + data[0]);
287
288                     Object[] o =
289                             Globals.importFormatReader.importUnknownFormat(data[0]
290                                     .replaceAll("~", System.getProperty("user.home")));
291                     String formatName = (String) o[0];
292
293                     if (formatName == null) {
294                         System.err.println(Globals.lang("Error opening file") + " '" + data[0] + "'");
295                     } else if (formatName.equals(ImportFormatReader.BIBTEX_FORMAT)) {
296                         ParserResult pr = (ParserResult) o[1];
297                         loaded.add(pr);
298
299                     } else {
300                         List entries = (java.util.List) o[1];
301                         if (entries != null)
302                             System.out.println(Globals.lang("Format used") + ": "
303                                     + formatName);
304                         else
305                             System.out.println(Globals.lang(
306                                     "Could not find a suitable import format."));
307
308                         if (entries != null) {
309                             BibtexDatabase base = ImportFormatReader.createDatabase(entries);
310                             ParserResult pr = new ParserResult(base, null, new HashMap());
311
312                             //pr.setFile(new File(data[0]));
313                             loaded.add(pr);
314                         }
315                     }
316                 }
317             } catch (IOException ex) {
318                 System.err.println(Globals.lang("Error opening file") + " '"
319                         + data[0] + "': " + ex.getMessage());
320             }
321
322
323         }
324
325
326         if (!blank.isInvoked() && importToOpenBase.isInvoked()) {
327             ParserResult res = importToOpenBase(importToOpenBase.getStringValue());
328             if (res != null)
329                 loaded.add(res);
330         }
331
332         if (exportFile.isInvoked()) {
333             if (loaded.size() > 0) {
334                 String[] data = exportFile.getStringValue().split(",");
335
336                 if (data.length == 1) {
337                     // This signals that the latest import should be stored in BibTeX
338                     // format to the given file.
339                     if (loaded.size() > 0) {
340                         ParserResult pr =
341                             (ParserResult) loaded.elementAt(loaded.size() - 1);
342
343                         try {
344                             System.out.println(Globals.lang("Saving") + ": " + data[0]);
345                             SaveSession session = FileActions.saveDatabase(pr.getDatabase(),
346                                 new MetaData(pr.getMetaData(),pr.getDatabase()), new File(data[0]), Globals.prefs,
347                                 false, false, Globals.prefs.get("defaultEncoding"));
348                             // Show just a warning message if encoding didn't work for all characters:
349                             if (!session.getWriter().couldEncodeAll())
350                                 System.err.println(Globals.lang("Warning")+": "+
351                                     Globals.lang("The chosen encoding '%0' could not encode the following characters: ",
352                                     session.getEncoding())+session.getWriter().getProblemCharacters());
353                             session.commit();
354                         } catch (SaveException ex) {
355                             System.err.println(Globals.lang("Could not save file") + " '"
356                                 + data[0] + "': " + ex.getMessage());
357                         }
358                     } else
359                         System.err.println(Globals.lang(
360                                 "The output option depends on a valid import option."));
361                 } else if (data.length == 2) {
362                     // This signals that the latest import should be stored in the given
363                     // format to the given file.
364                     ParserResult pr = (ParserResult) loaded.elementAt(loaded.size() - 1);
365
366                     // We first try to find a matching custom export format.
367                     boolean foundCustom = false;
368
369                     for (int i = 0; i < Globals.prefs.customExports.size(); i++) {
370                         String[] format = Globals.prefs.customExports.getElementAt(i);
371
372                         if (format[0].equals(data[1])) {
373                             // Found the correct export format here.
374                             
375                             try {
376                                 File lfFile = new File(format[1]);
377
378                                 //System.out.println(lfFile.getName());
379                                 String fname = (lfFile.getName().split("\\."))[0];
380                                 FileActions.exportDatabase(pr.getDatabase(),
381                                     lfFile.getParent() + File.separator, fname,
382                                     new File(data[0]), pr.getEncoding());
383                                 System.out.println(Globals.lang("Exporting") + ": "
384                                     + data[0]);
385                             } catch (Exception ex) {
386                                 //ex.printStackTrace();
387                                 System.err.println(Globals.lang("Could not export file")
388                                     + " '" + data[0] + "': " + ex.getMessage());
389                             }
390
391                             foundCustom = true;
392
393                             break;
394                         }
395                     }
396
397                     if (!foundCustom) {
398                         try {
399                             System.out.println(Globals.lang("Exporting") + ": " + data[0]);
400                             FileActions.performExport(pr.getDatabase(), data[1], data[0],
401                                     pr.getEncoding());
402                             //FileActions.exportDatabase(pr.getDatabase(), data[1],
403                             //    new File(data[0]), pr.getEncoding());
404                         } catch (NullPointerException ex2) {
405                             System.err.println(Globals.lang("Unknown export format")
406                                 + ": " + data[1]);
407                         } catch (Exception ex) {
408                             System.err.println(Globals.lang("Could not export file")
409                                 + " '" + data[0] + "': " + ex.getMessage());
410                         }
411                     }
412                 }
413             } else
414                 System.err.println(Globals.lang(
415                         "The output option depends on a valid import option."));
416         }
417
418         //Util.pr(": Finished export");
419
420         if (exportPrefs.isInvoked()) {
421             try {
422                 Globals.prefs.exportPreferences(exportPrefs.getStringValue());
423             } catch (IOException ex) {
424                 Util.pr(ex.getMessage());
425             }
426         }
427
428
429         if (importPrefs.isInvoked()) {
430             try {
431                 Globals.prefs.importPreferences(importPrefs.getStringValue());
432                 BibtexEntryType.loadCustomEntryTypes(Globals.prefs);
433             }
434             catch (IOException ex) {
435                 Util.pr(ex.getMessage());
436             }
437         }
438
439         if (!blank.isInvoked() && auxImExport.isInvoked()) {
440             boolean usageMsg = false;
441
442             if (loaded.size() > 0) // bibtex file loaded
443              {
444                 String[] data = auxImExport.getStringValue().split(",");
445
446                 if (data.length == 2) {
447                     ParserResult pr = (ParserResult) loaded.firstElement();
448                     AuxCommandLine acl = new AuxCommandLine(data[0], pr.getDatabase());
449                     BibtexDatabase newBase = acl.perform();
450
451                     boolean notSavedMsg = false;
452
453                     // write an output, if something could be resolved
454                     if (newBase != null) {
455                         if (newBase.getEntryCount() > 0) {
456                             String subName = Util.getCorrectFileName(data[1], "bib");
457
458                             try {
459                                 System.out.println(Globals.lang("Saving") + ": "
460                                     + subName);
461                                 SaveSession session = FileActions.saveDatabase(newBase, new MetaData(), // no Metadata
462                                     new File(subName), Globals.prefs, false, false,
463                                     Globals.prefs.get("defaultEncoding"));
464                                 // Show just a warning message if encoding didn't work for all characters:
465                                 if (!session.getWriter().couldEncodeAll())
466                                     System.err.println(Globals.lang("Warning")+": "+
467                                         Globals.lang("The chosen encoding '%0' could not encode the following characters: ",
468                                         session.getEncoding())+session.getWriter().getProblemCharacters());
469                                 session.commit();
470                             } catch (SaveException ex) {
471                                 System.err.println(Globals.lang("Could not save file")
472                                     + " '" + subName + "': " + ex.getMessage());
473                             }
474
475                             notSavedMsg = true;
476                         }
477                     }
478
479                     if (!notSavedMsg)
480                         System.out.println(Globals.lang("no database generated"));
481                 } else
482                     usageMsg = true;
483             } else
484                 usageMsg = true;
485
486             if (usageMsg) {
487                 System.out.println(Globals.lang("no base-bibtex-file specified"));
488                 System.out.println(Globals.lang("usage") + " :");
489                 System.out.println(
490                     "jabref --aux infile[.aux],outfile[.bib] base-bibtex-file");
491             }
492         }
493
494         return loaded;
495     }
496
497     public void openWindow(Vector loaded) {
498         if (!graphicFailure && !disableGui.isInvoked()) {
499             // Call the method performCompatibilityUpdate(), which does any
500             // necessary changes for users with a preference set from an older
501             // Jabref version.
502             Util.performCompatibilityUpdate();
503
504            // This property is set to make the Mac OSX Java VM move the menu bar to
505             // the top
506             // of the screen, where Mac users expect it to be.
507             System.setProperty("apple.laf.useScreenMenuBar", "true");
508
509             // Set antialiasing on everywhere. This only works in JRE >= 1.5.
510             // Or... it doesn't work, period.
511             //System.setProperty("swing.aatext", "true");
512             // If we are not on Mac, deal with font sizes and LookAndFeels:
513             if (!Globals.ON_MAC) {
514                 int fontSizes = Globals.prefs.getInt("menuFontSize");
515
516                 String defaultLookAndFeel;
517
518                 if (Globals.ON_WIN)
519                     defaultLookAndFeel = GUIGlobals.windowsDefaultLookAndFeel;
520                 else
521                     defaultLookAndFeel = GUIGlobals.linuxDefaultLookAndFeel;
522
523                 String lookAndFeel = null;
524
525                 if (!Globals.prefs.getBoolean("useDefaultLookAndFeel"))
526                     lookAndFeel = Globals.prefs.get("lookAndFeel");
527                 else
528                     lookAndFeel = defaultLookAndFeel;
529
530                 LookAndFeel lnf = null;
531                 Object objLnf = null;
532
533
534                 try {
535                     if (lookAndFeel != null)
536                         objLnf = Class.forName(lookAndFeel).newInstance();
537                     else
538                         objLnf = Class.forName(defaultLookAndFeel).newInstance();
539                 } catch (Exception ex) {
540                     ex.printStackTrace();
541
542                     try {
543                         objLnf = Class.forName(defaultLookAndFeel).newInstance();
544                     } catch (Exception ex2) {
545                     }
546                 }
547
548                 if (objLnf != null)
549                     lnf = (LookAndFeel) objLnf;
550
551                 // Set font sizes if we are using a JGoodies look and feel.
552                 /*if ((lnf != null) && (lnf instanceof Plastic3DLookAndFeel)) {
553                     //MetalLookAndFeel.setCurrentTheme(new
554                     // com.jgoodies.plaf.plastic.theme.SkyBluer());
555                     Plastic3DLookAndFeel plLnf = (Plastic3DLookAndFeel) lnf;
556                     //Plastic3DLookAndFeel.setFontPolicy();
557                     //Plastic3DLookAndFeel.setFontPolicy(FontPolicy.);
558                     //plLnf.setFontSizeHints(new FontSizeHints(fontSizes, fontSizes,
559                     //        fontSizes, fontSizes));
560                 } else if ((lnf != null) && (lnf instanceof WindowsLookAndFeel)) {
561                     //System.out.println("ttt");
562                     //ExtWindowsLookAndFeel plLnf = (ExtWindowsLookAndFeel) lnf;
563                     //plLnf.setFontSizeHints(new FontSizeHints(fontSizes, fontSizes,
564                     //        fontSizes, fontSizes));
565                 } */
566
567                 if (lnf != null) {
568                     try {
569                         UIManager.setLookAndFeel(lnf);
570                         
571                         if (!Globals.ON_WIN) {
572                             UIManager.put("SimpleInternalFrame.activeTitleBackground", GUIGlobals.gradientBlue);
573                             //UIManager.put("TabbedPane.selected", Color.red);
574                         }
575                     } catch (Throwable ex) {
576                         ex.printStackTrace();
577                         System.err.println("Trying to set system default Look&Feel...");
578
579                         // if desired lnf could not be set, try system default
580                         try {
581                             UIManager.setLookAndFeel(UIManager
582                                 .getSystemLookAndFeelClassName());
583                         } catch (Throwable e) {
584                             e.printStackTrace();
585                         }
586                     }
587
588                     //LookAndFeel lnf = new com.sun.java.swing.plaf.gtk.GTKLookAndFeel();
589                     //Look1AndFeel lnf = new
590                     // com.incors.plaf.kunststoff.KunststoffLookAndFeel();
591                     //com.incors.plaf.kunststoff.KunststoffLookAndFeel.setCurrentTheme(new
592                     // com.incors.plaf.kunststoff.themes.KunststoffDesktopTheme());
593                 }
594
595             }
596
597
598             // If the option is enabled, open the last edited databases, if any.
599             if (!blank.isInvoked() && Globals.prefs.getBoolean("openLastEdited") && (Globals.prefs.get("lastEdited") != null)) {
600                 // How to handle errors in the databases to open?
601                 String[] names = Globals.prefs.getStringArray("lastEdited");
602 lastEdLoop: 
603                 for (int i = 0; i < names.length; i++) {
604                     File fileToOpen = new File(names[i]);
605
606                     for (int j = 0; j < loaded.size(); j++) {
607                         ParserResult pr = (ParserResult) loaded.elementAt(j);
608
609                         if ((pr.getFile() != null) &&pr.getFile().equals(fileToOpen))
610                             continue lastEdLoop;
611                     }
612
613                     if (fileToOpen.exists()) {
614                         ParserResult pr = openBibFile(names[i]);
615
616                         if (pr != null) {
617
618                             if (pr == ParserResult.INVALID_FORMAT) {
619                                 System.out.println(Globals.lang("Error opening file")+" '"+fileToOpen.getPath()+"'");
620                             }
621                             else
622                                 loaded.add(pr);
623
624                         }
625                     }
626                 }
627             }
628
629             GUIGlobals.init();
630             GUIGlobals.CURRENTFONT =
631                 new Font(Globals.prefs.get("fontFamily"), Globals.prefs.getInt("fontStyle"),
632                     Globals.prefs.getInt("fontSize"));
633
634             //Util.pr(": Initializing frame");
635             jrf = new JabRefFrame();
636
637             // Add all loaded databases to the frame:
638             boolean first = true;
639             if (loaded.size() > 0) {
640                 for (Iterator i=loaded.iterator(); i.hasNext();) {
641                     ParserResult pr = (ParserResult)i.next();
642                     jrf.addTab(pr.getDatabase(), pr.getFile(), pr.getMetaData(), pr.getEncoding(), first);
643                     first = false;
644                 }
645             }
646
647             if (loadSess.isInvoked())
648                 jrf.loadSessionAction.actionPerformed(new java.awt.event.ActionEvent(
649                         jrf, 0, ""));
650
651             if (splashScreen != null) {// do this only if splashscreen was actually created
652                 splashScreen.dispose();
653                 splashScreen = null;
654             }
655
656             //Util.pr(": Showing frame");
657             jrf.setVisible(true);
658
659             for (int i = 0; i < loaded.size(); i++) {
660                 ParserResult pr = (ParserResult) loaded.elementAt(i);
661                 if (Globals.prefs.getBoolean("displayKeyWarningDialogAtStartup") && pr.hasWarnings()) {
662                     String[] wrns = pr.warnings();
663                     StringBuffer wrn = new StringBuffer();
664                     for (int j = 0; j<wrns.length; j++)
665                         wrn.append(j + 1).append(". ").append(wrns[j]).append("\n");
666                     if (wrn.length() > 0)
667                         wrn.deleteCharAt(wrn.length() - 1);
668                     jrf.showBaseAt(i);
669                     JOptionPane.showMessageDialog(jrf, wrn.toString(),
670                         Globals.lang("Warnings"),
671                         JOptionPane.WARNING_MESSAGE);
672                 }
673             }
674
675             //Util.pr(": Finished adding panels");
676
677             if (loaded.size() > 0) {
678                 jrf.tabbedPane.setSelectedIndex(0);
679                 new FocusRequester(((BasePanel) jrf.tabbedPane.getComponentAt(0)).mainTable);
680             }
681         } else
682             System.exit(0);
683     }
684
685     public static ParserResult openBibFile(String name) {
686         System.out.println(Globals.lang("Opening") + ": " + name);
687
688         try {
689             File file = new File(name);
690             String encoding = Globals.prefs.get("defaultEncoding");
691             ParserResult pr = OpenDatabaseAction.loadDatabase(file, encoding);
692             if (pr == null)
693                 return ParserResult.INVALID_FORMAT;
694             pr.setFile(file);
695             if (pr.hasWarnings()) {
696                 String[] warn = pr.warnings();
697                 for (int i=0; i<warn.length; i++)
698                     System.out.println(Globals.lang("Warning")+": "+warn[i]);
699
700             }
701             return pr;
702         } catch (Throwable ex) {
703             //System.err.println(Globals.lang("Error opening file")+" '"+ name+"':
704             // "+ex.getMessage());
705             System.err.println(Globals.lang("Error opening file") + ": "
706                 + ex.getMessage());
707         }
708
709         return null;
710     }
711
712     public static ParserResult importToOpenBase(String argument) {
713         String[] data = argument.split(",");
714         try {
715             if ((data.length > 1) && !"*".equals(data[1])) {
716                 System.out.println(Globals.lang("Importing") + ": " + data[0]);
717                 List entries =
718                     Globals.importFormatReader.importFromFile(data[1],
719                         data[0].replaceAll("~", System.getProperty("user.home")));
720                 BibtexDatabase base = ImportFormatReader.createDatabase(entries);
721                 ParserResult pr = new ParserResult(base, null, new HashMap());
722                 pr.setToOpenTab(true);
723                 //loaded.add(pr);
724                 return pr;
725             } else {
726                 // * means "guess the format":
727                 System.out.println(Globals.lang("Importing in unknown format")
728                     + ": " + data[0]);
729
730                 Object[] o =
731                     Globals.importFormatReader.importUnknownFormat(data[0]
732                         .replaceAll("~", System.getProperty("user.home")));
733                 String formatName = (String) o[0];
734
735                 if (formatName.equals(ImportFormatReader.BIBTEX_FORMAT)) {
736                     ParserResult pr = (ParserResult)o[1];
737                     pr.setToOpenTab(true);
738                     //loaded.add(pr);
739                     return pr;
740                 }
741                 else {
742                     List entries = (java.util.List) o[1];
743                     if (entries != null)
744                         System.out.println(Globals.lang("Format used") + ": "
745                             + formatName);
746                     else
747                         System.out.println(Globals.lang(
748                                 "Could not find a suitable import format."));
749
750                     if (entries != null) {
751                         BibtexDatabase base = ImportFormatReader.createDatabase(entries);
752                         ParserResult pr = new ParserResult(base, null, new HashMap());
753
754                         //pr.setFile(new File(data[0]));
755                         pr.setToOpenTab(true);
756                         //loaded.add(pr);
757                         return pr;
758                     }
759                 }
760
761             }
762         } catch (IOException ex) {
763             System.err.println(Globals.lang("Error opening file") + " '"
764                 + data[0] + "': " + ex.getMessage());
765         }
766
767         return null;
768     }
769 }