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