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