JAL-2164 prevent jalview news from opening
[jalview.git] / test / jalview / io / 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.io;
22
23 import static org.testng.AssertJUnit.assertEquals;
24 import static org.testng.AssertJUnit.assertFalse;
25 import static org.testng.AssertJUnit.assertNotNull;
26 import static org.testng.AssertJUnit.assertSame;
27 import static org.testng.AssertJUnit.assertTrue;
28
29 import jalview.api.AlignViewportI;
30 import jalview.api.AlignmentViewPanel;
31 import jalview.api.ViewStyleI;
32 import jalview.bin.Cache;
33 import jalview.datamodel.AlignmentAnnotation;
34 import jalview.datamodel.AlignmentI;
35 import jalview.datamodel.HiddenSequences;
36 import jalview.datamodel.SequenceCollectionI;
37 import jalview.datamodel.SequenceGroup;
38 import jalview.datamodel.SequenceI;
39 import jalview.gui.AlignFrame;
40 import jalview.gui.Desktop;
41 import jalview.gui.Jalview2XML;
42 import jalview.schemes.AnnotationColourGradient;
43 import jalview.schemes.ColourSchemeI;
44 import jalview.viewmodel.AlignmentViewport;
45
46 import java.io.File;
47 import java.time.Instant;
48 import java.util.ArrayList;
49 import java.util.Date;
50 import java.util.HashMap;
51 import java.util.List;
52 import java.util.Map;
53
54 import org.testng.Assert;
55 import org.testng.AssertJUnit;
56 import org.testng.annotations.AfterClass;
57 import org.testng.annotations.BeforeClass;
58 import org.testng.annotations.Test;
59
60 @Test(singleThreaded = true)
61 public class Jalview2xmlTests
62 {
63
64   /**
65    * @throws java.lang.Exception
66    */
67   @BeforeClass(alwaysRun = true)
68   public static void setUpBeforeClass() throws Exception
69   {
70     jalview.bin.Jalview.main(new String[] { "-props",
71         "test/jalview/io/testProps.jvprops" });
72     jalview.bin.Cache.setProperty("JALVIEW_NEWS_RSS_LASTMODIFIED",
73             Cache.date_format.format(Date.from(Instant.now().plusSeconds(
74                     3600))));
75   }
76
77   /**
78    * @throws java.lang.Exception
79    */
80   @AfterClass(alwaysRun = true)
81   public static void tearDownAfterClass() throws Exception
82   {
83     jalview.gui.Desktop.instance.closeAll_actionPerformed(null);
84   }
85
86   int countDsAnn(jalview.viewmodel.AlignmentViewport avp)
87   {
88     int numdsann = 0;
89     for (SequenceI sq : avp.getAlignment().getDataset().getSequences())
90     {
91       if (sq.getAnnotation() != null)
92       {
93         for (AlignmentAnnotation dssa : sq.getAnnotation())
94         {
95           if (dssa.isValidStruc())
96           {
97             numdsann++;
98           }
99         }
100       }
101     }
102     return numdsann;
103   }
104
105   @Test(groups = { "Functional" })
106   public void testRNAStructureRecovery() throws Exception
107   {
108     String inFile = "examples/RF00031_folded.stk";
109     String tfile = File.createTempFile("JalviewTest", ".jvp")
110             .getAbsolutePath();
111     AlignFrame af = new jalview.io.FileLoader().LoadFileWaitTillLoaded(
112             inFile, FormatAdapter.FILE);
113     assertTrue("Didn't read input file " + inFile, af != null);
114     int olddsann = countDsAnn(af.getViewport());
115     assertTrue("Didn't find any dataset annotations", olddsann > 0);
116     af.rnahelicesColour_actionPerformed(null);
117     assertTrue(
118             "Couldn't apply RNA helices colourscheme",
119             af.getViewport().getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
120     assertTrue("Failed to store as a project.",
121             af.saveAlignment(tfile, "Jalview"));
122     af.closeMenuItem_actionPerformed(true);
123     af = null;
124     af = new jalview.io.FileLoader().LoadFileWaitTillLoaded(tfile,
125             FormatAdapter.FILE);
126     assertTrue("Failed to import new project", af != null);
127     int newdsann = countDsAnn(af.getViewport());
128     assertTrue(
129             "Differing numbers of dataset sequence annotation\nOriginally "
130                     + olddsann + " and now " + newdsann,
131             olddsann == newdsann);
132     System.out
133             .println("Read in same number of annotations as originally present ("
134                     + olddsann + ")");
135     assertTrue(
136             "RNA helices colourscheme was not applied on import.",
137             af.getViewport().getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
138   }
139
140   @Test(groups = { "Functional" })
141   public void testTCoffeeScores() throws Exception
142   {
143     String inFile = "examples/uniref50.fa", inAnnot = "examples/uniref50.score_ascii";
144     String tfile = File.createTempFile("JalviewTest", ".jvp")
145             .getAbsolutePath();
146     AlignFrame af = new jalview.io.FileLoader().LoadFileWaitTillLoaded(
147             inFile, FormatAdapter.FILE);
148     assertTrue("Didn't read input file " + inFile, af != null);
149     af.loadJalviewDataFile(inAnnot, FormatAdapter.FILE, null, null);
150     assertTrue(
151             "Didn't set T-coffee colourscheme",
152             af.getViewport().getGlobalColourScheme().getClass()
153                     .equals(jalview.schemes.TCoffeeColourScheme.class));
154     assertTrue(
155             "Recognise T-Coffee score from string",
156             jalview.schemes.ColourSchemeProperty.getColour(af.getViewport()
157                     .getAlignment(),
158                     jalview.schemes.ColourSchemeProperty.getColourName(af
159                             .getViewport().getGlobalColourScheme())) != null);
160
161     assertTrue("Failed to store as a project.",
162             af.saveAlignment(tfile, "Jalview"));
163     af.closeMenuItem_actionPerformed(true);
164     af = null;
165     af = new jalview.io.FileLoader().LoadFileWaitTillLoaded(tfile,
166             FormatAdapter.FILE);
167     assertTrue("Failed to import new project", af != null);
168     assertTrue(
169             "Didn't set T-coffee colourscheme for imported project.",
170             af.getViewport().getGlobalColourScheme().getClass()
171                     .equals(jalview.schemes.TCoffeeColourScheme.class));
172     System.out
173             .println("T-Coffee score shading successfully recovered from project.");
174   }
175
176   @Test(groups = { "Functional" })
177   public void testColourByAnnotScores() throws Exception
178   {
179     String inFile = "examples/uniref50.fa", inAnnot = "examples/testdata/uniref50_iupred.jva";
180     String tfile = File.createTempFile("JalviewTest", ".jvp")
181             .getAbsolutePath();
182     AlignFrame af = new jalview.io.FileLoader().LoadFileWaitTillLoaded(
183             inFile, FormatAdapter.FILE);
184     assertTrue("Didn't read input file " + inFile, af != null);
185     af.loadJalviewDataFile(inAnnot, FormatAdapter.FILE, null, null);
186     AlignmentAnnotation[] aa = af.getViewport().getAlignment()
187             .getSequenceAt(0).getAnnotation("IUPredWS (Short)");
188     assertTrue(
189             "Didn't find any IUPred annotation to use to shade alignment.",
190             aa != null && aa.length > 0);
191     AnnotationColourGradient cs = new jalview.schemes.AnnotationColourGradient(
192             aa[0], null, AnnotationColourGradient.ABOVE_THRESHOLD);
193     AnnotationColourGradient gcs = new jalview.schemes.AnnotationColourGradient(
194             aa[0], null, AnnotationColourGradient.BELOW_THRESHOLD);
195     cs.setSeqAssociated(true);
196     gcs.setSeqAssociated(true);
197     af.changeColour(cs);
198     SequenceGroup sg = new SequenceGroup();
199     sg.setStartRes(57);
200     sg.setEndRes(92);
201     sg.cs = gcs;
202     af.getViewport().getAlignment().addGroup(sg);
203     sg.addSequence(af.getViewport().getAlignment().getSequenceAt(1), false);
204     sg.addSequence(af.getViewport().getAlignment().getSequenceAt(2), true);
205     af.alignPanel.alignmentChanged();
206     assertTrue("Failed to store as a project.",
207             af.saveAlignment(tfile, "Jalview"));
208     af.closeMenuItem_actionPerformed(true);
209     af = null;
210     af = new jalview.io.FileLoader().LoadFileWaitTillLoaded(tfile,
211             FormatAdapter.FILE);
212     assertTrue("Failed to import new project", af != null);
213
214     // check for group and alignment colourschemes
215
216     ColourSchemeI _rcs = af.getViewport().getGlobalColourScheme();
217     ColourSchemeI _rgcs = af.getViewport().getAlignment().getGroups()
218             .get(0).cs;
219     assertTrue("Didn't recover global colourscheme", _rcs != null);
220     assertTrue("Didn't recover annotation colour global scheme",
221             _rcs instanceof AnnotationColourGradient);
222     AnnotationColourGradient __rcs = (AnnotationColourGradient) _rcs;
223     assertTrue("Annotation colourscheme wasn't sequence associated",
224             __rcs.isSeqAssociated());
225
226     boolean diffseqcols = false, diffgseqcols = false;
227     SequenceI[] sqs = af.getViewport().getAlignment().getSequencesArray();
228     for (int p = 0, pSize = af.getViewport().getAlignment().getWidth(); p < pSize
229             && (!diffseqcols || !diffgseqcols); p++)
230     {
231       if (_rcs.findColour(sqs[0].getCharAt(p), p, sqs[0]) != _rcs
232               .findColour(sqs[5].getCharAt(p), p, sqs[5]))
233       {
234         diffseqcols = true;
235       }
236     }
237     assertTrue("Got Different sequence colours", diffseqcols);
238     System.out
239             .println("Per sequence colourscheme (Background) successfully applied and recovered.");
240
241     assertTrue("Didn't recover group colourscheme", _rgcs != null);
242     assertTrue("Didn't recover annotation colour group colourscheme",
243             _rgcs instanceof AnnotationColourGradient);
244     __rcs = (AnnotationColourGradient) _rgcs;
245     assertTrue("Group Annotation colourscheme wasn't sequence associated",
246             __rcs.isSeqAssociated());
247
248     for (int p = 0, pSize = af.getViewport().getAlignment().getWidth(); p < pSize
249             && (!diffseqcols || !diffgseqcols); p++)
250     {
251       if (_rgcs.findColour(sqs[1].getCharAt(p), p, sqs[1]) != _rgcs
252               .findColour(sqs[2].getCharAt(p), p, sqs[2]))
253       {
254         diffgseqcols = true;
255       }
256     }
257     assertTrue("Got Different group sequence colours", diffgseqcols);
258     System.out
259             .println("Per sequence (Group) colourscheme successfully applied and recovered.");
260   }
261
262   @Test(groups = { "Functional" })
263   public void gatherViewsHere() throws Exception
264   {
265     int origCount = Desktop.getAlignFrames() == null ? 0 : Desktop
266             .getAlignFrames().length;
267     AlignFrame af = new jalview.io.FileLoader().LoadFileWaitTillLoaded(
268             "examples/exampleFile_2_7.jar", FormatAdapter.FILE);
269     assertTrue("Didn't read in the example file correctly.", af != null);
270     assertTrue("Didn't gather the views in the example file.",
271             Desktop.getAlignFrames().length == 1 + origCount);
272
273   }
274
275   @Test(groups = { "Functional" })
276   public void viewRefPdbAnnotation() throws Exception
277   {
278     Cache.applicationProperties.setProperty("STRUCT_FROM_PDB",
279             Boolean.TRUE.toString());
280     Cache.applicationProperties.setProperty("ADD_SS_ANN",
281             Boolean.TRUE.toString());
282     AlignFrame af = new jalview.io.FileLoader().LoadFileWaitTillLoaded(
283             "examples/exampleFile_2_7.jar", FormatAdapter.FILE);
284     assertTrue("Didn't read in the example file correctly.", af != null);
285     AlignmentViewPanel sps = null;
286     for (AlignmentViewPanel ap : af.alignPanel.alignFrame.getAlignPanels())
287     {
288       if ("Spinach Feredoxin Structure".equals(ap.getViewName()))
289       {
290         sps = ap;
291         break;
292       }
293     }
294     assertTrue("Couldn't find the structure view", sps != null);
295     SequenceI sq = sps.getAlignment().findName("1A70|");
296     AlignmentAnnotation refan = null;
297     for (AlignmentAnnotation ra : sps.getAlignment()
298             .getAlignmentAnnotation())
299     {
300       if (ra.graph != 0)
301       {
302         refan = ra;
303         break;
304       }
305     }
306     assertTrue("Annotation secondary structure not found.", refan != null);
307     assertTrue("Couldn't find 1a70 null chain", sq != null);
308     // compare the manually added temperature factor annotation
309     // to the track automatically transferred from the pdb structure on load
310     for (AlignmentAnnotation ala : sq.getDatasetSequence().getAnnotation())
311     {
312       AlignmentAnnotation alaa;
313       sq.addAlignmentAnnotation(alaa = new AlignmentAnnotation(ala));
314       alaa.adjustForAlignment();
315       if (ala.graph == refan.graph)
316       {
317         for (int p = 0; p < ala.annotations.length; p++)
318         {
319           sq.findPosition(p);
320           try
321           {
322             assertTrue(
323                     "Mismatch at alignment position " + p,
324                     (alaa.annotations[p] == null && refan.annotations[p] == null)
325                             || alaa.annotations[p].value == refan.annotations[p].value);
326           } catch (NullPointerException q)
327           {
328             Assert.fail("Mismatch of alignment annotations at position "
329                     + p + " Ref seq ann: " + refan.annotations[p]
330                     + " alignment " + alaa.annotations[p]);
331           }
332         }
333       }
334     }
335
336   }
337
338   @Test(groups = { "Functional" })
339   public void testCopyViewSettings() throws Exception
340   {
341     AlignFrame af = new jalview.io.FileLoader().LoadFileWaitTillLoaded(
342             "examples/exampleFile_2_7.jar", FormatAdapter.FILE);
343     assertTrue("Didn't read in the example file correctly.", af != null);
344     AlignmentViewPanel sps = null, groups = null;
345     for (AlignmentViewPanel ap : af.alignPanel.alignFrame.getAlignPanels())
346     {
347       if ("Spinach Feredoxin Structure".equals(ap.getViewName()))
348       {
349         sps = ap;
350       }
351       if (ap.getViewName().contains("MAFFT"))
352       {
353         groups = ap;
354       }
355     }
356     assertTrue("Couldn't find the structure view", sps != null);
357     assertTrue("Couldn't find the MAFFT view", groups != null);
358
359     ViewStyleI structureStyle = sps.getAlignViewport().getViewStyle();
360     ViewStyleI groupStyle = groups.getAlignViewport().getViewStyle();
361     AssertJUnit.assertFalse(structureStyle.sameStyle(groupStyle));
362
363     groups.getAlignViewport().setViewStyle(structureStyle);
364     AssertJUnit.assertFalse(groupStyle.sameStyle(groups.getAlignViewport()
365             .getViewStyle()));
366     Assert.assertTrue(structureStyle.sameStyle(groups.getAlignViewport()
367             .getViewStyle()));
368
369   }
370
371   /**
372    * test store and recovery of expanded views
373    * 
374    * @throws Exception
375    */
376   @Test(groups = { "Functional" }, enabled = true)
377   public void testStoreAndRecoverExpandedviews() throws Exception
378   {
379     Desktop.instance.closeAll_actionPerformed(null);
380
381     AlignFrame af = new jalview.io.FileLoader().LoadFileWaitTillLoaded(
382             "examples/exampleFile_2_7.jar", FormatAdapter.FILE);
383     assertTrue("Didn't read in the example file correctly.", af != null);
384     Assert.assertEquals(Desktop.getAlignFrames().length, 1);
385     String afid = af.getViewport().getSequenceSetId();
386
387     // check FileLoader returned a reference to the one alignFrame that is
388     // actually on the Desktop
389     assertTrue(
390             "Jalview2XML.loadAlignFrame() didn't return correct AlignFrame reference for multiple view window",
391             af == Desktop.getAlignFrameFor(af.getViewport()));
392
393     Desktop.explodeViews(af);
394
395     int oldviews = Desktop.getAlignFrames().length;
396     Assert.assertEquals(Desktop.getAlignFrames().length,
397             Desktop.getAlignmentPanels(afid).length);
398     File tfile = File.createTempFile("testStoreAndRecoverExpanded", ".jvp");
399     try
400     {
401       new Jalview2XML(false).saveState(tfile);
402     } catch (Error e)
403     {
404       Assert.fail("Didn't save the expanded view state", e);
405     } catch (Exception e)
406     {
407       Assert.fail("Didn't save the expanded view state", e);
408     }
409     Desktop.instance.closeAll_actionPerformed(null);
410     if (Desktop.getAlignFrames() != null)
411     {
412       Assert.assertEquals(Desktop.getAlignFrames().length, 0);
413     }
414     af = new jalview.io.FileLoader().LoadFileWaitTillLoaded(
415             tfile.getAbsolutePath(), FormatAdapter.FILE);
416     Assert.assertNotNull(af);
417     Assert.assertEquals(
418             Desktop.getAlignFrames().length,
419             Desktop.getAlignmentPanels(af.getViewport().getSequenceSetId()).length);
420     Assert.assertEquals(
421             oldviews,
422             Desktop.getAlignmentPanels(af.getViewport().getSequenceSetId()).length);
423   }
424
425   /**
426    * Test save and reload of a project with a different representative sequence
427    * in each view.
428    * 
429    * @throws Exception
430    */
431   @Test(groups = { "Functional" })
432   public void testStoreAndRecoverReferenceSeqSettings() throws Exception
433   {
434     Desktop.instance.closeAll_actionPerformed(null);
435     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
436             "examples/exampleFile_2_7.jar", FormatAdapter.FILE);
437     assertTrue("Didn't read in the example file correctly.", af != null);
438     String afid = af.getViewport().getSequenceSetId();
439
440     // remember reference sequence for each panel
441     Map<String, SequenceI> refseqs = new HashMap<String, SequenceI>();
442
443     /*
444      * mark sequence 2, 3, 4.. in panels 1, 2, 3...
445      * as reference sequence for itself and the preceding sequence
446      */
447     int n = 1;
448     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
449     {
450       AlignViewportI av = ap.getAlignViewport();
451       AlignmentI alignment = ap.getAlignment();
452       int repIndex = n % alignment.getHeight();
453       SequenceI rep = alignment.getSequenceAt(repIndex);
454       refseqs.put(ap.getViewName(), rep);
455
456       // code from mark/unmark sequence as reference in jalview.gui.PopupMenu
457       // todo refactor this to an alignment view controller
458       av.setDisplayReferenceSeq(true);
459       av.setColourByReferenceSeq(true);
460       av.getAlignment().setSeqrep(rep);
461
462       n++;
463     }
464     File tfile = File.createTempFile("testStoreAndRecoverReferenceSeq",
465             ".jvp");
466     try
467     {
468       new Jalview2XML(false).saveState(tfile);
469     } catch (Throwable e)
470     {
471       Assert.fail("Didn't save the expanded view state", e);
472     }
473     Desktop.instance.closeAll_actionPerformed(null);
474     if (Desktop.getAlignFrames() != null)
475     {
476       Assert.assertEquals(Desktop.getAlignFrames().length, 0);
477     }
478
479     af = new FileLoader().LoadFileWaitTillLoaded(
480             tfile.getAbsolutePath(), FormatAdapter.FILE);
481     afid = af.getViewport().getSequenceSetId();
482
483     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
484     {
485       // check representative
486       AlignmentI alignment = ap.getAlignment();
487       SequenceI rep = alignment.getSeqrep();
488       Assert.assertNotNull(rep,
489               "Couldn't restore sequence representative from project");
490       // can't use a strong equals here, because by definition, the sequence IDs
491       // will be different.
492       // could set vamsas session save/restore flag to preserve IDs across
493       // load/saves.
494       Assert.assertEquals(refseqs.get(ap.getViewName()).toString(),
495               rep.toString(),
496               "Representative wasn't the same when recovered.");
497       Assert.assertTrue(ap.getAlignViewport().isDisplayReferenceSeq(),
498               "Display reference sequence view setting not set.");
499       Assert.assertTrue(ap.getAlignViewport().isColourByReferenceSeq(),
500               "Colour By Reference Seq view setting not set.");
501     }
502   }
503
504   @Test(groups = { "Functional" })
505   public void testIsVersionStringLaterThan()
506   {
507     /*
508      * No version / development / test / autobuild is leniently assumed to be
509      * compatible
510      */
511     assertTrue(Jalview2XML.isVersionStringLaterThan(null, null));
512     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", null));
513     assertTrue(Jalview2XML.isVersionStringLaterThan(null, "2.8.3"));
514     assertTrue(Jalview2XML.isVersionStringLaterThan(null,
515             "Development Build"));
516     assertTrue(Jalview2XML.isVersionStringLaterThan(null,
517             "DEVELOPMENT BUILD"));
518     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3",
519             "Development Build"));
520     assertTrue(Jalview2XML.isVersionStringLaterThan(null, "Test"));
521     assertTrue(Jalview2XML.isVersionStringLaterThan(null, "TEST"));
522     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "Test"));
523     assertTrue(Jalview2XML
524             .isVersionStringLaterThan(null, "Automated Build"));
525     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3",
526             "Automated Build"));
527     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3",
528             "AUTOMATED BUILD"));
529
530     /*
531      * same version returns true i.e. compatible
532      */
533     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8", "2.8"));
534     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.3"));
535     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3b1", "2.8.3b1"));
536     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3B1", "2.8.3b1"));
537     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3b1", "2.8.3B1"));
538
539     /*
540      * later version returns true
541      */
542     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.4"));
543     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.9"));
544     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.9.2"));
545     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8", "2.8.3"));
546     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.3b1"));
547
548     /*
549      * earlier version returns false
550      */
551     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8"));
552     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.4", "2.8.3"));
553     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.3b1", "2.8.3"));
554     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.2b1"));
555     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.0b2", "2.8.0b1"));
556   }
557
558   /**
559    * Test save and reload of a project with a different sequence group (and
560    * representative sequence) in each view.
561    * 
562    * @throws Exception
563    */
564   @Test(groups = { "Functional" })
565   public void testStoreAndRecoverGroupRepSeqs() throws Exception
566   {
567     Desktop.instance.closeAll_actionPerformed(null);
568     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
569             "examples/uniref50.fa", FormatAdapter.FILE);
570     assertTrue("Didn't read in the example file correctly.", af != null);
571     String afid = af.getViewport().getSequenceSetId();
572     // make a second view of the alignment
573     af.newView_actionPerformed(null);
574   
575     /*
576      * remember representative and hidden sequences marked 
577      * on each panel
578      */
579     Map<String, SequenceI> repSeqs = new HashMap<String, SequenceI>();
580     Map<String, List<String>> hiddenSeqNames = new HashMap<String, List<String>>();
581   
582     /*
583      * mark sequence 2, 3, 4.. in panels 1, 2, 3...
584      * as reference sequence for itself and the preceding sequence
585      */
586     int n = 1;
587     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
588     {
589       AlignViewportI av = ap.getAlignViewport();
590       AlignmentI alignment = ap.getAlignment();
591       int repIndex = n % alignment.getHeight();
592       // ensure at least one preceding sequence i.e. index >= 1
593       repIndex = Math.max(repIndex, 1);
594       SequenceI repSeq = alignment.getSequenceAt(repIndex);
595       repSeqs.put(ap.getViewName(), repSeq);
596       List<String> hiddenNames = new ArrayList<String>();
597       hiddenSeqNames.put(ap.getViewName(), hiddenNames);
598   
599       /*
600        * have rep sequence represent itself and the one before it
601        * this hides the group (except for the rep seq)
602        */
603       SequenceGroup sg = new SequenceGroup();
604       sg.addSequence(repSeq, false);
605       SequenceI precedingSeq = alignment.getSequenceAt(repIndex - 1);
606       sg.addSequence(precedingSeq, false);
607       sg.setSeqrep(repSeq);
608       assertTrue(sg.getSequences().contains(repSeq));
609       assertTrue(sg.getSequences().contains(precedingSeq));
610       av.setSelectionGroup(sg);
611       assertSame(repSeq, sg.getSeqrep());
612
613       /*
614        * represent group with sequence adds to a map of hidden rep sequences
615        * (it does not create a group on the alignment) 
616        */
617       ((AlignmentViewport) av).hideSequences(repSeq, true);
618       assertSame(repSeq, sg.getSeqrep());
619       assertTrue(sg.getSequences().contains(repSeq));
620       assertTrue(sg.getSequences().contains(precedingSeq));
621       assertTrue("alignment has groups", alignment.getGroups().isEmpty());
622       Map<SequenceI, SequenceCollectionI> hiddenRepSeqsMap = av.getHiddenRepSequences();
623       assertNotNull(hiddenRepSeqsMap);
624       assertEquals(1, hiddenRepSeqsMap.size());
625       assertSame(sg, hiddenRepSeqsMap.get(repSeq));
626       assertTrue(alignment.getHiddenSequences().isHidden(precedingSeq));
627       assertFalse(alignment.getHiddenSequences().isHidden(repSeq));
628       hiddenNames.add(precedingSeq.getName());
629
630       n++;
631     }
632     File tfile = File
633             .createTempFile("testStoreAndRecoverGroupReps",
634             ".jvp");
635     try
636     {
637       new Jalview2XML(false).saveState(tfile);
638     } catch (Throwable e)
639     {
640       Assert.fail("Didn't save the expanded view state", e);
641     }
642     Desktop.instance.closeAll_actionPerformed(null);
643     if (Desktop.getAlignFrames() != null)
644     {
645       Assert.assertEquals(Desktop.getAlignFrames().length, 0);
646     }
647   
648     af = new FileLoader().LoadFileWaitTillLoaded(
649             tfile.getAbsolutePath(), FormatAdapter.FILE);
650     afid = af.getViewport().getSequenceSetId();
651   
652     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
653     {
654       String viewName = ap.getViewName();
655       AlignViewportI av = ap.getAlignViewport();
656       AlignmentI alignment = ap.getAlignment();
657       List<SequenceGroup> groups = alignment.getGroups();
658       assertNotNull(groups);
659       assertTrue("Alignment has groups", groups.isEmpty());
660       Map<SequenceI, SequenceCollectionI> hiddenRepSeqsMap = av
661               .getHiddenRepSequences();
662       assertNotNull("No hidden represented sequences", hiddenRepSeqsMap);
663       assertEquals(1, hiddenRepSeqsMap.size());
664       assertEquals(repSeqs.get(viewName).getDisplayId(true),
665               hiddenRepSeqsMap.keySet().iterator().next()
666                       .getDisplayId(true));
667
668       /*
669        * verify hidden sequences in restored panel
670        */
671       List<String> hidden = hiddenSeqNames.get(ap.getViewName());
672       HiddenSequences hs = alignment.getHiddenSequences();
673       assertEquals(
674               "wrong number of restored hidden sequences in "
675                       + ap.getViewName(),
676               hidden.size(), hs.getSize());
677     }
678   }
679 }