JAL-1713 unit test for save/restore Overview in project
[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.Map;
39
40 import javax.swing.JInternalFrame;
41
42 import org.testng.Assert;
43 import org.testng.AssertJUnit;
44 import org.testng.annotations.BeforeClass;
45 import org.testng.annotations.Test;
46
47 import jalview.analysis.scoremodels.SimilarityParams;
48 import jalview.api.AlignViewportI;
49 import jalview.api.AlignmentViewPanel;
50 import jalview.api.FeatureColourI;
51 import jalview.api.ViewStyleI;
52 import jalview.bin.Cache;
53 import jalview.datamodel.AlignmentAnnotation;
54 import jalview.datamodel.AlignmentI;
55 import jalview.datamodel.DBRefEntry;
56 import jalview.datamodel.GeneLocus;
57 import jalview.datamodel.HiddenSequences;
58 import jalview.datamodel.Mapping;
59 import jalview.datamodel.PDBEntry;
60 import jalview.datamodel.PDBEntry.Type;
61 import jalview.datamodel.Sequence.DBModList;
62 import jalview.datamodel.SequenceCollectionI;
63 import jalview.datamodel.SequenceFeature;
64 import jalview.datamodel.SequenceGroup;
65 import jalview.datamodel.SequenceI;
66 import jalview.datamodel.features.FeatureMatcher;
67 import jalview.datamodel.features.FeatureMatcherSet;
68 import jalview.datamodel.features.FeatureMatcherSetI;
69 import jalview.gui.AlignFrame;
70 import jalview.gui.AlignViewport;
71 import jalview.gui.AlignmentPanel;
72 import jalview.gui.Desktop;
73 import jalview.gui.JvOptionPane;
74 import jalview.gui.OverviewPanel;
75 import jalview.gui.PCAPanel;
76 import jalview.gui.PopupMenu;
77 import jalview.gui.Preferences;
78 import jalview.gui.SliderPanel;
79 import jalview.io.DataSourceType;
80 import jalview.io.FileFormat;
81 import jalview.io.FileLoader;
82 import jalview.io.Jalview2xmlBase;
83 import jalview.renderer.ResidueShaderI;
84 import jalview.schemes.AnnotationColourGradient;
85 import jalview.schemes.BuriedColourScheme;
86 import jalview.schemes.ColourSchemeI;
87 import jalview.schemes.ColourSchemeProperty;
88 import jalview.schemes.FeatureColour;
89 import jalview.schemes.JalviewColourScheme;
90 import jalview.schemes.RNAHelicesColour;
91 import jalview.schemes.StrandColourScheme;
92 import jalview.schemes.TCoffeeColourScheme;
93 import jalview.structure.StructureImportSettings;
94 import jalview.util.MapList;
95 import jalview.util.matcher.Condition;
96 import jalview.viewmodel.AlignmentViewport;
97 import jalview.viewmodel.seqfeatures.FeatureRendererModel;
98
99 @Test(singleThreaded = true)
100 public class Jalview2xmlTests extends Jalview2xmlBase
101 {
102
103   @Override
104   @BeforeClass(alwaysRun = true)
105   public void setUpJvOptionPane()
106   {
107     JvOptionPane.setInteractiveMode(false);
108     JvOptionPane.setMockResponse(JvOptionPane.CANCEL_OPTION);
109   }
110
111   @Test(groups = { "Functional" })
112   public void testRNAStructureRecovery() throws Exception
113   {
114     String inFile = "examples/RF00031_folded.stk";
115     String tfile = File.createTempFile("JalviewTest", ".jvp")
116             .getAbsolutePath();
117     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(inFile,
118             DataSourceType.FILE);
119     assertNotNull(af, "Didn't read input file " + inFile);
120     int olddsann = countDsAnn(af.getViewport());
121     assertTrue(olddsann > 0, "Didn't find any dataset annotations");
122     af.changeColour_actionPerformed(
123             JalviewColourScheme.RNAHelices.toString());
124     assertTrue(
125             af.getViewport()
126                     .getGlobalColourScheme() instanceof RNAHelicesColour,
127             "Couldn't apply RNA helices colourscheme");
128     af.saveAlignment(tfile, FileFormat.Jalview);
129     assertTrue(af.isSaveAlignmentSuccessful(),
130             "Failed to store as a project.");
131     af.closeMenuItem_actionPerformed(true);
132     af = null;
133     af = new FileLoader().LoadFileWaitTillLoaded(tfile,
134             DataSourceType.FILE);
135     assertNotNull(af, "Failed to import new project");
136     int newdsann = countDsAnn(af.getViewport());
137     assertEquals(olddsann, newdsann,
138             "Differing numbers of dataset sequence annotation\nOriginally "
139                     + olddsann + " and now " + newdsann);
140     System.out.println(
141             "Read in same number of annotations as originally present ("
142                     + olddsann + ")");
143     assertTrue(
144
145             af.getViewport()
146                     .getGlobalColourScheme() instanceof RNAHelicesColour,
147             "RNA helices colourscheme was not applied on import.");
148   }
149
150   @Test(groups = { "Functional" })
151   public void testTCoffeeScores() throws Exception
152   {
153     String inFile = "examples/uniref50.fa",
154             inAnnot = "examples/uniref50.score_ascii";
155     String tfile = File.createTempFile("JalviewTest", ".jvp")
156             .getAbsolutePath();
157     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(inFile,
158             DataSourceType.FILE);
159     assertNotNull(af, "Didn't read input file " + inFile);
160     af.loadJalviewDataFile(inAnnot, DataSourceType.FILE, null, null);
161     AlignViewport viewport = af.getViewport();
162     assertSame(viewport.getGlobalColourScheme().getClass(),
163             TCoffeeColourScheme.class, "Didn't set T-coffee colourscheme");
164     assertNotNull(
165             ColourSchemeProperty.getColourScheme(viewport,
166                     viewport.getAlignment(),
167                     viewport.getGlobalColourScheme()
168                             .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(
458             Desktop.getAlignmentPanels(
459                     af.getViewport().getSequenceSetId()).length,
460             oldviews);
461   }
462
463   /**
464    * Test save and reload of a project with a different representative sequence
465    * in each view.
466    * 
467    * @throws Exception
468    */
469   @Test(groups = { "Functional" })
470   public void testStoreAndRecoverReferenceSeqSettings() throws Exception
471   {
472     Desktop.instance.closeAll_actionPerformed(null);
473     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
474             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
475     assertNotNull(af, "Didn't read in the example file correctly.");
476     String afid = af.getViewport().getSequenceSetId();
477
478     // remember reference sequence for each panel
479     Map<String, SequenceI> refseqs = new HashMap<>();
480
481     /*
482      * mark sequence 2, 3, 4.. in panels 1, 2, 3...
483      * as reference sequence for itself and the preceding sequence
484      */
485     int n = 1;
486     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
487     {
488       AlignViewportI av = ap.getAlignViewport();
489       AlignmentI alignment = ap.getAlignment();
490       int repIndex = n % alignment.getHeight();
491       SequenceI rep = alignment.getSequenceAt(repIndex);
492       refseqs.put(ap.getViewName(), rep);
493
494       // code from mark/unmark sequence as reference in jalview.gui.PopupMenu
495       // todo refactor this to an alignment view controller
496       av.setDisplayReferenceSeq(true);
497       av.setColourByReferenceSeq(true);
498       av.getAlignment().setSeqrep(rep);
499
500       n++;
501     }
502     File tfile = File.createTempFile("testStoreAndRecoverReferenceSeq",
503             ".jvp");
504     try
505     {
506       new Jalview2XML(false).saveState(tfile);
507     } catch (Throwable e)
508     {
509       Assert.fail("Didn't save the expanded view state", e);
510     }
511     Desktop.instance.closeAll_actionPerformed(null);
512     if (Desktop.getAlignFrames() != null)
513     {
514       Assert.assertEquals(Desktop.getAlignFrames().length, 0);
515     }
516
517     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
518             DataSourceType.FILE);
519     afid = af.getViewport().getSequenceSetId();
520
521     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
522     {
523       // check representative
524       AlignmentI alignment = ap.getAlignment();
525       SequenceI rep = alignment.getSeqrep();
526       Assert.assertNotNull(rep,
527               "Couldn't restore sequence representative from project");
528       // can't use a strong equals here, because by definition, the sequence IDs
529       // will be different.
530       // could set vamsas session save/restore flag to preserve IDs across
531       // load/saves.
532       Assert.assertEquals(refseqs.get(ap.getViewName()).toString(),
533               rep.toString(),
534               "Representative wasn't the same when recovered.");
535       Assert.assertTrue(ap.getAlignViewport().isDisplayReferenceSeq(),
536               "Display reference sequence view setting not set.");
537       Assert.assertTrue(ap.getAlignViewport().isColourByReferenceSeq(),
538               "Colour By Reference Seq view setting not set.");
539     }
540   }
541
542   @Test(groups = { "Functional" })
543   public void testIsVersionStringLaterThan()
544   {
545     /*
546      * No version / development / test / autobuild is leniently assumed to be
547      * compatible
548      */
549     assertTrue(Jalview2XML.isVersionStringLaterThan(null, null));
550     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", null));
551     assertTrue(Jalview2XML.isVersionStringLaterThan(null, "2.8.3"));
552     assertTrue(Jalview2XML.isVersionStringLaterThan(null,
553             "Development Build"));
554     assertTrue(Jalview2XML.isVersionStringLaterThan(null,
555             "DEVELOPMENT BUILD"));
556     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3",
557             "Development Build"));
558     assertTrue(Jalview2XML.isVersionStringLaterThan(null, "Test"));
559     assertTrue(Jalview2XML.isVersionStringLaterThan(null, "TEST"));
560     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "Test"));
561     assertTrue(
562             Jalview2XML.isVersionStringLaterThan(null, "Automated Build"));
563     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3",
564             "Automated Build"));
565     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3",
566             "AUTOMATED BUILD"));
567
568     /*
569      * same version returns true i.e. compatible
570      */
571     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8", "2.8"));
572     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.3"));
573     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3b1", "2.8.3b1"));
574     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3B1", "2.8.3b1"));
575     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3b1", "2.8.3B1"));
576
577     /*
578      * later version returns true
579      */
580     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.4"));
581     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.9"));
582     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.9.2"));
583     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8", "2.8.3"));
584     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.3b1"));
585
586     /*
587      * earlier version returns false
588      */
589     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8"));
590     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.4", "2.8.3"));
591     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.3b1", "2.8.3"));
592     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.2b1"));
593     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.0b2", "2.8.0b1"));
594   }
595
596   /**
597    * Test save and reload of a project with a different sequence group (and
598    * representative sequence) in each view.
599    * 
600    * @throws Exception
601    */
602   @Test(groups = { "Functional" })
603   public void testStoreAndRecoverGroupRepSeqs() throws Exception
604   {
605     Desktop.instance.closeAll_actionPerformed(null);
606     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
607             "examples/uniref50.fa", DataSourceType.FILE);
608     assertNotNull(af, "Didn't read in the example file correctly.");
609     String afid = af.getViewport().getSequenceSetId();
610     // make a second view of the alignment
611     af.newView_actionPerformed(null);
612
613     /*
614      * remember representative and hidden sequences marked 
615      * on each panel
616      */
617     Map<String, SequenceI> repSeqs = new HashMap<>();
618     Map<String, List<String>> hiddenSeqNames = new HashMap<>();
619
620     /*
621      * mark sequence 2, 3, 4.. in panels 1, 2, 3...
622      * as reference sequence for itself and the preceding sequence
623      */
624     int n = 1;
625     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
626     {
627       AlignViewportI av = ap.getAlignViewport();
628       AlignmentI alignment = ap.getAlignment();
629       int repIndex = n % alignment.getHeight();
630       // ensure at least one preceding sequence i.e. index >= 1
631       repIndex = Math.max(repIndex, 1);
632       SequenceI repSeq = alignment.getSequenceAt(repIndex);
633       repSeqs.put(ap.getViewName(), repSeq);
634       List<String> hiddenNames = new ArrayList<>();
635       hiddenSeqNames.put(ap.getViewName(), hiddenNames);
636
637       /*
638        * have rep sequence represent itself and the one before it
639        * this hides the group (except for the rep seq)
640        */
641       SequenceGroup sg = new SequenceGroup();
642       sg.addSequence(repSeq, false);
643       SequenceI precedingSeq = alignment.getSequenceAt(repIndex - 1);
644       sg.addSequence(precedingSeq, false);
645       sg.setSeqrep(repSeq);
646       assertTrue(sg.getSequences().contains(repSeq));
647       assertTrue(sg.getSequences().contains(precedingSeq));
648       av.setSelectionGroup(sg);
649       assertSame(repSeq, sg.getSeqrep());
650
651       /*
652        * represent group with sequence adds to a map of hidden rep sequences
653        * (it does not create a group on the alignment) 
654        */
655       ((AlignmentViewport) av).hideSequences(repSeq, true);
656       assertSame(repSeq, sg.getSeqrep());
657       assertTrue(sg.getSequences().contains(repSeq));
658       assertTrue(sg.getSequences().contains(precedingSeq));
659       assertTrue(alignment.getGroups().isEmpty(), "alignment has groups");
660       Map<SequenceI, SequenceCollectionI> hiddenRepSeqsMap = av
661               .getHiddenRepSequences();
662       assertNotNull(hiddenRepSeqsMap);
663       assertEquals(1, hiddenRepSeqsMap.size());
664       assertSame(sg, hiddenRepSeqsMap.get(repSeq));
665       assertTrue(alignment.getHiddenSequences().isHidden(precedingSeq));
666       assertFalse(alignment.getHiddenSequences().isHidden(repSeq));
667       hiddenNames.add(precedingSeq.getName());
668
669       n++;
670     }
671     File tfile = File.createTempFile("testStoreAndRecoverGroupReps",
672             ".jvp");
673     try
674     {
675       new Jalview2XML(false).saveState(tfile);
676     } catch (Throwable e)
677     {
678       Assert.fail("Didn't save the expanded view state", e);
679     }
680     Desktop.instance.closeAll_actionPerformed(null);
681     if (Desktop.getAlignFrames() != null)
682     {
683       Assert.assertEquals(Desktop.getAlignFrames().length, 0);
684     }
685
686     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
687             DataSourceType.FILE);
688     afid = af.getViewport().getSequenceSetId();
689
690     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
691     {
692       String viewName = ap.getViewName();
693       AlignViewportI av = ap.getAlignViewport();
694       AlignmentI alignment = ap.getAlignment();
695       List<SequenceGroup> groups = alignment.getGroups();
696       assertNotNull(groups);
697       assertTrue(groups.isEmpty(), "Alignment has groups");
698       Map<SequenceI, SequenceCollectionI> hiddenRepSeqsMap = av
699               .getHiddenRepSequences();
700       assertNotNull(hiddenRepSeqsMap, "No hidden represented sequences");
701       assertEquals(1, hiddenRepSeqsMap.size());
702       assertEquals(repSeqs.get(viewName).getDisplayId(true),
703               hiddenRepSeqsMap.keySet().iterator().next()
704                       .getDisplayId(true));
705
706       /*
707        * verify hidden sequences in restored panel
708        */
709       List<String> hidden = hiddenSeqNames.get(ap.getViewName());
710       HiddenSequences hs = alignment.getHiddenSequences();
711       assertEquals(hidden.size(), hs.getSize(),
712               "wrong number of restored hidden sequences in "
713                       + ap.getViewName());
714     }
715   }
716
717   /**
718    * Test save and reload of PDBEntry in Jalview project
719    * 
720    * @throws Exception
721    */
722   @Test(groups = { "Functional" })
723   public void testStoreAndRecoverPDBEntry() throws Exception
724   {
725     Desktop.instance.closeAll_actionPerformed(null);
726     String exampleFile = "examples/3W5V.pdb";
727     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(exampleFile,
728             DataSourceType.FILE);
729     assertNotNull(af, "Didn't read in the example file correctly.");
730     String afid = af.getViewport().getSequenceSetId();
731
732     AlignmentPanel[] alignPanels = Desktop.getAlignmentPanels(afid);
733     System.out.println();
734     AlignmentViewPanel ap = alignPanels[0];
735     String tfileBase = new File(".").getAbsolutePath().replace(".", "");
736     String testFile = tfileBase + exampleFile;
737     AlignmentI alignment = ap.getAlignment();
738     System.out.println("blah");
739     SequenceI[] seqs = alignment.getSequencesArray();
740     Assert.assertNotNull(seqs[0]);
741     Assert.assertNotNull(seqs[1]);
742     Assert.assertNotNull(seqs[2]);
743     Assert.assertNotNull(seqs[3]);
744     Assert.assertNotNull(seqs[0].getDatasetSequence());
745     Assert.assertNotNull(seqs[1].getDatasetSequence());
746     Assert.assertNotNull(seqs[2].getDatasetSequence());
747     Assert.assertNotNull(seqs[3].getDatasetSequence());
748     PDBEntry[] pdbEntries = new PDBEntry[4];
749     pdbEntries[0] = new PDBEntry("3W5V", "A", Type.PDB, testFile);
750     pdbEntries[1] = new PDBEntry("3W5V", "B", Type.PDB, testFile);
751     pdbEntries[2] = new PDBEntry("3W5V", "C", Type.PDB, testFile);
752     pdbEntries[3] = new PDBEntry("3W5V", "D", Type.PDB, testFile);
753     Assert.assertEquals(
754             seqs[0].getDatasetSequence().getAllPDBEntries().get(0),
755             pdbEntries[0]);
756     Assert.assertEquals(
757             seqs[1].getDatasetSequence().getAllPDBEntries().get(0),
758             pdbEntries[1]);
759     Assert.assertEquals(
760             seqs[2].getDatasetSequence().getAllPDBEntries().get(0),
761             pdbEntries[2]);
762     Assert.assertEquals(
763             seqs[3].getDatasetSequence().getAllPDBEntries().get(0),
764             pdbEntries[3]);
765
766     File tfile = File.createTempFile("testStoreAndRecoverPDBEntry", ".jvp");
767     try
768     {
769       new Jalview2XML(false).saveState(tfile);
770     } catch (Throwable e)
771     {
772       Assert.fail("Didn't save the state", e);
773     }
774     Desktop.instance.closeAll_actionPerformed(null);
775     if (Desktop.getAlignFrames() != null)
776     {
777       Assert.assertEquals(Desktop.getAlignFrames().length, 0);
778     }
779
780     AlignFrame restoredFrame = new FileLoader().LoadFileWaitTillLoaded(
781             tfile.getAbsolutePath(), DataSourceType.FILE);
782     String rfid = restoredFrame.getViewport().getSequenceSetId();
783     AlignmentPanel[] rAlignPanels = Desktop.getAlignmentPanels(rfid);
784     AlignmentViewPanel rap = rAlignPanels[0];
785     AlignmentI rAlignment = rap.getAlignment();
786     System.out.println("blah");
787     SequenceI[] rseqs = rAlignment.getSequencesArray();
788     Assert.assertNotNull(rseqs[0]);
789     Assert.assertNotNull(rseqs[1]);
790     Assert.assertNotNull(rseqs[2]);
791     Assert.assertNotNull(rseqs[3]);
792     Assert.assertNotNull(rseqs[0].getDatasetSequence());
793     Assert.assertNotNull(rseqs[1].getDatasetSequence());
794     Assert.assertNotNull(rseqs[2].getDatasetSequence());
795     Assert.assertNotNull(rseqs[3].getDatasetSequence());
796
797     // The Asserts below are expected to fail until the PDB chainCode is
798     // recoverable from a Jalview projects
799     for (int chain = 0; chain < 4; chain++)
800     {
801       PDBEntry recov = rseqs[chain].getDatasetSequence().getAllPDBEntries()
802               .get(0);
803       PDBEntry expected = pdbEntries[chain];
804       Assert.assertEquals(recov.getId(), expected.getId(),
805               "Mismatch PDB ID");
806       Assert.assertEquals(recov.getChainCode(), expected.getChainCode(),
807               "Mismatch PDB ID");
808       Assert.assertEquals(recov.getType(), expected.getType(),
809               "Mismatch PDBEntry 'Type'");
810       Assert.assertNotNull(recov.getFile(),
811               "Recovered PDBEntry should have a non-null file entry");
812     }
813   }
814
815   /**
816    * Configure an alignment and a sub-group each with distinct colour schemes,
817    * Conservation and PID thresholds, and confirm these are restored from the
818    * saved project.
819    * 
820    * @throws IOException
821    */
822   @Test(groups = { "Functional" })
823   public void testStoreAndRecoverColourThresholds() throws IOException
824   {
825     Desktop.instance.closeAll_actionPerformed(null);
826     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
827             "examples/uniref50.fa", DataSourceType.FILE);
828
829     AlignViewport av = af.getViewport();
830     AlignmentI al = av.getAlignment();
831
832     /*
833      * Colour alignment by Buried Index, Above 10% PID, By Conservation 20%
834      */
835     av.setColourAppliesToAllGroups(false);
836     af.changeColour_actionPerformed(JalviewColourScheme.Buried.toString());
837     assertTrue(av.getGlobalColourScheme() instanceof BuriedColourScheme);
838     af.abovePIDThreshold_actionPerformed(true);
839     SliderPanel sp = SliderPanel.getSliderPanel();
840     assertFalse(sp.isForConservation());
841     sp.valueChanged(10);
842     af.conservationMenuItem_actionPerformed(true);
843     sp = SliderPanel.getSliderPanel();
844     assertTrue(sp.isForConservation());
845     sp.valueChanged(20);
846     ResidueShaderI rs = av.getResidueShading();
847     assertEquals(rs.getThreshold(), 10);
848     assertTrue(rs.conservationApplied());
849     assertEquals(rs.getConservationInc(), 20);
850
851     /*
852      * create a group with Strand colouring, 30% Conservation
853      * and 40% PID threshold
854      * (notice menu action applies to selection group even if mouse click
855      * is at a sequence not in the group)
856      */
857     SequenceGroup sg = new SequenceGroup();
858     sg.addSequence(al.getSequenceAt(0), false);
859     sg.setStartRes(15);
860     sg.setEndRes(25);
861     av.setSelectionGroup(sg);
862     PopupMenu popupMenu = new PopupMenu(af.alignPanel, al.getSequenceAt(2),
863             null);
864     popupMenu.changeColour_actionPerformed(
865             JalviewColourScheme.Strand.toString());
866     assertTrue(sg.getColourScheme() instanceof StrandColourScheme);
867     assertEquals(al.getGroups().size(), 1);
868     assertSame(al.getGroups().get(0), sg);
869     popupMenu.conservationMenuItem_actionPerformed(true);
870     sp = SliderPanel.getSliderPanel();
871     assertTrue(sp.isForConservation());
872     sp.valueChanged(30);
873     popupMenu.abovePIDColour_actionPerformed(true);
874     sp = SliderPanel.getSliderPanel();
875     assertFalse(sp.isForConservation());
876     sp.valueChanged(40);
877     assertTrue(sg.getGroupColourScheme().conservationApplied());
878     assertEquals(sg.getGroupColourScheme().getConservationInc(), 30);
879     assertEquals(sg.getGroupColourScheme().getThreshold(), 40);
880
881     /*
882      * save project, close windows, reload project, verify
883      */
884     File tfile = File.createTempFile("testStoreAndRecoverColourThresholds",
885             ".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     /*
894      * verify alignment (background) colouring
895      */
896     rs = af.getViewport().getResidueShading();
897     assertTrue(rs.getColourScheme() instanceof BuriedColourScheme);
898     assertEquals(rs.getThreshold(), 10);
899     assertTrue(rs.conservationApplied());
900     assertEquals(rs.getConservationInc(), 20);
901
902     /*
903      * verify group colouring
904      */
905     assertEquals(1, af.getViewport().getAlignment().getGroups().size(), 1);
906     rs = af.getViewport().getAlignment().getGroups().get(0)
907             .getGroupColourScheme();
908     assertTrue(rs.getColourScheme() instanceof StrandColourScheme);
909     assertEquals(rs.getThreshold(), 40);
910     assertTrue(rs.conservationApplied());
911     assertEquals(rs.getConservationInc(), 30);
912   }
913
914   /**
915    * Test save and reload of feature colour schemes and filter settings
916    * 
917    * @throws IOException
918    */
919   @Test(groups = { "Functional" })
920   public void testSaveLoadFeatureColoursAndFilters() throws IOException
921   {
922     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
923             ">Seq1\nACDEFGHIKLM", DataSourceType.PASTE);
924     SequenceI seq1 = af.getViewport().getAlignment().getSequenceAt(0);
925
926     /*
927      * add some features to the sequence
928      */
929     int score = 1;
930     addFeatures(seq1, "type1", score++);
931     addFeatures(seq1, "type2", score++);
932     addFeatures(seq1, "type3", score++);
933     addFeatures(seq1, "type4", score++);
934     addFeatures(seq1, "type5", score++);
935
936     /*
937      * set colour schemes for features
938      */
939     FeatureRendererModel fr = af.getFeatureRenderer();
940     fr.findAllFeatures(true);
941
942     // type1: red
943     fr.setColour("type1", new FeatureColour(Color.red));
944
945     // type2: by label
946     FeatureColourI byLabel = new FeatureColour();
947     byLabel.setColourByLabel(true);
948     fr.setColour("type2", byLabel);
949
950     // type3: by score above threshold
951     FeatureColourI byScore = new FeatureColour(null, Color.BLACK,
952             Color.BLUE, null, 1, 10);
953     byScore.setAboveThreshold(true);
954     byScore.setThreshold(2f);
955     fr.setColour("type3", byScore);
956
957     // type4: by attribute AF
958     FeatureColourI byAF = new FeatureColour();
959     byAF.setColourByLabel(true);
960     byAF.setAttributeName("AF");
961     fr.setColour("type4", byAF);
962
963     // type5: by attribute CSQ:PolyPhen below threshold
964     FeatureColourI byPolyPhen = new FeatureColour(null, Color.BLACK,
965             Color.BLUE, null, 1, 10);
966     byPolyPhen.setBelowThreshold(true);
967     byPolyPhen.setThreshold(3f);
968     byPolyPhen.setAttributeName("CSQ", "PolyPhen");
969     fr.setColour("type5", byPolyPhen);
970
971     /*
972      * set filters for feature types
973      */
974
975     // filter type1 features by (label contains "x")
976     FeatureMatcherSetI filterByX = new FeatureMatcherSet();
977     filterByX.and(FeatureMatcher.byLabel(Condition.Contains, "x"));
978     fr.setFeatureFilter("type1", filterByX);
979
980     // filter type2 features by (score <= 2.4 and score > 1.1)
981     FeatureMatcherSetI filterByScore = new FeatureMatcherSet();
982     filterByScore.and(FeatureMatcher.byScore(Condition.LE, "2.4"));
983     filterByScore.and(FeatureMatcher.byScore(Condition.GT, "1.1"));
984     fr.setFeatureFilter("type2", filterByScore);
985
986     // filter type3 features by (AF contains X OR CSQ:PolyPhen != 0)
987     FeatureMatcherSetI filterByXY = new FeatureMatcherSet();
988     filterByXY
989             .and(FeatureMatcher.byAttribute(Condition.Contains, "X", "AF"));
990     filterByXY.or(FeatureMatcher.byAttribute(Condition.NE, "0", "CSQ",
991             "PolyPhen"));
992     fr.setFeatureFilter("type3", filterByXY);
993
994     /*
995      * save as Jalview project
996      */
997     File tfile = File.createTempFile("JalviewTest", ".jvp");
998     tfile.deleteOnExit();
999     String filePath = tfile.getAbsolutePath();
1000     af.saveAlignment(filePath, FileFormat.Jalview);
1001     assertTrue(af.isSaveAlignmentSuccessful(),
1002             "Failed to store as a project.");
1003
1004     /*
1005      * close current alignment and load the saved project
1006      */
1007     af.closeMenuItem_actionPerformed(true);
1008     af = null;
1009     af = new FileLoader().LoadFileWaitTillLoaded(filePath,
1010             DataSourceType.FILE);
1011     assertNotNull(af, "Failed to import new project");
1012
1013     /*
1014      * verify restored feature colour schemes and filters
1015      */
1016     fr = af.getFeatureRenderer();
1017     FeatureColourI fc = fr.getFeatureStyle("type1");
1018     assertTrue(fc.isSimpleColour());
1019     assertEquals(fc.getColour(), Color.red);
1020     fc = fr.getFeatureStyle("type2");
1021     assertTrue(fc.isColourByLabel());
1022     fc = fr.getFeatureStyle("type3");
1023     assertTrue(fc.isGraduatedColour());
1024     assertNull(fc.getAttributeName());
1025     assertTrue(fc.isAboveThreshold());
1026     assertEquals(fc.getThreshold(), 2f);
1027     fc = fr.getFeatureStyle("type4");
1028     assertTrue(fc.isColourByLabel());
1029     assertTrue(fc.isColourByAttribute());
1030     assertEquals(fc.getAttributeName(), new String[] { "AF" });
1031     fc = fr.getFeatureStyle("type5");
1032     assertTrue(fc.isGraduatedColour());
1033     assertTrue(fc.isColourByAttribute());
1034     assertEquals(fc.getAttributeName(), new String[] { "CSQ", "PolyPhen" });
1035     assertTrue(fc.isBelowThreshold());
1036     assertEquals(fc.getThreshold(), 3f);
1037
1038     assertEquals(fr.getFeatureFilter("type1").toStableString(),
1039             "Label Contains x");
1040     assertEquals(fr.getFeatureFilter("type2").toStableString(),
1041             "(Score LE 2.4) AND (Score GT 1.1)");
1042     assertEquals(fr.getFeatureFilter("type3").toStableString(),
1043             "(AF Contains X) OR (CSQ:PolyPhen NE 0)");
1044   }
1045
1046   private void addFeature(SequenceI seq, String featureType, int score)
1047   {
1048     SequenceFeature sf = new SequenceFeature(featureType, "desc", 1, 2,
1049             score, "grp");
1050     sf.setValue("AF", score);
1051     sf.setValue("CSQ", new HashMap<String, String>()
1052     {
1053       {
1054         put("PolyPhen", Integer.toString(score));
1055       }
1056     });
1057     seq.addSequenceFeature(sf);
1058   }
1059
1060   /**
1061    * Adds two features of the given type to the given sequence, also setting the
1062    * score as the value of attribute "AF" and sub-attribute "CSQ:PolyPhen"
1063    * 
1064    * @param seq
1065    * @param featureType
1066    * @param score
1067    */
1068   private void addFeatures(SequenceI seq, String featureType, int score)
1069   {
1070     addFeature(seq, featureType, score++);
1071     addFeature(seq, featureType, score);
1072   }
1073
1074   /**
1075    * pre 2.11 - jalview 2.10 erroneously created new dataset entries for each
1076    * view (JAL-3171) this test ensures we can import and merge those views
1077    */
1078   @Test(groups = { "Functional" })
1079   public void testMergeDatasetsforViews() throws IOException
1080   {
1081     // simple project - two views on one alignment
1082     AlignFrame af = new FileLoader(false).LoadFileWaitTillLoaded(
1083             "examples/testdata/projects/twoViews.jvp", DataSourceType.FILE);
1084     assertNotNull(af);
1085     assertTrue(af.getAlignPanels().size() > 1);
1086     verifyDs(af);
1087   }
1088
1089   /**
1090    * pre 2.11 - jalview 2.10 erroneously created new dataset entries for each
1091    * view (JAL-3171) this test ensures we can import and merge those views This
1092    * is a more complex project
1093    */
1094   @Test(groups = { "Functional" })
1095   public void testMergeDatasetsforManyViews() throws IOException
1096   {
1097     Desktop.instance.closeAll_actionPerformed(null);
1098
1099     // complex project - one dataset, several views on several alignments
1100     AlignFrame af = new FileLoader(false).LoadFileWaitTillLoaded(
1101             "examples/testdata/projects/manyViews.jvp",
1102             DataSourceType.FILE);
1103     assertNotNull(af);
1104
1105     AlignmentI ds = null;
1106     for (AlignFrame alignFrame : Desktop.getAlignFrames())
1107     {
1108       if (ds == null)
1109       {
1110         ds = verifyDs(alignFrame);
1111       }
1112       else
1113       {
1114         // check that this frame's dataset matches the last
1115         assertTrue(ds == verifyDs(alignFrame));
1116       }
1117     }
1118   }
1119
1120   private AlignmentI verifyDs(AlignFrame af)
1121   {
1122     AlignmentI ds = null;
1123     for (AlignmentViewPanel ap : af.getAlignPanels())
1124     {
1125       if (ds == null)
1126       {
1127         ds = ap.getAlignment().getDataset();
1128       }
1129       else
1130       {
1131         assertTrue(ap.getAlignment().getDataset() == ds,
1132                 "Dataset was not the same for imported 2.10.5 project with several alignment views");
1133       }
1134     }
1135     return ds;
1136   }
1137
1138   @Test(groups = "Functional")
1139   public void testPcaViewAssociation() throws IOException
1140   {
1141     Desktop.instance.closeAll_actionPerformed(null);
1142     final String PCAVIEWNAME = "With PCA";
1143     // create a new tempfile
1144     File tempfile = File.createTempFile("jvPCAviewAssoc", "jvp");
1145
1146     {
1147       String exampleFile = "examples/uniref50.fa";
1148       AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(exampleFile,
1149               DataSourceType.FILE);
1150       assertNotNull(af, "Didn't read in the example file correctly.");
1151       AlignmentPanel origView = (AlignmentPanel) af.getAlignPanels().get(0);
1152       AlignmentPanel newview = af.newView(PCAVIEWNAME, true);
1153       // create another for good measure
1154       af.newView("Not the PCA View", true);
1155       PCAPanel pcaPanel = new PCAPanel(origView, "BLOSUM62",
1156               new SimilarityParams(true, true, true, false));
1157       // we're in the test exec thread, so we can just run synchronously here
1158       pcaPanel.run();
1159
1160       // now switch the linked view
1161       pcaPanel.selectAssociatedView(newview);
1162
1163       assertTrue(pcaPanel.getAlignViewport() == newview.getAlignViewport(),
1164               "PCA should be associated with 'With PCA' view: test is broken");
1165
1166       // now save and reload project
1167       Jalview2XML jv2xml = new jalview.project.Jalview2XML(false);
1168       tempfile.delete();
1169       jv2xml.saveState(tempfile);
1170       assertTrue(jv2xml.errorMessage == null,
1171               "Failed to save dummy project with PCA: test broken");
1172     }
1173
1174     // load again.
1175     Desktop.instance.closeAll_actionPerformed(null);
1176     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
1177             tempfile.getCanonicalPath(), DataSourceType.FILE);
1178     JInternalFrame[] frames = Desktop.instance.getAllFrames();
1179     // PCA and the tabbed alignment view should be the only two windows on the
1180     // desktop
1181     assertEquals(frames.length, 2,
1182             "PCA and the tabbed alignment view should be the only two windows on the desktop");
1183     PCAPanel pcaPanel = (PCAPanel) frames[frames[0] == af ? 1 : 0];
1184
1185     AlignmentViewPanel restoredNewView = null;
1186     for (AlignmentViewPanel alignpanel : Desktop.getAlignmentPanels(null))
1187     {
1188       if (alignpanel.getAlignViewport() == pcaPanel.getAlignViewport())
1189       {
1190         restoredNewView = alignpanel;
1191       }
1192     }
1193     assertEquals(restoredNewView.getViewName(), PCAVIEWNAME);
1194     assertTrue(
1195             restoredNewView.getAlignViewport() == pcaPanel
1196                     .getAlignViewport(),
1197             "Didn't restore correct view association for the PCA view");
1198   }
1199
1200   /**
1201    * Test save and reload of DBRefEntry including GeneLocus in project
1202    * 
1203    * @throws Exception
1204    */
1205   @Test(groups = { "Functional" })
1206   public void testStoreAndRecoverGeneLocus() throws Exception
1207   {
1208     Desktop.instance.closeAll_actionPerformed(null);
1209     String seqData = ">P30419\nACDE\n>X1235\nGCCTGTGACGAA";
1210     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(seqData,
1211             DataSourceType.PASTE);
1212     assertNotNull(af, "Didn't read in the example file correctly.");
1213   
1214     AlignmentViewPanel ap = Desktop.getAlignmentPanels(null)[0];
1215     SequenceI pep = ap.getAlignment().getSequenceAt(0);
1216     SequenceI cds = ap.getAlignment().getSequenceAt(1);
1217
1218     /*
1219      * give 'protein' a dbref to self, a dbref with map to CDS,
1220      * and a dbref with map to gene 'locus'
1221      */
1222     DBRefEntry dbref1 = new DBRefEntry("Uniprot", "1", "P30419", null);
1223     pep.addDBRef(dbref1);
1224     Mapping cdsmap = new Mapping(cds,
1225             new MapList(new int[]
1226             { 1, 4 }, new int[] { 1, 12 }, 1, 3));
1227     DBRefEntry dbref2 = new DBRefEntry("EMBLCDS", "2", "X1235", cdsmap);
1228     pep.addDBRef(dbref2);
1229     Mapping locusmap = new Mapping(null,
1230             new MapList(new int[]
1231             { 1, 4 }, new int[] { 2674123, 2674135 }, 1, 3));
1232     DBRefEntry dbref3 = new GeneLocus("human", "GRCh38", "5", locusmap);
1233     pep.addDBRef(dbref3);
1234
1235     File tfile = File.createTempFile("testStoreAndRecoverGeneLocus",
1236             ".jvp");
1237     try
1238     {
1239       new Jalview2XML(false).saveState(tfile);
1240     } catch (Throwable e)
1241     {
1242       Assert.fail("Didn't save the state", e);
1243     }
1244     Desktop.instance.closeAll_actionPerformed(null);
1245   
1246     new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
1247             DataSourceType.FILE);
1248     AlignmentViewPanel rap = Desktop.getAlignmentPanels(null)[0];
1249     SequenceI rpep = rap.getAlignment().getSequenceAt(0);
1250     DBModList<DBRefEntry> dbrefs = rpep.getDBRefs();
1251     assertEquals(rpep.getName(), "P30419");
1252     assertEquals(dbrefs.size(), 3);
1253     DBRefEntry dbRef = dbrefs.get(0);
1254     assertFalse(dbRef instanceof GeneLocus);
1255     assertNull(dbRef.getMap());
1256     assertEquals(dbRef, dbref1);
1257
1258     /*
1259      * restored dbrefs with mapping have a different 'map to'
1260      * sequence but otherwise match the original dbrefs
1261      */
1262     dbRef = dbrefs.get(1);
1263     assertFalse(dbRef instanceof GeneLocus);
1264     assertTrue(dbRef.equalRef(dbref2));
1265     assertNotNull(dbRef.getMap());
1266     SequenceI rcds = rap.getAlignment().getSequenceAt(1);
1267     assertSame(dbRef.getMap().getTo(), rcds);
1268     // compare MapList but not map.to
1269     assertEquals(dbRef.getMap().getMap(), dbref2.getMap().getMap());
1270
1271     /*
1272      * GeneLocus map.to is null so can compare Mapping objects
1273      */
1274     dbRef = dbrefs.get(2);
1275     assertTrue(dbRef instanceof GeneLocus);
1276     assertEquals(dbRef, dbref3);
1277   }
1278
1279   /**
1280    * test store and recovery of Overview windows
1281    * 
1282    * @throws Exception
1283    */
1284   @Test(groups = { "Functional" }, enabled = true)
1285   public void testStoreAndRecoverOverview() throws Exception
1286   {
1287     Desktop.instance.closeAll_actionPerformed(null);
1288     
1289     Cache.setProperty("SHOW_OVERVIEW",  "false");
1290     Cache.setProperty(Preferences.USE_LEGACY_GAP, "false");
1291     Cache.setColourProperty(Preferences.GAP_COLOUR, Color.green);
1292     Cache.setColourProperty(Preferences.HIDDEN_COLOUR, Color.yellow);
1293     Cache.setProperty(Preferences.SHOW_OV_HIDDEN_AT_START, "true");
1294     
1295     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
1296             "examples/uniref50.fa", DataSourceType.FILE);
1297     
1298     /*
1299      * open and resize / reposition overview 
1300      */
1301     af.overviewMenuItem_actionPerformed(null);
1302     OverviewPanel ov1 = af.alignPanel.getOverviewPanel();
1303     assertNotNull(ov1);
1304     ov1.setFrameBounds(20,  30,  200,  400);
1305     assertEquals(ov1.getTitle(), "Overview examples/uniref50.fa");
1306     
1307     /*
1308      * open a New View and its Overview and reposition it
1309      */
1310     af.newView_actionPerformed(null);
1311     af.overviewMenuItem_actionPerformed(null);
1312     OverviewPanel ov2 = af.alignPanel.getOverviewPanel();
1313     assertNotNull(ov2);
1314     assertNotSame(ov1, ov2);
1315     ov2.setFrameBounds(25,  35,  205,  405);
1316     assertEquals(ov1.getTitle(), "Overview examples/uniref50.fa Original");
1317     assertEquals(ov2.getTitle(), "Overview examples/uniref50.fa View 1");
1318     
1319     
1320     File tfile = File.createTempFile("testStoreAndRecoverOverview", ".jvp");
1321     new Jalview2XML(false).saveState(tfile);
1322     Desktop.instance.closeAll_actionPerformed(null);
1323     
1324     /*
1325      * change preferences (should _not_ affect reloaded Overviews)
1326      */
1327     Cache.setProperty("SHOW_OVERVIEW",  "true");
1328     Cache.setProperty(Preferences.USE_LEGACY_GAP, "true");
1329     Cache.setColourProperty(Preferences.GAP_COLOUR, Color.blue);
1330     Cache.setColourProperty(Preferences.HIDDEN_COLOUR, Color.orange);
1331     Cache.setProperty(Preferences.SHOW_OV_HIDDEN_AT_START, "false");
1332     
1333     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
1334             DataSourceType.FILE);
1335     
1336     /*
1337      * workaround: explicitly select View 1 (not in focus after restore)
1338      */
1339     af.tabSelectionChanged(1);
1340     
1341     /*
1342      * verify restored overview for View 1
1343      */
1344     ov2 = af.alignPanel.getOverviewPanel();
1345     assertEquals(ov2.getCanvas().getGapColour(), Color.green);
1346     // 'non-legacy' colouring uses white for non-gapped residues
1347     assertEquals(ov2.getCanvas().getResidueColour(), Color.white);
1348     assertEquals(ov2.getCanvas().getHiddenColour(), Color.yellow);
1349     assertEquals(ov2.getTitle(), "Overview examples/uniref50.fa View 1");
1350     assertEquals(ov2.getFrameBounds(), new Rectangle(25,  35,  205,  405));
1351     
1352     
1353     /*
1354      * verify restored overview for Original view
1355      */
1356     af.tabSelectionChanged(0);
1357     ov1 = af.alignPanel.getOverviewPanel();
1358     assertEquals(ov1.getCanvas().getGapColour(), Color.green);
1359     // 'non-legacy' colouring uses white for non-gapped residues
1360     assertEquals(ov1.getCanvas().getResidueColour(), Color.white);
1361     assertEquals(ov1.getCanvas().getHiddenColour(), Color.yellow);
1362     assertEquals(ov1.getTitle(), "Overview examples/uniref50.fa Original");
1363     assertEquals(ov1.getFrameBounds(), new Rectangle(20,  30,  200,  400));
1364   }
1365 }