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