KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > edu > rice > cs > drjava > ui > DefinitionsPaneTest


1 /*BEGIN_COPYRIGHT_BLOCK
2  *
3  * This file is part of DrJava. Download the current version of this project from http://www.drjava.org/
4  * or http://sourceforge.net/projects/drjava/
5  *
6  * DrJava Open Source License
7  *
8  * Copyright (C) 2001-2005 JavaPLT group at Rice University (javaplt@rice.edu). All rights reserved.
9  *
10  * Developed by: Java Programming Languages Team, Rice University, http://www.cs.rice.edu/~javaplt/
11  *
12  * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
13  * documentation files (the "Software"), to deal with the Software without restriction, including without limitation
14  * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
15  * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
16  *
17  * - Redistributions of source code must retain the above copyright notice, this list of conditions and the
18  * following disclaimers.
19  * - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
20  * following disclaimers in the documentation and/or other materials provided with the distribution.
21  * - Neither the names of DrJava, the JavaPLT, Rice University, nor the names of its contributors may be used to
22  * endorse or promote products derived from this Software without specific prior written permission.
23  * - Products derived from this software may not be called "DrJava" nor use the term "DrJava" as part of their
24  * names without prior written permission from the JavaPLT group. For permission, write to javaplt@rice.edu.
25  *
26  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
27  * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28  * CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
29  * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
30  * WITH THE SOFTWARE.
31  *
32  END_COPYRIGHT_BLOCK*/

33
34 package edu.rice.cs.drjava.ui;
35
36 import edu.rice.cs.drjava.DrJava;
37 import edu.rice.cs.drjava.config.OptionConstants;
38 import edu.rice.cs.drjava.model.MultiThreadedTestCase;
39 import edu.rice.cs.drjava.model.*;
40 import edu.rice.cs.drjava.model.definitions.DefinitionsDocument;
41 import edu.rice.cs.util.Log;
42 import edu.rice.cs.util.UnexpectedException;
43 import edu.rice.cs.util.swing.Utilities;
44
45 import javax.swing.*;
46 import javax.swing.text.BadLocationException JavaDoc;
47 import java.awt.event.InputEvent JavaDoc;
48 import java.awt.event.KeyEvent JavaDoc;
49 import java.awt.event.KeyListener JavaDoc;
50 import java.io.IOException JavaDoc;
51 import java.lang.reflect.InvocationTargetException JavaDoc;
52 import java.util.Date JavaDoc;
53
54 /** Tests the Definitions Pane
55   * @version $Id: DefinitionsPaneTest.java 4031 2006-11-15 22:09:06Z rcartwright $
56   */

57 public final class DefinitionsPaneTest extends MultiThreadedTestCase {
58
59   private volatile MainFrame _frame;
60   
61   public static final Log _log = new Log("DefinitionsPaneTest.txt", false); // used in other tests
62

63   private static final char UNDEFINED = KeyEvent.CHAR_UNDEFINED;
64   private static final int PRESSED = KeyEvent.KEY_PRESSED;
65   private static final int RELEASED = KeyEvent.KEY_RELEASED;
66   private static final int SHIFT = InputEvent.SHIFT_MASK;
67   private static final int TYPED = KeyEvent.KEY_TYPED;
68   private static final int VK_UNDEF = KeyEvent.VK_UNDEFINED;
69   private static final int META = KeyEvent.VK_META;
70   private static final int W = KeyEvent.VK_W;
71   private static final int M_MASK = InputEvent.META_MASK;
72   private static final int BANG = KeyEvent.VK_EXCLAMATION_MARK;
73   private static final int ALT = InputEvent.ALT_MASK;
74   
75   private static final int DEL_NEXT = OptionConstants.KEY_DELETE_NEXT.getDefault().getKeyCode();
76   private static final int DEL_PREV = OptionConstants.KEY_DELETE_PREVIOUS.getDefault().getKeyCode();
77     
78   /** Setup method for each JUnit test case. */
79   public void setUp() throws Exception JavaDoc {
80     super.setUp();
81     DrJava.getConfig().resetToDefaults();
82     _frame = new MainFrame();
83     
84 // super.setUp();
85
// Utilities.invokeAndWait(new Runnable() {
86
// public void run() {
87
// DrJava.getConfig().resetToDefaults();
88
// _frame = new MainFrame();
89
// }
90
// });
91
// Utilities.clearEventQueue();
92
}
93   
94   public void tearDown() throws Exception JavaDoc {
95     Utilities.invokeLater(new Runnable JavaDoc() {
96       public void run() {
97         _frame.dispose();
98         _log.log("Main Frame disposed");
99         _frame = null;
100       }
101     });
102     Utilities.clearEventQueue();
103     super.tearDown();
104   }
105   
106   /** Tests that shift backspace works the same as backspace. (Ease of use issue 693253). Ideally, this test should
107     * be lighter weight, and not require the creation of an entire MainFrame+GlobalModel. Refactor?
108     * NOTE: This test doesn't work yet, since we can't currently bind two keys to the same action. This should be
109     * implemented as part of feature request 683300.
110     */

111   public void testShiftBackspace() throws BadLocationException JavaDoc {
112 // _log.log("Starting testShiftBackSpace");
113
final DefinitionsPane defPane = _frame.getCurrentDefPane();
114     final OpenDefinitionsDocument doc = defPane.getOpenDefDocument();
115   
116     _assertDocumentEmpty(doc, "before testing");
117     
118     Utilities.invokeAndWait(new Runnable JavaDoc() {
119       public void run() {
120         doc.append("test", null);
121         defPane.setCaretPosition(4);
122         
123         // The following is the sequence of key events for shift+backspace
124
defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, PRESSED, (new Date JavaDoc()).getTime(), SHIFT, DEL_PREV, UNDEFINED));
125         _log.log("first key event processed");
126         defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, RELEASED, (new Date JavaDoc()).getTime(), SHIFT, DEL_PREV, UNDEFINED));
127         _frame.validate();
128       }
129     });
130     Utilities.clearEventQueue();
131     
132     _log.log("second key event processed");
133     _assertDocumentContents(doc, "tes", "Did not delete on shift+backspace");
134     _log.log("Halfway through testShiftBackspace");
135     
136      
137     Utilities.invokeAndWait(new Runnable JavaDoc() {
138       public void run() {
139         
140         defPane.setCaretPosition(1);
141         // The following is the sequence of key events for shift+delete
142
defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, PRESSED, (new Date JavaDoc()).getTime(), SHIFT, DEL_NEXT, UNDEFINED));
143         defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, RELEASED, (new Date JavaDoc()).getTime(), SHIFT, DEL_NEXT, UNDEFINED));
144         _frame.validate();
145       }
146     });
147     Utilities.clearEventQueue();
148     _assertDocumentContents(doc, "ts", "Did not delete on shift+delete");
149     _log.log("testShiftBackSpace completed");
150    
151   }
152
153   
154   /** Tests that typing a brace in a string/comment does not cause an indent. */
155   public void testTypeBraceNotInCode() throws BadLocationException JavaDoc {
156     final DefinitionsPane defPane = _frame.getCurrentDefPane();
157     final OpenDefinitionsDocument doc = defPane.getOpenDefDocument();
158     _assertDocumentEmpty(doc, "before testing");
159     _log.log("calling invokeAndWait in testTypeBraceNotInCode");
160     Utilities.invokeAndWait(new Runnable JavaDoc() {
161       public void run() {
162         doc.append(" \"", null);
163         defPane.setCaretPosition(3);
164         // The following is the sequence of key events for a left brace
165
defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, TYPED, (new Date JavaDoc()).getTime(), 0, VK_UNDEF, '{'));
166       }
167     });
168     Utilities.clearEventQueue();
169         
170     _assertDocumentContents(doc, " \"{", "Brace should not indent in a string");
171     _log.log("testTypeBraceNotInCode completed");
172   }
173   
174   /** Tests that typing Enter in a string/comment does cause an indent. This behavior works in practice, but I can't
175     * get the test to work. If we use definitions.processKeyEvent, the caret position is not updated, so the " * "
176     * is not inserted. If we try to dispatchEvent from the EventDispatchingThread, it hangs...?
177     */

178   public void testTypeEnterNotInCode() throws BadLocationException JavaDoc, InterruptedException JavaDoc, InvocationTargetException JavaDoc {
179     final DefinitionsPane defPane = _frame.getCurrentDefPane();
180 // _frame.setVisible(true);
181
final OpenDefinitionsDocument doc = defPane.getOpenDefDocument();
182     _assertDocumentEmpty(doc, "before testing");
183     Utilities.invokeAndWait(new Runnable JavaDoc() {
184       public void run() {
185
186         try {
187           doc.insertString(0, "/**", null);
188           defPane.setCaretPosition(3);
189           // The following is the sequence of key events for Enter
190
int enter = KeyEvent.VK_ENTER;
191           defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, PRESSED, (new Date JavaDoc()).getTime(), 0, enter, UNDEFINED));
192           defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, RELEASED, (new Date JavaDoc()).getTime(), 0, enter, UNDEFINED));
193           _frame.validate();
194         }
195         catch(Throwable JavaDoc t) { listenerFail(t.getMessage()); }
196         _log.log("Completed processing of keyEvents");
197       }
198     });
199     Utilities.clearEventQueue();
200     _assertDocumentContents(doc, "/**\n * ", "Enter should indent in a comment");
201     _log.log("testTypeEnterNotInCode completed");
202   }
203   
204   /** Tests that a simulated key press with the meta modifier is correct. Reveals bug 676586. */
205   public void testMetaKeyPress() throws BadLocationException JavaDoc {
206     final DefinitionsPane defPane = _frame.getCurrentDefPane();
207     final OpenDefinitionsDocument doc = defPane.getOpenDefDocument();
208     _assertDocumentEmpty(doc, "point 0");
209     
210     Utilities.invokeAndWait(new Runnable JavaDoc() {
211       public void run() {
212         // The following is the sequence of key events that happen when the user presses Meta-a
213
defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, PRESSED, (new Date JavaDoc()).getTime(), M_MASK, META, UNDEFINED));
214         _frame.validate();
215       }
216     });
217     Utilities.clearEventQueue();
218         
219     _assertDocumentEmpty(doc, "point 1");
220     
221     Utilities.invokeAndWait(new Runnable JavaDoc() {
222       public void run() {
223         defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, PRESSED, (new Date JavaDoc()).getTime(), M_MASK, W, UNDEFINED));
224         _frame.validate();
225       }
226     });
227     Utilities.clearEventQueue();
228     
229     _assertDocumentEmpty(doc, "point 2");
230         
231     Utilities.invokeAndWait(new Runnable JavaDoc() {
232       public void run() {
233         defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, TYPED, (new Date JavaDoc()).getTime(), M_MASK, VK_UNDEF, 'w'));
234         _frame.validate();
235       }
236     });
237     Utilities.clearEventQueue();
238     
239     _assertDocumentEmpty(doc, "point 3");
240     
241     Utilities.invokeAndWait(new Runnable JavaDoc() {
242       public void run() {
243         defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, RELEASED, (new Date JavaDoc()).getTime(), M_MASK, W, UNDEFINED));
244         _frame.validate();
245       }
246     });
247     Utilities.clearEventQueue();
248      
249     _assertDocumentEmpty(doc, "point 4");
250     
251     Utilities.invokeAndWait(new Runnable JavaDoc() {
252       public void run() {
253         defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, RELEASED, (new Date JavaDoc()).getTime(), 0, META, UNDEFINED));
254         _frame.validate();
255       }
256     });
257     Utilities.clearEventQueue();
258     
259     _assertDocumentEmpty(doc, "point 5");
260     
261     _log.log("testMetaKeyPress completed");
262   }
263   
264   /** Tests that undoing/redoing a multi-line comment/uncomment will restore the caret position */
265   public void testMultilineCommentOrUncommentAfterScroll() throws BadLocationException JavaDoc {
266     
267     final DefinitionsPane pane = _frame.getCurrentDefPane();
268     final OpenDefinitionsDocument doc = pane.getOpenDefDocument();
269     final String JavaDoc text =
270       "public class stuff {\n" +
271       " private int _int;\n" +
272       " private Bar _bar;\n" +
273       " public void foo() {\n" +
274       " _bar.baz(_int);\n" +
275       " }\n" +
276       "}\n";
277     
278     String JavaDoc commented =
279       "//public class stuff {\n" +
280       "// private int _int;\n" +
281       "// private Bar _bar;\n" +
282       "// public void foo() {\n" +
283       "// _bar.baz(_int);\n" +
284       "// }\n" +
285       "//}\n";
286     
287     final int newPos = 20;
288     
289     // The following statement hung when run in the main test thread. There must be a pending access to doc in a
290
// task on the event queue that sometimes has not yet executed.
291

292     Utilities.invokeAndWait(new Runnable JavaDoc() { public void run() { doc.append(text, null); } });
293     Utilities.clearEventQueue();
294     
295     assertEquals("insertion", text, doc.getText());
296     
297     // Need to do this here since the commentLines action in MainFrame usually takes care of this.
298
// I can't run the test here because I'm not sure how to select the text so that we can comment it.
299

300     Utilities.invokeAndWait(new Runnable JavaDoc() { public void run() { pane.endCompoundEdit(); } });
301      
302     doc.acquireWriteLock();
303     try { doc.commentLines(0, doc.getLength()); }
304     finally { doc.releaseWriteLock(); }
305     
306     // pane.endCompoundEdit();
307
assertEquals("commenting", commented, doc.getText());
308     
309     int oldPos = pane.getCaretPosition();
310     
311     Utilities.invokeAndWait(new Runnable JavaDoc() {
312       public void run() {
313         pane.setCaretPosition(newPos);
314         _frame.validate();
315       }
316     });
317     Utilities.clearEventQueue();
318     
319     doc.getUndoManager().undo();
320     assertEquals("undo commenting", text, doc.getText());
321     assertEquals("undoing commenting restores caret position", oldPos, pane.getCaretPosition());
322     
323     // Perturb the caret position and redo
324
Utilities.invokeAndWait(new Runnable JavaDoc() { public void run() { pane.setCaretPosition(newPos); } });
325     Utilities.clearEventQueue();
326     
327     doc.getUndoManager().redo();
328     assertEquals("redo commenting", commented, doc.getText());
329     assertEquals("redoing commenting restores caret position", oldPos, pane.getCaretPosition());
330     
331     // Need to do this here since the commentLines action in MainFrame usually takes care of this.
332
// I can't simulate a keystroke here because I'm not sure how to select the text so that we can comment it.
333
Utilities.invokeAndWait(new Runnable JavaDoc() { public void run() { pane.endCompoundEdit(); } });
334     Utilities.clearEventQueue();
335     
336     doc.acquireWriteLock();
337     try { doc.uncommentLines(0, doc.getLength()); }
338     finally { doc.releaseWriteLock(); }
339     
340     // pane.endCompoundEdit();
341
assertEquals("uncommenting", text, doc.getText());
342     
343     oldPos = pane.getCaretPosition(); // executing this method call outside of the event thread is borderline
344

345     Utilities.invokeAndWait(new Runnable JavaDoc() { public void run() { pane.setCaretPosition(newPos); } });
346     Utilities.clearEventQueue();
347     
348     doc.getUndoManager().undo();
349     
350     assertEquals("undo uncommenting", commented, doc.getText());
351     assertEquals("undoing uncommenting restores caret position", oldPos, pane.getCaretPosition());
352     
353     Utilities.invokeAndWait(new Runnable JavaDoc() { public void run() { pane.setCaretPosition(newPos); } });
354     Utilities.clearEventQueue();
355     
356     doc.getUndoManager().redo();
357     assertEquals("redo uncommenting",text, doc.getText());
358     assertEquals("redoing uncommenting restores caret position", oldPos, pane.getCaretPosition());
359     
360     _log.log("testMultiLineCommentOrUncommentAfterScroll completed");
361   }
362   
363   protected void _assertDocumentEmpty(DJDocument doc, String JavaDoc message) {
364     _assertDocumentContents(doc, "", message);
365   }
366   
367   protected void _assertDocumentContents(DJDocument doc, String JavaDoc contents, String JavaDoc message) {
368     assertEquals(message, contents, doc.getText());
369   }
370   
371   public void testGranularUndo() throws BadLocationException JavaDoc {
372     final DefinitionsPane defPane = _frame.getCurrentDefPane();
373     final OpenDefinitionsDocument doc = defPane.getOpenDefDocument();
374     // doc.addUndoableEditListener(doc.getUndoManager());
375

376     // 1
377
assertEquals("Should start out empty.", "", doc.getText());
378     
379     // Type in consecutive characters and see if they are all undone at once.
380
// Type 'a'
381
Utilities.invokeAndWait(new Runnable JavaDoc() {
382       public void run() {
383         defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, PRESSED, (new Date JavaDoc()).getTime(), 0, KeyEvent.VK_A, UNDEFINED));
384         defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, TYPED, (new Date JavaDoc()).getTime(), 0, VK_UNDEF, 'a'));
385         defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, RELEASED, (new Date JavaDoc()).getTime(), 0, KeyEvent.VK_A, UNDEFINED));
386         defPane.setCaretPosition(doc.getLength());
387         
388         // Type '!'
389
defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, PRESSED, (new Date JavaDoc()).getTime(), 0, BANG, UNDEFINED));
390         defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, TYPED, (new Date JavaDoc()).getTime(), 0, VK_UNDEF, '!'));
391         defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, RELEASED, (new Date JavaDoc()).getTime(), 0, BANG, UNDEFINED));
392         defPane.setCaretPosition(doc.getLength());
393         
394         // Type 'B'
395
defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, PRESSED, (new Date JavaDoc()).getTime(), SHIFT, KeyEvent.VK_B, UNDEFINED));
396         defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, TYPED, (new Date JavaDoc()).getTime(), 0, VK_UNDEF, 'B'));
397         defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, RELEASED, (new Date JavaDoc()).getTime(), SHIFT, KeyEvent.VK_B, UNDEFINED));
398         defPane.setCaretPosition(doc.getLength());
399         
400         // Type '9'
401
defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, PRESSED, (new Date JavaDoc()).getTime(), 0, KeyEvent.VK_9, UNDEFINED));
402         defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, TYPED, (new Date JavaDoc()).getTime(), 0, VK_UNDEF, '9'));
403         defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, RELEASED, (new Date JavaDoc()).getTime(), 0, KeyEvent.VK_9, UNDEFINED));
404         defPane.setCaretPosition(doc.getLength());
405         _frame.validate();
406       }
407     });
408     Utilities.clearEventQueue();
409     
410     assertEquals("The text should have been inserted", "a!B9", doc.getText());
411     
412     // Call the undoAction in MainFrame through the KeyBindingManager.
413
final KeyStroke ks = DrJava.getConfig().getSetting(OptionConstants.KEY_UNDO);
414     final Action a = KeyBindingManager.Singleton.get(ks);
415     
416     final KeyEvent JavaDoc e = new KeyEvent JavaDoc(defPane, PRESSED, 0, ks.getModifiers(), ks.getKeyCode(), UNDEFINED);
417     
418     Utilities.invokeAndWait(new Runnable JavaDoc() {
419       public void run() {
420       defPane.processKeyEvent(e);
421       _frame.validate();
422       }
423     });
424     Utilities.clearEventQueue();
425   
426     assertEquals("Should have undone correctly.", "", doc.getText());
427     
428     // 2
429
/* Test bug #905405 Undo Alt+Anything Causes Exception */
430     
431     // What does the following code test? There are no assertions! -- Corky 5/9/06
432

433     // Type 'Alt-B'
434
Utilities.invokeAndWait(new Runnable JavaDoc() {
435        public void run() {
436          defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, PRESSED, (new Date JavaDoc()).getTime(), ALT, KeyEvent.VK_Q, UNDEFINED));
437          defPane.processKeyEvent(new KeyEvent JavaDoc(defPane,
438                                                   TYPED,
439                                                   (new Date JavaDoc()).getTime(),
440                                                   ALT,
441                                                   VK_UNDEF, 'Q'));
442          defPane.processKeyEvent(new KeyEvent JavaDoc(defPane,
443                                                   RELEASED,
444                                                   (new Date JavaDoc()).getTime(),
445                                                   ALT,
446                                                   KeyEvent.VK_Q, UNDEFINED));
447          
448          /*
449           * If the bug is not fixed in DefinitionsPane.processKeyEvent, this test
450           * will not fail because the exception is thrown in another thread.
451           * However, the stack trace will get printed onto the console. I don't
452           * know how to fix this problem in case someone unfixes the bug.
453           */

454          SwingUtilities.notifyAction(a, ks, e, e.getSource(), e.getModifiers());
455          _frame.validate();
456     // definitions.setCaretPosition(doc.getLength());
457
}
458      });
459      Utilities.clearEventQueue();
460     
461     // 2
462
/* This part doesn't work right now because by just calling processKeyEvent we
463      * have to manually move the caret, and the UndoWithPosition is off by one. This
464      * bites us since when the backspace is done, the backspace undo position is
465      * still at position 1 which doesn't exist in the document anymore.
466      *
467      *
468      // Test undoing backspace.
469      definitions.processKeyEvent(new KeyEvent(definitions,
470      PRESSED,
471      (new Date()).getTime(),
472      0,
473      VK_UNDEF, UNDEFINED));
474      definitions.processKeyEvent(new KeyEvent(definitions,
475      TYPED,
476      (new Date()).getTime(),
477      0,
478      VK_UNDEF, 'a'));
479      definitions.processKeyEvent(new KeyEvent(definitions,
480      RELEASED,
481      (new Date()).getTime(),
482      0,
483      VK_UNDEF, UNDEFINED));
484      definitions.setCaretPosition(doc.getLength());
485      
486      assertEquals("The text should have been inserted", "a",
487      doc.getText());
488      
489      definitions.processKeyEvent(new KeyEvent(definitions,
490      PRESSED,
491      (new Date()).getTime(),
492      0,
493      KeyEvent.VK_BACK_SPACE, UNDEFINED));
494      definitions.processKeyEvent(new KeyEvent(definitions,
495      TYPED,
496      (new Date()).getTime(),
497      0,
498      VK_UNDEF, '\010'));
499      definitions.processKeyEvent(new KeyEvent(definitions,
500      RELEASED,
501      (new Date()).getTime(),
502      0,
503      KeyEvent.VK_BACK_SPACE, UNDEFINED));
504      System.out.println(definitions.getCaretPosition());
505      definitions.setCaretPosition(doc.getLength());
506      
507      assertEquals("The text should have been deleted", "",
508      doc.getText());
509      
510      // Call the undoAction in MainFrame through the KeyBindingManager.
511      // KeyStroke ks = DrJava.getConfig().getSetting(OptionConstants.KEY_UNDO);
512      // Action a = KeyBindingManager.Singleton.get(ks);
513      // KeyEvent e = new KeyEvent(definitions,
514      // PRESSED,
515      // 0,
516      // ks.getModifiers(),
517      // ks.getKeyCode(),
518      // ks.getKeyChar());
519      // Performs the action a
520      definitions.processKeyEvent(new KeyEvent(definitions,
521      PRESSED,
522      (new Date()).getTime(),
523      ks.getModifiers(),
524      ks.getKeyCode(), UNDEFINED));
525      // doc.getUndoManager().undo();
526      assertEquals("Should have undone correctly.", "a",
527      doc.getText());*/

528      
529      _log.log("testGranularUndo completed");
530   }
531   
532   
533   public void testActiveAndInactive() {
534     SingleDisplayModel _model = _frame.getModel(); // creates a frame with a new untitled document and makes it active
535

536     DefinitionsPane pane1, pane2;
537     DJDocument doc1, doc2;
538     
539     pane1 = _frame.getCurrentDefPane();
540     doc1 = pane1.getDJDocument();
541     assertTrue("the active pane should have an open definitions document", doc1 instanceof OpenDefinitionsDocument);
542     
543     _model.newFile(); // creates a new untitled document and makes it active
544
pane2 = _frame.getCurrentDefPane();
545     doc2 = pane2.getDJDocument();
546     
547     assertTrue("the active pane should have an open definitions document", doc2 instanceof OpenDefinitionsDocument);
548     
549     _model.setActiveNextDocument(); // makes doc1 active
550
DefinitionsPane pane = _frame.getCurrentDefPane();
551     assertEquals("Confirm that next pane is the other pane", pane1, pane);
552     
553     assertTrue("pane2 should have an open definitions document", doc2 instanceof OpenDefinitionsDocument);
554     assertTrue("pane1 should have an open definitions document", doc1 instanceof OpenDefinitionsDocument);
555     
556     _log.log("testActiveAndInactive completed");
557   }
558   
559   
560   private volatile int _finalCount;
561   private volatile int _finalDocCount;
562   
563   public void testDocumentPaneMemoryLeak() throws InterruptedException JavaDoc, java.io.IOException JavaDoc{
564     _finalCount = 0;
565     _finalDocCount = 0;
566     
567     FinalizationListener<DefinitionsPane> fl = new FinalizationListener<DefinitionsPane>() {
568       public void finalized(FinalizationEvent<DefinitionsPane> e) {
569         _finalCount++;
570 // System.out.println("Finalizing: " + e.getObject().hashCode());
571
}
572     };
573     
574     FinalizationListener<DefinitionsDocument> fldoc = new FinalizationListener<DefinitionsDocument>() {
575       public void finalized(FinalizationEvent<DefinitionsDocument> e) {
576         _finalDocCount++;
577       }
578     };
579     
580     SingleDisplayModel _model = _frame.getModel();
581     _model.newFile().addFinalizationListener(fldoc);
582     _frame.getCurrentDefPane().addFinalizationListener(fl);
583 // System.out.println("Created File: " + _frame.getCurrentDefPane().hashCode());
584
_model.newFile().addFinalizationListener(fldoc);
585     _frame.getCurrentDefPane().addFinalizationListener(fl);
586 // System.out.println("Created File: " + _frame.getCurrentDefPane().hashCode());
587
_model.newFile().addFinalizationListener(fldoc);
588     _frame.getCurrentDefPane().addFinalizationListener(fl);
589 // System.out.println("Created File: " + _frame.getCurrentDefPane().hashCode());
590
_model.newFile().addFinalizationListener(fldoc);
591     _frame.getCurrentDefPane().addFinalizationListener(fl);
592 // System.out.println("Created File: " + _frame.getCurrentDefPane().hashCode());
593
_model.newFile().addFinalizationListener(fldoc);
594     _frame.getCurrentDefPane().addFinalizationListener(fl);
595 // System.out.println("Created File: " + _frame.getCurrentDefPane().hashCode());
596
_model.newFile().addFinalizationListener(fldoc);
597     _frame.getCurrentDefPane().addFinalizationListener(fl);
598 // System.out.println("Created File: " + _frame.getCurrentDefPane().hashCode());
599

600     // all the panes have a listener, so lets close all files
601

602     _model.closeAllFiles();
603     
604     _ct = 0;
605     do { _cleanup(); }
606     while (_finalDocCount != 6 || _finalCount != 6);
607     
608     if (_ct > 1) System.out.println("testDocumentPaneMemoryLeak required " + _ct + " iterations");
609     
610 // System.out.println("Current: " + _frame.getCurrentDefPane().hashCode());
611

612 // System.out.println("Foo");
613
// System.in.read();
614
assertEquals("all the defdocs should have been garbage collected", 6, _finalDocCount);
615     assertEquals("all the panes should have been garbage collected", 6, _finalCount);
616 // System.err.println("_finalCount = " + _finalCount);
617

618     _log.log("testDocumentPaneMemoryLeak completed");
619   }
620   
621   private int _ct = 0;
622   private void _cleanup() {
623     // make sure that the event queue is empty
624
Utilities.clearEventQueue();
625     Utilities.clearEventQueue();
626     System.gc();
627     System.runFinalization();
628     System.gc();
629     _ct++;
630   }
631   
632   // This testcase checks that we do no longer discard Alt keys that would be used to make the {,},[,] chars that the french keyboards has.
633
// Using the Locale did not work, and checking if the key was consumed by the document would only pass on the specific keyboards.
634
// It was therefore unavoidable to add a few lines of code in the original code that is only used for this test case.
635
// These lines were added to the DefinitionsPane.java file.
636
public void testFrenchKeyStrokes() throws IOException JavaDoc, InterruptedException JavaDoc {
637     
638     final DefinitionsPane pane = _frame.getCurrentDefPane(); // pane is NOT null.
639
//KeyEvent ke = new KeyEvent(pane, TYPED, 0, ALT, VK_UNDEF, '{');
640
final KeyEvent JavaDoc ke1 = new KeyEvent JavaDoc(pane, TYPED, 0, 0, VK_UNDEF, 'T');
641     
642     Utilities.invokeAndWait(new Runnable JavaDoc() {
643       public void run() {
644         pane.processKeyEvent(ke1);
645         _frame.validate();
646       }
647     });
648     Utilities.clearEventQueue();
649     
650     assertFalse("The KeyEvent for pressing \"T\" should not involve an Alt Key if this fails we are in trouble!", pane.checkAltKey());
651     
652     final KeyEvent JavaDoc ke2 = new KeyEvent JavaDoc(pane, TYPED, 0, ALT, VK_UNDEF, '{');
653     Utilities.invokeAndWait(new Runnable JavaDoc() {
654       public void run() {
655         pane.processKeyEvent(ke2);
656         _frame.validate();
657       }
658     });
659     Utilities.clearEventQueue();
660         
661     assertTrue("Alt should have been registered and allowed to pass!", pane.checkAltKey());
662     
663     final KeyEvent JavaDoc ke3 = new KeyEvent JavaDoc(pane, TYPED, 0, ALT, VK_UNDEF, '}');
664     Utilities.invokeAndWait(new Runnable JavaDoc() {
665       public void run() {
666         pane.processKeyEvent(ke3);
667         _frame.validate();
668       }
669     });
670     Utilities.clearEventQueue();
671     
672     assertTrue("Alt should have been registered and allowed to pass!", pane.checkAltKey());
673     
674     
675     final KeyEvent JavaDoc ke4 = new KeyEvent JavaDoc(pane, TYPED, 0, ALT, VK_UNDEF, '[');
676     Utilities.invokeAndWait(new Runnable JavaDoc() {
677       public void run() {
678         pane.processKeyEvent(ke4);
679         _frame.validate();
680       }
681     });
682     Utilities.clearEventQueue();
683     
684     assertTrue("Alt should have been registered and allowed to pass!", pane.checkAltKey());
685     
686     final KeyEvent JavaDoc ke5 = new KeyEvent JavaDoc(pane, TYPED, 0, ALT, VK_UNDEF, ']');
687     Utilities.invokeAndWait(new Runnable JavaDoc() {
688       public void run() {
689         pane.processKeyEvent(ke5);
690         _frame.validate();
691       }
692     });
693     Utilities.clearEventQueue();
694     
695     assertTrue("Alt should have been registered and allowed to pass!", pane.checkAltKey());
696     
697     _log.log("testFrenchKeyStrokes completed");
698   }
699
700 /* We had several problems with the backspace deleting 2 chars instead of one.
701  * Recently the problem reoccured in Java version 1.4, but not in 1.5
702  * This shows that we clearly needs a test for this.
703  */

704   public void testBackspace() {
705     final DefinitionsPane defPane = _frame.getCurrentDefPane();
706     final OpenDefinitionsDocument doc = defPane.getOpenDefDocument();
707     _assertDocumentEmpty(doc, "before testing");
708
709     Utilities.invokeAndWait(new Runnable JavaDoc() {
710       public void run() {
711         doc.append("test", null);
712         defPane.setCaretPosition(4);
713         int backspaceCode = KeyEvent.VK_BACK_SPACE;
714         // The following is the sequence of key events for backspace
715
defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, PRESSED, (new Date JavaDoc()).getTime(), 0,
716                                                  backspaceCode, UNDEFINED));
717         defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, RELEASED, (new Date JavaDoc()).getTime(), 0,
718                                                  backspaceCode, UNDEFINED));
719         defPane.processKeyEvent(new KeyEvent JavaDoc(defPane, TYPED, (new Date JavaDoc()).getTime(), 0,
720                                                  VK_UNDEF, '\b'));
721         _frame.validate();
722       }
723     });
724     Utilities.clearEventQueue();
725     
726     _assertDocumentContents(doc, "tes", "Deleting with Backspace went wrong");
727     
728     _log.log("testBackSpace completed");
729   }
730   
731   private volatile String JavaDoc _result;
732   
733   /** Tests the functionality that allows brace matching that displays the line matched in the status bar */
734   public void testMatchBraceText() {
735
736     final DefinitionsPane defPane = _frame.getCurrentDefPane();
737     final OpenDefinitionsDocument doc = defPane.getOpenDefDocument();
738     Utilities.clearEventQueue();
739     
740     _assertDocumentEmpty(doc, "before testing");
741     
742     Utilities.invokeAndWait(new Runnable JavaDoc() {
743       public void run() {
744         doc.append(
745                    "{\n" +
746                    "public class Foo {\n" + //21
747
" private int whatev\n" + //42
748
" private void _method()\n" + //67
749
" {\n" + //71
750
" do stuff\n" + //85
751
" new Object() {\n" + //105
752
" }\n" + //116
753
" }\n" +
754                    "}" +
755                    "}"
756                      , null);
757         
758         defPane.setCaretPosition(4);
759       }
760     });
761     
762     /* Ensure that DocumentListeners complete. */
763     Utilities.invokeAndWait(new Runnable JavaDoc() { public void run() { _result = _frame.getFileNameField(); } });
764     
765     final String JavaDoc fileName = doc.getCompletePath();
766     assertEquals("Should display the document path", fileName, _result);
767     
768     Utilities.invokeAndWait(new Runnable JavaDoc() { public void run() { defPane.setCaretPosition(115); } });
769     // Complete the actions spawned by the preceding command before executing the following command
770
Utilities.invokeAndWait(new Runnable JavaDoc() { public void run() { _result = _frame.getFileNameField(); } });
771     assertEquals("Should display the line matched", "Matches: new Object() {", _result);
772     
773     Utilities.invokeAndWait(new Runnable JavaDoc() { public void run() { defPane.setCaretPosition(102); } });
774     // Complete the actions spawned by the preceding command before executing the following command
775
Utilities.invokeAndWait(new Runnable JavaDoc() { public void run() { _result = _frame.getFileNameField(); } });
776     assertEquals("Should display the document matched", fileName, _result);
777     
778     Utilities.invokeAndWait(new Runnable JavaDoc() { public void run() { defPane.setCaretPosition(119); } });
779     // Complete the actions spawned by the preceding command before executing the following command
780
Utilities.invokeAndWait(new Runnable JavaDoc() { public void run() { _result = _frame.getFileNameField(); } });
781     assertEquals("Should display the line matched", "Matches: private void _method()...{", _result);
782     
783     Utilities.invokeAndWait(new Runnable JavaDoc() { public void run() { defPane.setCaretPosition(121); } });
784     // Complete the actions spawned by the preceding command before executing the following command
785
Utilities.invokeAndWait(new Runnable JavaDoc() { public void run() { _result = _frame.getFileNameField(); } });
786     assertEquals("Should display the line matched", "Matches: public class Foo {", _frame.getFileNameField());
787     
788     Utilities.invokeAndWait(new Runnable JavaDoc() { public void run() { defPane.setCaretPosition(122); } });
789     // Complete the actions spawned by the preceding command before executing the following command
790
Utilities.invokeAndWait(new Runnable JavaDoc() { public void run() { _result = _frame.getFileNameField(); } });
791     assertEquals("Should display only one brace when matching an open brace that is the first character in a line",
792                  "Matches: {", _result);
793     
794     _log.log("testMatchBraceTest completed");
795   }
796
797   class KeyTestListener implements KeyListener JavaDoc {
798     
799     public void keyPressed(KeyEvent JavaDoc e) { DefinitionsPaneTest.fail("Unexpected keypress " + e); }
800     public void keyReleased(KeyEvent JavaDoc e) { DefinitionsPaneTest.fail("Unexpected keyrelease " + e); }
801     public void keyTyped(KeyEvent JavaDoc e) { DefinitionsPaneTest.fail("Unexpected keytyped " + e); }
802     public boolean done() { return true; }
803   }
804 }
805
806
Popular Tags