KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > editor > example > Editor


1 /*
2  * Editor.java
3  *
4  * Created on August 4, 2000, 9:06 AM
5  */

6 package org.netbeans.editor.example;
7
8 import java.util.*;
9
10 import java.net.URL JavaDoc;
11 import java.io.*;
12 import java.awt.Component JavaDoc;
13 import java.awt.Dimension JavaDoc;
14 import java.awt.MenuItem JavaDoc;
15 import java.awt.event.*;
16 import java.util.ArrayList JavaDoc;
17 import java.util.Collection JavaDoc;
18 import java.util.Iterator JavaDoc;
19
20 import javax.swing.*;
21 import javax.swing.text.Document JavaDoc;
22 import javax.swing.text.EditorKit JavaDoc;
23 import javax.swing.text.JTextComponent JavaDoc;
24 import javax.swing.event.DocumentListener JavaDoc;
25 import javax.swing.event.DocumentEvent JavaDoc;
26 import javax.swing.undo.UndoManager JavaDoc;
27 import javax.swing.filechooser.FileFilter JavaDoc;
28 import javax.swing.filechooser.FileView JavaDoc;
29 import org.netbeans.editor.*;
30 import org.netbeans.editor.ext.*;
31
32
33 /**
34  *
35  * @author Petr Nejedly
36  * @version 0.2
37  */

38 public class Editor extends javax.swing.JFrame JavaDoc {
39
40     private static final File distributionDirectory;
41     
42     static {
43     URL JavaDoc url = Editor.class.getProtectionDomain().getCodeSource().getLocation();
44     String JavaDoc protocol = url.getProtocol();
45     File file = new File(url.getFile());
46     if (!file.isDirectory()) file = file.getParentFile();
47     distributionDirectory = file;
48     }
49     
50     /** Document property holding String name of associated file */
51     private static final String JavaDoc FILE = "file"; // NOI18N
52
/** Document property holding Boolean if document was created or opened */
53     private static final String JavaDoc CREATED = "created"; // NOI18N
54
/** Document property holding Boolean modified information */
55     private static final String JavaDoc MODIFIED = "modified"; // NOI18N
56

57     private ResourceBundle settings = ResourceBundle.getBundle( "settings" ); // NOI18N
58

59     private JFileChooser fileChooser;
60
61     private boolean createBackups;
62     private boolean safeSave;
63
64     private int fileCounter = -1;
65     Map com2text = new HashMap();
66     
67     private Impl impl = new Impl("org.netbeans.editor.Bundle"); // NOI18N
68

69     private class Impl extends FileView JavaDoc implements WindowListener,
70                                     ActionListener, LocaleSupport.Localizer {
71                                         
72         private ResourceBundle bundle;
73     
74     public Impl( String JavaDoc bundleName ) {
75         bundle = ResourceBundle.getBundle( bundleName );
76     }
77
78         // FileView implementation
79
public String JavaDoc getName( File f ) { return null; }
80     public String JavaDoc getDescription( File f ) { return null; }
81     public String JavaDoc getTypeDescription( File f ) { return null; }
82     public Boolean JavaDoc isTraversable( File f ) { return null; }
83         public Icon getIcon( File f ) {
84             if( f.isDirectory() ) return null;
85             KitInfo ki = KitInfo.getKitInfoForFile( f );
86             return ki == null ? null : ki.getIcon();
87         }
88         
89         // Localizer
90
public String JavaDoc getString( String JavaDoc key ) {
91         return bundle.getString( key );
92     }
93         
94         // Mostly no-op WindowListener for close
95
public void windowActivated(WindowEvent evt) {}
96         public void windowClosed(WindowEvent evt) {}
97         public void windowDeactivated(WindowEvent evt) {}
98         public void windowDeiconified(WindowEvent evt) {}
99         public void windowIconified(WindowEvent evt) {}
100         public void windowOpened(WindowEvent evt) {}
101         public void windowClosing(java.awt.event.WindowEvent JavaDoc evt) {
102             doExit();
103         }
104
105         // ActionListener for menu items
106
public void actionPerformed(java.awt.event.ActionEvent JavaDoc evt) {
107             Object JavaDoc src = evt.getSource();
108
109             if (!handleOpenRecent(src)) {
110                 if (src == openItem) {
111                     fileChooser.setMultiSelectionEnabled(true);
112                     int returnVal = fileChooser.showOpenDialog(Editor.this);
113                     if (returnVal == JFileChooser.APPROVE_OPTION) {
114                         File[] files = fileChooser.getSelectedFiles();
115                         for (int i = 0; i < files.length; i++) openFile(files[i], i == 0);
116                     }
117                     fileChooser.setMultiSelectionEnabled(false);
118                 } else if (src == closeItem) {
119                     Component JavaDoc editor = tabPane.getSelectedComponent();
120                     if (checkClose(editor)) {
121                         doCloseEditor(editor);
122                     }
123                 } else if (src == saveItem) {
124                     saveFile(tabPane.getSelectedComponent());
125                 } else if (src == saveAsItem) {
126                     saveAs(tabPane.getSelectedComponent());
127                 } else if (src == saveAllItem) {
128                     int index = tabPane.getSelectedIndex();
129                     for (int i = 0; i < tabPane.getComponentCount(); i++) {
130                         saveFile(tabPane.getComponentAt(i));
131                     }
132                     tabPane.setSelectedIndex(index);
133                 } else if (src == exitItem) {
134                     doExit();
135                 } else if (src instanceof JMenuItem) {
136                     Object JavaDoc ki = ((JMenuItem) src).getClientProperty("kitInfo"); // NOI18N
137

138                     if (ki instanceof KitInfo) {
139                         createNewFile((KitInfo) ki);
140                     }
141                 }
142             }
143         }
144     }
145     
146     public Editor() {
147         super( "NetBeans Editor" ); // NOI18N
148
LocaleSupport.addLocalizer(impl);
149
150         // Feed our kits with their default Settings
151
Settings.addInitializer(new BaseSettingsInitializer(), Settings.CORE_LEVEL);
152         Settings.addInitializer(new ExtSettingsInitializer(), Settings.CORE_LEVEL);
153         Settings.reset();
154         
155         // Create visual hierarchy
156
initComponents ();
157         openItem.addActionListener(impl);
158         closeItem.addActionListener(impl);
159         saveItem.addActionListener(impl);
160         saveAsItem.addActionListener(impl);
161         saveAllItem.addActionListener(impl);
162         exitItem.addActionListener(impl);
163         addWindowListener(impl);
164         
165         // Prepare the editor kits and such things
166
readSettings();
167                 
168         // Do the actual layout
169
setLocation( 150, 150 );
170         pack ();
171
172         fileToMenu = new HashMap();
173         menuToFile = new HashMap();
174         recentFiles = new Vector();
175         maxRecent = 4;
176
177         createBackups = false;
178         safeSave = true;
179     }
180     
181     public Dimension JavaDoc getPreferredSize() {
182         Dimension JavaDoc size = new Dimension JavaDoc( 640,480 );
183         return size;
184     }
185     
186     /** This method is called from within the constructor to
187      * initialize the form.
188      * WARNING: Do NOT modify this code. The content of this method is
189      * always regenerated by the Form Editor.
190      */

191     private void initComponents() {//GEN-BEGIN:initComponents
192
tabPane = new javax.swing.JTabbedPane JavaDoc();
193         menuBar = new javax.swing.JMenuBar JavaDoc();
194         fileMenu = new javax.swing.JMenu JavaDoc();
195         newMenu = new javax.swing.JMenu JavaDoc();
196         openItem = new javax.swing.JMenuItem JavaDoc();
197         closeItem = new javax.swing.JMenuItem JavaDoc();
198         sep1 = new javax.swing.JSeparator JavaDoc();
199         saveItem = new javax.swing.JMenuItem JavaDoc();
200         saveAsItem = new javax.swing.JMenuItem JavaDoc();
201         saveAllItem = new javax.swing.JMenuItem JavaDoc();
202         sep2 = new javax.swing.JSeparator JavaDoc();
203         exitItem = new javax.swing.JMenuItem JavaDoc();
204
205         getContentPane().setLayout(new java.awt.GridLayout JavaDoc(1, 1));
206
207         setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
208         getContentPane().add(tabPane);
209
210         fileMenu.setMnemonic(KeyEvent.VK_F);
211         fileMenu.setText("File"); // NOI18N
212
newMenu.setMnemonic(KeyEvent.VK_N);
213         newMenu.setText("New..."); // NOI18N
214
fileMenu.add(newMenu);
215         openItem.setMnemonic(KeyEvent.VK_O);
216         openItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
217         openItem.setText("Open File..."); // NOI18N
218
fileMenu.add(openItem);
219         closeItem.setMnemonic(KeyEvent.VK_C);
220         closeItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.CTRL_MASK));
221         closeItem.setText("Close"); // NOI18N
222
fileMenu.add(closeItem);
223         fileMenu.add(sep1);
224         saveItem.setMnemonic(KeyEvent.VK_S);
225         saveItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
226         saveItem.setText("Save"); // NOI18N
227
fileMenu.add(saveItem);
228         saveAsItem.setMnemonic(KeyEvent.VK_A);
229         saveAsItem.setText("Save As..."); // NOI18N
230
fileMenu.add(saveAsItem);
231         saveAllItem.setMnemonic(KeyEvent.VK_L);
232         saveAllItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.CTRL_MASK));
233         saveAllItem.setText("Save All"); // NOI18N
234
fileMenu.add(saveAllItem);
235         fileMenu.add(sep2);
236         exitItem.setMnemonic(KeyEvent.VK_E);
237         exitItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
238         exitItem.setText("Exit"); // NOI18N
239
fileMenu.add(exitItem);
240         menuBar.add(fileMenu);
241         setJMenuBar(menuBar);
242
243     }//GEN-END:initComponents
244

245     private boolean saveFile( Component JavaDoc comp, File file, boolean checkOverwrite ) {
246         if( comp == null ) return false;
247         tabPane.setSelectedComponent( comp );
248         JTextComponent JavaDoc edit = (JTextComponent JavaDoc)com2text.get( comp );
249         Document JavaDoc doc = edit.getDocument();
250         
251         if( checkOverwrite && file.exists() ) {
252             tabPane.setSelectedComponent( comp );
253             int choice = JOptionPane.showOptionDialog(this,
254             "File " + file.getName() + " already exists, overwrite?", // NOI18N
255
"File exists", // NOI18N
256
JOptionPane.YES_NO_CANCEL_OPTION,
257             JOptionPane.QUESTION_MESSAGE,
258             null, // don't use a custom Icon
259
null, // use standard button titles
260
null // no default selection
261
);
262             if( choice != 0 ) return false;
263         }
264
265         File safeSaveFile = new File(file.getAbsolutePath() + "~~"); // NOI18N
266
File backupFile = new File(file.getAbsolutePath() + "~"); // NOI18N
267

268         if (safeSave || createBackups) {
269             file.renameTo(safeSaveFile);
270         }
271
272         FileWriter output = null;
273
274         try {
275             output = new FileWriter( file );
276             edit.write( output );
277
278             if (createBackups) {
279                 safeSaveFile.renameTo(backupFile);
280             } else {
281                 if (safeSave) {
282                     safeSaveFile.delete();
283                 }
284             }
285         } catch( IOException exc ) {
286             JOptionPane.showMessageDialog( this, "Can't write to file '" + // NOI18N
287
file.getName() + "'.", "Error", JOptionPane.ERROR_MESSAGE ); // NOI18N
288

289             if (safeSave)
290                 safeSaveFile.renameTo(file);
291
292             return false;
293         } finally {
294             if (output != null) {
295                 try {
296                     output.close();
297                 } catch (IOException e) {
298                     e.printStackTrace(System.err);
299                 }
300             }
301         }
302
303         doc.putProperty( MODIFIED, Boolean.FALSE );
304         doc.putProperty( CREATED, Boolean.FALSE );
305         doc.putProperty( FILE, file );
306         doc.addDocumentListener( new MarkingDocumentListener( comp ) );
307         
308         int index = tabPane.indexOfComponent( comp );
309         tabPane.setTitleAt( index, file.getName() );
310         
311         return true;
312     }
313     
314     private boolean saveFile( Component JavaDoc comp ) {
315         if( comp == null ) return false;
316         JTextComponent JavaDoc edit = (JTextComponent JavaDoc)com2text.get( comp );
317         Document JavaDoc doc = edit.getDocument();
318         File file = (File)doc.getProperty( FILE );
319         boolean created = ((Boolean JavaDoc)doc.getProperty( CREATED )).booleanValue();
320         
321         return saveFile( comp, file, created );
322     }
323     
324     private boolean saveAs( Component JavaDoc comp ) {
325         if( comp == null ) return false;
326         JTextComponent JavaDoc edit = (JTextComponent JavaDoc)com2text.get( comp );
327         File file = (File)edit.getDocument().getProperty( FILE );
328         
329         fileChooser.setCurrentDirectory( file.getParentFile() );
330         fileChooser.setSelectedFile( file );
331         KitInfo fileInfo = KitInfo.getKitInfoOrDefault( file );
332         
333         if( fileInfo != null ) fileChooser.setFileFilter( fileInfo );
334         
335         // show the dialog, test the result
336
if( fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
337             return saveFile( comp, fileChooser.getSelectedFile(), true );
338         else
339             return false; // Cancel was pressed - not saved
340
}
341
342     private void openFile( File file, boolean focus ) {
343         KitInfo info = KitInfo.getKitInfoOrDefault( file );
344         
345         final JEditorPane pane = new JEditorPane( info.getType(), "" );
346         try {
347             pane.read( new FileInputStream( file ), file.getCanonicalPath() );
348         } catch( IOException exc ) {
349             JOptionPane.showMessageDialog( this, "Can't read from file '" + // NOI18N
350
file.getName() + "'.", "Error", JOptionPane.ERROR_MESSAGE ); // NOI18N
351
return;
352         }
353         addEditorPane( pane, info.getIcon(), file, false, focus );
354
355         removeFromRecent(file.getAbsolutePath());
356     }
357
358     private void doExit() {
359         boolean exit = true;
360         int components = tabPane.getComponentCount();
361
362         for (int cntr = 0; cntr < components; cntr++) {
363             Component JavaDoc editor = tabPane.getComponentAt( cntr );
364
365             if( ! checkClose( editor ) ) {
366                 exit = false;
367                 return;
368             }
369         }
370
371         if (!exit) {
372             System.err.println("keeping");
373             return;
374         }
375
376         writeUserConfiguration();
377
378         while( tabPane.getComponentCount() > 0 ) {
379             Component JavaDoc editor = tabPane.getComponentAt( 0 );
380
381             if ((editor != null) && (com2text.get(editor) != null))
382                 doCloseEditor(editor);
383         }
384
385         if( exit ) System.exit (0);
386     }
387
388     private void doCloseEditor(Component JavaDoc editor) {
389         JTextComponent JavaDoc editorPane = (JTextComponent JavaDoc ) com2text.get(editor);
390         if (editorPane != null) {
391             File file = (File) editorPane.getDocument().getProperty(FILE);
392
393             addToRecent(file.getAbsolutePath());
394         }
395
396         tabPane.remove( editor );
397         com2text.remove( editor );
398     }
399
400     private boolean checkClose( Component JavaDoc comp ) {
401         if( comp == null ) return false;
402         JTextComponent JavaDoc edit = (JTextComponent JavaDoc)com2text.get( comp );
403         Document JavaDoc doc = edit.getDocument();
404         
405         Object JavaDoc mod = doc.getProperty( MODIFIED );
406         if( mod == null || ! ((Boolean JavaDoc)mod).booleanValue()) return true;
407         
408         tabPane.setSelectedComponent( comp );
409         File file = (File)doc.getProperty( FILE );
410         
411         for( ;; ) {
412             int choice = JOptionPane.showOptionDialog(this,
413             "File " + file.getName() + " was modified, save it?", // NOI18N
414
"File modified", // NOI18N
415
JOptionPane.YES_NO_CANCEL_OPTION,
416             JOptionPane.QUESTION_MESSAGE,
417             null, // don't use a custom Icon
418
new String JavaDoc[] { "Save", "Save As...", "Discard", "Cancel" }, // use standard button titles // NOI18N
419
"Cancel" //default selection // NOI18N
420
);
421             
422             switch( choice ) {
423                 case JOptionPane.CLOSED_OPTION:
424                 case 4:
425                     return false; // Cancel or Esc pressed
426
case 1:
427                     if( !saveAs( comp ) ) continue; // Ask for fileName, then save
428
return true;
429                 case 0:
430                     if( !saveFile( comp ) ) continue; // else fall through
431
case 2:
432                     return true; // Discard changes, close window
433
}
434             return false;
435         }
436     }
437     
438     private void addEditorPane( JEditorPane pane, Icon icon, File file, boolean created, boolean focus ) {
439         final JComponent c = (pane.getUI() instanceof BaseTextUI) ?
440         Utilities.getEditorUI(pane).getExtComponent() : new JScrollPane( pane );
441         Document JavaDoc doc = pane.getDocument();
442         
443         doc.addDocumentListener( new MarkingDocumentListener( c ) );
444         doc.putProperty( FILE, file );
445         doc.putProperty( CREATED, created ? Boolean.TRUE : Boolean.FALSE );
446         
447         UndoManager JavaDoc um = new UndoManager JavaDoc();
448         doc.addUndoableEditListener( um );
449         doc.putProperty( BaseDocument.UNDO_MANAGER_PROP, um );
450         
451         com2text.put( c, pane );
452         tabPane.addTab( file.getName(), icon, c, file.getAbsolutePath() );
453         if (focus) {
454             tabPane.setSelectedComponent( c );
455             pane.requestFocus();
456         }
457     }
458     
459     
460     private void createNewFile( KitInfo info ) {
461         final String JavaDoc fileName = ((++fileCounter == 0 ) ?
462             "unnamed" : // NOI18N
463
("unnamed" + fileCounter)) + info.getDefaultExtension(); // NOI18N
464
final File file = new File( fileName ).getAbsoluteFile();
465
466         final JEditorPane pane = new JEditorPane( info.getType(), "" );
467         URL JavaDoc template = info.getTemplate();
468         if( template != null ) {
469             try {
470                 pane.read( template.openStream(), file.getCanonicalPath() );
471             } catch( IOException e ) {
472                 JOptionPane.showMessageDialog( this, "Can't read template", "Error", JOptionPane.ERROR_MESSAGE ); // NOI18N
473
}
474         }
475         addEditorPane( pane, info.getIcon(), file, true, true );
476     }
477     
478     
479     
480     public static File getDistributionDirectory() {
481        return distributionDirectory;
482     }
483     
484     /**
485      * @param args the command line arguments
486      */

487     public static void main (String JavaDoc args[]) {
488         if (!getDistributionDirectory().canRead()) {
489             System.err.println("Fatal error while startup - can read from distribution directory.");
490             System.exit(0);
491         }
492       
493         Editor editor = new Editor ();
494
495         editor.show ();
496
497         editor.readUserConfiguration();
498
499         for( int i = 0; i < args.length; i++ ) {
500             String JavaDoc fileName = args[i];
501             editor.openFile( new File( fileName ), i == 0 );
502         }
503     }
504     
505     private Map fileToMenu;
506     private Map menuToFile;
507     private Vector recentFiles;
508     private int maxRecent;
509     private JSeparator recentSeparator;
510     private int separatorIndex;
511     
512     private String JavaDoc[] getOpenedFiles() {
513         ArrayList JavaDoc opened = new ArrayList JavaDoc();
514
515         int components = tabPane.getComponentCount();
516
517         for (int cntr = 0; cntr < components; cntr++) {
518             Component JavaDoc editorComponent = tabPane.getComponentAt( cntr );
519
520             JTextComponent JavaDoc editor = (JTextComponent JavaDoc) com2text.get(editorComponent);
521         
522         if (editor == null) {
523             continue;
524         }
525         
526             Document JavaDoc doc = editor.getDocument();
527             File file = (File) doc.getProperty(FILE);
528             
529             if (file != null) {
530                 opened.add(file.getAbsolutePath());
531             }
532         }
533     
534         return (String JavaDoc []) opened.toArray(new String JavaDoc[opened.size()]);
535     }
536     
537     private int findInRecent(String JavaDoc fileToFind) {
538         for (int cntr = 0; cntr < recentFiles.size(); cntr++) {
539             String JavaDoc file = (String JavaDoc) recentFiles.get(cntr);
540             
541             if (fileToFind.equals(file))
542                 return cntr;
543         }
544         
545         return -1;
546     }
547
548     private boolean handleOpenRecent(Object JavaDoc source) {
549         String JavaDoc fileName = (String JavaDoc) menuToFile.get(source);
550
551         if (fileName == null)
552             return false;
553
554         openFile(new File(fileName), true);
555
556         return true;
557     }
558
559     private String JavaDoc generateMenuItemName(int index, String JavaDoc file) {
560         return "" + index + ". " + file; // NOI18N
561
}
562
563     private void addToRecent(String JavaDoc fileToAdd) {
564         //Remove possible previous occurence:
565
removeFromRecent(fileToAdd);
566         
567         if (recentFiles.size() >= maxRecent) {
568             while (recentFiles.size() >= maxRecent) {
569                 removeFromRecent(recentFiles.size() - 1);
570             }
571         }
572         
573         recentFiles.add(0, fileToAdd);
574         
575         JMenuItem newItem = new JMenuItem(generateMenuItemName(1, fileToAdd));
576     
577     if (recentFiles.size() == 1) {
578         recentSeparator = new JSeparator();
579         fileMenu.add(recentSeparator);
580         separatorIndex = fileMenu.getMenuComponentCount();
581     }
582
583         newItem.addActionListener(impl);
584
585         fileMenu.insert(newItem, separatorIndex);
586         fileToMenu.put(fileToAdd, newItem);
587         menuToFile.put(newItem, fileToAdd);
588     
589     correctItemNumbers();
590     }
591
592     private void correctItemNumbers() {
593         for (int cntr = 0; cntr < recentFiles.size(); cntr++) {
594             JMenuItem item = (JMenuItem ) fileToMenu.get(recentFiles.get(cntr));
595
596             item.setText(generateMenuItemName(cntr + 1, (String JavaDoc) recentFiles.get(cntr)));
597         }
598     }
599
600     private void removeFromRecent(String JavaDoc fileToRemove) {
601         int position = findInRecent(fileToRemove);
602         
603         if (position != (-1))
604             removeFromRecent(position);
605     }
606
607     private void removeFromRecent(int indexToRemove) {
608         String JavaDoc file = (String JavaDoc) recentFiles.get(indexToRemove);
609         
610         recentFiles.remove(indexToRemove);
611         
612         JMenuItem fileItem = (JMenuItem) fileToMenu.get(file);
613         
614         fileMenu.remove(fileItem);
615
616         fileToMenu.remove(file);
617         menuToFile.remove(fileItem);
618
619         correctItemNumbers();
620
621     if (recentFiles.size() == 0) {
622         fileMenu.remove(recentSeparator);
623         recentSeparator = null;
624         separatorIndex = -1;
625     }
626     }
627     
628     private String JavaDoc[] readStrings(ResourceBundle bundle, String JavaDoc prefix) {
629         int count = 0;
630         boolean finish = false;
631         ArrayList JavaDoc result = new ArrayList JavaDoc();
632         
633         while (!finish) {
634             try {
635                 String JavaDoc current = bundle.getString(prefix + "_" + count);
636                 
637                 result.add(current);
638                 count++;
639             } catch (MissingResourceException e) {
640                 finish = true;
641             }
642         }
643         
644         return (String JavaDoc []) result.toArray(new String JavaDoc[result.size()]);
645     }
646     
647     private void readUserConfiguration(ResourceBundle bundle) {
648         String JavaDoc[] openedFiles = readStrings(bundle, "Open-File"); // NOI18N
649
String JavaDoc[] recentFiles = readStrings(bundle, "Recent-File"); // NOI18N
650
String JavaDoc recentFilesMaxCount = bundle.getString("Max-Recent-Files");
651         String JavaDoc safeSaveString = bundle.getString("Safe-Save");
652         String JavaDoc createBackupsString = bundle.getString("Create-Backups");
653
654         this.maxRecent = Integer.parseInt(recentFilesMaxCount);
655         this.safeSave = Boolean.valueOf(safeSaveString).booleanValue();
656         this.createBackups = Boolean.valueOf(createBackupsString).booleanValue();
657
658         for (int cntr = recentFiles.length; cntr > 0; cntr--) {
659             addToRecent(recentFiles[cntr - 1]);
660         }
661
662         for (int cntr = 0; cntr < openedFiles.length; cntr++) {
663             openFile(new File(openedFiles[cntr]), false);
664         }
665     }
666
667     private void writeUserConfiguration(PrintWriter output) {
668         output.println("Max-Recent-Files=" + maxRecent); // NOI18N
669
output.println("Safe-Save=" + safeSave); // NOI18N
670
output.println("Create-Backups=" + createBackups); // NOI18N
671

672         for (int cntr = 0; cntr < recentFiles.size(); cntr++) {
673             output.println("Recent-File_" + cntr + "=" + recentFiles.get(cntr)); // NOI18N
674
}
675         String JavaDoc[] openFiles = getOpenedFiles();
676
677         for (int cntr = 0; cntr < openFiles.length; cntr++) {
678             output.println("Open-File_" + cntr + "=" + openFiles[cntr]); // NOI18N
679
}
680     }
681
682     private File getConfigurationFileName() {
683         File homedir = new File( System.getProperty( "user.home" ) ).getAbsoluteFile();
684         File configurationFile = new File(homedir, ".nb-editor"); // NOI18N
685

686         return configurationFile;
687     }
688
689     private void writeUserConfiguration() {
690         File configurationFile = getConfigurationFileName();
691         File configurationFileBackup = new File(configurationFile.getAbsolutePath() + "~"); // NOI18N
692
boolean backup = false;
693
694         if (configurationFile.exists()) {
695             backup = true;
696             configurationFile.renameTo(configurationFileBackup);
697         }
698
699         PrintWriter output = null;
700         try {
701             output = new PrintWriter(new FileWriter(configurationFile));
702
703             writeUserConfiguration(output);
704
705             if (backup) {
706                 if (!output.checkError()) {
707                     configurationFileBackup.delete();
708                 } else {
709                     //Put back to original configuration:
710
configurationFileBackup.renameTo(configurationFile);
711                 }
712             }
713         } catch (IOException e) {
714             e.printStackTrace();
715         } finally {
716             if (output != null) {
717                 output.close();
718             }
719         }
720     }
721
722     private void readUserConfiguration() {
723         File configurationFileName = getConfigurationFileName();
724         InputStream in = null;
725         try {
726             in = new FileInputStream(configurationFileName);
727             readUserConfiguration(new PropertyResourceBundle(in));
728         } catch (FileNotFoundException e) {
729             //The file containing user-defined configuration not found.
730
//This is nothing really important.
731
try {
732                 System.err.println("User configuration not found in \"" + configurationFileName.getCanonicalPath() + "\".");
733             } catch (IOException f) {
734             }
735         } catch (IOException e) {
736             e.printStackTrace();
737         } finally {
738             if (in != null) {
739                 try {
740                     in.close();
741                 } catch (IOException e) {
742                     e.printStackTrace();
743                 }
744             }
745         }
746
747     }
748
749     // Variables declaration - do not modify//GEN-BEGIN:variables
750
private javax.swing.JSeparator JavaDoc sep2;
751     private javax.swing.JSeparator JavaDoc sep1;
752     private javax.swing.JMenu JavaDoc newMenu;
753     private javax.swing.JMenuItem JavaDoc saveAllItem;
754     private javax.swing.JMenuItem JavaDoc closeItem;
755     private javax.swing.JMenuBar JavaDoc menuBar;
756     private javax.swing.JMenuItem JavaDoc exitItem;
757     private javax.swing.JTabbedPane JavaDoc tabPane;
758     private javax.swing.JMenuItem JavaDoc saveAsItem;
759     private javax.swing.JMenu JavaDoc fileMenu;
760     private javax.swing.JMenuItem JavaDoc openItem;
761     private javax.swing.JMenuItem JavaDoc saveItem;
762     // End of variables declaration//GEN-END:variables
763

764     
765     private void readSettings() throws MissingResourceException {
766         File currentPath = new File( System.getProperty( "user.dir" ) ).getAbsoluteFile();
767         fileChooser = new JFileChooser( currentPath );
768         
769         fileChooser.setFileView(impl);
770         
771         String JavaDoc kits = settings.getString( "InstalledEditors" );
772         String JavaDoc defaultKit = settings.getString( "DefaultEditor" );
773         
774         StringTokenizer st = new StringTokenizer( kits, "," ); // NOI18N
775
while( st.hasMoreTokens() ) {
776             String JavaDoc kitName = st.nextToken();
777             // At the first, we have to read ALL info about kit
778
String JavaDoc contentType = settings.getString( kitName + "_ContentType" );
779             String JavaDoc extList = settings.getString( kitName + "_ExtensionList" );
780             String JavaDoc menuTitle = settings.getString( kitName + "_NewMenuTitle" );
781             char menuMnemonic = settings.getString( kitName + "_NewMenuMnemonic" ).charAt( 0 );
782             String JavaDoc templateURL = settings.getString( kitName + "_Template" );
783             String JavaDoc iconName = settings.getString( kitName + "_Icon" );
784             String JavaDoc filterTitle = settings.getString( kitName + "_FileFilterTitle" );
785             String JavaDoc kit = settings.getString( kitName + "_KitClass" );
786
787             // At the second, we surely need an instance of kitClass
788
Class JavaDoc kitClass;
789             try {
790                 kitClass = Class.forName( kit );
791             } catch( ClassNotFoundException JavaDoc exc ) { // we really need it
792
throw new MissingResourceException( "Missing class", kit, "KitClass" ); // NOI18N
793
}
794
795             // At the third, it is nice to have icon although we could live without one
796
Icon icon = null;
797             ClassLoader JavaDoc loader = kitClass.getClassLoader();
798             if( loader == null ) loader = ClassLoader.getSystemClassLoader();
799             URL JavaDoc resource = loader.getResource( iconName );
800             if( resource == null ) resource = ClassLoader.getSystemResource( iconName );
801             if( resource != null ) icon = new ImageIcon( resource );
802
803             // At the fourth, try to get URL for template
804
URL JavaDoc template = loader.getResource( templateURL );
805             if( resource == null ) template = ClassLoader.getSystemResource( templateURL );
806
807             // Finally, convert the list of extensions to, ehm, List :-)
808
List JavaDoc l = new ArrayList JavaDoc( 5 );
809             StringTokenizer extST = new StringTokenizer( extList, "," ); // NOI18N
810
while( extST.hasMoreTokens() ) l.add( extST.nextToken() );
811             
812             // Actually create the KitInfo from provided informations
813
KitInfo ki = new KitInfo( contentType, l, template, icon, filterTitle, kitClass, loader, defaultKit.equals( kitName ) );
814
815             // Make the MenuItem for it
816
JMenuItem item = new JMenuItem( menuTitle, icon );
817             item.setMnemonic( menuMnemonic );
818             item.putClientProperty( "kitInfo", ki ); // NOI18N
819
item.addActionListener( impl );
820         newMenu.add( item );
821
822             // Register a FileFilter for given type of file
823
fileChooser.addChoosableFileFilter( ki );
824         }
825         
826         // Finally, add fileFilter that would recognize files of all kits
827

828         fileChooser.addChoosableFileFilter( new FileFilter JavaDoc() {
829             public String JavaDoc getDescription() {
830                 return "All recognized files"; // NOI18N
831
}
832         
833             public boolean accept( File f ) {
834                 return f.isDirectory() || KitInfo.getKitInfoForFile( f ) != null;
835             }
836         });
837         
838         if( KitInfo.getDefault() == null ) throw new MissingResourceException( "Missing default kit definition", defaultKit, "DefaultEditor" ); // NOI18N
839
}
840             
841     private static final class KitInfo extends FileFilter JavaDoc{
842         
843         private static List JavaDoc kits = new ArrayList JavaDoc();
844         private static KitInfo defaultKitInfo;
845         
846         public static List JavaDoc getKitList() {
847             return new ArrayList JavaDoc( kits );
848         }
849         
850         public static KitInfo getDefault() {
851             return defaultKitInfo;
852         }
853         
854         public static KitInfo getKitInfoOrDefault( File f ) {
855             KitInfo ki = getKitInfoForFile( f );
856             return ki == null ? defaultKitInfo : ki;
857         }
858         
859         public static KitInfo getKitInfoForFile( File f ) {
860             for( int i = 0; i < kits.size(); i++ ) {
861                 if( ((KitInfo)kits.get(i)).accept( f ) )
862                     return (KitInfo)kits.get(i);
863             }
864             return null;
865         }
866
867         private String JavaDoc type;
868         private String JavaDoc[] extensions;
869         private URL JavaDoc template;
870         private Icon icon;
871         private Class JavaDoc kitClass;
872         private String JavaDoc description;
873         
874         public KitInfo( String JavaDoc type, List JavaDoc exts, URL JavaDoc template, Icon icon, String JavaDoc description, Class JavaDoc kitClass, ClassLoader JavaDoc loader, boolean isDefault ) {
875             // Fill in the structure
876
this.type = type;
877             this.extensions = (String JavaDoc[])exts.toArray( new String JavaDoc[0] );
878             this.template = template;
879             this.icon = icon;
880             this.description = description;
881             this.kitClass = kitClass;
882             
883             // Register us
884
JEditorPane.registerEditorKitForContentType( type, kitClass.getName(), loader );
885             kits.add( this );
886             if( isDefault ) defaultKitInfo = this;
887         }
888         
889
890         
891         public String JavaDoc getType() {
892             return type;
893         }
894         
895         public String JavaDoc getDefaultExtension() {
896             return extensions[0];
897         }
898
899         public URL JavaDoc getTemplate() {
900             return template;
901         }
902         
903         public Icon getIcon() {
904             return icon;
905         }
906
907         public Class JavaDoc getKitClass() {
908             return kitClass;
909         }
910                         
911         public String JavaDoc getDescription() {
912             return description;
913         }
914         
915         public boolean accept( File f ) {
916             if( f.isDirectory() ) return true;
917             String JavaDoc fileName = f.getName();
918             for( int i=0; i<extensions.length; i++ ) {
919                 if( fileName.endsWith( extensions[i] ) ) return true;
920             }
921             return false;
922         }
923     }
924     
925     /** Listener listening for document changes on opened documents. There is
926      * initially one instance per opened document, but this listener is
927      * one-fire only - as soon as it gets fired, markes changes and removes
928      * itself from document. On save, new Listener is hooked again.
929      */

930     private class MarkingDocumentListener implements DocumentListener JavaDoc {
931         private Component JavaDoc comp;
932         
933         public MarkingDocumentListener( Component JavaDoc comp ) {
934             this.comp = comp;
935         }
936         
937         private void markChanged( DocumentEvent JavaDoc evt ) {
938             Document JavaDoc doc = evt.getDocument();
939             doc.putProperty( MODIFIED, Boolean.TRUE );
940             
941             File file = (File)doc.getProperty( FILE );
942             int index = tabPane.indexOfComponent( comp );
943             
944             tabPane.setTitleAt( index, file.getName() + '*' );
945             
946             doc.removeDocumentListener( this );
947         }
948         
949         public void changedUpdate( DocumentEvent JavaDoc e ) {
950         }
951         
952         public void insertUpdate( DocumentEvent JavaDoc evt ) {
953             markChanged( evt );
954         }
955         
956         public void removeUpdate( DocumentEvent JavaDoc evt ) {
957             markChanged( evt );
958         }
959     }
960 }
961
Popular Tags