KickJava   Java API By Example, From Geeks To Geeks.

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


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

45
46 package edu.rice.cs.drjava.ui;
47
48 import java.awt.Component JavaDoc;
49 import java.awt.event.*;
50 import java.awt.datatransfer.Clipboard JavaDoc;
51 import java.awt.datatransfer.DataFlavor JavaDoc;
52 import java.awt.datatransfer.StringSelection JavaDoc;
53 import java.awt.datatransfer.Transferable JavaDoc;
54 import java.awt.datatransfer.UnsupportedFlavorException JavaDoc;
55 import java.awt.Toolkit JavaDoc;
56 import javax.swing.*;
57 import javax.swing.text.*;
58 import java.io.*;
59 import java.util.List JavaDoc;
60
61 import edu.rice.cs.drjava.model.*;
62 import edu.rice.cs.drjava.model.repl.*;
63 import edu.rice.cs.drjava.model.repl.InteractionsDocumentTest.TestBeep;
64 import edu.rice.cs.drjava.DrJava;
65 import edu.rice.cs.drjava.config.OptionConstants;
66 import edu.rice.cs.plt.io.IOUtil;
67 import edu.rice.cs.util.FileOpenSelector;
68 import edu.rice.cs.util.*;
69 import edu.rice.cs.util.text.*;
70 import edu.rice.cs.util.swing.Utilities;
71
72 /** Test functions of MainFrame.
73  * @version $Id: MainFrameTest.java 4075 2007-01-19 21:35:50Z dlsmith $
74  */

75 public final class MainFrameTest extends MultiThreadedTestCase {
76
77   private volatile MainFrame _frame;
78
79   /** A temporary directory */
80   private volatile File _tempDir;
81   
82   /* Flag and lock for signalling when file has been opened and active document changed. */
83   protected volatile boolean _openDone;
84   protected final Object JavaDoc _openLock = new Object JavaDoc();
85   
86   /* Flag and lock for signalling when file has been closed. */
87   protected volatile boolean _closeDone;
88   protected final Object JavaDoc _closeLock = new Object JavaDoc();
89   
90   /* Flag and lock for signalling when compilation is done. */
91   protected volatile boolean _compileDone;
92   protected final Object JavaDoc _compileLock = new Object JavaDoc();
93
94   private final static Log _log = new Log("MainFrameTest.txt", false);
95  
96   /** Setup method for each JUnit test case. */
97   public void setUp() throws Exception JavaDoc {
98     super.setUp();
99     _log.log("super.setUp() for next test completed");
100
101     _frame = new MainFrame();
102     _log.log("new MainFrame() for next test completed");
103     _frame.pack();
104     _log.log("setUp complete for next test");
105   }
106
107   public void tearDown() throws Exception JavaDoc {
108     super.tearDown();
109 // Utilities.invokeAndWait(new Runnable() {
110
// public void run() {
111
_frame.dispose(); // disposes GUI elements of _frame
112
_frame.getModel().dispose(); // explicitly kills the slave JVM
113
_frame = null;
114 // }
115
// });
116
//
117

118   }
119
120   JButton _but;
121   /** Tests that the returned JButton of <code>createManualToolbarButton</code>:
122    * 1. Is disabled upon return.
123    * 2. Inherits the tooltip of the Action parameter <code>a</code>.
124    */

125   public void testCreateManualToolbarButton() {
126     final Action a = new AbstractAction("Test Action") { public void actionPerformed(ActionEvent ae) { } };
127     
128     a.putValue(Action.SHORT_DESCRIPTION, "test tooltip");
129     Utilities.invokeAndWait(new Runnable JavaDoc() { public void run() { _but = _frame._createManualToolbarButton(a); } });
130
131     assertTrue("Returned JButton is enabled.", ! _but.isEnabled());
132     assertEquals("Tooltip text not set.", "test tooltip", _but.getToolTipText());
133     _log.log("testCreateManualToobarButton completed");
134   }
135
136   /** Tests that the current location of a document is equal to the caret location after documents are switched. */
137   public void testDocLocationAfterSwitch() throws BadLocationException {
138     final DefinitionsPane pane = _frame.getCurrentDefPane();
139     OpenDefinitionsDocument doc = pane.getOpenDefDocument();
140     doc.insertString(0, "abcd", null);
141     Utilities.invokeAndWait(new Runnable JavaDoc() { public void run() { pane.setCaretPosition(3); } });
142     Utilities.clearEventQueue(); // Empty the event queue of any asynchronous tasks
143

144     assertEquals("Location of old doc before switch", 3, doc.getCurrentLocation());
145       
146     // Create a new file
147
SingleDisplayModel model = _frame.getModel();
148     final OpenDefinitionsDocument oldDoc = doc;
149     final OpenDefinitionsDocument newDoc = model.newFile();
150
151     // Current pane should be new doc, pos 0
152
DefinitionsPane curPane;
153     OpenDefinitionsDocument curDoc;
154     curPane = _frame.getCurrentDefPane();
155     curDoc = curPane.getOpenDefDocument();//.getDocument();
156
assertEquals("New curr DefPane's document", newDoc, curDoc);
157     assertEquals("Location in new document", 0, newDoc.getCurrentLocation());
158
159     // Switch back to old document
160
model.setActiveNextDocument();
161     assertEquals("Next active doc", oldDoc, model.getActiveDocument());
162                  
163     // Current pane should be old doc, pos 3
164
curPane = _frame.getCurrentDefPane();
165     curDoc = curPane.getOpenDefDocument();//.getDocument();
166
assertEquals("Current document is old document", oldDoc, curDoc);
167     assertEquals("Location of old document", 3, curDoc.getCurrentLocation());
168     _log.log("testDocLocationAfterSwitch completed");
169   }
170
171   
172   private String JavaDoc _data;
173   private String JavaDoc _newData;
174   
175   /** Tests that the clipboard is unmodified after a "clear line" action. */
176   public void testClearLine() throws BadLocationException, UnsupportedFlavorException JavaDoc, IOException {
177     // First, copy some data out of the main document.
178
final DefinitionsPane pane = _frame.getCurrentDefPane();
179     final OpenDefinitionsDocument doc = pane.getOpenDefDocument();
180     final String JavaDoc clipString = "***Clipboard***";
181 // _frame.setVisible(true);
182

183     Utilities.invokeAndWait(new Runnable JavaDoc() {
184       public void run() {
185         
186         try {
187           doc.insertString(0, "abcdefg", null);
188           pane.setCaretPosition(5);
189           
190 // ActionMap actionMap = _pane.getActionMap();
191
// String selString = DefaultEditorKit.selectionEndLineAction;
192
// actionMap.get(selString).actionPerformed(new ActionEvent(this, 0, "SelectionEndLine"));
193
// _frame.cutAction.actionPerformed(new ActionEvent(this, 0, "Cut"));
194

195           _frame.validate();
196 // _frame.paint(_frame.getGraphics());
197
// ActionMap actionMap = _pane.getActionMap();
198
// String selString = DefaultEditorKit.selectionEndLineAction;
199
// actionMap.get(selString).actionPerformed(new ActionEvent(this, 0, "SelectionEndLine"));
200
// pane.setSelectionStart(2);
201
// pane.setSelectionEnd(7);
202

203           // Get a copy of the current clipboard.
204
Clipboard JavaDoc clip = Toolkit.getDefaultToolkit().getSystemClipboard();
205           // Insert valid string in clipboars.
206

207           clip.setContents(new StringSelection JavaDoc(clipString), _frame);
208           Transferable JavaDoc contents = clip.getContents(_frame);
209           
210           // Trigger the Clear Line action from a new position.
211
pane.setCaretPosition(2);
212           _frame.validate();
213 // _frame.paint(_frame.getGraphics());
214

215           _frame._clearLineAction.actionPerformed(new ActionEvent(pane, 0, "Clear Line"));
216 // _frame.paint(_frame.getGraphics());
217
_frame.validate();
218           
219           // Verify that the clipboard contents are still the same.
220
contents = clip.getContents(null);
221           _data = (String JavaDoc) contents.getTransferData(DataFlavor.stringFlavor);
222         }
223         catch(Throwable JavaDoc t) { listenerFail(t.getMessage()); }
224       }
225     });
226     Utilities.clearEventQueue();
227
228     assertEquals("Clipboard contents should be unchanged after Clear Line.", clipString, _data);
229
230     // Verify that the document text is what we expect.
231
assertEquals("Current line of text should be truncated by Clear Line.", "ab", doc.getText());
232     _log.log("testClearLine completed");
233   }
234   
235   /** Tests that the clipboard is modified after a "cut line" action.
236     * NOTE: Commented out for commit because of failures, despite proper behavior in GUI.
237     * This may not work unless ActionEvents are dropped in the event queue
238     */

239   public void testCutLine() throws BadLocationException {
240     // First, copy some data out of the main document.
241

242     final DefinitionsPane pane = _frame.getCurrentDefPane();
243     final OpenDefinitionsDocument doc = pane.getOpenDefDocument();
244 // _frame.setVisible(true);
245
Utilities.invokeAndWait(new Runnable JavaDoc() {
246       public void run() {
247         
248         try {
249           doc.insertString(0, "abcdefg", null);
250           pane.setCaretPosition(5);
251           _frame.validate();
252 // _frame.paint(_frame.getGraphics());
253
// ActionMap actionMap = _pane.getActionMap();
254
// String selString = DefaultEditorKit.selectionEndLineAction;
255
// actionMap.get(selString).actionPerformed(new ActionEvent(pane, 0, "SelectionEndLine"));
256
pane.setSelectionStart(2);
257           pane.setSelectionEnd(7);
258           _frame.validate();
259           pane.cut();
260 // _frame.cutAction.actionPerformed(new ActionEvent(pane, 0, "Cut"));
261

262           // Get a copy of the current clipboard.
263

264           // Trigger the Cut Line action from a new position.
265
// _pane.setCaretPosition(2);
266
_frame.validate();
267 // _frame.paint(_frame.getGraphics());
268

269 // _frame._cutLineAction.actionPerformed(new ActionEvent(this, 0, "Cut Line"));
270
// _frame.dispatchEvent(new ActionEvent(this, 0, "Cut Line"));
271

272           // Verify that the clipboard contents are what we expect.
273
Clipboard JavaDoc clip = Toolkit.getDefaultToolkit().getSystemClipboard();
274           Transferable JavaDoc contents = clip.getContents(null);
275           _data = (String JavaDoc) contents.getTransferData(DataFlavor.stringFlavor);
276         }
277         catch(Throwable JavaDoc t) { listenerFail(t.getMessage()); }
278       }
279     });
280     Utilities.clearEventQueue();
281     assertEquals("Clipboard contents should be changed after Cut Line.", "cdefg", _data);
282     
283     // Verify that the document text is what we expect.
284
assertEquals("Current line of text should be truncated by Cut Line.", "ab", doc.getText());
285     _log.log("testCutLine completed");
286   }
287
288
289   /** Make sure that the InteractionsPane is displaying the correct InteractionsDocument. (SourceForge bug #681547)
290     * Also make sure this document cannot be edited before the prompt.
291     */

292   public void testCorrectInteractionsDocument() throws EditDocumentException {
293     InteractionsPane pane = _frame.getInteractionsPane();
294     final SingleDisplayModel model = _frame.getModel();
295     InteractionsDJDocument doc = model.getSwingInteractionsDocument();
296
297     // Make the test silent
298
Utilities.invokeAndWait(new Runnable JavaDoc() {
299       public void run() {
300         model.getInteractionsModel().getDocument().setBeep(new TestBeep());
301       }
302     });
303     Utilities.clearEventQueue();
304
305     // Test for strict == equality
306
assertTrue("UI's int. doc. should equals Model's int. doc.", pane.getDocument() == doc);
307
308     int origLength = doc.getLength();
309     doc.insertText(1, "typed text", InteractionsDocument.DEFAULT_STYLE);
310     Utilities.clearEventQueue();
311     assertEquals("Document should not have changed.", origLength, doc.getLength());
312     _log.log("testCorrectInteractionsDocument completed");
313   }
314
315   /** Tests that undoing/redoing a multi-line indent will restore the caret position. */
316   public void testMultilineIndentAfterScroll() throws BadLocationException, InterruptedException JavaDoc {
317     String JavaDoc text =
318       "public class stuff {\n" +
319       "private int _int;\n" +
320       "private Bar _bar;\n" +
321       "public void foo() {\n" +
322       "_bar.baz(_int);\n" +
323       "}\n" +
324       "}\n";
325     
326     String JavaDoc indented =
327       "public class stuff {\n" +
328       " private int _int;\n" +
329       " private Bar _bar;\n" +
330       " public void foo() {\n" +
331       " _bar.baz(_int);\n" +
332       " }\n" +
333       "}\n";
334     
335     final int newPos = 20;
336     
337     final DefinitionsPane pane = _frame.getCurrentDefPane();
338     final OpenDefinitionsDocument doc = pane.getOpenDefDocument();
339     
340     DrJava.getConfig().setSetting(OptionConstants.INDENT_LEVEL, new Integer JavaDoc(2));
341     doc.append(text, null);
342     Utilities.invokeAndWait(new Runnable JavaDoc() {
343       public void run() {
344         pane.setCaretPosition(0);
345         pane.endCompoundEdit();
346       }
347     });
348     
349     Utilities.clearEventQueue();
350     assertEquals("Should have inserted correctly.", text, doc.getText());
351     
352     doc.acquireWriteLock();
353     
354     try { doc.indentLines(0, doc.getLength()); }
355     finally { doc.releaseWriteLock(); }
356     
357     assertEquals("Should have indented.", indented, doc.getText());
358     
359     final int oldPos = pane.getCaretPosition();
360 // System.err.println("Old position is: " + oldPos);
361

362     Utilities.invokeAndWait(new Runnable JavaDoc() {
363       public void run() {
364         pane.setCaretPosition(newPos);
365 // System.err.println("New position is: " + pane.getCaretPosition());
366
}
367     });
368     Utilities.clearEventQueue();
369     
370     // Moving this statement to the event thread breaks "Undo should have restored ..." Why?
371
doc.getUndoManager().undo();
372     
373     assertEquals("Should have undone.", text, doc.getText());
374     
375     int rePos = pane.getCaretPosition();
376 // System.err.println("Restored position is: " + rePos);
377
assertEquals("Undo should have restored caret position.", oldPos, rePos);
378     
379     Utilities.invokeAndWait(new Runnable JavaDoc() {
380       public void run() {
381         pane.setCaretPosition(newPos);
382         doc.getUndoManager().redo();
383       }
384     });
385     Utilities.clearEventQueue();
386     
387     assertEquals("redo",indented, doc.getText());
388     assertEquals("redo restores caret position", oldPos, pane.getCaretPosition());
389     _log.log("testMultilineIndentAfterScroll completed");
390   }
391   
392   JScrollPane _pane1, _pane2;
393   DefinitionsPane _defPane1, _defPane2;
394
395   /** Ensure that a document's editable status is set appropriately throughout the compile process. Since the behavior
396    * is interesting only when the model changes its active document, that's what this test looks most like.
397    */

398   public void testGlassPaneEditableState() {
399     SingleDisplayModel model = _frame.getModel();
400
401     final OpenDefinitionsDocument doc1 = model.newFile();
402     final OpenDefinitionsDocument doc2 = model.newFile();
403
404     // doc2 is now active
405
Utilities.invokeAndWait(new Runnable JavaDoc() {
406       public void run() {
407
408         _pane1 = _frame._createDefScrollPane(doc1);
409         _pane2 = _frame._createDefScrollPane(doc2);
410         
411         _defPane1 = (DefinitionsPane) _pane1.getViewport().getView();
412         _defPane2 = (DefinitionsPane) _pane2.getViewport().getView();
413         
414         _frame._switchDefScrollPane();
415       }
416     });
417     
418     Utilities.clearEventQueue(); // Execute all pending asynchronous tasks;
419

420     assertTrue("Start: defPane1", _defPane1.isEditable());
421     assertTrue("Start: defPane2", _defPane2.isEditable());
422     
423     Utilities.invokeAndWait(new Runnable JavaDoc() { public void run() { _frame.hourglassOn(); } });
424     Utilities.clearEventQueue();
425     
426     assertTrue("Glass on: defPane1", _defPane1.isEditable());
427     assertTrue("Glass on: defPane2",(! _defPane2.isEditable()));
428     model.setActiveDocument(doc1);
429             
430     Utilities.invokeAndWait(new Runnable JavaDoc() { public void run() { _frame._switchDefScrollPane(); } });
431     Utilities.clearEventQueue();
432     
433     assertTrue("Doc Switch: defPane1",(! _defPane1.isEditable()));
434     assertTrue("Doc Switch: defPane2", _defPane2.isEditable());
435     
436     Utilities.invokeAndWait(new Runnable JavaDoc() { public void run() { _frame.hourglassOff(); } });
437     Utilities.clearEventQueue();
438     
439     assertTrue("End: defPane1", _defPane1.isEditable());
440     assertTrue("End: defPane2", _defPane2.isEditable());
441     _log.log("testGlassPaneEditableState completed");
442   }
443
444   private KeyEvent makeFindKeyEvent(Component JavaDoc c, long when) {
445     return new KeyEvent(c, KeyEvent.KEY_PRESSED, when, KeyEvent.CTRL_MASK, KeyEvent.VK_F, 'F');
446   }
447   
448   /** Ensure that all key events are disabled when the glass pane is up. */
449   public void testGlassPaneHidesKeyEvents() {
450     SingleDisplayModel model = _frame.getModel();
451
452     final OpenDefinitionsDocument doc1 = model.newFile();
453     final OpenDefinitionsDocument doc2 = model.newFile();
454
455     // doc2 is now active
456
Utilities.invokeAndWait(new Runnable JavaDoc() {
457       public void run() {
458         _pane1 = _frame._createDefScrollPane(doc1);
459         _pane2 = _frame._createDefScrollPane(doc2);
460         _defPane1 = (DefinitionsPane) _pane1.getViewport().getView();
461         _defPane2 = (DefinitionsPane) _pane2.getViewport().getView();
462         _frame.validate();
463         _frame.hourglassOn();
464         _defPane1.processKeyEvent(makeFindKeyEvent(_defPane1, 70));
465         _frame.validate();
466       }
467     });
468     Utilities.clearEventQueue();
469     
470     assertTrue("the find replace dialog should not come up", ! _frame.getFindReplaceDialog().isDisplayed());
471     Utilities.invokeAndWait(new Runnable JavaDoc() {
472       public void run() {
473         _frame.getInteractionsPane().processKeyEvent(makeFindKeyEvent(_frame.getInteractionsPane(), 0));
474         _frame.validate();
475       }
476     });
477     Utilities.clearEventQueue();
478     
479     assertTrue("the find replace dialog should not come up", ! _frame.getFindReplaceDialog().isDisplayed());
480
481     Utilities.invokeAndWait(new Runnable JavaDoc() { public void run() { _frame.hourglassOff(); } });
482     _log.log("testGlassPaneHidesKeyEvents completed");
483   }
484
485   
486   /** Tests that the save button does not set itself as enabled immediately after opening a file. */
487   public void testSaveButtonEnabled() throws IOException {
488     String JavaDoc user = System.getProperty("user.name");
489     _tempDir = IOUtil.createAndMarkTempDirectory("DrJava-test-" + user, "");
490     File forceOpenClass1_file = new File(_tempDir, "ForceOpenClass1.java");
491     String JavaDoc forceOpenClass1_string =
492       "public class ForceOpenClass1 {\n" +
493       " ForceOpenClass2 class2;\n" +
494       " ForceOpenClass3 class3;\n\n" +
495       " public ForceOpenClass1() {\n" +
496       " class2 = new ForceOpenClass2();\n" +
497       " class3 = new ForceOpenClass3();\n" +
498       " }\n" +
499       "}";
500     
501     IOUtil.writeStringToFile(forceOpenClass1_file, forceOpenClass1_string);
502     forceOpenClass1_file.deleteOnExit();
503     
504     //_frame.setVisible(true);
505
Utilities.invokeAndWait(new Runnable JavaDoc() {
506       public void run() {
507         _frame.pack();
508         _frame.open(new FileOpenSelector() {
509           public File[] getFiles() {
510             File[] return_me = new File[1];
511             return_me[0] = new File(_tempDir, "ForceOpenClass1.java");
512             return return_me;
513           }
514         });
515       }
516     });
517     Utilities.clearEventQueue();
518     
519     assertTrue("the save button should not be enabled after opening a document", !_frame.saveEnabledHuh());
520     _log.log("testSaveButtonEnabled completed");
521   }
522   
523   /** A Test to guarantee that the Dancing UI bug will not rear its ugly head again.
524    * Basically, add a component listener to the leftComponent of _docSplitPane and
525    * make certain its size does not change while compiling a class which depends on
526    * another class.
527    */

528   public void testDancingUIFileOpened() throws IOException {
529     //System.out.println("DEBUG: Entering messed up test");
530
/** Maybe this sequence of calls should be incorporated into one function createTestDir(), which would get
531      * the username and create the temporary directory. Only sticky part is deciding where to put it, in FileOps
532      * maybe?
533      */

534     
535     _log.log("Starting testingDancingUIFileOpened");
536     
537     final GlobalModel _model = _frame.getModel();
538     
539      String JavaDoc user = System.getProperty("user.name");
540      _tempDir = IOUtil.createAndMarkTempDirectory("DrJava-test-" + user, "");
541
542      File forceOpenClass1_file = new File(_tempDir, "ForceOpenClass1.java");
543      String JavaDoc forceOpenClass1_string =
544        "public class ForceOpenClass1 {\n" +
545        " ForceOpenClass2 class2;\n" +
546        " ForceOpenClass3 class3;\n\n" +
547        " public ForceOpenClass1() {\n" +
548        " class2 = new ForceOpenClass2();\n" +
549        " class3 = new ForceOpenClass3();\n" +
550        " }\n" +
551        "}";
552
553      File forceOpenClass2_file = new File(_tempDir, "ForceOpenClass2.java");
554      String JavaDoc forceOpenClass2_string =
555        "public class ForceOpenClass2 {\n" +
556        " inx x = 4;\n" +
557        "}";
558
559      File forceOpenClass3_file = new File(_tempDir, "ForceOpenClass3.java");
560      String JavaDoc forceOpenClass3_string =
561        "public class ForceOpenClass3 {\n" +
562        " String s = \"asf\";\n" +
563        "}";
564
565      IOUtil.writeStringToFile(forceOpenClass1_file, forceOpenClass1_string);
566      IOUtil.writeStringToFile(forceOpenClass2_file, forceOpenClass2_string);
567      IOUtil.writeStringToFile(forceOpenClass3_file, forceOpenClass3_string);
568      forceOpenClass1_file.deleteOnExit();
569      forceOpenClass2_file.deleteOnExit();
570      forceOpenClass3_file.deleteOnExit();
571      
572      _log.log("DancingUIFileOpened Set Up");
573
574      //_frame.setVisible(true);
575

576      // set up listeners and signal flags
577

578      final ComponentAdapter listener = new ComponentAdapter() {
579        public void componentResized(ComponentEvent event) {
580          _testFailed = true;
581          fail("testDancingUI: Open Documents List danced!");
582        }
583      };
584      final SingleDisplayModelFileOpenedListener openListener = new SingleDisplayModelFileOpenedListener();
585      final SingleDisplayModelCompileListener compileListener = new SingleDisplayModelCompileListener();
586      
587      _openDone = false;
588
589      Utilities.invokeAndWait(new Runnable JavaDoc() {
590       public void run() {
591 // _frame.setVisible(true);
592
_frame.pack();
593         _frame.addComponentListenerToOpenDocumentsList(listener);
594       }
595      });
596      Utilities.clearEventQueue();
597      
598      _model.addListener(openListener);
599      
600      _log.log("opening file");
601      
602      Utilities.invokeLater(new Runnable JavaDoc() {
603        public void run() {
604         _frame.open(new FileOpenSelector() {
605            public File[] getFiles() {
606              File[] return_me = new File[1];
607              return_me[0] = new File(_tempDir, "ForceOpenClass1.java");
608              return return_me;
609            }
610          });
611        }
612      });
613      Utilities.clearEventQueue();
614      
615      /* wait until file has been open and active document changed. */
616      synchronized(_openLock) {
617        try { while (! _openDone) _openLock.wait(); }
618        catch(InterruptedException JavaDoc e) { fail(e.toString()); }
619      }
620      
621      _model.removeListener(openListener);
622      
623      _log.log("File opened");
624      
625      _compileDone = false;
626      _model.addListener(compileListener);
627      
628      // save and compile the new file asynchronously
629

630      Utilities.invokeLater(new Runnable JavaDoc() {
631        public void run() {
632          _log.log("saving all files");
633          _frame._saveAll();
634          _log.log("invoking compileAll action");
635          _frame.getCompileAllButton().doClick();
636        }
637      });
638      Utilities.clearEventQueue();
639
640      synchronized(_compileLock) {
641        try { while (! _compileDone) _compileLock.wait(); }
642        catch(InterruptedException JavaDoc e) { fail(e.toString()); }
643      }
644      _log.log("File saved and compiled");
645      
646      if (! IOUtil.deleteRecursively(_tempDir))
647        System.out.println("Couldn't fully delete directory " + _tempDir.getAbsolutePath() + "\nDo it by hand.\n");
648    
649      _log.log("testDancingUIFileOpened completed");
650   }
651
652   /** A Test to guarantee that the Dancing UI bug will not rear its ugly head again. Basically, add a component listener
653    * to the leftComponent of _docSplitPane and make certain its size does not change while closing an
654    * OpenDefinitionsDocument outside the event thread.
655    */

656   public void testDancingUIFileClosed() throws IOException {
657     /** Maybe this sequence of calls should be incorporated into one function createTestDir(), which would get the
658      * username and create the temporary directory. Only sticky part is deciding where to put it, in FileOps maybe?
659      */

660     String JavaDoc user = System.getProperty("user.name");
661     _tempDir = IOUtil.createAndMarkTempDirectory("DrJava-test-" + user, "");
662     File forceOpenClass1_file = new File(_tempDir, "ForceOpenClass1.java");
663     String JavaDoc forceOpenClass1_string =
664       "public class ForceOpenClass1 {\n" +
665       " ForceOpenClass2 class2;\n" +
666       " ForceOpenClass3 class3;\n\n" +
667       " public ForceOpenClass1() {\n" +
668       " class2 = new ForceOpenClass2();\n" +
669       " class3 = new ForceOpenClass3();\n" +
670       " }\n" +
671       "}";
672     
673     IOUtil.writeStringToFile(forceOpenClass1_file, forceOpenClass1_string);
674     forceOpenClass1_file.deleteOnExit();
675     
676     final ComponentAdapter listener = new ComponentAdapter() {
677       public void componentResized(ComponentEvent event) {
678         _testFailed = true;
679         fail("testDancingUI: Open Documents List danced!");
680       }
681     };
682     final SingleDisplayModelFileClosedListener closeListener = new SingleDisplayModelFileClosedListener();
683     
684     _closeDone = false;
685     Utilities.invokeAndWait(new Runnable JavaDoc() {
686       public void run() {
687 // _frame.setVisible(true);
688
_frame.pack();
689         _frame.addComponentListenerToOpenDocumentsList(listener);
690         _frame.open(new FileOpenSelector() {
691           public File[] getFiles() {
692             File[] return_me = new File[1];
693             return_me[0] = new File(_tempDir, "ForceOpenClass1.java");
694             return return_me;
695           }
696         });
697         _frame.getModel().addListener(closeListener);
698       }
699     });
700     Utilities.clearEventQueue();
701            
702     /* Asynchronously close the file */
703     Utilities.invokeLater(new Runnable JavaDoc() {
704       public void run() { _frame.getCloseButton().doClick(); }
705     });
706     
707     _log.log("Waiting for file closing");
708     
709     synchronized(_closeLock) {
710       try { while (! _closeDone) _closeLock.wait(); }
711       catch(InterruptedException JavaDoc e) { fail(e.toString()); }
712     }
713     
714     if (! IOUtil.deleteRecursively(_tempDir)) {
715       System.out.println("Couldn't fully delete directory " + _tempDir.getAbsolutePath() +
716                          "\nDo it by hand.\n");
717     }
718     _log.log("testDancingUIFileClosed completed");
719   }
720
721   /** A CompileListener for SingleDisplayModel (instead of GlobalModel) */
722   class SingleDisplayModelCompileListener extends GlobalModelTestCase.TestListener implements GlobalModelListener {
723
724     @Override JavaDoc public void compileStarted() { }
725
726     /** Just notify when the compile has ended */
727     @Override JavaDoc public void compileEnded(File workDir, List JavaDoc<? extends File> excludedFiles) {
728       synchronized(_compileLock) {
729         _compileDone = true;
730         _compileLock.notify();
731       }
732     }
733
734     @Override JavaDoc public void fileOpened(OpenDefinitionsDocument doc) { }
735     @Override JavaDoc public void activeDocumentChanged(OpenDefinitionsDocument active) { }
736   }
737   
738    /** A FileClosedListener for SingleDisplayModel (instead of GlobalModel) */
739   class SingleDisplayModelFileOpenedListener extends GlobalModelTestCase.TestListener implements GlobalModelListener {
740     
741     @Override JavaDoc public void fileClosed(OpenDefinitionsDocument doc) { }
742
743     @Override JavaDoc public void fileOpened(OpenDefinitionsDocument doc) { }
744   
745     @Override JavaDoc public void newFileCreated(OpenDefinitionsDocument doc) { }
746     @Override JavaDoc public void activeDocumentChanged(OpenDefinitionsDocument doc) {
747         synchronized(_openLock) {
748         _openDone = true;
749         _openLock.notify();
750       }
751     }
752   }
753
754   /** A FileClosedListener for SingleDisplayModel (instead of GlobalModel) */
755   class SingleDisplayModelFileClosedListener extends GlobalModelTestCase.TestListener implements GlobalModelListener {
756
757     @Override JavaDoc public void fileClosed(OpenDefinitionsDocument doc) {
758       synchronized(_closeLock) {
759         _closeDone = true;
760         _closeLock.notify();
761       }
762     }
763
764     @Override JavaDoc public void fileOpened(OpenDefinitionsDocument doc) { }
765     @Override JavaDoc public void newFileCreated(OpenDefinitionsDocument doc) { }
766     @Override JavaDoc public void activeDocumentChanged(OpenDefinitionsDocument active) { }
767   }
768
769   /** Create a new temporary file in _tempDir. */
770   protected File tempFile(String JavaDoc fileName) throws IOException {
771     File f = File.createTempFile(fileName, ".java", _tempDir).getCanonicalFile();
772     f.deleteOnExit();
773     return f;
774   }
775   
776   /** Tests that "go to file under cursor" works if unique. */
777   public void testGotoFileUnderCursor() throws IOException {
778 // Utilities.show("Running testGotoFileUnderCursor");
779
String JavaDoc user = System.getProperty("user.name");
780     _tempDir = IOUtil.createAndMarkTempDirectory("DrJava-test-" + user, "");
781
782     final File goto1_file = new File(_tempDir, "GotoFileUnderCursor1.java");
783     String JavaDoc goto1_string = "GotoFileUnderCursorTest";
784     IOUtil.writeStringToFile(goto1_file, goto1_string);
785     goto1_file.deleteOnExit();
786
787     final File goto2_file = new File(_tempDir, "GotoFileUnderCursorTest.java");
788     String JavaDoc goto2_string = "GotoFileUnderCursor1";
789     IOUtil.writeStringToFile(goto2_file, goto2_string);
790     goto2_file.deleteOnExit();
791
792     Utilities.invokeAndWait(new Runnable JavaDoc() {
793       public void run() {
794         _frame.pack();
795         _frame.open(new FileOpenSelector() {
796           public File[] getFiles() { return new File[] { goto1_file, goto2_file }; }
797         });
798       }
799     });
800     
801     Utilities.invokeAndWait(new Runnable JavaDoc() {
802       public void run() {
803         _frame.initGotoFileDialog();
804         _frame._gotoFileDialog.addWindowListener(new WindowListener() {
805           public void windowActivated(WindowEvent e) { throw new RuntimeException JavaDoc("Should not activate _gotoFileDialog"); }
806           public void windowClosed(WindowEvent e) { throw new RuntimeException JavaDoc("Should not close _gotoFileDialog"); }
807           public void windowClosing(WindowEvent e) { throw new RuntimeException JavaDoc("Should not be closing _gotoFileDialog"); }
808           public void windowDeactivated(WindowEvent e) { throw new RuntimeException JavaDoc("Should not deactivate _gotoFileDialog"); }
809           public void windowDeiconified(WindowEvent e) { throw new RuntimeException JavaDoc("Should not deiconify _gotoFileDialog"); }
810           public void windowIconified(WindowEvent e) { throw new RuntimeException JavaDoc("Should not iconify _gotoFileDialog"); }
811           public void windowOpened(WindowEvent e) { throw new RuntimeException JavaDoc("Should not open _gotoFileDialog"); }
812         });
813       }});
814     
815     Utilities.clearEventQueue();
816     SingleDisplayModel model = _frame.getModel();
817     OpenDefinitionsDocument goto1_doc = model.getDocumentForFile(goto1_file);
818     OpenDefinitionsDocument goto2_doc = model.getDocumentForFile(goto2_file);
819     model.setActiveDocument(model.getDocumentForFile(goto1_file));
820     assertEquals("Document contains the incorrect text", goto1_string, model.getActiveDocument().getText());
821     
822     Utilities.invokeAndWait(new Runnable JavaDoc() {
823       public void run() { _frame._gotoFileUnderCursor(); }
824     });
825     
826     Utilities.clearEventQueue();
827     assertEquals("Incorrect active document; did not go to?", goto2_doc, model.getActiveDocument());
828     
829     Utilities.invokeAndWait(new Runnable JavaDoc() {
830       public void run() { _frame._gotoFileUnderCursor(); }
831     });
832     
833     Utilities.clearEventQueue();
834     assertEquals("Incorrect active document; did not go to?", goto1_doc, model.getActiveDocument());
835     
836     _log.log("gotoFileUnderCursor completed");
837   }
838   
839   /** Tests that "go to file under cursor" works if unique after appending ".java" */
840   public void testGotoFileUnderCursorAppendJava() throws IOException {
841     String JavaDoc user = System.getProperty("user.name");
842     _tempDir = IOUtil.createAndMarkTempDirectory("DrJava-test-" + user, "");
843
844     final File goto1_file = new File(_tempDir, "GotoFileUnderCursor2Test.java");
845     String JavaDoc goto1_string = "GotoFileUnderCursor2";
846     IOUtil.writeStringToFile(goto1_file, goto1_string);
847     goto1_file.deleteOnExit();
848
849     final File goto2_file = new File(_tempDir, "GotoFileUnderCursor2.java");
850     String JavaDoc goto2_string = "GotoFileUnderCursor2Test";
851     IOUtil.writeStringToFile(goto2_file, goto2_string);
852     goto2_file.deleteOnExit();
853
854     Utilities.invokeAndWait(new Runnable JavaDoc() {
855       public void run() {
856         _frame.pack();
857         _frame.open(new FileOpenSelector() {
858           public File[] getFiles() {
859               return new File[] { goto1_file, goto2_file };
860           }
861         });
862       }
863     });
864     
865     Utilities.clearEventQueue();
866     
867     Utilities.invokeAndWait(new Runnable JavaDoc() {
868       public void run() {
869         _frame.initGotoFileDialog();
870         _frame._gotoFileDialog.addWindowListener(new WindowListener() {
871           public void windowActivated(WindowEvent e) { throw new RuntimeException JavaDoc("Should not activate _gotoFileDialog"); }
872           public void windowClosed(WindowEvent e) { throw new RuntimeException JavaDoc("Should not close _gotoFileDialog"); }
873           public void windowClosing(WindowEvent e) { throw new RuntimeException JavaDoc("Should not be closing _gotoFileDialog"); }
874           public void windowDeactivated(WindowEvent e) { throw new RuntimeException JavaDoc("Should not deactivate _gotoFileDialog"); }
875           public void windowDeiconified(WindowEvent e) { throw new RuntimeException JavaDoc("Should not deiconify _gotoFileDialog"); }
876           public void windowIconified(WindowEvent e) { throw new RuntimeException JavaDoc("Should not iconify _gotoFileDialog"); }
877           public void windowOpened(WindowEvent e) { throw new RuntimeException JavaDoc("Should not open _gotoFileDialog"); }
878         });
879       }});
880      
881     Utilities.clearEventQueue();
882     
883     SingleDisplayModel model = _frame.getModel();
884     OpenDefinitionsDocument goto1_doc = model.getDocumentForFile(goto1_file);
885     OpenDefinitionsDocument goto2_doc = model.getDocumentForFile(goto2_file);
886     model.setActiveDocument(model.getDocumentForFile(goto1_file));
887     assertEquals("Document contains the incorrect text", goto1_string, model.getActiveDocument().getText());
888     
889     Utilities.invokeAndWait(new Runnable JavaDoc() {
890       public void run() { _frame._gotoFileUnderCursor(); }
891     });
892     
893     Utilities.clearEventQueue();
894     
895     assertEquals("Incorrect active document; did not go to?", goto2_doc, model.getActiveDocument());
896     
897     Utilities.invokeAndWait(new Runnable JavaDoc() {
898       public void run() { _frame._gotoFileUnderCursor(); }
899     });
900     
901     Utilities.clearEventQueue();
902     assertEquals("Incorrect active document; did not go to?", goto1_doc, model.getActiveDocument());
903     
904     _log.log("gotoFileUnderCursorAppendJava completed");
905   }
906   
907   /** Tests that "go to file under cursor" displays the dialog if choice is not unique */
908   public void testGotoFileUnderCursorShowDialog() throws IOException {
909 // Utilities.show("Running testGotoFileUnderCursorShowDialog()");
910
String JavaDoc user = System.getProperty("user.name");
911     _tempDir = IOUtil.createAndMarkTempDirectory("DrJava-test-" + user, "");
912
913     final File goto1_file = new File(_tempDir, "GotoFileUnderCursor3.java");
914     String JavaDoc goto1_string = "GotoFileUnderCursor";
915     IOUtil.writeStringToFile(goto1_file, goto1_string);
916     goto1_file.deleteOnExit();
917
918     final File goto2_file = new File(_tempDir, "GotoFileUnderCursor4.java");
919     String JavaDoc goto2_string = "GotoFileUnderCursor3";
920     IOUtil.writeStringToFile(goto2_file, goto2_string);
921     goto2_file.deleteOnExit();
922
923     Utilities.invokeAndWait(new Runnable JavaDoc() {
924       public void run() {
925         _frame.pack();
926         _frame.open(new FileOpenSelector() {
927           public File[] getFiles() { return new File[] { goto1_file, goto2_file }; }
928         });
929       }
930     });
931     
932     final int[] count = new int[2];
933     Utilities.invokeAndWait(new Runnable JavaDoc() {
934       public void run() {
935         _frame.initGotoFileDialog();
936         _frame._gotoFileDialog.addWindowListener(new WindowListener() {
937           public void windowActivated(WindowEvent e) { ++count[0]; }
938           public void windowClosed(WindowEvent e) { throw new RuntimeException JavaDoc("Should not close _gotoFileDialog"); }
939           public void windowClosing(WindowEvent e) { throw new RuntimeException JavaDoc("Should not be closing _gotoFileDialog"); }
940           public void windowDeactivated(WindowEvent e) { /* throw new RuntimeException("Should not deactivate _gotoFileDialog"); */ }
941           public void windowDeiconified(WindowEvent e) { throw new RuntimeException JavaDoc("Should not deiconify _gotoFileDialog"); }
942           public void windowIconified(WindowEvent e) { throw new RuntimeException JavaDoc("Should not iconify _gotoFileDialog"); }
943           public void windowOpened(WindowEvent e) { ++count[1]; }
944         });
945       }
946     });
947     
948     Utilities.clearEventQueue();
949                             
950     SingleDisplayModel model = _frame.getModel();
951     OpenDefinitionsDocument goto1_doc = model.getDocumentForFile(goto1_file);
952     OpenDefinitionsDocument goto2_doc = model.getDocumentForFile(goto2_file);
953     model.setActiveDocument(model.getDocumentForFile(goto1_file));
954
955     assertEquals("Document contains the incorrect text", goto1_string, model.getActiveDocument().getText());
956     
957     Utilities.invokeAndWait(new Runnable JavaDoc() { public void run() { _frame._gotoFileUnderCursor(); } });
958     Utilities.clearEventQueue(); // wait for any asynchronous actions to complete
959

960     
961      /* The following test was commented out before test following it was. It presumably fails even if
962       * the "MainFrame.this.isVisible()" test mentioned below is removed from _gotoFileUnderCursor */

963 // assertEquals("Did not activate _gotoFileDialog", 1, count[0]);
964
/* The following test was commented out after suppressing this display when _frame is not visible. If it is
965      * uncommented, then the "MainFrame.this.isVisible()" test in _gotoFileDialog must be removed. */

966 // assertEquals("Did not open _gotoFileDialog", 1, count[1]);
967

968     _log.log("gotoFileUnderCursorShowDialog completed");
969   }
970 }
971
Popular Tags