51f19059929edc3b622fc847fbdc92427d3a1190
[debian/jabref.git] / src / java / net / sf / jabref / journals / ManageJournalsPanel.java
1 package net.sf.jabref.journals;
2
3 import net.sf.jabref.*;
4 import net.sf.jabref.net.URLDownload;
5
6 import javax.swing.*;
7 import javax.swing.table.AbstractTableModel;
8
9 import com.jgoodies.forms.layout.FormLayout;
10 import com.jgoodies.forms.layout.CellConstraints;
11 import com.jgoodies.forms.builder.DefaultFormBuilder;
12 import com.jgoodies.forms.builder.ButtonBarBuilder;
13 import com.jgoodies.forms.builder.ButtonStackBuilder;
14
15 import java.awt.event.*;
16 import java.awt.*;
17 import java.io.File;
18 import java.io.FileNotFoundException;
19 import java.io.FileWriter;
20 import java.io.IOException;
21 import java.util.Map;
22 import java.util.ArrayList;
23 import java.util.Iterator;
24 import java.util.Collections;
25 import java.net.URL;
26 import java.net.MalformedURLException;
27
28 /**
29  * Created by IntelliJ IDEA.
30  * User: alver
31  * Date: Sep 19, 2005
32  * Time: 7:57:29 PM
33  * To browseOld this template use File | Settings | File Templates.
34  */
35 public class ManageJournalsPanel extends JPanel{
36
37     JabRefFrame frame;
38     JTextField personalFile = new JTextField();
39     AbbreviationsTableModel tableModel = new AbbreviationsTableModel();
40     JTable userTable; // builtInTable
41     JPanel userPanel = new JPanel(),
42         journalEditPanel,
43         externalFilesPanel = new JPanel(),
44         addExtPan = new JPanel();
45     JTextField nameTf = new JTextField(),
46         newNameTf = new JTextField(),
47         abbrTf = new JTextField();
48     java.util.List externals = new ArrayList(); // To hold references to external journal lists.
49     JDialog dialog;
50     JRadioButton newFile = new JRadioButton(Globals.lang("New file")),
51         oldFile = new JRadioButton(Globals.lang("Existing file"));
52
53     JButton add = new JButton(GUIGlobals.getImage("add")),
54         remove = new JButton(GUIGlobals.getImage("remove")),
55         ok = new JButton(Globals.lang("Ok")),
56         cancel = new JButton(Globals.lang("Cancel")),
57         help = new JButton(Globals.lang("Help")),
58         browseOld = new JButton(Globals.lang("Browse")),
59         browseNew = new JButton(Globals.lang("Browse")),
60         addExt = new JButton(GUIGlobals.getImage("add"));
61
62
63     public ManageJournalsPanel(final JabRefFrame frame) {
64         this.frame = frame;
65
66         personalFile.setEditable(false);
67
68         ButtonGroup group = new ButtonGroup();
69         group.add(newFile);
70         group.add(oldFile);
71         addExtPan.setLayout(new BorderLayout());
72         addExtPan.add(addExt, BorderLayout.EAST);
73         addExtPan.setToolTipText(Globals.lang("Add"));
74         //addExtPan.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.red));
75         FormLayout layout = new FormLayout
76                 ("1dlu, 8dlu, left:pref, 4dlu, fill:200dlu:grow, 4dlu, fill:pref", // 4dlu, left:pref, 4dlu",
77                         "pref, 20dlu, 20dlu, fill:200dlu, 4dlu, pref");//150dlu");
78         DefaultFormBuilder builder = new DefaultFormBuilder(layout);
79
80         CellConstraints cc = new CellConstraints();
81
82         /*JLabel description = new JLabel("<HTML>"+Globals.lang("JabRef can switch journal names between "
83             +"abbreviated and full form. Since it knows only a limited number of journal names, "
84             +"you may need to add your own definitions.")+"</HTML>");*/
85         builder.addSeparator(Globals.lang("Personal journal list"), cc.xyw(2,1,6));
86
87         //builder.add(description, cc.xyw(2,1,6));
88         builder.add(newFile, cc.xy(3,2));
89         builder.add(newNameTf, cc.xy(5,2));
90         builder.add(browseNew, cc.xy(7,2));
91         builder.add(oldFile, cc.xy(3,3));
92         builder.add(personalFile, cc.xy(5,3));
93         //BrowseAction action = new BrowseAction(personalFile, false);
94         //JButton browse = new JButton(Globals.lang("Browse"));
95         //browse.addActionListener(action);
96         builder.add(browseOld, cc.xy(7,3));
97
98         userPanel.setLayout(new BorderLayout());
99         //builtInTable = new JTable(Globals.journalAbbrev.getTableModel());
100         builder.add(userPanel, cc.xyw(2,4,4));
101         ButtonStackBuilder butBul = new ButtonStackBuilder();
102         butBul.addGridded(add);
103         butBul.addGridded(remove);
104
105         butBul.addGlue();
106         builder.add(butBul.getPanel(), cc.xy(7,4));
107
108         builder.addSeparator(Globals.lang("External files"), cc.xyw(2,6,6));
109         externalFilesPanel.setLayout(new BorderLayout());
110         //builder.add(/*new JScrollPane(*/externalFilesPanel/*)*/, cc.xyw(2,8,6));
111
112         setLayout(new BorderLayout());
113         builder.getPanel().setBorder(BorderFactory.createEmptyBorder(5,5,5,5));//createMatteBorder(1,1,1,1,Color.green));
114         add(builder.getPanel(), BorderLayout.NORTH);
115         add(externalFilesPanel, BorderLayout.CENTER);
116         ButtonBarBuilder bb = new ButtonBarBuilder();
117         bb.addGlue();
118         bb.addGridded(ok);
119         bb.addGridded(cancel);
120         bb.addUnrelatedGap();
121         bb.addGridded(help);
122         bb.addGlue();
123         bb.getPanel().setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
124         dialog = new JDialog(frame, Globals.lang("Journal abbreviations"), false);
125         dialog.getContentPane().add(this, BorderLayout.CENTER);
126         dialog.getContentPane().add(bb.getPanel(), BorderLayout.SOUTH);
127
128         //add(new JScrollPane(builtInTable), BorderLayout.CENTER);
129
130         // Set up panel for editing a single journal, to be used in a dialog box:
131         FormLayout layout2 = new FormLayout
132                 ("right:pref, 4dlu, fill:180dlu", "");
133         DefaultFormBuilder builder2 = new DefaultFormBuilder(layout2);
134         builder2.append(Globals.lang("Journal name"));
135         builder2.append(nameTf);
136         builder2.nextLine();
137         builder2.append(Globals.lang("ISO abbreviation"));
138         builder2.append(abbrTf);
139         journalEditPanel = builder2.getPanel();
140
141         browseNew.addActionListener(new ActionListener() {
142             public void actionPerformed(ActionEvent e) {
143                 File old = null;
144                 if (!newNameTf.getText().equals(""))
145                     old = new File(newNameTf.getText());
146                 String name = Globals.getNewFile(frame, old, null, JFileChooser.SAVE_DIALOG, false);
147                 if (name != null) {
148                     if ((old != null) && (tableModel.getRowCount() > 0)) {
149                     }
150                     newNameTf.setText(name);
151                     newFile.setSelected(true);
152                 }
153             }
154         });
155         browseOld.addActionListener(new ActionListener() {
156             public void actionPerformed(ActionEvent e) {
157                 File old = null;
158                 if (!personalFile.getText().equals(""))
159                     old = new File(personalFile.getText());
160                 String name = Globals.getNewFile(frame, old, null, JFileChooser.OPEN_DIALOG, false);
161                 if (name != null) {
162                     if ((old != null) && (tableModel.getRowCount() > 0)) {
163                     }
164                     personalFile.setText(name);
165                     oldFile.setSelected(true);
166                     oldFile.setEnabled(true);
167                     setupUserTable();
168                 }
169             }
170         });
171
172
173         ok.addActionListener(new ActionListener() {
174             public void actionPerformed(ActionEvent e) {
175                 if (readyToClose()) {
176                     storeSettings();
177                     dialog.dispose();
178                 }
179             }
180         });
181         help.addActionListener(new HelpAction(Globals.helpDiag, GUIGlobals.journalAbbrHelp));
182         cancel.addActionListener(new ActionListener() {
183                     public void actionPerformed(ActionEvent e) {
184                         dialog.dispose();
185                     }
186                 });
187
188         add.addActionListener(tableModel);
189         remove.addActionListener(tableModel);
190         addExt.addActionListener(new ActionListener() {
191             public void actionPerformed(ActionEvent e) {
192                 externals.add(new ExternalFileEntry());
193                 buildExternalsPanel();
194             }
195         });
196
197         //dialog.pack();
198         int xSize = getPreferredSize().width;
199         dialog.setSize(xSize+10,700);
200     }
201
202     public JDialog getDialog() {
203         return dialog;
204     }
205
206     public void setValues() {
207         personalFile.setText(Globals.prefs.get("personalJournalList"));
208         if (personalFile.getText().length() == 0) {
209             newFile.setSelected(true);
210             oldFile.setEnabled(false);
211         } else {
212             oldFile.setSelected(true);
213             oldFile.setEnabled(true);
214         }
215         setupUserTable();
216         setupExternals();
217         buildExternalsPanel();
218
219     }
220
221     private void buildExternalsPanel() {
222
223         DefaultFormBuilder builder = new DefaultFormBuilder(new FormLayout("fill:pref:grow",""));
224         for (Iterator i=externals.iterator(); i.hasNext();) {
225             ExternalFileEntry efe = (ExternalFileEntry)i.next();
226             builder.append(efe.getPanel());
227             builder.nextLine();
228         }
229         builder.append(Box.createVerticalGlue());
230         builder.nextLine();
231         builder.append(addExtPan);
232         builder.nextLine();
233         builder.append(Box.createVerticalGlue());
234
235         //builder.getPanel().setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.green));
236         //externalFilesPanel.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.red));
237         JScrollPane pane = new JScrollPane(builder.getPanel());
238         pane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
239         externalFilesPanel.setMinimumSize(new Dimension(400,400));
240         externalFilesPanel.setPreferredSize(new Dimension(400,400));
241         externalFilesPanel.removeAll();
242         externalFilesPanel.add(pane, BorderLayout.CENTER);
243         externalFilesPanel.revalidate();
244         externalFilesPanel.repaint();
245
246     }
247
248     private void setupExternals() {
249         String[] externalFiles = Globals.prefs.getStringArray("externalJournalLists");
250         if ((externalFiles == null) || (externalFiles.length == 0)) {
251             ExternalFileEntry efe = new ExternalFileEntry();
252             externals.add(efe);
253         } else {
254             for (int i=0; i<externalFiles.length; i++) {
255                 ExternalFileEntry efe = new ExternalFileEntry(externalFiles[i]);
256                 externals.add(efe);
257
258             }
259
260         }
261
262         //efe = new ExternalFileEntry();
263         //externals.add(efe);
264
265     }
266
267     public void setupUserTable() {
268         JournalAbbreviations userAbbr = new JournalAbbreviations();
269         String filename = personalFile.getText();
270         if (!filename.equals("") && (new File(filename)).exists()) {
271             try {
272                 userAbbr.readJournalList(new File(filename));
273             } catch (FileNotFoundException e) {
274                 e.printStackTrace();
275             }
276         }
277
278         tableModel.setJournals(userAbbr.getJournals());
279         userTable = new JTable(tableModel);
280         userTable.addMouseListener(tableModel.getMouseListener());
281         userPanel.add(new JScrollPane(userTable), BorderLayout.CENTER);
282     }
283
284     public boolean readyToClose() {
285         File f;
286         if (newFile.isSelected()) {
287             if (newNameTf.getText().length() > 0) {
288                 f = new File(newNameTf.getText());
289                 return (!f.exists() ||
290                     (JOptionPane.showConfirmDialog
291                      (this, "'"+f.getName()+"' "+Globals.lang("exists. Overwrite file?"),
292                       Globals.lang("Store journal abbreviations"), JOptionPane.OK_CANCEL_OPTION)
293                      == JOptionPane.OK_OPTION));
294             } else {
295                 if (tableModel.getRowCount() > 0) {
296                     JOptionPane.showMessageDialog(this, Globals.lang("You must choose a file name to store journal abbreviations"),
297                             Globals.lang("Store journal abbreviations"), JOptionPane.ERROR_MESSAGE);
298                         return false;
299                 }
300                 else return true;
301
302             }
303         }
304         return true;
305     }
306
307     public void storeSettings() {
308         File f = null;
309         if (newFile.isSelected()) {
310             if (newNameTf.getText().length() > 0) {
311                 f = new File(newNameTf.getText());
312             }// else {
313             //    return; // Nothing to do.
314             //}
315         } else
316             f = new File(personalFile.getText());
317
318         if (f != null) {
319             FileWriter fw = null;
320             try {
321                 fw = new FileWriter(f, false);
322                 for (Iterator i=tableModel.getJournals().iterator(); i.hasNext();) {
323                     JournalEntry entry = (JournalEntry)i.next();
324                     fw.write(entry.name);
325                     fw.write(" = ");
326                     fw.write(entry.abbreviation);
327                     fw.write(Globals.NEWLINE);
328                 }
329
330             } catch (IOException e) {
331                 e.printStackTrace();
332
333             } finally {
334                 if (fw != null)
335                     try {
336                         fw.close();
337                     } catch (IOException e) {
338                         e.printStackTrace();
339                     }
340             }
341
342             String filename = f.getPath();
343             if (filename.equals(""))
344                 filename = null;
345             Globals.prefs.put("personalJournalList", filename);
346         }
347
348         // Store the list of external files set up:
349         ArrayList extFiles = new ArrayList();
350         for (Iterator i=externals.iterator(); i.hasNext();) {
351             ExternalFileEntry efe = (ExternalFileEntry)i.next();
352             if (!efe.getValue().equals("")) {
353                 extFiles.add(efe.getValue());
354             }
355         }
356         if (extFiles.size() == 0)
357             Globals.prefs.put("externalJournalLists", "");
358         else {
359             String[] list = (String[])extFiles.toArray(new String[extFiles.size()]);
360             Globals.prefs.putStringArray("externalJournalLists", list);
361         }
362
363
364         Globals.initializeJournalNames();
365
366     }
367
368     class DownloadAction extends AbstractAction {
369         JTextField comp;
370
371         public DownloadAction(JTextField tc) {
372             super(Globals.lang("Download"));
373             comp = tc;
374         }
375
376         public void actionPerformed(ActionEvent e) {
377             String chosen = null;
378             chosen = JOptionPane.showInputDialog(Globals.lang("Choose the URL to download. The default value points to a list provided by the JabRef developers."),
379                     "http://jabref.sf.net/journals/journal_abbreviations_general.txt");
380             if (chosen == null)
381                 return;
382             File toFile;
383             try {
384                 URL url = new URL(chosen);
385                 String toName = Globals.getNewFile(frame, new File(System.getProperty("user.home")),
386                         null, JFileChooser.SAVE_DIALOG, false);
387                 if (toName == null)
388                     return;
389                 else toFile = new File(toName);
390                 URLDownload ud = new URLDownload(comp, url, toFile);
391                 ud.download();
392                 comp.setText(toFile.getPath());
393             } catch (MalformedURLException ex) {
394                 ex.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
395             } catch (IOException ex2) {
396                 ex2.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
397             }
398         }
399     }
400
401     class BrowseAction extends AbstractAction {
402         JTextField comp;
403         boolean dir;
404
405         public BrowseAction(JTextField tc, boolean dir) {
406             super(Globals.lang("Browse"));
407             this.dir = dir;
408             comp = tc;
409         }
410
411         public void actionPerformed(ActionEvent e) {
412             String chosen = null;
413             if (dir)
414                 chosen = Globals.getNewDir(frame, new File(comp.getText()), Globals.NONE,
415                         JFileChooser.OPEN_DIALOG, false);
416             else
417                 chosen = Globals.getNewFile(frame, new File(comp.getText()), Globals.NONE,
418                         JFileChooser.OPEN_DIALOG, false);
419             if (chosen != null) {
420                 File newFile = new File(chosen);
421                 comp.setText(newFile.getPath());
422             }
423         }
424     }
425
426     class AbbreviationsTableModel extends AbstractTableModel implements ActionListener {
427
428         String[] names = new String[] {Globals.lang("Journal name"), Globals.lang("Abbreviation")};
429         ArrayList journals = null;
430
431         public AbbreviationsTableModel() {
432
433
434         }
435
436         public void setJournals(Map journals) {
437             this.journals = new ArrayList();
438             for (Iterator i=journals.keySet().iterator(); i.hasNext();) {
439                 String journal = (String)i.next(),
440                         abbr = (String)journals.get(journal);
441                 this.journals.add(new JournalEntry(journal, abbr));
442             }
443             fireTableDataChanged();
444         }
445
446         public ArrayList getJournals() {
447             return journals;
448         }
449
450         public int getColumnCount() {
451             return 2;
452         }
453
454         public int getRowCount() {
455             return journals.size();
456         }
457
458         public Object getValueAt(int row, int col) {
459             if (col == 0)
460                 return ((JournalEntry)journals.get(row)).name;
461             else
462                 return ((JournalEntry)journals.get(row)).abbreviation;
463         }
464
465         public void setValueAt(Object object, int row, int col) {
466             JournalEntry entry = (JournalEntry)journals.get(row);
467             if (col == 0)
468                 entry.name = (String)object;
469             else
470                 entry.abbreviation = (String)object;
471
472         }
473
474         public String getColumnName(int i) {
475             return names[i];
476         }
477
478         public boolean isCellEditable(int i, int i1) {
479             return false;
480         }
481
482         public MouseListener getMouseListener() {
483             return new MouseAdapter() {
484                 public void mouseClicked(MouseEvent e) {
485                     if (e.getClickCount() == 2) {
486                         JTable table = (JTable)e.getSource();
487                         int row = table.rowAtPoint(e.getPoint());
488                         nameTf.setText((String)getValueAt(row,0));
489                         abbrTf.setText((String)getValueAt(row,1));
490                         if (JOptionPane.showConfirmDialog(dialog, journalEditPanel, Globals.lang("Edit journal"),
491                             JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
492                             setValueAt(nameTf.getText(), row, 0);
493                             setValueAt(abbrTf.getText(), row, 1);
494                             Collections.sort(journals);
495                             fireTableDataChanged();
496                         }
497
498                     }
499                 }
500             };
501         }
502
503         public void actionPerformed(ActionEvent e) {
504             if (e.getSource() == add) {
505                 //int sel = userTable.getSelectedRow();
506                 //if (sel < 0)
507                 //    sel = 0;
508
509                 nameTf.setText("");
510                 abbrTf.setText("");
511                 if (JOptionPane.showConfirmDialog(dialog, journalEditPanel, Globals.lang("Edit journal"),
512                         JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
513                     journals.add(new JournalEntry(nameTf.getText(), abbrTf.getText()));
514                     //setValueAt(nameTf.getText(), sel, 0);
515                     //setValueAt(abbrTf.getText(), sel, 1);
516                     Collections.sort(journals);
517                     fireTableDataChanged();
518                 }
519             }
520             else if (e.getSource() == remove) {
521                 int[] rows = userTable.getSelectedRows();
522                 if (rows.length > 0) {
523                     for (int i=rows.length-1; i>=0; i--) {
524                         journals.remove(rows[i]);
525                     }
526                     fireTableDataChanged();
527                 }
528             }
529         }
530     }
531
532     class ExternalFileEntry {
533         private JPanel pan;
534         private JTextField tf;
535         private JButton browse = new JButton(Globals.lang("Browse")),
536             view = new JButton(Globals.lang("Preview")),
537             clear = new JButton(GUIGlobals.getImage("delete")),
538             download = new JButton(Globals.lang("Download"));
539         public ExternalFileEntry() {
540             tf = new JTextField();
541             setupPanel();
542         }
543         public ExternalFileEntry(String filename) {
544             tf = new JTextField(filename);
545             setupPanel();
546         }
547         private void setupPanel() {
548             tf.setEditable(false);
549             BrowseAction browseA = new BrowseAction(tf, false);
550             browse.addActionListener(browseA);
551             DownloadAction da = new DownloadAction(tf);
552             download.addActionListener(da);
553             DefaultFormBuilder builder = new DefaultFormBuilder
554                     (new FormLayout("fill:pref:grow, 4dlu, fill:pref, 4dlu, fill:pref, 4dlu, fill:pref, 4dlu, fill:pref", ""));
555             builder.append(tf);
556             builder.append(browse);
557             builder.append(download);
558             builder.append(view);
559             builder.append(clear);
560
561             pan = builder.getPanel();
562
563             view.addActionListener(new ActionListener() {
564                 public void actionPerformed(ActionEvent e) {
565                     try {
566                         JournalAbbreviations abbr = new JournalAbbreviations(new File(tf.getText()));
567                         JTable table = new JTable(abbr.getTableModel());
568                         JScrollPane pane = new JScrollPane(table);
569                         JOptionPane.showMessageDialog(null, pane, Globals.lang("Journal list preview"), JOptionPane.INFORMATION_MESSAGE);
570                     } catch (FileNotFoundException ex) {
571                         JOptionPane.showMessageDialog(null, Globals.lang("File '%0' not found", tf.getText()),
572                                 Globals.lang("Error"), JOptionPane.ERROR_MESSAGE);
573                     }
574                 }
575             });
576             clear.addActionListener(new ActionListener() {
577                 public void actionPerformed(ActionEvent e) {
578                     externals.remove(ExternalFileEntry.this);
579                     buildExternalsPanel();
580                 }
581             });
582             clear.setToolTipText(Globals.lang("Remove"));
583
584         }
585         public JPanel getPanel() { return pan; }
586         public String getValue() { return tf.getText(); }
587     }
588
589     class JournalEntry implements Comparable {
590         String name, abbreviation;
591         public JournalEntry(String name, String abbreviation) {
592             this.name = name;
593             this.abbreviation = abbreviation;
594         }
595         public int compareTo(Object other) {
596             JournalEntry entry = (JournalEntry)other;
597             return this.name.compareTo(entry.name);
598         }
599     }
600 }
601
602