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