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