1   package main;
2   
3   import intellego.Intellego;
4   import util.*;
5   import interfaces.*;
6   import real.*;
7   
8   import java.awt.*;
9   import java.lang.*;
10  import java.awt.event.*;
11  import javax.swing.*;
12  import java.io.*;
13  import java.net.*;
14  
15  /**
16  * Provides a simple textual code editor
17  *
18  * @author Graham Ritchie
19  */
20  public class CodeEditor extends JInternalFrame 
21  {
22      static final int xOffset = 30, yOffset = 30;
23      static int openFrameCount = 0;
24      
25      // the current file
26      private File currentFile;
27      
28      //the current file's local name
29      private String currentFileName;
30      
31      // the current file's directory
32      private File currentDir;
33      
34      // the main code display pane
35      private JEditorPane codePane;
36  
37      public CodeEditor() 
38      {
39          super("Code Editor: (no file)",true,true,true,true);
40          ++openFrameCount;
41          
42          // create the code editor GUI and put it in the window...
43          
44          // add the menu bar
45          setJMenuBar(createMenuBar());
46          
47          // create and add the editor pane
48          codePane=new JEditorPane();
49          codePane.setVisible(true);
50          codePane.setEditable(true);
51          
52          // put it in a scroll pane
53          JScrollPane codeScrollPane = new JScrollPane(codePane);
54          codeScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
55          codeScrollPane.setPreferredSize(new Dimension(400,600));
56          codeScrollPane.setMinimumSize(new Dimension(10, 10));
57          
58          // and add this to a main content pane
59          JPanel contentPane = new JPanel();
60          BoxLayout box = new BoxLayout(contentPane, BoxLayout.X_AXIS);
61          contentPane.setLayout(box);
62          contentPane.add(codeScrollPane);
63          setContentPane(contentPane);
64          
65          // set the window size
66          setSize(400,600);
67  
68          // and set the window's location.
69          setLocation(xOffset*openFrameCount, yOffset*openFrameCount);
70      }
71      
72      private JMenuBar createMenuBar()
73      {
74          JMenuBar menuBar = new JMenuBar();
75          
76          // create the file menu
77          JMenu fileMenu = new JMenu("File");
78          
79          // create the file menu items
80          JMenuItem newFile = new JMenuItem("New");
81          JMenuItem open = new JMenuItem("Open");
82          JMenuItem save=new JMenuItem("Save");
83          JMenuItem saveAs=new JMenuItem("Save As");
84          JMenuItem close = new JMenuItem("Close");
85          
86          // create the action listeners
87          newFile.addActionListener(new ActionListener() 
88          {
89              public void actionPerformed(ActionEvent e) 
90              {
91                  createNewFile();
92              }
93          });
94          
95          open.addActionListener(new ActionListener() 
96          {
97              public void actionPerformed(ActionEvent e) 
98              {
99                  openFile();
100             }
101         });
102         
103         save.addActionListener(new ActionListener() 
104         {
105             public void actionPerformed(ActionEvent e) 
106             {
107                 saveFile();
108             }
109         });
110         
111         saveAs.addActionListener(new ActionListener() 
112         {
113             public void actionPerformed(ActionEvent e) 
114             {
115                 saveFileAs();
116             }
117         });
118         
119         close.addActionListener(new ActionListener() 
120         {
121             public void actionPerformed(ActionEvent e) 
122             {
123                 closeFile();
124             }
125         });
126         
127         // add the menu items to the menu
128         fileMenu.add(newFile);
129         fileMenu.add(open);
130         fileMenu.add(save);
131         fileMenu.add(saveAs);
132         fileMenu.add(close);
133         
134         // create the lejos menu
135         JMenu lejosMenu = new JMenu("leJOS");
136         
137         // create the lejos menu items
138         JMenuItem compile = new JMenuItem("Compile");
139         JMenuItem download = new JMenuItem("Link & Download");
140         
141         // create the action listeners
142         
143         compile.addActionListener(new ActionListener() 
144         {
145             public void actionPerformed(ActionEvent e) 
146             {
147                 lejosCompileFile();
148             }
149         });
150         
151         download.addActionListener(new ActionListener() 
152         {
153             public void actionPerformed(ActionEvent e) 
154             {
155                 downloadFile();
156             }
157         });
158         
159         // add the menu items to the menu
160         lejosMenu.add(compile);
161         lejosMenu.add(download);
162         
163         // create the sim menu
164         JMenu simMenu = new JMenu("Simulator");
165         
166         // create the lejos menu items
167         JMenuItem javaCompile = new JMenuItem("Compile");
168         JMenuItem openInSim = new JMenuItem("Open controller in simulator");
169         
170         // create the action listeners
171         
172         openInSim.addActionListener(new ActionListener() 
173         {
174             public void actionPerformed(ActionEvent e) 
175             {
176                 openFileInSim();
177             }
178         });
179         
180         javaCompile.addActionListener(new ActionListener() 
181         {
182             public void actionPerformed(ActionEvent e) 
183             {
184                 javaCompileFile();
185             }
186         });
187         
188         // add the menu items to the menu
189         simMenu.add(javaCompile);
190         simMenu.add(openInSim);
191         
192         // add the menus to the menu bar
193         menuBar.add(fileMenu);
194         menuBar.add(lejosMenu);
195         menuBar.add(simMenu);
196         
197         // return the final menu bar
198         return menuBar;
199     }
200     
201     /**
202     * Creates a new editor pane
203     */
204     public void createNewFile()
205     {
206         MainInterface.createCodeEditorFrame();
207     }
208     
209     /**
210     * Opens a file
211     */
212     private void openFile()
213     {
214         JFileChooser chooser=new JFileChooser(new File(System.getProperties().getProperty("user.dir"),"controllers"));
215         
216         // add a filename filter for java files
217         String[] extensions={".java"};
218         chooser.addChoosableFileFilter(new FileChooserFilter(extensions,"Java Controller Files"));
219         
220         chooser.showOpenDialog(this);
221         
222         File file=chooser.getSelectedFile();
223         
224         try // to open the file
225         {
226             URL filePath=chooser.getSelectedFile().toURL();
227             
228             // set this file as the page in the codePane
229             codePane.setPage(filePath);
230             
231             // set file as current file
232             currentFile=file;
233             
234             // set current directory
235             currentDir=chooser.getCurrentDirectory();
236             
237             // and change the title
238             super.setTitle("Code Editor:  "+file.toString());
239         }
240         catch (Exception e)
241         {
242             MainInterface.displayMessage("Cannot open file");
243             Intellego.addToLog("CodeEditor.openFile(): Failed to open file: "+e);
244         }
245     }
246     
247     /**
248     * Saves the current file
249     */
250     private void saveFile()
251     {
252         if (currentFile!=null)
253         {
254             // save file
255             try
256             {
257                 FileWriter fw=new FileWriter(currentFile);
258                 
259                 fw.write(codePane.getText());
260                 
261                 fw.close();
262             }
263             catch (Exception e)
264             {
265                 MainInterface.displayMessage("Cannot save file");
266                 Intellego.addToLog("CodeEditor.saveFile(): Save to file failed: "+e);
267             }
268         }
269         else
270         {
271             // no current file, so it must be new, so save as
272             saveFileAs();
273         }
274     }
275     
276     private void saveFileAs()
277     {
278         JFileChooser chooser=new JFileChooser();
279         
280         int returnValue=chooser.showSaveDialog(this);
281         
282         if (returnValue==JFileChooser.APPROVE_OPTION && currentFile!=null)
283         {
284             // save file
285             try
286             {
287                 FileWriter fw=new FileWriter(currentFile);
288                 
289                 fw.write(codePane.getText());
290                 
291                 fw.close();
292             }
293             catch (Exception e)
294             {
295                 MainInterface.displayMessage("Cannot save file");
296                 Intellego.addToLog("CodeEditor.saveFile(): Save to file failed: "+e);
297             }
298         }
299         else if(returnValue==JFileChooser.APPROVE_OPTION && currentFile==null)
300         {
301             // save file
302             try
303             {
304                 FileWriter fw=new FileWriter("filename.java");
305                 
306                 fw.write(codePane.getText());
307                 
308                 fw.close();
309             }
310             catch (Exception e)
311             {
312                 MainInterface.displayMessage("Cannot save file");
313                 Intellego.addToLog("CodeEditor.saveFile(): Save to file failed: "+e);
314             }
315         }
316         else
317         {   
318             // cancel, do nothing atm
319         }
320     }
321     
322     /**
323     * Closes the current file
324     */
325     private void closeFile()
326     {
327         // save the file
328         saveFile();
329         
330         // and get rid of it
331         currentFile=null;
332         codePane.setText(" ");
333         
334         // and change the title
335         super.setTitle("Code Editor:  (no file)");
336     }
337     
338     /**
339     * Compiles the current file with lejosc
340     */
341     private void lejosCompileFile()
342     {
343         if(currentFile!=null)
344         {
345             externalCommand("lejosc "+currentFile.toString());
346         }
347         else
348         {
349             MainInterface.displayMessage("Cannot compile an empty file");
350         }
351     }
352     
353     /**
354     * Compiles the current file with javac
355     */
356     private void javaCompileFile()
357     {
358         if(currentFile!=null)
359         {
360             externalCommand("javac "+currentFile.toString());
361         }
362         else
363         {
364             MainInterface.displayMessage("Cannot compile an empty file");
365         }
366     }
367     
368     /**
369     * Links and downloads the current file
370     */
371     private void downloadFile()
372     {
373         if(currentFile!=null)
374         {
375             ControllerDL c=new ControllerDL(currentFile,currentDir);
376         }
377         else
378         {
379             MainInterface.displayMessage("You need to open a controller first");
380         }
381     }
382     
383     public void openFileInSim()
384     {
385         if(currentFile!=null)
386         {
387             // get rid of .java extension (to get the class name)
388             String className=currentFile.getName();
389             className=className.substring(0,className.length() - 5);
390             
391             // fire up a new simulator with this class
392             MainInterface.createSimulatorFrame(className);
393         }
394         else
395         {
396             MainInterface.displayMessage("You need to open a controller first");
397         }
398     }
399 
400     /**
401     * Processes all external calls, i.e calls to lejos & lejosc
402     */
403     private void externalCommand(String cmd)
404     {
405         int len;
406         byte buffer[] = new byte[1000];
407         
408         Intellego.addToLog("CodeEditor.externalCommand(): Processing External Command: "+cmd);
409         
410         try
411         {
412             Process external=Runtime.getRuntime().exec(cmd);
413             InputStream ees = external.getErrorStream();
414             
415             try 
416             {
417                 ExternalMessager output=MainInterface.createExternalMessagerFrame();
418                 while ((len = ees.read(buffer)) != -1)
419                 {
420                     String eo = new String (buffer, 0, len);
421                     output.append(eo);            
422                 }
423                 external.waitFor();
424              }
425              catch (Exception e) 
426              {
427                 Intellego.addToLog("CodeEditor.externalCommand(): error: "+e.getMessage());
428              }
429         }
430         catch (Exception e) 
431         {
432             Intellego.addToLog("CodeEditor.externalCommand(): error: "+e.getMessage());
433         }
434     }
435 }
436