d177fb90485f8340b2288af8821ebae20836ba20
[debian/jabref.git] / src / java / net / sf / jabref / export / ExportFormats.java
1 package net.sf.jabref.export;
2
3 import net.sf.jabref.*;
4
5 import javax.swing.*;
6 import javax.swing.filechooser.FileFilter;
7 import java.util.*;
8 import java.awt.event.ActionEvent;
9 import java.io.File;
10
11 /**
12  * User: alver
13  * 
14  * Date: Oct 18, 2006 
15  * 
16  * Time: 9:35:08 PM 
17  */
18 public class ExportFormats {
19
20         private static Map<String,ExportFormat> exportFormats = new TreeMap<String,ExportFormat>();
21
22     public static void initAllExports() {
23         exportFormats.clear();
24
25         // Initialize Build-In Export Formats
26         putFormat(new ExportFormat(
27                 Globals.lang("HTML"), "html", "html", null, ".html"));
28         putFormat(new ExportFormat(
29                 Globals.lang("Simple HTML"), "simplehtml", "simplehtml", null, ".html"));
30         putFormat(new ExportFormat(Globals.lang("Docbook"), "docbook", "docbook", null, ".xml"));
31         putFormat(new ExportFormat(Globals.lang("BibTeXML"), "bibtexml", "bibtexml", null, ".xml"));
32         putFormat(new ModsExportFormat());
33         putFormat(new ExportFormat(Globals.lang("HTML table"),
34                 "tablerefs", "tablerefs", "tablerefs", ".html"));
35         putFormat(new ExportFormat(Globals.lang("HTML table (with Abstract & BibTeX)"),
36                 "tablerefsabsbib", "tablerefsabsbib", "tablerefsabsbib", ".html"));
37         putFormat(new ExportFormat(Globals.lang("Harvard RTF"), "harvard", "harvard",
38                 "harvard", ".rtf"));
39         putFormat(new ExportFormat(Globals.lang("MIS Quarterly"), "misq", "misq",
40                 "misq", ".rtf"));
41         putFormat(new ExportFormat(Globals.lang("Endnote"), "endnote", "EndNote",
42                 "endnote", ".txt"));
43         putFormat(new OpenOfficeDocumentCreator());
44         putFormat(new OpenDocumentSpreadsheetCreator());
45         putFormat(new MSBibExportFormat());
46     
47         // Now add custom export formats
48         TreeMap customExports = Globals.prefs.customExports.getCustomExportFormats();
49         for (Iterator i=customExports.keySet().iterator(); i.hasNext();) {
50             putFormat((ExportFormat)customExports.get(i.next()));
51         }
52     }
53
54         /**
55          * Build a string listing of all available export formats.
56          * 
57          * @param maxLineLength
58          *            The max line length before a line break must be added.
59          * @param linePrefix
60          *            If a line break is added, this prefix will be inserted at the
61          *            beginning of the next line.
62          * @return The string describing available formats.
63          */
64         public static String getConsoleExportList(int maxLineLength, int firstLineSubtr,
65                 String linePrefix) {
66                 StringBuffer sb = new StringBuffer();
67                 int lastBreak = -firstLineSubtr;
68
69                 for (Iterator i = exportFormats.keySet().iterator(); i.hasNext();) {
70                         String name = (String) i.next();
71                         if (sb.length() + 2 + name.length() - lastBreak > maxLineLength) {
72                                 sb.append(",\n");
73                                 lastBreak = sb.length();
74                                 sb.append(linePrefix);
75                         } else if (sb.length() > 0)
76                                 sb.append(", ");
77                         sb.append(name);
78                 }
79
80                 return sb.toString();
81         }
82
83     /**
84      * Get a Map of all export formats.
85      * @return A Map containing all export formats, mapped to their console names.
86      */
87     public static Map getExportFormats() {
88         // It is perhaps overly paranoid to make a defensive copy in this case:
89         return Collections.unmodifiableMap(exportFormats);
90     } 
91
92     /**
93          * Look up the named export format.
94          * 
95          * @param consoleName
96          *            The export name given in the JabRef console help information.
97          * @return The ExportFormat, or null if no exportformat with that name is
98          *         registered.
99          */
100         public static ExportFormat getExportFormat(String consoleName) {
101                 return (ExportFormat) exportFormats.get(consoleName);
102         }
103
104         /**
105          * Create an AbstractAction for performing an export operation.
106          * 
107          * @param frame
108          *            The JabRefFrame of this JabRef instance.
109          * @param selectedOnly
110          *            true indicates that only selected entries should be exported,
111          *            false indicates that all entries should be exported.
112          * @return The action.
113          */
114         public static AbstractAction getExportAction(JabRefFrame frame, boolean selectedOnly) {
115
116                 class ExportAction extends MnemonicAwareAction {
117
118                         private static final long serialVersionUID = 639463604530580554L;
119
120                         private JabRefFrame frame;
121
122                         private boolean selectedOnly;
123
124                         public ExportAction(JabRefFrame frame, boolean selectedOnly) {
125                                 this.frame = frame;
126                                 this.selectedOnly = selectedOnly;
127                                 putValue(NAME, selectedOnly ? "Export selected entries" : "Export");
128                         }
129
130                         public void actionPerformed(ActionEvent e) {
131                                 ExportFormats.initAllExports();
132                                 JFileChooser fc = ExportFormats.createExportFileChooser(
133                     Globals.prefs.get("exportWorkingDirectory"));
134                                 fc.showSaveDialog(frame);
135                                 File file = fc.getSelectedFile();
136                                 if (file == null)
137                                         return;
138                                 FileFilter ff = fc.getFileFilter();
139                                 if (ff instanceof ExportFileFilter) {
140
141                     ExportFileFilter eff = (ExportFileFilter) ff;
142                     String path = file.getPath();
143                     if (!path.endsWith(eff.getExportFormat().getExtension()))
144                         path = path + eff.getExportFormat().getExtension();
145                     file = new File(path);
146                     if (file.exists()) {
147                         // Warn that the file exists:
148                         if (JOptionPane.showConfirmDialog(frame, "'" + file.getName() + "' "
149                             + Globals.lang("exists. Overwrite file?"), Globals.lang("Export"),
150                             JOptionPane.OK_CANCEL_OPTION) != JOptionPane.OK_OPTION)
151                             return;
152                     }
153                     final ExportFormat format = eff.getExportFormat();
154                     Set<String> entryIds = null;
155                     if (selectedOnly) {
156                         BibtexEntry[] selected = frame.basePanel().getSelectedEntries();
157                         entryIds = new HashSet<String>();
158                         for (int i = 0; i < selected.length; i++) {
159                             BibtexEntry bibtexEntry = selected[i];
160                             entryIds.add(bibtexEntry.getId());
161                         }
162                     }
163
164                     // Make sure we remember which filter was used, to set
165                     // the default for next time:
166                     Globals.prefs.put("lastUsedExport", format.getConsoleName());
167                     Globals.prefs.put("exportWorkingDirectory", file.getParent());
168                     final File finFile = file;
169                     final Set<String> finEntryIDs = entryIds;
170                     AbstractWorker exportWorker = new AbstractWorker() {
171                         String errorMessage = null;
172                         public void run() {
173                             try {
174                                 format.performExport(frame.basePanel().database(), finFile.getPath(), frame
175                                     .basePanel().getEncoding(), finEntryIDs);
176                             } catch (Exception ex) {
177                                 //ex.printStackTrace();
178                                 errorMessage = ex.getMessage();
179                             }
180                         }
181
182                         public void update() {
183                             // No error message. Report success:
184                             if (errorMessage == null) {
185                                 frame.output(Globals.lang("%0 export successful", format.getDisplayName()));
186                             }
187                             // ... or show an error dialog:
188                             else {
189                                 frame.output(Globals.lang("Could not save file")
190                                         + " - " + errorMessage);
191                                 // Need to warn the user that saving failed!
192                                 JOptionPane.showMessageDialog(frame, Globals.lang("Could not save file")
193                                     + ".\n" + errorMessage, Globals.lang("Save database"),
194                                     JOptionPane.ERROR_MESSAGE);
195                             }
196                         }
197                     };
198
199                     // Run the export action in a background thread:
200                     (exportWorker.getWorker()).run();
201                     // Run the update method:
202                     exportWorker.update();
203                 }
204                         }
205                 }
206
207                 return new ExportAction(frame, selectedOnly);
208         }
209
210     
211     public static JFileChooser createExportFileChooser(String currentDir) {
212                 String lastUsedFormat = Globals.prefs.get("lastUsedExport");
213                 FileFilter defaultFilter = null;
214                 JFileChooser fc = new JFileChooser(currentDir);
215                 TreeSet<FileFilter> filters = new TreeSet<FileFilter>();
216                 for (Iterator i = exportFormats.keySet().iterator(); i.hasNext();) {
217                         String formatName = (String) i.next();
218                         ExportFormat format = (ExportFormat) exportFormats.get(formatName);
219                         filters.add(format.getFileFilter());
220                         if (formatName.equals(lastUsedFormat))
221                                 defaultFilter = format.getFileFilter();
222                 }
223                 for (Iterator i = filters.iterator(); i.hasNext();) {
224                         fc.addChoosableFileFilter((ExportFileFilter) i.next());
225                 }
226                 fc.setAcceptAllFileFilterUsed(false);
227                 if (defaultFilter != null)
228                         fc.setFileFilter(defaultFilter);
229                 return fc;
230         }
231
232         private static void putFormat(ExportFormat format) {
233                 exportFormats.put(format.getConsoleName(), format);
234         }
235
236 }