JAL-3253 temporary branch SwingJS upgrade with testNG fixes Java 8
[jalview.git] / test / jalview / project / Jalview2xmlTests.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.project;
22
23 import static org.testng.Assert.assertEquals;
24 import static org.testng.Assert.assertFalse;
25 import static org.testng.Assert.assertNotNull;
26 import static org.testng.Assert.assertNull;
27 import static org.testng.Assert.assertSame;
28 import static org.testng.Assert.assertTrue;
29
30 import jalview.analysis.scoremodels.SimilarityParams;
31 import jalview.api.AlignViewportI;
32 import jalview.api.AlignmentViewPanel;
33 import jalview.api.FeatureColourI;
34 import jalview.api.ViewStyleI;
35 import jalview.bin.Jalview;
36 import jalview.datamodel.AlignmentAnnotation;
37 import jalview.datamodel.AlignmentI;
38 import jalview.datamodel.HiddenSequences;
39 import jalview.datamodel.PDBEntry;
40 import jalview.datamodel.PDBEntry.Type;
41 import jalview.datamodel.SequenceCollectionI;
42 import jalview.datamodel.SequenceFeature;
43 import jalview.datamodel.SequenceGroup;
44 import jalview.datamodel.SequenceI;
45 import jalview.datamodel.features.FeatureMatcher;
46 import jalview.datamodel.features.FeatureMatcherSet;
47 import jalview.datamodel.features.FeatureMatcherSetI;
48 import jalview.gui.AlignFrame;
49 import jalview.gui.AlignViewport;
50 import jalview.gui.AlignmentPanel;
51 import jalview.gui.Desktop;
52 import jalview.gui.FeatureRenderer;
53 import jalview.gui.JvOptionPane;
54 import jalview.gui.PCAPanel;
55 import jalview.gui.PopupMenu;
56 import jalview.gui.SliderPanel;
57 import jalview.io.DataSourceType;
58 import jalview.io.FileFormat;
59 import jalview.io.FileLoader;
60 import jalview.io.Jalview2xmlBase;
61 import jalview.renderer.ResidueShaderI;
62 import jalview.schemes.AnnotationColourGradient;
63 import jalview.schemes.BuriedColourScheme;
64 import jalview.schemes.ColourSchemeI;
65 import jalview.schemes.ColourSchemeProperty;
66 import jalview.schemes.FeatureColour;
67 import jalview.schemes.JalviewColourScheme;
68 import jalview.schemes.RNAHelicesColour;
69 import jalview.schemes.StrandColourScheme;
70 import jalview.schemes.TCoffeeColourScheme;
71 import jalview.structure.StructureImportSettings;
72 import jalview.structure.StructureMapping;
73 import jalview.util.matcher.Condition;
74 import jalview.viewmodel.AlignmentViewport;
75
76 import java.awt.Color;
77 import java.io.File;
78 import java.io.IOException;
79 import java.util.ArrayList;
80 import java.util.HashMap;
81 import java.util.List;
82 import java.util.Map;
83
84 import javax.swing.JInternalFrame;
85
86 import org.testng.Assert;
87 import org.testng.AssertJUnit;
88 import org.testng.annotations.BeforeClass;
89 import org.testng.annotations.Test;
90
91 @Test(singleThreaded = true)
92 public class Jalview2xmlTests extends Jalview2xmlBase
93 {
94
95   @BeforeClass(alwaysRun = true)
96   public void setUpJalviewSynchonization()
97   {
98     Jalview.setSynchronous(true);
99   }
100
101   @Override
102   @BeforeClass(alwaysRun = true)
103   public void setUpJvOptionPane()
104   {
105     JvOptionPane.setInteractiveMode(false);
106     JvOptionPane.setMockResponse(JvOptionPane.CANCEL_OPTION);
107   }
108
109   @Test(groups = { "Functional" })
110   public void testRNAStructureRecovery() throws Exception
111   {
112     String inFile = "examples/RF00031_folded.stk";
113     String tfile = File.createTempFile("JalviewTest", ".jvp")
114             .getAbsolutePath();
115     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(inFile,
116             DataSourceType.FILE);
117     assertNotNull(af, "Didn't read input file " + inFile);
118     int olddsann = countDsAnn(af.getViewport());
119     assertTrue(olddsann > 0, "Didn't find any dataset annotations");
120     af.changeColour_actionPerformed(
121             JalviewColourScheme.RNAHelices.toString());
122     assertTrue(
123             af.getViewport()
124                     .getGlobalColourScheme() instanceof RNAHelicesColour,
125             "Couldn't apply RNA helices colourscheme");
126     af.saveAlignment(tfile, FileFormat.Jalview);
127     assertTrue(af.isSaveAlignmentSuccessful(),
128             "Failed to store as a project.");
129     af.closeMenuItem_actionPerformed(true);
130     af = new FileLoader().LoadFileWaitTillLoaded(tfile,
131             DataSourceType.FILE);
132     assertNotNull(af, "Failed to import new project");
133     int newdsann = countDsAnn(af.getViewport());
134     assertEquals(olddsann, newdsann,
135             "Differing numbers of dataset sequence annotation\nOriginally "
136                     + olddsann + " and now " + newdsann);
137     System.out.println(
138             "Read in same number of annotations as originally present ("
139                     + olddsann + ")");
140     assertTrue(
141
142             af.getViewport()
143                     .getGlobalColourScheme() instanceof RNAHelicesColour,
144             "RNA helices colourscheme was not applied on import.");
145   }
146
147   @Test(groups = { "Functional" })
148   public void testTCoffeeScores() throws Exception
149   {
150     String inFile = "examples/uniref50.fa",
151             inAnnot = "examples/uniref50.score_ascii";
152     String tfile = File.createTempFile("JalviewTest", ".jvp")
153             .getAbsolutePath();
154     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(inFile,
155             DataSourceType.FILE);
156     assertNotNull(af, "Didn't read input file " + inFile);
157     af.loadJalviewDataFile(inAnnot, DataSourceType.FILE, null, null);
158     AlignViewport viewport = af.getViewport();
159     assertSame(viewport.getGlobalColourScheme().getClass(),
160             TCoffeeColourScheme.class, "Didn't set T-coffee colourscheme");
161     assertNotNull(
162             ColourSchemeProperty.getColourScheme(viewport,
163                     viewport.getAlignment(),
164                     viewport.getGlobalColourScheme().getSchemeName()),
165             "Recognise T-Coffee score from string");
166
167     af.saveAlignment(tfile, FileFormat.Jalview);
168     assertTrue(af.isSaveAlignmentSuccessful(),
169             "Failed to store as a project.");
170     af.closeMenuItem_actionPerformed(true);
171     af = new FileLoader().LoadFileWaitTillLoaded(tfile,
172             DataSourceType.FILE);
173     assertNotNull(af, "Failed to import new project");
174     assertSame(af.getViewport().getGlobalColourScheme().getClass(),
175             TCoffeeColourScheme.class,
176             "Didn't set T-coffee colourscheme for imported project.");
177     System.out.println(
178             "T-Coffee score shading successfully recovered from project.");
179   }
180
181   @Test(groups = { "Functional" })
182   public void testColourByAnnotScores() throws Exception
183   {
184     String inFile = "examples/uniref50.fa",
185             inAnnot = "examples/testdata/uniref50_iupred.jva";
186     String tfile = File.createTempFile("JalviewTest", ".jvp")
187             .getAbsolutePath();
188     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(inFile,
189             DataSourceType.FILE);
190     assertNotNull(af, "Didn't read input file " + inFile);
191     af.loadJalviewDataFile(inAnnot, DataSourceType.FILE, null, null);
192     AlignmentAnnotation[] aa = af.getViewport().getAlignment()
193             .getSequenceAt(0).getAnnotation("IUPredWS (Short)");
194     assertTrue(
195
196             aa != null && aa.length > 0,
197             "Didn't find any IUPred annotation to use to shade alignment.");
198     AnnotationColourGradient cs = new AnnotationColourGradient(aa[0], null,
199             AnnotationColourGradient.ABOVE_THRESHOLD);
200     AnnotationColourGradient gcs = new AnnotationColourGradient(aa[0], null,
201             AnnotationColourGradient.BELOW_THRESHOLD);
202     cs.setSeqAssociated(true);
203     gcs.setSeqAssociated(true);
204     af.changeColour(cs);
205     SequenceGroup sg = new SequenceGroup();
206     sg.setStartRes(57);
207     sg.setEndRes(92);
208     sg.cs.setColourScheme(gcs);
209     af.getViewport().getAlignment().addGroup(sg);
210     sg.addSequence(af.getViewport().getAlignment().getSequenceAt(1), false);
211     sg.addSequence(af.getViewport().getAlignment().getSequenceAt(2), true);
212     af.alignPanel.alignmentChanged();
213     af.saveAlignment(tfile, FileFormat.Jalview);
214     assertTrue(af.isSaveAlignmentSuccessful(),
215             "Failed to store as a project.");
216     af.closeMenuItem_actionPerformed(true);
217     af = null;
218     af = new FileLoader().LoadFileWaitTillLoaded(tfile,
219             DataSourceType.FILE);
220     assertNotNull(af, "Failed to import new project");
221
222     // check for group and alignment colourschemes
223
224     ColourSchemeI _rcs = af.getViewport().getGlobalColourScheme();
225     ColourSchemeI _rgcs = af.getViewport().getAlignment().getGroups().get(0)
226             .getColourScheme();
227     assertNotNull(_rcs, "Didn't recover global colourscheme");
228     assertTrue(_rcs instanceof AnnotationColourGradient,
229             "Didn't recover annotation colour global scheme");
230     AnnotationColourGradient __rcs = (AnnotationColourGradient) _rcs;
231     assertTrue(__rcs.isSeqAssociated(),
232             "Annotation colourscheme wasn't sequence associated");
233
234     boolean diffseqcols = false, diffgseqcols = false;
235     SequenceI[] sqs = af.getViewport().getAlignment().getSequencesArray();
236     for (int p = 0, pSize = af.getViewport().getAlignment()
237             .getWidth(); p < pSize && (!diffseqcols || !diffgseqcols); p++)
238     {
239       if (_rcs.findColour(sqs[0].getCharAt(p), p, sqs[0], null, 0f) != _rcs
240               .findColour(sqs[5].getCharAt(p), p, sqs[5], null, 0f))
241       {
242         diffseqcols = true;
243       }
244     }
245     assertTrue(diffseqcols, "Got Different sequence colours");
246     System.out.println(
247             "Per sequence colourscheme (Background) successfully applied and recovered.");
248
249     assertNotNull(_rgcs, "Didn't recover group colourscheme");
250     assertTrue(_rgcs instanceof AnnotationColourGradient,
251             "Didn't recover annotation colour group colourscheme");
252     __rcs = (AnnotationColourGradient) _rgcs;
253     assertTrue(__rcs.isSeqAssociated(),
254             "Group Annotation colourscheme wasn't sequence associated");
255
256     for (int p = 0, pSize = af.getViewport().getAlignment()
257             .getWidth(); p < pSize && (!diffseqcols || !diffgseqcols); p++)
258     {
259       if (_rgcs.findColour(sqs[1].getCharAt(p), p, sqs[1], null,
260               0f) != _rgcs.findColour(sqs[2].getCharAt(p), p, sqs[2], null,
261                       0f))
262       {
263         diffgseqcols = true;
264       }
265     }
266     assertTrue(diffgseqcols, "Got Different group sequence colours");
267     System.out.println(
268             "Per sequence (Group) colourscheme successfully applied and recovered.");
269   }
270
271   @Test(groups = { "Functional" })
272   public void gatherViewsHere() throws Exception
273   {
274     int origCount = Desktop.getAlignFrames() == null ? 0
275             : Desktop.getAlignFrames().length;
276     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
277             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
278     assertNotNull(af, "Didn't read in the example file correctly.");
279     assertTrue(Desktop.getAlignFrames().length == 1 + origCount,
280             "Didn't gather the views in the example file.");
281
282   }
283
284   /**
285    * Test for JAL-2223 - multiple mappings in View Mapping report
286    * 
287    * @throws Exception
288    */
289   @Test(groups = { "Functional" })
290   public void noDuplicatePdbMappingsMade() throws Exception
291   {
292     StructureImportSettings.setProcessSecondaryStructure(true);
293     StructureImportSettings.setVisibleChainAnnotation(true);
294     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
295             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
296     assertNotNull(af, "Didn't read in the example file correctly.");
297
298     // locate Jmol viewer
299     // count number of PDB mappings the structure selection manager holds -
300     String pdbFile = af.getCurrentView().getStructureSelectionManager()
301             .findFileForPDBId("1A70");
302     StructureMapping[] x = af.getCurrentView()
303             .getStructureSelectionManager()//
304             .getMapping(pdbFile);
305     assertEquals(x.length, 2, "Expected only two mappings for 1A70");
306
307   }
308
309   @Test(groups = { "Functional" })
310   public void viewRefPdbAnnotation() throws Exception
311   {
312     StructureImportSettings.setProcessSecondaryStructure(true);
313     StructureImportSettings.setVisibleChainAnnotation(true);
314     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
315             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
316     assertNotNull(af, "Didn't read in the example file correctly.");
317     AlignmentViewPanel sps = null;
318     for (AlignmentViewPanel ap : af.alignPanel.alignFrame.getAlignPanels())
319     {
320       if ("Spinach Feredoxin Structure".equals(ap.getViewName()))
321       {
322         sps = ap;
323         break;
324       }
325     }
326     assertNotNull(sps, "Couldn't find the structure view");
327     AlignmentAnnotation refan = null;
328     for (AlignmentAnnotation ra : sps.getAlignment()
329             .getAlignmentAnnotation())
330     {
331       if (ra.graph != 0)
332       {
333         refan = ra;
334         break;
335       }
336     }
337     assertNotNull(refan, "Annotation secondary structure not found.");
338     SequenceI sq = sps.getAlignment().findName("1A70|");
339     assertNotNull(sq, "Couldn't find 1a70 null chain");
340     // compare the manually added temperature factor annotation
341     // to the track automatically transferred from the pdb structure on load
342     assertNotNull(sq.getDatasetSequence().getAnnotation(),
343             "1a70 has no annotation");
344     for (AlignmentAnnotation ala : sq.getDatasetSequence().getAnnotation())
345     {
346       AlignmentAnnotation alaa;
347       sq.addAlignmentAnnotation(alaa = new AlignmentAnnotation(ala));
348       alaa.adjustForAlignment();
349       if (ala.graph == refan.graph)
350       {
351         for (int p = 0; p < ala.annotations.length; p++)
352         {
353           sq.findPosition(p);
354           try
355           {
356             assertTrue((alaa.annotations[p] == null
357                     && refan.annotations[p] == null)
358                     || alaa.annotations[p].value == refan.annotations[p].value,
359                     "Mismatch at alignment position " + p);
360           } catch (NullPointerException q)
361           {
362             Assert.fail("Mismatch of alignment annotations at position " + p
363                     + " Ref seq ann: " + refan.annotations[p]
364                     + " alignment " + alaa.annotations[p]);
365           }
366         }
367       }
368     }
369
370   }
371
372   @Test(groups = { "Functional" })
373   public void testCopyViewSettings() throws Exception
374   {
375     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
376             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
377     assertNotNull(af, "Didn't read in the example file correctly.");
378     AlignmentViewPanel sps = null, groups = null;
379     for (AlignmentViewPanel ap : af.alignPanel.alignFrame.getAlignPanels())
380     {
381       if ("Spinach Feredoxin Structure".equals(ap.getViewName()))
382       {
383         sps = ap;
384       }
385       if (ap.getViewName().contains("MAFFT"))
386       {
387         groups = ap;
388       }
389     }
390     assertNotNull(sps, "Couldn't find the structure view");
391     assertNotNull(groups, "Couldn't find the MAFFT view");
392
393     ViewStyleI structureStyle = sps.getAlignViewport().getViewStyle();
394     ViewStyleI groupStyle = groups.getAlignViewport().getViewStyle();
395     AssertJUnit.assertFalse(structureStyle.sameStyle(groupStyle));
396
397     groups.getAlignViewport().setViewStyle(structureStyle);
398     AssertJUnit.assertFalse(
399             groupStyle.sameStyle(groups.getAlignViewport().getViewStyle()));
400     Assert.assertTrue(structureStyle
401             .sameStyle(groups.getAlignViewport().getViewStyle()));
402
403   }
404
405   /**
406    * test store and recovery of expanded views
407    * 
408    * @throws Exception
409    */
410   @Test(groups = { "Functional" }, enabled = true)
411   public void testStoreAndRecoverExpandedviews() throws Exception
412   {
413     Desktop.getInstance().closeAll_actionPerformed(null);
414     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
415             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
416     Assert.assertEquals(Desktop.getAlignFrames().length, 1);
417     String afid = af.getViewport().getSequenceSetId();
418
419     // check FileLoader returned a reference to the one alignFrame that is
420     // actually on the Desktop
421     assertSame(af, Desktop.getAlignFrameFor(af.getViewport()),
422             "Jalview2XML.loadAlignFrame() didn't return correct AlignFrame reference for multiple view window");
423
424     Desktop.explodeViews(af);
425
426     int oldviews = Desktop.getAlignFrames().length;
427     Assert.assertEquals(Desktop.getAlignFrames().length,
428             Desktop.getAlignmentPanels(afid).length);
429     File tfile = File.createTempFile("testStoreAndRecoverExpanded", ".jvp");
430     try
431     {
432       new Jalview2XML(false).saveState(tfile);
433     } catch (Error e)
434     {
435       Assert.fail("Didn't save the expanded view state", e);
436     } catch (Exception e)
437     {
438       Assert.fail("Didn't save the expanded view state", e);
439     }
440     Desktop.getInstance().closeAll_actionPerformed(null);
441     if (Desktop.getAlignFrames() != null)
442     {
443       Assert.assertEquals(Desktop.getAlignFrames().length, 0);
444     }
445     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
446             DataSourceType.FILE);
447     Assert.assertNotNull(af);
448     Assert.assertEquals(Desktop.getAlignFrames().length,
449             Desktop.getAlignmentPanels(
450                     af.getViewport().getSequenceSetId()).length);
451     Assert.assertEquals(Desktop
452             .getAlignmentPanels(af.getViewport().getSequenceSetId()).length,
453             oldviews);
454   }
455
456   /**
457    * Test save and reload of a project with a different representative sequence
458    * in each view.
459    * 
460    * @throws Exception
461    */
462   @Test(groups = { "Functional" })
463   public void testStoreAndRecoverReferenceSeqSettings() throws Exception
464   {
465     Desktop.getInstance().closeAll_actionPerformed(null);
466     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
467             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
468     assertNotNull(af, "Didn't read in the example file correctly.");
469     String afid = af.getViewport().getSequenceSetId();
470
471     // remember reference sequence for each panel
472     Map<String, SequenceI> refseqs = new HashMap<>();
473
474     /*
475      * mark sequence 2, 3, 4.. in panels 1, 2, 3...
476      * as reference sequence for itself and the preceding sequence
477      */
478     int n = 1;
479     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
480     {
481       AlignViewportI av = ap.getAlignViewport();
482       AlignmentI alignment = ap.getAlignment();
483       int repIndex = n % alignment.getHeight();
484       SequenceI rep = alignment.getSequenceAt(repIndex);
485       refseqs.put(ap.getViewName(), rep);
486
487       // code from mark/unmark sequence as reference in jalview.gui.PopupMenu
488       // todo refactor this to an alignment view controller
489       av.setDisplayReferenceSeq(true);
490       av.setColourByReferenceSeq(true);
491       av.getAlignment().setSeqrep(rep);
492
493       n++;
494     }
495     File tfile = File.createTempFile("testStoreAndRecoverReferenceSeq",
496             ".jvp");
497     try
498     {
499       new Jalview2XML(false).saveState(tfile);
500     } catch (Throwable e)
501     {
502       Assert.fail("Didn't save the expanded view state", e);
503     }
504     Desktop.getInstance().closeAll_actionPerformed(null);
505     if (Desktop.getAlignFrames() != null)
506     {
507       Assert.assertEquals(Desktop.getAlignFrames().length, 0);
508     }
509
510     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
511             DataSourceType.FILE);
512     afid = af.getViewport().getSequenceSetId();
513
514     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
515     {
516       // check representative
517       AlignmentI alignment = ap.getAlignment();
518       SequenceI rep = alignment.getSeqrep();
519       Assert.assertNotNull(rep,
520               "Couldn't restore sequence representative from project");
521       // can't use a strong equals here, because by definition, the sequence IDs
522       // will be different.
523       // could set vamsas session save/restore flag to preserve IDs across
524       // load/saves.
525       Assert.assertEquals(refseqs.get(ap.getViewName()).toString(),
526               rep.toString(),
527               "Representative wasn't the same when recovered.");
528       Assert.assertTrue(ap.getAlignViewport().isDisplayReferenceSeq(),
529               "Display reference sequence view setting not set.");
530       Assert.assertTrue(ap.getAlignViewport().isColourByReferenceSeq(),
531               "Colour By Reference Seq view setting not set.");
532     }
533   }
534
535   @Test(groups = { "Functional" })
536   public void testIsVersionStringLaterThan()
537   {
538     /*
539      * No version / development / test / autobuild is leniently assumed to be
540      * compatible
541      */
542     assertTrue(Jalview2XML.isVersionStringLaterThan(null, null));
543     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", null));
544     assertTrue(Jalview2XML.isVersionStringLaterThan(null, "2.8.3"));
545     assertTrue(Jalview2XML.isVersionStringLaterThan(null,
546             "Development Build"));
547     assertTrue(Jalview2XML.isVersionStringLaterThan(null,
548             "DEVELOPMENT BUILD"));
549     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3",
550             "Development Build"));
551     assertTrue(Jalview2XML.isVersionStringLaterThan(null, "Test"));
552     assertTrue(Jalview2XML.isVersionStringLaterThan(null, "TEST"));
553     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "Test"));
554     assertTrue(
555             Jalview2XML.isVersionStringLaterThan(null, "Automated Build"));
556     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3",
557             "Automated Build"));
558     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3",
559             "AUTOMATED BUILD"));
560
561     /*
562      * same version returns true i.e. compatible
563      */
564     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8", "2.8"));
565     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.3"));
566     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3b1", "2.8.3b1"));
567     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3B1", "2.8.3b1"));
568     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3b1", "2.8.3B1"));
569
570     /*
571      * later version returns true
572      */
573     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.4"));
574     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.9"));
575     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.9.2"));
576     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8", "2.8.3"));
577     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.3b1"));
578
579     /*
580      * earlier version returns false
581      */
582     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8"));
583     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.4", "2.8.3"));
584     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.3b1", "2.8.3"));
585     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.2b1"));
586     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.0b2", "2.8.0b1"));
587   }
588
589   /**
590    * Test save and reload of a project with a different sequence group (and
591    * representative sequence) in each view.
592    * 
593    * @throws Exception
594    */
595   @Test(groups = { "Functional" })
596   public void testStoreAndRecoverGroupRepSeqs() throws Exception
597   {
598     Desktop.getInstance().closeAll_actionPerformed(null);
599     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
600             "examples/uniref50.fa", DataSourceType.FILE);
601     assertNotNull(af, "Didn't read in the example file correctly.");
602     String afid = af.getViewport().getSequenceSetId();
603     // make a second view of the alignment
604     af.newView_actionPerformed(null);
605
606     /*
607      * remember representative and hidden sequences marked 
608      * on each panel
609      */
610     Map<String, SequenceI> repSeqs = new HashMap<>();
611     Map<String, List<String>> hiddenSeqNames = new HashMap<>();
612
613     /*
614      * mark sequence 2, 3, 4.. in panels 1, 2, 3...
615      * as reference sequence for itself and the preceding sequence
616      */
617     int n = 1;
618     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
619     {
620       AlignViewportI av = ap.getAlignViewport();
621       AlignmentI alignment = ap.getAlignment();
622       int repIndex = n % alignment.getHeight();
623       // ensure at least one preceding sequence i.e. index >= 1
624       repIndex = Math.max(repIndex, 1);
625       SequenceI repSeq = alignment.getSequenceAt(repIndex);
626       repSeqs.put(ap.getViewName(), repSeq);
627       List<String> hiddenNames = new ArrayList<>();
628       hiddenSeqNames.put(ap.getViewName(), hiddenNames);
629
630       /*
631        * have rep sequence represent itself and the one before it
632        * this hides the group (except for the rep seq)
633        */
634       SequenceGroup sg = new SequenceGroup();
635       sg.addSequence(repSeq, false);
636       SequenceI precedingSeq = alignment.getSequenceAt(repIndex - 1);
637       sg.addSequence(precedingSeq, false);
638       sg.setSeqrep(repSeq);
639       assertTrue(sg.getSequences().contains(repSeq));
640       assertTrue(sg.getSequences().contains(precedingSeq));
641       av.setSelectionGroup(sg);
642       assertSame(repSeq, sg.getSeqrep());
643
644       /*
645        * represent group with sequence adds to a map of hidden rep sequences
646        * (it does not create a group on the alignment) 
647        */
648       ((AlignmentViewport) av).hideSequences(repSeq, true);
649       assertSame(repSeq, sg.getSeqrep());
650       assertTrue(sg.getSequences().contains(repSeq));
651       assertTrue(sg.getSequences().contains(precedingSeq));
652       assertTrue(alignment.getGroups().isEmpty(), "alignment has groups");
653       Map<SequenceI, SequenceCollectionI> hiddenRepSeqsMap = av
654               .getHiddenRepSequences();
655       assertNotNull(hiddenRepSeqsMap);
656       assertEquals(1, hiddenRepSeqsMap.size());
657       assertSame(sg, hiddenRepSeqsMap.get(repSeq));
658       assertTrue(alignment.getHiddenSequences().isHidden(precedingSeq));
659       assertFalse(alignment.getHiddenSequences().isHidden(repSeq));
660       hiddenNames.add(precedingSeq.getName());
661
662       n++;
663     }
664     File tfile = File.createTempFile("testStoreAndRecoverGroupReps",
665             ".jvp");
666     try
667     {
668       new Jalview2XML(false).saveState(tfile);
669     } catch (Throwable e)
670     {
671       Assert.fail("Didn't save the expanded view state", e);
672     }
673     Desktop.getInstance().closeAll_actionPerformed(null);
674     if (Desktop.getAlignFrames() != null)
675     {
676       Assert.assertEquals(Desktop.getAlignFrames().length, 0);
677     }
678
679     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
680             DataSourceType.FILE);
681     afid = af.getViewport().getSequenceSetId();
682
683     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
684     {
685       String viewName = ap.getViewName();
686       AlignViewportI av = ap.getAlignViewport();
687       AlignmentI alignment = ap.getAlignment();
688       List<SequenceGroup> groups = alignment.getGroups();
689       assertNotNull(groups);
690       assertTrue(groups.isEmpty(), "Alignment has groups");
691       Map<SequenceI, SequenceCollectionI> hiddenRepSeqsMap = av
692               .getHiddenRepSequences();
693       assertNotNull(hiddenRepSeqsMap, "No hidden represented sequences");
694       assertEquals(1, hiddenRepSeqsMap.size());
695       assertEquals(repSeqs.get(viewName).getDisplayId(true),
696               hiddenRepSeqsMap.keySet().iterator().next()
697                       .getDisplayId(true));
698
699       /*
700        * verify hidden sequences in restored panel
701        */
702       List<String> hidden = hiddenSeqNames.get(ap.getViewName());
703       HiddenSequences hs = alignment.getHiddenSequences();
704       assertEquals(hidden.size(), hs.getSize(),
705               "wrong number of restored hidden sequences in "
706                       + ap.getViewName());
707     }
708   }
709
710   /**
711    * Test save and reload of PDBEntry in Jalview project
712    * 
713    * @throws Exception
714    */
715   @Test(groups = { "Functional" })
716   public void testStoreAndRecoverPDBEntry() throws Exception
717   {
718     Desktop.getInstance().closeAll_actionPerformed(null);
719     String exampleFile = "examples/3W5V.pdb";
720     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(exampleFile,
721             DataSourceType.FILE);
722     assertNotNull(af, "Didn't read in the example file correctly.");
723     String afid = af.getViewport().getSequenceSetId();
724
725     AlignmentPanel[] alignPanels = Desktop.getAlignmentPanels(afid);
726     System.out.println();
727     AlignmentViewPanel ap = alignPanels[0];
728     String tfileBase = new File(".").getAbsolutePath().replace(".", "");
729     String testFile = tfileBase + exampleFile;
730     AlignmentI alignment = ap.getAlignment();
731     System.out.println("blah");
732     SequenceI[] seqs = alignment.getSequencesArray();
733     Assert.assertNotNull(seqs[0]);
734     Assert.assertNotNull(seqs[1]);
735     Assert.assertNotNull(seqs[2]);
736     Assert.assertNotNull(seqs[3]);
737     Assert.assertNotNull(seqs[0].getDatasetSequence());
738     Assert.assertNotNull(seqs[1].getDatasetSequence());
739     Assert.assertNotNull(seqs[2].getDatasetSequence());
740     Assert.assertNotNull(seqs[3].getDatasetSequence());
741     PDBEntry[] pdbEntries = new PDBEntry[4];
742     pdbEntries[0] = new PDBEntry("3W5V", "A", Type.PDB, testFile);
743     pdbEntries[1] = new PDBEntry("3W5V", "B", Type.PDB, testFile);
744     pdbEntries[2] = new PDBEntry("3W5V", "C", Type.PDB, testFile);
745     pdbEntries[3] = new PDBEntry("3W5V", "D", Type.PDB, testFile);
746     Assert.assertEquals(
747             seqs[0].getDatasetSequence().getAllPDBEntries().get(0),
748             pdbEntries[0]);
749     Assert.assertEquals(
750             seqs[1].getDatasetSequence().getAllPDBEntries().get(0),
751             pdbEntries[1]);
752     Assert.assertEquals(
753             seqs[2].getDatasetSequence().getAllPDBEntries().get(0),
754             pdbEntries[2]);
755     Assert.assertEquals(
756             seqs[3].getDatasetSequence().getAllPDBEntries().get(0),
757             pdbEntries[3]);
758
759     File tfile = File.createTempFile("testStoreAndRecoverPDBEntry", ".jvp");
760     try
761     {
762       new Jalview2XML(false).saveState(tfile);
763     } catch (Throwable e)
764     {
765       Assert.fail("Didn't save the state", e);
766     }
767     Desktop.getInstance().closeAll_actionPerformed(null);
768     if (Desktop.getAlignFrames() != null)
769     {
770       Assert.assertEquals(Desktop.getAlignFrames().length, 0);
771     }
772
773     AlignFrame restoredFrame = new FileLoader().LoadFileWaitTillLoaded(
774             tfile.getAbsolutePath(), DataSourceType.FILE);
775     String rfid = restoredFrame.getViewport().getSequenceSetId();
776     AlignmentPanel[] rAlignPanels = Desktop.getAlignmentPanels(rfid);
777     AlignmentViewPanel rap = rAlignPanels[0];
778     AlignmentI rAlignment = rap.getAlignment();
779     System.out.println("blah");
780     SequenceI[] rseqs = rAlignment.getSequencesArray();
781     Assert.assertNotNull(rseqs[0]);
782     Assert.assertNotNull(rseqs[1]);
783     Assert.assertNotNull(rseqs[2]);
784     Assert.assertNotNull(rseqs[3]);
785     Assert.assertNotNull(rseqs[0].getDatasetSequence());
786     Assert.assertNotNull(rseqs[1].getDatasetSequence());
787     Assert.assertNotNull(rseqs[2].getDatasetSequence());
788     Assert.assertNotNull(rseqs[3].getDatasetSequence());
789
790     // The Asserts below are expected to fail until the PDB chainCode is
791     // recoverable from a Jalview projects
792     for (int chain = 0; chain < 4; chain++)
793     {
794       PDBEntry recov = rseqs[chain].getDatasetSequence().getAllPDBEntries()
795               .get(0);
796       PDBEntry expected = pdbEntries[chain];
797       Assert.assertEquals(recov.getId(), expected.getId(),
798               "Mismatch PDB ID");
799       Assert.assertEquals(recov.getChainCode(), expected.getChainCode(),
800               "Mismatch PDB ID");
801       Assert.assertEquals(recov.getType(), expected.getType(),
802               "Mismatch PDBEntry 'Type'");
803       Assert.assertNotNull(recov.getFile(),
804               "Recovered PDBEntry should have a non-null file entry");
805     }
806   }
807
808   /**
809    * Configure an alignment and a sub-group each with distinct colour schemes,
810    * Conservation and PID thresholds, and confirm these are restored from the
811    * saved project.
812    * 
813    * @throws IOException
814    */
815   @Test(groups = { "Functional" })
816   public void testStoreAndRecoverColourThresholds() throws IOException
817   {
818     Desktop.getInstance().closeAll_actionPerformed(null);
819     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
820             "examples/uniref50.fa", DataSourceType.FILE);
821
822     AlignViewport av = af.getViewport();
823     AlignmentI al = av.getAlignment();
824
825     /*
826      * Colour alignment by Buried Index, Above 10% PID, By Conservation 20%
827      */
828     av.setColourAppliesToAllGroups(false);
829     af.changeColour_actionPerformed(JalviewColourScheme.Buried.toString());
830     assertTrue(av.getGlobalColourScheme() instanceof BuriedColourScheme);
831     af.abovePIDThreshold_actionPerformed(true);
832     SliderPanel sp = SliderPanel.getSliderPanel();
833     assertFalse(sp.isForConservation());
834     sp.valueChanged(10);
835     af.conservationMenuItem_actionPerformed(true);
836     sp = SliderPanel.getSliderPanel();
837     assertTrue(sp.isForConservation());
838     sp.valueChanged(20);
839     ResidueShaderI rs = av.getResidueShading();
840     assertEquals(rs.getThreshold(), 10);
841     assertTrue(rs.conservationApplied());
842     assertEquals(rs.getConservationInc(), 20);
843
844     /*
845      * create a group with Strand colouring, 30% Conservation
846      * and 40% PID threshold
847      */
848     SequenceGroup sg = new SequenceGroup();
849     sg.addSequence(al.getSequenceAt(0), false);
850     sg.setStartRes(15);
851     sg.setEndRes(25);
852     av.setSelectionGroup(sg);
853     PopupMenu popupMenu = new PopupMenu(af.alignPanel, null, null);
854     popupMenu.changeColour_actionPerformed(
855             JalviewColourScheme.Strand.toString());
856     assertTrue(sg.getColourScheme() instanceof StrandColourScheme);
857     assertEquals(al.getGroups().size(), 1);
858     assertSame(al.getGroups().get(0), sg);
859     popupMenu.conservationMenuItem_actionPerformed(true);
860     sp = SliderPanel.getSliderPanel();
861     assertTrue(sp.isForConservation());
862     sp.valueChanged(30);
863     popupMenu.abovePIDColour_actionPerformed(true);
864     sp = SliderPanel.getSliderPanel();
865     assertFalse(sp.isForConservation());
866     sp.valueChanged(40);
867     assertTrue(sg.getGroupColourScheme().conservationApplied());
868     assertEquals(sg.getGroupColourScheme().getConservationInc(), 30);
869     assertEquals(sg.getGroupColourScheme().getThreshold(), 40);
870
871     /*
872      * save project, close windows, reload project, verify
873      */
874     File tfile = File.createTempFile("testStoreAndRecoverColourThresholds",
875             ".jvp");
876     tfile.deleteOnExit();
877     new Jalview2XML(false).saveState(tfile);
878     Desktop.getInstance().closeAll_actionPerformed(null);
879     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
880             DataSourceType.FILE);
881     Assert.assertNotNull(af, "Failed to reload project");
882
883     /*
884      * verify alignment (background) colouring
885      */
886     rs = af.getViewport().getResidueShading();
887     assertTrue(rs.getColourScheme() instanceof BuriedColourScheme);
888     assertEquals(rs.getThreshold(), 10);
889     assertTrue(rs.conservationApplied());
890     assertEquals(rs.getConservationInc(), 20);
891
892     /*
893      * verify group colouring
894      */
895     assertEquals(1, af.getViewport().getAlignment().getGroups().size(), 1);
896     rs = af.getViewport().getAlignment().getGroups().get(0)
897             .getGroupColourScheme();
898     assertTrue(rs.getColourScheme() instanceof StrandColourScheme);
899     assertEquals(rs.getThreshold(), 40);
900     assertTrue(rs.conservationApplied());
901     assertEquals(rs.getConservationInc(), 30);
902   }
903
904   /**
905    * Test save and reload of feature colour schemes and filter settings
906    * 
907    * @throws IOException
908    */
909   @Test(groups = { "Functional" })
910   public void testSaveLoadFeatureColoursAndFilters() throws IOException
911   {
912     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
913             ">Seq1\nACDEFGHIKLM", DataSourceType.PASTE);
914     SequenceI seq1 = af.getViewport().getAlignment().getSequenceAt(0);
915
916     /*
917      * add some features to the sequence
918      */
919     int score = 1;
920     addFeatures(seq1, "type1", score++);
921     addFeatures(seq1, "type2", score++);
922     addFeatures(seq1, "type3", score++);
923     addFeatures(seq1, "type4", score++);
924     addFeatures(seq1, "type5", score++);
925
926     /*
927      * set colour schemes for features
928      */
929     FeatureRenderer fr = af.getFeatureRenderer();
930     fr.findAllFeatures(true);
931
932     // type1: red
933     fr.setColour("type1", new FeatureColour(Color.red));
934
935     // type2: by label
936     FeatureColourI byLabel = new FeatureColour();
937     byLabel.setColourByLabel(true);
938     fr.setColour("type2", byLabel);
939
940     // type3: by score above threshold
941     FeatureColourI byScore = new FeatureColour(null, Color.BLACK,
942             Color.BLUE, null, 1, 10);
943     byScore.setAboveThreshold(true);
944     byScore.setThreshold(2f);
945     fr.setColour("type3", byScore);
946
947     // type4: by attribute AF
948     FeatureColourI byAF = new FeatureColour();
949     byAF.setColourByLabel(true);
950     byAF.setAttributeName("AF");
951     fr.setColour("type4", byAF);
952
953     // type5: by attribute CSQ:PolyPhen below threshold
954     FeatureColourI byPolyPhen = new FeatureColour(null, Color.BLACK,
955             Color.BLUE, null, 1, 10);
956     byPolyPhen.setBelowThreshold(true);
957     byPolyPhen.setThreshold(3f);
958     byPolyPhen.setAttributeName("CSQ", "PolyPhen");
959     fr.setColour("type5", byPolyPhen);
960
961     /*
962      * set filters for feature types
963      */
964
965     // filter type1 features by (label contains "x")
966     FeatureMatcherSetI filterByX = new FeatureMatcherSet();
967     filterByX.and(FeatureMatcher.byLabel(Condition.Contains, "x"));
968     fr.setFeatureFilter("type1", filterByX);
969
970     // filter type2 features by (score <= 2.4 and score > 1.1)
971     FeatureMatcherSetI filterByScore = new FeatureMatcherSet();
972     filterByScore.and(FeatureMatcher.byScore(Condition.LE, "2.4"));
973     filterByScore.and(FeatureMatcher.byScore(Condition.GT, "1.1"));
974     fr.setFeatureFilter("type2", filterByScore);
975
976     // filter type3 features by (AF contains X OR CSQ:PolyPhen != 0)
977     FeatureMatcherSetI filterByXY = new FeatureMatcherSet();
978     filterByXY
979             .and(FeatureMatcher.byAttribute(Condition.Contains, "X", "AF"));
980     filterByXY.or(FeatureMatcher.byAttribute(Condition.NE, "0", "CSQ",
981             "PolyPhen"));
982     fr.setFeatureFilter("type3", filterByXY);
983
984     /*
985      * save as Jalview project
986      */
987     File tfile = File.createTempFile("JalviewTest", ".jvp");
988     tfile.deleteOnExit();
989     String filePath = tfile.getAbsolutePath();
990     af.saveAlignment(filePath, FileFormat.Jalview);
991     assertTrue(af.isSaveAlignmentSuccessful(),
992             "Failed to store as a project.");
993
994     /*
995      * close current alignment and load the saved project
996      */
997     af.closeMenuItem_actionPerformed(true);
998     af = null;
999     af = new FileLoader().LoadFileWaitTillLoaded(filePath,
1000             DataSourceType.FILE);
1001     assertNotNull(af, "Failed to import new project");
1002
1003     /*
1004      * verify restored feature colour schemes and filters
1005      */
1006     fr = af.getFeatureRenderer();
1007     FeatureColourI fc = fr.getFeatureStyle("type1");
1008     assertTrue(fc.isSimpleColour());
1009     assertEquals(fc.getColour(), Color.red);
1010     fc = fr.getFeatureStyle("type2");
1011     assertTrue(fc.isColourByLabel());
1012     fc = fr.getFeatureStyle("type3");
1013     assertTrue(fc.isGraduatedColour());
1014     assertNull(fc.getAttributeName());
1015     assertTrue(fc.isAboveThreshold());
1016     assertEquals(fc.getThreshold(), 2f);
1017     fc = fr.getFeatureStyle("type4");
1018     assertTrue(fc.isColourByLabel());
1019     assertTrue(fc.isColourByAttribute());
1020     assertEquals(fc.getAttributeName(), new String[] { "AF" });
1021     fc = fr.getFeatureStyle("type5");
1022     assertTrue(fc.isGraduatedColour());
1023     assertTrue(fc.isColourByAttribute());
1024     assertEquals(fc.getAttributeName(), new String[] { "CSQ", "PolyPhen" });
1025     assertTrue(fc.isBelowThreshold());
1026     assertEquals(fc.getThreshold(), 3f);
1027
1028     assertEquals(fr.getFeatureFilter("type1").toStableString(),
1029             "Label Contains x");
1030     assertEquals(fr.getFeatureFilter("type2").toStableString(),
1031             "(Score LE 2.4) AND (Score GT 1.1)");
1032     assertEquals(fr.getFeatureFilter("type3").toStableString(),
1033             "(AF Contains X) OR (CSQ:PolyPhen NE 0.0)");
1034   }
1035
1036   private void addFeature(SequenceI seq, String featureType, int score)
1037   {
1038     SequenceFeature sf = new SequenceFeature(featureType, "desc", 1, 2,
1039             score, "grp");
1040     sf.setValue("AF", score);
1041     sf.setValue("CSQ", new HashMap<String, String>()
1042     {
1043       {
1044         put("PolyPhen", Integer.toString(score));
1045       }
1046     });
1047     seq.addSequenceFeature(sf);
1048   }
1049
1050   /**
1051    * Adds two features of the given type to the given sequence, also setting the
1052    * score as the value of attribute "AF" and sub-attribute "CSQ:PolyPhen"
1053    * 
1054    * @param seq
1055    * @param featureType
1056    * @param score
1057    */
1058   private void addFeatures(SequenceI seq, String featureType, int score)
1059   {
1060     addFeature(seq, featureType, score++);
1061     addFeature(seq, featureType, score);
1062   }
1063
1064   /**
1065    * pre 2.11 - jalview 2.10 erroneously created new dataset entries for each
1066    * view (JAL-3171) this test ensures we can import and merge those views
1067    */
1068   @Test(groups = { "Functional" })
1069   public void testMergeDatasetsforViews() throws IOException
1070   {
1071     // simple project - two views on one alignment
1072     AlignFrame af = new FileLoader(false).LoadFileWaitTillLoaded(
1073             "examples/testdata/projects/twoViews.jvp", DataSourceType.FILE);
1074     assertNotNull(af);
1075     assertTrue(af.getAlignPanels().size() > 1);
1076     verifyDs(af);
1077   }
1078
1079   /**
1080    * pre 2.11 - jalview 2.10 erroneously created new dataset entries for each
1081    * view (JAL-3171) this test ensures we can import and merge those views This
1082    * is a more complex project
1083    */
1084   @Test(groups = { "Functional" })
1085   public void testMergeDatasetsforManyViews() throws IOException
1086   {
1087     Desktop.getInstance().closeAll_actionPerformed(null);
1088
1089     // complex project - one dataset, several views on several alignment
1090     AlignFrame af = new FileLoader(false).LoadFileWaitTillLoaded(
1091             "examples/testdata/projects/manyViews.jvp",
1092             DataSourceType.FILE);
1093     assertNotNull(af);
1094
1095     AlignmentI ds = null;
1096     for (AlignFrame alignFrame : Desktop.getAlignFrames())
1097     {
1098       if (ds == null)
1099       {
1100         ds = verifyDs(alignFrame);
1101       }
1102       else
1103       {
1104         // check that this frame's dataset matches the last
1105         assertTrue(ds == verifyDs(alignFrame));
1106       }
1107     }
1108   }
1109
1110   private AlignmentI verifyDs(AlignFrame af)
1111   {
1112     AlignmentI ds = null;
1113     for (AlignmentViewPanel ap : af.getAlignPanels())
1114     {
1115       if (ds == null)
1116       {
1117         ds = ap.getAlignment().getDataset();
1118       }
1119       else
1120       {
1121         assertTrue(ap.getAlignment().getDataset() == ds,
1122                 "Dataset was not the same for imported 2.10.5 project with several alignment views");
1123       }
1124     }
1125     return ds;
1126   }
1127
1128   @Test(groups = "Functional")
1129   public void testPcaViewAssociation() throws IOException
1130   {
1131     Desktop.getInstance().closeAll_actionPerformed(null);
1132     final String PCAVIEWNAME = "With PCA";
1133     // create a new tempfile
1134     File tempfile = File.createTempFile("jvPCAviewAssoc", "jvp");
1135
1136     {
1137       String exampleFile = "examples/uniref50.fa";
1138       AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(exampleFile,
1139               DataSourceType.FILE);
1140       assertNotNull(af, "Didn't read in the example file correctly.");
1141       AlignmentPanel origView = (AlignmentPanel) af.getAlignPanels().get(0);
1142       AlignmentPanel newview = af.newView(PCAVIEWNAME, true);
1143       // create another for good measure
1144       af.newView("Not the PCA View", true);
1145       PCAPanel pcaPanel = new PCAPanel(origView, "BLOSUM62",
1146               new SimilarityParams(true, true, true, false));
1147       // we're in the test exec thread, so we can just run synchronously here
1148       pcaPanel.run();
1149
1150       // now switch the linked view
1151       pcaPanel.selectAssociatedView(newview);
1152
1153       assertTrue(pcaPanel.getAlignViewport() == newview.getAlignViewport(),
1154               "PCA should be associated with 'With PCA' view: test is broken");
1155
1156       // now save and reload project
1157       Jalview2XML jv2xml = new jalview.project.Jalview2XML(false);
1158       tempfile.delete();
1159       jv2xml.saveState(tempfile);
1160       assertTrue(jv2xml.errorMessage == null,
1161               "Failed to save dummy project with PCA: test broken");
1162     }
1163
1164     // load again.
1165     Desktop.getInstance().closeAll_actionPerformed(null);
1166     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
1167             tempfile.getCanonicalPath(), DataSourceType.FILE);
1168     JInternalFrame[] frames = Desktop.getInstance().getAllFrames();
1169     // PCA and the tabbed alignment view should be the only two windows on the
1170     // desktop
1171     assertEquals(frames.length, 2,
1172             "PCA and the tabbed alignment view should be the only two windows on the desktop");
1173     PCAPanel pcaPanel = (PCAPanel) frames[frames[0] == af ? 1 : 0];
1174
1175     AlignmentViewPanel restoredNewView = null;
1176     for (AlignmentViewPanel alignpanel : Desktop.getAlignmentPanels(null))
1177     {
1178       if (alignpanel.getAlignViewport() == pcaPanel.getAlignViewport())
1179       {
1180         restoredNewView = alignpanel;
1181       }
1182     }
1183     assertEquals(restoredNewView.getViewName(), PCAVIEWNAME);
1184     assertTrue(
1185             restoredNewView.getAlignViewport() == pcaPanel
1186                     .getAlignViewport(),
1187             "Didn't restore correct view association for the PCA view");
1188   }
1189 }