Docjar: A Java Source and Docuemnt Enginecom.*    java.*    javax.*    org.*    all    new    plug-in

Quick Search    Search Deep

Source code: com/barteo/emulator/app/EclipseSwt.java


1   /*
2    *  MicroEmulator
3    *  Copyright (C) 2001-2003 Bartek Teodorczyk <barteo@it.pl>
4    *
5    *  This library is free software; you can redistribute it and/or
6    *  modify it under the terms of the GNU Lesser General Public
7    *  License as published by the Free Software Foundation; either
8    *  version 2.1 of the License, or (at your option) any later version.
9    *
10   *  This library is distributed in the hope that it will be useful,
11   *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12   *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13   *  Lesser General Public License for more details.
14   *
15   *  You should have received a copy of the GNU Lesser General Public
16   *  License along with this library; if not, write to the Free Software
17   *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18   */
19  
20  package com.barteo.emulator.app;
21          
22  import java.io.ByteArrayOutputStream;
23  import java.io.File;
24  import java.io.PrintStream;
25  import java.net.MalformedURLException;
26  import java.net.URL;
27  import java.util.Enumeration;
28  
29  import javax.microedition.midlet.MIDlet;
30  import javax.microedition.midlet.MIDletStateChangeException;
31  
32  import org.eclipse.swt.SWT;
33  import org.eclipse.swt.events.KeyEvent;
34  import org.eclipse.swt.events.KeyListener;
35  import org.eclipse.swt.events.ShellEvent;
36  import org.eclipse.swt.events.ShellListener;
37  import org.eclipse.swt.graphics.Color;
38  import org.eclipse.swt.graphics.Cursor;
39  import org.eclipse.swt.graphics.DeviceData;
40  import org.eclipse.swt.graphics.Font;
41  import org.eclipse.swt.graphics.FontData;
42  import org.eclipse.swt.graphics.GC;
43  import org.eclipse.swt.graphics.Image;
44  import org.eclipse.swt.graphics.Point;
45  import org.eclipse.swt.graphics.Rectangle;
46  import org.eclipse.swt.graphics.Region;
47  import org.eclipse.swt.layout.GridData;
48  import org.eclipse.swt.layout.GridLayout;
49  import org.eclipse.swt.widgets.Button;
50  import org.eclipse.swt.widgets.Canvas;
51  import org.eclipse.swt.widgets.Display;
52  import org.eclipse.swt.widgets.Event;
53  import org.eclipse.swt.widgets.Label;
54  import org.eclipse.swt.widgets.List;
55  import org.eclipse.swt.widgets.Listener;
56  import org.eclipse.swt.widgets.MessageBox;
57  import org.eclipse.swt.widgets.Shell;
58  import org.eclipse.swt.widgets.Text;
59  
60  import com.barteo.emulator.DisplayComponent;
61  import com.barteo.emulator.EmulatorContext;
62  import com.barteo.emulator.MIDletBridge;
63  import com.barteo.emulator.app.ui.swt.SwtDeviceComponent;
64  import com.barteo.emulator.app.ui.swt.SwtSelectDeviceDialog;
65  import com.barteo.emulator.app.util.DeviceEntry;
66  import com.barteo.emulator.app.util.ProgressJarClassLoader;
67  import com.barteo.emulator.device.Device;
68  import com.barteo.emulator.device.DeviceFactory;
69  import com.barteo.emulator.device.swt.SwtDevice;
70  import com.barteo.emulator.util.JadMidletEntry;
71  
72  
73  public class EclipseSwt extends Common
74  {
75    public static Shell shell;
76  
77    private static SwtDeviceComponent devicePanel;
78  
79    private boolean initialized = false;
80    
81    private SwtSelectDeviceDialog selectDeviceDialog;
82    private DeviceEntry deviceEntry;
83    
84    private KeyListener keyListener = new KeyListener()
85    {    
86      public void keyTyped(KeyEvent e)
87      {
88      }
89      
90      public void keyPressed(KeyEvent e)
91      {
92  //      devicePanel.keyPressed(e);
93      }
94      
95      public void keyReleased(KeyEvent e)
96      {
97  //      devicePanel.keyReleased(e);
98      }    
99    };
100        
101   private ShellListener shellListener = new ShellListener()
102   {
103     public void shellActivated(ShellEvent e) 
104     {
105     }
106 
107     public void shellClosed(ShellEvent e) 
108     {
109       close();
110     }
111 
112     public void shellDeactivated(ShellEvent e) 
113     {
114     }
115 
116     public void shellDeiconified(ShellEvent e) 
117     {
118       try {
119         MIDletBridge.getMIDletAccess(getLauncher().getCurrentMIDlet()).startApp();
120       } catch (MIDletStateChangeException ex) {
121         System.err.println(ex);
122       }
123     }
124 
125     public void shellIconified(ShellEvent e) 
126     {
127       MIDletBridge.getMIDletAccess(getLauncher().getCurrentMIDlet()).pauseApp();
128     }
129   };
130  
131   
132   EclipseSwt(Shell shell, Device device, String captureFile)
133   {
134     super(new EmulatorContext()
135     {
136       ProgressJarClassLoader loader = new ProgressJarClassLoader();
137     
138       public ClassLoader getClassLoader()
139       {
140         return loader;
141       }
142     
143       public DisplayComponent getDisplayComponent()
144       {
145         return devicePanel.getDisplayComponent();
146       }    
147     });
148 
149     GridLayout layout = new GridLayout(1, false);
150     shell.setLayout(layout);
151     shell.setLayoutData(new GridData(GridData.FILL_BOTH));
152 
153     shell.setText("Microemu");
154 //    addWindowListener(windowListener);
155         
156     Config.loadConfig("config-swt.xml");
157     shell.addKeyListener(keyListener);
158 
159     devicePanel = new SwtDeviceComponent(shell);
160     devicePanel.setLayoutData(new GridData(GridData.FILL_BOTH));
161     
162     this.captureFile = captureFile;
163 
164     if (device == null) {
165       selectDeviceDialog = new SwtSelectDeviceDialog(shell);
166       setDevice(selectDeviceDialog.getSelectedDeviceEntry());
167     } else {
168       setDevice(device);
169     }
170     
171     initialized = true;
172   }
173       
174   
175   public DeviceEntry getDevice()
176   {
177     return deviceEntry;
178   }
179   
180   
181   public void setDevice(DeviceEntry entry)
182   {
183     if (DeviceFactory.getDevice() != null) {
184       ((SwtDevice) DeviceFactory.getDevice()).dispose();
185     }
186     
187     ProgressJarClassLoader loader = (ProgressJarClassLoader) emulatorContext.getClassLoader();
188     try {
189       Class deviceClass = null;
190       if (entry.getFileName() != null) {
191         loader.addRepository(
192             new File(Config.getConfigPath(), entry.getFileName()).toURL());
193         deviceClass = loader.findClass(entry.getClassName());
194       } else {
195         deviceClass = Class.forName(entry.getClassName());
196       }
197       SwtDevice device = (SwtDevice) deviceClass.newInstance();
198       this.deviceEntry = entry;
199       setDevice(device);
200     } catch (MalformedURLException ex) {
201       System.err.println(ex);          
202     } catch (ClassNotFoundException ex) {
203       System.err.println(ex);          
204     } catch (InstantiationException ex) {
205       System.err.println(ex);          
206     } catch (IllegalAccessException ex) {
207       System.err.println(ex);          
208     }
209   }
210 
211 
212   protected void setDevice(SwtDevice device)
213   {
214     super.setDevice(device);
215 
216     device.init(emulatorContext);
217     shell.setSize(shell.computeSize(SWT.DEFAULT, SWT.DEFAULT, true));
218   }
219   
220   
221   protected void loadFromJad(URL jadUrl)
222   {    
223     try {
224       for (Enumeration e = jad.getMidletEntries().elements(); e.hasMoreElements(); ) {
225         JadMidletEntry jadEntry = (JadMidletEntry) e.nextElement();
226         Class midletClass = emulatorContext.getClassLoader().loadClass(jadEntry.getClassName());
227         loadMidlet(jadEntry.getName(), midletClass);
228       }
229       notifyDestroyed();
230     } catch (ClassNotFoundException ex) {
231       System.err.println(ex);
232     }        
233   }
234 
235 
236   public static void main(String args[])
237   {
238     DeviceData data = new DeviceData();
239     data.tracking = true;
240     
241     Display display = new Display(data);
242     shell = new Shell(display, SWT.CLOSE | SWT.TITLE | SWT.MIN | SWT.ON_TOP);
243         
244     MIDlet m = null;
245 
246 //    Sleak sleak = app.new Sleak (display);
247 //    sleak.open ();
248 
249     Device device = null;
250     String captureFile = null;
251     URL jadUrl = null;
252     Class midletClass = null;
253 
254     if (args.length > 0) {
255       for (int i = 0; i < args.length; i++) {
256         if (args[i].equals("--deviceClass")) {
257           i++;
258           try {
259             Class deviceClass = Class.forName(args[i]);
260             device = (Device) deviceClass.newInstance();
261           } catch (ClassNotFoundException ex) {
262             System.err.println(ex);          
263           } catch (InstantiationException ex) {
264             System.err.println(ex);          
265           } catch (IllegalAccessException ex) {
266             System.err.println(ex);          
267           }          
268         } else if (args[i].equals("--captureFile")) {
269           i++;
270           captureFile = args[i];
271         } else if (args[i].endsWith(".jad")) {
272           try {
273             File file = new File(args[i]);
274             jadUrl = file.exists() ? file.toURL() : new URL(args[i]);
275           } catch(MalformedURLException exception) {
276             System.out.println("Cannot parse " + args[0] + " URL");
277           }
278         } else {
279           try {
280             midletClass = Class.forName(args[i]);
281           } catch (ClassNotFoundException ex) {
282             System.out.println("Cannot find " + args[i] + " MIDlet class");
283           }
284         }
285       }
286     }
287 
288     EclipseSwt app = new EclipseSwt(shell, device, captureFile);
289     shell.addShellListener(app.shellListener);
290     
291     if (jadUrl != null) {
292       app.openJadFile(jadUrl);      
293     } else if (midletClass != null) {
294       m = app.loadMidlet("MIDlet", midletClass);      
295     } else {
296       m = app.getLauncher();
297     }
298     
299     
300     if (app.initialized) {
301       if (m != null) {
302         app.startMidlet(m);
303       }
304       
305       shell.pack ();
306       shell.open ();
307       while (!shell.isDisposed ()) {
308         if (!display.readAndDispatch ())
309           display.sleep ();
310       }
311       display.dispose ();      
312     }
313 
314     System.exit(0);
315   }  
316   
317   
318   class Sleak {
319     Display display;
320     Shell shell;
321     List list;
322     Canvas canvas;
323     Button start, stop, check;
324     Text text;
325     Label label;
326   
327     Object [] oldObjects = new Object [0];
328     Error [] oldErrors = new Error [0];
329     Object [] objects = new Object [0];
330     Error [] errors = new Error [0];
331   
332     public Sleak(Display display) 
333     {
334       this.display = display;
335     }
336 
337     public void open () {
338     display = Display.getCurrent ();
339     shell = new Shell (display);
340     shell.setText ("S-Leak");
341     list = new List (shell, SWT.BORDER | SWT.V_SCROLL);
342     list.addListener (SWT.Selection, new Listener () {
343       public void handleEvent (Event event) {
344         refreshObject ();
345       }
346     });
347     text = new Text (shell, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
348     canvas = new Canvas (shell, SWT.BORDER);
349     canvas.addListener (SWT.Paint, new Listener () {
350       public void handleEvent (Event event) {
351         paintCanvas (event);
352       }
353     });
354     check = new Button (shell, SWT.CHECK);
355     check.setText ("Stack");
356     check.addListener (SWT.Selection, new Listener () {
357       public void handleEvent (Event e) {
358         toggleStackTrace ();
359       }
360     });
361     start = new Button (shell, SWT.PUSH);
362     start.setText ("Snap");
363     start.addListener (SWT.Selection, new Listener () {
364       public void handleEvent (Event event) {
365         refreshAll ();
366       }
367     });
368     stop = new Button (shell, SWT.PUSH);
369     stop.setText ("Diff");
370     stop.addListener (SWT.Selection, new Listener () {
371       public void handleEvent (Event event) {
372         refreshDifference ();
373       }
374     });
375     label = new Label (shell, SWT.BORDER);
376     label.setText ("0 object(s)");
377     shell.addListener (SWT.Resize, new Listener () {
378       public void handleEvent (Event e) {
379         layout ();
380       }
381     });
382     check.setSelection (false);
383     text.setVisible (false);
384     Point size = shell.getSize ();
385     shell.setSize (size.x / 2, size.y / 2);
386     shell.open ();
387   }
388 
389   void refreshLabel () {
390     int colors = 0, cursors = 0, fonts = 0, gcs = 0, images = 0, regions = 0;
391     for (int i=0; i<objects.length; i++) {
392       Object object = objects [i];
393       if (object instanceof Color) colors++;
394       if (object instanceof Cursor) cursors++;
395       if (object instanceof Font) fonts++;
396       if (object instanceof GC) gcs++;
397       if (object instanceof Image) images++;
398       if (object instanceof Region) regions++;
399     }
400     String string = "";
401     if (colors != 0) string += colors + " Color(s)\n";
402     if (cursors != 0) string += cursors + " Cursor(s)\n";
403     if (fonts != 0) string += fonts + " Font(s)\n";
404     if (gcs != 0) string += gcs + " GC(s)\n";
405     if (images != 0) string += images + " Image(s)\n";
406     /* Currently regions are not counted. */
407 //    if (regions != 0) string += regions + " Region(s)\n";
408     if (string.length () != 0) {
409       string = string.substring (0, string.length () - 1);
410     }
411     label.setText (string);
412   }
413 
414   void refreshDifference () {
415     DeviceData info = display.getDeviceData ();
416     if (!info.tracking) {
417       MessageBox dialog = new MessageBox (shell, SWT.ICON_WARNING | SWT.OK);
418       dialog.setText (shell.getText ());
419       dialog.setMessage ("Warning: Device is not tracking resource allocation");
420       dialog.open ();
421     }
422     Object [] newObjects = info.objects;
423     Error [] newErrors = info.errors;
424     Object [] diffObjects = new Object [newObjects.length];
425     Error [] diffErrors = new Error [newErrors.length];
426     int count = 0;
427     for (int i=0; i<newObjects.length; i++) {
428       int index = 0;
429       while (index < oldObjects.length) {
430         if (newObjects [i] == oldObjects [index]) break;
431         index++;
432       }
433       if (index == oldObjects.length) {
434         diffObjects [count] = newObjects [i];
435         diffErrors [count] = newErrors [i];
436         count++;
437       }
438     }
439     objects = new Object [count];
440     errors = new Error [count];
441     System.arraycopy (diffObjects, 0, objects, 0, count);
442     System.arraycopy (diffErrors, 0, errors, 0, count);
443     list.removeAll ();
444     text.setText ("");
445     canvas.redraw ();
446     for (int i=0; i<objects.length; i++) {
447       list.add (objectName (objects [i]));
448     }
449     refreshLabel ();
450     layout ();
451   }
452 
453   String objectName (Object object) {
454     String string = object.toString ();
455     int index = string.lastIndexOf ('.');
456     if (index == -1) return string;
457     return string.substring (index + 1, string.length ());
458   }
459 
460   void toggleStackTrace () {
461     refreshObject ();
462     layout ();
463   }
464 
465   void paintCanvas (Event event) {
466     canvas.setCursor (null);
467     int index = list.getSelectionIndex ();
468     if (index == -1) return;
469     GC gc = event.gc;
470     Object object = objects [index];
471     if (object instanceof Color) {
472       if (((Color)object).isDisposed ()) return;
473       gc.setBackground ((Color) object);
474       gc.fillRectangle (canvas.getClientArea());
475       return;
476     }
477     if (object instanceof Cursor) {
478       if (((Cursor)object).isDisposed ()) return;
479       canvas.setCursor ((Cursor) object);
480       return;
481     }
482     if (object instanceof Font) {
483       if (((Font)object).isDisposed ()) return;
484       gc.setFont ((Font) object);
485       FontData [] array = gc.getFont ().getFontData ();
486       String string = "";
487       String lf = text.getLineDelimiter ();
488       for (int i=0; i<array.length; i++) {
489         FontData data = array [i];
490         String style = "NORMAL";
491         int bits = data.getStyle ();
492         if (bits != 0) {
493           if ((bits & SWT.BOLD) != 0) style = "BOLD ";
494           if ((bits & SWT.ITALIC) != 0) style += "ITALIC";
495         }
496         string += data.getName () + " " + data.getHeight () + " " + style + lf;
497       }
498       gc.drawString (string, 0, 0);
499       return;
500     }
501     //NOTHING TO DRAW FOR GC
502 //    if (object instanceof GC) {
503 //      return;
504 //    }
505     if (object instanceof Image) {
506       if (((Image)object).isDisposed ()) return;
507       gc.drawImage ((Image) object, 0, 0);
508       return;
509     }
510     if (object instanceof Region) {
511       if (((Region)object).isDisposed ()) return;
512       String string = ((Region)object).getBounds().toString();
513       gc.drawString (string, 0, 0);
514       return;
515     }
516   }
517 
518   void refreshObject () {
519     int index = list.getSelectionIndex ();
520     if (index == -1) return;
521     if (check.getSelection ()) {
522       ByteArrayOutputStream stream = new ByteArrayOutputStream ();
523       PrintStream s = new PrintStream (stream);
524       errors [index].printStackTrace (s);
525       text.setText (stream.toString ());
526       text.setVisible (true);
527       canvas.setVisible (false);
528     } else {
529       canvas.setVisible (true);
530       text.setVisible (false);
531       canvas.redraw ();
532     }
533   }
534 
535   void refreshAll () {
536     oldObjects = new Object [0];
537     oldErrors = new Error [0];
538     refreshDifference ();
539     oldObjects = objects;
540     oldErrors = errors;
541   }
542 
543   void layout () {
544     Rectangle rect = shell.getClientArea ();
545     int width = 0;
546     String [] items = list.getItems ();
547     GC gc = new GC (list);
548     for (int i=0; i<objects.length; i++) {
549       width = Math.max (width, gc.stringExtent (items [i]).x);
550     }
551     gc.dispose ();
552     Point size1 = start.computeSize (SWT.DEFAULT, SWT.DEFAULT);
553     Point size2 = stop.computeSize (SWT.DEFAULT, SWT.DEFAULT);
554     Point size3 = check.computeSize (SWT.DEFAULT, SWT.DEFAULT);
555     Point size4 = label.computeSize (SWT.DEFAULT, SWT.DEFAULT);
556     width = Math.max (size1.x, Math.max (size2.x, Math.max (size3.x, width)));
557     width = Math.max (64, Math.max (size4.x, list.computeSize (width, SWT.DEFAULT).x));
558     start.setBounds (0, 0, width, size1.y);
559     stop.setBounds (0, size1.y, width, size2.y);
560     check.setBounds (0, size1.y + size2.y, width, size3.y);
561     label.setBounds (0, rect.height - size4.y, width, size4.y);
562     int height = size1.y + size2.y + size3.y;
563     list.setBounds (0, height, width, rect.height - height - size4.y);
564     text.setBounds (width, 0, rect.width - width, rect.height);
565     canvas.setBounds (width, 0, rect.width - width, rect.height);
566   }
567   }
568   
569 }