Merge branch 'develop' into features/filetypeEnum
authorgmungoc <g.m.carstairs@dundee.ac.uk>
Tue, 30 Aug 2016 11:56:34 +0000 (12:56 +0100)
committergmungoc <g.m.carstairs@dundee.ac.uk>
Tue, 30 Aug 2016 11:56:34 +0000 (12:56 +0100)
Conflicts:
src/jalview/io/AppletFormatAdapter.java
src/jalview/io/FormatAdapter.java
src/jalview/io/MSFfile.java
src/jalview/io/RnamlFile.java
src/jalview/io/StockholmFile.java
src/jalview/ws/dbsources/Pdb.java
test/jalview/ext/jmol/JmolParserTest.java
test/jalview/gui/AlignViewportTest.java
test/jalview/ws/jabaws/RNAStructExportImport.java

195 files changed:
.checkstyle [new file with mode: 0644]
examples/groovy/featureCounter.groovy
help/html/features/clarguments.html
help/html/features/dasfeatures.html
help/html/features/sifts_mapping_output.png
help/html/features/siftsmapping.html
help/html/features/varna.html
help/html/io/index.html
help/html/na/index.html
help/html/releases.html
help/html/webServices/index.html
help/html/webServices/newsreader.html
resources/lang/Messages.properties
resources/lang/Messages_es.properties
src/MCview/Atom.java
src/MCview/PDBChain.java
src/MCview/PDBfile.java
src/jalview/analysis/AAFrequency.java
src/jalview/analysis/AlignmentUtils.java
src/jalview/analysis/Conservation.java
src/jalview/analysis/CrossRef.java
src/jalview/analysis/Dna.java
src/jalview/analysis/Grouping.java
src/jalview/analysis/Rna.java
src/jalview/analysis/SequenceIdMatcher.java
src/jalview/analysis/StructureFrequency.java
src/jalview/api/AlignCalcManagerI.java
src/jalview/api/AlignCalcWorkerI.java
src/jalview/api/DBRefEntryI.java
src/jalview/appletgui/APopupMenu.java
src/jalview/appletgui/AlignFrame.java
src/jalview/appletgui/AnnotationColourChooser.java
src/jalview/appletgui/AnnotationPanel.java
src/jalview/appletgui/AnnotationRowFilter.java
src/jalview/appletgui/FeatureColourChooser.java
src/jalview/appletgui/FeatureRenderer.java
src/jalview/appletgui/FeatureSettings.java
src/jalview/appletgui/OverviewPanel.java
src/jalview/appletgui/ScalePanel.java
src/jalview/appletgui/SeqCanvas.java
src/jalview/appletgui/SeqPanel.java
src/jalview/appletgui/SliderPanel.java
src/jalview/bin/Cache.java
src/jalview/bin/Jalview.java
src/jalview/bin/JalviewLite.java
src/jalview/controller/AlignViewController.java
src/jalview/datamodel/AlignedCodonFrame.java
src/jalview/datamodel/Alignment.java
src/jalview/datamodel/AlignmentAnnotation.java
src/jalview/datamodel/AlignmentI.java
src/jalview/datamodel/AlignmentView.java
src/jalview/datamodel/CigarBase.java
src/jalview/datamodel/ColumnSelection.java
src/jalview/datamodel/DBRefEntry.java
src/jalview/datamodel/DBRefSource.java
src/jalview/datamodel/Mapping.java
src/jalview/datamodel/PDBEntry.java
src/jalview/datamodel/Sequence.java
src/jalview/datamodel/SequenceGroup.java
src/jalview/datamodel/SequenceI.java
src/jalview/datamodel/xdb/embl/EmblEntry.java
src/jalview/ext/ensembl/EnsemblInfo.java
src/jalview/ext/ensembl/EnsemblRestClient.java
src/jalview/ext/ensembl/EnsemblSeqProxy.java
src/jalview/ext/jmol/JmolParser.java
src/jalview/gui/AlignFrame.java
src/jalview/gui/AlignViewport.java
src/jalview/gui/AlignmentPanel.java
src/jalview/gui/AnnotationColourChooser.java
src/jalview/gui/AnnotationLabels.java
src/jalview/gui/AnnotationPanel.java
src/jalview/gui/AnnotationRowFilter.java
src/jalview/gui/BlogReader.java
src/jalview/gui/DasSourceBrowser.java
src/jalview/gui/Desktop.java
src/jalview/gui/FeatureColourChooser.java
src/jalview/gui/FeatureRenderer.java
src/jalview/gui/FeatureSettings.java
src/jalview/gui/FontChooser.java
src/jalview/gui/Jalview2XML.java
src/jalview/gui/Jalview2XML_V1.java
src/jalview/gui/OverviewPanel.java
src/jalview/gui/PCAPanel.java
src/jalview/gui/PopupMenu.java
src/jalview/gui/Preferences.java
src/jalview/gui/RedundancyPanel.java
src/jalview/gui/ScalePanel.java
src/jalview/gui/SeqCanvas.java
src/jalview/gui/SeqPanel.java
src/jalview/gui/SequenceFetcher.java
src/jalview/gui/SequenceRenderer.java
src/jalview/gui/SliderPanel.java
src/jalview/gui/SplitFrame.java
src/jalview/gui/TextColourChooser.java
src/jalview/gui/TreePanel.java
src/jalview/gui/UserDefinedColours.java
src/jalview/gui/WsParamSetManager.java
src/jalview/io/AlignFile.java
src/jalview/io/AppletFormatAdapter.java
src/jalview/io/BioJsHTMLOutput.java
src/jalview/io/FileFormat.java
src/jalview/io/HTMLOutput.java
src/jalview/io/HtmlSvgOutput.java
src/jalview/io/JSONFile.java
src/jalview/io/JalviewFileChooser.java
src/jalview/io/MSFfile.java
src/jalview/io/PfamFile.java
src/jalview/io/RnamlFile.java
src/jalview/io/StockholmFile.java
src/jalview/io/StructureFile.java
src/jalview/jbgui/GAlignFrame.java
src/jalview/jbgui/GFinder.java
src/jalview/jbgui/GStructureChooser.java
src/jalview/renderer/AnnotationRenderer.java
src/jalview/renderer/ScaleRenderer.java
src/jalview/renderer/seqfeatures/FeatureRenderer.java
src/jalview/schemes/ResidueProperties.java
src/jalview/structure/StructureImportSettings.java
src/jalview/structure/StructureSelectionManager.java
src/jalview/util/Comparison.java
src/jalview/util/DBRefUtils.java
src/jalview/util/ImageMaker.java
src/jalview/util/MapList.java
src/jalview/util/MappingUtils.java
src/jalview/util/Platform.java
src/jalview/viewmodel/AlignmentViewport.java
src/jalview/viewmodel/seqfeatures/FeatureRendererModel.java
src/jalview/workers/AlignCalcManager.java
src/jalview/workers/AlignCalcWorker.java
src/jalview/workers/AlignmentAnnotationFactory.java
src/jalview/workers/AnnotationProviderI.java
src/jalview/workers/AnnotationWorker.java
src/jalview/workers/ColumnCounterWorker.java
src/jalview/workers/ConsensusThread.java
src/jalview/workers/ConservationThread.java
src/jalview/workers/StrucConsensusThread.java
src/jalview/ws/AWSThread.java
src/jalview/ws/SequenceFetcher.java
src/jalview/ws/SequenceFetcherFactory.java [new file with mode: 0644]
src/jalview/ws/dbsources/Pdb.java
src/jalview/ws/jws1/Annotate3D.java
src/jalview/ws/jws1/JPredThread.java
src/jalview/ws/jws1/MsaWSClient.java
src/jalview/ws/jws1/MsaWSThread.java
src/jalview/ws/jws1/SeqSearchWSClient.java
src/jalview/ws/jws1/SeqSearchWSThread.java
src/jalview/ws/jws2/AbstractJabaCalcWorker.java
src/jalview/ws/jws2/MsaWSClient.java
src/jalview/ws/jws2/MsaWSThread.java
src/jalview/ws/jws2/SequenceAnnotationWSClient.java
src/jalview/ws/rest/params/Alignment.java
src/jalview/ws/seqfetcher/ASequenceFetcher.java
test/MCview/AtomTest.java
test/jalview/analysis/AlignmentUtilsTests.java
test/jalview/analysis/CrossRefTest.java
test/jalview/analysis/DnaTest.java
test/jalview/analysis/GroupingTest.java
test/jalview/analysis/RnaTest.java
test/jalview/analysis/SequenceIdMatcherTest.java
test/jalview/bin/CacheTest.java [new file with mode: 0644]
test/jalview/controller/AlignViewControllerTest.java [new file with mode: 0644]
test/jalview/datamodel/AlignedCodonFrameTest.java
test/jalview/datamodel/AlignmentAnnotationTests.java
test/jalview/datamodel/AlignmentTest.java
test/jalview/datamodel/ColumnSelectionTest.java
test/jalview/datamodel/MappingTest.java
test/jalview/datamodel/SequenceTest.java
test/jalview/datamodel/xdb/embl/EmblEntryTest.java
test/jalview/datamodel/xdb/embl/EmblFileTest.java
test/jalview/datamodel/xdb/embl/EmblTestHelper.java
test/jalview/ext/jmol/JmolParserTest.java
test/jalview/ext/jmol/JmolVsJalviewPDBParserEndToEndTest.java [new file with mode: 0644]
test/jalview/gui/AlignViewportTest.java
test/jalview/io/AnnotatedPDBFileInputTest.java
test/jalview/io/FormatAdapterTest.java [new file with mode: 0644]
test/jalview/io/Jalview2xmlTests.java
test/jalview/io/StockholmFileTest.java
test/jalview/schemes/UserColourSchemeTest.java
test/jalview/structure/StructureSelectionManagerTest.java
test/jalview/util/DBRefUtilsTest.java
test/jalview/util/MapListTest.java
test/jalview/util/MappingUtilsTest.java
test/jalview/workers/AlignCalcManagerTest.java [new file with mode: 0644]
test/jalview/ws/PDBSequenceFetcherTest.java
test/jalview/ws/SequenceFetcherTest.java
test/jalview/ws/jabaws/RNAStructExportImport.java
test/jalview/ws/seqfetcher/DbRefFetcherTest.java
test/jalview/ws/sifts/SiftsClientTest.java
utils/HelpLinksChecker.java
utils/MessageBundleChecker.java
utils/checkstyle/README.txt [new file with mode: 0644]
utils/checkstyle/checkstyle-suppress.xml [new file with mode: 0644]
utils/checkstyle/checkstyle.xml [new file with mode: 0644]
utils/checkstyle/import-control.xml [new file with mode: 0644]
utils/i18nAnt.xml

diff --git a/.checkstyle b/.checkstyle
new file mode 100644 (file)
index 0000000..0329bb7
--- /dev/null
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<fileset-config file-format-version="1.2.0" simple-config="false" sync-formatter="false">
+  <local-check-config name="JalviewCheckstyle" location="utils/checkstyle/checkstyle.xml" type="project" description="">
+    <additional-data name="protect-config-file" value="false"/>
+  </local-check-config>
+  <fileset name="source" enabled="true" check-config-name="JalviewCheckstyle" local="true">
+    <file-match-pattern match-pattern="src/.*.java" include-pattern="true"/>
+    <file-match-pattern match-pattern="resources/.*.properties" include-pattern="true"/>
+  </fileset>
+  <filter name="NonSrcDirs" enabled="false"/>
+</fileset-config>
index 42d3187..a16d8bb 100644 (file)
@@ -5,11 +5,15 @@ import jalview.workers.AlignmentAnnotationFactory;
  * Example script that registers two alignment annotation calculators
  * - one that counts residues in a column with Pfam annotation
  * - one that counts only charged residues with Pfam annotation
- * To try this, first load uniref50.fa from the examples folder, then load features
- * from examples/exampleFeatures.txt, before running this script from the Groovy console.
+ *
+ * To try:
+ * 1. load uniref50.fa from the examples folder
+ * 2. load features onto it from from examples/exampleFeatures.txt
+ * 3. Open this script in the Groovy console.
+ * 4. Either execute this script from the console, or via Calculate->Run Groovy Script
  
- * Modify this example as required to count by column any desired value that can be 
- * derived from the residue and sequence features at each position of an alignment.
+ * To explore further, try changing this script to count other kinds of occurrences of 
+ * residue and sequence features at columns in an alignment.
  */
 
 /*
@@ -45,7 +49,8 @@ def hasPfam = { features ->
 }
 
 /*
- * Closure that counts residues with a Pfam feature annotation
+ * Closure that computes an annotation based on 
+ * presence of particular residues and features
  * Parameters are
  * - the name (label) for the alignment annotation
  * - the description (tooltip) for the annotation
@@ -74,12 +79,12 @@ def getColumnCounter = { name, desc, acceptResidue, acceptFeatures ->
 }
 
 /*
- * Define an annotation that counts any residue with Pfam domain annotation
+ * Define an annotation row that counts any residue with Pfam domain annotation
  */
 def pfamAnnotation = getColumnCounter("Pfam", "Count of residues with Pfam domain annotation", {true}, hasPfam)
 
 /*
- * Define an annotation that counts charged residues with Pfam domain annotation
+ * Define an annotation row that counts charged residues with Pfam domain annotation
  */
 def chargedPfamAnnotation = getColumnCounter("Pfam charged", "Count of charged residues with Pfam domain annotation", isCharged, hasPfam)
 
index 63a14af..1d6f62d 100644 (file)
     </tr>
     <tr>
       <td>
+        <div align="center">-nonews</div>
+      <td>
+        <div align="left">Disable check for <a href="../webServices/newsreader.html">Jalview news</a> on startup (not recommended other than for classroom / demo usage)</div>
+      </td>
+    </tr>
+    <tr>
+      <td>
         <div align="center">-nousagestats</div>
       <td>
         <div align="left">Turn off google analytics usage tracking</div>
index c0c888a..90958ae 100644 (file)
@@ -29,8 +29,7 @@
   </p>
   <p>
     Jalview includes a client for retrieving sequences and their
-    features via the <a href="http://www.biodas.org">Distributed
-      Annotation System</a>.
+    features via the Distributed Annotation System.
   </p>
   <ol>
     <li>Open the Feature Settings panel by selecting &quot;View
   <p>
     <em>DAS support was introduced in Jalview Version 2.1.</em>
   </p>
+  <br/>
+  <p>
+    <em>The DAS registry at http://www.dasregistry.org was decommissioned early in 2015. An unmaintained mirror is currently hosted at http://www.ebi.ac.uk/das-srv/registry/.</em>
+  </p>
   <p>&nbsp;
 </body>
 </html>
index 3c28b81..ddc8a1f 100644 (file)
Binary files a/help/html/features/sifts_mapping_output.png and b/help/html/features/sifts_mapping_output.png differ
index c344a20..08089ad 100644 (file)
@@ -9,8 +9,8 @@
   <p><strong>SIFTS Mapping</strong></p>
   
   <p>
-       SIFTS (Structure integration with function, taxonomy
-       and sequences) provides an up-to-date resource for residue-level
+       SIFTS (Structure Integration with Function, Taxonomy
+       and Sequences) provides an up-to-date resource for residue-level
        mapping between Uniprot and PDB entries. The information is updated and
        released weekly simultaneously with the release of new PDB entries.
        SIFTS Entries are published as XML files and made publicly available via an FTP
@@ -18,7 +18,8 @@
   </p>
        
   <p>
-    At the point of viewing a PDB structure, Jalview downloads a SIFTS file 
+    At the point of viewing a PDB structure, if the default mapping method is set as 'SIFTS', 
+    Jalview will download a SIFTS file 
        for the target entry and uses it to accurately map the sequence residues with the 
        structure residue. Prior to SIFTS integration, Jalview uses Needleman and Wunsch 
        Alignment algorithm to  map sequence residues to structure residues, and that may not 
   </p>
   
   <p>
-       The default method for 'Sequence &harr; Structure' mapping can be configured 
-       in the Structure tab in the <strong>Tools &rarr; Preferences</strong> dialog box. When 'SIFTS' 
-       is enabled as the default, all mappings between 'Sequence &harr; Structure' is 
-       performed via SIFTS provided that there is a valid SIFTS entry for PDB structure. If no 
-       valid SIFTS resource is available, then the 'Sequence &harr; Structure' mapping falls 
-       back to Needleman and Wunsch Alignment algorithm.
+  <strong>Configuration</strong><br/>
+       The default mapping method can be configured via <strong>Tools &rarr; Preferences &rarr; 
+       Structure tab</strong> Then scroll to the 'Sequence &harr; Structure method' section of 
+       the dialog box and change the default method. When 'SIFTS' is enabled as the default, all 
+       mappings between 'Sequence &harr; Structure' is performed via SIFTS provided that there 
+       is a valid SIFTS resource for the PDB entry. If no valid SIFTS resource is available, then 
+       the 'Sequence &harr; Structure' mapping falls back to Needleman and Wunsch Alignment algorithm.
   </p>
        
-  <p>To verify the mapping method used, you can view the mapping output via the structure viewer menu <strong>File &rarr; View mapping.</strong> A sample mapping output can be seen in the screenshot below. The highlighted position shows the method used. </p>     
+  <p><strong>Multi-Chain Mappings</strong>
+  <br/>One of the main merits of SIFTS is the ability to accurately achieve multi-chain mapping 
+  (one-to-many) between a single Uniprot sequence and its corresponding multiple chains in 
+  PDB. Consequently, mousing over the uniprot sequence in the alignment window results 
+  to highlighting multiple corresponding positions in the structure viewer for the mapped chains. 
+  </p>
   <p>
-       <img src="sifts_mapping_output.png" align="left" alt="SIFTS mapping output" />
+  To see this in action, load uniprot sequence for FER1_MAIZE then veiw PDB structure for 3B2F, you
+  will notice that mousing over the sequence results to two positions being highlighted in the 
+  structure, also colouring the sequence transfers the color to all the mapped chains in the structure.
   </p>
+  
+  <p>
+  <Strong>Viewing Mapping Output</Strong> <br/>
+  The mapping output is accessible via <strong>File &rarr; View mapping</strong> menu of the structure 
+  viewers. The screenshot below is the mapping output for the <Strong>{FER1_MAIZE &harr; 3B2F}</Strong> 
+  example described above. Observe that all the two chains were mapped. The mapping method used can be 
+  seen within the area highlighted with red boarder. This is useful for visually ascertaining the 
+  mapping method when in doubt.    
+  <p>
+       
+       &emsp;<img src="sifts_mapping_output.png" align="left" alt="SIFTS mapping output" />
        
   <p><em>SIFTS Mapping integration was added in Jalview 2.9.1</em></p>
        
index 029edce..ce446f3 100644 (file)
@@ -27,7 +27,7 @@
     <strong>The VARNA RNA Viewer</strong>
   </p>
   <p>
-    <a href="http://varna.lri.fr/index.html">VARNA</a> was integrated
+    <a href="http://varna.lri.fr">VARNA</a> was integrated
     into Jalview 2.8 to allow interactive viewing of RNA secondary
     structure annotation. It is opened by selecting the <strong>&quot;Structure&#8594;View
       Structure:&quot;</strong> option in the <a href="../menus/popupMenu.html">sequence
index c0a89cf..d2196c1 100755 (executable)
       NBRF/PIR (including MODELLER variant), Pfam/Stockholm</em>
   </p>
   <p>
-    The EBI has <a href="http://www.ebi.ac.uk/help/formats.html">examples</a>
-    of these file formats.
-  </p>
-  <p>
     Additionally, whole sets of coloured and annotated alignments and
     trees can be read from a <a href="../features/jalarchive.html">Jalview
       (jar) format</a> file using <strong>Desktop&#8594;Load
index ae4c1c6..de2741b 100644 (file)
@@ -65,7 +65,7 @@ td {
       annotation.</li>
     <li><em>Clustal files</em> - certain RNA alignment programs,
       such as <a
-      href="http://rna.informatik.uni-freiburg.de:8080/LocARNA.jsp"
+      href="http://rna.informatik.uni-freiburg.de/LocARNA"
     >LocaRNA</a> output consensus RNA secondary structure lines in the
       line normally reserved for the Clustal consensus line in a clustal
       file.</li>
index 0e7d02d..5a5020a 100755 (executable)
@@ -92,6 +92,7 @@
             <li><!--  JAL-2085  -->Cannot save project when view has a reference sequence defined</li>
             <li><!--  JAL-1011  -->Columns are suddenly selected in other alignments and views when revealing hidden columns</li>
             <li><!--  JAL-1989  -->Hide columns not mirrored in complement view in a cDNA/Protein splitframe</li>
+            <li><!--  JAL-1369 -->Cannot save/restore representative sequence from project when only one sequence is represented</li>
             <!--  may exclude, this is an external service stability issue  JAL-1941 /> RNA 3D structure not added via DSSR service</li> -->
           </ul>
           <em>Applet</em>
                 region export in flat file generation</li>
 
               <li>Export alignment views for display with the <a
-                href="http://biojs.io/d/msa">BioJS MSAViewer</a></li>
+                href="http://msa.biojs.net/">BioJS MSAViewer</a></li>
 
               <li>Export scrollable SVG in HTML page</li>
               <li>Optional embedding of BioJSON data when exporting
index b03bb9d..1463554 100755 (executable)
@@ -90,7 +90,7 @@
     services were maintained by the Barton group at the University of
     Dundee, and ran programs on the Life Sciences High-performance
     Computing Cluster. With the advent of <a
-      href="http://www.compbio.dundee.ac.uk/JABAWS"
+      href="http://www.compbio.dundee.ac.uk/jabaws"
     >JABAWS</a>, however, it is possible for anyone to host Jalview web
     services.
   </p>
index ee69290..5ec088a 100644 (file)
@@ -19,7 +19,7 @@
  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
  * The Jalview Authors are detailed in the 'AUTHORS' file.
  -->
-<head>Jalview Desktop RSS News Reader
+<head>
 </head>
 <body>
   <p>
   <p>The news reader will be launched automatically when you start
     the Desktop if new items are available. Should you want to browse
     older items, however, you can open it manually from the 'Jalview
-    news reader' option in the Desktop's 'Tools' menu.</p>
-  <img src="jalviewrssreader.gif" align="center" width="513"
-    height="337" alt="Snapshot of the Jalview Desktop's RSS reader"
-  />
-  <p>
+    news reader' option in the Desktop's <a href="../menus/desktopMenu.html">'Tools' menu</a>.</p><br/>
+  <div style="text-align: center;"><img src="jalviewrssreader.gif" width="513"
+    height="337" alt="Snapshot of the Jalview Desktop's RSS reader"/></div>
+
+  <br/><p>
     The <em>Jalview news reader</em> was introduced in <a
       href="http://www.jalview.org/releaseHistory.html#Jalview2.7"
     >Jalview version 2.7</a>. Its implementation is based on <a
       href="http://jswingreader.sourceforge.net/"
     >JSwingReader</a>.
   </p>
+  <br/><em>From Jalview 2.10.0, check for news on startup can be disabled with <a href="../features/clarguments.html">command-line parameter</a> &#39;-nonews&#39;. 
+  This is not recommended for normal use, but may be useful to avoid interruptions when teaching, demonstrating, recording etc.</em>
 </body>
 </html>
index 40c311f..b01464a 100644 (file)
@@ -38,7 +38,6 @@ action.cancel = Cancel
 action.create = Create
 action.update = Update
 action.delete = Delete
-action.snapshot = Snapshot
 action.clear = Clear
 action.accept = Accept
 action.select_ddbb = --- Select Database ---
@@ -121,7 +120,6 @@ action.save_as_default = Save as default
 action.save_as = Save as...
 action.save = Save
 action.cancel_fetch = Cancel Fetch
-action.save_omit_hidden_columns = Save / Omit Hidden Regions
 action.change_font = Change Font
 action.change_font_tree_panel = Change Font (Tree Panel)
 action.colour = Colour
@@ -137,21 +135,22 @@ action.show_group = Show Group
 action.fetch_db_references = Fetch DB References
 action.view_flanking_regions = Show flanking regions
 label.view_flanking_regions = Show sequence data either side of the subsequences involved in this alignment
-label.str = Str:
-label.seq = Seq:
 label.structures_manager = Structures Manager
 label.nickname = Nickname:
 label.url = URL:
 label.input_file_url = Enter URL or Input File
-label.select_feature = Select feature:
+label.select_feature = Select feature
 label.name = Name
+label.name\: = Name:
 label.name_param = Name: {0}
 label.group = Group
+label.group\: = Group:
 label.group_name = Group Name
 label.group_description = Group Description
 label.edit_group_name_description = Edit Group Name/Description
 label.colour = Colour:
-label.description = Description:
+label.description = Description
+label.description\: = Description:
 label.start = Start:
 label.end = End:
 label.current_parameter_set_name = Current parameter set name:
@@ -222,8 +221,8 @@ label.proteins = Proteins
 label.to_new_alignment = To New Alignment
 label.to_this_alignment = Add To This Alignment
 label.apply_colour_to_all_groups = Apply Colour To All Groups
-label.modify_identity_thereshold = Modify Identity Threshold...
-label.modify_conservation_thereshold = Modify Conservation Threshold...
+label.modify_identity_threshold = Modify Identity Threshold...
+label.modify_conservation_threshold = Modify Conservation Threshold...
 label.input_from_textbox = Input from textbox
 label.centre_column_labels = Centre column labels
 label.automatic_scrolling = Automatic Scrolling
@@ -240,7 +239,6 @@ label.except_selected_sequences = All except selected sequences
 label.all_but_selected_region = All but Selected Region (Shift+Ctrl+H)
 label.selected_region = Selected Region
 label.all_sequences_columns = All Sequences and Columns
-label.hide_insertions = Hide columns gapped for selection
 label.hide_selected_annotations = Hide selected annotations
 label.show_selected_annotations = Show selected annotations
 label.group_consensus = Group Consensus
@@ -321,7 +319,6 @@ label.found_match_for = Found match for {0}
 label.font = Font:
 label.size = Size:
 label.style = Style:
-label.enter_redundancy_threshold = Enter the redundancy threshold
 label.calculating = Calculating....
 label.modify_conservation_visibility = Modify conservation visibility
 label.colour_residues_above_occurence = Colour residues above % occurence
@@ -365,7 +362,6 @@ label.example = Example
 label.example_param = Example: {0}
 label.select_file_format_before_saving = You must select a file format before saving!
 label.file_format_not_specified = File format not specified
-label.alignment_contains_hidden_columns = The Alignment contains hidden regions (hidden sequences/columns).\nDo you want to save only the visible alignment?
 label.couldnt_save_file = Couldn't save file: {0}
 label.error_saving_file = Error Saving File
 label.remove_from_default_list = Remove from default list?
@@ -393,7 +389,7 @@ label.ignore_unmatched_dropped_files = Ignore unmatched dropped files?
 label.view_name_original = Original
 label.enter_view_name = Enter View Name
 label.enter_label = Enter label
-label.enter_label_for_the_structure = Enter a label for the structure?
+label.enter_label_for_the_structure = Enter a label for the structure
 label.pdb_entry_is_already_displayed = {0} is already displayed.\nDo you want to re-use this viewer ?
 label.map_sequences_to_visible_window = Map Sequences to Visible Window: {0}
 label.add_pdbentry_to_view = Do you want to add {0} to the view called\n{1}\n
@@ -467,7 +463,6 @@ label.no_features_added_to_this_alignment = No Features added to this alignment!
 label.features_can_be_added_from_searches_1 = (Features can be added from searches or
 label.features_can_be_added_from_searches_2 = from Jalview / GFF features files)
 label.calculating_pca= Calculating PCA
-label.reveal_columns = Reveal Columns
 label.jalview_cannot_open_file = Jalview can't open file
 label.jalview_applet = Jalview applet
 label.loading_data = Loading data
@@ -475,7 +470,6 @@ label.memory_stats = Total Free Memory: {0} MB; Max Memory: {1} MB; {2} %
 label.calculating_tree = Calculating tree
 label.state_queueing = queuing
 label.state_running = running
-label.state_complete = complete
 label.state_completed = finished
 label.state_job_cancelled = job cancelled!!
 label.state_job_error = job error!
@@ -501,7 +495,6 @@ label.jmol_help = Jmol Help
 label.chimera_help = Chimera Help
 label.close_viewer = Close Viewer
 label.confirm_close_chimera = This will close Jalview''s connection to {0}.<br>Do you want to close the Chimera window as well?
-label.chimera_help = Chimera Help
 label.all = All
 label.sort_by = Sort alignment by
 label.sort_by_score = Sort by Score
@@ -521,15 +514,14 @@ label.reset_min_max_colours_to_defaults = Reset min and max colours to defaults
 label.align_structures_using_linked_alignment_views = Align structures using {0} linked alignment views
 label.connect_to_session = Connect to session {0}
 label.threshold_feature_display_by_score = Threshold the feature display by score.
-label.threshold_feature_no_thereshold = No Threshold
-label.threshold_feature_above_thereshold = Above Threshold
-label.threshold_feature_below_thereshold = Below Threshold
-label.adjust_thereshold = Adjust threshold
+label.threshold_feature_no_threshold = No Threshold
+label.threshold_feature_above_threshold = Above Threshold
+label.threshold_feature_below_threshold = Below Threshold
+label.adjust_threshold = Adjust threshold
 label.toggle_absolute_relative_display_threshold = Toggle between absolute and relative display threshold.
 label.display_features_same_type_different_label_using_different_colour = Display features of the same type with a different label using a different colour. (e.g. domain features)
 label.select_colour_minimum_value = Select Colour for Minimum Value
 label.select_colour_maximum_value = Select Colour for Maximum Value
-label.open_new_jmol_view_with_all_structures_associated_current_selection_superimpose_using_alignment = Open a new structure viewer with all structures associated with the current selection and superimpose them using the alignment.
 label.open_url_param = Open URL {0}
 label.open_url_seqs_param = Open URL ({0}..) ({1} seqs)
 label.load_pdb_file_associate_with_sequence = Load a PDB file and associate it with sequence {0}
@@ -584,8 +576,8 @@ label.histogram = Histogram
 label.logo = Logo
 label.non_positional_features = List Non-positional Features
 label.database_references = List Database References
-label.share_selection_across_views = Share selection across views
-label.scroll_highlighted_regions = Scroll to highlighted regions
+#label.share_selection_across_views = Share selection across views
+#label.scroll_highlighted_regions = Scroll to highlighted regions
 label.gap_symbol = Gap Symbol
 label.prot_alignment_colour = Protein Alignment Colour
 label.nuc_alignment_colour = Nucleotide Alignment Colour
@@ -668,20 +660,12 @@ label.cut_paste = Cut'n'Paste
 label.adjusting_parameters_for_calculation = Adjusting parameters for existing Calculation
 label.2d_rna_structure_line = 2D RNA {0} (alignment)
 label.2d_rna_sequence_name = 2D RNA - {0}
-label.edit_name_and_description_current_group = Edit name and description of current group.
-label.view_structure_for = View structure for {0}
-label.view_all_structures = View all {0} structures.
-label.view_all_representative_structures = View all {0} representative structures.
-label.open_new_jmol_view_with_all_representative_structures_associated_current_selection_superimpose_using_alignment = Opens a new structure viewer with all representative structures\nassociated with the current selection\nsuperimposed with the current alignment.
-label.associate_structure_with_sequence = Associate Structure with Sequence
+label.edit_name_and_description_current_group = Edit name and description of current group
 label.from_file = From File
 label.enter_pdb_id = Enter PDB Id (or pdbid:chaincode)
-label.discover_pdb_ids = Discover PDB IDs
 label.text_colour = Text Colour
 action.set_text_colour = Text Colour...
 label.structure = Structure
-label.view_structure = View Structure
-label.view_protein_structure = View Protein Structure
 label.show_pdbstruct_dialog = 3D Structure Data...
 label.view_rna_structure = VARNA 2D Structure
 label.clustalx_colours = Clustalx colours
@@ -709,7 +693,6 @@ label.translate_cDNA = Translate as cDNA
 label.reverse = Reverse
 label.reverse_complement = Reverse Complement
 label.linked_view_title = Linked CDS and protein view
-label.align = Align
 label.extract_scores = Extract Scores
 label.get_cross_refs = Get Cross-References
 label.sort_alignment_new_tree = Sort Alignment With New Tree
@@ -721,7 +704,6 @@ label.use_registry = Use Registry
 label.add_local_source = Add Local Source
 label.set_as_default = Set as Default
 label.show_labels = Show labels
-label.background_colour = Background Colour
 action.background_colour = Background Colour...
 label.associate_nodes_with = Associate Nodes With
 label.jalview_pca_calculation = Jalview PCA Calculation
@@ -814,7 +796,6 @@ label.services_at = Services at {0}
 label.rest_client_submit = {0} using {1}
 label.fetch_retrieve_from =Retrieve from {0}</html>
 label.fetch_retrieve_from_all_sources = Retrieve from all {0} sources in {1}<br>First is :{2}<html> 
-#label.feature_settings_click_drag = <html>Click/drag feature types up or down to change render order.<br/>Double click to select columns containing feature in alignment/current selection<br/>Pressing Alt will select columns outside features rather than inside<br/>Pressing Shift to modify current selection (rather than clear current selection)<br/>Press CTRL or Command/Meta to toggle columns in/outside features<br/></html>
 label.feature_settings_click_drag = Drag up or down to change render order.<br/>Double click to select columns containing feature.
 label.transparency_tip = Adjust transparency to 'see through' feature colours.
 label.opt_and_params_further_details = see further details by right-clicking
@@ -830,17 +811,10 @@ label.user_preset = User Preset
 label.service_preset = Service Preset
 label.run_with_preset = Run {0} with preset
 label.view_service_doc_url = <html>View <a href="{0}">{1}</a></html>
-label.submit_sequence = <html>Submit {0} {1} {2} {3} to<br/>{4}</html>
 action.by_title_param = By {0}
-label.alignment = Alignment
-label.secondary_structure_prediction = Secondary Structure Prediction
-label.sequence_database_search = Sequence Database Search
-label.analysis = Analysis
-label.protein_disorder = Protein Disorder 
 label.source_from_db_source = Sources from {0}
 label.from_msname = from {0}
 label.superpose_with = Superpose with
-action.do = Do
 label.scale_label_to_column = Scale Label to Column
 label.add_new_row = Add New Row
 label.edit_label_description = Edit Label/Description
@@ -884,7 +858,7 @@ label.service_url = Service URL
 label.copied_sequences = Copied sequences
 label.cut_sequences = Cut Sequences
 label.conservation_colour_increment = Conservation Colour Increment ({0})
-label.percentage_identity_thereshold = Percentage Identity Threshold ({0})
+label.percentage_identity_threshold = Percentage Identity Threshold ({0})
 label.error_unsupported_owwner_user_colour_scheme = Unsupported owner for User Colour scheme dialog
 label.save_alignment_to_file = Save Alignment to file
 label.save_features_to_file = Save Features to File
@@ -900,7 +874,6 @@ label.save_vamsas_document_archive = Save Vamsas Document Archive
 label.saving_vamsas_doc = Saving VAMSAS Document to {0}
 label.load_feature_colours = Load Feature Colours
 label.save_feature_colours = Save Feature Colour Scheme
-label.dataset_for = {0} Dataset for {1}
 label.select_startup_file = Select startup file
 label.select_default_browser = Select default web browser
 label.save_tree_as_newick = Save tree as newick file
@@ -928,15 +901,9 @@ error.null_from_clone1 = Null from clone1!
 error.implementation_error_sortbyfeature = Implementation Error - sortByFeature method must be one of FEATURE_SCORE, FEATURE_LABEL or FEATURE_DENSITY.
 error.not_yet_implemented = Not yet implemented
 error.unknown_type_dna_or_pep = Unknown Type {0} - dna or pep are the only allowed values.
-error.implementation_error_dont_know_thereshold_annotationcolourgradient = Implementation error: don't know about threshold setting for current AnnotationColourGradient.
-error.implementation_error_embeddedpopup_not_null = Implementation error - embeddedPopup must be non-null
-error.invalid_colour_for_mycheckbox = Invalid color for MyCheckBox
-error.implementation_error_unrecognised_render_object_for_features_type = Implementation Error: Unrecognised render object {0} for features of type {1}
-error.implementation_error_unsupported_feature_colour_object = Implementation error: Unsupported feature colour object.
+error.implementation_error_dont_know_threshold_annotationcolourgradient = Implementation error: don't know about threshold setting for current AnnotationColourGradient.
 error.invalid_separator_parameter = Invalid separator parameter - must be non-zero length
 error.alignment_cigararray_not_implemented = Alignment(CigarArray) not yet implemented
-error.weak_sequencei_equivalence_not_yet_implemented = Weak sequenceI equivalence not yet implemented.
-error.implementation_error_can_only_make_alignmnet_from_cigararray = Implementation Error - can only make an alignment view from a CigarArray of sequences.
 error.empty_view_cannot_be_updated = empty view cannot be updated.
 error.mismatch_between_number_of_sequences_in_block = Mismatch between number of sequences in block {0} ({1}) and the original view ({2})
 error.padding_not_yet_implemented = Padding not yet implemented
@@ -958,16 +925,14 @@ error.not_yet_implemented_cigar_object_from_cigar_string = NOT YET Implemented:
 error.implementation_bug_cigar_operation = Implementation Bug. Cigar Operation {0} {1} not one of {2}, {3}, or {4}.
 error.implementation_error_for_new_cigar = Implementation error for new Cigar(SequenceI)
 error.implementation_error_cigar_seq_no_operations = Implementation error: {0}th sequence Cigar has no operations.
-error.implementation_error_jmol_getting_data = Implementation error - Jmol seems to be still working on getting its data - report at http://issues.jalview.org/browse/JAL-1016
 error.implementation_error_no_pdbentry_from_index = Implementation error - no corresponding pdbentry (for index {0}) to add sequences mappings to
 error.jmol_version_not_compatible_with_jalview_version = Jmol version {0} is not compatible with this version of Jalview. Report this problem at issues.jalview.org
 error.not_implemented_remove = Remove: Not implemented
 error.not_implemented_clone = Clone: Not implemented
-error.implementation_error_chimera_getting_data = Implementation error - Chimera seems to be still working on getting its data - report at http://issues.jalview.org/browse/JAL-1016
 error.call_setprogressbar_before_registering_handler = call setProgressBar before registering the progress bar's handler.
 label.cancelled_params = Cancelled {0}
 error.implementation_error_cannot_show_view_alignment_frame = Implementation error: cannot show a view from another alignment in an AlignFrame.
-error.implementation_error_dont_know_about_thereshold_setting = Implementation error: don't know about threshold setting for current AnnotationColourGradient.
+error.implementation_error_dont_know_about_threshold_setting = Implementation error: don't know about threshold setting for current AnnotationColourGradient.
 error.eps_generation_not_implemented = EPS Generation not yet implemented
 error.png_generation_not_implemented = PNG Generation not yet implemented
 error.try_join_vamsas_session_another = Trying to join a vamsas session when another is already connected
@@ -986,7 +951,6 @@ error.setstatus_called_non_existent_job_pane = setStatus called for non-existent
 error.implementation_error_cannot_find_marshaller_for_param_set =Implementation error: Can't find a marshaller for the parameter set
 error.implementation_error_old_jalview_object_not_bound =IMPLEMENTATION ERROR: old jalview object is not bound ! ({0})
 error.implementation_error_vamsas_doc_class_should_bind_to_type = Implementation Error: Vamsas Document Class {0} should bind to a {1} (found a {2})
-error.implementation_error_jalview_class_should_bind_to_type = Implementation Error: Jalview Class {0} should bind to a {1} (found a {2})
 error.invalid_vamsas_rangetype_cannot_resolve_lists = Invalid vamsas RangeType - cannot resolve both lists of Pos and Seg from choice!
 error.implementation_error_maplist_is_null = Implementation error. MapList is null for initMapType.
 error.implementation_error_cannot_have_null_alignment = Implementation error: Cannot have null alignment property key
@@ -1028,10 +992,11 @@ error.implementation_error_need_to_have_httpresponse = Implementation Error: nee
 error.dbrefsource_implementation_exception =DBRefSource Implementation Exception
 error.implementation_error_dbinstance_must_implement_interface = Implmentation Error - getDbInstances must be given a class that implements jalview.ws.seqfetcher.DbSourceProxy (was given{0})
 error.implementation_error_must_init_dbsources =Implementation error. Must initialise dbSources
-label.view_controller_toggled_marked = {0} {1} columns containing features of type {2}  across {3} sequence(s)
+label.view_controller_toggled_marked = {0} {1} columns {2} features of type {3}  across {4} sequence(s)
 label.toggled = Toggled
 label.marked = Marked
-label.not = not
+label.containing = containing
+label.not_containing = not containing
 label.no_feature_of_type_found = No features of type {0} found.
 label.submission_params = Submission {0}
 label.empty_alignment_job = Empty Alignment Job
@@ -1041,7 +1006,7 @@ label.pca_recalculating = Recalculating PCA
 label.pca_calculating = Calculating PCA
 label.select_foreground_colour = Choose foreground colour
 label.select_colour_for_text = Select Colour for Text
-label.adjunst_foreground_text_colour_thereshold = Adjust Foreground Text Colour Threshold
+label.adjunst_foreground_text_colour_threshold = Adjust Foreground Text Colour Threshold
 label.select_subtree_colour = Select Sub-Tree Colour
 label.create_new_sequence_features = Create New Sequence Feature(s)
 label.amend_delete_features = Amend/Delete Features for {0}
@@ -1061,7 +1026,6 @@ exception.mismatched_unseen_closing_char = Mismatched (unseen) closing character
 exception.mismatched_closing_char = Mismatched closing character {0}
 exception.mismatched_opening_char = Mismatched opening character {0} at {1}
 exception.invalid_datasource_couldnt_obtain_reader = Invalid datasource. Could not obtain Reader
-exception.index_value_not_in_range = {0}: Index value {1} not in range [0..{2}]
 exception.unterminated_cigar_string = Unterminated cigar string
 exception.unexpected_operation_cigar_string_pos = Unexpected operation {0} in cigar string (position {1} in {2}
 exception.couldnt_parse_responde_from_annotated3d_server = Couldn't parse response from Annotate3d server
@@ -1089,7 +1053,6 @@ exception.ranml_problem_parsing_data = Problem parsing data as RNAML ({0})
 exception.pfam_no_sequences_found = No sequences found (PFAM input)
 exception.stockholm_invalid_format = This file is not in valid STOCKHOLM format: First line does not contain '# STOCKHOLM'
 exception.couldnt_parse_sequence_line = Could not parse sequence line: {0}
-exception.error_parsing_line = Error parsing {0}
 exception.unknown_annotation_detected = Unknown annotation detected: {0} {1}
 exception.couldnt_store_sequence_mappings = Couldn't store sequence mappings for {0}
 exception.matrix_too_many_iteration = Too many iterations in {0} (max is {1})
@@ -1097,7 +1060,6 @@ exception.browser_not_found = Exception in finding browser: {0}
 exception.browser_unable_to_locate = Unable to locate browser: {0}
 exception.invocation_target_exception_creating_aedesc = InvocationTargetException while creating AEDesc: {0}
 exception.illegal_access_building_apple_evt= IllegalAccessException while building AppleEvent: {0}
-exception.instantiation_creating_aedesc = InstantiationException while creating AEDesc: {0}
 exception.unable_to_launch_url = Unable to launch URL: {0}
 exception.unable_to_create_internet_config = Unable to create an Internet Config instance: {0}
 exception.invocation_target_calling_url = InvocationTargetException while calling openURL: {0}
@@ -1106,8 +1068,6 @@ exception.interrupted_launching_browser = InterruptedException while launching b
 exception.das_source_doesnt_support_sequence_command = Source {0} does not support the sequence command.
 exception.invalid_das_source = Invalid das source: {0}
 exception.ebiembl_retrieval_failed_on = EBI EMBL XML retrieval failed on {0}:{1}
-label.no_embl_record_found = # No EMBL record retrieved for {0}:{1}
-label.embl_successfully_parsed = # Successfully parsed the {0} queries into an Alignment
 exception.no_pdb_records_for_chain = No PDB Records for {0} chain {1}
 exception.unexpected_handling_rnaml_translation_for_pdb = Unexpected exception when handling RNAML translation of PDB data
 exception.couldnt_recover_sequence_properties_for_alignment = Couldn't recover sequence properties for alignment
@@ -1198,8 +1158,8 @@ label.edit_jabaws_url = Edit JABAWS URL
 label.add_jabaws_url = Add new JABAWS URL
 label.news_from_jalview = News from http://www.jalview.org
 label.cut_paste_alignmen_file = Cut & Paste Alignment File
-label.enter_redundancy_thereshold = Enter the redundancy threshold
-label.select_dark_light_set_thereshold = <html><i>Select a dark and light text colour, then set the threshold to<br>switch between colours, based on background colour</i></html>
+label.enter_redundancy_threshold = Enter the redundancy threshold
+label.select_dark_light_set_threshold = <html><i>Select a dark and light text colour, then set the threshold to<br>switch between colours, based on background colour</i></html>
 label.select_feature_colour = Select Feature Colour
 label.delete_all = Delete all sequences
 warn.delete_all = <html>Deleting all sequences will close the alignment window.<br>Confirm deletion or Cancel.
@@ -1220,28 +1180,23 @@ label.no_colour_selection_in_scheme = Please make a colour selection before appl
 label.no_colour_selection_warn = Error saving colour scheme
 label.open_split_window? = Would you like to open as a split window, with cDNA and protein linked?
 label.open_split_window = Open split window
-label.no_mappings = No mappings found
 action.no = No
 action.yes = Yes
 label.for = for
 label.select_by_annotation = Select/Hide Columns by Annotation
 action.select_by_annotation = Select/Hide Columns by Annotation...
 label.threshold_filter =  Threshold Filter
-action.hide = Hide
-action.select = Select
 label.alpha_helix = Alpha Helix
 label.beta_strand = Beta Strand
 label.turn = Turn
 label.select_all = Select All
 label.structures_filter = Structures Filter
 label.search_filter = Search Filter
-label.description = Description
 label.include_description= Include Description
 action.back = Back
 label.hide_insertions = Hide Insertions
 label.mark_as_representative = Mark as representative
 label.open_jabaws_web_page = Open JABAWS web page
-label.opens_the_jabaws_server_homepage = Opens the JABAWS server's homepage in web browser
 label.pdb_sequence_fetcher = PDB Sequence Fetcher
 label.result = result
 label.results = results
@@ -1308,3 +1263,6 @@ status.fetching_3d_structures_for = Fetching 3D Structure for {0}
 status.obtaining_mapping_with_sifts = Obtaining mapping with SIFTS
 status.obtaining_mapping_with_nw_alignment = Obtaining mapping with NW alignment
 status.exporting_alignment_as_x_file = Exporting alignment as {0} file
+label.column = Column
+label.cant_map_cds = Unable to map CDS to protein\nCDS missing or incomplete
+label.operation_failed = Operation failed
index f814c97..87538be 100644 (file)
@@ -38,7 +38,6 @@ action.cancel = Cancelar
 action.create = Crear
 action.update = Actualizar
 action.delete = Borrar
-action.snapshot = Imagen
 action.clear = Limpiar
 action.accept = Aceptar
 action.select_ddbb = --- Seleccionar base de datos ---
@@ -118,7 +117,6 @@ action.save_as_default = Guardar como por defecto
 action.save_as = Guardar como
 action.save = Guardar
 action.cancel_fetch = Cancelar búsqueda
-action.save_omit_hidden_columns = Guardar / Omitir las columnas ocultas
 action.change_font = Cambiar Fuente
 action.change_font_tree_panel = Cambiar fuente (panel del Ã¡rbol)
 action.colour = Color
@@ -134,21 +132,22 @@ action.show_group = Mostrar grupo
 action.fetch_db_references = Recuperar referencias a base de datos
 action.view_flanking_regions = Mostrar flancos
 label.view_flanking_regions = Mostrar los datos de la secuencia a ambos lados de las subsecuencias implicadas en este alineamiento
-label.str = Str: 
-label.seq = Seq: 
 label.structures_manager = Administrar estructuras
 label.nickname = Sobrenombre:
 label.url = URL: 
 label.input_file_url = Introducir URL en el fichero de entrada
-label.select_feature = Seleccionar función:
-label.name = Nombre:
+label.select_feature = Seleccionar característica
+label.name = Nombre
+label.name\: = Nombre:
 label.name_param = Nombre: {0}
-label.group = Grupo:
+label.group = Grupo
+label.group\: = Grupo:
 label.group_name = Nombre del grupo
 label.group_description = Descripción del grupo
 label.edit_group_name_description = Editar nombre/descripción del grupo
 label.colour = Color:
-label.description = Descripción:
+label.description = Descripción
+label.description\: = Descripción:
 label.start = Comenzar:
 label.end = Terminar:
 label.current_parameter_set_name = Nombre actual del conjunto de parámetros:
@@ -208,8 +207,8 @@ label.nucleotide = Nucle
 label.to_new_alignment = A nuevo alineamiento
 label.to_this_alignment = Añadir a este alineamiento
 label.apply_colour_to_all_groups = Aplicar color a todos los grupos
-label.modify_identity_thereshold = Modificar el umbral de identidad...
-label.modify_conservation_thereshold = Modificar el umbral de conservación...
+label.modify_identity_threshold = Modificar el umbral de identidad...
+label.modify_conservation_threshold = Modificar el umbral de conservación...
 label.input_from_textbox = Introducir desde el cuadro de texto
 label.centre_column_labels = Centrar las etiquetas de las columnas
 label.automatic_scrolling = Desplazamiento automático
@@ -217,7 +216,6 @@ label.documentation = Documentaci
 label.about = Acerca de...
 label.show_sequence_limits = Mostrar los límites de la secuencia
 label.feature_settings = Ajustar funciones...
-label.sequence_features = Funciones de la secuencia
 label.all_columns = Todas las columnas
 label.all_sequences = Todas las secuencias
 label.selected_columns = Columnas seleccionadas
@@ -291,7 +289,6 @@ label.found_match_for = Buscar coincidencia para {0}
 label.font = Fuente:
 label.size = Talla:
 label.style = Estilo:
-label.enter_redundancy_threshold = Introducir el umbral de redundancia
 label.calculating = Calculando....
 label.modify_conservation_visibility = Modificar la visibilidad de conservación
 label.colour_residues_above_occurence = Residuos de color por encima del % de aparición 
@@ -315,8 +312,6 @@ label.blog_item_published_on_date = {0} {1}
 label.select_das_service_from_table = Seleccionar servicio DAS de la tabla para leer una descripción completa aquí.
 label.session_update = Actualizar sesión
 label.new_vamsas_session = Nueva sesión Vamsas
-label.load_vamsas_session = Cargar sesión Vamsas
-label.save_vamsas_session = Guardar sesión Vamsas
 action.save_vamsas_session = Guardar Sesión Vamsas
 label.select_vamsas_session_opened_as_new_vamsas_session= Selecciones una sesión vamsas para abrirla como una nueva sesión.
 label.open_saved_vamsas_session = Abrir una sesión VAMSAS guardada
@@ -336,7 +331,6 @@ label.example = Ejemplo
 label.example_param = Ejemplo: {0}
 label.select_file_format_before_saving = Debe seleccionar un formato de fichero antes de guardar!
 label.file_format_not_specified = Formato de fichero no especificado
-label.alignment_contains_hidden_columns = El alineamiento contiene columnas ocultas.\nQuieres guardar s\u00F3lo el alineamiento visible?
 label.couldnt_save_file = No se pudo guardar el fichero: {0}
 label.error_saving_file = Error guardando el fichero
 label.remove_from_default_list = eliminar de la lista de defectuosos?
@@ -361,9 +355,9 @@ label.automatically_associate_pdb_files_with_sequences_same_name = Quieres asoci
 label.automatically_associate_pdb_files_by_name = Asociar los ficheros PDB por nombre automáticamente
 label.ignore_unmatched_dropped_files_info = Quieres <em>ignorar</em> los {0} ficheros cuyos nombres no coincidan con ningún IDs de las secuencias ?
 label.ignore_unmatched_dropped_files = Ignorar los ficheros sin coincidencias?
-label.enter_view_name = Introducir nombre visible (¿?)
+label.enter_view_name = Introduzca un nombre para la vista
 label.enter_label = Introducir etiqueta
-label.enter_label_for_the_structure = Introducir una etiqueta para la estructura?
+label.enter_label_for_the_structure = Introducir una etiqueta para la estructura
 label.pdb_entry_is_already_displayed = {0} Ya est\u00E1 mostrado.\nQuieres volver a usar este visor?
 label.map_sequences_to_visible_window = Mapa de secuencias en ventana visible: {0}
 label.add_pdbentry_to_view = Quieres a\u00F1adir {0} a la vista llamada\n{1}\n
@@ -436,7 +430,6 @@ label.no_features_added_to_this_alignment = No hay funciones asociadas a este al
 label.features_can_be_added_from_searches_1 = (Las funciones pueden ser añadidas de búsquedas o
 label.features_can_be_added_from_searches_2 = de ficheros de funciones Jalview / GFF)
 label.calculating_pca= Calculando PCA
-label.reveal_columns = Mostrar Columnas
 label.jalview_cannot_open_file = Jalview no puede abrir el fichero
 label.jalview_applet = Aplicación Jalview  
 label.loading_data = Cargando datos
@@ -444,7 +437,6 @@ label.memory_stats = Memoria libre total: {0} MB; Memoria m
 label.calculating_tree = Calculando Ã¡rbol
 label.state_queueing = En cola 
 label.state_running = Procesando
-label.state_complete = Completar
 label.state_completed = Finalizado
 label.state_job_cancelled = Â¡Trabajo cancelado!
 label.state_job_error = Error del trabajo!
@@ -458,8 +450,6 @@ label.load_associated_tree = Cargar 
 label.load_features_annotations = Cargar características/anotaciones ...
 label.export_features = Exportar características...
 label.export_annotations = Exportar anotaciones ...
-label.jalview_copy = Copiar (sólo Jalview)
-label.jalview_cut = Cortar (sólo Jalview)
 label.to_upper_case = Pasar a mayúsculas
 label.to_lower_case = Pasar a minúsculas
 label.toggle_case = Alternar mayúsculas y minúsculas
@@ -468,8 +458,9 @@ label.create_sequence_feature = Crear funci
 label.edit_sequence = Editar secuencia
 label.edit_sequences = Editar secuencias
 label.sequence_details = Detalles de la secuencia
-label.jmol_help = Ayuda de Jmol 
-label.all = Todo
+label.jmol_help = Ayuda de Jmol
+# Todos/Todas is gender-sensitive, but currently only used for feminine (cadena / anotación)! 
+label.all = Todas
 label.sort_by = Ordenar por
 label.sort_by_score = Ordenar por puntuación
 label.sort_by_density = Ordenar por densidad
@@ -485,15 +476,14 @@ label.reset_min_max_colours_to_defaults = Reiniciar los colores min y max colour
 label.align_structures_using_linked_alignment_views = Alinear las estructuras utlizando las {0} vistas de alineamiento enlazadas
 label.connect_to_session = Conectar a la sesión {0}
 label.threshold_feature_display_by_score = Filtrar la característica mostrada por puntuación.
-label.threshold_feature_no_thereshold = Sin umbral
-label.threshold_feature_above_thereshold = Por encima del umbral
-label.threshold_feature_below_thereshold = Por debajo del umbral
-label.adjust_thereshold = Ajustar umbral
+label.threshold_feature_no_threshold = Sin umbral
+label.threshold_feature_above_threshold = Por encima del umbral
+label.threshold_feature_below_threshold = Por debajo del umbral
+label.adjust_threshold = Ajustar umbral
 label.toggle_absolute_relative_display_threshold = Cambiar entre mostrar el umbral absoluto y el relativo.
 label.display_features_same_type_different_label_using_different_colour = Mostrar las características del mismo tipo con una etiqueta diferente y empleando un color distinto (p.e. características del dominio)
 label.select_colour_minimum_value = Seleccionar el color para el valor mínimo
 label.select_colour_maximum_value = Seleccionar el color para el valor máximo
-label.open_new_jmol_view_with_all_structures_associated_current_selection_superimpose_using_alignment = Abrir una nueva vista Jmol con todas las estructuras asociadas con la selección acxtual y superponer las utilizando el alineamiento.
 label.open_url_param = Abrir URL {0}
 label.open_url_seqs_param = Abrir URL ({0}..) ({1} secuencias)
 label.load_pdb_file_associate_with_sequence = Cargar un fichero PDB y asociarlo con la secuencia {0}
@@ -544,10 +534,9 @@ label.histogram = Histograma
 label.logo = Logo
 label.non_positional_features = Características no posicionales
 label.database_references = Referencias a base de datos
-label.share_selection_across_views = Compartir la selección en todas las vistas
-label.scroll_highlighted_regions = Desplazarse hasta las regiones resaltadas
+#label.share_selection_across_views = Compartir la selección en todas las vistas
+#label.scroll_highlighted_regions = Desplazarse hasta las regiones resaltadas
 label.gap_symbol = Símbolo del hueco
-label.alignment_colour = Color del alineamiento
 label.address = Dirección
 label.port = Puerto
 label.default_browser_unix = Navegador por defecto (Unix)
@@ -626,18 +615,11 @@ label.cut_paste = Cortar y pegar
 label.adjusting_parameters_for_calculation = Ajustar los parámetros para el cálculo existente
 label.2d_rna_structure_line = 2D RNA {0}
 label.2d_rna_sequence_name = 2D RNA - {0}
-label.edit_name_and_description_current_group = Editar el nombre y la descripción del grupo actual.
-label.view_structure_for = Visualizar la estructura para {0}
-label.view_all_structures = Visualizar todas las {0} estructuras.
-label.view_all_representative_structures = Visualizar todas las {0} estructuras representativas.
-label.open_new_jmol_view_with_all_representative_structures_associated_current_selection_superimpose_using_alignment = Abrir una nueva vista de Jmol con todas las estructuras representativas\nasociadas con la selecci\u00F3n actual\nsuperpuesta con el alineamiento actual.
-label.associate_structure_with_sequence = Asociar estructura con la secuencia
+label.edit_name_and_description_current_group = Editar el nombre y la descripción del grupo actual
 label.from_file = desde fichero
 label.enter_pdb_id = Introducir PDB Id
-label.discover_pdb_ids = Buscar PDB ids
 label.text_colour = Color del texto
 label.structure = Estructura
-label.view_structure = Visualizar estructura
 label.clustalx_colours = Colores de Clustalx
 label.above_identity_percentage = Sobre % identidad
 label.create_sequence_details_report_annotation_for = Anotación para {0}
@@ -670,7 +652,6 @@ label.use_registry = Utilizar el registro
 label.add_local_source = Añadir fuente local
 label.set_as_default = Establecer por defecto
 label.show_labels = Mostrar etiquetas
-label.background_colour = Color de fondo
 label.associate_nodes_with = Asociar nodos con
 label.jalview_pca_calculation = Cálculo del PCA por Jalview
 label.link_name = Nombre del enalce
@@ -763,17 +744,10 @@ label.user_preset = Preselecci
 label.service_preset = Preselección del servicio
 label.run_with_preset = Ejecutar {0} con preselección
 label.view_service_doc_url = Visualizar <a href="{0}">{1}</a></html>
-label.submit_sequence = Enviar {0} {1} {2} {3} a<br/>{4}</html>
 action.by_title_param = por {0}
-label.alignment = Alineamiento
-label.secondary_structure_prediction = Predicción de la estructura secundaria
-label.sequence_database_search = Búsqueda en base de datos de secuencias
-label.analysis = Análisis
-label.protein_disorder = Desorden en la proteína 
 label.source_from_db_source = Fuentes de {0}
 label.from_msname = de {0}
 label.superpose_with = Superponer con...
-action.do = Hacer
 label.scale_label_to_column = Ajustar la etiqueta a la columna
 label.add_new_row = Añadir nuevo fila
 label.edit_label_description = Editar etiqueta/descripción
@@ -817,7 +791,7 @@ label.service_url = URL del servicio
 label.copied_sequences = Secuencias copiadas
 label.cut_sequences = Cortar secuencias
 label.conservation_colour_increment = Incremento de Conservación del Color ({0})
-label.percentage_identity_thereshold = Umbral del Porcentaje de Identidad ({0})
+label.percentage_identity_threshold = Umbral del Porcentaje de Identidad ({0})
 label.error_unsupported_owwner_user_colour_scheme = Propietario no soportado para el diálogo del Esquema Cromático del Usuario
 label.save_alignment_to_file = Guardar Alineamiento en fichero
 label.save_features_to_file = Guardar Características en un fichero
@@ -833,7 +807,6 @@ label.save_vamsas_document_archive = Guardar el archivo de documento Vamsas
 label.saving_vamsas_doc = Guardando el documento VAMSAS en {0}
 label.load_feature_colours = Cargar colores de características
 label.save_feature_colours = Guardar esquema cromático de características
-label.dataset_for = {0} conjunto de datos para {1}
 label.select_startup_file = Seleccionar fichero de arranque
 label.select_default_browser = Seleccionar navegador web por defecto
 label.save_tree_as_newick = Guardar Ã¡rbol como fichero newick
@@ -861,15 +834,9 @@ error.null_from_clone1 = Nulo de clone1!
 error.implementation_error_sortbyfeature = Error de implementación - sortByFeature debe ser uno de FEATURE_SCORE, FEATURE_LABEL o FEATURE_DENSITY.
 error.not_yet_implemented = No se ha implementado todavía
 error.unknown_type_dna_or_pep = Tipo desconocido {0} - dna o pep son los Ãºnicos valores permitidos
-error.implementation_error_dont_know_thereshold_annotationcolourgradient = Error de implementación: no se conoce el valor umbral para el AnnotationColourGradient actual.
-error.implementation_error_embeddedpopup_not_null = Error de implementación - embeddedPopup debe ser no nulo.
-error.invalid_colour_for_mycheckbox = Color no válido para MyCheckBox
-error.implementation_error_unrecognised_render_object_for_features_type = Error de implementación: no se reconoce el objeto de representación {0} para las características de tipo {1}
-error.implementation_error_unsupported_feature_colour_object = Error de implementación: objeto de color de características no soportado.
+error.implementation_error_dont_know_threshold_annotationcolourgradient = Error de implementación: no se conoce el valor umbral para el AnnotationColourGradient actual.
 error.invalid_separator_parameter = Separador de parámetros no válido - debe tener longitud mayor que cero
 error.alignment_cigararray_not_implemented = Alignment(CigarArray) no se ha implementado todavía
-error.weak_sequencei_equivalence_not_yet_implemented = Equivalencia débil sequenceI no se ha implementado todavía.
-error.implementation_error_can_only_make_alignmnet_from_cigararray = Error de implementación - sólo se puede construir un vista de alineamiento a partir de una CigarArray de secuencias.
 error.empty_view_cannot_be_updated = una vista vacía no se puede actualizar.
 error.mismatch_between_number_of_sequences_in_block = No hay coincidencia entre el número de secuencias en el bloque {0} ({1}) y la vista original ({2})
 error.padding_not_yet_implemented = El relleno no se ha implementado todavía
@@ -891,16 +858,14 @@ error.not_yet_implemented_cigar_object_from_cigar_string = No implementado todav
 error.implementation_bug_cigar_operation = Bug de implementación. La operación Cigar {0} {1} no es ni {2}, ni {3} ni {4}.
 error.implementation_error_for_new_cigar = Error de implementación en new Cigar(SequenceI)
 error.implementation_error_cigar_seq_no_operations = Error de implementación: la {0}a secuencia Cigar no tiene operaciones.
-error.implementation_error_jmol_getting_data = Error de implementación - Jmol parece estar todavía intentando recuperar sus datos - informe de ello en http://issues.jalview.org/browse/JAL-1016
 error.implementation_error_no_pdbentry_from_index = Error de implementación - no existe la correspondiente entrada pdb (para el Ã­ndice {0}) para añadir el mapeo de secuencias a
 error.jmol_version_not_compatible_with_jalview_version = La versión {0} de Jmol no es compatible con esta versión de Jalview. Informe de este problema en http://issues.jalview.org
 error.not_implemented_remove = Borrar: no implementado
 error.not_implemented_clone = Clonar: no implementado
-error.implementation_error_chimera_getting_data = Error de implementación - Chimera parece estar todavía intentando recuperar sus datos - informe de ello en http://issues.jalview.org/browse/JAL-1016
 error.call_setprogressbar_before_registering_handler = llamada a setProgressBar antes de registrar el manejador de la barra de estado
 label.cancelled_params = {0} cancelado
 error.implementation_error_cannot_show_view_alignment_frame = Error de implementación: no es posible mostrar una vista de otro alineamiento en un AlignFrame.
-error.implementation_error_dont_know_about_thereshold_setting = Error de implementación: no se conoce la configuración del umbral para el AnnotationColourGradient actual.
+error.implementation_error_dont_know_about_threshold_setting = Error de implementación: no se conoce la configuración del umbral para el AnnotationColourGradient actual.
 error.eps_generation_not_implemented = La generación de EPS no se ha implementado todavía
 error.png_generation_not_implemented = La generación de PNG no se ha implementado todavía
 error.try_join_vamsas_session_another = Tratando de establecer una sesión VAMSAS cuando ya había otra conectada
@@ -919,7 +884,6 @@ error.setstatus_called_non_existent_job_pane = se lllamado a setStatus para el p
 error.implementation_error_cannot_find_marshaller_for_param_set =Error de implementación: no puede encontrar un marshaller para el conjunto de parámetros
 error.implementation_error_old_jalview_object_not_bound =Error de implementación: Â¡el objeto Jalview antiguo no está enlazado! ({0})
 error.implementation_error_vamsas_doc_class_should_bind_to_type = Error de implementación: la clase de documento VAMSAS {0} debe enlazar a {1} (pero se ha encontrado que lo está a {2})
-error.implementation_error_jalview_class_should_bind_to_type = Error de implementación: la clase Jalview {0} debe enlazar a {1} (pero se ha encontrado que lo está a {2})
 error.invalid_vamsas_rangetype_cannot_resolve_lists = RangeType VAMSAS no válido - Â¡no es posible resolver ambas listas de Pos y Seg con los valores elegidos!
 error.implementation_error_maplist_is_null = Error de implementación. MapList es nulo en initMapType.
 error.implementation_error_cannot_have_null_alignment = Error de implementación: no es posible tener una clave nula en el alineamiento
@@ -961,10 +925,11 @@ error.implementation_error_need_to_have_httpresponse = Error de implementaci
 error.dbrefsource_implementation_exception = Excepción de implementación DBRefSource
 error.implementation_error_dbinstance_must_implement_interface = Error de Implementación- getDbInstances debe recibir una clase que implemente jalview.ws.seqfetcher.DbSourceProxy (recibió {0})
 error.implementation_error_must_init_dbsources =Error de implementación. Debe inicializar dbSources
-label.view_controller_toggled_marked = {0} {1} columnas conteniendo características del tipo {2} en {3} secuencia(s)
+label.view_controller_toggled_marked = {0} {1} columnas {2} características del tipo {3} en {4} secuencia(s)
 label.toggled = Invertida
 label.marked = Marcada
-label.not = no
+label.containing = conteniendo
+label.not_containing = no conteniendo
 label.no_feature_of_type_found = No se han encontrado características del tipo {0}.
 label.submission_params = Envío {0}
 label.empty_alignment_job = Trabajo de alineamiento vacío
@@ -974,7 +939,7 @@ label.pca_recalculating = Recalculando PCA
 label.pca_calculating = Calculando PCA
 label.select_foreground_colour = Escoger color del primer plano
 label.select_colour_for_text = Seleccione el color del texto
-label.adjunst_foreground_text_colour_thereshold = Ajustar el umbral del color del texto en primer plano
+label.adjunst_foreground_text_colour_threshold = Ajustar el umbral del color del texto en primer plano
 label.select_subtree_colour = Seleccioanr el color del sub-árbol
 label.create_new_sequence_features = Crear nueva(s) característica(s) de secuencia
 label.amend_delete_features = Arrelgar/Borrar características de {0}
@@ -994,7 +959,6 @@ exception.mismatched_unseen_closing_char = Discordancia (no vista) en el car
 exception.mismatched_closing_char = Carácter de cierre discordante {0}
 exception.mismatched_opening_char = Carácter de apertura discordante {0} en {1}
 exception.invalid_datasource_couldnt_obtain_reader = Fuente de datos no válida. No es posible obtener el Reader
-exception.index_value_not_in_range = {0}: el valor del Ã­ndice {1} en se encuentra en el rango [0..{2}]
 exception.unterminated_cigar_string = Cadena cigar sin terminar
 exception.unexpected_operation_cigar_string_pos = Operación no esperada {0} en una cadena cigar (posición {1} en {2})
 exception.couldnt_parse_responde_from_annotated3d_server = No es posible parsear la respuesta procedente del servidor Annotate3d 
@@ -1022,7 +986,6 @@ exception.ranml_problem_parsing_data = Problema parseando los datos como RNAML (
 exception.pfam_no_sequences_found = No se han encontrado secuencias (entrada PFAM)
 exception.stockholm_invalid_format = Este fichero no es tiene un formato STOCKHOLM válido: la primera línea no contiene '# STOCKHOLM'
 exception.couldnt_parse_sequence_line = No es posible parse la línea de secuencia: {0}
-exception.error_parsing_line = Error parseando {0}
 exception.unknown_annotation_detected = Anotación desconocida detectada: {0} {1}
 exception.couldnt_store_sequence_mappings = No es posible almacenar los mapeos de secuencia para {0}
 exception.matrix_too_many_iteration = Demasiadas iteraciones en {0} (el máximo es {1})
@@ -1030,7 +993,6 @@ exception.browser_not_found = Excepci
 exception.browser_unable_to_locate = Imposible encontrar el navegador: {0}
 exception.invocation_target_exception_creating_aedesc = InvocationTargetException mientras se creaba AEDesc: {0}
 exception.illegal_access_building_apple_evt= IllegalAccessException mientras se construía AppleEvent: {0}
-exception.instantiation_creating_aedesc = InstantiationException mientras se creaba AEDesc: {0}
 exception.unable_to_launch_url = Imposible lanzar la URL: {0}
 exception.unable_to_create_internet_config = Imposible crear una instancia de configuración de Internet: {0}
 exception.invocation_target_calling_url = InvocationTargetException mientras se invocaba openURL: {0}
@@ -1039,8 +1001,6 @@ exception.interrupted_launching_browser = InterruptedException mientras se lanza
 exception.das_source_doesnt_support_sequence_command = La fuente {0} no soporta el comando sequence.
 exception.invalid_das_source = Fuente DAS no válida: {0}
 exception.ebiembl_retrieval_failed_on = La recuperación de datos EBI EMBL XML ha fallado en {0}:{1}
-label.no_embl_record_found = # No se ha recuperado ningún registro EMBL de {0}:{1}
-label.embl_successfully_parsed = # Se han parseado con Ã©xito las consultas {0} en un alineamiento
 exception.no_pdb_records_for_chain = No se han encontrado registros {0} para la cadena {1}
 exception.unexpected_handling_rnaml_translation_for_pdb = Excepcion inesperada cuando se traducían a RNAML los datos PDB
 exception.couldnt_recover_sequence_properties_for_alignment = No es posible recuperar las propiedades de la secuencia para el alineamiento
@@ -1122,8 +1082,8 @@ label.edit_jabaws_url = Editar JABAWS URL
 label.add_jabaws_url = Añadir nueva JABAWS URL
 label.news_from_jalview = Noticias de http://www.jalview.org
 label.cut_paste_alignmen_file = Cortar & Pegar fichero de alineamiento
-label.enter_redundancy_thereshold = Introducir el umbral de redundancia
-label.select_dark_light_set_thereshold = <i>Seleccionar un color oscuro y un color claro para el texto y establecer el umbral en que<br>cambiar entre colores, basándose en el color de fondo</i>
+label.enter_redundancy_threshold = Introducir el umbral de redundancia
+label.select_dark_light_set_threshold = <i>Seleccionar un color oscuro y un color claro para el texto y establecer el umbral en que<br>cambiar entre colores, basándose en el color de fondo</i>
 label.select_feature_colour = Seleccionar color de las características
 label.ignore_gaps_consensus = Ignorar huecos en el consenso
 label.show_group_histogram = Mostrar histograma de grupo
@@ -1143,7 +1103,6 @@ action.feature_settings=Ajustes de caracter
 info.invalid_msa_notenough=No suficientes datos de sequencia para alinear
 label.result=resultado
 label.results=resultados
-label.no_mappings=No hay mapeados encontrados
 label.struct_from_pdb=Procesar la estructura secundaria PDB
 label.hide_selected_annotations=Ocultar anotaciones seleccionados
 info.select_annotation_row=Seleccionar Fila de Anotaciones
@@ -1167,7 +1126,6 @@ action.no=No
 action.yes=Sí
 label.export_settings=Exportar Ajustes
 label.linked_view_title=Vista vinculada de cDNA y proteína
-label.view_protein_structure=Ver Estructura Proteica
 label.couldnt_read_data=No se pudo leer los datos
 status.opening_file=abriendo fichero
 label.except_selected_sequences=Todo excepto secuencias seleccionadas
@@ -1212,7 +1170,6 @@ action.select_by_annotation=Seleccionar/Ocultar Columnas por Anotaci
 action.export_features=Exportar Características
 error.invalid_regex=Expresión regular inválida
 label.autoadd_temp=Añadir anotación factor de temperatura al alineamiento
-tooltip.rnalifold_settings=Modificar la configuración de la predicción RNAAlifold. Ãšselo para ocultar o mostrar resultados del cálculo de RNA, o cambiar parámetros de el plegado de RNA.
 label.chimera_path_tip=Jalview intentará primero las rutas introducidas aquí, Y si no las rutas usuales de instalación
 label.structure_chooser=Selector de Estructuras
 label.structure_chooser_manual_association=Selector de Estructuras - asociación manual
@@ -1228,9 +1185,7 @@ label.colour_with_chimera=Colorear con Chimera
 label.show_pdbstruct_dialog=Datos de Estructura 3D...
 label.hide_all=Ocultar todos
 label.invert=Invertir
-label.pdb_sequence_getcher=Buscador de Secuencias PDB
 tooltip.aacon_settings=Cambiar ajustes para cálculos AACon
-label.align=Alinear
 label.mark_as_representative=Marcar como representativa
 label.include_description=Incluir Descripción
 label.for=para
@@ -1246,15 +1201,13 @@ info.associate_wit_sequence=Asociar con secuencia
 label.protein=Proteína
 warn.oneseq_msainput_selection=La selección actual sólo contiene una Ãºnica secuencia. Â¿Quieres enviar todas las secuencias para la alineación en su lugar?
 label.use_rnaview=Usar RNAView para estructura secondaria
-label.opens_the_jabaws_server_homepage=Abre la página de inicio del servidor JABAWS en navegador
 label.search_all=Introducir uno o más valores de búsqueda separados por punto y coma ";" (Nota: buscará en toda la base de datos PDB)
 label.confirm_close_chimera=Cerrará la conexión de Jalview a {0}.<br>¿Quieres cerrar la ventana Chimera también?
 tooltip.rnalifold_calculations=Se calcularán predicciones de estructura secondaria de RNA para el alineaminento, y se actualizarán si se efectuan cambios
-Calcular predicciónes de estructura secondaria para el alineamiento
+tooltip.rnalifold_settings=Modificar la configuración de la predicción RNAAlifold. Ãšselo para ocultar o mostrar resultados del cálculo de RNA, o cambiar parámetros de el plegado de RNA.
 label.show_selected_annotations=Mostrar anotaciones seleccionadas
 status.colouring_chimera=Coloreando Chimera
 label.configure_displayed_columns=Configurar Columnas Mostradas
-exception.pdb_server_error=Error desde el servidor PDB
 exception.resource_not_be_found=El recurso solicitado no se ha encontrado
 label.aacon_calculations=cálculos AACon
 label.pdb_web-service_error=Error de servicio web PDB
@@ -1263,10 +1216,8 @@ label.chimera_path=Ruta de acceso a programa Chimera
 warn.delete_all=<html>Borrar todas las secuencias cerrará la ventana del alineamiento.<br>Confirmar o Cancelar.
 label.select_all=Seleccionar Todos
 label.alpha_helix=Hélice Alfa
-label.sequence_details_for=Detalles de secuencia para {0}
 label.chimera_help=Ayuda para Chimera
 label.find_tip=Buscar alineamiento, selección o IDs de secuencia para una subsecuencia (sin huecos)
-exception.pdb_server_unreachable=Jalview no puede conectar con el servidor PDBE Solr.\nPor favor, asegúrese de que está conectado a Internet y vuelva a intentarlo.
 label.structure_viewer=Visualizador de estructura for defecto
 label.embbed_biojson=Incrustar BioJSON al exportar HTML
 label.transparency_tip=Ajustar la transparencia a "ver a través" los colores de las características.
@@ -1279,7 +1230,6 @@ info.select_filter_option=Escoger Opci
 info.invalid_msa_input_mininfo=Necesita por lo menos dos secuencias con al menos 3 residuos cada una, sin regiones ocultas entre ellas.
 label.chimera_missing=Visualizador de estructura Chimera no encontrado.<br/>Por favor, introduzca la ruta de Chimera,<br/>o descargar e instalar la UCSF Chimera.
 label.save_as_biojs_html=Guardar como HTML BioJs
-exception.pdb_rest_service_no_longer_available=Servicios Rest PDB ya no están disponibles!
 exception.fts_server_unreachable=Jalview no puede conectar con el servidor {0}. \nPor favor asegúrese de que está conectado a Internet y vuelva a intentarlo.
 exception.outofmemory_loading_mmcif_file=Sin memoria al cargar el fichero mmCIF
 label.hide_columns_not_containing=Ocultar las columnas que no contengan
@@ -1312,4 +1262,8 @@ status.obtaining_mapping_with_sifts=Obteniendo mapeo por SIFTS
 status.fetching_3d_structures_for=Buscando la estructura 3D para {0}
 status.fetching_3d_structures_for_selected_entries=Buscando las estructuras 3D para entradas seleccionadas...
 status.fetching_dbrefs_for_sequences_without_valid_refs=Buscando referencias para {0} secuencia(s) sin referencia válida necesaria para mapeado SIFTS
-status.obtaining_mapping_with_nw_alignment=Obteniendo mapeo por alineamiento Needleman y Wunsch
\ No newline at end of file
+status.obtaining_mapping_with_nw_alignment=Obteniendo mapeo por alineamiento Needleman y Wunsch
+status.exporting_alignment_as_x_file = Exportando alineamiento como fichero tipo {0}
+label.column = Columna
+label.cant_map_cds = No se pudo mapear CDS a proteína\nDatos CDS faltantes o incompletos
+label.operation_failed = Operación fallada
index 68a7c21..fe6a0ac 100755 (executable)
@@ -81,7 +81,7 @@ public class Atom
     chain = str.substring(21, 22);
 
     resNumber = Integer.parseInt(str.substring(22, 26).trim());
-    resNumIns = str.substring(22, 27);
+    resNumIns = str.substring(22, 27).trim();
     insCode = str.substring(26, 27).charAt(0);
     this.x = (new Float(str.substring(30, 38).trim()).floatValue());
     this.y = (new Float(str.substring(38, 46).trim()).floatValue());
@@ -109,6 +109,23 @@ public class Atom
     }
   }
 
+  @Override
+  public boolean equals(Object that)
+  {
+    if (this == that || that == null)
+    {
+      return true;
+    }
+    if (that instanceof Atom)
+    {
+      Atom other = (Atom) that;
+      return other.resName.equals(this.resName)
+              && other.resNumber == this.resNumber
+              && other.resNumIns.equals(this.resNumIns)
+              && other.chain.equals(this.chain);
+    }
+    return false;
+  }
   public Atom(float x, float y, float z)
   {
     this.x = x;
index 885521b..cf794b6 100755 (executable)
@@ -29,8 +29,8 @@ import jalview.datamodel.SequenceFeature;
 import jalview.datamodel.SequenceI;
 import jalview.schemes.ColourSchemeI;
 import jalview.schemes.ResidueProperties;
-import jalview.structure.StructureMapping;
 import jalview.structure.StructureImportSettings;
+import jalview.structure.StructureMapping;
 
 import java.awt.Color;
 import java.util.List;
@@ -582,12 +582,13 @@ public class PDBChain
         {
           for (AlignmentAnnotation ana : sequence.getAnnotation())
           {
-            List<AlignmentAnnotation> transfer = sq
+            List<AlignmentAnnotation> transfer = dsq
                     .getAlignmentAnnotations(ana.getCalcId(), ana.label);
             if (transfer == null || transfer.size() == 0)
             {
               ana = new AlignmentAnnotation(ana);
               ana.liftOver(dsq, sqmpping);
+              dsq.addAlignmentAnnotation(ana);
               // mapping.transfer(ana);
             }
             else
index 6da867d..060de45 100755 (executable)
@@ -23,10 +23,9 @@ package MCview;
 import jalview.datamodel.AlignmentAnnotation;
 import jalview.datamodel.DBRefSource;
 import jalview.datamodel.SequenceI;
-import jalview.io.FileParse;
 import jalview.io.DataSourceType;
+import jalview.io.FileParse;
 import jalview.io.StructureFile;
-import jalview.structure.StructureImportSettings;
 import jalview.util.MessageManager;
 
 import java.io.IOException;
@@ -67,7 +66,7 @@ public class PDBfile extends StructureFile
   }
 
   @Override
-  public String print()
+  public String print(SequenceI[] seqs, boolean jvSuffix)
   {
     return null;
   }
@@ -134,8 +133,7 @@ public class PDBfile extends StructureFile
           break;
         }
         if (line.indexOf("ATOM") == 0
-                || (StructureImportSettings.isProcessHETATMs()
-                        && line.indexOf("HETATM") == 0 && !terFlag))
+                || (line.indexOf("HETATM") == 0 && !terFlag))
         {
           terFlag = false;
 
index 3d61b11..fb49541 100755 (executable)
@@ -624,8 +624,11 @@ public class AAFrequency
       String modalCodon = String.valueOf(CodingUtils
               .decodeCodon(modalCodonEncoded));
       if (sortedCodonCounts.length > 1
-              && sortedCodonCounts[codons.length - 2] == modalCodonEncoded)
+              && sortedCodonCounts[codons.length - 2] == sortedCodonCounts[codons.length - 1])
       {
+        /*
+         * two or more codons share the modal count
+         */
         modalCodon = "+";
       }
       float pid = sortedCodonCounts[sortedCodonCounts.length - 1] * 100
index 33a54e8..d1cd5a3 100644 (file)
@@ -22,8 +22,10 @@ package jalview.analysis;
 
 import static jalview.io.gff.GffConstants.CLINICAL_SIGNIFICANCE;
 
+import jalview.api.DBRefEntryI;
 import jalview.datamodel.AlignedCodon;
 import jalview.datamodel.AlignedCodonFrame;
+import jalview.datamodel.AlignedCodonFrame.SequenceToSequenceMapping;
 import jalview.datamodel.Alignment;
 import jalview.datamodel.AlignmentAnnotation;
 import jalview.datamodel.AlignmentI;
@@ -38,6 +40,7 @@ import jalview.io.gff.SequenceOntologyFactory;
 import jalview.io.gff.SequenceOntologyI;
 import jalview.schemes.ResidueProperties;
 import jalview.util.Comparison;
+import jalview.util.DBRefUtils;
 import jalview.util.MapList;
 import jalview.util.MappingUtils;
 import jalview.util.StringUtils;
@@ -70,6 +73,7 @@ import java.util.TreeMap;
 public class AlignmentUtils
 {
 
+  private static final int CODON_LENGTH = 3;
   private static final String SEQUENCE_VARIANT = "sequence_variant:";
   private static final String ID = "ID";
 
@@ -77,15 +81,16 @@ public class AlignmentUtils
    * A data model to hold the 'normal' base value at a position, and an optional
    * sequence variant feature
    */
-  static class DnaVariant
+  static final class DnaVariant
   {
-    String base;
+    final String base;
 
     SequenceFeature variant;
 
     DnaVariant(String nuc)
     {
       base = nuc;
+      variant = null;
     }
 
     DnaVariant(String nuc, SequenceFeature var)
@@ -93,6 +98,11 @@ public class AlignmentUtils
       base = nuc;
       variant = var;
     }
+
+    public String getSource()
+    {
+      return variant == null ? null : variant.getFeatureGroup();
+    }
   }
 
   /**
@@ -425,7 +435,7 @@ public class AlignmentUtils
     /*
      * cdnaStart/End, proteinStartEnd are base 1 (for dataset sequence mapping)
      */
-    final int mappedLength = 3 * aaSeqChars.length;
+    final int mappedLength = CODON_LENGTH * aaSeqChars.length;
     int cdnaLength = cdnaSeqChars.length;
     int cdnaStart = cdnaSeq.getStart();
     int cdnaEnd = cdnaSeq.getEnd();
@@ -437,14 +447,14 @@ public class AlignmentUtils
      */
     if (cdnaLength != mappedLength && cdnaLength > 2)
     {
-      String lastCodon = String.valueOf(cdnaSeqChars, cdnaLength - 3, 3)
+      String lastCodon = String.valueOf(cdnaSeqChars, cdnaLength - CODON_LENGTH, CODON_LENGTH)
               .toUpperCase();
       for (String stop : ResidueProperties.STOP)
       {
         if (lastCodon.equals(stop))
         {
-          cdnaEnd -= 3;
-          cdnaLength -= 3;
+          cdnaEnd -= CODON_LENGTH;
+          cdnaLength -= CODON_LENGTH;
           break;
         }
       }
@@ -456,12 +466,12 @@ public class AlignmentUtils
     int startOffset = 0;
     if (cdnaLength != mappedLength
             && cdnaLength > 2
-            && String.valueOf(cdnaSeqChars, 0, 3).toUpperCase()
+            && String.valueOf(cdnaSeqChars, 0, CODON_LENGTH).toUpperCase()
                     .equals(ResidueProperties.START))
     {
-      startOffset += 3;
-      cdnaStart += 3;
-      cdnaLength -= 3;
+      startOffset += CODON_LENGTH;
+      cdnaStart += CODON_LENGTH;
+      cdnaLength -= CODON_LENGTH;
     }
 
     if (translatesAs(cdnaSeqChars, startOffset, aaSeqChars))
@@ -470,7 +480,7 @@ public class AlignmentUtils
        * protein is translation of dna (+/- start/stop codons)
        */
       MapList map = new MapList(new int[] { cdnaStart, cdnaEnd }, new int[]
-      { proteinStart, proteinEnd }, 3, 1);
+      { proteinStart, proteinEnd }, CODON_LENGTH, 1);
       return map;
     }
 
@@ -501,9 +511,9 @@ public class AlignmentUtils
     int aaPos = 0;
     int dnaPos = cdnaStart;
     for (; dnaPos < cdnaSeqChars.length - 2
-            && aaPos < aaSeqChars.length; dnaPos += 3, aaPos++)
+            && aaPos < aaSeqChars.length; dnaPos += CODON_LENGTH, aaPos++)
     {
-      String codon = String.valueOf(cdnaSeqChars, dnaPos, 3);
+      String codon = String.valueOf(cdnaSeqChars, dnaPos, CODON_LENGTH);
       final String translated = ResidueProperties.codonTranslate(codon);
 
       /*
@@ -539,9 +549,9 @@ public class AlignmentUtils
     {
       return true;
     }
-    if (dnaPos == cdnaSeqChars.length - 3)
+    if (dnaPos == cdnaSeqChars.length - CODON_LENGTH)
     {
-      String codon = String.valueOf(cdnaSeqChars, dnaPos, 3);
+      String codon = String.valueOf(cdnaSeqChars, dnaPos, CODON_LENGTH);
       if ("STOP".equals(ResidueProperties.codonTranslate(codon)))
       {
         return true;
@@ -849,6 +859,11 @@ public class AlignmentUtils
    */
   public static int alignProteinAsDna(AlignmentI protein, AlignmentI dna)
   {
+    if (protein.isNucleotide() || !dna.isNucleotide())
+    {
+      System.err.println("Wrong alignment type in alignProteinAsDna");
+      return 0;
+    }
     List<SequenceI> unmappedProtein = new ArrayList<SequenceI>();
     Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons = buildCodonColumnsMap(
             protein, dna, unmappedProtein);
@@ -856,6 +871,177 @@ public class AlignmentUtils
   }
 
   /**
+   * Realigns the given dna to match the alignment of the protein, using codon
+   * mappings to translate aligned peptide positions to codons.
+   * 
+   * Always produces a padded CDS alignment.
+   * 
+   * @param dna
+   *          the alignment whose sequences are realigned by this method
+   * @param protein
+   *          the protein alignment whose alignment we are 'copying'
+   * @return the number of sequences that were realigned
+   */
+  public static int alignCdsAsProtein(AlignmentI dna, AlignmentI protein)
+  {
+    if (protein.isNucleotide() || !dna.isNucleotide())
+    {
+      System.err.println("Wrong alignment type in alignProteinAsDna");
+      return 0;
+    }
+    // todo: implement this
+    List<AlignedCodonFrame> mappings = protein.getCodonFrames();
+    int alignedCount = 0;
+    int width = 0; // alignment width for padding CDS
+    for (SequenceI dnaSeq : dna.getSequences())
+    {
+      if (alignCdsSequenceAsProtein(dnaSeq, protein, mappings,
+              dna.getGapCharacter()))
+      {
+        alignedCount++;
+      }
+      width = Math.max(dnaSeq.getLength(), width);
+    }
+    int oldwidth;
+    int diff;
+    for (SequenceI dnaSeq : dna.getSequences())
+    {
+      oldwidth = dnaSeq.getLength();
+      diff = width - oldwidth;
+      if (diff > 0)
+      {
+        dnaSeq.insertCharAt(oldwidth, diff, dna.getGapCharacter());
+      }
+    }
+    return alignedCount;
+  }
+
+  /**
+   * Helper method to align (if possible) the dna sequence to match the
+   * alignment of a mapped protein sequence. This is currently limited to
+   * handling coding sequence only.
+   * 
+   * @param cdsSeq
+   * @param protein
+   * @param mappings
+   * @param gapChar
+   * @return
+   */
+  static boolean alignCdsSequenceAsProtein(SequenceI cdsSeq,
+          AlignmentI protein, List<AlignedCodonFrame> mappings, char gapChar)
+  {
+    SequenceI cdsDss = cdsSeq.getDatasetSequence();
+    if (cdsDss == null)
+    {
+      System.err
+              .println("alignCdsSequenceAsProtein needs aligned sequence!");
+      return false;
+    }
+    
+    List<AlignedCodonFrame> dnaMappings = MappingUtils
+            .findMappingsForSequence(cdsSeq, mappings);
+    for (AlignedCodonFrame mapping : dnaMappings)
+    {
+      SequenceI peptide = mapping.findAlignedSequence(cdsSeq, protein);
+      if (peptide != null)
+      {
+        int peptideLength = peptide.getLength();
+        Mapping map = mapping.getMappingBetween(cdsSeq, peptide);
+        if (map != null)
+        {
+          MapList mapList = map.getMap();
+          if (map.getTo() == peptide.getDatasetSequence())
+          {
+            mapList = mapList.getInverse();
+          }
+          int cdsLength = cdsDss.getLength();
+          int mappedFromLength = MappingUtils.getLength(mapList
+                  .getFromRanges());
+          int mappedToLength = MappingUtils
+                  .getLength(mapList.getToRanges());
+          boolean addStopCodon = (cdsLength == mappedFromLength * CODON_LENGTH + CODON_LENGTH)
+                  || (peptide.getDatasetSequence().getLength() == mappedFromLength - 1);
+          if (cdsLength != mappedToLength && !addStopCodon)
+          {
+            System.err
+                    .println(String
+                            .format("Can't align cds as protein (length mismatch %d/%d): %s",
+                                    cdsLength, mappedToLength,
+                                    cdsSeq.getName()));
+          }
+
+          /*
+           * pre-fill the aligned cds sequence with gaps
+           */
+          char[] alignedCds = new char[peptideLength * CODON_LENGTH
+                  + (addStopCodon ? CODON_LENGTH : 0)];
+          Arrays.fill(alignedCds, gapChar);
+
+          /*
+           * walk over the aligned peptide sequence and insert mapped 
+           * codons for residues in the aligned cds sequence 
+           */
+          char[] alignedPeptide = peptide.getSequence();
+          char[] nucleotides = cdsDss.getSequence();
+          int copiedBases = 0;
+          int cdsStart = cdsDss.getStart();
+          int proteinPos = peptide.getStart() - 1;
+          int cdsCol = 0;
+          for (char residue : alignedPeptide)
+          {
+            if (Comparison.isGap(residue))
+            {
+              cdsCol += CODON_LENGTH;
+            }
+            else
+            {
+              proteinPos++;
+              int[] codon = mapList.locateInTo(proteinPos, proteinPos);
+              if (codon == null)
+              {
+                // e.g. incomplete start codon, X in peptide
+                cdsCol += CODON_LENGTH;
+              }
+              else
+              {
+                for (int j = codon[0]; j <= codon[1]; j++)
+                {
+                  char mappedBase = nucleotides[j - cdsStart];
+                  alignedCds[cdsCol++] = mappedBase;
+                  copiedBases++;
+                }
+              }
+            }
+          }
+
+          /*
+           * append stop codon if not mapped from protein,
+           * closing it up to the end of the mapped sequence
+           */
+          if (copiedBases == nucleotides.length - CODON_LENGTH)
+          {
+            for (int i = alignedCds.length - 1; i >= 0; i--)
+            {
+              if (!Comparison.isGap(alignedCds[i]))
+              {
+                cdsCol = i + 1; // gap just after end of sequence
+                break;
+              }
+            }
+            for (int i = nucleotides.length - CODON_LENGTH; i < nucleotides.length; i++)
+            {
+              alignedCds[cdsCol++] = nucleotides[i];
+            }
+          }
+          cdsSeq.setSequence(new String(alignedCds));
+          return true;
+        }
+      }
+    }
+    return false;
+  }
+
+  /**
    * Builds a map whose key is an aligned codon position (3 alignment column
    * numbers base 0), and whose value is a map from protein sequence to each
    * protein's peptide residue for that codon. The map generates an ordering of
@@ -1403,75 +1589,272 @@ public class AlignmentUtils
    * added to the alignment dataset.
    * 
    * @param dna
-   *          aligned dna sequences
-   * @param mappings
-   *          from dna to protein
-   * @param al
+   *          aligned nucleotide (dna or cds) sequences
+   * @param dataset
+   *          the alignment dataset the sequences belong to
+   * @param products
+   *          (optional) to restrict results to CDS that map to specified
+   *          protein products
    * @return an alignment whose sequences are the cds-only parts of the dna
    *         sequences (or null if no mappings are found)
    */
   public static AlignmentI makeCdsAlignment(SequenceI[] dna,
-          List<AlignedCodonFrame> mappings, AlignmentI al)
+          AlignmentI dataset, SequenceI[] products)
   {
+    if (dataset == null || dataset.getDataset() != null)
+    {
+      throw new IllegalArgumentException(
+              "IMPLEMENTATION ERROR: dataset.getDataset() must be null!");
+    }
+    List<SequenceI> foundSeqs = new ArrayList<SequenceI>();
     List<SequenceI> cdsSeqs = new ArrayList<SequenceI>();
-    
-    for (SequenceI seq : dna)
+    List<AlignedCodonFrame> mappings = dataset.getCodonFrames();
+    HashSet<SequenceI> productSeqs = null;
+    if (products != null)
     {
-      AlignedCodonFrame cdsMappings = new AlignedCodonFrame();
+      productSeqs = new HashSet<SequenceI>();
+      for (SequenceI seq : products)
+      {
+        productSeqs.add(seq.getDatasetSequence() == null ? seq : seq
+                .getDatasetSequence());
+      }
+    }
+
+    /*
+     * Construct CDS sequences from mappings on the alignment dataset.
+     * The logic is:
+     * - find the protein product(s) mapped to from each dna sequence
+     * - if the mapping covers the whole dna sequence (give or take start/stop
+     *   codon), take the dna as the CDS sequence
+     * - else search dataset mappings for a suitable dna sequence, i.e. one
+     *   whose whole sequence is mapped to the protein 
+     * - if no sequence found, construct one from the dna sequence and mapping
+     *   (and add it to dataset so it is found if this is repeated)
+     */
+    for (SequenceI dnaSeq : dna)
+    {
+      SequenceI dnaDss = dnaSeq.getDatasetSequence() == null ? dnaSeq
+              : dnaSeq.getDatasetSequence();
+
       List<AlignedCodonFrame> seqMappings = MappingUtils
-              .findMappingsForSequence(seq, mappings);
-      List<AlignedCodonFrame> alignmentMappings = al.getCodonFrames();
+              .findMappingsForSequence(dnaSeq, mappings);
       for (AlignedCodonFrame mapping : seqMappings)
       {
-        for (Mapping aMapping : mapping.getMappingsFromSequence(seq))
+        List<Mapping> mappingsFromSequence = mapping
+                .getMappingsFromSequence(dnaSeq);
+
+        for (Mapping aMapping : mappingsFromSequence)
         {
-          SequenceI cdsSeq = makeCdsSequence(seq.getDatasetSequence(),
-                  aMapping);
+          MapList mapList = aMapping.getMap();
+          if (mapList.getFromRatio() == 1)
+          {
+            /*
+             * not a dna-to-protein mapping (likely dna-to-cds)
+             */
+            continue;
+          }
+
+          /*
+           * skip if mapping is not to one of the target set of proteins
+           */
+          SequenceI proteinProduct = aMapping.getTo();
+          if (productSeqs != null && !productSeqs.contains(proteinProduct))
+          {
+            continue;
+          }
+
+          /*
+           * try to locate the CDS from the dataset mappings;
+           * guard against duplicate results (for the case that protein has
+           * dbrefs to both dna and cds sequences)
+           */
+          SequenceI cdsSeq = findCdsForProtein(mappings, dnaSeq,
+                  seqMappings, aMapping);
+          if (cdsSeq != null)
+          {
+            if (!foundSeqs.contains(cdsSeq))
+            {
+              foundSeqs.add(cdsSeq);
+              SequenceI derivedSequence = cdsSeq.deriveSequence();
+              cdsSeqs.add(derivedSequence);
+              if (!dataset.getSequences().contains(cdsSeq))
+              {
+                dataset.addSequence(cdsSeq);
+              }
+            }
+            continue;
+          }
+
+          /*
+           * didn't find mapped CDS sequence - construct it and add
+           * its dataset sequence to the dataset
+           */
+          cdsSeq = makeCdsSequence(dnaSeq.getDatasetSequence(), aMapping);
+          SequenceI cdsSeqDss = cdsSeq.createDatasetSequence();
           cdsSeqs.add(cdsSeq);
-    
+          if (!dataset.getSequences().contains(cdsSeqDss))
+          {
+            dataset.addSequence(cdsSeqDss);
+          }
+
           /*
            * add a mapping from CDS to the (unchanged) mapped to range
            */
           List<int[]> cdsRange = Collections.singletonList(new int[] { 1,
               cdsSeq.getLength() });
-          MapList map = new MapList(cdsRange, aMapping.getMap()
-                  .getToRanges(), aMapping.getMap().getFromRatio(),
-                  aMapping.getMap().getToRatio());
-          cdsMappings.addMap(cdsSeq, aMapping.getTo(), map);
+          MapList cdsToProteinMap = new MapList(cdsRange, mapList.getToRanges(),
+                  mapList.getFromRatio(), mapList.getToRatio());
+          AlignedCodonFrame cdsToProteinMapping = new AlignedCodonFrame();
+          cdsToProteinMapping.addMap(cdsSeq, proteinProduct, cdsToProteinMap);
+
+          /*
+           * guard against duplicating the mapping if repeating this action
+           */
+          if (!mappings.contains(cdsToProteinMapping))
+          {
+            mappings.add(cdsToProteinMapping);
+          }
+
+          /*
+           * copy protein's dbrefs to CDS sequence
+           * this enables Get Cross-References from CDS alignment
+           */
+          DBRefEntry[] proteinRefs = DBRefUtils.selectDbRefs(false,
+                  proteinProduct.getDBRefs());
+          if (proteinRefs != null)
+          {
+            for (DBRefEntry ref : proteinRefs)
+            {
+              DBRefEntry cdsToProteinRef = new DBRefEntry(ref);
+              cdsToProteinRef.setMap(new Mapping(proteinProduct,
+                      cdsToProteinMap));
+              cdsSeqDss.addDBRef(cdsToProteinRef);
+            }
+          }
 
           /*
            * add another mapping from original 'from' range to CDS
            */
-          map = new MapList(aMapping.getMap().getFromRanges(), cdsRange, 1,
+          AlignedCodonFrame dnaToCdsMapping = new AlignedCodonFrame();
+          MapList dnaToCdsMap = new MapList(mapList.getFromRanges(),
+                  cdsRange, 1,
                   1);
-          cdsMappings.addMap(seq.getDatasetSequence(), cdsSeq, map);
+          dnaToCdsMapping.addMap(dnaSeq.getDatasetSequence(), cdsSeq,
+                  dnaToCdsMap);
+          if (!mappings.contains(dnaToCdsMapping))
+          {
+            mappings.add(dnaToCdsMapping);
+          }
 
-          alignmentMappings.add(cdsMappings);
+          /*
+           * add DBRef with mapping from protein to CDS
+           * (this enables Get Cross-References from protein alignment)
+           * This is tricky because we can't have two DBRefs with the
+           * same source and accession, so need a different accession for
+           * the CDS from the dna sequence
+           */
+          DBRefEntryI dnaRef = dnaDss.getSourceDBRef();
+          if (dnaRef != null)
+          {
+            // assuming cds version same as dna ?!?
+            DBRefEntry proteinToCdsRef = new DBRefEntry(dnaRef.getSource(),
+                    dnaRef.getVersion(), cdsSeq.getName());
+            proteinToCdsRef.setMap(new Mapping(cdsSeqDss, cdsToProteinMap
+                    .getInverse()));
+            proteinProduct.addDBRef(proteinToCdsRef);
+          }
 
           /*
            * transfer any features on dna that overlap the CDS
            */
-          transferFeatures(seq, cdsSeq, map, null, SequenceOntologyI.CDS);
+          transferFeatures(dnaSeq, cdsSeq, cdsToProteinMap, null,
+                  SequenceOntologyI.CDS);
         }
       }
     }
 
+    AlignmentI cds = new Alignment(cdsSeqs.toArray(new SequenceI[cdsSeqs
+            .size()]));
+    cds.setDataset(dataset);
+
+    return cds;
+  }
+
+  /**
+   * A helper method that finds a CDS sequence in the alignment dataset that is
+   * mapped to the given protein sequence, and either is, or has a mapping from,
+   * the given dna sequence.
+   * 
+   * @param mappings
+   *          set of all mappings on the dataset
+   * @param dnaSeq
+   *          a dna (or cds) sequence we are searching from
+   * @param seqMappings
+   *          the set of mappings involving dnaSeq
+   * @param aMapping
+   *          an initial candidate from seqMappings
+   * @return
+   */
+  static SequenceI findCdsForProtein(List<AlignedCodonFrame> mappings,
+          SequenceI dnaSeq, List<AlignedCodonFrame> seqMappings,
+          Mapping aMapping)
+  {
+    /*
+     * TODO a better dna-cds-protein mapping data representation to allow easy
+     * navigation; until then this clunky looping around lists of mappings
+     */
+    SequenceI seqDss = dnaSeq.getDatasetSequence() == null ? dnaSeq
+            : dnaSeq.getDatasetSequence();
+    SequenceI proteinProduct = aMapping.getTo();
+
+    /*
+     * is this mapping from the whole dna sequence (i.e. CDS)?
+     * allowing for possible stop codon on dna but not peptide
+     */
+    int mappedFromLength = MappingUtils.getLength(aMapping.getMap()
+            .getFromRanges());
+    int dnaLength = seqDss.getLength();
+    if (mappedFromLength == dnaLength || mappedFromLength == dnaLength - CODON_LENGTH)
+    {
+      return seqDss;
+    }
+
     /*
-     * add CDS seqs to shared dataset
+     * looks like we found the dna-to-protein mapping; search for the
+     * corresponding cds-to-protein mapping
      */
-    Alignment dataset = al.getDataset();
-    for (SequenceI seq : cdsSeqs)
+    List<AlignedCodonFrame> mappingsToPeptide = MappingUtils
+            .findMappingsForSequence(proteinProduct, mappings);
+    for (AlignedCodonFrame acf : mappingsToPeptide)
     {
-      if (!dataset.getSequences().contains(seq.getDatasetSequence()))
+      for (SequenceToSequenceMapping map : acf.getMappings())
       {
-        dataset.addSequence(seq.getDatasetSequence());
+        Mapping mapping = map.getMapping();
+        if (mapping != aMapping && mapping.getMap().getFromRatio() == CODON_LENGTH
+                && proteinProduct == mapping.getTo()
+                && seqDss != map.getFromSeq())
+        {
+          mappedFromLength = MappingUtils.getLength(mapping.getMap()
+                  .getFromRanges());
+          if (mappedFromLength == map.getFromSeq().getLength())
+          {
+            /*
+            * found a 3:1 mapping to the protein product which covers
+            * the whole dna sequence i.e. is from CDS; finally check it
+            * is from the dna start sequence
+            */
+            SequenceI cdsSeq = map.getFromSeq();
+            List<AlignedCodonFrame> dnaToCdsMaps = MappingUtils
+                    .findMappingsForSequence(cdsSeq, seqMappings);
+            if (!dnaToCdsMaps.isEmpty())
+            {
+              return cdsSeq;
+            }
+          }
+        }
       }
     }
-    AlignmentI cds = new Alignment(cdsSeqs.toArray(new SequenceI[cdsSeqs
-            .size()]));
-    cds.setDataset(dataset);
-
-    return cds;
+    return null;
   }
 
   /**
@@ -1481,7 +1864,7 @@ public class AlignmentUtils
    * 
    * @param seq
    * @param mapping
-   * @return
+   * @return CDS sequence (as a dataset sequence)
    */
   static SequenceI makeCdsSequence(SequenceI seq, Mapping mapping)
   {
@@ -1511,9 +1894,15 @@ public class AlignmentUtils
       }
     }
 
-    SequenceI newSeq = new Sequence(seq.getName() + "|"
-            + mapping.getTo().getName(), newSeqChars, 1, newPos);
-    newSeq.createDatasetSequence();
+    /*
+     * assign 'from id' held in the mapping if set (e.g. EMBL protein_id),
+     * else generate a sequence name
+     */
+    String mapFromId = mapping.getMappedFromId();
+    String seqId = "CDS|" + (mapFromId != null ? mapFromId : seq.getName());
+    SequenceI newSeq = new Sequence(seqId, newSeqChars, 1, newPos);
+    // newSeq.setDescription(mapFromId);
+
     return newSeq;
   }
 
@@ -1646,7 +2035,7 @@ public class AlignmentUtils
     /*
      * dna length should map to protein (or protein plus stop codon)
      */
-    int codesForResidues = mappedDnaLength / 3;
+    int codesForResidues = mappedDnaLength / CODON_LENGTH;
     if (codesForResidues == (proteinLength + 1))
     {
       // assuming extra codon is for STOP and not in peptide
@@ -1655,7 +2044,7 @@ public class AlignmentUtils
     if (codesForResidues == proteinLength)
     {
       proteinRange.add(new int[] { proteinStart, proteinEnd });
-      return new MapList(ranges, proteinRange, 3, 1);
+      return new MapList(ranges, proteinRange, CODON_LENGTH, 1);
     }
     return null;
   }
@@ -1799,17 +2188,20 @@ public class AlignmentUtils
      * sort to get sequence features in start position order
      * - would be better to store in Sequence as a TreeSet or NCList?
      */
-    Arrays.sort(peptide.getSequenceFeatures(),
-            new Comparator<SequenceFeature>()
-            {
-              @Override
-              public int compare(SequenceFeature o1, SequenceFeature o2)
+    if (peptide.getSequenceFeatures() != null)
+    {
+      Arrays.sort(peptide.getSequenceFeatures(),
+              new Comparator<SequenceFeature>()
               {
-                int c = Integer.compare(o1.getBegin(), o2.getBegin());
-                return c == 0 ? Integer.compare(o1.getEnd(), o2.getEnd())
-                        : c;
-              }
-            });
+                @Override
+                public int compare(SequenceFeature o1, SequenceFeature o2)
+                {
+                  int c = Integer.compare(o1.getBegin(), o2.getBegin());
+                  return c == 0 ? Integer.compare(o1.getEnd(), o2.getEnd())
+                          : c;
+                }
+              });
+    }
     return count;
   }
 
@@ -1928,7 +2320,7 @@ public class AlignmentUtils
      * are currently ignored here
      */
     String trans = codon.contains("-") ? "-"
-            : (codon.length() > 3 ? null : ResidueProperties
+            : (codon.length() > CODON_LENGTH ? null : ResidueProperties
                     .codonTranslate(codon));
     if (trans != null && !trans.equals(residue))
     {
@@ -1940,7 +2332,7 @@ public class AlignmentUtils
       // set score to 0f so 'graduated colour' option is offered! JAL-2060
       SequenceFeature sf = new SequenceFeature(
               SequenceOntologyI.SEQUENCE_VARIANT, desc, peptidePos,
-              peptidePos, 0f, "Jalview");
+              peptidePos, 0f, var.getSource());
       StringBuilder attributes = new StringBuilder(32);
       String id = (String) var.variant.getValue(ID);
       if (id != null)
@@ -1951,7 +2343,7 @@ public class AlignmentUtils
         }
         sf.setValue(ID, id);
         attributes.append(ID).append("=").append(id);
-        // TODO handle other species variants
+        // TODO handle other species variants JAL-2064
         StringBuilder link = new StringBuilder(32);
         try
         {
@@ -1990,6 +2382,7 @@ public class AlignmentUtils
    * @param dnaToProtein
    * @return
    */
+  @SuppressWarnings("unchecked")
   static LinkedHashMap<Integer, List<DnaVariant>[]> buildDnaVariantsMap(
           SequenceI dnaSeq, MapList dnaToProtein)
   {
@@ -2033,7 +2426,7 @@ public class AlignmentUtils
         List<DnaVariant>[] codonVariants = variants.get(peptidePosition);
         if (codonVariants == null)
         {
-          codonVariants = new ArrayList[3];
+          codonVariants = new ArrayList[CODON_LENGTH];
           codonVariants[0] = new ArrayList<DnaVariant>();
           codonVariants[1] = new ArrayList<DnaVariant>();
           codonVariants[2] = new ArrayList<DnaVariant>();
@@ -2067,7 +2460,7 @@ public class AlignmentUtils
         /*
          * save nucleotide (and any variant) for each codon position
          */
-        for (int codonPos = 0; codonPos < 3; codonPos++)
+        for (int codonPos = 0; codonPos < CODON_LENGTH; codonPos++)
         {
           String nucleotide = String.valueOf(
                   dnaSeq.getCharAt(codon[codonPos] - dnaStart))
@@ -2111,32 +2504,15 @@ public class AlignmentUtils
    * 
    * @param seqs
    * @param xrefs
+   * @param dataset
+   *          the alignment dataset shared by the new copy
    * @return
    */
   public static AlignmentI makeCopyAlignment(SequenceI[] seqs,
-          SequenceI[] xrefs)
+          SequenceI[] xrefs, AlignmentI dataset)
   {
     AlignmentI copy = new Alignment(new Alignment(seqs));
-
-    /*
-     * add mappings between sequences to the new alignment
-     */
-    AlignedCodonFrame mappings = new AlignedCodonFrame();
-    copy.addCodonFrame(mappings);
-    for (int i = 0; i < copy.getHeight(); i++)
-    {
-      SequenceI from = seqs[i];
-      SequenceI to = copy.getSequenceAt(i);
-      if (to.getDatasetSequence() != null)
-      {
-        to = to.getDatasetSequence();
-      }
-      int start = from.getStart();
-      int end = from.getEnd();
-      MapList map = new MapList(new int[] { start, end }, new int[] {
-          start, end }, 1, 1);
-      mappings.addMap(to, from, map);
-    }
+    copy.setDataset(dataset);
 
     SequenceIdMatcher matcher = new SequenceIdMatcher(seqs);
     if (xrefs != null)
@@ -2182,19 +2558,32 @@ public class AlignmentUtils
    */
   public static int alignAs(AlignmentI unaligned, AlignmentI aligned)
   {
+    /*
+     * easy case - aligning a copy of aligned sequences
+     */
+    if (alignAsSameSequences(unaligned, aligned))
+    {
+      return unaligned.getHeight();
+    }
+
+    /*
+     * fancy case - aligning via mappings between sequences
+     */
     List<SequenceI> unmapped = new ArrayList<SequenceI>();
     Map<Integer, Map<SequenceI, Character>> columnMap = buildMappedColumnsMap(
             unaligned, aligned, unmapped);
     int width = columnMap.size();
     char gap = unaligned.getGapCharacter();
     int realignedCount = 0;
+    // TODO: verify this loop scales sensibly for very wide/high alignments
 
     for (SequenceI seq : unaligned.getSequences())
     {
       if (!unmapped.contains(seq))
       {
         char[] newSeq = new char[width];
-        Arrays.fill(newSeq, gap);
+        Arrays.fill(newSeq, gap); // JBPComment - doubt this is faster than the
+                                  // Integer iteration below
         int newCol = 0;
         int lastCol = 0;
 
@@ -2226,6 +2615,7 @@ public class AlignmentUtils
           System.arraycopy(newSeq, 0, tmp, 0, lastCol + 1);
           newSeq = tmp;
         }
+        // TODO: optimise SequenceI to avoid char[]->String->char[]
         seq.setSequence(String.valueOf(newSeq));
         realignedCount++;
       }
@@ -2234,6 +2624,72 @@ public class AlignmentUtils
   }
 
   /**
+   * If unaligned and aligned sequences share the same dataset sequences, then
+   * simply copies the aligned sequences to the unaligned sequences and returns
+   * true; else returns false
+   * 
+   * @param unaligned
+   *          - sequences to be aligned based on aligned
+   * @param aligned
+   *          - 'guide' alignment containing sequences derived from same dataset
+   *          as unaligned
+   * @return
+   */
+  static boolean alignAsSameSequences(AlignmentI unaligned,
+          AlignmentI aligned)
+  {
+    if (aligned.getDataset() == null || unaligned.getDataset() == null)
+    {
+      return false; // should only pass alignments with datasets here
+    }
+
+    // map from dataset sequence to alignment sequence(s)
+    Map<SequenceI, List<SequenceI>> alignedDatasets = new HashMap<SequenceI, List<SequenceI>>();
+    for (SequenceI seq : aligned.getSequences())
+    {
+      SequenceI ds = seq.getDatasetSequence();
+      if (alignedDatasets.get(ds) == null)
+      {
+        alignedDatasets.put(ds, new ArrayList<SequenceI>());
+      }
+      alignedDatasets.get(ds).add(seq);
+    }
+
+    /*
+     * first pass - check whether all sequences to be aligned share a dataset
+     * sequence with an aligned sequence
+     */
+    for (SequenceI seq : unaligned.getSequences())
+    {
+      if (!alignedDatasets.containsKey(seq.getDatasetSequence()))
+      {
+        return false;
+      }
+    }
+
+    /*
+     * second pass - copy aligned sequences;
+     * heuristic rule: pair off sequences in order for the case where 
+     * more than one shares the same dataset sequence 
+     */
+    for (SequenceI seq : unaligned.getSequences())
+    {
+      List<SequenceI> alignedSequences = alignedDatasets.get(seq
+              .getDatasetSequence());
+      // TODO: getSequenceAsString() will be deprecated in the future
+      // TODO: need to leave to SequenceI implementor to update gaps
+      seq.setSequence(alignedSequences.get(0).getSequenceAsString());
+      if (alignedSequences.size() > 0)
+      {
+        // pop off aligned sequences (except the last one)
+        alignedSequences.remove(0);
+      }
+    }
+
+    return true;
+  }
+
+  /**
    * Returns a map whose key is alignment column number (base 1), and whose
    * values are a map of sequence characters in that column.
    * 
@@ -2247,13 +2703,13 @@ public class AlignmentUtils
   {
     /*
      * Map will hold, for each aligned column position, a map of
-     * {unalignedSequence, sequenceCharacter} at that position.
+     * {unalignedSequence, characterPerSequence} at that position.
      * TreeMap keeps the entries in ascending column order. 
      */
     Map<Integer, Map<SequenceI, Character>> map = new TreeMap<Integer, Map<SequenceI, Character>>();
 
     /*
-     * r any sequences that have no mapping so can't be realigned
+     * record any sequences that have no mapping so can't be realigned
      */
     unmapped.addAll(unaligned.getSequences());
 
@@ -2302,6 +2758,15 @@ public class AlignmentUtils
       return false;
     }
 
+    /*
+     * invert mapping if it is from unaligned to aligned sequence
+     */
+    if (seqMap.getTo() == fromSeq.getDatasetSequence())
+    {
+      seqMap = new Mapping(seq.getDatasetSequence(), seqMap.getMap()
+              .getInverse());
+    }
+
     char[] fromChars = fromSeq.getSequence();
     int toStart = seq.getStart();
     char[] toChars = seq.getSequence();
@@ -2335,7 +2800,8 @@ public class AlignmentUtils
          * of the next character of the mapped-to sequence; stop when all
          * the characters of the range have been counted
          */
-        while (mappedCharPos <= range[1])
+        while (mappedCharPos <= range[1] && fromCol <= fromChars.length
+                && fromCol >= 0)
         {
           if (!Comparison.isGap(fromChars[fromCol - 1]))
           {
index 7b3ce25..21d990c 100755 (executable)
@@ -693,7 +693,7 @@ public class Conservation
       qmax = qualityRange[1].floatValue();
     }
 
-    for (int i = 0; i < alWidth; i++)
+    for (int i = istart; i < alWidth; i++)
     {
       float value = 0;
 
index 7e77fc1..288d60e 100644 (file)
@@ -24,23 +24,21 @@ import jalview.datamodel.AlignedCodonFrame;
 import jalview.datamodel.Alignment;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.DBRefEntry;
-import jalview.datamodel.DBRefSource;
 import jalview.datamodel.Mapping;
 import jalview.datamodel.Sequence;
 import jalview.datamodel.SequenceFeature;
 import jalview.datamodel.SequenceI;
 import jalview.util.DBRefUtils;
 import jalview.util.MapList;
-import jalview.ws.SequenceFetcher;
+import jalview.ws.SequenceFetcherFactory;
 import jalview.ws.seqfetcher.ASequenceFetcher;
 
 import java.util.ArrayList;
+import java.util.Iterator;
 import java.util.List;
-import java.util.Vector;
 
 /**
- * Functions for cross-referencing sequence databases. user must first specify
- * if cross-referencing from protein or dna (set dna==true)
+ * Functions for cross-referencing sequence databases.
  * 
  * @author JimP
  * 
@@ -48,195 +46,173 @@ import java.util.Vector;
 public class CrossRef
 {
   /*
-   * A sub-class that ignores Parent attribute when comparing sequence 
-   * features. This avoids 'duplicate' CDS features that only
-   * differ in their parent Transcript ids.
+   * the dataset of the alignment for which we are searching for 
+   * cross-references; in some cases we may resolve xrefs by 
+   * searching in the dataset
    */
-  class MySequenceFeature extends SequenceFeature
-  {
-    private SequenceFeature feat;
+  private AlignmentI dataset;
 
-    MySequenceFeature(SequenceFeature sf)
-    {
-      this.feat = sf;
-    }
+  /*
+   * the sequences for which we are seeking cross-references
+   */
+  private SequenceI[] fromSeqs;
 
-    @Override
-    public boolean equals(Object o)
-    {
-      return feat.equals(o, true);
-    }
-  }
+  /**
+   * matcher built from dataset
+   */
+  SequenceIdMatcher matcher;
 
   /**
-   * Select just the DNA or protein references for a protein or dna sequence
-   * 
-   * @param fromDna
-   *          if true, select references from DNA (i.e. Protein databases), else
-   *          DNA database references
-   * @param refs
-   *          a set of references to select from
-   * @return
+   * sequences found by cross-ref searches to fromSeqs
    */
-  public static DBRefEntry[] findXDbRefs(boolean fromDna, DBRefEntry[] refs)
-  {
-    return DBRefUtils.selectRefs(refs, fromDna ? DBRefSource.PROTEINDBS
-            : DBRefSource.DNACODINGDBS);
-    // could attempt to find other cross
-    // refs here - ie PDB xrefs
-    // (not dna, not protein seq)
-  }
+  List<SequenceI> rseqs;
 
   /**
-   * @param dna
-   *          true if seqs are DNA seqs
+   * Constructor
+   * 
    * @param seqs
-   * @return a list of sequence database cross reference source types
+   *          the sequences for which we are seeking cross-references
+   * @param ds
+   *          the containing alignment dataset (may be searched to resolve
+   *          cross-references)
    */
-  public static String[] findSequenceXrefTypes(boolean dna, SequenceI[] seqs)
+  public CrossRef(SequenceI[] seqs, AlignmentI ds)
   {
-    return findSequenceXrefTypes(dna, seqs, null);
+    fromSeqs = seqs;
+    dataset = ds.getDataset() == null ? ds : ds.getDataset();
   }
 
   /**
-   * Indirect references are references from other sequences from the dataset to
-   * any of the direct DBRefEntrys on the given sequences.
+   * Returns a list of distinct database sources for which sequences have either
+   * <ul>
+   * <li>a (dna-to-protein or protein-to-dna) cross-reference</li>
+   * <li>an indirect cross-reference - a (dna-to-protein or protein-to-dna)
+   * reference from another sequence in the dataset which has a cross-reference
+   * to a direct DBRefEntry on the given sequence</li>
+   * </ul>
    * 
    * @param dna
-   *          true if seqs are DNA seqs
-   * @param seqs
-   * @return a list of sequence database cross reference source types
+   *          - when true, cross-references *from* dna returned. When false,
+   *          cross-references *from* protein are returned
+   * @return
    */
-  public static String[] findSequenceXrefTypes(boolean dna,
-          SequenceI[] seqs, AlignmentI dataset)
+  public List<String> findXrefSourcesForSequences(boolean dna)
   {
-    String[] dbrefs = null;
-    List<String> refs = new ArrayList<String>();
-    for (SequenceI seq : seqs)
+    List<String> sources = new ArrayList<String>();
+    for (SequenceI seq : fromSeqs)
     {
       if (seq != null)
       {
-        SequenceI dss = seq;
-        while (dss.getDatasetSequence() != null)
-        {
-          dss = dss.getDatasetSequence();
-        }
-        DBRefEntry[] rfs = findXDbRefs(dna, dss.getDBRefs());
-        if (rfs != null)
-        {
-          for (DBRefEntry ref : rfs)
-          {
-            if (!refs.contains(ref.getSource()))
-            {
-              refs.add(ref.getSource());
-            }
-          }
-        }
-        if (dataset != null)
-        {
-          // search for references to this sequence's direct references.
-          DBRefEntry[] lrfs = CrossRef.findXDbRefs(!dna, seq.getDBRefs());
-          List<SequenceI> rseqs = new ArrayList<SequenceI>();
-          CrossRef.searchDatasetXrefs(seq, !dna, lrfs, dataset, rseqs,
-                  null); // don't need to specify codon frame for mapping here
-          for (SequenceI rs : rseqs)
-          {
-            DBRefEntry[] xrs = findXDbRefs(dna, rs.getDBRefs());
-            if (xrs != null)
-            {
-              for (DBRefEntry ref : xrs)
-              {
-                if (!refs.contains(ref.getSource()))
-                {
-                  refs.add(ref.getSource());
-                }
-              }
-            }
-            // looks like copy and paste - change rfs to xrs?
-            // for (int r = 0; rfs != null && r < rfs.length; r++)
-            // {
-            // if (!refs.contains(rfs[r].getSource()))
-            // {
-            // refs.add(rfs[r].getSource());
-            // }
-            // }
-          }
-        }
+        findXrefSourcesForSequence(seq, dna, sources);
       }
     }
-    if (refs.size() > 0)
-    {
-      dbrefs = new String[refs.size()];
-      refs.toArray(dbrefs);
-    }
-    return dbrefs;
+    return sources;
   }
 
-  public static boolean hasCdnaMap(SequenceI[] seqs)
+  /**
+   * Returns a list of distinct database sources for which a sequence has either
+   * <ul>
+   * <li>a (dna-to-protein or protein-to-dna) cross-reference</li>
+   * <li>an indirect cross-reference - a (dna-to-protein or protein-to-dna)
+   * reference from another sequence in the dataset which has a cross-reference
+   * to a direct DBRefEntry on the given sequence</li>
+   * </ul>
+   * 
+   * @param seq
+   *          the sequence whose dbrefs we are searching against
+   * @param fromDna
+   *          when true, context is DNA - so sources identifying protein
+   *          products will be returned.
+   * @param sources
+   *          a list of sources to add matches to
+   */
+  void findXrefSourcesForSequence(SequenceI seq, boolean fromDna,
+          List<String> sources)
   {
-    // TODO unused - remove?
-    String[] reftypes = findSequenceXrefTypes(false, seqs);
-    for (int s = 0; s < reftypes.length; s++)
+    /*
+     * first find seq's xrefs (dna-to-peptide or peptide-to-dna)
+     */
+    DBRefEntry[] rfs = DBRefUtils.selectDbRefs(!fromDna, seq.getDBRefs());
+    addXrefsToSources(rfs, sources);
+    if (dataset != null)
     {
-      if (reftypes.equals(DBRefSource.EMBLCDS))
+      /*
+       * find sequence's direct (dna-to-dna, peptide-to-peptide) xrefs
+       */
+      DBRefEntry[] lrfs = DBRefUtils.selectDbRefs(fromDna, seq.getDBRefs());
+      List<SequenceI> foundSeqs = new ArrayList<SequenceI>();
+
+      /*
+       * find sequences in the alignment which xref one of these DBRefs
+       * i.e. is xref-ed to a common sequence identifier
+       */
+      searchDatasetXrefs(fromDna, seq, lrfs, foundSeqs, null);
+
+      /*
+       * add those sequences' (dna-to-peptide or peptide-to-dna) dbref sources
+       */
+      for (SequenceI rs : foundSeqs)
       {
-        return true;
-        // no map
+        DBRefEntry[] xrs = DBRefUtils
+                .selectDbRefs(!fromDna, rs.getDBRefs());
+        addXrefsToSources(xrs, sources);
       }
     }
-    return false;
   }
 
-  public static SequenceI[] getCdnaMap(SequenceI[] seqs)
+  /**
+   * Helper method that adds the source identifiers of some cross-references to
+   * a (non-redundant) list of database sources
+   * 
+   * @param xrefs
+   * @param sources
+   */
+  void addXrefsToSources(DBRefEntry[] xrefs, List<String> sources)
   {
-    // TODO unused - remove?
-    Vector cseqs = new Vector();
-    for (int s = 0; s < seqs.length; s++)
+    if (xrefs != null)
     {
-      DBRefEntry[] cdna = findXDbRefs(true, seqs[s].getDBRefs());
-      for (int c = 0; c < cdna.length; c++)
+      for (DBRefEntry ref : xrefs)
       {
-        if (cdna[c].getSource().equals(DBRefSource.EMBLCDS))
+        /*
+         * avoid duplication e.g. ENSEMBL and Ensembl
+         */
+        String source = DBRefUtils.getCanonicalName(ref.getSource());
+        if (!sources.contains(source))
         {
-          System.err
-                  .println("TODO: unimplemented sequence retrieval for coding region sequence.");
-          // TODO: retrieve CDS dataset sequences
-          // need global dataset sequence retriever/resolver to reuse refs
-          // and construct Mapping entry.
-          // insert gaps in CDS according to peptide gaps.
-          // add gapped sequence to cseqs
+          sources.add(source);
         }
       }
     }
-    if (cseqs.size() > 0)
-    {
-      SequenceI[] rsqs = new SequenceI[cseqs.size()];
-      cseqs.copyInto(rsqs);
-      return rsqs;
-    }
-    return null;
-
   }
 
   /**
+   * Attempts to find cross-references from the sequences provided in the
+   * constructor to the given source database. Cross-references may be found
+   * <ul>
+   * <li>in dbrefs on the sequence which hold a mapping to a sequence
+   * <ul>
+   * <li>provided with a fetched sequence (e.g. ENA translation), or</li>
+   * <li>populated previously after getting cross-references</li>
+   * </ul>
+   * <li>as other sequences in the alignment which share a dbref identifier with
+   * the sequence</li>
+   * <li>by fetching from the remote database</li>
+   * </ul>
+   * The cross-referenced sequences, and mappings to them, are added to the
+   * alignment dataset.
    * 
-   * @param seqs
-   *          sequences whose xrefs are being retrieved
-   * @param dna
-   *          true if sequences are nucleotide
    * @param source
-   * @param al
-   *          alignment to search for cross-referenced sequences (and possibly
-   *          add to)
-   * @return products (as dataset sequences)
+   * @return cross-referenced sequences (as dataset sequences)
    */
-  public static Alignment findXrefSequences(SequenceI[] seqs,
-          final boolean dna, final String source, AlignmentI al)
+  public Alignment findXrefSequences(String source, boolean fromDna)
   {
-    AlignmentI dataset = al.getDataset() == null ? al : al.getDataset();
-    List<SequenceI> rseqs = new ArrayList<SequenceI>();
+
+    rseqs = new ArrayList<SequenceI>();
     AlignedCodonFrame cf = new AlignedCodonFrame();
-    for (SequenceI seq : seqs)
+    matcher = new SequenceIdMatcher(
+            dataset.getSequences());
+
+    for (SequenceI seq : fromSeqs)
     {
       SequenceI dss = seq;
       while (dss.getDatasetSequence() != null)
@@ -244,242 +220,389 @@ public class CrossRef
         dss = dss.getDatasetSequence();
       }
       boolean found = false;
-      DBRefEntry[] xrfs = CrossRef.findXDbRefs(dna, dss.getDBRefs());
+      DBRefEntry[] xrfs = DBRefUtils
+              .selectDbRefs(!fromDna, dss.getDBRefs());
       if ((xrfs == null || xrfs.length == 0) && dataset != null)
       {
-        System.out.println("Attempting to find ds Xrefs refs.");
-        // FIXME should be dss not seq here?
-        DBRefEntry[] lrfs = CrossRef.findXDbRefs(!dna, seq.getDBRefs());
-        // less ambiguous would be a 'find primary dbRefEntry' method.
-        // filter for desired source xref here
-        found = CrossRef.searchDatasetXrefs(dss, !dna, lrfs, dataset,
-                rseqs, cf);
+        /*
+         * found no suitable dbrefs on sequence - look for sequences in the
+         * alignment which share a dbref with this one
+         */
+        DBRefEntry[] lrfs = DBRefUtils.selectDbRefs(fromDna,
+                seq.getDBRefs());
+
+        /*
+         * find sequences (except this one!), of complementary type,
+         *  which have a dbref to an accession id for this sequence,
+         *  and add them to the results
+         */
+        found = searchDatasetXrefs(fromDna, dss, lrfs, rseqs, cf);
       }
-      for (int r = 0; xrfs != null && r < xrfs.length; r++)
+      if (xrfs == null && !found)
       {
-        DBRefEntry xref = xrfs[r];
-        if (source != null && !source.equals(xref.getSource()))
-        {
-          continue;
-        }
+        /*
+         * no dbref to source on this sequence or matched
+         * complementary sequence in the dataset 
+         */
+        continue;
+      }
+      List<DBRefEntry> sourceRefs = DBRefUtils.searchRefsForSource(xrfs,
+              source);
+      Iterator<DBRefEntry> refIterator = sourceRefs.iterator();
+      while (refIterator.hasNext())
+      {
+        DBRefEntry xref = refIterator.next();
+        found = false;
         if (xref.hasMap())
         {
-          if (xref.getMap().getTo() != null)
+          SequenceI mappedTo = xref.getMap().getTo();
+          if (mappedTo != null)
           {
-            SequenceI rsq = new Sequence(xref.getMap().getTo());
+            /*
+             * dbref contains the sequence it maps to; add it to the
+             * results unless we have done so already (could happen if 
+             * fetching xrefs for sequences which have xrefs in common)
+             * for example: UNIPROT {P0CE19, P0CE20} -> EMBL {J03321, X06707}
+             */
+            found = true;
+            /*
+             * problem: matcher.findIdMatch() is lenient - returns a sequence
+             * with a dbref to the search arg e.g. ENST for ENSP - wrong
+             * but findInDataset() matches ENSP when looking for Uniprot...
+             */
+            SequenceI matchInDataset = findInDataset(xref);
+            /*matcher.findIdMatch(mappedTo);*/
+            if (matchInDataset != null)
+            {
+              if (!rseqs.contains(matchInDataset))
+              {
+                rseqs.add(matchInDataset);
+              }
+              refIterator.remove();
+              continue;
+            }
+            SequenceI rsq = new Sequence(mappedTo);
             rseqs.add(rsq);
-            if (xref.getMap().getMap().getFromRatio() != xref
-                    .getMap().getMap().getToRatio())
+            if (xref.getMap().getMap().getFromRatio() != xref.getMap()
+                    .getMap().getToRatio())
             {
               // get sense of map correct for adding to product alignment.
-              if (dna)
+              if (fromDna)
               {
                 // map is from dna seq to a protein product
-                cf.addMap(dss, rsq, xref.getMap().getMap());
+                cf.addMap(dss, rsq, xref.getMap().getMap(), xref.getMap()
+                        .getMappedFromId());
               }
               else
               {
                 // map should be from protein seq to its coding dna
-                cf.addMap(rsq, dss, xref.getMap().getMap().getInverse());
+                cf.addMap(rsq, dss, xref.getMap().getMap().getInverse(),
+                        xref.getMap().getMappedFromId());
               }
             }
-            found = true;
           }
         }
+
         if (!found)
         {
-          // do a bit more work - search for sequences with references matching
-          // xrefs on this sequence.
-          if (dataset != null)
+          SequenceI matchedSeq = matcher.findIdMatch(xref.getSource() + "|"
+                  + xref.getAccessionId());
+          if (matchedSeq != null)
           {
-            found |= searchDataset(dss, xref, dataset, rseqs, cf, false,
-                    !dna);
-            if (found)
+            if (constructMapping(seq, matchedSeq, xref, cf, fromDna))
             {
-              xrfs[r] = null; // we've recovered seqs for this one.
+              found = true;
             }
           }
         }
+
+        if (!found)
+        {
+          // do a bit more work - search for sequences with references matching
+          // xrefs on this sequence.
+          found = searchDataset(fromDna, dss, xref, rseqs, cf, false);
+        }
+        if (found)
+        {
+          refIterator.remove();
+        }
+      }
+
+      /*
+       * fetch from source database any dbrefs we haven't resolved up to here
+       */
+      if (!sourceRefs.isEmpty())
+      {
+        retrieveCrossRef(sourceRefs, seq, xrfs, fromDna, cf);
+      }
+    }
+
+    Alignment ral = null;
+    if (rseqs.size() > 0)
+    {
+      ral = new Alignment(rseqs.toArray(new SequenceI[rseqs.size()]));
+      if (!cf.isEmpty())
+      {
+        dataset.addCodonFrame(cf);
       }
-      if (!found)
+    }
+    return ral;
+  }
+
+  private void retrieveCrossRef(List<DBRefEntry> sourceRefs, SequenceI seq,
+          DBRefEntry[] xrfs, boolean fromDna, AlignedCodonFrame cf)
+  {
+    ASequenceFetcher sftch = SequenceFetcherFactory.getSequenceFetcher();
+    SequenceI[] retrieved = null;
+    SequenceI dss = seq.getDatasetSequence() == null ? seq : seq
+            .getDatasetSequence();
+    try
+    {
+      retrieved = sftch.getSequences(sourceRefs, !fromDna);
+    } catch (Exception e)
+    {
+      System.err
+              .println("Problem whilst retrieving cross references for Sequence : "
+                      + seq.getName());
+      e.printStackTrace();
+    }
+
+    if (retrieved != null)
+    {
+      updateDbrefMappings(seq, xrfs, retrieved, cf, fromDna);
+      for (SequenceI retrievedSequence : retrieved)
       {
-        if (xrfs != null && xrfs.length > 0)
+        // dataset gets contaminated ccwith non-ds sequences. why ??!
+        // try: Ensembl -> Nuc->Ensembl, Nuc->Uniprot-->Protein->EMBL->
+        SequenceI retrievedDss = retrievedSequence.getDatasetSequence() == null ? retrievedSequence
+                : retrievedSequence.getDatasetSequence();
+        DBRefEntry[] dbr = retrievedSequence.getDBRefs();
+        if (dbr != null)
         {
-          // Try and get the sequence reference...
-          /*
-           * Ideal world - we ask for a sequence fetcher implementation here if
-           * (jalview.io.RunTimeEnvironment.getSequenceFetcher()) (
-           */
-          ASequenceFetcher sftch = new SequenceFetcher();
-          SequenceI[] retrieved = null;
-          int l = xrfs.length;
-          for (int r = 0; r < xrfs.length; r++)
-          {
-            // filter out any irrelevant or irretrievable references
-            if (xrfs[r] == null
-                    || ((source != null && !source.equals(xrfs[r]
-                            .getSource())) || !sftch.isFetchable(xrfs[r]
-                            .getSource())))
-            {
-              l--;
-              xrfs[r] = null;
-            }
-          }
-          if (l > 0)
+          for (DBRefEntry dbref : dbr)
           {
-            // System.out
-            // .println("Attempting to retrieve cross referenced sequences.");
-            DBRefEntry[] t = new DBRefEntry[l];
-            l = 0;
-            for (int r = 0; r < xrfs.length; r++)
+            // find any entry where we should put in the sequence being
+            // cross-referenced into the map
+            Mapping map = dbref.getMap();
+            if (map != null)
             {
-              if (xrfs[r] != null)
+              if (map.getTo() != null && map.getMap() != null)
               {
-                t[l++] = xrfs[r];
-              }
-            }
-            xrfs = t;
-            try
-            {
-              retrieved = sftch.getSequences(xrfs, !dna);
-              // problem here is we don't know which of xrfs resulted in which
-              // retrieved element
-            } catch (Exception e)
-            {
-              System.err
-                      .println("Problem whilst retrieving cross references for Sequence : "
-                              + seq.getName());
-              e.printStackTrace();
-            }
-
-            if (retrieved != null)
-            {
-              updateDbrefMappings(dna, seq, xrfs, retrieved, cf);
-
-              SequenceIdMatcher matcher = new SequenceIdMatcher(
-                      dataset.getSequences());
-              List<SequenceFeature> copiedFeatures = new ArrayList<SequenceFeature>();
-              CrossRef me = new CrossRef();
-              for (int rs = 0; rs < retrieved.length; rs++)
-              {
-                // TODO: examine each sequence for 'redundancy'
-                DBRefEntry[] dbr = retrieved[rs].getDBRefs();
-                if (dbr != null && dbr.length > 0)
+                // TODO findInDataset requires exact sequence match but
+                // 'congruent' test is only for the mapped part
+                // maybe not a problem in practice since only ENA provide a
+                // mapping and it is to the full protein translation of CDS
+                SequenceI matched = findInDataset(dbref);
+                // matcher.findIdMatch(map.getTo());
+                if (matched != null)
                 {
-                  for (int di = 0; di < dbr.length; di++)
+                  /*
+                   * already got an xref to this sequence; update this
+                   * map to point to the same sequence, and add
+                   * any new dbrefs to it
+                   */
+                  DBRefEntry[] toRefs = map.getTo().getDBRefs();
+                  if (toRefs != null)
                   {
-                    // find any entry where we should put in the sequence being
-                    // cross-referenced into the map
-                    Mapping map = dbr[di].getMap();
-                    if (map != null)
+                    for (DBRefEntry ref : toRefs)
                     {
-                      if (map.getTo() != null && map.getMap() != null)
+                      matched.addDBRef(ref); // add or update mapping
+                    }
+                  }
+                  map.setTo(matched);
+                }
+                else
+                {
+                  matcher.add(map.getTo());
+                }
+                try
+                {
+                  // compare ms with dss and replace with dss in mapping
+                  // if map is congruent
+                  SequenceI ms = map.getTo();
+                  int sf = map.getMap().getToLowest();
+                  int st = map.getMap().getToHighest();
+                  SequenceI mappedrg = ms.getSubSequence(sf, st);
+                  // SequenceI loc = dss.getSubSequence(sf, st);
+                  if (mappedrg.getLength() > 0
+                          && ms.getSequenceAsString().equals(
+                                  dss.getSequenceAsString()))
+                  // && mappedrg.getSequenceAsString().equals(
+                  // loc.getSequenceAsString()))
+                  {
+                    String msg = "Mapping updated from " + ms.getName()
+                            + " to retrieved crossreference "
+                            + dss.getName();
+                    System.out.println(msg);
+                    map.setTo(dss);
+
+                    /*
+                     * give the reverse reference the inverse mapping 
+                     * (if it doesn't have one already)
+                     */
+                    setReverseMapping(dss, dbref, cf);
+
+                    /*
+                     * copy sequence features as well, avoiding
+                     * duplication (e.g. same variation from two 
+                     * transcripts)
+                     */
+                    SequenceFeature[] sfs = ms.getSequenceFeatures();
+                    if (sfs != null)
+                    {
+                      for (SequenceFeature feat : sfs)
                       {
-                        SequenceI matched = matcher
-                                .findIdMatch(map.getTo());
-                        if (matched != null)
-                        {
-                          /*
-                           * already got an xref to this sequence; update this
-                           * map to point to the same sequence, and add
-                           * any new dbrefs to it
-                           */
-                          for (DBRefEntry ref : map.getTo().getDBRefs())
-                          {
-                            matched.addDBRef(ref); // add or update mapping
-                          }
-                          map.setTo(matched);
-                        }
-                        else
+                        /*
+                         * make a flyweight feature object which ignores Parent
+                         * attribute in equality test; this avoids creating many
+                         * otherwise duplicate exon features on genomic sequence
+                         */
+                        SequenceFeature newFeature = new SequenceFeature(
+                                feat)
                         {
-                          matcher.add(map.getTo());
-                        }
-                        try
-                        {
-                          // compare ms with dss and replace with dss in mapping
-                          // if map is congruent
-                          SequenceI ms = map.getTo();
-                          int sf = map.getMap().getToLowest();
-                          int st = map.getMap().getToHighest();
-                          SequenceI mappedrg = ms.getSubSequence(sf, st);
-                          // SequenceI loc = dss.getSubSequence(sf, st);
-                          if (mappedrg.getLength() > 0
-                                  && ms.getSequenceAsString().equals(
-                                          dss.getSequenceAsString()))
-                          // && mappedrg.getSequenceAsString().equals(
-                          // loc.getSequenceAsString()))
-                          {
-                            String msg = "Mapping updated from "
-                                    + ms.getName()
-                                    + " to retrieved crossreference "
-                                    + dss.getName();
-                            System.out.println(msg);
-                            // method to update all refs of existing To on
-                            // retrieved sequence with dss and merge any props
-                            // on To onto dss.
-                            map.setTo(dss);
-                            /*
-                             * copy sequence features as well, avoiding
-                             * duplication (e.g. same variation from 2 
-                             * transcripts)
-                             */
-                            SequenceFeature[] sfs = ms
-                                    .getSequenceFeatures();
-                            if (sfs != null)
-                            {
-                              for (SequenceFeature feat : sfs)
-                              {
-                                /* 
-                                 * we override SequenceFeature.equals here (but
-                                 * not elsewhere) to ignore Parent attribute
-                                 * TODO not quite working yet!
-                                 */
-                                if (!copiedFeatures
-                                        .contains(me.new MySequenceFeature(
-                                                feat)))
-                                {
-                                  dss.addSequenceFeature(feat);
-                                  copiedFeatures.add(feat);
-                                }
-                              }
-                            }
-                            cf.addMap(retrieved[rs].getDatasetSequence(),
-                                    dss, map.getMap());
-                          }
-                          else
+                          @Override
+                          public boolean equals(Object o)
                           {
-                            cf.addMap(retrieved[rs].getDatasetSequence(),
-                                    map.getTo(), map.getMap());
+                            return super.equals(o, true);
                           }
-                        } catch (Exception e)
-                        {
-                          System.err
-                                  .println("Exception when consolidating Mapped sequence set...");
-                          e.printStackTrace(System.err);
-                        }
+                        };
+                        dss.addSequenceFeature(newFeature);
                       }
                     }
                   }
+                  cf.addMap(retrievedDss, map.getTo(), map.getMap());
+                } catch (Exception e)
+                {
+                  System.err
+                          .println("Exception when consolidating Mapped sequence set...");
+                  e.printStackTrace(System.err);
                 }
-                retrieved[rs].updatePDBIds();
-                rseqs.add(retrieved[rs]);
               }
             }
           }
         }
+        retrievedSequence.updatePDBIds();
+        rseqs.add(retrievedDss);
+        dataset.addSequence(retrievedDss);
+        matcher.add(retrievedDss);
+      }
+    }
+  }
+  /**
+   * Sets the inverse sequence mapping in the corresponding dbref of the mapped
+   * to sequence (if any). This is used after fetching a cross-referenced
+   * sequence, if the fetched sequence has a mapping to the original sequence,
+   * to set the mapping in the original sequence's dbref.
+   * 
+   * @param mapFrom
+   *          the sequence mapped from
+   * @param dbref
+   * @param mappings
+   */
+  void setReverseMapping(SequenceI mapFrom, DBRefEntry dbref,
+          AlignedCodonFrame mappings)
+  {
+    SequenceI mapTo = dbref.getMap().getTo();
+    if (mapTo == null)
+    {
+      return;
+    }
+    DBRefEntry[] dbrefs = mapTo.getDBRefs();
+    if (dbrefs == null)
+    {
+      return;
+    }
+    for (DBRefEntry toRef : dbrefs)
+    {
+      if (toRef.hasMap() && mapFrom == toRef.getMap().getTo())
+      {
+        /*
+         * found the reverse dbref; update its mapping if null
+         */
+        if (toRef.getMap().getMap() == null)
+        {
+          MapList inverse = dbref.getMap().getMap().getInverse();
+          toRef.getMap().setMap(inverse);
+          mappings.addMap(mapTo, mapFrom, inverse);
+        }
       }
     }
+  }
 
-    Alignment ral = null;
-    if (rseqs.size() > 0)
+  /**
+   * Returns the first identical sequence in the dataset if any, else null
+   * 
+   * @param xref
+   * @return
+   */
+  SequenceI findInDataset(DBRefEntry xref)
+  {
+    if (xref == null || !xref.hasMap() || xref.getMap().getTo() == null)
     {
-      ral = new Alignment(rseqs.toArray(new SequenceI[rseqs.size()]));
-      if (cf != null && !cf.isEmpty())
+      return null;
+    }
+    SequenceI mapsTo = xref.getMap().getTo();
+    String name = xref.getAccessionId();
+    String name2 = xref.getSource() + "|" + name;
+    SequenceI dss = mapsTo.getDatasetSequence() == null ? mapsTo : mapsTo
+            .getDatasetSequence();
+    for (SequenceI seq : dataset.getSequences())
+    {
+      /*
+       * clumsy alternative to using SequenceIdMatcher which currently
+       * returns sequences with a dbref to the matched accession id 
+       * which we don't want
+       */
+      if (name.equals(seq.getName()) || seq.getName().startsWith(name2))
       {
-        ral.addCodonFrame(cf);
+        if (sameSequence(seq, dss))
+        {
+          return seq;
+        }
       }
     }
-    return ral;
+    return null;
+  }
+
+  /**
+   * Answers true if seq1 and seq2 contain exactly the same characters (ignoring
+   * case), else false. This method compares the lengths, then each character in
+   * turn, in order to 'fail fast'. For case-sensitive comparison, it would be
+   * possible to use Arrays.equals(seq1.getSequence(), seq2.getSequence()).
+   * 
+   * @param seq1
+   * @param seq2
+   * @return
+   */
+  // TODO move to Sequence / SequenceI
+  static boolean sameSequence(SequenceI seq1, SequenceI seq2)
+  {
+    if (seq1 == seq2)
+    {
+      return true;
+    }
+    if (seq1 == null || seq2 == null)
+    {
+      return false;
+    }
+    char[] c1 = seq1.getSequence();
+    char[] c2 = seq2.getSequence();
+    if (c1.length != c2.length)
+    {
+      return false;
+    }
+    for (int i = 0; i < c1.length; i++)
+    {
+      int diff = c1[i] - c2[i];
+      /*
+       * same char or differ in case only ('a'-'A' == 32)
+       */
+      if (diff != 0 && diff != 32 && diff != -32)
+      {
+        return false;
+      }
+    }
+    return true;
   }
 
   /**
@@ -487,62 +610,123 @@ public class CrossRef
    * retrieved sequence if found, and adds any new mappings to the
    * AlignedCodonFrame
    * 
-   * @param dna
    * @param mapFrom
    * @param xrefs
    * @param retrieved
    * @param acf
    */
-  static void updateDbrefMappings(boolean dna, SequenceI mapFrom,
-          DBRefEntry[] xrefs, SequenceI[] retrieved, AlignedCodonFrame acf)
+  void updateDbrefMappings(SequenceI mapFrom, DBRefEntry[] xrefs,
+          SequenceI[] retrieved, AlignedCodonFrame acf, boolean fromDna)
   {
-    SequenceIdMatcher matcher = new SequenceIdMatcher(retrieved);
+    SequenceIdMatcher idMatcher = new SequenceIdMatcher(retrieved);
     for (DBRefEntry xref : xrefs)
     {
       if (!xref.hasMap())
       {
         String targetSeqName = xref.getSource() + "|"
                 + xref.getAccessionId();
-        SequenceI[] matches = matcher.findAllIdMatches(targetSeqName);
+        SequenceI[] matches = idMatcher.findAllIdMatches(targetSeqName);
         if (matches == null)
         {
           return;
         }
         for (SequenceI seq : matches)
         {
-          MapList mapping = null;
-          if (dna)
-          {
-            mapping = AlignmentUtils.mapCdnaToProtein(seq, mapFrom);
-          }
-          else
-          {
-            mapping = AlignmentUtils.mapCdnaToProtein(mapFrom, seq);
-            if (mapping != null)
-            {
-              mapping = mapping.getInverse();
-            }
-          }
-          if (mapping != null)
-          {
-            xref.setMap(new Mapping(seq, mapping));
-            if (dna)
-            {
-              AlignmentUtils.computeProteinFeatures(mapFrom, seq, mapping);
-            }
-            if (dna)
-            {
-              acf.addMap(mapFrom, seq, mapping);
-            }
-            else
-            {
-              acf.addMap(seq, mapFrom, mapping.getInverse());
-            }
-            continue;
-          }
+          constructMapping(mapFrom, seq, xref, acf, fromDna);
+        }
+      }
+    }
+  }
+
+  /**
+   * Tries to make a mapping between sequences. If successful, adds the mapping
+   * to the dbref and the mappings collection and answers true, otherwise
+   * answers false. The following methods of making are mapping are tried in
+   * turn:
+   * <ul>
+   * <li>if 'mapTo' holds a mapping to 'mapFrom', take the inverse; this is, for
+   * example, the case after fetching EMBL cross-references for a Uniprot
+   * sequence</li>
+   * <li>else check if the dna translates exactly to the protein (give or take
+   * start and stop codons></li>
+   * <li>else try to map based on CDS features on the dna sequence</li>
+   * </ul>
+   * 
+   * @param mapFrom
+   * @param mapTo
+   * @param xref
+   * @param mappings
+   * @return
+   */
+  boolean constructMapping(SequenceI mapFrom, SequenceI mapTo,
+          DBRefEntry xref, AlignedCodonFrame mappings, boolean fromDna)
+  {
+    MapList mapping = null;
+
+    /*
+     * look for a reverse mapping, if found make its inverse
+     */
+    if (mapTo.getDBRefs() != null)
+    {
+      for (DBRefEntry dbref : mapTo.getDBRefs())
+      {
+        String name = dbref.getSource() + "|" + dbref.getAccessionId();
+        if (dbref.hasMap() && mapFrom.getName().startsWith(name))
+        {
+          /*
+           * looks like we've found a map from 'mapTo' to 'mapFrom'
+           * - invert it to make the mapping the other way 
+           */
+          MapList reverse = dbref.getMap().getMap().getInverse();
+          xref.setMap(new Mapping(mapTo, reverse));
+          mappings.addMap(mapFrom, mapTo, reverse);
+          return true;
         }
       }
     }
+
+    if (fromDna)
+    {
+      mapping = AlignmentUtils.mapCdnaToProtein(mapTo, mapFrom);
+    }
+    else
+    {
+      mapping = AlignmentUtils.mapCdnaToProtein(mapFrom, mapTo);
+      if (mapping != null)
+      {
+        mapping = mapping.getInverse();
+      }
+    }
+    if (mapping == null)
+    {
+      return false;
+    }
+    xref.setMap(new Mapping(mapTo, mapping));
+
+    /*
+     * and add a reverse DbRef with the inverse mapping
+     */
+    if (mapFrom.getDatasetSequence() != null
+            && mapFrom.getDatasetSequence().getSourceDBRef() != null)
+    {
+      DBRefEntry dbref = new DBRefEntry(mapFrom.getDatasetSequence()
+              .getSourceDBRef());
+      dbref.setMap(new Mapping(mapFrom.getDatasetSequence(), mapping
+              .getInverse()));
+      mapTo.addDBRef(dbref);
+    }
+
+    if (fromDna)
+    {
+      AlignmentUtils.computeProteinFeatures(mapFrom, mapTo, mapping);
+      mappings.addMap(mapFrom, mapTo, mapping);
+    }
+    else
+    {
+      mappings.addMap(mapTo, mapFrom, mapping.getInverse());
+    }
+
+    return true;
   }
 
   /**
@@ -550,15 +734,16 @@ public class CrossRef
    * dataset (that is not equal to sequenceI) Identifies matching DBRefEntry
    * based on source and accession string only - Map and Version are nulled.
    * 
+   * @param fromDna
+   *          - true if context was searching from Dna sequences, false if
+   *          context was searching from Protein sequences
    * @param sequenceI
    * @param lrfs
-   * @param dataset
-   * @param rseqs
+   * @param foundSeqs
    * @return true if matches were found.
    */
-  private static boolean searchDatasetXrefs(SequenceI sequenceI,
-          boolean dna, DBRefEntry[] lrfs, AlignmentI dataset,
-          List<SequenceI> rseqs, AlignedCodonFrame cf)
+  private boolean searchDatasetXrefs(boolean fromDna, SequenceI sequenceI,
+          DBRefEntry[] lrfs, List<SequenceI> foundSeqs, AlignedCodonFrame cf)
   {
     boolean found = false;
     if (lrfs == null)
@@ -571,50 +756,44 @@ public class CrossRef
       // add in wildcards
       xref.setVersion(null);
       xref.setMap(null);
-      found = searchDataset(sequenceI, xref, dataset, rseqs, cf, false, dna);
+      found |= searchDataset(fromDna, sequenceI, xref, foundSeqs, cf, false);
     }
     return found;
   }
 
   /**
-   * search a given sequence dataset for references matching cross-references to
-   * the given sequence
-   * 
-   * @param sequenceI
-   * @param xrf
-   * @param dataset
-   * @param rseqs
-   *          set of unique sequences
-   * @param cf
-   * @return true if one or more unique sequences were found and added
-   */
-  public static boolean searchDataset(SequenceI sequenceI, DBRefEntry xrf,
-          AlignmentI dataset, List<SequenceI> rseqs, AlignedCodonFrame cf)
-  {
-    return searchDataset(sequenceI, xrf, dataset, rseqs, cf, true, false);
-  }
-
-  /**
-   * TODO: generalise to different protein classifications Search dataset for
-   * DBRefEntrys matching the given one (xrf) and add the associated sequence to
-   * rseq.
+   * Searches dataset for DBRefEntrys matching the given one (xrf) and adds the
+   * associated sequence to rseqs
    * 
-   * @param sequenceI
+   * @param fromDna
+   *          true if context was searching for refs *from* dna sequence, false
+   *          if context was searching for refs *from* protein sequence
+   * @param fromSeq
+   *          a sequence to ignore (start point of search)
    * @param xrf
-   * @param dataset
-   * @param rseqs
+   *          a cross-reference to try to match
+   * @param foundSeqs
+   *          result list to add to
+   * @param mappings
+   *          a set of sequence mappings to add to
    * @param direct
-   *          - search all references or only subset
-   * @param dna
-   *          search dna or protein xrefs (if direct=false)
+   *          - indicates the type of relationship between returned sequences,
+   *          xrf, and sequenceI that is required.
+   *          <ul>
+   *          <li>direct implies xrf is a primary reference for sequenceI AND
+   *          the sequences to be located (eg a uniprot ID for a protein
+   *          sequence, and a uniprot ref on a transcript sequence).</li>
+   *          <li>indirect means xrf is a cross reference with respect to
+   *          sequenceI or all the returned sequences (eg a genomic reference
+   *          associated with a locus and one or more transcripts)</li>
+   *          </ul>
    * @return true if relationship found and sequence added.
    */
-  public static boolean searchDataset(SequenceI sequenceI, DBRefEntry xrf,
-          AlignmentI dataset, List<SequenceI> rseqs, AlignedCodonFrame cf,
-          boolean direct, boolean dna)
+  boolean searchDataset(boolean fromDna, SequenceI fromSeq,
+          DBRefEntry xrf, List<SequenceI> foundSeqs, AlignedCodonFrame mappings,
+          boolean direct)
   {
     boolean found = false;
-    SequenceI[] typer = new SequenceI[1];
     if (dataset == null)
     {
       return false;
@@ -634,107 +813,84 @@ public class CrossRef
           if (nxt.getDatasetSequence() != null)
           {
             System.err
-                    .println("Implementation warning: getProducts passed a dataset alignment without dataset sequences in it!");
+                    .println("Implementation warning: CrossRef initialised with a dataset alignment with non-dataset sequences in it! ("
+                            + nxt.getDisplayId(true)
+                            + " has ds reference "
+                            + nxt.getDatasetSequence().getDisplayId(true)
+                            + ")");
+          }
+          if (nxt == fromSeq || nxt == fromSeq.getDatasetSequence())
+          {
+            continue;
           }
-          if (nxt != sequenceI && nxt != sequenceI.getDatasetSequence())
+          /*
+           * only look at same molecule type if 'direct', or
+           * complementary type if !direct
+           */
           {
-            // check if this is the correct sequence type
+            boolean isDna = !nxt.isProtein();
+            if (direct ? (isDna != fromDna) : (isDna == fromDna))
             {
-              typer[0] = nxt;
-              boolean isDna = jalview.util.Comparison.isNucleotide(typer);
-              if ((direct && isDna == dna) || (!direct && isDna != dna))
-              {
-                // skip this sequence because it is same molecule type
-                continue;
-              }
+              // skip this sequence because it is wrong molecule type
+              continue;
             }
+          }
 
-            // look for direct or indirect references in common
-            DBRefEntry[] poss = nxt.getDBRefs(), cands = null;
-            if (direct)
-            {
-              cands = jalview.util.DBRefUtils.searchRefs(poss, xrf);
-            }
-            else
-            {
-              poss = CrossRef.findXDbRefs(dna, poss); //
-              cands = jalview.util.DBRefUtils.searchRefs(poss, xrf);
-            }
-            if (cands != null)
+          // look for direct or indirect references in common
+          DBRefEntry[] poss = nxt.getDBRefs();
+          List<DBRefEntry> cands = null;
+
+          // todo: indirect specifies we select either direct references to nxt
+          // that match xrf which is indirect to sequenceI, or indirect
+          // references to nxt that match xrf which is direct to sequenceI
+          cands = DBRefUtils.searchRefs(poss, xrf);
+          // else
+          // {
+          // poss = DBRefUtils.selectDbRefs(nxt.isProtein()!fromDna, poss);
+          // cands = DBRefUtils.searchRefs(poss, xrf);
+          // }
+          if (!cands.isEmpty())
+          {
+            if (!foundSeqs.contains(nxt))
             {
-              if (!rseqs.contains(nxt))
+              found = true;
+              foundSeqs.add(nxt);
+              if (mappings != null && !direct)
               {
-                rseqs.add(nxt);
-                boolean foundmap = cf != null;
-                // don't search if we aren't given a codon map object
-                for (int r = 0; foundmap && r < cands.length; r++)
+                /*
+                 * if the matched sequence has mapped dbrefs to
+                 * protein product / cdna, add equivalent mappings to
+                 * our source sequence
+                 */
+                for (DBRefEntry candidate : cands)
                 {
-                  if (cands[r].hasMap())
+                  Mapping mapping = candidate.getMap();
+                  if (mapping != null)
                   {
-                    if (cands[r].getMap().getTo() != null
-                            && cands[r].getMap().getMap().getFromRatio() != cands[r]
-                                    .getMap().getMap().getToRatio())
+                    MapList map = mapping.getMap();
+                    if (mapping.getTo() != null
+                            && map.getFromRatio() != map.getToRatio())
                     {
-                      foundmap = true;
-                      // get sense of map correct for adding to product
-                      // alignment.
-                      if (dna)
+                      /*
+                       * add a mapping, as from dna to peptide sequence
+                       */
+                      if (map.getFromRatio() == 3)
                       {
-                        // map is from dna seq to a protein product
-                        cf.addMap(sequenceI, nxt, cands[r].getMap()
-                                .getMap());
+                        mappings.addMap(nxt, fromSeq, map);
                       }
                       else
                       {
-                        // map should be from protein seq to its coding dna
-                        cf.addMap(nxt, sequenceI, cands[r].getMap()
-                                .getMap().getInverse());
+                        mappings.addMap(nxt, fromSeq, map.getInverse());
                       }
                     }
                   }
                 }
-                // TODO: add mapping between sequences if necessary
-                found = true;
               }
             }
-
           }
         }
       }
     }
     return found;
   }
-
-  /**
-   * precalculate different products that can be found for seqs in dataset and
-   * return them.
-   * 
-   * @param dna
-   * @param seqs
-   * @param dataset
-   * @param fake
-   *          - don't actually build lists - just get types
-   * @return public static Object[] buildXProductsList(boolean dna, SequenceI[]
-   *         seqs, AlignmentI dataset, boolean fake) { String types[] =
-   *         jalview.analysis.CrossRef.findSequenceXrefTypes( dna, seqs,
-   *         dataset); if (types != null) { System.out.println("Xref Types for:
-   *         "+(dna ? "dna" : "prot")); for (int t = 0; t < types.length; t++) {
-   *         System.out.println("Type: " + types[t]); SequenceI[] prod =
-   *         jalview.analysis.CrossRef.findXrefSequences(seqs, dna, types[t]);
-   *         System.out.println("Found " + ((prod == null) ? "no" : "" +
-   *         prod.length) + " products"); if (prod!=null) { for (int p=0;
-   *         p<prod.length; p++) { System.out.println("Prod "+p+":
-   *         "+prod[p].getDisplayId(true)); } } } } else {
-   *         System.out.println("Trying getProducts for
-   *         "+al.getSequenceAt(0).getDisplayId(true));
-   *         System.out.println("Search DS Xref for: "+(dna ? "dna" : "prot"));
-   *         // have a bash at finding the products amongst all the retrieved
-   *         sequences. SequenceI[] prod =
-   *         jalview.analysis.CrossRef.findXrefSequences(al
-   *         .getSequencesArray(), dna, null, ds); System.out.println("Found " +
-   *         ((prod == null) ? "no" : "" + prod.length) + " products"); if
-   *         (prod!=null) { // select non-equivalent sequences from dataset list
-   *         for (int p=0; p<prod.length; p++) { System.out.println("Prod "+p+":
-   *         "+prod[p].getDisplayId(true)); } } } }
-   */
 }
index be138f3..800cef2 100644 (file)
@@ -69,7 +69,7 @@ public class Dna
 
   final private int dnaWidth;
 
-  final private Alignment dataset;
+  final private AlignmentI dataset;
 
   /*
    * Working variables for the translation.
@@ -852,13 +852,18 @@ public class Dna
     char[] originalSequence = sequence.toCharArray();
     int length = originalSequence.length;
     char[] reversedSequence = new char[length];
-
+    int bases = 0;
     for (int i = 0; i < length; i++)
     {
-      reversedSequence[length - i - 1] = complement ? getComplement(originalSequence[i])
+      char c = complement ? getComplement(originalSequence[i])
               : originalSequence[i];
+      reversedSequence[length - i - 1] = c;
+      if (!Comparison.isGap(c))
+      {
+        bases++;
+      }
     }
-    SequenceI reversed = new Sequence(newName, reversedSequence, 1, length);
+    SequenceI reversed = new Sequence(newName, reversedSequence, 1, bases);
     return reversed;
   }
 
@@ -874,6 +879,10 @@ public class Dna
   {
     char result = c;
     switch (c) {
+    case '-':
+    case '.':
+    case ' ':
+      break;
     case 'a':
       result = 't';
       break;
index 51a818f..2ddd015 100644 (file)
@@ -127,6 +127,11 @@ public class Grouping
         }
       }
     }
+
+    /*
+     * get selected columns (in the order they were selected);
+     * note this could include right-to-left ranges
+     */
     int[] spos = new int[cs.getSelected().size()];
     int width = -1;
     int i = 0;
@@ -134,7 +139,7 @@ public class Grouping
     {
       spos[i++] = pos.intValue();
     }
-    ;
+
     for (i = 0; i < sequences.length; i++)
     {
       int slen = sequences[i].getLength();
index e752126..e3d999a 100644 (file)
@@ -31,82 +31,108 @@ import jalview.datamodel.SequenceFeature;
 import jalview.util.MessageManager;
 
 import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
 import java.util.Hashtable;
+import java.util.List;
 import java.util.Stack;
 import java.util.Vector;
 
 public class Rna
 {
 
-  static Hashtable<Integer, Integer> pairHash = new Hashtable();
-
-  private static final Character[] openingPars = { '(', '[', '{', '<', 'A',
-      'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
-      'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
-
-  private static final Character[] closingPars = { ')', ']', '}', '>', 'a',
-      'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
-      'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
-
-  private static HashSet<Character> openingParsSet = new HashSet<Character>(
-          Arrays.asList(openingPars));
-
-  private static HashSet<Character> closingParsSet = new HashSet<Character>(
-          Arrays.asList(closingPars));
+  /**
+   * Answers true if the character is a valid open pair rna secondary structure
+   * symbol. Currently accepts A-Z, ([{<
+   * 
+   * @param c
+   * @return
+   */
+  public static boolean isOpeningParenthesis(char c)
+  {
+    return ('A' <= c && c <= 'Z' || c == '(' || c == '[' || c == '{' || c == '<');
+  }
 
-  private static Hashtable<Character, Character> closingToOpening = new Hashtable<Character, Character>()
-  // Initializing final data structure
+  /**
+   * Answers true if the string is a valid open pair rna secondary structure
+   * symbol. Currently accepts A-Z, ([{<
+   * 
+   * @param s
+   * @return
+   */
+  public static boolean isOpeningParenthesis(String s)
   {
-    private static final long serialVersionUID = 1L;
-    {
-      for (int i = 0; i < openingPars.length; i++)
-      {
-        // System.out.println(closingPars[i] + "->" + openingPars[i]);
-        put(closingPars[i], openingPars[i]);
-      }
-    }
-  };
+    return s != null && s.length() == 1
+            && isOpeningParenthesis(s.charAt(0));
+  }
 
-  private static boolean isOpeningParenthesis(char c)
+  /**
+   * Answers true if the character is a valid close pair rna secondary structure
+   * symbol. Currently accepts a-z, )]}>
+   * 
+   * @param c
+   * @return
+   */
+  public static boolean isClosingParenthesis(char c)
   {
-    return openingParsSet.contains(c);
+    return ('a' <= c && c <= 'z' || c == ')' || c == ']' || c == '}' || c == '>');
   }
 
-  private static boolean isClosingParenthesis(char c)
+  /**
+   * Answers true if the string is a valid close pair rna secondary structure
+   * symbol. Currently accepts a-z, )]}>
+   * 
+   * @param s
+   * @return
+   */
+  public static boolean isClosingParenthesis(String s)
   {
-    return closingParsSet.contains(c);
+    return s != null && s.length() == 1
+            && isClosingParenthesis(s.charAt(0));
   }
 
-  private static char matchingOpeningParenthesis(char closingParenthesis)
-          throws WUSSParseException
+  /**
+   * Returns the matching open pair symbol for the given closing symbol.
+   * Currently returns A-Z for a-z, or ([{< for )]}>, or the input symbol if it
+   * is not a valid closing symbol.
+   * 
+   * @param c
+   * @return
+   */
+  public static char getMatchingOpeningParenthesis(char c)
   {
-    if (!isClosingParenthesis(closingParenthesis))
+    if ('a' <= c && c <= 'z')
     {
-      throw new WUSSParseException(
-              MessageManager.formatMessage(
-                      "exception.querying_matching_opening_parenthesis_for_non_closing_parenthesis",
-                      new String[] { new StringBuffer(closingParenthesis)
-                              .toString() }), -1);
+      return (char) (c + 'A' - 'a');
+    }
+    switch (c)
+    {
+    case ')':
+      return '(';
+    case ']':
+      return '[';
+    case '}':
+      return '{';
+    case '>':
+      return '<';
+    default:
+      return c;
     }
-
-    return closingToOpening.get(closingParenthesis);
   }
 
   /**
    * Based off of RALEE code ralee-get-base-pairs. Keeps track of open bracket
    * positions in "stack" vector. When a close bracket is reached, pair this
-   * with the last element in the "stack" vector and store in "pairs" vector.
-   * Remove last element in the "stack" vector. Continue in this manner until
-   * the whole string is processed.
+   * with the last matching element in the "stack" vector and store in "pairs"
+   * vector. Remove last element in the "stack" vector. Continue in this manner
+   * until the whole string is processed. Parse errors are thrown as exceptions
+   * wrapping the error location - position of the first unmatched closing
+   * bracket, or string length if there is an unmatched opening bracket.
    * 
    * @param line
    *          Secondary structure line of an RNA Stockholm file
-   * @return Array of SequenceFeature; type = RNA helix, begin is open base
-   *         pair, end is close base pair
+   * @return
+   * @throw {@link WUSSParseException}
    */
-  public static Vector<SimpleBP> GetSimpleBPs(CharSequence line)
+  public static Vector<SimpleBP> getSimpleBPs(CharSequence line)
           throws WUSSParseException
   {
     Hashtable<Character, Stack<Integer>> stacks = new Hashtable<Character, Stack<Integer>>();
@@ -128,13 +154,13 @@ public class Rna
       else if (isClosingParenthesis(base))
       {
 
-        char opening = matchingOpeningParenthesis(base);
+        char opening = getMatchingOpeningParenthesis(base);
 
         if (!stacks.containsKey(opening))
         {
           throw new WUSSParseException(MessageManager.formatMessage(
                   "exception.mismatched_unseen_closing_char",
-                  new String[] { new StringBuffer(base).toString() }), i);
+                  new String[] { String.valueOf(base) }), i);
         }
 
         Stack<Integer> stack = stacks.get(opening);
@@ -143,7 +169,7 @@ public class Rna
           // error whilst parsing i'th position. pass back
           throw new WUSSParseException(MessageManager.formatMessage(
                   "exception.mismatched_closing_char",
-                  new String[] { new StringBuffer(base).toString() }), i);
+                  new String[] { String.valueOf(base) }), i);
         }
         int temp = stack.pop();
 
@@ -156,33 +182,36 @@ public class Rna
       Stack<Integer> stack = stacks.get(opening);
       if (!stack.empty())
       {
+        /*
+         * we have an unmatched opening bracket; report error as at
+         * i (length of input string)
+         */
         throw new WUSSParseException(MessageManager.formatMessage(
                 "exception.mismatched_opening_char",
-                new String[] { new StringBuffer(opening).toString(),
-                    Integer.valueOf(stack.pop()).toString() }), i);
+                new String[] { String.valueOf(opening),
+                    String.valueOf(stack.pop()) }), i);
       }
     }
     return pairs;
   }
 
-  public static SequenceFeature[] GetBasePairs(CharSequence line)
+  public static SequenceFeature[] getBasePairs(List<SimpleBP> bps)
           throws WUSSParseException
   {
-    Vector<SimpleBP> bps = GetSimpleBPs(line);
     SequenceFeature[] outPairs = new SequenceFeature[bps.size()];
     for (int p = 0; p < bps.size(); p++)
     {
-      SimpleBP bp = bps.elementAt(p);
+      SimpleBP bp = bps.get(p);
       outPairs[p] = new SequenceFeature("RNA helix", "", "", bp.getBP5(),
               bp.getBP3(), "");
     }
     return outPairs;
   }
 
-  public static ArrayList<SimpleBP> GetModeleBP(CharSequence line)
+  public static List<SimpleBP> getModeleBP(CharSequence line)
           throws WUSSParseException
   {
-    Vector<SimpleBP> bps = GetSimpleBPs(line);
+    Vector<SimpleBP> bps = getSimpleBPs(line);
     return new ArrayList<SimpleBP>(bps);
   }
 
@@ -220,8 +249,8 @@ public class Rna
     int close; // Position of a close bracket under review
     int j; // Counter
 
-    Hashtable helices = new Hashtable(); // Keep track of helix number for each
-                                         // position
+    Hashtable<Integer, Integer> helices = new Hashtable<Integer, Integer>();
+    // Keep track of helix number for each position
 
     // Go through each base pair and assign positions a helix
     for (i = 0; i < pairs.length; i++)
@@ -255,7 +284,7 @@ public class Rna
         if ((popen < lastopen) && (popen > open))
         {
           if (helices.containsValue(popen)
-                  && (((Integer) helices.get(popen)) == helix))
+                  && ((helices.get(popen)) == helix))
           {
             continue;
           }
@@ -281,4 +310,138 @@ public class Rna
 
     }
   }
+
+  /**
+   * Answers true if the character is a recognised symbol for RNA secondary
+   * structure. Currently accepts a-z, A-Z, ()[]{}<>.
+   * 
+   * @param c
+   * @return
+   */
+  public static boolean isRnaSecondaryStructureSymbol(char c)
+  {
+    return isOpeningParenthesis(c) || isClosingParenthesis(c);
+  }
+
+  /**
+   * Answers true if the string is a recognised symbol for RNA secondary
+   * structure. Currently accepts a-z, A-Z, ()[]{}<>.
+   * 
+   * @param s
+   * @return
+   */
+  public static boolean isRnaSecondaryStructureSymbol(String s)
+  {
+    return isOpeningParenthesis(s) || isClosingParenthesis(s);
+  }
+
+  /**
+   * Translates a string to RNA secondary structure representation. Returns the
+   * string with any non-SS characters changed to spaces. Accepted characters
+   * are a-z, A-Z, and (){}[]<> brackets.
+   * 
+   * @param ssString
+   * @return
+   */
+  public static String getRNASecStrucState(String ssString)
+  {
+    if (ssString == null)
+    {
+      return null;
+    }
+    StringBuilder result = new StringBuilder(ssString.length());
+    for (int i = 0; i < ssString.length(); i++)
+    {
+      char c = ssString.charAt(i);
+      result.append(isRnaSecondaryStructureSymbol(c) ? c : " ");
+    }
+    return result.toString();
+  }
+
+  /**
+   * Answers true if the base-pair is either a canonical (A-T/U, C-G) or a
+   * wobble (G-T/U) pair (either way round), else false
+   * 
+   * @param first
+   * @param second
+   * @return
+   */
+  public static boolean isCanonicalOrWobblePair(char first, char second)
+  {
+    if (first > 'Z')
+    {
+      first -= 32;
+    }
+    if (second > 'Z')
+    {
+      second -= 32;
+    }
+  
+    switch (first)
+    {
+    case 'A':
+      switch (second)
+      {
+      case 'T':
+      case 'U':
+        return true;
+      }
+      break;
+    case 'C':
+      switch (second)
+      {
+      case 'G':
+        return true;
+      }
+      break;
+    case 'T':
+    case 'U':
+      switch (second)
+      {
+      case 'A':
+      case 'G':
+        return true;
+      }
+      break;
+    case 'G':
+      switch (second)
+      {
+      case 'C':
+      case 'T':
+      case 'U':
+        return true;
+      }
+      break;
+    }
+    return false;
+  }
+
+  /**
+   * Returns the matching close pair symbol for the given opening symbol.
+   * Currently returns a-z for A-Z, or )]}> for ([{<, or the input symbol if it
+   * is not a valid opening symbol.
+   * 
+   * @param c
+   * @return
+   */
+  public static char getMatchingClosingParenthesis(char c)
+  {
+    if ('A' <= c && c <= 'Z')
+    {
+      return (char) (c + 'a' - 'A');
+    }
+    switch (c)
+    {
+    case '(':
+      return ')';
+    case '[':
+      return ']';
+    case '{':
+      return '}';
+    case '<':
+      return '>';
+    default:
+      return c;
+    }
+  }
 }
index 3fd0581..c12de4e 100755 (executable)
@@ -290,7 +290,7 @@ public class SequenceIdMatcher
     {
       if (s != null)
       {
-        id = new String(s.toLowerCase());
+        id = s.toLowerCase();
       }
       else
       {
@@ -357,5 +357,15 @@ public class SequenceIdMatcher
                 .indexOf(s.charAt(id.length())) > -1)) : false;
       }
     }
+
+    /**
+     * toString method returns the wrapped sequence id. For debugging purposes
+     * only, behaviour not guaranteed not to change.
+     */
+    @Override
+    public String toString()
+    {
+      return id;
+    }
   }
 }
index 88387dd..479c856 100644 (file)
@@ -24,6 +24,7 @@ import jalview.datamodel.AlignmentAnnotation;
 import jalview.datamodel.Annotation;
 import jalview.datamodel.SequenceFeature;
 import jalview.datamodel.SequenceI;
+import jalview.util.Comparison;
 import jalview.util.Format;
 
 import java.util.ArrayList;
@@ -103,23 +104,23 @@ public class StructureFrequency
 
     SequenceFeature[] rna = rnaStruc._rnasecstr;
     char c, s, cEnd;
-    int count = 0, nonGap = 0, i, bpEnd = -1, j, jSize = sequences.length;
+    int bpEnd = -1;
+    int jSize = sequences.length;
     int[] values;
     int[][] pairs;
     float percentage;
-    boolean wooble = true;
-    for (i = start; i < end; i++) // foreach column
+
+    for (int i = start; i < end; i++) // foreach column
     {
-      residueHash = new Hashtable();
+      int canonicalOrWobblePairCount = 0;
+      int otherPairCount = 0;
       maxResidue = "-";
       values = new int[255];
       pairs = new int[255][255];
       bpEnd = -1;
-      // System.out.println("s="+struc[i]);
       if (i < struc.length)
       {
         s = struc[i];
-
       }
       else
       {
@@ -130,7 +131,7 @@ public class StructureFrequency
         s = '-';
       }
 
-      if (s != '(' && s != '[')
+      if (!Rna.isOpeningParenthesis(s))
       {
         if (s == '-')
         {
@@ -139,12 +140,11 @@ public class StructureFrequency
       }
       else
       {
-
         bpEnd = findPair(rna, i);
 
         if (bpEnd > -1)
         {
-          for (j = 0; j < jSize; j++) // foreach row
+          for (int j = 0; j < jSize; j++) // foreach row
           {
             if (sequences[j] == null)
             {
@@ -152,45 +152,46 @@ public class StructureFrequency
                       .println("WARNING: Consensus skipping null sequence - possible race condition.");
               continue;
             }
-            c = sequences[j].getCharAt(i);
-            // System.out.println("c="+c);
 
-            // standard representation for gaps in sequence and structure
-            if (c == '.' || c == ' ')
-            {
-              c = '-';
-            }
+            c = sequences[j].getCharAt(i);
+            cEnd = sequences[j].getCharAt(bpEnd);
 
-            if (c == '-')
+            if (Comparison.isGap(c) || Comparison.isGap(cEnd))
             {
               values['-']++;
               continue;
             }
-            cEnd = sequences[j].getCharAt(bpEnd);
 
-            // System.out.println("pairs ="+c+","+cEnd);
-            if (checkBpType(c, cEnd) == true)
+            /*
+             * ensure upper-case for counting purposes
+             */
+            if ('a' <= c && 'z' >= c)
+            {
+              c += 'A' - 'a';
+            }
+            if ('a' <= cEnd && 'z' >= cEnd)
+            {
+              cEnd += 'A' - 'a';
+            }
+            if (Rna.isCanonicalOrWobblePair(c, cEnd))
             {
-              values['(']++; // H means it's a helix (structured)
+              values['(']++;
               maxResidue = "(";
-              wooble = true;
-              // System.out.println("It's a pair wc");
-
+              canonicalOrWobblePairCount++;
             }
-            if (checkBpType(c, cEnd) == false)
+            else
             {
-              wooble = false;
-              values['[']++; // H means it's a helix (structured)
+              values['[']++;
               maxResidue = "[";
-
+              otherPairCount++;
             }
             pairs[c][cEnd]++;
-
           }
         }
         // nonGap++;
       }
-      // UPDATE this for new values
+
+      residueHash = new Hashtable();
       if (profile)
       {
         // TODO 1-dim array with jsize in [0], nongapped in [1]; or Pojo
@@ -199,13 +200,21 @@ public class StructureFrequency
 
         residueHash.put(PAIRPROFILE, pairs);
       }
-      if (wooble == true)
-      {
-        count = values['('];
-      }
-      if (wooble == false)
+
+      /*
+       * the count is the number of valid pairs (as a percentage, determines
+       * the relative size of the profile logo)
+       */
+      int count = canonicalOrWobblePairCount;
+
+      /*
+       * currently displaying as '(' if most pairs are valid, or as
+       * '[' if there are more invalid than valid pairs 
+       */
+      if (!maxResidue.equals("-"))
       {
-        count = values['['];
+        maxResidue = canonicalOrWobblePairCount >= otherPairCount ? "("
+                : "[";
       }
       residueHash.put(MAXCOUNT, new Integer(count));
       residueHash.put(MAXRESIDUE, maxResidue);
@@ -225,17 +234,9 @@ public class StructureFrequency
         values[']'] = values['['];
         values['('] = 0;
         values['['] = 0;
+        maxResidue = maxResidue.equals("(") ? ")" : "]";
+
         residueHash = new Hashtable();
-        if (wooble == true)
-        {
-          // System.out.println(maxResidue+","+wooble);
-          maxResidue = ")";
-        }
-        if (wooble == false)
-        {
-          // System.out.println(maxResidue+","+wooble);
-          maxResidue = "]";
-        }
         if (profile)
         {
           residueHash.put(PROFILE, new int[][] { values,
@@ -251,80 +252,8 @@ public class StructureFrequency
         residueHash.put(PID_GAPS, new Float(percentage));
 
         result[bpEnd] = residueHash;
-
-      }
-    }
-  }
-
-  /**
-   * Method to check if a base-pair is a canonical or a wobble bp
-   * 
-   * @param up
-   *          5' base
-   * @param down
-   *          3' base
-   * @return True if it is a canonical/wobble bp
-   */
-  public static boolean checkBpType(char up, char down)
-  {
-    if (up > 'Z')
-    {
-      up -= 32;
-    }
-    if (down > 'Z')
-    {
-      down -= 32;
-    }
-
-    switch (up)
-    {
-    case 'A':
-      switch (down)
-      {
-      case 'T':
-        return true;
-      case 'U':
-        return true;
-      }
-      break;
-    case 'C':
-      switch (down)
-      {
-      case 'G':
-        return true;
-      }
-      break;
-    case 'T':
-      switch (down)
-      {
-      case 'A':
-        return true;
-      case 'G':
-        return true;
-      }
-      break;
-    case 'G':
-      switch (down)
-      {
-      case 'C':
-        return true;
-      case 'T':
-        return true;
-      case 'U':
-        return true;
-      }
-      break;
-    case 'U':
-      switch (down)
-      {
-      case 'A':
-        return true;
-      case 'G':
-        return true;
       }
-      break;
     }
-    return false;
   }
 
   /**
@@ -534,7 +463,7 @@ public class StructureFrequency
       for (String j : test)
       {
         System.out.println(i + "-" + j + ": "
-                + StructureFrequency.checkBpType(i.charAt(0), j.charAt(0)));
+                + Rna.isCanonicalOrWobblePair(i.charAt(0), j.charAt(0)));
       }
     }
   }
index 66f4036..18605b8 100644 (file)
@@ -35,17 +35,12 @@ public interface AlignCalcManagerI
   void notifyStart(AlignCalcWorkerI worker);
 
   /**
-   * check if a calculation of this type is already active
-   * 
-   * @param worker
-   * @return
-   */
-  boolean alreadyDoing(AlignCalcWorkerI worker);
-
-  /**
-   * tell manager that worker is now processing data
+   * tell manager that a thread running worker's run() loop is ready to start
+   * processing data
    * 
    * @param worker
+   * @return true if worker should start processing, false if another thread is
+   *         in progress
    */
   boolean notifyWorking(AlignCalcWorkerI worker);
 
@@ -63,7 +58,7 @@ public interface AlignCalcManagerI
    * 
    * @param worker
    */
-  void workerCannotRun(AlignCalcWorkerI worker);
+  void disableWorker(AlignCalcWorkerI worker);
 
   /**
    * indicate that a worker like this may be run on the platform.
@@ -71,7 +66,15 @@ public interface AlignCalcManagerI
    * @param worker
    *          of class to be removed from the execution blacklist
    */
-  void workerMayRun(AlignCalcWorkerI worker);
+  void enableWorker(AlignCalcWorkerI worker);
+
+  /**
+   * Answers true if the worker is disabled from running
+   * 
+   * @param worker
+   * @return
+   */
+  boolean isDisabled(AlignCalcWorkerI worker);
 
   /**
    * launch a new worker
@@ -83,7 +86,7 @@ public interface AlignCalcManagerI
   /**
    * 
    * @param worker
-   * @return
+   * @return true if the worker is currently running
    */
   boolean isWorking(AlignCalcWorkerI worker);
 
@@ -120,7 +123,7 @@ public interface AlignCalcManagerI
    * 
    * @param workerClass
    */
-  void updateAnnotationFor(Class workerClass);
+  void updateAnnotationFor(Class<? extends AlignCalcWorkerI> workerClass);
 
   /**
    * return any registered workers of the given class
@@ -128,17 +131,8 @@ public interface AlignCalcManagerI
    * @param workerClass
    * @return null or one or more workers of the given class
    */
-  List<AlignCalcWorkerI> getRegisteredWorkersOfClass(Class workerClass);
-
-  /**
-   * start any workers of the given class
-   * 
-   * @param workerClass
-   * @return false if no workers of given class were registered (note -
-   *         blacklisted classes cannot be restarted, so this method will return
-   *         true for blacklisted workers)
-   */
-  boolean startRegisteredWorkersOfClass(Class workerClass);
+  List<AlignCalcWorkerI> getRegisteredWorkersOfClass(
+          Class<? extends AlignCalcWorkerI> workerClass);
 
   /**
    * work out if there is an instance of a worker that is *waiting* to start
@@ -156,6 +150,15 @@ public interface AlignCalcManagerI
    * 
    * @param typeToRemove
    */
-  void removeRegisteredWorkersOfClass(Class typeToRemove);
+  void removeRegisteredWorkersOfClass(
+          Class<? extends AlignCalcWorkerI> typeToRemove);
 
+  /**
+   * Removes the worker that produces the given annotation, provided it is
+   * marked as 'deletable'. Some workers may need to continue to run as the
+   * results of their calculations are needed, e.g. for colour schemes.
+   * 
+   * @param ann
+   */
+  void removeWorkerForAnnotation(AlignmentAnnotation ann);
 }
index 06dc054..85157c4 100644 (file)
@@ -35,17 +35,26 @@ public interface AlignCalcWorkerI extends Runnable
    * @param annot
    * @return
    */
-  public boolean involves(AlignmentAnnotation annot);
+  boolean involves(AlignmentAnnotation annot);
 
   /**
    * Updates the display of calculated annotation values (does not recalculate
-   * the values). This allows for quick redraw of annotations when display
-   * settings are changed.
+   * the values). This allows ÃŸquick redraw of annotations when display settings
+   * are changed.
    */
-  public void updateAnnotation();
+  void updateAnnotation();
 
   /**
-   * Removes any annotation managed by this worker from the alignment
+   * Removes any annotation(s) managed by this worker from the alignment
    */
   void removeAnnotation();
+
+  /**
+   * Answers true if the worker should be deleted entirely when its annotation
+   * is deleted from the display, or false if it should continue to run. Some
+   * workers are required to run for their side-effects.
+   * 
+   * @return
+   */
+  boolean isDeletable();
 }
index 2ce7e4a..32245b3 100644 (file)
@@ -48,32 +48,6 @@ public interface DBRefEntryI
   public void setVersion(String version);
 
   /**
-   * 
-   * @param startRes
-   *          index of start residue in the source DB
-   */
-  public void setStartRes(int startRes);
-
-  /**
-   * 
-   * @return index of start residue in the source DB
-   */
-  public int getStartRes();
-
-  /**
-   * 
-   * @param endRes
-   *          index of end residue in the source DB
-   */
-  public void setEndRes(int endRes);
-
-  /**
-   * 
-   * @return index of end residue in the source DB
-   */
-  public int getEndRes();
-
-  /**
    * access a mapping, if present that can be used to map positions from the
    * associated dataset sequence to the DBRef's sequence frame.
    * 
index 71f126b..abb6848 100644 (file)
@@ -73,8 +73,6 @@ import java.util.Vector;
 public class APopupMenu extends java.awt.PopupMenu implements
         ActionListener, ItemListener
 {
-  private static final String ALL_ANNOTATIONS = "All";
-
   Menu groupMenu = new Menu();
 
   MenuItem editGroupName = new MenuItem();
@@ -970,7 +968,7 @@ public class APopupMenu extends java.awt.PopupMenu implements
             "label.represent_group_with", new Object[] { "" }));
     revealAll.setLabel(MessageManager.getString("action.reveal_all"));
     revealSeq.setLabel(MessageManager.getString("action.reveal_sequences"));
-    menu1.setLabel(MessageManager.getString("label.group") + ":");
+    menu1.setLabel(MessageManager.getString("label.group:"));
     add(groupMenu);
     this.add(seqMenu);
     this.add(hideSeqs);
@@ -1330,7 +1328,8 @@ public class APopupMenu extends java.awt.PopupMenu implements
     showMenu.removeAll();
     hideMenu.removeAll();
 
-    final List<String> all = Arrays.asList(ALL_ANNOTATIONS);
+    final List<String> all = Arrays.asList(new String[] { MessageManager
+            .getString("label.all") });
     addAnnotationTypeToShowHide(showMenu, forSequences, "", all, true, true);
     addAnnotationTypeToShowHide(hideMenu, forSequences, "", all, true,
             false);
index 8e69134..2ee86f1 100644 (file)
@@ -221,6 +221,7 @@ public class AlignFrame extends EmbmenuFrame implements ActionListener,
     {
       viewport.setColumnSelection(columnSelection);
     }
+    viewport.setScaleAboveWrapped(scaleAbove.getState());
 
     alignPanel = new AlignmentPanel(this, viewport);
     avc = new jalview.controller.AlignViewController(this, viewport,
@@ -2235,7 +2236,10 @@ public class AlignFrame extends EmbmenuFrame implements ActionListener,
     }
     sg.setEndRes(viewport.getAlignment().getWidth() - 1);
     viewport.setSelectionGroup(sg);
-    alignPanel.paintAlignment(true);
+    // JAL-2034 - should delegate to
+    // alignPanel to decide if overview needs
+    // updating.
+    alignPanel.paintAlignment(false);
     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
     viewport.sendSelection();
   }
@@ -2252,7 +2256,10 @@ public class AlignFrame extends EmbmenuFrame implements ActionListener,
     viewport.setSelectionGroup(null);
     alignPanel.idPanel.idCanvas.searchResults = null;
     alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
-    alignPanel.paintAlignment(true);
+    // JAL-2034 - should delegate to
+    // alignPanel to decide if overview needs
+    // updating.
+    alignPanel.paintAlignment(false);
     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
     viewport.sendSelection();
   }
@@ -3512,10 +3519,10 @@ public class AlignFrame extends EmbmenuFrame implements ActionListener,
     nucleotideColour.setLabel(MessageManager.getString("label.nucleotide"));
     nucleotideColour.addActionListener(this);
     modifyPID.setLabel(MessageManager
-            .getString("label.modify_identity_thereshold"));
+            .getString("label.modify_identity_threshold"));
     modifyPID.addActionListener(this);
     modifyConservation.setLabel(MessageManager
-            .getString("label.modify_conservation_thereshold"));
+            .getString("label.modify_conservation_threshold"));
     modifyConservation.addActionListener(this);
     annotationColour.setLabel(MessageManager
             .getString("action.by_annotation"));
index 57b182c..5a9cd55 100644 (file)
@@ -138,11 +138,11 @@ public class AnnotationColourChooser extends Panel implements
     }
 
     threshold.addItem(MessageManager
-            .getString("label.threshold_feature_no_thereshold"));
+            .getString("label.threshold_feature_no_threshold"));
     threshold.addItem(MessageManager
-            .getString("label.threshold_feature_above_thereshold"));
+            .getString("label.threshold_feature_above_threshold"));
     threshold.addItem(MessageManager
-            .getString("label.threshold_feature_below_thereshold"));
+            .getString("label.threshold_feature_below_threshold"));
 
     if (oldcs instanceof AnnotationColourGradient)
     {
@@ -162,7 +162,7 @@ public class AnnotationColourChooser extends Panel implements
       default:
         throw new Error(
                 MessageManager
-                        .getString("error.implementation_error_dont_know_thereshold_annotationcolourgradient"));
+                        .getString("error.implementation_error_dont_know_threshold_annotationcolourgradient"));
       }
       thresholdIsMin.setState(acg.thresholdIsMinMax);
       thresholdValue.setText("" + acg.getAnnotationThreshold());
index 77700d0..6012c1a 100755 (executable)
@@ -22,9 +22,13 @@ package jalview.appletgui;
 
 import jalview.datamodel.AlignmentAnnotation;
 import jalview.datamodel.Annotation;
+import jalview.datamodel.SequenceI;
 import jalview.renderer.AnnotationRenderer;
 import jalview.renderer.AwtRenderPanelI;
+import jalview.schemes.ResidueProperties;
+import jalview.util.Comparison;
 import jalview.util.MessageManager;
+import jalview.util.Platform;
 
 import java.awt.Color;
 import java.awt.Dimension;
@@ -98,7 +102,8 @@ public class AnnotationPanel extends Panel implements AwtRenderPanelI,
 
   public AnnotationPanel(AlignmentPanel ap)
   {
-    MAC = new jalview.util.Platform().isAMac();
+    new jalview.util.Platform();
+    MAC = Platform.isAMac();
     this.ap = ap;
     av = ap.av;
     setLayout(null);
@@ -158,12 +163,12 @@ public class AnnotationPanel extends Panel implements AwtRenderPanelI,
 
     if (evt.getActionCommand().equals(REMOVE))
     {
-      for (int sel : av.getColumnSelection().getSelected())
+      for (int index : av.getColumnSelection().getSelected())
       {
-        // TODO: JAL-2001 check if applet has faulty 'REMOVE' selected columns
-        // of
-        // annotation if selection includes hidden columns
-        anot[sel] = null;
+        if (av.getColumnSelection().isVisible(index))
+        {
+          anot[index] = null;
+        }
       }
     }
     else if (evt.getActionCommand().equals(LABEL))
@@ -239,7 +244,8 @@ public class AnnotationPanel extends Panel implements AwtRenderPanelI,
       else if (evt.getActionCommand().equals(STEM))
       {
         type = 'S';
-        symbol = "\u03C3";
+        int column = av.getColumnSelection().getSelectedRanges().get(0)[0];
+        symbol = aa[activeRow].getDefaultRnaHelixSymbol(column);
       }
 
       if (!aa[activeRow].hasIcons)
@@ -344,7 +350,8 @@ public class AnnotationPanel extends Panel implements AwtRenderPanelI,
     if ((evt.getModifiers() & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK
             && activeRow != -1)
     {
-      if (av.getColumnSelection() == null)
+      if (av.getColumnSelection() == null
+              || av.getColumnSelection().isEmpty())
       {
         return;
       }
@@ -352,10 +359,8 @@ public class AnnotationPanel extends Panel implements AwtRenderPanelI,
       PopupMenu pop = new PopupMenu(
               MessageManager.getString("label.structure_type"));
       MenuItem item;
-      /*
-       * Just display the needed structure options
-       */
-      if (av.getAlignment().isNucleotide() == true)
+
+      if (av.getAlignment().isNucleotide())
       {
         item = new MenuItem(STEM);
         item.addActionListener(this);
@@ -457,21 +462,67 @@ public class AnnotationPanel extends Panel implements AwtRenderPanelI,
       }
     }
 
-    int res = evt.getX() / av.getCharWidth() + av.getStartRes();
+    int column = evt.getX() / av.getCharWidth() + av.getStartRes();
 
     if (av.hasHiddenColumns())
     {
-      res = av.getColumnSelection().adjustForHiddenColumns(res);
+      column = av.getColumnSelection().adjustForHiddenColumns(column);
     }
 
-    if (row > -1 && res < aa[row].annotations.length
-            && aa[row].annotations[res] != null)
+    if (row > -1 && column < aa[row].annotations.length
+            && aa[row].annotations[column] != null)
     {
-      StringBuffer text = new StringBuffer("Sequence position " + (res + 1));
-      if (aa[row].annotations[res].description != null)
+      StringBuilder text = new StringBuilder();
+      text.append(MessageManager.getString("label.column")).append(" ")
+              .append(column + 1);
+      String description = aa[row].annotations[column].description;
+      if (description != null && description.length() > 0)
+      {
+        text.append("  ").append(description);
+      }
+
+      /*
+       * if the annotation is sequence-specific, show the sequence number
+       * in the alignment, and (if not a gap) the residue and position
+       */
+      SequenceI seqref = aa[row].sequenceRef;
+      if (seqref != null)
       {
-        text.append("  " + aa[row].annotations[res].description);
+        int seqIndex = av.getAlignment().findIndex(seqref);
+        if (seqIndex != -1)
+        {
+          text.append(", ")
+                  .append(MessageManager.getString("label.sequence"))
+                  .append(" ").append(seqIndex + 1);
+          char residue = seqref.getCharAt(column);
+          if (!Comparison.isGap(residue))
+          {
+            text.append(" ");
+            String name;
+            if (av.getAlignment().isNucleotide())
+            {
+              name = ResidueProperties.nucleotideName.get(String
+                      .valueOf(residue));
+              text.append(" Nucleotide: ").append(
+                      name != null ? name : residue);
+            }
+            else
+            {
+              name = 'X' == residue ? "X" : ('*' == residue ? "STOP"
+                      : ResidueProperties.aa2Triplet.get(String
+                              .valueOf(residue)));
+              text.append(" Residue: ").append(
+                      name != null ? name : residue);
+            }
+            int residuePos = seqref.findPosition(column);
+            text.append(" (").append(residuePos).append(")");
+            // int residuePos = seqref.findPosition(column);
+            // text.append(residue).append(" (")
+            // .append(residuePos).append(")");
+          }
+        }
       }
+
       ap.alignFrame.statusBar.setText(text.toString());
     }
   }
index 4cb5ede..fc49de5 100644 (file)
@@ -186,11 +186,11 @@ public abstract class AnnotationRowFilter extends Panel
   protected void populateThresholdComboBox(Choice threshold)
   {
     threshold.addItem(MessageManager
-            .getString("label.threshold_feature_no_thereshold"));
+            .getString("label.threshold_feature_no_threshold"));
     threshold.addItem(MessageManager
-            .getString("label.threshold_feature_above_thereshold"));
+            .getString("label.threshold_feature_above_threshold"));
     threshold.addItem(MessageManager
-            .getString("label.threshold_feature_below_thereshold"));
+            .getString("label.threshold_feature_below_threshold"));
   }
 
   public jalview.datamodel.AlignmentAnnotation getCurrentAnnotation()
index 3c04ccd..0e85017 100644 (file)
@@ -191,11 +191,11 @@ public class FeatureColourChooser extends Panel implements ActionListener,
     jPanel4.setBackground(Color.white);
     threshold.addItemListener(this);
     threshold.addItem(MessageManager
-            .getString("label.threshold_feature_no_thereshold"));
+            .getString("label.threshold_feature_no_threshold"));
     threshold.addItem(MessageManager
-            .getString("label.threshold_feature_above_thereshold"));
+            .getString("label.threshold_feature_above_threshold"));
     threshold.addItem(MessageManager
-            .getString("label.threshold_feature_below_thereshold"));
+            .getString("label.threshold_feature_below_threshold"));
     thresholdValue.addActionListener(this);
     slider.setBackground(Color.white);
     slider.setEnabled(false);
index 3f87549..82736d7 100644 (file)
@@ -70,8 +70,8 @@ public class FeatureRenderer extends
    */
   public FeatureRenderer(AlignmentViewport av)
   {
-    super();
-    this.av = av;
+    super(av);
+
   }
 
   static String lastFeatureAdded;
@@ -251,23 +251,24 @@ public class FeatureRenderer extends
 
     tmp = new Panel();
     panel.add(tmp);
-    tmp.add(new Label("Name: ", Label.RIGHT));
+    tmp.add(new Label(MessageManager.getString("label.name:"), Label.RIGHT));
     tmp.add(name);
 
     tmp = new Panel();
     panel.add(tmp);
-    tmp.add(new Label("Group: ", Label.RIGHT));
+    tmp.add(new Label(MessageManager.getString("label.group:"), Label.RIGHT));
     tmp.add(source);
 
     tmp = new Panel();
     panel.add(tmp);
-    tmp.add(new Label("Colour: ", Label.RIGHT));
+    tmp.add(new Label(MessageManager.getString("label.colour"), Label.RIGHT));
     tmp.add(colourPanel);
 
     bigPanel.add(panel, BorderLayout.NORTH);
 
     panel = new Panel();
-    panel.add(new Label("Description: ", Label.RIGHT));
+    panel.add(new Label(MessageManager.getString("label.description:"),
+            Label.RIGHT));
     panel.add(new ScrollPane().add(description));
 
     if (!newFeatures)
@@ -275,9 +276,11 @@ public class FeatureRenderer extends
       bigPanel.add(panel, BorderLayout.SOUTH);
 
       panel = new Panel();
-      panel.add(new Label(" Start:", Label.RIGHT));
+      panel.add(new Label(MessageManager.getString("label.start"),
+              Label.RIGHT));
       panel.add(start);
-      panel.add(new Label("  End:", Label.RIGHT));
+      panel.add(new Label(MessageManager.getString("label.end"),
+              Label.RIGHT));
       panel.add(end);
       bigPanel.add(panel, BorderLayout.CENTER);
     }
index bfac241..9733c86 100755 (executable)
@@ -763,28 +763,31 @@ public class FeatureSettings extends Panel implements ItemListener,
     public void paint(Graphics g)
     {
       Dimension d = getSize();
-      if (col.isColourByLabel())
+      if (col != null)
       {
-        g.setColor(Color.white);
-        g.fillRect(d.width / 2, 0, d.width / 2, d.height);
-        /*
-         * g.setColor(Color.black); Font f=g.getFont().deriveFont(9);
-         * g.setFont(f);
-         * 
-         * // g.setFont(g.getFont().deriveFont( //
-         * AffineTransform.getScaleInstance( //
-         * width/g.getFontMetrics().stringWidth("Label"), //
-         * height/g.getFontMetrics().getHeight()))); g.drawString("Label",
-         * width/2, 0);
-         */
+        if (col.isColourByLabel())
+        {
+          g.setColor(Color.white);
+          g.fillRect(d.width / 2, 0, d.width / 2, d.height);
+          /*
+           * g.setColor(Color.black); Font f=g.getFont().deriveFont(9);
+           * g.setFont(f);
+           * 
+           * // g.setFont(g.getFont().deriveFont( //
+           * AffineTransform.getScaleInstance( //
+           * width/g.getFontMetrics().stringWidth("Label"), //
+           * height/g.getFontMetrics().getHeight()))); g.drawString("Label",
+           * width/2, 0);
+           */
 
-      }
-      else if (col.isGraduatedColour())
-      {
-        Color maxCol = col.getMaxColour();
-        g.setColor(maxCol);
-        g.fillRect(d.width / 2, 0, d.width / 2, d.height);
+        }
+        else if (col.isGraduatedColour())
+        {
+          Color maxCol = col.getMaxColour();
+          g.setColor(maxCol);
+          g.fillRect(d.width / 2, 0, d.width / 2, d.height);
 
+        }
       }
 
       if (hasLink)
index bc64728..9b2be4c 100755 (executable)
@@ -265,7 +265,8 @@ public class OverviewPanel extends Panel implements Runnable,
   {
     miniMe = null;
     int alwidth = av.getAlignment().getWidth();
-    int alheight = av.getAlignment().getHeight();
+    int alheight = av.getAlignment().getHeight()
+            + av.getAlignment().getHiddenSequences().getSize();
 
     if (av.isShowSequenceFeatures())
     {
@@ -304,6 +305,10 @@ public class OverviewPanel extends Panel implements Runnable,
     AlignmentI alignment = av.getAlignment();
     for (row = 0; row <= sequencesHeight; row++)
     {
+      if (resizeAgain)
+      {
+        break;
+      }
       if ((int) (row * sampleRow) == lastrow)
       {
         sameRow++;
@@ -385,6 +390,10 @@ public class OverviewPanel extends Panel implements Runnable,
     {
       for (col = 0; col < width; col++)
       {
+        if (resizeAgain)
+        {
+          break;
+        }
         lastcol = (int) (col * sampleCol);
         {
           mg.translate(col, sequencesHeight);
index 71ecb13..d2c1693 100755 (executable)
@@ -22,6 +22,8 @@ package jalview.appletgui;
 
 import jalview.datamodel.ColumnSelection;
 import jalview.datamodel.SequenceGroup;
+import jalview.renderer.ScaleRenderer;
+import jalview.renderer.ScaleRenderer.ScaleMark;
 import jalview.util.MessageManager;
 
 import java.awt.Color;
@@ -36,6 +38,7 @@ import java.awt.event.InputEvent;
 import java.awt.event.MouseEvent;
 import java.awt.event.MouseListener;
 import java.awt.event.MouseMotionListener;
+import java.util.List;
 
 public class ScalePanel extends Panel implements MouseMotionListener,
         MouseListener
@@ -406,64 +409,69 @@ public class ScalePanel extends Panel implements MouseMotionListener,
 
     // Fill the selected columns
     ColumnSelection cs = av.getColumnSelection();
-    gg.setColor(new Color(220, 0, 0));
-    int avcharWidth = av.getCharWidth(), avcharHeight = av.getCharHeight();
-    for (int sel : cs.getSelected())
+    int avCharWidth = av.getCharWidth();
+    int avcharHeight = av.getCharHeight();
+    if (cs != null)
     {
-      // TODO: JAL-2001 - provide a fast method to list visible selected in a
-      // given range
-      if (av.hasHiddenColumns())
+      gg.setColor(new Color(220, 0, 0));
+      boolean hasHiddenColumns = cs.hasHiddenColumns();
+      for (int sel : cs.getSelected())
       {
-        sel = av.getColumnSelection().findColumnPosition(sel);
-      }
+        // TODO: JAL-2001 - provide a fast method to list visible selected in a
+        // given range
+        if (hasHiddenColumns)
+        {
+          if (cs.isVisible(sel))
+          {
+            sel = cs.findColumnPosition(sel);
+          }
+          else
+          {
+            continue;
+          }
+        }
 
-      if ((sel >= startx) && (sel <= endx))
-      {
-        gg.fillRect((sel - startx) * avcharWidth, 0, avcharWidth,
-                getSize().height);
+        if ((sel >= startx) && (sel <= endx))
+        {
+          gg.fillRect((sel - startx) * avCharWidth, 0, avCharWidth,
+                  getSize().height);
+        }
       }
     }
 
     // Draw the scale numbers
     gg.setColor(Color.black);
 
-    int scalestartx = (startx / 10) * 10;
-    int widthx = 1 + endx - startx;
-
-    FontMetrics fm = gg.getFontMetrics(av.getFont());
-    int y = avcharHeight - fm.getDescent();
-
-    if ((scalestartx % 10) == 0)
-    {
-      scalestartx += 5;
-    }
-
-    String string;
     int maxX = 0;
+    List<ScaleMark> marks = new ScaleRenderer().calculateMarks(av, startx,
+            endx);
 
-    for (int i = scalestartx; i < endx; i += 5)
+    FontMetrics fm = gg.getFontMetrics(av.getFont());
+    int y = avcharHeight;
+    int yOf = fm.getDescent();
+    y -= yOf;
+    for (ScaleMark mark : marks)
     {
-      if ((i % 10) == 0)
+      boolean major = mark.major;
+      int mpos = mark.column; // (i - startx - 1)
+      String mstring = mark.text;
+      if (mstring != null)
       {
-        string = String.valueOf(av.getColumnSelection()
-                .adjustForHiddenColumns(i));
-        if ((i - startx - 1) * avcharWidth > maxX)
+        if (mpos * avCharWidth > maxX)
         {
-          gg.drawString(string, (i - startx - 1) * avcharWidth, y);
-          maxX = (i - startx + 1) * avcharWidth + fm.stringWidth(string);
+          gg.drawString(mstring, mpos * avCharWidth, y);
+          maxX = (mpos + 2) * avCharWidth + fm.stringWidth(mstring);
         }
-
-        gg.drawLine(((i - startx - 1) * avcharWidth) + (avcharWidth / 2),
-                y + 2,
-                ((i - startx - 1) * avcharWidth) + (avcharWidth / 2), y
-                        + (fm.getDescent() * 2));
-
+      }
+      if (major)
+      {
+        gg.drawLine((mpos * avCharWidth) + (avCharWidth / 2), y + 2,
+                (mpos * avCharWidth) + (avCharWidth / 2), y + (yOf * 2));
       }
       else
       {
-        gg.drawLine(((i - startx - 1) * avcharWidth) + (avcharWidth / 2), y
-                + fm.getDescent(), ((i - startx - 1) * avcharWidth)
-                + (avcharWidth / 2), y + (fm.getDescent() * 2));
+        gg.drawLine((mpos * avCharWidth) + (avCharWidth / 2), y + yOf,
+                (mpos * avCharWidth) + (avCharWidth / 2), y + (yOf * 2));
       }
     }
 
@@ -473,33 +481,25 @@ public class ScalePanel extends Panel implements MouseMotionListener,
       int res;
       if (av.getShowHiddenMarkers())
       {
-        for (int i = 0; i < av.getColumnSelection().getHiddenColumns()
-                .size(); i++)
+        int widthx = 1 + endx - startx;
+        for (int i = 0; i < cs.getHiddenColumns().size(); i++)
         {
 
-          res = av.getColumnSelection().findHiddenRegionPosition(i)
-                  - startx;
+          res = cs.findHiddenRegionPosition(i) - startx;
 
           if (res < 0 || res > widthx)
           {
             continue;
           }
 
-          gg.fillPolygon(new int[] { res * avcharWidth - avcharHeight / 4,
-              res * avcharWidth + avcharHeight / 4, res * avcharWidth },
-                  new int[] { y - avcharHeight / 2, y - avcharHeight / 2,
-                      y + 8 }, 3);
-
+          gg.fillPolygon(new int[] {
+              -1 + res * avCharWidth - avcharHeight / 4,
+              -1 + res * avCharWidth + avcharHeight / 4,
+              -1 + res * avCharWidth },
+                  new int[] { y, y, y + 2 * yOf }, 3);
         }
       }
-
-      if (reveal != null && reveal[0] > startx && reveal[0] < endx)
-      {
-        gg.drawString(MessageManager.getString("label.reveal_columns"),
-                reveal[0] * avcharWidth, 0);
-      }
     }
-
   }
 
 }
index 024fdc7..22849f1 100755 (executable)
@@ -24,6 +24,8 @@ import jalview.datamodel.AlignmentI;
 import jalview.datamodel.SearchResults;
 import jalview.datamodel.SequenceGroup;
 import jalview.datamodel.SequenceI;
+import jalview.renderer.ScaleRenderer;
+import jalview.renderer.ScaleRenderer.ScaleMark;
 import jalview.viewmodel.AlignmentViewport;
 
 import java.awt.Color;
@@ -90,26 +92,30 @@ public class SeqCanvas extends Panel
 
   private void drawNorthScale(Graphics g, int startx, int endx, int ypos)
   {
-    int scalestartx = startx - startx % 10 + 10;
-
+    updateViewport();
     g.setColor(Color.black);
-
-    // NORTH SCALE
-    for (int i = scalestartx; i < endx; i += 10)
+    for (ScaleMark mark : new ScaleRenderer().calculateMarks(av, startx,
+            endx))
     {
-      int value = i;
-      if (av.hasHiddenColumns())
+      int mpos = mark.column; // (i - startx - 1)
+      if (mpos < 0)
       {
-        value = av.getColumnSelection().adjustForHiddenColumns(value);
+        continue;
       }
+      String mstring = mark.text;
 
-      g.drawString(String.valueOf(value), (i - startx - 1) * avcharWidth,
-              ypos - (avcharHeight / 2));
-
-      g.drawLine(((i - startx - 1) * avcharWidth) + (avcharWidth / 2),
-              (ypos + 2) - (avcharHeight / 2),
-              ((i - startx - 1) * avcharWidth) + (avcharWidth / 2),
-              ypos - 2);
+      if (mark.major)
+      {
+        if (mstring != null)
+        {
+          g.drawString(mstring, mpos * avcharWidth, ypos
+                  - (avcharHeight / 2));
+        }
+        g.drawLine((mpos * avcharWidth) + (avcharWidth / 2), (ypos + 2)
+                - (avcharHeight / 2), (mpos * avcharWidth)
+                + (avcharWidth / 2),
+                ypos - 2);
+      }
     }
   }
 
index 31bf6a4..02172d6 100644 (file)
@@ -919,6 +919,21 @@ public class SeqPanel extends Panel implements MouseMotionListener,
 
   Tooltip tooltip;
 
+  /**
+   * set when the current UI interaction has resulted in a change that requires
+   * overview shading to be recalculated. this could be changed to something
+   * more expressive that indicates what actually has changed, so selective
+   * redraws can be applied
+   */
+  private boolean needOverviewUpdate; // TODO: refactor to avcontroller
+
+  /**
+   * set if av.getSelectionGroup() refers to a group that is defined on the
+   * alignment view, rather than a transient selection
+   */
+  private boolean editingDefinedGroup = false; // TODO: refactor to avcontroller
+                                               // or viewModel
+
   @Override
   public void mouseDragged(MouseEvent evt)
   {
@@ -1421,10 +1436,12 @@ public class SeqPanel extends Panel implements MouseMotionListener,
               && res < stretchGroup.getEndRes())
       {
         av.setSelectionGroup(stretchGroup);
+        editingDefinedGroup = true;
       }
       else
       {
         stretchGroup = null;
+        editingDefinedGroup = false;
       }
     }
 
@@ -1444,6 +1461,7 @@ public class SeqPanel extends Panel implements MouseMotionListener,
                   && allGroups[i].getEndRes() >= res)
           {
             stretchGroup = allGroups[i];
+            editingDefinedGroup = true;
             break;
           }
         }
@@ -1499,6 +1517,7 @@ public class SeqPanel extends Panel implements MouseMotionListener,
       sg.setEndRes(res);
       sg.addSequence(sequence, false);
       av.setSelectionGroup(sg);
+      editingDefinedGroup = false;
       stretchGroup = sg;
 
       if (av.getConservationSelected())
@@ -1521,9 +1540,10 @@ public class SeqPanel extends Panel implements MouseMotionListener,
     {
       return;
     }
-
-    stretchGroup.recalcConservation(); // always do this - annotation has own
-                                       // state
+    // always do this - annotation has own state
+    // but defer colourscheme update until hidden sequences are passed in
+    boolean vischange = stretchGroup.recalcConservation(true);
+    needOverviewUpdate |= vischange && editingDefinedGroup;
     if (stretchGroup.cs != null)
     {
       stretchGroup.cs.alignmentChanged(stretchGroup,
@@ -1540,11 +1560,13 @@ public class SeqPanel extends Panel implements MouseMotionListener,
                 stretchGroup.getName());
       }
     }
+    PaintRefresher.Refresh(ap, av.getSequenceSetId());
+    ap.paintAlignment(needOverviewUpdate);
+    needOverviewUpdate =false;
+    editingDefinedGroup = false;
     changeEndRes = false;
     changeStartRes = false;
     stretchGroup = null;
-    PaintRefresher.Refresh(ap, av.getSequenceSetId());
-    ap.paintAlignment(true);
     av.sendSelection();
   }
 
@@ -1596,6 +1618,7 @@ public class SeqPanel extends Panel implements MouseMotionListener,
       if (res > (stretchGroup.getStartRes() - 1))
       {
         stretchGroup.setEndRes(res);
+        needOverviewUpdate |= editingDefinedGroup;
       }
     }
     else if (changeStartRes)
@@ -1603,6 +1626,7 @@ public class SeqPanel extends Panel implements MouseMotionListener,
       if (res < (stretchGroup.getEndRes() + 1))
       {
         stretchGroup.setStartRes(res);
+        needOverviewUpdate |= editingDefinedGroup;
       }
     }
 
@@ -1636,6 +1660,7 @@ public class SeqPanel extends Panel implements MouseMotionListener,
       if (stretchGroup.getSequences(null).contains(nextSeq))
       {
         stretchGroup.deleteSequence(seq, false);
+        needOverviewUpdate |= editingDefinedGroup;
       }
       else
       {
@@ -1645,6 +1670,7 @@ public class SeqPanel extends Panel implements MouseMotionListener,
         }
 
         stretchGroup.addSequence(nextSeq, false);
+        needOverviewUpdate |= editingDefinedGroup;
       }
     }
 
index 2fc15d0..2c53c08 100644 (file)
@@ -132,7 +132,7 @@ public class SliderPanel extends Panel implements ActionListener,
       pid.cs = cs;
     }
     PIDSlider.setTitle(MessageManager
-            .formatMessage("label.percentage_identity_thereshold",
+            .formatMessage("label.percentage_identity_threshold",
                     new String[] { source }));
 
     if (ap.av.getAlignment().getGroups() != null)
index cf251dc..df71ccc 100755 (executable)
@@ -20,7 +20,7 @@
  */
 package jalview.bin;
 
-import jalview.datamodel.DBRefSource;
+import jalview.datamodel.PDBEntry;
 import jalview.structure.StructureImportSettings;
 import jalview.ws.dbsources.das.api.DasSourceRegistryI;
 import jalview.ws.dbsources.das.datamodel.DasSourceRegistry;
@@ -38,6 +38,7 @@ import java.text.SimpleDateFormat;
 import java.util.Collections;
 import java.util.Date;
 import java.util.Enumeration;
+import java.util.Locale;
 import java.util.Properties;
 import java.util.TreeSet;
 
@@ -227,8 +228,24 @@ public class Cache
   private final static String DEFAULT_CACHE_THRESHOLD_IN_DAYS = "2";
 
   private final static String DEFAULT_FAIL_SAFE_PID_THRESHOLD = "30";
+  
+  /**
+   * Allowed values are PDB or mmCIF
+   */
+  private final static String DEFAULT_STRUCTURE_FORMAT = PDBEntry.Type.MMCIF
+          .toString();
+
+  private final static String DEFAULT_PDB_FILE_PARSER = StructureImportSettings.StructureParser.JMOL_PARSER
+          .toString();
 
-  private final static String DEFAULT_STRUCTURE_FORMAT = DBRefSource.PDB;
+  /*
+   * a date formatter using a fixed (rather than the user's) locale; 
+   * this ensures that date properties can be written and re-read successfully
+   * even if the user changes their locale setting
+   */
+  private static final DateFormat date_format = SimpleDateFormat
+          .getDateTimeInstance(SimpleDateFormat.MEDIUM,
+                  SimpleDateFormat.MEDIUM, Locale.UK);
 
   /**
    * Initialises the Jalview Application Log
@@ -426,12 +443,12 @@ public class Cache
     System.out
             .println("Jalview Version: " + codeVersion + codeInstallation);
 
-    StructureImportSettings.setCurrentDefaultFormat(jalview.bin.Cache
+    StructureImportSettings.setDefaultStructureFileFormat(jalview.bin.Cache
             .getDefault(
             "DEFAULT_STRUCTURE_FORMAT", DEFAULT_STRUCTURE_FORMAT));
-
-    StructureImportSettings.setProcessHETATMs(jalview.bin.Cache.getDefault(
-            "PROCESS_HETATM", false));
+    StructureImportSettings
+            .setDefaultPDBFileParser(jalview.bin.Cache.getDefault(
+                    "DEFAULT_PDB_FILE_PARSER", DEFAULT_PDB_FILE_PARSER));
     // jnlpVersion will be null if we're using InstallAnywhere
     // Dont do this check if running in headless mode
     if (jnlpVersion == null
@@ -877,31 +894,32 @@ public class Cache
   {
     setProperty(property, jalview.util.Format.getHexString(colour));
   }
-
-  public static final DateFormat date_format = SimpleDateFormat
-          .getDateTimeInstance();
-
+  
   /**
-   * store a date in a jalview property
+   * Stores a formatted date in a jalview property, using a fixed locale.
    * 
-   * @param string
-   * @param time
+   * @param propertyName
+   * @param date
+   * @return the formatted date string
    */
-  public static void setDateProperty(String property, Date time)
+  public static String setDateProperty(String propertyName, Date date)
   {
-    setProperty(property, date_format.format(time));
+    String formatted = date_format.format(date);
+    setProperty(propertyName, formatted);
+    return formatted;
   }
 
   /**
-   * read a date stored in a jalview property
+   * Reads a date stored in a Jalview property, parses it (using a fixed locale
+   * format) and returns as a Date, or null if parsing fails
    * 
-   * @param property
-   * @return valid date as stored by setDateProperty, or null
+   * @param propertyName
+   * @return
    * 
    */
-  public static Date getDateProperty(String property)
+  public static Date getDateProperty(String propertyName)
   {
-    String val = getProperty(property);
+    String val = getProperty(propertyName);
     if (val != null)
     {
       try
@@ -910,7 +928,7 @@ public class Cache
       } catch (Exception ex)
       {
         System.err.println("Invalid or corrupt date in property '"
-                + property + "' : value was '" + val + "'");
+                + propertyName + "' : value was '" + val + "'");
       }
     }
     return null;
index cd4d138..1ab837f 100755 (executable)
@@ -331,7 +331,6 @@ public class Jalview
             Cache.log.debug("Starting questionnaire with default url: "
                     + defurl);
             desktop.checkForQuestionnaire(defurl);
-
           }
         }
       }
@@ -339,11 +338,12 @@ public class Jalview
       {
         System.err.println("CMD [-noquestionnaire] executed successfully!");
       }
-      desktop.checkForNews();
-    }
 
-    if (!isHeadlessMode())
-    {
+      if (!aparser.contains("nonews"))
+      {
+        desktop.checkForNews();
+      }
+
       BioJsHTMLOutput.updateBioJS();
     }
 
@@ -799,6 +799,7 @@ public class Jalview
                     + "-eps FILE\tCreate EPS file FILE from alignment.\n"
                     + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
                     + "-noquestionnaire\tTurn off questionnaire check.\n"
+                    + "-nonews\tTurn off check for Jalview news.\n"
                     + "-nousagestats\tTurn off google analytics tracking for this session.\n"
                     + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
                     // +
index 0f3feb2..7f15b3e 100644 (file)
@@ -38,6 +38,7 @@ import jalview.datamodel.SequenceI;
 import jalview.io.AnnotationFile;
 import jalview.io.AppletFormatAdapter;
 import jalview.io.DataSourceType;
+import jalview.io.FileFormat;
 import jalview.io.FileFormatI;
 import jalview.io.FileParse;
 import jalview.io.IdentifyFile;
@@ -469,17 +470,11 @@ public class JalviewLite extends Applet implements
         SequenceI rs = sel.getSequenceAt(0);
         start = rs.findIndex(start);
         end = rs.findIndex(end);
-        if (csel != null)
-        {
-          List<Integer> cs = csel.getSelected();
-          // note - the following actually clears cs as well, since
-          // csel.getSelected returns a reference. Need to check if we need to
-          // have a concurrentModification exception thrown here
-          csel.clear();
-          for (Integer selectedCol : cs)
-          {
-            csel.addElement(rs.findIndex(selectedCol));
-          }
+        List<Integer> cs = csel.getSelected();
+        csel.clear();
+        for (Integer selectedCol : cs)
+        {
+          csel.addElement(rs.findIndex(selectedCol));
         }
       }
       sel.setStartRes(start);
@@ -518,25 +513,27 @@ public class JalviewLite extends Applet implements
    */
   @Override
   public String getSelectedSequencesAsAlignmentFrom(AlignFrame alf,
-          FileFormatI format, String suffix)
+          String format, String suffix)
   {
     try
     {
+      FileFormatI theFormat = FileFormat.valueOf(format);
       boolean seqlimits = suffix.equalsIgnoreCase(TRUE);
       if (alf.viewport.getSelectionGroup() != null)
       {
         // JBPNote: getSelectionAsNewSequence behaviour has changed - this
         // method now returns a full copy of sequence data
         // TODO consider using getSequenceSelection instead here
-        String reply = new AppletFormatAdapter().formatSequences(format,
+        String reply = new AppletFormatAdapter().formatSequences(theFormat,
                 new Alignment(alf.viewport.getSelectionAsNewSequence()),
                 seqlimits);
         return reply;
       }
-    } catch (Exception ex)
+    } catch (IllegalArgumentException ex)
     {
       ex.printStackTrace();
-      return "Error retrieving alignment in " + format + " format. ";
+      return "Error retrieving alignment, possibly invalid format specifier: "
+              + format;
     }
     return "";
   }
@@ -718,13 +715,15 @@ public class JalviewLite extends Applet implements
     {
       boolean seqlimits = suffix.equalsIgnoreCase(TRUE);
 
-      String reply = new AppletFormatAdapter().formatSequences(format,
+      FileFormatI theFormat = FileFormat.valueOf(format);
+      String reply = new AppletFormatAdapter().formatSequences(theFormat,
               alf.viewport.getAlignment(), seqlimits);
       return reply;
-    } catch (Exception ex)
+    } catch (IllegalArgumentException ex)
     {
       ex.printStackTrace();
-      return "Error retrieving alignment in " + format + " format. ";
+      return "Error retrieving alignment, possibly invalid format specifier: "
+              + format;
     }
   }
 
index e1fdbfc..7d60dc8 100644 (file)
@@ -170,157 +170,136 @@ public class AlignViewController implements AlignViewControllerI
     // JBPNote this routine could also mark rows, not just columns.
     // need a decent query structure to allow all types of feature searches
     BitSet bs = new BitSet();
-    int alw, alStart;
-    SequenceCollectionI sqcol = (viewport.getSelectionGroup() == null ? viewport
-            .getAlignment() : viewport.getSelectionGroup());
-    alStart = sqcol.getStartRes();
-    alw = sqcol.getEndRes() + 1;
+    SequenceCollectionI sqcol = (viewport.getSelectionGroup() == null || extendCurrent) ? viewport
+            .getAlignment() : viewport.getSelectionGroup();
+
+    int nseq = findColumnsWithFeature(featureType, sqcol, bs);
+
+    ColumnSelection cs = viewport.getColumnSelection();
+    if (cs == null)
+    {
+      cs = new ColumnSelection();
+    }
+
+    if (bs.cardinality() > 0 || invert)
+    {
+      boolean changed = cs.markColumns(bs, sqcol.getStartRes(),
+              sqcol.getEndRes(), invert, extendCurrent, toggle);
+      if (changed)
+      {
+        viewport.setColumnSelection(cs);
+        alignPanel.paintAlignment(true);
+        int columnCount = invert ? (sqcol.getEndRes() - sqcol.getStartRes() + 1)
+                - bs.cardinality()
+                : bs.cardinality();
+        avcg.setStatus(MessageManager.formatMessage(
+                "label.view_controller_toggled_marked",
+                new String[] {
+                    toggle ? MessageManager.getString("label.toggled")
+                            : MessageManager.getString("label.marked"),
+                    String.valueOf(columnCount),
+                    invert ? MessageManager
+                            .getString("label.not_containing")
+                            : MessageManager.getString("label.containing"),
+                    featureType, Integer.valueOf(nseq).toString() }));
+        return true;
+      }
+    }
+    else
+    {
+      avcg.setStatus(MessageManager.formatMessage(
+              "label.no_feature_of_type_found",
+              new String[] { featureType }));
+      if (!extendCurrent)
+      {
+        cs.clear();
+        alignPanel.paintAlignment(true);
+      }
+    }
+    return false;
+  }
+
+  /**
+   * Sets a bit in the BitSet for each column (base 0) in the sequence
+   * collection which includes the specified feature type. Returns the number of
+   * sequences which have the feature in the selected range.
+   * 
+   * @param featureType
+   * @param sqcol
+   * @param bs
+   * @return
+   */
+  static int findColumnsWithFeature(String featureType,
+          SequenceCollectionI sqcol, BitSet bs)
+  {
+    final int startPosition = sqcol.getStartRes() + 1; // converted to base 1
+    final int endPosition = sqcol.getEndRes() + 1;
     List<SequenceI> seqs = sqcol.getSequences();
     int nseq = 0;
     for (SequenceI sq : seqs)
     {
-      int tfeat = 0;
+      boolean sequenceHasFeature = false;
       if (sq != null)
       {
-        SequenceFeature[] sf = sq.getSequenceFeatures();
-        if (sf != null)
+        SequenceFeature[] sfs = sq.getSequenceFeatures();
+        if (sfs != null)
         {
+          /*
+           * check whether the feature start/end (base 1) 
+           * overlaps the selection start/end
+           */
           int ist = sq.findIndex(sq.getStart());
           int iend = sq.findIndex(sq.getEnd());
-          if (iend < alStart || ist > alw)
+          if (iend < startPosition || ist > endPosition)
           {
             // sequence not in region
             continue;
           }
-          for (SequenceFeature sfpos : sf)
+          for (SequenceFeature sf : sfs)
           {
-            // future functionalty - featureType == null means mark columns
+            // future functionality - featureType == null means mark columns
             // containing all displayed features
-            if (sfpos != null && (featureType.equals(sfpos.getType())))
+            if (sf != null && (featureType.equals(sf.getType())))
             {
-              tfeat++;
               // optimisation - could consider 'spos,apos' like cursor argument
               // - findIndex wastes time by starting from first character and
               // counting
 
-              int i = sq.findIndex(sfpos.getBegin());
-              int j = sq.findIndex(sfpos.getEnd());
-              if (j < alStart || i > alw)
+              int i = sq.findIndex(sf.getBegin());
+              int j = sq.findIndex(sf.getEnd());
+              if (j < startPosition || i > endPosition)
               {
                 // feature is outside selected region
                 continue;
               }
-              if (i < alStart)
+              sequenceHasFeature = true;
+              if (i < startPosition)
               {
-                i = alStart;
+                i = startPosition;
               }
               if (i < ist)
               {
                 i = ist;
               }
-              if (j > alw)
+              if (j > endPosition)
               {
-                j = alw;
+                j = endPosition;
               }
               for (; i <= j; i++)
               {
-                bs.set(i - 1);
+                bs.set(i - 1); // convert to base 0
               }
             }
           }
         }
 
-        if (tfeat > 0)
+        if (sequenceHasFeature)
         {
           nseq++;
         }
       }
     }
-    ColumnSelection cs = viewport.getColumnSelection();
-    if (bs.cardinality() > 0 || invert)
-    {
-      boolean changed = false;
-      if (cs == null)
-      {
-        cs = new ColumnSelection();
-      }
-      else
-      {
-        if (!extendCurrent)
-        {
-          changed = !cs.isEmpty();
-          cs.clear();
-        }
-      }
-      if (invert)
-      {
-        // invert only in the currently selected sequence region
-        for (int i = bs.nextClearBit(alStart), ibs = bs.nextSetBit(alStart); i >= alStart
-                && i < (alw);)
-        {
-          if (ibs < 0 || i < ibs)
-          {
-            changed = true;
-            if (toggle && cs.contains(i))
-            {
-              cs.removeElement(i++);
-            }
-            else
-            {
-              cs.addElement(i++);
-            }
-          }
-          else
-          {
-            i = bs.nextClearBit(ibs);
-            ibs = bs.nextSetBit(i);
-          }
-        }
-      }
-      else
-      {
-        for (int i = bs.nextSetBit(alStart); i >= alStart; i = bs
-                .nextSetBit(i + 1))
-        {
-          changed = true;
-          if (toggle && cs.contains(i))
-          {
-            cs.removeElement(i);
-          }
-          else
-          {
-            cs.addElement(i);
-          }
-        }
-      }
-      if (changed)
-      {
-        viewport.setColumnSelection(cs);
-        alignPanel.paintAlignment(true);
-        avcg.setStatus(MessageManager.formatMessage(
-                "label.view_controller_toggled_marked",
-                new String[] {
-                    (toggle ? MessageManager.getString("label.toggled")
-                            : MessageManager.getString("label.marked")),
-                    (invert ? (Integer.valueOf((alw - alStart)
-                            - bs.cardinality()).toString()) : (Integer
-                            .valueOf(bs.cardinality()).toString())),
-                    featureType, Integer.valueOf(nseq).toString() }));
-        return true;
-      }
-    }
-    else
-    {
-      avcg.setStatus(MessageManager.formatMessage(
-              "label.no_feature_of_type_found",
-              new String[] { featureType }));
-      if (!extendCurrent && cs != null)
-      {
-        cs.clear();
-        alignPanel.paintAlignment(true);
-      }
-    }
-    return false;
+    return nseq;
   }
 
   @Override
index 6d6cdb5..326cc4e 100644 (file)
@@ -23,6 +23,7 @@ package jalview.datamodel;
 import jalview.util.MapList;
 import jalview.util.MappingUtils;
 
+import java.util.AbstractList;
 import java.util.ArrayList;
 import java.util.List;
 
@@ -36,7 +37,7 @@ public class AlignedCodonFrame
   /*
    * Data bean to hold mappings from one sequence to another
    */
-  private class SequenceToSequenceMapping
+  public class SequenceToSequenceMapping
   {
     private SequenceI fromSeq;
 
@@ -57,6 +58,54 @@ public class AlignedCodonFrame
       return String.format("From %s %s", fromSeq.getName(),
               mapping.toString());
     }
+
+    /**
+     * Returns a hashCode derived from the hashcodes of the mappings and fromSeq
+     * 
+     * @see SequenceToSequenceMapping#hashCode()
+     */
+    @Override
+    public int hashCode()
+    {
+      return (fromSeq == null ? 0 : fromSeq.hashCode() * 31)
+              + mapping.hashCode();
+    }
+
+    /**
+     * Answers true if the objects hold the same mapping between the same two
+     * sequences
+     * 
+     * @see Mapping#equals
+     */
+    @Override
+    public boolean equals(Object obj)
+    {
+      if (!(obj instanceof SequenceToSequenceMapping))
+      {
+        return false;
+      }
+      SequenceToSequenceMapping that = (SequenceToSequenceMapping) obj;
+      if (this.mapping == null)
+      {
+        return that.mapping == null;
+      }
+      // TODO: can simplify by asserting fromSeq is a dataset sequence
+      return (this.fromSeq == that.fromSeq || (this.fromSeq != null
+              && that.fromSeq != null
+              && this.fromSeq.getDatasetSequence() != null && this.fromSeq
+              .getDatasetSequence() == that.fromSeq
+              .getDatasetSequence())) && this.mapping.equals(that.mapping);
+    }
+
+    public SequenceI getFromSeq()
+    {
+      return fromSeq;
+    }
+
+    public Mapping getMapping()
+    {
+      return mapping;
+    }
   }
 
   private List<SequenceToSequenceMapping> mappings;
@@ -79,6 +128,21 @@ public class AlignedCodonFrame
    */
   public void addMap(SequenceI dnaseq, SequenceI aaseq, MapList map)
   {
+    addMap(dnaseq, aaseq, map, null);
+  }
+
+  /**
+   * Adds a mapping between the dataset sequences for the associated dna and
+   * protein sequence objects
+   * 
+   * @param dnaseq
+   * @param aaseq
+   * @param map
+   * @param mapFromId
+   */
+  public void addMap(SequenceI dnaseq, SequenceI aaseq, MapList map,
+          String mapFromId)
+  {
     // JBPNote DEBUG! THIS !
     // dnaseq.transferAnnotation(aaseq, mp);
     // aaseq.transferAnnotation(dnaseq, new Mapping(map.getInverse()));
@@ -90,6 +154,8 @@ public class AlignedCodonFrame
 
     /*
      * if we already hold a mapping between these sequences, just add to it 
+     * note that 'adding' a duplicate map does nothing; this protects against
+     * creating duplicate mappings in AlignedCodonFrame
      */
     for (SequenceToSequenceMapping ssm : mappings)
     {
@@ -104,6 +170,7 @@ public class AlignedCodonFrame
      * otherwise, add a new sequence mapping
      */
     Mapping mp = new Mapping(toSeq, map);
+    mp.setMappedFromId(mapFromId);
     mappings.add(new SequenceToSequenceMapping(fromSeq, mp));
   }
 
@@ -421,7 +488,8 @@ public class AlignedCodonFrame
 
     for (SequenceToSequenceMapping ssm : mappings)
     {
-      if (ssm.mapping.to == protein)
+      if (ssm.mapping.to == protein
+              && ssm.mapping.getMap().getFromRatio() == 3)
       {
         ml = ssm.mapping.map;
         dnaSeq = ssm.fromSeq;
@@ -651,7 +719,7 @@ public class AlignedCodonFrame
   }
 
   /**
-   * Returns the first mapping found that is from 'fromSeq' to 'toSeq', or null
+   * Returns the first mapping found that is between 'fromSeq' and 'toSeq', or null
    * if none found
    * 
    * @param fromSeq
@@ -662,16 +730,54 @@ public class AlignedCodonFrame
    */
   public Mapping getMappingBetween(SequenceI fromSeq, SequenceI toSeq)
   {
+    SequenceI dssFrom = fromSeq.getDatasetSequence() == null ? fromSeq
+            : fromSeq.getDatasetSequence();
+    SequenceI dssTo = toSeq.getDatasetSequence() == null ? toSeq : toSeq
+            .getDatasetSequence();
+
     for (SequenceToSequenceMapping mapping : mappings)
     {
       SequenceI from = mapping.fromSeq;
       SequenceI to = mapping.mapping.to;
-      if ((from == fromSeq || from == fromSeq.getDatasetSequence())
-              && (to == toSeq || to == toSeq.getDatasetSequence()))
+      if ((from == dssFrom && to == dssTo)
+              || (from == dssTo && to == dssFrom))
       {
         return mapping.mapping;
       }
     }
     return null;
   }
+
+  /**
+   * Returns a hashcode derived from the list of sequence mappings
+   * 
+   * @see SequenceToSequenceMapping#hashCode()
+   * @see AbstractList#hashCode()
+   */
+  @Override
+  public int hashCode()
+  {
+    return this.mappings.hashCode();
+  }
+
+  /**
+   * Two AlignedCodonFrame objects are equal if they hold the same ordered list
+   * of mappings
+   * 
+   * @see SequenceToSequenceMapping#
+   */
+  @Override
+  public boolean equals(Object obj)
+  {
+    if (!(obj instanceof AlignedCodonFrame))
+    {
+      return false;
+    }
+    return this.mappings.equals(((AlignedCodonFrame) obj).mappings);
+  }
+
+  public List<SequenceToSequenceMapping> getMappings()
+  {
+    return mappings;
+  }
 }
index f14539b..286e284 100755 (executable)
@@ -30,7 +30,6 @@ import java.util.Collections;
 import java.util.Enumeration;
 import java.util.HashSet;
 import java.util.Hashtable;
-import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
@@ -45,7 +44,7 @@ import java.util.Vector;
  */
 public class Alignment implements AlignmentI
 {
-  protected Alignment dataset;
+  private Alignment dataset;
 
   protected List<SequenceI> sequences;
 
@@ -110,7 +109,10 @@ public class Alignment implements AlignmentI
     /*
      * Share the same dataset sequence mappings (if any). 
      */
-    this.setCodonFrames(al.getCodonFrames());
+    if (dataset == null && al.getDataset() == null)
+    {
+      this.setCodonFrames(al.getCodonFrames());
+    }
   }
 
   /**
@@ -987,7 +989,7 @@ public class Alignment implements AlignmentI
   }
 
   @Override
-  public void setDataset(Alignment data)
+  public void setDataset(AlignmentI data)
   {
     if (dataset == null && data == null)
     {
@@ -995,7 +997,12 @@ public class Alignment implements AlignmentI
     }
     else if (dataset == null && data != null)
     {
-      dataset = data;
+      if (!(data instanceof Alignment))
+      {
+        throw new Error(
+                "Implementation Error: jalview.datamodel.Alignment does not yet support other implementations of AlignmentI as its dataset reference");
+      }
+      dataset = (Alignment) data;
       for (int i = 0; i < getHeight(); i++)
       {
         SequenceI currentSeq = getSequenceAt(i);
@@ -1288,22 +1295,6 @@ public class Alignment implements AlignmentI
     }
   }
 
-  /**
-   * adds a set of mappings (while ignoring any duplicates)
-   */
-  @Override
-  public void addCodonFrames(Iterable<AlignedCodonFrame> codons)
-  {
-    if (codons != null)
-    {
-      Iterator<AlignedCodonFrame> it = codons.iterator();
-      while (it.hasNext())
-      {
-        addCodonFrame(it.next());
-      }
-    }
-  }
-
   /*
    * (non-Javadoc)
    * 
@@ -1357,6 +1348,10 @@ public class Alignment implements AlignmentI
   @Override
   public List<AlignedCodonFrame> getCodonFrames()
   {
+    // TODO: Fix this method to fix failing AlignedCodonFrame tests
+    // this behaviour is currently incorrect. method should return codon frames
+    // for just the alignment,
+    // selected from dataset
     return dataset != null ? dataset.getCodonFrames() : codonFrameList;
   }
 
@@ -1378,11 +1373,7 @@ public class Alignment implements AlignmentI
   @Override
   public void append(AlignmentI toappend)
   {
-    if (toappend == this)
-    {
-      System.err.println("Self append may cause a deadlock.");
-    }
-    // TODO test this method for a future 2.5 release
+    // TODO JAL-1270 needs test coverage
     // currently tested for use in jalview.gui.SequenceFetcher
     boolean samegap = toappend.getGapCharacter() == getGapCharacter();
     char oldc = toappend.getGapCharacter();
@@ -1393,6 +1384,8 @@ public class Alignment implements AlignmentI
             .getFullAlignment().getSequences() : toappend.getSequences();
     if (sqs != null)
     {
+      // avoid self append deadlock by
+      List<SequenceI> toappendsq = new ArrayList<SequenceI>();
       synchronized (sqs)
       {
         for (SequenceI addedsq : sqs)
@@ -1408,9 +1401,13 @@ public class Alignment implements AlignmentI
               }
             }
           }
-          addSequence(addedsq);
+          toappendsq.add(addedsq);
         }
       }
+      for (SequenceI addedsq : toappendsq)
+      {
+        addSequence(addedsq);
+      }
     }
     AlignmentAnnotation[] alan = toappend.getAlignmentAnnotation();
     for (int a = 0; alan != null && a < alan.length; a++)
@@ -1418,6 +1415,7 @@ public class Alignment implements AlignmentI
       addAnnotation(alan[a]);
     }
 
+    // use add method
     getCodonFrames().addAll(toappend.getCodonFrames());
 
     List<SequenceGroup> sg = toappend.getGroups();
@@ -1708,9 +1706,11 @@ public class Alignment implements AlignmentI
    * Parameters control whether gaps in exon (mapped) and intron (unmapped)
    * regions are preserved. Gaps that connect introns to exons are treated
    * conservatively, i.e. only preserved if both intron and exon gaps are
-   * preserved.
+   * preserved. TODO: check caveats below where the implementation fails
    * 
    * @param al
+   *          - must have same dataset, and sequences in al must have equivalent
+   *          dataset sequence and start/end bounds under given mapping
    * @param preserveMappedGaps
    *          if true, gaps within and between mapped codons are preserved
    * @param preserveUnmappedGaps
@@ -1721,12 +1721,17 @@ public class Alignment implements AlignmentI
           boolean preserveUnmappedGaps)
   {
     // TODO should this method signature be the one in the interface?
+    // JBPComment - yes - neither flag is used, so should be deleted.
     boolean thisIsNucleotide = this.isNucleotide();
     boolean thatIsProtein = !al.isNucleotide();
     if (!thatIsProtein && !thisIsNucleotide)
     {
       return AlignmentUtils.alignProteinAsDna(this, al);
     }
+    else if (thatIsProtein && thisIsNucleotide)
+    {
+      return AlignmentUtils.alignCdsAsProtein(this, al);
+    }
     return AlignmentUtils.alignAs(this, al);
   }
 
@@ -1737,7 +1742,7 @@ public class Alignment implements AlignmentI
   @Override
   public String toString()
   {
-    return new FastaFile().print(getSequencesArray());
+    return new FastaFile().print(getSequencesArray(), true);
   }
 
   /**
index 7990a5c..2a89fa1 100755 (executable)
@@ -24,11 +24,11 @@ import jalview.analysis.Rna;
 import jalview.analysis.SecStrConsensus.SimpleBP;
 import jalview.analysis.WUSSParseException;
 
-import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.Iterator;
+import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
 
@@ -79,7 +79,7 @@ public class AlignmentAnnotation
   /** Array of annotations placed in the current coordinate system */
   public Annotation[] annotations;
 
-  public ArrayList<SimpleBP> bps = null;
+  public List<SimpleBP> bps = null;
 
   /**
    * RNA secondary structure contact positions
@@ -102,8 +102,8 @@ public class AlignmentAnnotation
   {
     try
     {
-      _rnasecstr = Rna.GetBasePairs(RNAannot);
-      bps = Rna.GetModeleBP(RNAannot);
+      bps = Rna.getModeleBP(RNAannot);
+      _rnasecstr = Rna.getBasePairs(bps);
       invalidrnastruc = -1;
     } catch (WUSSParseException px)
     {
@@ -272,7 +272,7 @@ public class AlignmentAnnotation
   // JBPNote: what does this do ?
   public void ConcenStru(CharSequence RNAannot) throws WUSSParseException
   {
-    bps = Rna.GetModeleBP(RNAannot);
+    bps = Rna.getModeleBP(RNAannot);
   }
 
   /**
@@ -485,7 +485,7 @@ public class AlignmentAnnotation
       this(0, annotations.length);
     }
 
-    public AnnotCharSequence(int start, int end)
+    AnnotCharSequence(int start, int end)
     {
       offset = start;
       max = end;
@@ -593,6 +593,7 @@ public class AlignmentAnnotation
     if (annotations == null)
     {
       visible = false; // try to prevent renderer from displaying.
+      invalidrnastruc = -1;
       return; // this is a non-annotation row annotation - ie a sequence score.
     }
 
@@ -1411,6 +1412,77 @@ public class AlignmentAnnotation
     this.annotationId = ANNOTATION_ID_PREFIX + Long.toString(nextId());
   }
 
+  /**
+   * Returns the match for the last unmatched opening RNA helix pair symbol
+   * preceding the given column, or '(' if nothing found to match.
+   * 
+   * @param column
+   * @return
+   */
+  public String getDefaultRnaHelixSymbol(int column)
+  {
+    String result = "(";
+    if (annotations == null)
+    {
+      return result;
+    }
+
+    /*
+     * for each preceding column, if it contains an open bracket, 
+     * count whether it is still unmatched at column, if so return its pair
+     * (likely faster than the fancy alternative using stacks)
+     */
+    for (int col = column - 1; col >= 0; col--)
+    {
+      Annotation annotation = annotations[col];
+      if (annotation == null)
+      {
+        continue;
+      }
+      String displayed = annotation.displayCharacter;
+      if (displayed == null || displayed.length() != 1)
+      {
+        continue;
+      }
+      char symbol = displayed.charAt(0);
+      if (!Rna.isOpeningParenthesis(symbol))
+      {
+        continue;
+      }
+
+      /*
+       * found an opening bracket symbol
+       * count (closing-opening) symbols of this type that follow it,
+       * up to and excluding the target column; if the count is less
+       * than 1, the opening bracket is unmatched, so return its match
+       */
+      String closer = String.valueOf(Rna
+              .getMatchingClosingParenthesis(symbol));
+      String opener = String.valueOf(symbol);
+      int count = 0;
+      for (int j = col + 1; j < column; j++)
+      {
+        if (annotations[j] != null)
+        {
+          String s = annotations[j].displayCharacter;
+          if (closer.equals(s))
+          {
+            count++;
+          }
+          else if (opener.equals(s))
+          {
+            count--;
+          }
+        }
+      }
+      if (count < 1)
+      {
+        return closer;
+      }
+    }
+    return result;
+  }
+
   protected static synchronized long nextId()
   {
     return counter++;
index 4ae8ba2..f1db4c0 100755 (executable)
@@ -41,7 +41,8 @@ public interface AlignmentI extends AnnotatedCollectionI
    * 
    * Calculates the maximum width of the alignment, including gaps.
    * 
-   * @return Greatest sequence length within alignment.
+   * @return Greatest sequence length within alignment, or -1 if no sequences
+   *         present
    */
   @Override
   int getWidth();
@@ -305,7 +306,7 @@ public interface AlignmentI extends AnnotatedCollectionI
    * @return Alignment containing dataset sequences or null of this is a
    *         dataset.
    */
-  Alignment getDataset();
+  AlignmentI getDataset();
 
   /**
    * Set the associated dataset for the alignment, or create one.
@@ -313,7 +314,7 @@ public interface AlignmentI extends AnnotatedCollectionI
    * @param dataset
    *          The dataset alignment or null to construct one.
    */
-  void setDataset(Alignment dataset);
+  void setDataset(AlignmentI dataset);
 
   /**
    * pads sequences with gaps (to ensure the set looks like an alignment)
@@ -363,14 +364,6 @@ public interface AlignmentI extends AnnotatedCollectionI
   void addCodonFrame(AlignedCodonFrame codons);
 
   /**
-   * add a set of aligned codons mappings for this alignment, apart from any
-   * duplicates which are ignored
-   * 
-   * @param codons
-   */
-  void addCodonFrames(Iterable<AlignedCodonFrame> codons);
-
-  /**
    * remove a particular codon frame reference from this alignment
    * 
    * @param codons
index 756a116..9db9f38 100644 (file)
@@ -26,7 +26,6 @@ import jalview.util.ShiftList;
 import java.io.PrintStream;
 import java.util.ArrayList;
 import java.util.List;
-import java.util.Vector;
 
 /**
  * Transient object compactly representing a 'view' of an alignment - with
@@ -69,13 +68,51 @@ public class AlignmentView
    */
   private class ScGroup
   {
-    public Vector seqs;
+    public List<SeqCigar> seqs;
 
     public SequenceGroup sg;
 
     ScGroup()
     {
-      seqs = new Vector();
+      seqs = new ArrayList<SeqCigar>();
+    }
+
+    /**
+     * @param seq
+     * @return true if seq was not a member before and was added to group
+     */
+    public boolean add(SeqCigar seq)
+    {
+      if (!seq.isMemberOf(this))
+      {
+        seqs.add(seq);
+        seq.setGroupMembership(this);
+        return true;
+      }
+      else
+      {
+        return false;
+      }
+    }
+
+    /**
+     * 
+     * @param seq
+     * @return true if seq was a member and was removed from group
+     */
+    public boolean remove(SeqCigar seq)
+    {
+      if (seq.removeGroupMembership(this))
+      {
+        seqs.remove(seq);
+        return true;
+      }
+      return false;
+    }
+
+    public int size()
+    {
+      return seqs.size();
     }
   }
 
@@ -83,7 +120,7 @@ public class AlignmentView
    * vector of selected seqCigars. This vector is also referenced by each
    * seqCigar contained in it.
    */
-  private Vector selected;
+  private ScGroup selected;
 
   /**
    * Construct an alignmentView from a live jalview alignment view. Note -
@@ -124,7 +161,7 @@ public class AlignmentView
     if (selection != null && selection.getSize() > 0)
     {
       List<SequenceI> sel = selection.getSequences(null);
-      this.selected = new Vector();
+      this.selected = new ScGroup();
       selseqs = selection
               .getSequencesInOrder(alignment, selectedRegionOnly);
     }
@@ -194,8 +231,7 @@ public class AlignmentView
         if (selection != null && selection.getSize() > 0
                 && !selectedRegionOnly)
         {
-          sequences[csi].setGroupMembership(selected);
-          selected.addElement(sequences[csi]);
+          selected.add(sequences[csi]);
         }
         if (seqsets != null)
         {
@@ -203,9 +239,8 @@ public class AlignmentView
           {
             if ((seqsets.get(sg)).contains(selseqs[i]))
             {
-              sequences[csi].setGroupMembership(sgrps[sg]);
               sgrps[sg].sg.deleteSequence(selseqs[i], false);
-              sgrps[sg].seqs.addElement(sequences[csi]);
+              sgrps[sg].add(sequences[csi]);
               if (!addedgps[sg])
               {
                 if (scGroups == null)
@@ -242,8 +277,7 @@ public class AlignmentView
     if (!seqcigararray.isSeqCigarArray())
     {
       throw new Error(
-              MessageManager
-                      .getString("error.implementation_error_can_only_make_alignmnet_from_cigararray"));
+              "Implementation Error - can only make an alignment view from a CigarArray of sequences.");
     }
     // contigs = seqcigararray.applyDeletions();
     contigs = seqcigararray.getDeletedRegions();
@@ -1073,10 +1107,10 @@ public class AlignmentView
                 + sgr.sg.getEndRes());
         for (int s = 0; s < sgr.seqs.size(); s++)
         {
-          if (!((SeqCigar) sgr.seqs.elementAt(s)).isMemberOf(sgr))
+          // JBPnote this should be a unit test for ScGroup
+          if (!sgr.seqs.get(s).isMemberOf(sgr))
           {
-            os.println("** WARNING: sequence "
-                    + ((SeqCigar) sgr.seqs.elementAt(s)).toString()
+            os.println("** WARNING: sequence " + sgr.seqs.get(s).toString()
                     + " is not marked as member of group.");
           }
         }
index bcf8596..5fb507a 100644 (file)
@@ -533,6 +533,7 @@ public abstract class CigarBase
       {
       case M:
         cursor += range[i];
+        break;
       case I:
         vcursor += range[i];
         break;
index aaf70b8..7ef2a68 100644 (file)
@@ -290,11 +290,12 @@ public class ColumnSelection
   /**
    * Returns a list of selected columns. The list contains no duplicates but is
    * not necessarily ordered. It also may include columns hidden from the
-   * current view
+   * current view. This returns a copy of the actual list, and changes to the
+   * copy will not affect the selection.
    */
   public List<Integer> getSelected()
   {
-    return selection.getList();
+    return new ArrayList<Integer>(selection.getList());
   }
 
   /**
@@ -985,7 +986,7 @@ public class ColumnSelection
           SequenceI[] seqs)
   {
     int i, iSize = seqs.length;
-    String selection[] = new String[iSize];
+    String selections[] = new String[iSize];
     if (hiddenColumns != null && hiddenColumns.size() > 0)
     {
       for (i = 0; i < iSize; i++)
@@ -1027,18 +1028,18 @@ public class ColumnSelection
           visibleSeq.append(seqs[i].getSequence(blockStart, end));
         }
 
-        selection[i] = visibleSeq.toString();
+        selections[i] = visibleSeq.toString();
       }
     }
     else
     {
       for (i = 0; i < iSize; i++)
       {
-        selection[i] = seqs[i].getSequenceAsString(start, end);
+        selections[i] = seqs[i].getSequenceAsString(start, end);
       }
     }
 
-    return selection;
+    return selections;
   }
 
   /**
@@ -1703,4 +1704,78 @@ public class ColumnSelection
     return true;
   }
 
+  /**
+   * Updates the column selection depending on the parameters, and returns true
+   * if any change was made to the selection
+   * 
+   * @param markedColumns
+   *          a set identifying marked columns (base 0)
+   * @param startCol
+   *          the first column of the range to operate over (base 0)
+   * @param endCol
+   *          the last column of the range to operate over (base 0)
+   * @param invert
+   *          if true, deselect marked columns and select unmarked
+   * @param extendCurrent
+   *          if true, extend rather than replacing the current column selection
+   * @param toggle
+   *          if true, toggle the selection state of marked columns
+   * 
+   * @return
+   */
+  public boolean markColumns(BitSet markedColumns, int startCol,
+          int endCol, boolean invert, boolean extendCurrent, boolean toggle)
+  {
+    boolean changed = false;
+    if (!extendCurrent && !toggle)
+    {
+      changed = !this.isEmpty();
+      clear();
+    }
+    if (invert)
+    {
+      // invert only in the currently selected sequence region
+      int i = markedColumns.nextClearBit(startCol);
+      int ibs = markedColumns.nextSetBit(startCol);
+      while (i >= startCol && i <= endCol)
+      {
+        if (ibs < 0 || i < ibs)
+        {
+          changed = true;
+          if (toggle && contains(i))
+          {
+            removeElement(i++);
+          }
+          else
+          {
+            addElement(i++);
+          }
+        }
+        else
+        {
+          i = markedColumns.nextClearBit(ibs);
+          ibs = markedColumns.nextSetBit(i);
+        }
+      }
+    }
+    else
+    {
+      int i = markedColumns.nextSetBit(startCol);
+      while (i >= startCol && i <= endCol)
+      {
+        changed = true;
+        if (toggle && contains(i))
+        {
+          removeElement(i);
+        }
+        else
+        {
+          addElement(i);
+        }
+        i = markedColumns.nextSetBit(i + 1);
+      }
+    }
+    return changed;
+  }
+
 }
index 66a075e..a641b1b 100755 (executable)
@@ -25,8 +25,6 @@ import jalview.api.DBRefEntryI;
 public class DBRefEntry implements DBRefEntryI
 {
   String source = "", version = "", accessionId = "";
-
-  private int startRes, endRes;
   /**
    * maps from associated sequence to the database sequence's coordinate system
    */
@@ -150,6 +148,7 @@ public class DBRefEntry implements DBRefEntryI
      * otherwise the versions have to match
      */
     String otherVersion = other.getVersion();
+      
     if ((version == null || version.equals("0") || version.endsWith(":0"))
             && otherVersion != null)
     {
@@ -157,7 +156,9 @@ public class DBRefEntry implements DBRefEntryI
     }
     else
     {
-      if (!version.equalsIgnoreCase(otherVersion))
+      if (version != null
+              && (otherVersion == null || !version
+                      .equalsIgnoreCase(otherVersion)))
       {
         return false;
       }
@@ -279,28 +280,4 @@ public class DBRefEntry implements DBRefEntryI
   {
     return getSrcAccString();
   }
-
-  @Override
-  public int getStartRes()
-  {
-    return startRes;
-  }
-
-  @Override
-  public void setStartRes(int startRes)
-  {
-    this.startRes = startRes;
-  }
-
-  @Override
-  public int getEndRes()
-  {
-    return endRes;
-  }
-
-  @Override
-  public void setEndRes(int endRes)
-  {
-    this.endRes = endRes;
-  }
 }
index a2243be..fba9211 100755 (executable)
@@ -23,7 +23,10 @@ package jalview.datamodel;
 /**
  * Defines internal constants for unambiguous annotation of DbRefEntry source
  * strings and describing the data retrieved from external database sources (see
- * jalview.ws.DbSourcProxy)
+ * jalview.ws.DbSourcProxy) <br/>
+ * TODO: replace with ontology to allow recognition of particular attributes
+ * (e.g. protein coding, alignment (ortholog db, paralog db, domain db),
+ * genomic, transcriptomic, 3D structure providing (PDB, MODBASE, etc) ..).
  * 
  * @author JimP
  * 
@@ -54,11 +57,6 @@ public class DBRefSource
   public static String PDB = "PDB";
 
   /**
-   * mmCIF Entry Code
-   */
-  public static String MMCIF = "mmCIF";
-
-  /**
    * EMBL ID
    */
   public static String EMBL = "EMBL";
index bd83fe9..1c196be 100644 (file)
@@ -20,6 +20,7 @@
  */
 package jalview.datamodel;
 
+import jalview.util.Comparison;
 import jalview.util.MapList;
 
 import java.util.Iterator;
@@ -258,7 +259,8 @@ public class Mapping
       int truePos = sequencePos - (start - 1);
       while (alignedBases < truePos && alignedColumn < alignedSeq.length)
       {
-        if (alignedSeq[alignedColumn++] != gap)
+        char c = alignedSeq[alignedColumn++];
+        if (c != gap && !Comparison.isGap(c))
         {
           alignedBases++;
         }
@@ -274,18 +276,23 @@ public class Mapping
 
   }
 
-  /**
+  /*
    * Contains the start-end pairs mapping from the associated sequence to the
    * sequence in the database coordinate system. It also takes care of step
    * difference between coordinate systems.
    */
   MapList map = null;
 
-  /**
+  /*
    * The sequence that map maps the associated sequence to (if any).
    */
   SequenceI to = null;
 
+  /*
+   * optional sequence id for the 'from' ranges
+   */
+  private String mappedFromId;
+
   public Mapping(MapList map)
   {
     super();
@@ -333,6 +340,7 @@ public class Mapping
         map = new MapList(map2.map);
       }
       to = map2.to;
+      mappedFromId = map2.mappedFromId;
     }
   }
 
@@ -356,14 +364,13 @@ public class Mapping
   /**
    * Equals that compares both the to references and MapList mappings.
    * 
-   * @param other
+   * @param o
    * @return
+   * @see MapList#equals
    */
   @Override
   public boolean equals(Object o)
   {
-    // TODO should override Object.hashCode() to ensure that equal objects have
-    // equal hashcodes
     if (o == null || !(o instanceof Mapping))
     {
       return false;
@@ -390,6 +397,21 @@ public class Mapping
   }
 
   /**
+   * Returns a hashCode made from the sequence and maplist
+   */
+  @Override
+  public int hashCode()
+  {
+    int hashCode = (this.to == null ? 1 : this.to.hashCode());
+    if (this.map != null)
+    {
+      hashCode = hashCode * 31 + this.map.hashCode();
+    }
+
+    return hashCode;
+  }
+
+  /**
    * get the 'initial' position in the associated sequence for a position in the
    * mapped reference frame
    * 
@@ -728,4 +750,22 @@ public class Mapping
             : this.to.getName());
   }
 
+  /**
+   * Returns the identifier for the 'from' range sequence, or null if not set
+   * 
+   * @return
+   */
+  public String getMappedFromId()
+  {
+    return mappedFromId;
+  }
+
+  /**
+   * Sets the identifier for the 'from' range sequence
+   */
+  public void setMappedFromId(String mappedFromId)
+  {
+    this.mappedFromId = mappedFromId;
+  }
+
 }
index 243e00c..37dfdbf 100755 (executable)
@@ -34,7 +34,27 @@ public class PDBEntry
 
   public enum Type
   {
-    PDB, MMCIF, FILE
+    // TODO is FILE needed; if not is this needed or can we
+    // use FileFormatI for PDB, MMCIF?
+    PDB("pdb", "xml"), MMCIF("mmcif", "mmcif"), FILE("?", "?");
+    String ext;
+
+    String format;
+
+    private Type(String fmt, String ex)
+    {
+      format = fmt;
+      ext = ex;
+    }
+
+    public String getFormat()
+    {
+      return format;
+    }
+    public String getExtension()
+    {
+      return ext;
+    }
   }
 
   Hashtable<String, String> properties;
index 151d8c4..a857712 100755 (executable)
@@ -303,8 +303,13 @@ public class Sequence extends ASequence implements SequenceI
     }
     else
     {
-      System.err
+      if (datasetSequence.getSequenceFeatures() != features
+              && datasetSequence.getSequenceFeatures() != null
+              && datasetSequence.getSequenceFeatures().length > 0)
+      {
+        System.err
               .println("Warning: JAL-2046 side effect ? Possible implementation error: overwriting dataset sequence features by setting sequence features on alignment");
+      }
       datasetSequence.setSequenceFeatures(features);
     }
   }
@@ -1086,6 +1091,25 @@ public class Sequence extends ASequence implements SequenceI
     return new Sequence(this);
   }
 
+  private boolean _isNa;
+
+  private long _seqhash = 0;
+
+  @Override
+  public boolean isProtein()
+  {
+    if (datasetSequence != null)
+    {
+      return datasetSequence.isProtein();
+    }
+    if (_seqhash != sequence.hashCode())
+    {
+      _seqhash = sequence.hashCode();
+      _isNa=jalview.util.Comparison.isNucleotide(new SequenceI[] { this });
+    }
+    return !_isNa;
+  };
+
   /*
    * (non-Javadoc)
    * 
index d403d6e..22c537a 100755 (executable)
@@ -504,14 +504,31 @@ public class SequenceGroup implements AnnotatedCollectionI
   }
 
   /**
-   * calculate residue conservation for group - but only if necessary.
+   * calculate residue conservation and colourschemes for group - but only if
+   * necessary. returns true if the calculation resulted in a visible change to
+   * group
    */
-  public void recalcConservation()
+  public boolean recalcConservation()
+  {
+    return recalcConservation(false);
+  }
+
+  /**
+   * calculate residue conservation for group - but only if necessary. returns
+   * true if the calculation resulted in a visible change to group
+   * 
+   * @param defer
+   *          when set, colourschemes for this group are not refreshed after
+   *          recalculation
+   */
+  public boolean recalcConservation(boolean defer)
   {
     if (cs == null && consensus == null && conservation == null)
     {
-      return;
+      return false;
     }
+    // TODO: try harder to detect changes in state in order to minimise
+    // recalculation effort
     try
     {
       Hashtable cnsns[] = AAFrequency.calculate(sequences, startRes,
@@ -545,16 +562,22 @@ public class SequenceGroup implements AnnotatedCollectionI
           }
         }
       }
-      if (cs != null)
+      if (cs != null && !defer)
       {
+        // TODO: JAL-2034 should cs.alignmentChanged modify return state
         cs.alignmentChanged(context != null ? context : this, null);
+        return true;
+      }
+      else
+      {
+        return false;
       }
     } catch (java.lang.OutOfMemoryError err)
     {
       // TODO: catch OOM
       System.out.println("Out of memory loading groups: " + err);
     }
-
+    return false;
   }
 
   private void _updateConservationRow(Conservation c)
index 69eb1d4..45a767c 100755 (executable)
@@ -219,6 +219,12 @@ public interface SequenceI extends ASequenceI
   public int[] findPositionMap();
 
   /**
+   * 
+   * @return true if sequence is composed of amino acid characters
+   */
+  public boolean isProtein();
+
+  /**
    * Delete a range of aligned sequence columns, creating a new dataset sequence
    * if necessary and adjusting start and end positions accordingly.
    * 
@@ -233,19 +239,21 @@ public interface SequenceI extends ASequenceI
    * DOCUMENT ME!
    * 
    * @param i
-   *          DOCUMENT ME!
+   *          alignment column number
    * @param c
-   *          DOCUMENT ME!
+   *          character to insert
    */
   public void insertCharAt(int i, char c);
 
   /**
-   * DOCUMENT ME!
+   * insert given character at alignment column position
    * 
    * @param position
-   *          DOCUMENT ME!
+   *          alignment column number
+   * @param count
+   *          length of insert
    * @param ch
-   *          DOCUMENT ME!
+   *          character to insert
    */
   public void insertCharAt(int position, int count, char ch);
 
index f8c0bbe..06e929d 100644 (file)
@@ -49,8 +49,7 @@ import java.util.regex.Pattern;
  * Castor binding file
  * 
  * For example:
- * http://www.ebi.ac.uk/Tools/dbfetch/dbfetch?db=ena_sequence&id=J03321
- * &format=emblxml
+ * http://www.ebi.ac.uk/ena/data/view/J03321&display=xml
  * 
  * @see embl_mapping.xml
  */
@@ -187,21 +186,30 @@ public class EmblEntry
    */
   public SequenceI getSequence(String sourceDb, List<SequenceI> peptides)
   {
-    SequenceI dna = new Sequence(sourceDb + "|" + accession,
-            sequence.getSequence());
+    SequenceI dna = makeSequence(sourceDb);
+    if (dna == null)
+    {
+      return null;
+    }
     dna.setDescription(description);
     DBRefEntry retrievedref = new DBRefEntry(sourceDb,
             getSequenceVersion(), accession);
     dna.addDBRef(retrievedref);
+    dna.setSourceDBRef(retrievedref);
     // add map to indicate the sequence is a valid coordinate frame for the
     // dbref
     retrievedref.setMap(new Mapping(null, new int[] { 1, dna.getLength() },
             new int[] { 1, dna.getLength() }, 1, 1));
 
+
+    /*
+     * transform EMBL Database refs to canonical form
+     */
     if (dbRefs != null)
     {
       for (DBRefEntry dbref : dbRefs)
       {
+        dbref.setSource(DBRefUtils.getCanonicalName(dbref.getSource()));
         dna.addDBRef(dbref);
       }
     }
@@ -211,13 +219,6 @@ public class EmblEntry
     {
       for (EmblFeature feature : features)
       {
-        if (feature.dbRefs != null)
-        {
-          for (DBRefEntry dbref : feature.dbRefs)
-          {
-            dna.addDBRef(dbref);
-          }
-        }
         if (FeatureProperties.isCodingFeature(sourceDb, feature.getName()))
         {
           parseCodingFeature(feature, sourceDb, dna, peptides, matcher);
@@ -237,6 +238,23 @@ public class EmblEntry
   }
 
   /**
+   * @param sourceDb
+   * @return
+   */
+  SequenceI makeSequence(String sourceDb)
+  {
+    if (sequence == null)
+    {
+      System.err.println("No sequence was returned for ENA accession "
+              + accession);
+      return null;
+    }
+    SequenceI dna = new Sequence(sourceDb + "|" + accession,
+            sequence.getSequence());
+    return dna;
+  }
+
+  /**
    * Extracts coding region and product from a CDS feature and properly decorate
    * it with annotations.
    * 
@@ -248,17 +266,19 @@ public class EmblEntry
    *          parent dna sequence for this record
    * @param peptides
    *          list of protein product sequences for Embl entry
+   * @param matcher
+   *          helper to match xrefs in already retrieved sequences
    */
   void parseCodingFeature(EmblFeature feature, String sourceDb,
           SequenceI dna, List<SequenceI> peptides, SequenceIdMatcher matcher)
   {
     boolean isEmblCdna = sourceDb.equals(DBRefSource.EMBLCDS);
 
-    int[] exon = getCdsRanges(feature);
+    int[] exons = getCdsRanges(feature);
 
-    String prseq = null;
-    String prname = "";
-    String prid = null;
+    String translation = null;
+    String proteinName = "";
+    String proteinId = null;
     Map<String, String> vals = new Hashtable<String, String>();
 
     /*
@@ -279,11 +299,11 @@ public class EmblEntry
         if (qname.equals("translation"))
         {
           // remove all spaces (precompiled String.replaceAll(" ", ""))
-          prseq = SPACE_PATTERN.matcher(q.getValues()[0]).replaceAll("");
+          translation = SPACE_PATTERN.matcher(q.getValues()[0]).replaceAll("");
         }
         else if (qname.equals("protein_id"))
         {
-          prid = q.getValues()[0].trim();
+          proteinId = q.getValues()[0].trim();
         }
         else if (qname.equals("codon_start"))
         {
@@ -299,7 +319,7 @@ public class EmblEntry
         else if (qname.equals("product"))
         {
           // sometimes name is returned e.g. for V00488
-          prname = q.getValues()[0].trim();
+          proteinName = q.getValues()[0].trim();
         }
         else
         {
@@ -315,54 +335,59 @@ public class EmblEntry
       }
     }
 
-    DBRefEntry protEMBLCDS = null;
-    exon = MappingUtils.removeStartPositions(codonStart - 1, exon);
-    boolean noProteinDbref = true;
+    DBRefEntry proteinToEmblProteinRef = null;
+    exons = MappingUtils.removeStartPositions(codonStart - 1, exons);
 
     SequenceI product = null;
-    Mapping map = null;
-    if (prseq != null && prname != null && prid != null)
+    Mapping dnaToProteinMapping = null;
+    if (translation != null && proteinName != null && proteinId != null)
     {
+      int translationLength = translation.length();
+
       /*
        * look for product in peptides list, if not found, add it
        */
-      product = matcher.findIdMatch(prid);
+      product = matcher.findIdMatch(proteinId);
       if (product == null)
       {
-        product = new Sequence(prid, prseq, 1, prseq.length());
-        product.setDescription(((prname.length() == 0) ? "Protein Product from "
+        product = new Sequence(proteinId, translation, 1, translationLength);
+        product.setDescription(((proteinName.length() == 0) ? "Protein Product from "
                 + sourceDb
-                : prname));
+                : proteinName));
         peptides.add(product);
         matcher.add(product);
       }
 
       // we have everything - create the mapping and perhaps the protein
       // sequence
-      if (exon == null || exon.length == 0)
+      if (exons == null || exons.length == 0)
       {
+        /*
+         * workaround until we handle dna location for CDS sequence
+         * e.g. location="X53828.1:60..1058" correctly
+         */
         System.err
                 .println("Implementation Notice: EMBLCDS records not properly supported yet - Making up the CDNA region of this sequence... may be incorrect ("
                         + sourceDb + ":" + getAccession() + ")");
-        if (prseq.length() * 3 == (1 - codonStart + dna.getSequence().length))
+        if (translationLength * 3 == (1 - codonStart + dna.getSequence().length))
         {
           System.err
                   .println("Not allowing for additional stop codon at end of cDNA fragment... !");
-          // this might occur for CDS sequences where no features are
-          // marked.
-          exon = new int[] { dna.getStart() + (codonStart - 1),
+          // this might occur for CDS sequences where no features are marked
+          exons = new int[] { dna.getStart() + (codonStart - 1),
               dna.getEnd() };
-          map = new Mapping(product, exon, new int[] { 1, prseq.length() },
-                  3, 1);
+          dnaToProteinMapping = new Mapping(product, exons, new int[] { 1,
+              translationLength }, 3, 1);
         }
-        if ((prseq.length() + 1) * 3 == (1 - codonStart + dna.getSequence().length))
+        if ((translationLength + 1) * 3 == (1 - codonStart + dna
+                .getSequence().length))
         {
           System.err
                   .println("Allowing for additional stop codon at end of cDNA fragment... will probably cause an error in VAMSAs!");
-          exon = new int[] { dna.getStart() + (codonStart - 1),
+          exons = new int[] { dna.getStart() + (codonStart - 1),
               dna.getEnd() - 3 };
-          map = new Mapping(product, exon, new int[] { 1, prseq.length() },
-                  3, 1);
+          dnaToProteinMapping = new Mapping(product, exons, new int[] { 1,
+              translationLength }, 3, 1);
         }
       }
       else
@@ -381,38 +406,49 @@ public class EmblEntry
         else
         {
           // final product length truncation check
-          // TODO should from range include stop codon even if not in protein
-          // in order to include stop codon in CDS sequence (as done for
-          // Ensembl)?
-          int[] cdsRanges = adjustForProteinLength(prseq.length(), exon);
-          map = new Mapping(product, cdsRanges, new int[] { 1,
-              prseq.length() }, 3, 1);
-          // reconstruct the EMBLCDS entry
-          // TODO: this is only necessary when there codon annotation is
-          // complete (I think JBPNote)
-          DBRefEntry pcdnaref = new DBRefEntry();
-          pcdnaref.setAccessionId(prid);
-          pcdnaref.setSource(DBRefSource.EMBLCDS);
-          pcdnaref.setVersion(getSequenceVersion()); // same as parent EMBL
-                                                     // version.
-          MapList mp = new MapList(new int[] { 1, prseq.length() },
-                  new int[] { 1 + (codonStart - 1),
-                      (codonStart - 1) + 3 * prseq.length() }, 1, 3);
-          pcdnaref.setMap(new Mapping(mp));
+          int[] cdsRanges = adjustForProteinLength(translationLength, exons);
+          dnaToProteinMapping = new Mapping(product, cdsRanges, new int[] {
+              1, translationLength }, 3, 1);
           if (product != null)
           {
-            product.addDBRef(pcdnaref);
-            protEMBLCDS = new DBRefEntry(pcdnaref);
-            protEMBLCDS.setSource(DBRefSource.EMBLCDSProduct);
-            product.addDBRef(protEMBLCDS);
+            /*
+             * make xref with mapping from protein to EMBL dna
+             */
+            DBRefEntry proteinToEmblRef = new DBRefEntry(DBRefSource.EMBL,
+                    getSequenceVersion(), proteinId, new Mapping(
+                            dnaToProteinMapping.getMap().getInverse()));
+            product.addDBRef(proteinToEmblRef);
+
+            /*
+             * make xref from protein to EMBLCDS; we assume here that the 
+             * CDS sequence version is same as dna sequence (?!)
+             */
+            MapList proteinToCdsMapList = new MapList(new int[] { 1,
+                translationLength }, new int[] { 1 + (codonStart - 1),
+                (codonStart - 1) + 3 * translationLength }, 1, 3);
+            DBRefEntry proteinToEmblCdsRef = new DBRefEntry(
+                    DBRefSource.EMBLCDS, getSequenceVersion(), proteinId,
+                    new Mapping(proteinToCdsMapList));
+            product.addDBRef(proteinToEmblCdsRef);
+
+            /*
+             * make 'direct' xref from protein to EMBLCDSPROTEIN
+             */
+            proteinToEmblProteinRef = new DBRefEntry(proteinToEmblCdsRef);
+            proteinToEmblProteinRef.setSource(DBRefSource.EMBLCDSProduct);
+            proteinToEmblProteinRef.setMap(null);
+            product.addDBRef(proteinToEmblProteinRef);
           }
         }
       }
-      // add cds feature to dna seq - this may include the stop codon
-      for (int xint = 0; exon != null && xint < exon.length; xint += 2)
+
+      /*
+       * add cds features to dna sequence
+       */
+      for (int xint = 0; exons != null && xint < exons.length; xint += 2)
       {
-        SequenceFeature sf = makeCdsFeature(exon, xint, prname, prid, vals,
-                codonStart);
+        SequenceFeature sf = makeCdsFeature(exons, xint, proteinName,
+                proteinId, vals, codonStart);
         sf.setType(feature.getName()); // "CDS"
         sf.setEnaLocation(feature.getLocation());
         sf.setFeatureGroup(sourceDb);
@@ -421,19 +457,26 @@ public class EmblEntry
     }
 
     /*
-     * add dbRefs to sequence, and mappings for Uniprot xrefs
+     * add feature dbRefs to sequence, and mappings for Uniprot xrefs
      */
+    boolean hasUniprotDbref = false;
     if (feature.dbRefs != null)
     {
       boolean mappingUsed = false;
       for (DBRefEntry ref : feature.dbRefs)
       {
-        ref.setSource(DBRefUtils.getCanonicalName(ref.getSource()));
-        if (ref.getSource().equals(DBRefSource.UNIPROT))
+        /*
+         * ensure UniProtKB/Swiss-Prot converted to UNIPROT
+         */
+        String source = DBRefUtils.getCanonicalName(ref.getSource());
+        ref.setSource(source);
+        DBRefEntry proteinDbRef = new DBRefEntry(ref.getSource(), ref.getVersion(), ref
+                .getAccessionId());
+        if (source.equals(DBRefSource.UNIPROT))
         {
           String proteinSeqName = DBRefSource.UNIPROT + "|"
                   + ref.getAccessionId();
-          if (map != null && map.getTo() != null)
+          if (dnaToProteinMapping != null && dnaToProteinMapping.getTo() != null)
           {
             if (mappingUsed)
             {
@@ -441,13 +484,14 @@ public class EmblEntry
                * two or more Uniprot xrefs for the same CDS - 
                * each needs a distinct Mapping (as to a different sequence)
                */
-              map = new Mapping(map);
+              dnaToProteinMapping = new Mapping(dnaToProteinMapping);
             }
             mappingUsed = true;
 
             /*
              * try to locate the protein mapped to (possibly by a 
-             * previous CDS feature)
+             * previous CDS feature); if not found, construct it from
+             * the EMBL translation
              */
             SequenceI proteinSeq = matcher.findIdMatch(proteinSeqName);
             if (proteinSeq == null)
@@ -457,61 +501,64 @@ public class EmblEntry
               matcher.add(proteinSeq);
               peptides.add(proteinSeq);
             }
-            map.setTo(proteinSeq);
-            map.getTo().addDBRef(
-                    new DBRefEntry(ref.getSource(), ref.getVersion(), ref
-                            .getAccessionId()));
-            ref.setMap(map);
+            dnaToProteinMapping.setTo(proteinSeq);
+            dnaToProteinMapping.setMappedFromId(proteinId);
+            proteinSeq.addDBRef(proteinDbRef);
+            proteinSeq.setSourceDBRef(proteinDbRef);
+            ref.setMap(dnaToProteinMapping);
           }
-          noProteinDbref = false;
+          hasUniprotDbref = true;
         }
         if (product != null)
         {
-          DBRefEntry pref = new DBRefEntry(ref.getSource(),
-                  ref.getVersion(), ref.getAccessionId());
+          /*
+           * copy feature dbref to our protein product
+           */
+          DBRefEntry pref = proteinDbRef;
           pref.setMap(null); // reference is direct
           product.addDBRef(pref);
           // Add converse mapping reference
-          if (map != null)
+          if (dnaToProteinMapping != null)
           {
-            Mapping pmap = new Mapping(dna, map.getMap().getInverse());
+            Mapping pmap = new Mapping(dna, dnaToProteinMapping.getMap()
+                    .getInverse());
             pref = new DBRefEntry(sourceDb, getSequenceVersion(),
                     this.getAccession());
             pref.setMap(pmap);
-            if (map.getTo() != null)
+            if (dnaToProteinMapping.getTo() != null)
             {
-              map.getTo().addDBRef(pref);
+              dnaToProteinMapping.getTo().addDBRef(pref);
             }
           }
         }
         dna.addDBRef(ref);
       }
-      if (noProteinDbref && product != null)
+    }
+
+    /*
+     * if we have a product (translation) but no explicit Uniprot dbref
+     * (example: EMBL AAFI02000057 protein_id EAL65544.1)
+     * then construct mappings to an assumed EMBLCDSPROTEIN accession
+     */
+    if (!hasUniprotDbref && product != null)
+    {
+      if (proteinToEmblProteinRef == null)
       {
-        // add protein coding reference to dna sequence so xref matches
-        if (protEMBLCDS == null)
-        {
-          protEMBLCDS = new DBRefEntry();
-          protEMBLCDS.setAccessionId(prid);
-          protEMBLCDS.setSource(DBRefSource.EMBLCDSProduct);
-          protEMBLCDS.setVersion(getSequenceVersion());
-          protEMBLCDS
-                  .setMap(new Mapping(product, map.getMap().getInverse()));
-        }
-        product.addDBRef(protEMBLCDS);
+        // assuming CDSPROTEIN sequence version = dna version (?!)
+        proteinToEmblProteinRef = new DBRefEntry(
+                DBRefSource.EMBLCDSProduct, getSequenceVersion(), proteinId);
+      }
+      product.addDBRef(proteinToEmblProteinRef);
+      product.setSourceDBRef(proteinToEmblProteinRef);
 
-        // Add converse mapping reference
-        if (map != null)
-        {
-          Mapping pmap = new Mapping(product, protEMBLCDS.getMap().getMap()
-                  .getInverse());
-          DBRefEntry ncMap = new DBRefEntry(protEMBLCDS);
-          ncMap.setMap(pmap);
-          if (map.getTo() != null)
-          {
-            dna.addDBRef(ncMap);
-          }
-        }
+      if (dnaToProteinMapping != null
+              && dnaToProteinMapping.getTo() != null)
+      {
+        DBRefEntry dnaToEmblProteinRef = new DBRefEntry(
+                DBRefSource.EMBLCDSProduct, getSequenceVersion(), proteinId);
+        dnaToEmblProteinRef.setMap(dnaToProteinMapping);
+        dnaToProteinMapping.setMappedFromId(proteinId);
+        dna.addDBRef(dnaToEmblProteinRef);
       }
     }
   }
@@ -612,26 +659,30 @@ public class EmblEntry
   }
 
   /**
-   * truncate the last exon interval to the prlength'th codon
+   * Truncates (if necessary) the exon intervals to match 3 times the length of
+   * the protein; also accepts 3 bases longer (for stop codon not included in
+   * protein)
    * 
-   * @param prlength
+   * @param proteinLength
    * @param exon
-   * @return new exon
+   *          an array of [start, end, start, end...] intervals
+   * @return the same array (if unchanged) or a truncated copy
    */
-  static int[] adjustForProteinLength(int prlength, int[] exon)
+  static int[] adjustForProteinLength(int proteinLength, int[] exon)
   {
-    if (prlength <= 0 || exon == null)
+    if (proteinLength <= 0 || exon == null)
     {
       return exon;
     }
-    int desiredCdsLength = prlength * 3;
+    int expectedCdsLength = proteinLength * 3;
     int exonLength = MappingUtils.getLength(Arrays.asList(exon));
 
     /*
-     * assuming here exon might include stop codon in addition to protein codons
+     * if exon length matches protein, or is shorter, or longer by the 
+     * length of a stop codon (3 bases), then leave it unchanged
      */
-    if (desiredCdsLength == exonLength
-            || desiredCdsLength == exonLength - 3)
+    if (expectedCdsLength >= exonLength
+            || expectedCdsLength == exonLength - 3)
     {
       return exon;
     }
@@ -645,11 +696,11 @@ public class EmblEntry
     for (int x = 0; x < exon.length; x += 2)
     {
       cdspos += Math.abs(exon[x + 1] - exon[x]) + 1;
-      if (desiredCdsLength <= cdspos)
+      if (expectedCdsLength <= cdspos)
       {
         // advanced beyond last codon.
         sxpos = x;
-        if (desiredCdsLength != cdspos)
+        if (expectedCdsLength != cdspos)
         {
           // System.err
           // .println("Truncating final exon interval on region by "
@@ -662,11 +713,11 @@ public class EmblEntry
          */
         if (exon[x + 1] >= exon[x])
         {
-          endxon = exon[x + 1] - cdspos + desiredCdsLength;
+          endxon = exon[x + 1] - cdspos + expectedCdsLength;
         }
         else
         {
-          endxon = exon[x + 1] + cdspos - desiredCdsLength;
+          endxon = exon[x + 1] + cdspos - expectedCdsLength;
         }
         break;
       }
index 950b658..88b5ac4 100644 (file)
@@ -33,7 +33,7 @@ class EnsemblInfo
 
   /*
    * true when http://rest.ensembl.org/info/ping/?content-type=application/json
-   * returns response code 200
+   * returns response code 200 and not {"error":"Database is unavailable"}
    */
   boolean restAvailable;
 
index e651ddf..653d5d5 100644 (file)
@@ -1,5 +1,6 @@
 package jalview.ext.ensembl;
 
+import jalview.io.DataSourceType;
 import jalview.io.FileParse;
 import jalview.util.StringUtils;
 
@@ -35,9 +36,11 @@ abstract class EnsemblRestClient extends EnsemblSequenceFetcher
    * changes to Ensembl REST API
    * @see https://github.com/Ensembl/ensembl-rest/wiki/Change-log
    */
-  private static final String LATEST_ENSEMBLGENOMES_REST_VERSION = "4.4";
+  private static final String LATEST_ENSEMBLGENOMES_REST_VERSION = "4.6";
 
-  private static final String LATEST_ENSEMBL_REST_VERSION = "4.5";
+  private static final String LATEST_ENSEMBL_REST_VERSION = "4.6";
+
+  private static final String REST_CHANGE_LOG = "https://github.com/Ensembl/ensembl-rest/wiki/Change-log";
 
   private static Map<String, EnsemblInfo> domainData;
 
@@ -155,30 +158,40 @@ abstract class EnsemblRestClient extends EnsemblSequenceFetcher
   protected abstract String getResponseMimeType();
 
   /**
-   * Tries to connect to Ensembl's REST 'ping' endpoint, and returns true if
-   * successful, else false
+   * Checks Ensembl's REST 'ping' endpoint, and returns true if response
+   * indicates available, else false
    * 
+   * @see http://rest.ensembl.org/documentation/info/ping
    * @return
    */
   private boolean checkEnsembl()
   {
+    HttpURLConnection conn = null;
     try
     {
       // note this format works for both ensembl and ensemblgenomes
       // info/ping.json works for ensembl only (March 2016)
       URL ping = new URL(getDomain()
               + "/info/ping?content-type=application/json");
-      HttpURLConnection conn = (HttpURLConnection) ping.openConnection();
-      int rc = conn.getResponseCode();
-      conn.disconnect();
-      if (rc >= 200 && rc < 300)
-      {
-        return true;
-      }
+
+      /*
+       * expect {"ping":1} if ok
+       */
+      BufferedReader br = getHttpResponse(ping, null);
+      JSONParser jp = new JSONParser();
+      JSONObject val = (JSONObject) jp.parse(br);
+      String pingString = val.get("ping").toString();
+      return pingString != null;
     } catch (Throwable t)
     {
       System.err.println("Error connecting to " + PING_URL + ": "
               + t.getMessage());
+    } finally
+    {
+      if (conn != null)
+      {
+        conn.disconnect();
+      }
     }
     return false;
   }
@@ -196,7 +209,7 @@ abstract class EnsemblRestClient extends EnsemblSequenceFetcher
     URL url = getUrl(ids);
   
     BufferedReader reader = getHttpResponse(url, ids);
-    FileParse fp = new FileParse(reader, url.toString(), "HTTP_POST");
+    FileParse fp = new FileParse(reader, url.toString(), DataSourceType.URL);
     return fp;
   }
 
@@ -443,9 +456,8 @@ abstract class EnsemblRestClient extends EnsemblSequenceFetcher
       if (laterVersion)
       {
         System.err.println(String.format(
-                "Expected %s REST version %s but found %s", getDbSource(),
-                expected,
-                version));
+                "Expected %s REST version %s but found %s, see %s",
+                getDbSource(), expected, version, REST_CHANGE_LOG));
       }
       info.restVersion = version;
     } catch (Throwable t)
index c86469f..cc002e1 100644 (file)
@@ -5,7 +5,6 @@ import jalview.analysis.Dna;
 import jalview.datamodel.Alignment;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.DBRefEntry;
-import jalview.datamodel.DBRefSource;
 import jalview.datamodel.Mapping;
 import jalview.datamodel.SequenceFeature;
 import jalview.datamodel.SequenceI;
@@ -315,13 +314,6 @@ public abstract class EnsemblSeqProxy extends EnsemblRestClient
     for (DBRefEntry xref : xrefs)
     {
       seq.addDBRef(xref);
-      /*
-       * Save any Uniprot xref to be the reference for SIFTS mapping
-       */
-      if (DBRefSource.UNIPROT.equals(xref.getSource()))
-      {
-        seq.setSourceDBRef(xref);
-      }
     }
 
     /*
@@ -330,6 +322,7 @@ public abstract class EnsemblSeqProxy extends EnsemblRestClient
     DBRefEntry self = new DBRefEntry(getDbSource(),
             getEnsemblDataVersion(), seq.getName());
     seq.addDBRef(self);
+    seq.setSourceDBRef(self);
   }
 
   /**
@@ -387,8 +380,9 @@ public abstract class EnsemblSeqProxy extends EnsemblRestClient
         if (ids.contains(name)
                 || ids.contains(name.replace("ENSP", "ENST")))
         {
-          DBRefUtils.parseToDbRef(sq, getDbSource(),
+          DBRefEntry dbref = DBRefUtils.parseToDbRef(sq, getDbSource(),
                   getEnsemblDataVersion(), name);
+          sq.setSourceDBRef(dbref);
         }
       }
       if (alignment == null)
@@ -619,6 +613,10 @@ public abstract class EnsemblSeqProxy extends EnsemblRestClient
       SequenceFeature copy = new SequenceFeature(sf);
       copy.setBegin(Math.min(mappedRange[0], mappedRange[1]));
       copy.setEnd(Math.max(mappedRange[0], mappedRange[1]));
+      if (".".equals(copy.getFeatureGroup()))
+      {
+        copy.setFeatureGroup(getDbSource());
+      }
       targetSequence.addSequenceFeature(copy);
 
       /*
index ba57329..858aac7 100644 (file)
@@ -22,10 +22,9 @@ package jalview.ext.jmol;
 
 import jalview.datamodel.AlignmentAnnotation;
 import jalview.datamodel.Annotation;
-import jalview.datamodel.DBRefSource;
 import jalview.datamodel.SequenceI;
-import jalview.io.FileParse;
 import jalview.io.DataSourceType;
+import jalview.io.FileParse;
 import jalview.io.StructureFile;
 import jalview.schemes.ResidueProperties;
 import jalview.structure.StructureImportSettings;
@@ -33,6 +32,7 @@ import jalview.util.MessageManager;
 
 import java.io.IOException;
 import java.util.ArrayList;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Vector;
@@ -88,15 +88,6 @@ public class JmolParser extends StructureFile implements JmolStatusListener
   @Override
   public void parse() throws IOException
   {
-    String dataName = getDataName();
-    if (dataName.endsWith(".cif"))
-    {
-      setDbRefType(DBRefSource.MMCIF);
-    }
-    else
-    {
-      setDbRefType(DBRefSource.PDB);
-    }
     setChains(new Vector<PDBChain>());
     Viewer jmolModel = getJmolData();
     jmolModel.openReader(getDataName(), getDataName(), getReader());
@@ -173,7 +164,7 @@ public class JmolParser extends StructureFile implements JmolStatusListener
 
       if (getId() == null)
       {
-        setId(inFile.getName());
+        setId(safeName(getDataName()));
       }
       for (PDBChain chain : getChains())
       {
@@ -187,7 +178,7 @@ public class JmolParser extends StructureFile implements JmolStatusListener
           prot.add(chainseq);
         }
 
-        if (StructureImportSettings.isPredictSecondaryStructure())
+        if (StructureImportSettings.isProcessSecondaryStructure())
         {
           createAnnotation(chainseq, chain, ms.at);
         }
@@ -205,36 +196,91 @@ public class JmolParser extends StructureFile implements JmolStatusListener
   private List<Atom> convertSignificantAtoms(ModelSet ms)
   {
     List<Atom> significantAtoms = new ArrayList<Atom>();
+    HashMap<String, org.jmol.modelset.Atom> chainTerMap = new HashMap<String, org.jmol.modelset.Atom>();
+    org.jmol.modelset.Atom prevAtom = null;
     for (org.jmol.modelset.Atom atom : ms.at)
     {
-      // System.out.println("Seq Id : " + atom.getSeqID());
-      // System.out.println("To String : " + atom.toString());
-      if (!StructureImportSettings.isProcessHETATMs() && atom.isHetero())
-      {
-        continue;
-      }
       if (atom.getAtomName().equalsIgnoreCase("CA")
               || atom.getAtomName().equalsIgnoreCase("P"))
       {
+        if (!atomValidated(atom, prevAtom, chainTerMap))
+        {
+          continue;
+        }
         Atom curAtom = new Atom(atom.x, atom.y, atom.z);
         curAtom.atomIndex = atom.getIndex();
         curAtom.chain = atom.getChainIDStr();
-        curAtom.insCode = atom.group.getInsertionCode();
+        curAtom.insCode = atom.group.getInsertionCode() == '\000' ? ' '
+                : atom.group.getInsertionCode();
         curAtom.name = atom.getAtomName();
         curAtom.number = atom.getAtomNumber();
         curAtom.resName = atom.getGroup3(true);
         curAtom.resNumber = atom.getResno();
         curAtom.occupancy = ms.occupancies != null ? ms.occupancies[atom
                 .getIndex()] : Float.valueOf(atom.getOccupancy100());
-        curAtom.resNumIns = "" + curAtom.resNumber + curAtom.insCode;
+        curAtom.resNumIns = ("" + curAtom.resNumber + curAtom.insCode)
+                .trim();
         curAtom.tfactor = atom.getBfactor100() / 100f;
         curAtom.type = 0;
-        significantAtoms.add(curAtom);
+        // significantAtoms.add(curAtom);
+        // ignore atoms from subsequent models
+        if (!significantAtoms.contains(curAtom))
+        {
+          significantAtoms.add(curAtom);
+        }
+        prevAtom = atom;
       }
     }
     return significantAtoms;
   }
 
+  private boolean atomValidated(org.jmol.modelset.Atom curAtom,
+          org.jmol.modelset.Atom prevAtom,
+          HashMap<String, org.jmol.modelset.Atom> chainTerMap)
+  {
+    // System.out.println("Atom: " + curAtom.getAtomNumber()
+    // + "   Last atom index " + curAtom.group.lastAtomIndex);
+    if (chainTerMap == null || prevAtom == null)
+    {
+      return true;
+    }
+    String curAtomChId = curAtom.getChainIDStr();
+    String prevAtomChId = prevAtom.getChainIDStr();
+    // new chain encoutered
+    if (!prevAtomChId.equals(curAtomChId))
+    {
+      // On chain switch add previous chain termination to xTerMap if not exists
+      if (!chainTerMap.containsKey(prevAtomChId))
+      {
+        chainTerMap.put(prevAtomChId, prevAtom);
+      }
+      // if current atom belongs to an already terminated chain and the resNum
+      // diff < 5 then mark as valid and update termination Atom
+      if (chainTerMap.containsKey(curAtomChId))
+      {
+        if ((curAtom.getResno() - chainTerMap.get(curAtomChId).getResno()) < 5)
+        {
+          chainTerMap.put(curAtomChId, curAtom);
+          return true;
+        }
+        return false;
+      }
+    }
+    // atom with previously terminated chain encountered
+    else if (chainTerMap.containsKey(curAtomChId))
+    {
+      if ((curAtom.getResno() - chainTerMap.get(curAtomChId).getResno()) < 5)
+      {
+        chainTerMap.put(curAtomChId, curAtom);
+        return true;
+      }
+      return false;
+    }
+    // HETATM with resNum jump > 2
+    return !(curAtom.isHetero() && ((curAtom.getResno() - prevAtom
+            .getResno()) > 2));
+  }
+
   private void createAnnotation(SequenceI sequence, PDBChain chain,
           org.jmol.modelset.Atom[] jmolAtoms)
   {
@@ -398,7 +444,7 @@ public class JmolParser extends StructureFile implements JmolStatusListener
    * Not implemented - returns null
    */
   @Override
-  public String print()
+  public String print(SequenceI[] seqs, boolean jvSuffix)
   {
     return null;
   }
index 1554631..38223c7 100644 (file)
@@ -853,8 +853,9 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
     showGroupConservation.setEnabled(!nucleotide);
     rnahelicesColour.setEnabled(nucleotide);
     purinePyrimidineColour.setEnabled(nucleotide);
-    showComplementMenuItem.setText(MessageManager
-            .getString(nucleotide ? "label.protein" : "label.nucleotide"));
+    showComplementMenuItem.setText(nucleotide ? MessageManager
+            .getString("label.protein") : MessageManager
+            .getString("label.nucleotide"));
     setColourSelected(jalview.bin.Cache.getDefault(
             nucleotide ? Preferences.DEFAULT_COLOUR_NUC
                     : Preferences.DEFAULT_COLOUR_PROT, "None"));
@@ -1106,11 +1107,11 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
   @Override
   public void saveAs_actionPerformed(ActionEvent e)
   {
-    JalviewFileChooser chooser = new JalviewFileChooser(
+    JalviewFileChooser chooser = JalviewFileChooser.forWrite(
             Cache.getProperty("LAST_DIRECTORY"),
             // AppletFormatAdapter.WRITABLE_EXTENSIONS,
             // AppletFormatAdapter.WRITABLE_FNAMES,
-            currentFileFormat, false);
+            currentFileFormat.toString(), false);
 
     chooser.setFileView(new JalviewFileView());
     chooser.setDialogTitle(MessageManager
@@ -1866,7 +1867,8 @@ fileFormat,
       omitHidden = viewport.getViewAsString(true);
     }
 
-    String output = new FormatAdapter().formatSequences("Fasta", seqs,
+    String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
+            seqs,
             omitHidden, null);
 
     StringSelection ss = new StringSelection(output);
@@ -2438,7 +2440,10 @@ fileFormat,
     sg.setEndRes(viewport.getAlignment().getWidth() - 1);
     viewport.setSelectionGroup(sg);
     viewport.sendSelection();
-    alignPanel.paintAlignment(true);
+    // JAL-2034 - should delegate to
+    // alignPanel to decide if overview needs
+    // updating.
+    alignPanel.paintAlignment(false);
     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
   }
 
@@ -2461,7 +2466,10 @@ fileFormat,
     viewport.setSelectionGroup(null);
     alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
     alignPanel.getIdPanel().getIdCanvas().searchResults = null;
-    alignPanel.paintAlignment(true);
+    // JAL-2034 - should delegate to
+    // alignPanel to decide if overview needs
+    // updating.
+    alignPanel.paintAlignment(false);
     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
     viewport.sendSelection();
   }
@@ -2488,6 +2496,9 @@ fileFormat,
     {
       sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
     }
+    // JAL-2034 - should delegate to
+    // alignPanel to decide if overview needs
+    // updating.
 
     alignPanel.paintAlignment(true);
     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
@@ -2835,7 +2846,7 @@ fileFormat,
   @Override
   public void expandViews_actionPerformed(ActionEvent e)
   {
-    Desktop.instance.explodeViews(this);
+    Desktop.explodeViews(this);
   }
 
   /**
@@ -3214,30 +3225,6 @@ fileFormat,
   }
 
   /**
-   * Set or clear 'Show Sequence Features'
-   * 
-   * @param evt
-   *          DOCUMENT ME!
-   */
-  @Override
-  public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
-  {
-    viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
-            .isSelected());
-    if (viewport.isShowSequenceFeaturesHeight())
-    {
-      // ensure we're actually displaying features
-      viewport.setShowSequenceFeatures(true);
-      showSeqFeatures.setSelected(true);
-    }
-    alignPanel.paintAlignment(true);
-    if (alignPanel.getOverviewPanel() != null)
-    {
-      alignPanel.getOverviewPanel().updateOverviewImage();
-    }
-  }
-
-  /**
    * Action on toggle of the 'Show annotations' menu item. This shows or hides
    * the annotations panel as a whole.
    * 
@@ -4462,22 +4449,18 @@ fileFormat,
           // object broker mechanism.
           final Vector<JMenu> wsmenu = new Vector<JMenu>();
           final IProgressIndicator af = me;
+
+          /*
+           * do not i18n these strings - they are hard-coded in class
+           * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
+           * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
+           */
           final JMenu msawsmenu = new JMenu("Alignment");
           final JMenu secstrmenu = new JMenu(
                   "Secondary Structure Prediction");
           final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
           final JMenu analymenu = new JMenu("Analysis");
           final JMenu dismenu = new JMenu("Protein Disorder");
-          // final JMenu msawsmenu = new
-          // JMenu(MessageManager.getString("label.alignment"));
-          // final JMenu secstrmenu = new
-          // JMenu(MessageManager.getString("label.secondary_structure_prediction"));
-          // final JMenu seqsrchmenu = new
-          // JMenu(MessageManager.getString("label.sequence_database_search"));
-          // final JMenu analymenu = new
-          // JMenu(MessageManager.getString("label.analysis"));
-          // final JMenu dismenu = new
-          // JMenu(MessageManager.getString("label.protein_disorder"));
           // JAL-940 - only show secondary structure prediction services from
           // the legacy server
           if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
@@ -4637,38 +4620,38 @@ fileFormat,
   }
 
   /**
-   * Searches selected sequences for xRef products and builds the Show
-   * Cross-References menu (formerly called Show Products)
+   * Searches the alignment sequences for xRefs and builds the Show
+   * Cross-References menu (formerly called Show Products), with database
+   * sources for which cross-references are found (protein sources for a
+   * nucleotide alignment and vice versa)
    * 
-   * @return true if Show Cross-references menu should be enabled.
+   * @return true if Show Cross-references menu should be enabled
    */
   public boolean canShowProducts()
   {
-    SequenceI[] selection = viewport.getSequenceSelection();
+    SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
     AlignmentI dataset = viewport.getAlignment().getDataset();
     boolean showp = false;
     try
     {
       showProducts.removeAll();
       final boolean dna = viewport.getAlignment().isNucleotide();
-      String[] ptypes = (selection == null || selection.length == 0) ? null
-              : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
+      List<String> ptypes = (seqs == null || seqs.length == 0) ? null
+              : new CrossRef(seqs, dataset)
+                      .findXrefSourcesForSequences(dna);
 
-      for (int t = 0; ptypes != null && t < ptypes.length; t++)
+      for (final String source : ptypes)
       {
         showp = true;
         final AlignFrame af = this;
-        final String source = ptypes[t];
-        JMenuItem xtype = new JMenuItem(ptypes[t]);
+        JMenuItem xtype = new JMenuItem(source);
         xtype.addActionListener(new ActionListener()
         {
-
           @Override
           public void actionPerformed(ActionEvent e)
           {
             showProductsFor(af.viewport.getSequenceSelection(), dna, source);
           }
-
         });
         showProducts.add(xtype);
       }
@@ -4676,7 +4659,7 @@ fileFormat,
       showProducts.setEnabled(showp);
     } catch (Exception e)
     {
-      jalview.bin.Cache.log
+      Cache.log
               .warn("canShowProducts threw an exception - please report to help@jalview.org",
                       e);
       return false;
@@ -4695,8 +4678,8 @@ fileFormat,
    * @param source
    *          the database to show cross-references for
    */
-  protected void showProductsFor(final SequenceI[] sel, final boolean dna,
-          final String source)
+  protected void showProductsFor(final SequenceI[] sel,
+          final boolean _odna, final String source)
   {
     Runnable foo = new Runnable()
     {
@@ -4712,61 +4695,60 @@ fileFormat,
         {
           AlignmentI alignment = AlignFrame.this.getViewport()
                   .getAlignment();
-          AlignmentI xrefs = CrossRef.findXrefSequences(sel, dna, source,
-                  alignment);
-          if (xrefs != null)
+          AlignmentI dataset = alignment.getDataset() == null ? alignment
+                  : alignment.getDataset();
+          boolean dna = alignment.isNucleotide();
+          if (_odna != dna)
           {
-            /*
-             * get display scheme (if any) to apply to features
-             */
-            FeatureSettingsModelI featureColourScheme = new SequenceFetcher()
-                    .getFeatureColourScheme(source);
-
-            AlignmentI al = makeCrossReferencesAlignment(
-                    alignment.getDataset(), xrefs);
+            System.err
+                    .println("Conflict: showProducts for alignment originally "
+                            + "thought to be "
+                            + (_odna ? "DNA" : "Protein")
+                            + " now searching for "
+                            + (dna ? "DNA" : "Protein") + " Context.");
+          }
+          AlignmentI xrefs = new CrossRef(sel, dataset).findXrefSequences(
+                  source, dna);
+          if (xrefs == null)
+          {
+            return;
+          }
+          /*
+           * get display scheme (if any) to apply to features
+           */
+          FeatureSettingsModelI featureColourScheme = new SequenceFetcher()
+                  .getFeatureColourScheme(source);
 
-            AlignFrame newFrame = new AlignFrame(al, DEFAULT_WIDTH,
-                    DEFAULT_HEIGHT);
-            if (Cache.getDefault("HIDE_INTRONS", true))
-            {
-              newFrame.hideFeatureColumns(SequenceOntologyI.EXON, false);
-            }
-            String newtitle = String.format("%s %s %s",
-                    MessageManager.getString(dna ? "label.proteins"
-                            : "label.nucleotides"), MessageManager
-                            .getString("label.for"), getTitle());
-            newFrame.setTitle(newtitle);
+          AlignmentI xrefsAlignment = makeCrossReferencesAlignment(dataset,
+                  xrefs);
+          if (!dna)
+          {
+            xrefsAlignment = AlignmentUtils.makeCdsAlignment(
+                    xrefsAlignment.getSequencesArray(), dataset, sel);
+            xrefsAlignment.alignAs(alignment);
+          }
 
-            if (!Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
-            {
-              /*
-               * split frame display is turned off in preferences file
-               */
-              Desktop.addInternalFrame(newFrame, newtitle, DEFAULT_WIDTH,
-                      DEFAULT_HEIGHT);
-              return; // via finally clause
-            }
+          /*
+           * If we are opening a splitframe, make a copy of this alignment (sharing the same dataset
+           * sequences). If we are DNA, drop introns and update mappings
+           */
+          AlignmentI copyAlignment = null;
 
-            /*
-             * Make a copy of this alignment (sharing the same dataset
-             * sequences). If we are DNA, drop introns and update mappings
-             */
-            AlignmentI copyAlignment = null;
-            final SequenceI[] sequenceSelection = AlignFrame.this.viewport
-                    .getSequenceSelection();
-            List<AlignedCodonFrame> cf = xrefs.getCodonFrames();
+          if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
+          {
             boolean copyAlignmentIsAligned = false;
             if (dna)
             {
-              copyAlignment = AlignmentUtils.makeCdsAlignment(
-                      sequenceSelection, cf, alignment);
+              copyAlignment = AlignmentUtils.makeCdsAlignment(sel, dataset,
+                      xrefsAlignment.getSequencesArray());
               if (copyAlignment.getHeight() == 0)
               {
+                JOptionPane.showMessageDialog(AlignFrame.this,
+                        MessageManager.getString("label.cant_map_cds"),
+                        MessageManager.getString("label.operation_failed"),
+                        JOptionPane.OK_OPTION);
                 System.err.println("Failed to make CDS alignment");
               }
-              al.getCodonFrames().clear();
-              al.addCodonFrames(copyAlignment.getCodonFrames());
-              al.addCodonFrames(cf);
 
               /*
                * pending getting Embl transcripts to 'align', 
@@ -4782,18 +4764,20 @@ fileFormat,
             }
             else
             {
-              copyAlignment = AlignmentUtils.makeCopyAlignment(
-                      sequenceSelection, xrefs.getSequencesArray());
-              copyAlignment.addCodonFrames(cf);
-              al.addCodonFrames(copyAlignment.getCodonFrames());
-              al.addCodonFrames(cf);
+              copyAlignment = AlignmentUtils.makeCopyAlignment(sel,
+                      xrefs.getSequencesArray(), dataset);
             }
             copyAlignment.setGapCharacter(AlignFrame.this.viewport
                     .getGapCharacter());
 
             StructureSelectionManager ssm = StructureSelectionManager
                     .getStructureSelectionManager(Desktop.instance);
-            ssm.registerMappings(cf);
+
+            /*
+             * register any new mappings for sequence mouseover etc
+             * (will not duplicate any previously registered mappings)
+             */
+            ssm.registerMappings(dataset.getCodonFrames());
 
             if (copyAlignment.getHeight() <= 0)
             {
@@ -4806,7 +4790,7 @@ fileFormat,
              */
             if (dna && copyAlignmentIsAligned)
             {
-              al.alignAs(copyAlignment);
+              xrefsAlignment.alignAs(copyAlignment);
             }
             else
             {
@@ -4814,54 +4798,72 @@ fileFormat,
                * align cdna to protein - currently only if 
                * fetching and aligning Ensembl transcripts!
                */
-              if (DBRefSource.ENSEMBL.equalsIgnoreCase(source))
+              // TODO: generalise for other sources of locus/transcript/cds data
+              if (dna && DBRefSource.ENSEMBL.equalsIgnoreCase(source))
               {
-                copyAlignment.alignAs(al);
+                copyAlignment.alignAs(xrefsAlignment);
               }
             }
+          }
+          /*
+           * build AlignFrame(s) according to available alignment data
+           */
+          AlignFrame newFrame = new AlignFrame(xrefsAlignment,
+                  DEFAULT_WIDTH, DEFAULT_HEIGHT);
+          if (Cache.getDefault("HIDE_INTRONS", true))
+          {
+            newFrame.hideFeatureColumns(SequenceOntologyI.EXON, false);
+          }
+          String newtitle = String.format("%s %s %s",
+                  dna ? MessageManager.getString("label.proteins")
+                          : MessageManager.getString("label.nucleotides"),
+                  MessageManager.getString("label.for"), getTitle());
+          newFrame.setTitle(newtitle);
 
-            AlignFrame copyThis = new AlignFrame(copyAlignment,
-                    AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
-            copyThis.setTitle(AlignFrame.this.getTitle());
-
-            boolean showSequenceFeatures = viewport
-                    .isShowSequenceFeatures();
-            newFrame.setShowSeqFeatures(showSequenceFeatures);
-            copyThis.setShowSeqFeatures(showSequenceFeatures);
-            FeatureRenderer myFeatureStyling = alignPanel.getSeqPanel().seqCanvas
-                    .getFeatureRenderer();
-
-            /*
-             * copy feature rendering settings to split frame
-             */
-            newFrame.alignPanel.getSeqPanel().seqCanvas
-                    .getFeatureRenderer()
-                    .transferSettings(myFeatureStyling);
-            copyThis.alignPanel.getSeqPanel().seqCanvas
-                    .getFeatureRenderer()
-                    .transferSettings(myFeatureStyling);
-
+          if (copyAlignment == null)
+          {
             /*
-             * apply 'database source' feature configuration
-             * if any was found
+             * split frame display is turned off in preferences file
              */
-            // TODO is this the feature colouring for the original
-            // alignment or the fetched xrefs? either could be Ensembl
-            newFrame.getViewport().applyFeaturesStyle(featureColourScheme);
-            copyThis.getViewport().applyFeaturesStyle(featureColourScheme);
-
-            SplitFrame sf = new SplitFrame(dna ? copyThis : newFrame,
-                    dna ? newFrame : copyThis);
-            newFrame.setVisible(true);
-            copyThis.setVisible(true);
-            String linkedTitle = MessageManager
-                    .getString("label.linked_view_title");
-            Desktop.addInternalFrame(sf, linkedTitle, -1, -1);
-            sf.adjustDivider();
+            Desktop.addInternalFrame(newFrame, newtitle, DEFAULT_WIDTH,
+                    DEFAULT_HEIGHT);
+            return; // via finally clause
           }
-        } catch (Exception e)
-        {
-          Cache.log.error("Exception when finding crossreferences", e);
+          AlignFrame copyThis = new AlignFrame(copyAlignment,
+                  AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
+          copyThis.setTitle(AlignFrame.this.getTitle());
+
+          boolean showSequenceFeatures = viewport.isShowSequenceFeatures();
+          newFrame.setShowSeqFeatures(showSequenceFeatures);
+          copyThis.setShowSeqFeatures(showSequenceFeatures);
+          FeatureRenderer myFeatureStyling = alignPanel.getSeqPanel().seqCanvas
+                  .getFeatureRenderer();
+
+          /*
+           * copy feature rendering settings to split frame
+           */
+          newFrame.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
+                  .transferSettings(myFeatureStyling);
+          copyThis.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
+                  .transferSettings(myFeatureStyling);
+
+          /*
+           * apply 'database source' feature configuration
+           * if any was found
+           */
+          // TODO is this the feature colouring for the original
+          // alignment or the fetched xrefs? either could be Ensembl
+          newFrame.getViewport().applyFeaturesStyle(featureColourScheme);
+          copyThis.getViewport().applyFeaturesStyle(featureColourScheme);
+
+          SplitFrame sf = new SplitFrame(dna ? copyThis : newFrame,
+                  dna ? newFrame : copyThis);
+          newFrame.setVisible(true);
+          copyThis.setVisible(true);
+          String linkedTitle = MessageManager
+                  .getString("label.linked_view_title");
+          Desktop.addInternalFrame(sf, linkedTitle, -1, -1);
+          sf.adjustDivider();
         } catch (OutOfMemoryError e)
         {
           new OOMWarning("whilst fetching crossreferences", e);
@@ -4877,11 +4879,10 @@ fileFormat,
       }
 
       /**
-       * Makes an alignment containing the given sequences. If this is of the
-       * same type as the given dataset (nucleotide/protein), then the new
-       * alignment shares the same dataset, and its dataset sequences are added
-       * to it. Otherwise a new dataset sequence is created for the
-       * cross-references.
+       * Makes an alignment containing the given sequences, and adds them to the
+       * given dataset, which is also set as the dataset for the new alignment
+       * 
+       * TODO: refactor to DatasetI method
        * 
        * @param dataset
        * @param seqs
@@ -4890,32 +4891,20 @@ fileFormat,
       protected AlignmentI makeCrossReferencesAlignment(AlignmentI dataset,
               AlignmentI seqs)
       {
-        boolean sameType = dataset.isNucleotide() == seqs.isNucleotide();
-
         SequenceI[] sprods = new SequenceI[seqs.getHeight()];
         for (int s = 0; s < sprods.length; s++)
         {
           sprods[s] = (seqs.getSequenceAt(s)).deriveSequence();
-          if (sameType)
+          if (dataset.getSequences() == null
+                  || !dataset.getSequences().contains(
+                          sprods[s].getDatasetSequence()))
           {
-            if (dataset.getSequences() == null
-                    || !dataset.getSequences().contains(
-                            sprods[s].getDatasetSequence()))
-            {
-              dataset.addSequence(sprods[s].getDatasetSequence());
-            }
+            dataset.addSequence(sprods[s].getDatasetSequence());
           }
           sprods[s].updatePDBIds();
         }
         Alignment al = new Alignment(sprods);
-        if (sameType)
-        {
-          al.setDataset((Alignment) dataset);
-        }
-        else
-        {
-          al.createDatasetAlignment();
-        }
+        al.setDataset(dataset);
         return al;
       }
 
index 2f0d78b..d4d2054 100644 (file)
@@ -507,17 +507,6 @@ public class AlignViewport extends AlignmentViewport implements
   /**
    * DOCUMENT ME!
    * 
-   * @return DOCUMENT ME!
-   */
-  @Override
-  public ColumnSelection getColumnSelection()
-  {
-    return colSel;
-  }
-
-  /**
-   * DOCUMENT ME!
-   * 
    * @param tree
    *          DOCUMENT ME!
    */
index f06ca94..87d5933 100644 (file)
@@ -1269,6 +1269,7 @@ public class AlignmentPanel extends GAlignmentPanel implements
 
   void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
   {
+    int boarderBottomOffset = 5;
     long pSessionId = System.currentTimeMillis();
     headless = (System.getProperty("java.awt.headless") != null && System
             .getProperty("java.awt.headless").equals("true"));
@@ -1305,14 +1306,15 @@ public class AlignmentPanel extends GAlignmentPanel implements
         }
 
         im = new jalview.util.ImageMaker(this, type, imageAction,
-                aDimension.getWidth(), aDimension.getHeight(), file,
+                aDimension.getWidth(), aDimension.getHeight()
+                        + boarderBottomOffset, file,
                 imageTitle, alignFrame, pSessionId, headless);
         if (av.getWrapAlignment())
         {
           if (im.getGraphics() != null)
           {
             printWrappedAlignment(im.getGraphics(), aDimension.getWidth(),
-                    aDimension.getHeight(), 0);
+                    aDimension.getHeight() + boarderBottomOffset, 0);
             im.writeImage();
           }
         }
index 19eed27..93c9a6b 100644 (file)
@@ -141,7 +141,7 @@ public class AnnotationColourChooser extends AnnotationRowFilter
       default:
         throw new Error(
                 MessageManager
-                        .getString("error.implementation_error_dont_know_about_thereshold_setting"));
+                        .getString("error.implementation_error_dont_know_about_threshold_setting"));
       }
       thresholdIsMin.setSelected(acg.thresholdIsMinMax);
       thresholdValue.setText("" + acg.getAnnotationThreshold());
index c72cfaf..d497488 100755 (executable)
@@ -245,6 +245,7 @@ public class AnnotationLabels extends JPanel implements MouseListener,
     else if (evt.getActionCommand().equals(DELETE))
     {
       ap.av.getAlignment().deleteAnnotation(aa[selectedRow]);
+      ap.av.getCalcManager().removeWorkerForAnnotation(aa[selectedRow]);
     }
     else if (evt.getActionCommand().equals(SHOWALL))
     {
index bb311ef..6a621ff 100755 (executable)
@@ -26,6 +26,8 @@ import jalview.datamodel.ColumnSelection;
 import jalview.datamodel.SequenceI;
 import jalview.renderer.AnnotationRenderer;
 import jalview.renderer.AwtRenderPanelI;
+import jalview.schemes.ResidueProperties;
+import jalview.util.Comparison;
 import jalview.util.MessageManager;
 
 import java.awt.AlphaComposite;
@@ -47,6 +49,8 @@ import java.awt.event.MouseMotionListener;
 import java.awt.event.MouseWheelEvent;
 import java.awt.event.MouseWheelListener;
 import java.awt.image.BufferedImage;
+import java.util.Collections;
+import java.util.List;
 
 import javax.swing.JColorChooser;
 import javax.swing.JMenuItem;
@@ -286,14 +290,18 @@ public class AnnotationPanel extends JPanel implements AwtRenderPanelI,
       aa[activeRow].annotations = anot;
     }
 
-    if (evt.getActionCommand().equals(REMOVE))
+    String action = evt.getActionCommand();
+    if (action.equals(REMOVE))
     {
-      for (int sel : av.getColumnSelection().getSelected())
+      for (int index : av.getColumnSelection().getSelected())
       {
-        anot[sel] = null;
+        if (av.getColumnSelection().isVisible(index))
+        {
+          anot[index] = null;
+        }
       }
     }
-    else if (evt.getActionCommand().equals(LABEL))
+    else if (action.equals(LABEL))
     {
       String exMesg = collectAnnotVals(anot, LABEL);
       String label = JOptionPane.showInputDialog(this,
@@ -318,10 +326,7 @@ public class AnnotationPanel extends JPanel implements AwtRenderPanelI,
 
         if (anot[index] == null)
         {
-          anot[index] = new Annotation(label, "", ' ', 0); // TODO: verify that
-          // null exceptions
-          // aren't raised
-          // elsewhere.
+          anot[index] = new Annotation(label, "", ' ', 0);
         }
         else
         {
@@ -329,7 +334,7 @@ public class AnnotationPanel extends JPanel implements AwtRenderPanelI,
         }
       }
     }
-    else if (evt.getActionCommand().equals(COLOUR))
+    else if (action.equals(COLOUR))
     {
       Color col = JColorChooser.showDialog(this,
               MessageManager.getString("label.select_foreground_colour"),
@@ -351,26 +356,27 @@ public class AnnotationPanel extends JPanel implements AwtRenderPanelI,
       }
     }
     else
-    // HELIX OR SHEET
+    // HELIX, SHEET or STEM
     {
       char type = 0;
-      String symbol = "\u03B1";
+      String symbol = "\u03B1"; // alpha
 
-      if (evt.getActionCommand().equals(HELIX))
+      if (action.equals(HELIX))
       {
         type = 'H';
       }
-      else if (evt.getActionCommand().equals(SHEET))
+      else if (action.equals(SHEET))
       {
         type = 'E';
-        symbol = "\u03B2";
+        symbol = "\u03B2"; // beta
       }
 
       // Added by LML to color stems
-      else if (evt.getActionCommand().equals(STEM))
+      else if (action.equals(STEM))
       {
         type = 'S';
-        symbol = "\u03C3";
+        int column = av.getColumnSelection().getSelectedRanges().get(0)[0];
+        symbol = aa[activeRow].getDefaultRnaHelixSymbol(column);
       }
 
       if (!aa[activeRow].hasIcons)
@@ -389,7 +395,7 @@ public class AnnotationPanel extends JPanel implements AwtRenderPanelI,
       if ((label.length() > 0) && !aa[activeRow].hasText)
       {
         aa[activeRow].hasText = true;
-        if (evt.getActionCommand().equals(STEM))
+        if (action.equals(STEM))
         {
           aa[activeRow].showAllColLabels = true;
         }
@@ -412,22 +418,37 @@ public class AnnotationPanel extends JPanel implements AwtRenderPanelI,
 
       }
     }
+
     av.getAlignment().validateAnnotation(aa[activeRow]);
     ap.alignmentChanged();
-
+    ap.alignFrame.setMenusForViewport();
     adjustPanelHeight();
     repaint();
 
     return;
   }
 
-  private String collectAnnotVals(Annotation[] anot, String label2)
+  /**
+   * Returns any existing annotation concatenated as a string. For each
+   * annotation, takes the description, if any, else the secondary structure
+   * character (if type is HELIX, SHEET or STEM), else the display character (if
+   * type is LABEL).
+   * 
+   * @param anots
+   * @param type
+   * @return
+   */
+  private String collectAnnotVals(Annotation[] anots, String type)
   {
-    String collatedInput = "";
+    // TODO is this method wanted? why? 'last' is not used
+
+    StringBuilder collatedInput = new StringBuilder(64);
     String last = "";
     ColumnSelection viscols = av.getColumnSelection();
     // TODO: refactor and save av.getColumnSelection for efficiency
-    for (int index : viscols.getSelected())
+    List<Integer> selected = viscols.getSelected();
+    Collections.sort(selected);
+    for (int index : selected)
     {
       // always check for current display state - just in case
       if (!viscols.isVisible(index))
@@ -435,22 +456,22 @@ public class AnnotationPanel extends JPanel implements AwtRenderPanelI,
         continue;
       }
       String tlabel = null;
-      if (anot[index] != null)
+      if (anots[index] != null)
       { // LML added stem code
-        if (label2.equals(HELIX) || label2.equals(SHEET)
-                || label2.equals(STEM) || label2.equals(LABEL))
+        if (type.equals(HELIX) || type.equals(SHEET)
+                || type.equals(STEM) || type.equals(LABEL))
         {
-          tlabel = anot[index].description;
+          tlabel = anots[index].description;
           if (tlabel == null || tlabel.length() < 1)
           {
-            if (label2.equals(HELIX) || label2.equals(SHEET)
-                    || label2.equals(STEM))
+            if (type.equals(HELIX) || type.equals(SHEET)
+                    || type.equals(STEM))
             {
-              tlabel = "" + anot[index].secondaryStructure;
+              tlabel = "" + anots[index].secondaryStructure;
             }
             else
             {
-              tlabel = "" + anot[index].displayCharacter;
+              tlabel = "" + anots[index].displayCharacter;
             }
           }
         }
@@ -458,13 +479,13 @@ public class AnnotationPanel extends JPanel implements AwtRenderPanelI,
         {
           if (last.length() > 0)
           {
-            collatedInput += " ";
+            collatedInput.append(" ");
           }
-          collatedInput += tlabel;
+          collatedInput.append(tlabel);
         }
       }
     }
-    return collatedInput;
+    return collatedInput.toString();
   }
 
   /**
@@ -512,7 +533,8 @@ public class AnnotationPanel extends JPanel implements AwtRenderPanelI,
 
     if (evt.isPopupTrigger() && activeRow != -1)
     {
-      if (av.getColumnSelection() == null)
+      if (av.getColumnSelection() == null
+              || av.getColumnSelection().isEmpty())
       {
         return;
       }
@@ -523,7 +545,7 @@ public class AnnotationPanel extends JPanel implements AwtRenderPanelI,
       /*
        * Just display the needed structure options
        */
-      if (av.getAlignment().isNucleotide() == true)
+      if (av.getAlignment().isNucleotide())
       {
         item = new JMenuItem(STEM);
         item.addActionListener(this);
@@ -552,11 +574,6 @@ public class AnnotationPanel extends JPanel implements AwtRenderPanelI,
       return;
     }
 
-    if (aa == null)
-    {
-      return;
-    }
-
     ap.getScalePanel().mousePressed(evt);
 
   }
@@ -628,10 +645,10 @@ public class AnnotationPanel extends JPanel implements AwtRenderPanelI,
   }
 
   /**
-   * DOCUMENT ME!
+   * Constructs the tooltip, and constructs and displays a status message, for
+   * the current mouse position
    * 
    * @param evt
-   *          DOCUMENT ME!
    */
   @Override
   public void mouseMoved(MouseEvent evt)
@@ -657,7 +674,6 @@ public class AnnotationPanel extends JPanel implements AwtRenderPanelI,
       if (evt.getY() < height)
       {
         row = i;
-
         break;
       }
     }
@@ -668,64 +684,140 @@ public class AnnotationPanel extends JPanel implements AwtRenderPanelI,
       return;
     }
 
-    int res = (evt.getX() / av.getCharWidth()) + av.getStartRes();
+    int column = (evt.getX() / av.getCharWidth()) + av.getStartRes();
 
     if (av.hasHiddenColumns())
     {
-      res = av.getColumnSelection().adjustForHiddenColumns(res);
+      column = av.getColumnSelection().adjustForHiddenColumns(column);
     }
 
-    if (row > -1 && aa[row].annotations != null
-            && res < aa[row].annotations.length)
+    AlignmentAnnotation ann = aa[row];
+    if (row > -1 && ann.annotations != null
+            && column < ann.annotations.length)
+    {
+      buildToolTip(ann, column, aa);
+      setStatusMessage(column, ann);
+    }
+    else
     {
-      if (aa[row].graphGroup > -1)
+      this.setToolTipText(null);
+      ap.alignFrame.statusBar.setText(" ");
+    }
+  }
+
+  /**
+   * Builds a tooltip for the annotation at the current mouse position.
+   * 
+   * @param ann
+   * @param column
+   * @param anns
+   */
+  void buildToolTip(AlignmentAnnotation ann, int column,
+          AlignmentAnnotation[] anns)
+  {
+    if (ann.graphGroup > -1)
+    {
+      StringBuilder tip = new StringBuilder(32);
+      tip.append("<html>");
+      for (int i = 0; i < anns.length; i++)
       {
-        StringBuffer tip = new StringBuffer("<html>");
-        for (int gg = 0; gg < aa.length; gg++)
+        if (anns[i].graphGroup == ann.graphGroup
+                && anns[i].annotations[column] != null)
         {
-          if (aa[gg].graphGroup == aa[row].graphGroup
-                  && aa[gg].annotations[res] != null)
+          tip.append(anns[i].label);
+          String description = anns[i].annotations[column].description;
+          if (description != null && description.length() > 0)
           {
-            tip.append(aa[gg].label + " "
-                    + aa[gg].annotations[res].description + "<br>");
+            tip.append(" ").append(description);
           }
-        }
-        if (tip.length() != 6)
-        {
-          tip.setLength(tip.length() - 4);
-          this.setToolTipText(tip.toString() + "</html>");
+          tip.append("<br>");
         }
       }
-      else if (aa[row].annotations[res] != null
-              && aa[row].annotations[res].description != null
-              && aa[row].annotations[res].description.length() > 0)
+      if (tip.length() != 6)
       {
-        this.setToolTipText(JvSwingUtils.wrapTooltip(true,
-                aa[row].annotations[res].description));
+        tip.setLength(tip.length() - 4);
+        this.setToolTipText(tip.toString() + "</html>");
       }
-      else
+    }
+    else if (ann.annotations[column] != null)
+    {
+      String description = ann.annotations[column].description;
+      if (description != null && description.length() > 0)
       {
-        // clear the tooltip.
-        this.setToolTipText(null);
+        this.setToolTipText(JvSwingUtils.wrapTooltip(true, description));
       }
+    }
+    else
+    {
+      // clear the tooltip.
+      this.setToolTipText(null);
+    }
+  }
 
-      if (aa[row].annotations[res] != null)
+  /**
+   * Constructs and displays the status bar message
+   * 
+   * @param column
+   * @param ann
+   */
+  void setStatusMessage(int column, AlignmentAnnotation ann)
+  {
+    /*
+     * show alignment column and annotation description if any
+     */
+    StringBuilder text = new StringBuilder(32);
+    text.append(MessageManager.getString("label.column")).append(" ")
+            .append(column + 1);
+
+    if (ann.annotations[column] != null)
+    {
+      String description = ann.annotations[column].description;
+      if (description != null && description.trim().length() > 0)
       {
-        StringBuffer text = new StringBuffer("Sequence position "
-                + (res + 1));
+        text.append("  ").append(description);
+      }
+    }
 
-        if (aa[row].annotations[res].description != null)
+    /*
+     * if the annotation is sequence-specific, show the sequence number
+     * in the alignment, and (if not a gap) the residue and position
+     */
+    SequenceI seqref = ann.sequenceRef;
+    if (seqref != null)
+    {
+      int seqIndex = av.getAlignment().findIndex(seqref);
+      if (seqIndex != -1)
+      {
+        text.append(", ")
+                .append(MessageManager.getString("label.sequence"))
+                .append(" ")
+                .append(seqIndex + 1);
+        char residue = seqref.getCharAt(column);
+        if (!Comparison.isGap(residue))
         {
-          text.append("  " + aa[row].annotations[res].description);
+          text.append(" ");
+          String name;
+          if (av.getAlignment().isNucleotide())
+          {
+            name = ResidueProperties.nucleotideName.get(String
+                    .valueOf(residue));
+            text.append(" Nucleotide: ").append(
+                    name != null ? name : residue);
+          }
+          else
+          {
+            name = 'X' == residue ? "X" : ('*' == residue ? "STOP"
+                    : ResidueProperties.aa2Triplet.get(String
+                            .valueOf(residue)));
+            text.append(" Residue: ").append(name != null ? name : residue);
+          }
+          int residuePos = seqref.findPosition(column);
+          text.append(" (").append(residuePos).append(")");
         }
-
-        ap.alignFrame.statusBar.setText(text.toString());
       }
     }
-    else
-    {
-      this.setToolTipText(null);
-    }
+
+    ap.alignFrame.statusBar.setText(text.toString());
   }
 
   /**
index 17298ba..f0bea60 100644 (file)
@@ -257,11 +257,11 @@ public abstract class AnnotationRowFilter extends JPanel
   protected void populateThresholdComboBox(JComboBox<String> threshold)
   {
     threshold.addItem(MessageManager
-            .getString("label.threshold_feature_no_thereshold"));
+            .getString("label.threshold_feature_no_threshold"));
     threshold.addItem(MessageManager
-            .getString("label.threshold_feature_above_thereshold"));
+            .getString("label.threshold_feature_above_threshold"));
     threshold.addItem(MessageManager
-            .getString("label.threshold_feature_below_thereshold"));
+            .getString("label.threshold_feature_below_threshold"));
   }
 
   protected void seqAssociated_actionPerformed(ActionEvent arg0,
index 2e72e17..ab9aad7 100644 (file)
@@ -41,6 +41,7 @@ import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.Calendar;
 import java.util.Collections;
+import java.util.Date;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
@@ -285,6 +286,7 @@ public class BlogReader extends JPanel
   /**
    * check if the news panel's container is visible
    */
+  @Override
   public boolean isVisible()
   {
     if (parent == null)
@@ -312,6 +314,7 @@ public class BlogReader extends JPanel
           xf.setContentPane(me);
           xf.addWindowListener(new WindowAdapter()
           {
+            @Override
             public void windowClosing(WindowEvent e)
             {
               ActionEvent actionEvent = new ActionEvent(this,
@@ -320,6 +323,7 @@ public class BlogReader extends JPanel
               exitAction.actionPerformed(actionEvent);
             }
 
+            @Override
             public void windowOpened(WindowEvent e)
             {
             }
@@ -367,9 +371,9 @@ public class BlogReader extends JPanel
               + " and lastDate is " + lastDate);
       for (Item i : (List<Item>) chan.getItems())
       {
+        Date published = i.getPublishDate();
         boolean isread = lastDate == null ? false
-                : (i.getPublishDate() != null && !lastDate.before(i
-                        .getPublishDate()));
+                : (published != null && !lastDate.before(published));
 
         if (!updating || updateItems)
         {
@@ -379,11 +383,11 @@ public class BlogReader extends JPanel
         {
           i.setRead(isread);
         }
-        if (i.getPublishDate() != null && !i.isRead())
+        if (published != null && !i.isRead())
         {
-          if (earliest == null || earliest.after(i.getPublishDate()))
+          if (earliest == null || earliest.after(published))
           {
-            earliest = i.getPublishDate();
+            earliest = published;
           }
         }
       }
@@ -420,11 +424,9 @@ public class BlogReader extends JPanel
       }
       if (lastDate != null)
       {
-        jalview.bin.Cache.setDateProperty("JALVIEW_NEWS_RSS_LASTMODIFIED",
-                lastDate);
-        jalview.bin.Cache.log.debug("Saved last read date as "
-                + jalview.bin.Cache.date_format.format(lastDate));
-
+        String formatted = Cache.setDateProperty(
+                "JALVIEW_NEWS_RSS_LASTMODIFIED", lastDate);
+        Cache.log.debug("Saved last read date as " + formatted);
       }
     }
   }
@@ -472,6 +474,7 @@ public class BlogReader extends JPanel
 
     listItems.addMouseListener(new java.awt.event.MouseAdapter()
     {
+      @Override
       public void mouseClicked(MouseEvent e)
       {
         listItems_mouseClicked(e);
@@ -497,6 +500,7 @@ public class BlogReader extends JPanel
     }
     textDescription.addHyperlinkListener(new HyperlinkListener()
     {
+      @Override
       public void hyperlinkUpdate(HyperlinkEvent e)
       {
         if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
@@ -508,6 +512,7 @@ public class BlogReader extends JPanel
 
     listItems.addListSelectionListener(new ListSelectionListener()
     {
+      @Override
       public void valueChanged(ListSelectionEvent e)
       {
         if (e.getValueIsAdjusting() == false)
@@ -537,6 +542,7 @@ public class BlogReader extends JPanel
       _listItems = listItems;
     }
 
+    @Override
     public void actionPerformed(ActionEvent e)
     {
       Object o = _listItems.getSelectedValue();
@@ -550,6 +556,7 @@ public class BlogReader extends JPanel
       }
     }
 
+    @Override
     public void update(Object o)
     {
       setEnabled(true);
@@ -754,11 +761,10 @@ public class BlogReader extends JPanel
     lastread.set(1983, 01, 01);
     while (lastread.before(today))
     {
-      Cache.setDateProperty("JALVIEW_NEWS_RSS_LASTMODIFIED",
-              lastread.getTime());
+      String formattedDate = Cache.setDateProperty(
+              "JALVIEW_NEWS_RSS_LASTMODIFIED", lastread.getTime());
       BlogReader me = new BlogReader();
-      System.out.println("Set last date to "
-              + jalview.bin.Cache.date_format.format(lastread.getTime()));
+      System.out.println("Set last date to " + formattedDate);
       if (me.isNewsNew())
       {
         Cache.log.debug("There is news to read.");
@@ -810,6 +816,7 @@ class ChannelsRenderer extends DefaultListCellRenderer
   private final static Icon _icon = new ImageIcon(
           Main.class.getResource("image/ComposeMail16.gif"));
 
+  @Override
   public Component getListCellRendererComponent(JList list, Object value,
           int index, boolean isSelected, boolean cellHasFocus)
   {
@@ -837,6 +844,7 @@ class ItemsRenderer extends DefaultListCellRenderer
   private final static Icon _icon = new ImageIcon(
           Main.class.getResource("image/ComposeMail16.gif"));
 
+  @Override
   public Component getListCellRendererComponent(JList list, Object value,
           int index, boolean isSelected, boolean cellHasFocus)
   {
index b176672..e677084 100644 (file)
@@ -448,7 +448,7 @@ public class DasSourceBrowser extends GDasSourceBrowser implements
     seqs.setSelected(seqsrc);
     JPanel panel = new JPanel(new BorderLayout());
     JPanel pane12 = new JPanel(new BorderLayout());
-    pane12.add(new JLabel(MessageManager.getString("label.name")),
+    pane12.add(new JLabel(MessageManager.getString("label.name:")),
             BorderLayout.CENTER);
     pane12.add(nametf, BorderLayout.EAST);
     panel.add(pane12, BorderLayout.NORTH);
index 22a5203..624054b 100644 (file)
@@ -446,12 +446,11 @@ public class Desktop extends jalview.jbgui.GDesktop implements
       public void run()
       {
         Cache.log.debug("Filechooser init thread started.");
-        FileFormat fileFormat = FileFormat.valueOf(Cache
-                .getProperty("DEFAULT_FILE_FORMAT"));
-        new JalviewFileChooser(Cache.getProperty("LAST_DIRECTORY"),
+        String fileFormat = Cache.getProperty("DEFAULT_FILE_FORMAT");
+        JalviewFileChooser.forRead(Cache.getProperty("LAST_DIRECTORY"),
         // jalview.io.AppletFormatAdapter.READABLE_EXTENSIONS,
         // jalview.io.AppletFormatAdapter.READABLE_FNAMES,
-                fileFormat);
+                fileFormat, true);
         Cache.log.debug("Filechooser init thread finished.");
       }
     }).start();
@@ -1011,13 +1010,12 @@ public class Desktop extends jalview.jbgui.GDesktop implements
   @Override
   public void inputLocalFileMenuItem_actionPerformed(AlignViewport viewport)
   {
-    FileFormat fileFormat = FileFormat.valueOf(Cache
-            .getProperty("DEFAULT_FILE_FORMAT"));
-    JalviewFileChooser chooser = new JalviewFileChooser(
+    String fileFormat = Cache.getProperty("DEFAULT_FILE_FORMAT");
+    JalviewFileChooser chooser = JalviewFileChooser.forRead(
             Cache.getProperty("LAST_DIRECTORY"),
             // AppletFormatAdapter.READABLE_EXTENSIONS,
             // AppletFormatAdapter.READABLE_FNAMES,
-            fileFormat);
+            fileFormat, true);
 
     chooser.setFileView(new JalviewFileView());
     chooser.setDialogTitle(MessageManager
@@ -1070,7 +1068,7 @@ public class Desktop extends jalview.jbgui.GDesktop implements
    */
   @Override
   public void inputURLMenuItem_actionPerformed(AlignViewport viewport)
-          throws FileFormatException
+  // throws FileFormatException
   {
     // This construct allows us to have a wider textfield
     // for viewing
@@ -1125,10 +1123,17 @@ public class Desktop extends jalview.jbgui.GDesktop implements
     }
     else
     {
-      FileFormatI format = new IdentifyFile().identify(url,
-              DataSourceType.URL);
+      FileFormatI format = null;
+      try
+      {
+        format = new IdentifyFile().identify(url, DataSourceType.URL);
+      } catch (FileFormatException e)
+      {
+        // TODO revise error handling, distinguish between
+        // URL not found and response not valid
+      }
 
-      if (format.equals("URL NOT FOUND"))
+      if (format == null)
       {
         JOptionPane.showInternalMessageDialog(Desktop.desktop,
                 MessageManager.formatMessage("label.couldnt_locate",
@@ -1529,8 +1534,7 @@ public class Desktop extends jalview.jbgui.GDesktop implements
   public void saveState_actionPerformed(ActionEvent e)
   {
     JalviewFileChooser chooser = new JalviewFileChooser(
-            jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
-            new String[] { "jvp" }, new String[] { "Jalview Project" },
+            Cache.getProperty("LAST_DIRECTORY"), "jvp", "Jalview Project",
             "Jalview Project");
 
     chooser.setFileView(new JalviewFileView());
@@ -1601,7 +1605,7 @@ public class Desktop extends jalview.jbgui.GDesktop implements
   public void loadState_actionPerformed(ActionEvent e)
   {
     JalviewFileChooser chooser = new JalviewFileChooser(
-            jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[] {
+            Cache.getProperty("LAST_DIRECTORY"), new String[] {
                 "jvp", "jar" }, new String[] { "Jalview Project",
                 "Jalview Project (old)" }, "Jalview Project");
     chooser.setFileView(new JalviewFileView());
@@ -1614,7 +1618,7 @@ public class Desktop extends jalview.jbgui.GDesktop implements
       final File selectedFile = chooser.getSelectedFile();
       setProjectFile(selectedFile);
       final String choice = selectedFile.getAbsolutePath();
-      jalview.bin.Cache.setProperty("LAST_DIRECTORY",
+      Cache.setProperty("LAST_DIRECTORY",
               selectedFile.getParent());
       new Thread(new Runnable()
       {
@@ -1823,7 +1827,7 @@ public class Desktop extends jalview.jbgui.GDesktop implements
    * 
    * @param af
    */
-  public void explodeViews(AlignFrame af)
+  public static void explodeViews(AlignFrame af)
   {
     int size = af.alignPanels.size();
     if (size < 2)
@@ -2185,9 +2189,8 @@ public class Desktop extends jalview.jbgui.GDesktop implements
     if (v_client != null)
     {
       JalviewFileChooser chooser = new JalviewFileChooser(
-              jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
-              { "vdj" }, // TODO: VAMSAS DOCUMENT EXTENSION is VDJ
-              new String[] { "Vamsas Document" }, "Vamsas Document");
+              Cache.getProperty("LAST_DIRECTORY"), "vdj",
+              "Vamsas Document", "Vamsas Document");
 
       chooser.setFileView(new JalviewFileView());
       chooser.setDialogTitle(MessageManager
@@ -2201,7 +2204,7 @@ public class Desktop extends jalview.jbgui.GDesktop implements
         JPanel progpanel = addProgressPanel(MessageManager.formatMessage(
                 "label.saving_vamsas_doc",
                 new Object[] { choice.getName() }));
-        jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice.getParent());
+        Cache.setProperty("LAST_DIRECTORY", choice.getParent());
         String warnmsg = null;
         String warnttl = null;
         try
index 79217ea..5594e1a 100644 (file)
@@ -242,11 +242,11 @@ public class FeatureColourChooser extends JalviewDialog
     threshold.setToolTipText(MessageManager
             .getString("label.threshold_feature_display_by_score"));
     threshold.addItem(MessageManager
-            .getString("label.threshold_feature_no_thereshold")); // index 0
+            .getString("label.threshold_feature_no_threshold")); // index 0
     threshold.addItem(MessageManager
-            .getString("label.threshold_feature_above_thereshold")); // index 1
+            .getString("label.threshold_feature_above_threshold")); // index 1
     threshold.addItem(MessageManager
-            .getString("label.threshold_feature_below_thereshold")); // index 2
+            .getString("label.threshold_feature_below_threshold")); // index 2
     jPanel3.setLayout(flowLayout2);
     thresholdValue.addActionListener(new ActionListener()
     {
@@ -263,7 +263,7 @@ public class FeatureColourChooser extends JalviewDialog
     slider.setOpaque(false);
     slider.setPreferredSize(new Dimension(100, 32));
     slider.setToolTipText(MessageManager
-            .getString("label.adjust_thereshold"));
+            .getString("label.adjust_threshold"));
     thresholdValue.setEnabled(false);
     thresholdValue.setColumns(7);
     jPanel3.setBackground(Color.white);
index 1bf7453..426ea32 100644 (file)
@@ -75,9 +75,8 @@ public class FeatureRenderer extends
    */
   public FeatureRenderer(AlignmentPanel ap)
   {
-    super();
+    super(ap.av);
     this.ap = ap;
-    this.av = ap.av;
     if (ap != null && ap.getSeqPanel() != null
             && ap.getSeqPanel().seqCanvas != null
             && ap.getSeqPanel().seqCanvas.fr != null)
@@ -174,7 +173,8 @@ public class FeatureRenderer extends
     {
       panel = new JPanel(new GridLayout(4, 1));
       tmp = new JPanel();
-      tmp.add(new JLabel(MessageManager.getString("label.select_feature")));
+      tmp.add(new JLabel(MessageManager.getString("label.select_feature")
+              + ":"));
       overlaps = new JComboBox();
       for (int i = 0; i < features.length; i++)
       {
@@ -225,12 +225,13 @@ public class FeatureRenderer extends
 
     tmp = new JPanel();
     panel.add(tmp);
-    tmp.add(new JLabel(MessageManager.getString("label.name"), JLabel.RIGHT));
+    tmp.add(new JLabel(MessageManager.getString("label.name:"),
+            JLabel.RIGHT));
     tmp.add(name);
 
     tmp = new JPanel();
     panel.add(tmp);
-    tmp.add(new JLabel(MessageManager.getString("label.group") + ":",
+    tmp.add(new JLabel(MessageManager.getString("label.group:"),
             JLabel.RIGHT));
     tmp.add(source);
 
@@ -249,7 +250,7 @@ public class FeatureRenderer extends
     bigPanel.add(panel, BorderLayout.NORTH);
 
     panel = new JPanel();
-    panel.add(new JLabel(MessageManager.getString("label.description"),
+    panel.add(new JLabel(MessageManager.getString("label.description:"),
             JLabel.RIGHT));
     description.setFont(JvSwingUtils.getTextAreaFont());
     description.setLineWrap(true);
index bfc14b5..6dc5cb3 100644 (file)
@@ -174,7 +174,8 @@ public class FeatureSettings extends JPanel implements
       public void mousePressed(MouseEvent evt)
       {
         selectedRow = table.rowAtPoint(evt.getPoint());
-        if (SwingUtilities.isRightMouseButton(evt))
+        boolean ctrlDown = Platform.isControlDown(evt);
+        if (SwingUtilities.isRightMouseButton(evt) && !ctrlDown)
         {
           popupSort(selectedRow, (String) table.getValueAt(selectedRow, 0),
                   table.getValueAt(selectedRow, 1), fr.getMinMax(),
@@ -182,9 +183,11 @@ public class FeatureSettings extends JPanel implements
         }
         else if (evt.getClickCount() == 2)
         {
+          boolean invertSelection = evt.isAltDown();
+          boolean toggleSelection = ctrlDown;
+          boolean extendSelection = evt.isShiftDown();
           fr.ap.alignFrame.avc.markColumnsContainingFeatures(
-                  evt.isAltDown(), evt.isShiftDown() || evt.isMetaDown(),
-                  evt.isMetaDown(),
+                  invertSelection, extendSelection, toggleSelection,
                   (String) table.getValueAt(selectedRow, 0));
         }
       }
@@ -211,11 +214,20 @@ public class FeatureSettings extends JPanel implements
         int newRow = table.rowAtPoint(evt.getPoint());
         if (newRow != selectedRow && selectedRow != -1 && newRow != -1)
         {
+          /*
+           * reposition 'selectedRow' to 'newRow' (the dragged to location)
+           * this could be more than one row away for a very fast drag action
+           * so just swap it with adjacent rows until we get it there
+           */
           Object[][] data = ((FeatureTableModel) table.getModel())
                   .getData();
-          Object[] temp = data[selectedRow];
-          data[selectedRow] = data[newRow];
-          data[newRow] = temp;
+          int direction = newRow < selectedRow ? -1 : 1;
+          for (int i = selectedRow; i != newRow; i += direction)
+          {
+            Object[] temp = data[i];
+            data[i] = data[i + direction];
+            data[i + direction] = temp;
+          }
           updateFeatureRenderer(data);
           table.repaint();
           selectedRow = newRow;
@@ -383,7 +395,9 @@ public class FeatureSettings extends JPanel implements
               else
               {
                 // probably the color chooser!
-                table.setValueAt(colorChooser.getColor(), selectedRow, 1);
+                table.setValueAt(
+                        new FeatureColour(colorChooser.getColor()),
+                        selectedRow, 1);
                 table.validate();
                 me.updateFeatureRenderer(
                         ((FeatureTableModel) table.getModel()).getData(),
@@ -736,10 +750,8 @@ public class FeatureSettings extends JPanel implements
   void load()
   {
     JalviewFileChooser chooser = new JalviewFileChooser(
-            jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
-            new String[] { "fc" },
-            new String[] { "Sequence Feature Colours" },
-            "Sequence Feature Colours");
+            Cache.getProperty("LAST_DIRECTORY"), "fc",
+            "Sequence Feature Colours", "Sequence Feature Colours");
     chooser.setFileView(new jalview.io.JalviewFileView());
     chooser.setDialogTitle(MessageManager
             .getString("label.load_feature_colours"));
@@ -831,10 +843,8 @@ public class FeatureSettings extends JPanel implements
   void save()
   {
     JalviewFileChooser chooser = new JalviewFileChooser(
-            Cache.getProperty("LAST_DIRECTORY"),
-            new String[] { "fc" },
-            new String[] { "Sequence Feature Colours" },
-            "Sequence Feature Colours");
+            Cache.getProperty("LAST_DIRECTORY"), "fc",
+            "Sequence Feature Colours", "Sequence Feature Colours");
     chooser.setFileView(new jalview.io.JalviewFileView());
     chooser.setDialogTitle(MessageManager
             .getString("label.save_feature_colours"));
index 535196e..1f6c068 100755 (executable)
@@ -157,6 +157,7 @@ public class FontChooser extends GFontChooser
     init = false;
   }
 
+  @Override
   public void smoothFont_actionPerformed(ActionEvent e)
   {
     ap.av.antiAlias = smoothFont.isSelected();
@@ -170,6 +171,7 @@ public class FontChooser extends GFontChooser
    * @param e
    *          DOCUMENT ME!
    */
+  @Override
   protected void ok_actionPerformed(ActionEvent e)
   {
     try
@@ -194,6 +196,7 @@ public class FontChooser extends GFontChooser
    * @param e
    *          DOCUMENT ME!
    */
+  @Override
   protected void cancel_actionPerformed(ActionEvent e)
   {
     if (ap != null)
@@ -247,10 +250,10 @@ public class FontChooser extends GFontChooser
     double iw = iBounds.getWidth();
     if (mw < 1 || iw < 1)
     {
-      final String messageKey = iBounds.getHeight() < 1 ? "label.font_doesnt_have_letters_defined"
-              : "label.font_too_small";
-      JOptionPane.showInternalMessageDialog(this,
-              MessageManager.getString(messageKey),
+      String message = iBounds.getHeight() < 1 ? MessageManager
+              .getString("label.font_doesnt_have_letters_defined")
+              : MessageManager.getString("label.font_too_small");
+      JOptionPane.showInternalMessageDialog(this, message,
               MessageManager.getString("label.invalid_font"),
               JOptionPane.WARNING_MESSAGE);
       /*
@@ -301,6 +304,7 @@ public class FontChooser extends GFontChooser
    * @param e
    *          DOCUMENT ME!
    */
+  @Override
   protected void fontName_actionPerformed(ActionEvent e)
   {
     if (init)
@@ -317,6 +321,7 @@ public class FontChooser extends GFontChooser
    * @param e
    *          DOCUMENT ME!
    */
+  @Override
   protected void fontSize_actionPerformed(ActionEvent e)
   {
     if (init)
@@ -333,6 +338,7 @@ public class FontChooser extends GFontChooser
    * @param e
    *          DOCUMENT ME!
    */
+  @Override
   protected void fontStyle_actionPerformed(ActionEvent e)
   {
     if (init)
@@ -349,6 +355,7 @@ public class FontChooser extends GFontChooser
    * 
    * @param e
    */
+  @Override
   public void defaultButton_actionPerformed(ActionEvent e)
   {
     Cache.setProperty("FONT_NAME", fontName.getSelectedItem().toString());
index 1c2bfa6..35d4685 100644 (file)
@@ -37,6 +37,7 @@ import jalview.datamodel.StructureViewerModel.StructureData;
 import jalview.ext.varna.RnaModel;
 import jalview.gui.StructureViewer.ViewerType;
 import jalview.io.DataSourceType;
+import jalview.io.FileFormat;
 import jalview.schemabinding.version2.AlcodMap;
 import jalview.schemabinding.version2.AlcodonFrame;
 import jalview.schemabinding.version2.Annotation;
@@ -109,6 +110,7 @@ import java.lang.reflect.InvocationTargetException;
 import java.net.MalformedURLException;
 import java.net.URL;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.HashSet;
@@ -166,7 +168,9 @@ public class Jalview2XML
    */
   Map<String, SequenceI> seqRefIds = null;
 
-  Vector<Object[]> frefedSequence = null;
+  Map<String, SequenceI> incompleteSeqs = null;
+
+  List<SeqFref> frefedSequence = null;
 
   boolean raiseGUI = true; // whether errors are raised in dialog boxes or not
 
@@ -221,6 +225,10 @@ public class Jalview2XML
       {
         seqsToIds.clear();
       }
+      if (incompleteSeqs != null)
+      {
+        incompleteSeqs.clear();
+      }
       // seqRefIds = null;
       // seqsToIds = null;
     }
@@ -243,6 +251,14 @@ public class Jalview2XML
     {
       seqRefIds = new HashMap<String, SequenceI>();
     }
+    if (incompleteSeqs == null)
+    {
+      incompleteSeqs = new HashMap<String, SequenceI>();
+    }
+    if (frefedSequence == null)
+    {
+      frefedSequence = new ArrayList<SeqFref>();
+    }
   }
 
   public Jalview2XML()
@@ -254,78 +270,169 @@ public class Jalview2XML
     this.raiseGUI = raiseGUI;
   }
 
-  public void resolveFrefedSequences()
+  /**
+   * base class for resolving forward references to sequences by their ID
+   * 
+   * @author jprocter
+   *
+   */
+  abstract class SeqFref
   {
-    if (frefedSequence.size() > 0)
+    String sref;
+
+    String type;
+
+    public SeqFref(String _sref, String type)
+    {
+      sref = _sref;
+      this.type = type;
+    }
+
+    public String getSref()
+    {
+      return sref;
+    }
+
+    public SequenceI getSrefSeq()
+    {
+      return seqRefIds.get(sref);
+    }
+
+    public boolean isResolvable()
+    {
+      return seqRefIds.get(sref) != null;
+    }
+
+    public SequenceI getSrefDatasetSeq()
     {
-      int r = 0, rSize = frefedSequence.size();
-      while (r < rSize)
+      SequenceI sq = seqRefIds.get(sref);
+      if (sq != null)
       {
-        Object[] ref = frefedSequence.elementAt(r);
-        if (ref != null)
+        while (sq.getDatasetSequence() != null)
         {
-          String sref = (String) ref[0];
-          if (seqRefIds.containsKey(sref))
-          {
-            if (ref[1] instanceof jalview.datamodel.Mapping)
-            {
-              SequenceI seq = seqRefIds.get(sref);
-              while (seq.getDatasetSequence() != null)
-              {
-                seq = seq.getDatasetSequence();
-              }
-              ((jalview.datamodel.Mapping) ref[1]).setTo(seq);
-            }
-            else
-            {
-              if (ref[1] instanceof jalview.datamodel.AlignedCodonFrame)
-              {
-                SequenceI seq = seqRefIds.get(sref);
-                while (seq.getDatasetSequence() != null)
-                {
-                  seq = seq.getDatasetSequence();
-                }
-                if (ref[2] != null
-                        && ref[2] instanceof jalview.datamodel.Mapping)
-                {
-                  jalview.datamodel.Mapping mp = (jalview.datamodel.Mapping) ref[2];
-                  ((jalview.datamodel.AlignedCodonFrame) ref[1]).addMap(
-                          seq, mp.getTo(), mp.getMap());
-                }
-                else
-                {
-                  System.err
-                          .println("IMPLEMENTATION ERROR: Unimplemented forward sequence references for AlcodonFrames involving "
-                                  + ref[2].getClass() + " type objects.");
-                }
-              }
-              else
-              {
-                System.err
-                        .println("IMPLEMENTATION ERROR: Unimplemented forward sequence references for "
-                                + ref[1].getClass() + " type objects.");
-              }
-            }
-            frefedSequence.remove(r);
-            rSize--;
-          }
-          else
+          sq = sq.getDatasetSequence();
+        }
+      }
+      return sq;
+    }
+    /**
+     * @return true if the forward reference was fully resolved
+     */
+    abstract boolean resolve();
+
+    @Override
+    public String toString()
+    {
+      return type + " reference to " + sref;
+    }
+  }
+
+  /**
+   * create forward reference for a mapping
+   * 
+   * @param sref
+   * @param _jmap
+   * @return
+   */
+  public SeqFref newMappingRef(final String sref,
+          final jalview.datamodel.Mapping _jmap)
+  {
+    SeqFref fref = new SeqFref(sref, "Mapping")
+    {
+      public jalview.datamodel.Mapping jmap = _jmap;
+
+      @Override
+      boolean resolve()
+      {
+        SequenceI seq = getSrefDatasetSeq();
+        if (seq == null)
+        {
+          return false;
+        }
+        jmap.setTo(seq);
+        return true;
+      }
+    };
+    return fref;
+  }
+
+  public SeqFref newAlcodMapRef(final String sref,
+          final AlignedCodonFrame _cf, final jalview.datamodel.Mapping _jmap)
+  {
+
+    SeqFref fref = new SeqFref(sref, "Codon Frame")
+    {
+      AlignedCodonFrame cf = _cf;
+
+      public jalview.datamodel.Mapping mp = _jmap;
+
+      @Override
+      boolean resolve()
+      {
+        SequenceI seq = getSrefDatasetSeq();
+        if (seq == null)
+        {
+          return false;
+        }
+        cf.addMap(seq, mp.getTo(), mp.getMap());
+        return true;
+      }
+    };
+    return fref;
+  }
+
+  public void resolveFrefedSequences()
+  {
+    Iterator<SeqFref> nextFref=frefedSequence.iterator();
+    int toresolve=frefedSequence.size();
+    int unresolved=0,failedtoresolve=0;
+    while (nextFref.hasNext()) {
+      SeqFref ref = nextFref.next();
+      if (ref.isResolvable())
+      {
+        try {
+          if (ref.resolve())
           {
-            System.err
-                    .println("IMPLEMENTATION WARNING: Unresolved forward reference for hash string "
-                            + ref[0]
-                            + " with objecttype "
-                            + ref[1].getClass());
-            r++;
+            nextFref.remove();
+          } else {
+            failedtoresolve++;
           }
-        }
-        else
+        } catch (Exception x) {
+          System.err.println("IMPLEMENTATION ERROR: Failed to resolve forward reference for sequence "+ref.getSref());
+          x.printStackTrace();
+          failedtoresolve++;
+        } 
+      } else {
+        unresolved++;
+      }
+    }
+    if (unresolved>0)
+    {
+      System.err.println("Jalview Project Import: There were " + unresolved
+              + " forward references left unresolved on the stack.");
+    }
+    if (failedtoresolve>0)
+    {
+      System.err.println("SERIOUS! " + failedtoresolve
+              + " resolvable forward references failed to resolve.");
+    }
+    if (incompleteSeqs != null && incompleteSeqs.size() > 0)
+    {
+      System.err.println("Jalview Project Import: There are "
+              + incompleteSeqs.size()
+              + " sequences which may have incomplete metadata.");
+      if (incompleteSeqs.size() < 10)
+      {
+        for (SequenceI s : incompleteSeqs.values())
         {
-          // empty reference
-          frefedSequence.remove(r);
-          rSize--;
+          System.err.println(s.toString());
         }
       }
+      else
+      {
+        System.err
+                .println("Too many to report. Skipping output of incomplete sequences.");
+      }
     }
   }
 
@@ -397,7 +504,20 @@ public class Jalview2XML
     {
       return;
     }
+    saveAllFrames(Arrays.asList(frames), jout);
+  }
 
+  /**
+   * core method for storing state for a set of AlignFrames.
+   * 
+   * @param frames
+   *          - frames involving all data to be exported (including containing
+   *          splitframes)
+   * @param jout
+   *          - project output stream
+   */
+  private void saveAllFrames(List<AlignFrame> frames, JarOutputStream jout)
+  {
     Hashtable<String, AlignFrame> dsses = new Hashtable<String, AlignFrame>();
 
     /*
@@ -417,9 +537,9 @@ public class Jalview2XML
       List<String> viewIds = new ArrayList<String>();
 
       // REVERSE ORDER
-      for (int i = frames.length - 1; i > -1; i--)
+      for (int i = frames.size() - 1; i > -1; i--)
       {
-        AlignFrame af = frames[i];
+        AlignFrame af = frames.get(i);
         // skip ?
         if (skipList != null
                 && skipList
@@ -522,30 +642,20 @@ public class Jalview2XML
   {
     try
     {
-      int ap = 0;
-      int apSize = af.alignPanels.size();
       FileOutputStream fos = new FileOutputStream(jarFile);
       JarOutputStream jout = new JarOutputStream(fos);
-      Hashtable<String, AlignFrame> dsses = new Hashtable<String, AlignFrame>();
-      List<String> viewIds = new ArrayList<String>();
+      List<AlignFrame> frames = new ArrayList<AlignFrame>();
 
-      for (AlignmentPanel apanel : af.alignPanels)
+      // resolve splitframes
+      if (af.getViewport().getCodingComplement() != null)
       {
-        String jfileName = apSize == 1 ? fileName : fileName + ap;
-        ap++;
-        if (!jfileName.endsWith(".xml"))
-        {
-          jfileName = jfileName + ".xml";
-        }
-        saveState(apanel, jfileName, jout, viewIds);
-        String dssid = getDatasetIdRef(af.getViewport().getAlignment()
-                .getDataset());
-        if (!dsses.containsKey(dssid))
-        {
-          dsses.put(dssid, af);
-        }
+        frames = ((SplitFrame) af.getSplitViewContainer()).getAlignFrames();
+      }
+      else
+      {
+        frames.add(af);
       }
-      writeDatasetFor(dsses, fileName, jout);
+      saveAllFrames(frames, jout);
       try
       {
         jout.flush();
@@ -893,16 +1003,17 @@ public class Jalview2XML
       jal = av.getAlignment();
     }
     // SAVE MAPPINGS
-    if (jal.getCodonFrames() != null)
+    // FOR DATASET
+    if (storeDS && jal.getCodonFrames() != null)
     {
       List<AlignedCodonFrame> jac = jal.getCodonFrames();
       for (AlignedCodonFrame acf : jac)
       {
         AlcodonFrame alc = new AlcodonFrame();
-        vamsasSet.addAlcodonFrame(alc);
         if (acf.getProtMappings() != null
                 && acf.getProtMappings().length > 0)
         {
+          boolean hasMap = false;
           SequenceI[] dnas = acf.getdnaSeqs();
           jalview.datamodel.Mapping[] pmaps = acf.getProtMappings();
           for (int m = 0; m < pmaps.length; m++)
@@ -912,6 +1023,11 @@ public class Jalview2XML
             alcmap.setMapping(createVamsasMapping(pmaps[m], dnas[m], null,
                     false));
             alc.addAlcodMap(alcmap);
+            hasMap = true;
+          }
+          if (hasMap)
+          {
+            vamsasSet.addAlcodonFrame(alc);
           }
         }
         // TODO: delete this ? dead code from 2.8.3->2.9 ?
@@ -1936,16 +2052,17 @@ public class Jalview2XML
     if (jds.getDatasetSequence() != null)
     {
       vamsasSeq.setDsseqid(seqHash(jds.getDatasetSequence()));
-      if (jds.getDatasetSequence().getDBRefs() != null)
-      {
-        dbrefs = jds.getDatasetSequence().getDBRefs();
-      }
     }
     else
     {
-      vamsasSeq.setDsseqid(id); // so we can tell which sequences really are
+      // seqId==dsseqid so we can tell which sequences really are
       // dataset sequences only
+      vamsasSeq.setDsseqid(id);
       dbrefs = jds.getDBRefs();
+      if (parentseq == null)
+      {
+        parentseq = jds;
+      }
     }
     if (dbrefs != null)
     {
@@ -1997,38 +2114,32 @@ public class Jalview2XML
       if (jmp.getTo() != null)
       {
         MappingChoice mpc = new MappingChoice();
-        if (recurse
-                && (parentseq != jmp.getTo() || parentseq
-                        .getDatasetSequence() != jmp.getTo()))
+
+        // check/create ID for the sequence referenced by getTo()
+
+        String jmpid = "";
+        SequenceI ps = null;
+        if (parentseq != jmp.getTo()
+                && parentseq.getDatasetSequence() != jmp.getTo())
         {
-          mpc.setSequence(createVamsasSequence(false, seqHash(jmp.getTo()),
-                  jmp.getTo(), jds));
+          // chaining dbref rather than a handshaking one
+          jmpid = seqHash(ps = jmp.getTo());
         }
         else
         {
-          String jmpid = "";
-          SequenceI ps = null;
-          if (parentseq != jmp.getTo()
-                  && parentseq.getDatasetSequence() != jmp.getTo())
-          {
-            // chaining dbref rather than a handshaking one
-            jmpid = seqHash(ps = jmp.getTo());
-          }
-          else
-          {
-            jmpid = seqHash(ps = parentseq);
-          }
-          mpc.setDseqFor(jmpid);
-          if (!seqRefIds.containsKey(mpc.getDseqFor()))
-          {
-            jalview.bin.Cache.log.debug("creatign new DseqFor ID");
-            seqRefIds.put(mpc.getDseqFor(), ps);
-          }
-          else
-          {
-            jalview.bin.Cache.log.debug("reusing DseqFor ID");
-          }
+          jmpid = seqHash(ps = parentseq);
+        }
+        mpc.setDseqFor(jmpid);
+        if (!seqRefIds.containsKey(mpc.getDseqFor()))
+        {
+          jalview.bin.Cache.log.debug("creatign new DseqFor ID");
+          seqRefIds.put(mpc.getDseqFor(), ps);
+        }
+        else
+        {
+          jalview.bin.Cache.log.debug("reusing DseqFor ID");
         }
+
         mp.setMappingChoice(mpc);
       }
     }
@@ -2237,14 +2348,10 @@ public class Jalview2XML
     }
     if (seqRefIds == null)
     {
-      seqRefIds = new HashMap<String, SequenceI>();
-    }
-    if (frefedSequence == null)
-    {
-      frefedSequence = new Vector<Object[]>();
+      initSeqRefs();
     }
-
     AlignFrame af = null, _af = null;
+    IdentityHashMap<AlignmentI, AlignmentI> importedDatasets = new IdentityHashMap<AlignmentI, AlignmentI>();
     Map<String, AlignFrame> gatherToThisFrame = new HashMap<String, AlignFrame>();
     final String file = jprovider.getFilename();
     try
@@ -2272,13 +2379,24 @@ public class Jalview2XML
           if (true) // !skipViewport(object))
           {
             _af = loadFromObject(object, file, true, jprovider);
-            if (object.getJalviewModelSequence().getViewportCount() > 0)
+            if (_af != null
+                    && object.getJalviewModelSequence().getViewportCount() > 0)
             {
-              af = _af;
-              if (af.viewport.isGatherViewsHere())
+              if (af == null)
+              {
+                // store a reference to the first view
+                af = _af;
+              }
+              if (_af.viewport.isGatherViewsHere())
               {
-                gatherToThisFrame.put(af.viewport.getSequenceSetId(), af);
+                // if this is a gathered view, keep its reference since
+                // after gathering views, only this frame will remain
+                af = _af;
+                gatherToThisFrame.put(_af.viewport.getSequenceSetId(), _af);
               }
+              // Save dataset to register mappings once all resolved
+              importedDatasets.put(af.viewport.getAlignment().getDataset(),
+                      af.viewport.getAlignment().getDataset());
             }
           }
           entryCount++;
@@ -2334,11 +2452,6 @@ public class Jalview2XML
       e.printStackTrace();
     }
 
-    if (Desktop.instance != null)
-    {
-      Desktop.instance.stopLoading();
-    }
-
     /*
      * Regather multiple views (with the same sequence set id) to the frame (if
      * any) that is flagged as the one to gather to, i.e. convert them to tabbed
@@ -2352,11 +2465,24 @@ public class Jalview2XML
     }
 
     restoreSplitFrames();
-
+    for (AlignmentI ds : importedDatasets.keySet())
+    {
+      if (ds.getCodonFrames() != null)
+      {
+        StructureSelectionManager.getStructureSelectionManager(
+                Desktop.instance).registerMappings(ds.getCodonFrames());
+      }
+    }
     if (errorMessage != null)
     {
       reportErrors();
     }
+
+    if (Desktop.instance != null)
+    {
+      Desktop.instance.stopLoading();
+    }
+
     return af;
   }
 
@@ -2662,7 +2788,7 @@ public class Jalview2XML
     // LOAD SEQUENCES
 
     List<SequenceI> hiddenSeqs = null;
-    jalview.datamodel.Sequence jseq;
+
 
     List<SequenceI> tmpseqs = new ArrayList<SequenceI>();
 
@@ -2674,21 +2800,36 @@ public class Jalview2XML
     {
       String seqId = jseqs[i].getId();
 
-      if (seqRefIds.get(seqId) != null)
+      SequenceI tmpSeq = seqRefIds.get(seqId);
+      if (tmpSeq != null)
       {
-        tmpseqs.add(seqRefIds.get(seqId));
+        if (!incompleteSeqs.containsKey(seqId))
+        {
+          // may not need this check, but keep it for at least 2.9,1 release
+          if (tmpSeq.getStart()!=jseqs[i].getStart() || tmpSeq.getEnd()!=jseqs[i].getEnd())
+          { 
+            System.err
+                    .println("Warning JAL-2154 regression: updating start/end for sequence "
+                    + tmpSeq.toString());
+          }
+        } else {
+          incompleteSeqs.remove(seqId);
+        }
+        tmpSeq.setStart(jseqs[i].getStart());
+        tmpSeq.setEnd(jseqs[i].getEnd());
+        tmpseqs.add(tmpSeq);
         multipleView = true;
       }
       else
       {
-        jseq = new jalview.datamodel.Sequence(vamsasSeq[vi].getName(),
+        tmpSeq = new jalview.datamodel.Sequence(vamsasSeq[vi].getName(),
                 vamsasSeq[vi].getSequence());
-        jseq.setDescription(vamsasSeq[vi].getDescription());
-        jseq.setStart(jseqs[i].getStart());
-        jseq.setEnd(jseqs[i].getEnd());
-        jseq.setVamsasId(uniqueSetSuffix + seqId);
-        seqRefIds.put(vamsasSeq[vi].getId(), jseq);
-        tmpseqs.add(jseq);
+        tmpSeq.setDescription(vamsasSeq[vi].getDescription());
+        tmpSeq.setStart(jseqs[i].getStart());
+        tmpSeq.setEnd(jseqs[i].getEnd());
+        tmpSeq.setVamsasId(uniqueSetSuffix + seqId);
+        seqRefIds.put(vamsasSeq[vi].getId(), tmpSeq);
+        tmpseqs.add(tmpSeq);
         vi++;
       }
 
@@ -2704,7 +2845,7 @@ public class Jalview2XML
           hiddenSeqs = new ArrayList<SequenceI>();
         }
 
-        hiddenSeqs.add(seqRefIds.get(seqId));
+        hiddenSeqs.add(tmpSeq);
       }
     }
 
@@ -2714,7 +2855,39 @@ public class Jalview2XML
     SequenceI[] orderedSeqs = tmpseqs
             .toArray(new SequenceI[tmpseqs.size()]);
 
-    Alignment al = new Alignment(orderedSeqs);
+    AlignmentI al = null;
+    // so we must create or recover the dataset alignment before going further
+    // ///////////////////////////////
+    if (vamsasSet.getDatasetId() == null || vamsasSet.getDatasetId() == "")
+    {
+      // older jalview projects do not have a dataset - so creat alignment and
+      // dataset
+      al = new Alignment(orderedSeqs);
+      al.setDataset(null);
+    }
+    else
+    {
+      boolean isdsal = object.getJalviewModelSequence().getViewportCount() == 0;
+      if (isdsal)
+      {
+        // we are importing a dataset record, so
+        // recover reference to an alignment already materialsed as dataset
+        al = getDatasetFor(vamsasSet.getDatasetId());
+      }
+      if (al == null)
+      {
+        // materialse the alignment
+        al = new Alignment(orderedSeqs);
+      }
+      if (isdsal)
+      {
+        addDatasetRef(vamsasSet.getDatasetId(), al);
+      }
+
+      // finally, verify all data in vamsasSet is actually present in al
+      // passing on flag indicating if it is actually a stored dataset
+      recoverDatasetFor(vamsasSet, al, isdsal);
+    }
 
     if (referenceseqForView != null)
     {
@@ -2727,22 +2900,6 @@ public class Jalview2XML
       al.setProperty(ssp.getKey(), ssp.getValue());
     }
 
-    // /
-    // SequenceFeatures are added to the DatasetSequence,
-    // so we must create or recover the dataset before loading features
-    // ///////////////////////////////
-    if (vamsasSet.getDatasetId() == null || vamsasSet.getDatasetId() == "")
-    {
-      // older jalview projects do not have a dataset id.
-      al.setDataset(null);
-    }
-    else
-    {
-      // recover dataset - passing on flag indicating if this a 'viewless'
-      // sequence set (a.k.a. a stored dataset for the project)
-      recoverDatasetFor(vamsasSet, al, object.getJalviewModelSequence()
-              .getViewportCount() == 0);
-    }
     // ///////////////////////////////
 
     Hashtable pdbloaded = new Hashtable(); // TODO nothing writes to this??
@@ -2852,12 +3009,12 @@ public class Jalview2XML
             else
             {
               // defer to later
-              frefedSequence.add(new Object[] { maps[m].getDnasq(), cf,
-                  mapping });
+              frefedSequence.add(newAlcodMapRef(maps[m].getDnasq(), cf,
+                      mapping));
             }
           }
+          al.addCodonFrame(cf);
         }
-        al.addCodonFrame(cf);
       }
     }
 
@@ -4096,7 +4253,7 @@ public class Jalview2XML
   }
 
   AlignFrame loadViewport(String file, JSeq[] JSEQ,
-          List<SequenceI> hiddenSeqs, Alignment al,
+          List<SequenceI> hiddenSeqs, AlignmentI al,
           JalviewModelSequence jms, Viewport view, String uniqueSeqSetId,
           String viewId, List<JvAnnotRow> autoAlan)
   {
@@ -4104,7 +4261,7 @@ public class Jalview2XML
     af = new AlignFrame(al, view.getWidth(), view.getHeight(),
             uniqueSeqSetId, viewId);
 
-    af.setFileName(file, "Jalview");
+    af.setFileName(file, FileFormat.Jalview);
 
     for (int i = 0; i < JSEQ.length; i++)
     {
@@ -4424,7 +4581,7 @@ public class Jalview2XML
       }
     }
     af.setMenusFromViewport(af.viewport);
-
+    af.setTitle(view.getTitle());
     // TODO: we don't need to do this if the viewport is aready visible.
     /*
      * Add the AlignFrame to the desktop (it may be 'gathered' later), unless it
@@ -4449,7 +4606,7 @@ public class Jalview2XML
   }
 
   private ColourSchemeI constructAnnotationColour(
-          AnnotationColours viewAnnColour, AlignFrame af, Alignment al,
+          AnnotationColours viewAnnColour, AlignFrame af, AlignmentI al,
           JalviewModelSequence jms, boolean checkGroupAnnColour)
   {
     boolean propagateAnnColour = false;
@@ -4573,7 +4730,7 @@ public class Jalview2XML
     return cs;
   }
 
-  private void reorderAutoannotation(AlignFrame af, Alignment al,
+  private void reorderAutoannotation(AlignFrame af, AlignmentI al,
           List<JvAnnotRow> autoAlan)
   {
     // copy over visualization settings for autocalculated annotation in the
@@ -4728,10 +4885,11 @@ public class Jalview2XML
     }
   }
 
-  private void recoverDatasetFor(SequenceSet vamsasSet, Alignment al,
+  private void recoverDatasetFor(SequenceSet vamsasSet, AlignmentI al,
           boolean ignoreUnrefed)
   {
-    jalview.datamodel.Alignment ds = getDatasetFor(vamsasSet.getDatasetId());
+    jalview.datamodel.AlignmentI ds = getDatasetFor(vamsasSet
+            .getDatasetId());
     Vector dseqs = null;
     if (ds == null)
     {
@@ -4881,15 +5039,15 @@ public class Jalview2XML
    * TODO use AlignmentI here and in related methods - needs
    * AlignmentI.getDataset() changed to return AlignmentI instead of Alignment
    */
-  Hashtable<String, Alignment> datasetIds = null;
+  Hashtable<String, AlignmentI> datasetIds = null;
 
-  IdentityHashMap<Alignment, String> dataset2Ids = null;
+  IdentityHashMap<AlignmentI, String> dataset2Ids = null;
 
-  private Alignment getDatasetFor(String datasetId)
+  private AlignmentI getDatasetFor(String datasetId)
   {
     if (datasetIds == null)
     {
-      datasetIds = new Hashtable<String, Alignment>();
+      datasetIds = new Hashtable<String, AlignmentI>();
       return null;
     }
     if (datasetIds.containsKey(datasetId))
@@ -4899,11 +5057,11 @@ public class Jalview2XML
     return null;
   }
 
-  private void addDatasetRef(String datasetId, Alignment dataset)
+  private void addDatasetRef(String datasetId, AlignmentI dataset)
   {
     if (datasetIds == null)
     {
-      datasetIds = new Hashtable<String, Alignment>();
+      datasetIds = new Hashtable<String, AlignmentI>();
     }
     datasetIds.put(datasetId, dataset);
   }
@@ -4914,7 +5072,7 @@ public class Jalview2XML
    * @param dataset
    * @return
    */
-  private String getDatasetIdRef(Alignment dataset)
+  private String getDatasetIdRef(AlignmentI dataset)
   {
     if (dataset.getDataset() != null)
     {
@@ -4926,7 +5084,7 @@ public class Jalview2XML
       // make a new datasetId and record it
       if (dataset2Ids == null)
       {
-        dataset2Ids = new IdentityHashMap<Alignment, String>();
+        dataset2Ids = new IdentityHashMap<AlignmentI, String>();
       }
       else
       {
@@ -4994,7 +5152,7 @@ public class Jalview2XML
         }
         else
         {
-          frefedSequence.add(new Object[] { dsfor, jmap });
+          frefedSequence.add(newMappingRef(dsfor, jmap));
         }
       }
       else
@@ -5032,6 +5190,7 @@ public class Jalview2XML
           djs.setEnd(jmap.getMap().getToHighest());
           djs.setVamsasId(uniqueSetSuffix + sqid);
           jmap.setTo(djs);
+          incompleteSeqs.put(sqid, djs);
           seqRefIds.put(sqid, djs);
 
         }
index 61e20fa..4a582de 100755 (executable)
@@ -35,6 +35,7 @@ import jalview.binding.Tree;
 import jalview.binding.UserColours;
 import jalview.binding.Viewport;
 import jalview.datamodel.PDBEntry;
+import jalview.io.FileFormat;
 import jalview.schemes.ColourSchemeI;
 import jalview.schemes.ColourSchemeProperty;
 import jalview.schemes.ResidueProperties;
@@ -305,7 +306,7 @@ public class Jalview2XML_V1
 
     AlignFrame af = new AlignFrame(al, view.getWidth(), view.getHeight());
 
-    af.setFileName(file, "Jalview");
+    af.setFileName(file, FileFormat.Jalview);
 
     for (int i = 0; i < JSEQ.length; i++)
     {
index de0dbe5..d09c756 100755 (executable)
@@ -295,14 +295,25 @@ public class OverviewPanel extends JPanel implements Runnable
     final boolean hasHiddenRows = av.hasHiddenRows(), hasHiddenCols = av
             .hasHiddenColumns();
     boolean hiddenRow = false;
+    // get hidden row and hidden column map once at beginning.
+    // clone featureRenderer settings to avoid race conditions... if state is
+    // updated just need to refresh again
     for (row = 0; row < sequencesHeight; row++)
     {
+      if (resizeAgain)
+      {
+        break;
+      }
       if ((int) (row * sampleRow) == lastrow)
       {
         // No need to recalculate the colours,
         // Just copy from the row above
         for (col = 0; col < width; col++)
         {
+          if (resizeAgain)
+          {
+            break;
+          }
           miniMe.setRGB(col, row, miniMe.getRGB(col, row - 1));
         }
         continue;
@@ -340,6 +351,10 @@ public class OverviewPanel extends JPanel implements Runnable
 
       for (col = 0; col < width; col++)
       {
+        if (resizeAgain)
+        {
+          break;
+        }
         if ((int) (col * sampleCol) == lastcol
                 && (int) (row * sampleRow) == lastrow)
         {
@@ -380,6 +395,10 @@ public class OverviewPanel extends JPanel implements Runnable
       renderer.updateFromAlignViewport(av);
       for (col = 0; col < width; col++)
       {
+        if (resizeAgain)
+        {
+          break;
+        }
         lastcol = (int) (col * sampleCol);
         {
           mg.translate(col, sequencesHeight);
@@ -395,13 +414,17 @@ public class OverviewPanel extends JPanel implements Runnable
 
     resizing = false;
 
-    setBoxPosition();
-
     if (resizeAgain)
     {
       resizeAgain = false;
       updateOverviewImage();
     }
+    else
+    {
+      lastMiniMe = miniMe;
+    }
+
+    setBoxPosition();
   }
 
   /**
@@ -456,6 +479,7 @@ public class OverviewPanel extends JPanel implements Runnable
     repaint();
   }
 
+  private BufferedImage lastMiniMe = null;
   /**
    * DOCUMENT ME!
    * 
@@ -465,19 +489,32 @@ public class OverviewPanel extends JPanel implements Runnable
   @Override
   public void paintComponent(Graphics g)
   {
-    if (resizing)
+    if (resizing || resizeAgain)
     {
-      g.setColor(Color.white);
+      if (lastMiniMe == null)
+      {
+        g.setColor(Color.white);
+        g.fillRect(0, 0, getWidth(), getHeight());
+      }
+      else
+      {
+        g.drawImage(lastMiniMe, 0, 0, getWidth(), getHeight(), this);
+      }
+      g.setColor(new Color(100, 100, 100, 25));
       g.fillRect(0, 0, getWidth(), getHeight());
     }
-    else if (miniMe != null)
+    else if (lastMiniMe != null)
     {
-      g.drawImage(miniMe, 0, 0, this);
+      g.drawImage(lastMiniMe, 0, 0, this);
+      if (lastMiniMe != miniMe)
+      {
+        g.setColor(new Color(100, 100, 100, 25));
+        g.fillRect(0, 0, getWidth(), getHeight());
+      }
     }
-
+    // TODO: render selected regions
     g.setColor(Color.red);
     g.drawRect(boxX, boxY, boxWidth, boxHeight);
     g.drawRect(boxX + 1, boxY + 1, boxWidth - 2, boxHeight - 2);
-
   }
 }
index 47add28..51d247d 100644 (file)
@@ -21,6 +21,7 @@
 package jalview.gui;
 
 import jalview.datamodel.Alignment;
+import jalview.datamodel.AlignmentI;
 import jalview.datamodel.AlignmentView;
 import jalview.datamodel.ColumnSelection;
 import jalview.datamodel.SeqCigar;
@@ -139,8 +140,8 @@ public class PCAPanel extends GPCAPanel implements Runnable,
       {
         // create an entry for this score matrix for use in PCA
         JCheckBoxMenuItem jm = new JCheckBoxMenuItem();
-        jm.setText(MessageManager
-                .getStringOrReturn("label.score_model", sm));
+        jm.setText(MessageManager.getStringOrReturn("label.score_model_",
+                sm));
         jm.setSelected(pcaModel.getScore_matrix().equals(sm));
         if ((ResidueProperties.scoreMatrices.get(sm).isDNA() && ResidueProperties.scoreMatrices
                 .get(sm).isProtein())
@@ -383,8 +384,8 @@ public class PCAPanel extends GPCAPanel implements Runnable,
     {
       // AlignmentOrder origorder = new AlignmentOrder(alAndColsel[0]);
 
-      Alignment al = new Alignment((SequenceI[]) alAndColsel[0]);
-      Alignment dataset = (av != null && av.getAlignment() != null) ? av
+      AlignmentI al = new Alignment((SequenceI[]) alAndColsel[0]);
+      AlignmentI dataset = (av != null && av.getAlignment() != null) ? av
               .getAlignment().getDataset() : null;
       if (dataset != null)
       {
index f0fdb9f..52a0d41 100644 (file)
@@ -39,6 +39,7 @@ import jalview.datamodel.SequenceFeature;
 import jalview.datamodel.SequenceGroup;
 import jalview.datamodel.SequenceI;
 import jalview.io.FileFormat;
+import jalview.io.FileFormatI;
 import jalview.io.FormatAdapter;
 import jalview.io.SequenceAnnotationReport;
 import jalview.schemes.AnnotationColourGradient;
@@ -92,8 +93,6 @@ import javax.swing.JRadioButtonMenuItem;
  */
 public class PopupMenu extends JPopupMenu
 {
-  private static final String ALL_ANNOTATIONS = "All";
-
   JMenu groupMenu = new JMenu();
 
   JMenuItem groupName = new JMenuItem();
@@ -479,8 +478,6 @@ public class PopupMenu extends JPopupMenu
 
     if (sg != null && sg.getSize() > 0)
     {
-      groupName.setText(MessageManager.formatMessage("label.name_param",
-              new Object[] { sg.getName() }));
       groupName.setText(MessageManager
               .getString("label.edit_name_and_description_current_group"));
 
@@ -757,7 +754,8 @@ public class PopupMenu extends JPopupMenu
     showMenu.removeAll();
     hideMenu.removeAll();
 
-    final List<String> all = Arrays.asList(ALL_ANNOTATIONS);
+    final List<String> all = Arrays.asList(new String[] { MessageManager
+            .getString("label.all") });
     addAnnotationTypeToShowHide(showMenu, forSequences, "", all, true, true);
     addAnnotationTypeToShowHide(hideMenu, forSequences, "", all, true,
             false);
@@ -1099,7 +1097,6 @@ public class PopupMenu extends JPopupMenu
    */
   private void jbInit() throws Exception
   {
-    groupMenu.setText(MessageManager.getString("label.group"));
     groupMenu.setText(MessageManager.getString("label.selection"));
     groupName.setText(MessageManager.getString("label.name"));
     groupName.addActionListener(new java.awt.event.ActionListener()
@@ -2339,7 +2336,7 @@ public class PopupMenu extends JPopupMenu
     // or we simply trust the user wants
     // wysiwig behaviour
 
-    FileFormat fileFormat = FileFormat.forName(e.getActionCommand());
+    FileFormatI fileFormat = FileFormat.forName(e.getActionCommand());
     cap.setText(new FormatAdapter(ap).formatSequences(fileFormat, ap, true));
   }
 
index 80b1806..1ac17e4 100755 (executable)
@@ -24,7 +24,6 @@ import jalview.analysis.AnnotationSorter.SequenceAnnotationOrder;
 import jalview.bin.Cache;
 import jalview.gui.Help.HelpId;
 import jalview.gui.StructureViewer.ViewerType;
-import jalview.io.FileFormat;
 import jalview.io.JalviewFileChooser;
 import jalview.io.JalviewFileView;
 import jalview.jbgui.GPreferences;
@@ -684,14 +683,14 @@ public class Preferences extends GPreferences
   @Override
   public void startupFileTextfield_mouseClicked()
   {
-    FileFormat fileFormat = FileFormat.valueOf(Cache.getProperty("DEFAULT_FILE_FORMAT"));
-    JalviewFileChooser chooser = new JalviewFileChooser(
-    // fixme push into enum
-            Cache.getProperty("LAST_DIRECTORY"), new String[] {
-                "fa, fasta, fastq", "aln", "pfam", "msf", "pir", "blc",
-                "jar" }, new String[] { "Fasta", "Clustal", "PFAM", "MSF",
-                "PIR", "BLC", "Jalview" },
-            fileFormat);
+    String fileFormat = Cache.getProperty("DEFAULT_FILE_FORMAT");
+    JalviewFileChooser chooser = JalviewFileChooser.forRead(
+            Cache.getProperty("LAST_DIRECTORY"), fileFormat, true);
+    // new String[] {
+    // "fa, fasta, fastq", "aln", "pfam", "msf", "pir", "blc",
+    // "jar" }, new String[] { "Fasta", "Clustal", "PFAM", "MSF",
+    // "PIR", "BLC", "Jalview" },
+    // fileFormat);
     chooser.setFileView(new JalviewFileView());
     chooser.setDialogTitle(MessageManager
             .getString("label.select_startup_file"));
index 7fb0593..a9d2690 100755 (executable)
@@ -172,7 +172,7 @@ public class RedundancyPanel extends GSliderPanel implements Runnable
     progress = null;
 
     label.setText(MessageManager
-            .getString("label.enter_redundancy_thereshold"));
+            .getString("label.enter_redundancy_threshold"));
     slider.setVisible(true);
     applyButton.setEnabled(true);
     valueField.setVisible(true);
index 2165b2c..316b6be 100755 (executable)
@@ -23,7 +23,10 @@ package jalview.gui;
 import jalview.datamodel.ColumnSelection;
 import jalview.datamodel.SequenceGroup;
 import jalview.datamodel.SequenceI;
+import jalview.renderer.ScaleRenderer;
+import jalview.renderer.ScaleRenderer.ScaleMark;
 import jalview.util.MessageManager;
+import jalview.util.Platform;
 
 import java.awt.Color;
 import java.awt.FontMetrics;
@@ -219,7 +222,7 @@ public class ScalePanel extends JPanel implements MouseMotionListener,
    */
   protected void leftMouseButtonPressed(MouseEvent evt, final int res)
   {
-    if (!evt.isControlDown() && !evt.isShiftDown())
+    if (!Platform.isControlDown(evt) && !evt.isShiftDown())
     {
       av.getColumnSelection().clear();
     }
@@ -497,7 +500,8 @@ public class ScalePanel extends JPanel implements MouseMotionListener,
     int widthx = 1 + endx - startx;
 
     FontMetrics fm = gg.getFontMetrics(av.getFont());
-    int y = avCharHeight, yOf = fm.getDescent();
+    int y = avCharHeight;
+    int yOf = fm.getDescent();
     y -= yOf;
     if (av.hasHiddenColumns())
     {
@@ -522,7 +526,6 @@ public class ScalePanel extends JPanel implements MouseMotionListener,
               -1 + res * avCharWidth - avCharHeight / 4,
               -1 + res * avCharWidth + avCharHeight / 4,
               -1 + res * avCharWidth }, new int[] { y, y, y + 2 * yOf }, 3);
-
         }
       }
     }
@@ -530,14 +533,14 @@ public class ScalePanel extends JPanel implements MouseMotionListener,
     gg.setColor(Color.black);
 
     int maxX = 0;
-    List<Object[]> marks = jalview.renderer.ScaleRenderer.calculateMarks(
-            av, startx, endx);
+    List<ScaleMark> marks = new ScaleRenderer().calculateMarks(av, startx,
+            endx);
 
-    for (Object[] mark : marks)
+    for (ScaleMark mark : marks)
     {
-      boolean major = Boolean.valueOf((Boolean) mark[0]);
-      int mpos = ((Integer) mark[1]).intValue(); // (i - startx - 1)
-      String mstring = (String) mark[2];
+      boolean major = mark.major;
+      int mpos = mark.column; // (i - startx - 1)
+      String mstring = mark.text;
       if (mstring != null)
       {
         if (mpos * avCharWidth > maxX)
@@ -557,15 +560,6 @@ public class ScalePanel extends JPanel implements MouseMotionListener,
                 (mpos * avCharWidth) + (avCharWidth / 2), y + (yOf * 2));
       }
     }
-    if (av.hasHiddenColumns())
-    {
-      if (reveal != null && reveal[0] > startx && reveal[0] < endx)
-      {
-        gg.drawString(MessageManager.getString("label.reveal_columns"),
-                reveal[0] * avCharWidth, 0);
-      }
-    }
-
   }
 
 }
index 2f7cd76..760ece0 100755 (executable)
@@ -24,6 +24,8 @@ import jalview.datamodel.AlignmentI;
 import jalview.datamodel.SearchResults;
 import jalview.datamodel.SequenceGroup;
 import jalview.datamodel.SequenceI;
+import jalview.renderer.ScaleRenderer;
+import jalview.renderer.ScaleRenderer.ScaleMark;
 
 import java.awt.BasicStroke;
 import java.awt.BorderLayout;
@@ -122,17 +124,17 @@ public class SeqCanvas extends JComponent
   private void drawNorthScale(Graphics g, int startx, int endx, int ypos)
   {
     updateViewport();
-    for (Object[] mark : jalview.renderer.ScaleRenderer.calculateMarks(av,
-            startx, endx))
+    for (ScaleMark mark : new ScaleRenderer().calculateMarks(av, startx,
+            endx))
     {
-      int mpos = ((Integer) mark[1]).intValue(); // (i - startx - 1)
+      int mpos = mark.column; // (i - startx - 1)
       if (mpos < 0)
       {
         continue;
       }
-      String mstring = (String) mark[2];
+      String mstring = mark.text;
 
-      if (Boolean.valueOf((Boolean) mark[0]))
+      if (mark.major)
       {
         if (mstring != null)
         {
index 2d44a0f..f476d41 100644 (file)
@@ -825,6 +825,20 @@ public class SeqPanel extends JPanel implements MouseListener,
   String lastTooltip;
 
   /**
+   * set when the current UI interaction has resulted in a change that requires
+   * overview shading to be recalculated. this could be changed to something
+   * more expressive that indicates what actually has changed, so selective
+   * redraws can be applied
+   */
+  private boolean needOverviewUpdate = false; // TODO: refactor to avcontroller
+
+  /**
+   * set if av.getSelectionGroup() refers to a group that is defined on the
+   * alignment view, rather than a transient selection
+   */
+  private boolean editingDefinedGroup = false;  // TODO: refactor to avcontroller or viewModel
+
+  /**
    * Set status message in alignment panel
    * 
    * @param sequence
@@ -843,7 +857,8 @@ public class SeqPanel extends JPanel implements MouseListener,
      * Sequence number (if known), and sequence name.
      */
     String seqno = seq == -1 ? "" : " " + (seq + 1);
-    text.append("Sequence" + seqno + " ID: " + sequence.getName());
+    text.append("Sequence").append(seqno).append(" ID: ")
+            .append(sequence.getName());
 
     String residue = null;
     /*
@@ -1568,10 +1583,12 @@ public class SeqPanel extends JPanel implements MouseListener,
               && (res < stretchGroup.getEndRes()))
       {
         av.setSelectionGroup(stretchGroup);
+        editingDefinedGroup = true;
       }
       else
       {
         stretchGroup = null;
+        editingDefinedGroup = false;
       }
     }
     else if (!stretchGroup.getSequences(null).contains(sequence)
@@ -1590,6 +1607,7 @@ public class SeqPanel extends JPanel implements MouseListener,
                   && (allGroups[i].getEndRes() >= res))
           {
             stretchGroup = allGroups[i];
+            editingDefinedGroup = true;
             break;
           }
         }
@@ -1639,7 +1657,7 @@ public class SeqPanel extends JPanel implements MouseListener,
       sg.setEndRes(res);
       sg.addSequence(sequence, false);
       av.setSelectionGroup(sg);
-
+      editingDefinedGroup = false;
       stretchGroup = sg;
 
       if (av.getConservationSelected())
@@ -1682,9 +1700,10 @@ public class SeqPanel extends JPanel implements MouseListener,
     {
       return;
     }
-
-    stretchGroup.recalcConservation(); // always do this - annotation has own
-                                       // state
+    // always do this - annotation has own state
+    // but defer colourscheme update until hidden sequences are passed in
+    boolean vischange = stretchGroup.recalcConservation(true);
+    needOverviewUpdate |= vischange && editingDefinedGroup;
     if (stretchGroup.cs != null)
     {
       stretchGroup.cs.alignmentChanged(stretchGroup,
@@ -1702,8 +1721,9 @@ public class SeqPanel extends JPanel implements MouseListener,
       }
     }
     PaintRefresher.Refresh(this, av.getSequenceSetId());
-    ap.paintAlignment(true);
-
+    ap.paintAlignment(needOverviewUpdate);
+    needOverviewUpdate =false;
+    editingDefinedGroup = false;
     changeEndRes = false;
     changeStartRes = false;
     stretchGroup = null;
@@ -1757,6 +1777,7 @@ public class SeqPanel extends JPanel implements MouseListener,
       if (res > (stretchGroup.getStartRes() - 1))
       {
         stretchGroup.setEndRes(res);
+        needOverviewUpdate |= editingDefinedGroup;
       }
     }
     else if (changeStartRes)
@@ -1764,6 +1785,7 @@ public class SeqPanel extends JPanel implements MouseListener,
       if (res < (stretchGroup.getEndRes() + 1))
       {
         stretchGroup.setStartRes(res);
+        needOverviewUpdate |= editingDefinedGroup;
       }
     }
 
@@ -1797,6 +1819,7 @@ public class SeqPanel extends JPanel implements MouseListener,
       if (stretchGroup.getSequences(null).contains(nextSeq))
       {
         stretchGroup.deleteSequence(seq, false);
+        needOverviewUpdate |= editingDefinedGroup;
       }
       else
       {
@@ -1806,6 +1829,7 @@ public class SeqPanel extends JPanel implements MouseListener,
         }
 
         stretchGroup.addSequence(nextSeq, false);
+        needOverviewUpdate |= editingDefinedGroup;
       }
     }
 
index 3a77c6c..fca130b 100755 (executable)
@@ -837,10 +837,8 @@ public class SequenceFetcher extends JPanel implements Runnable
       Cache.log.info(
               "Error retrieving " + accession
               + " from " + proxy.getDbName(), e);
-    } finally
-    {
-      return success;
     }
+    return success;
   }
 
   /**
@@ -860,7 +858,6 @@ public class SequenceFetcher extends JPanel implements Runnable
 
     for (String q : queries)
     {
-      DBRefEntry[] found = null;
       DBRefEntry dbr = new DBRefEntry();
       dbr.setSource(proxy.getDbSource());
       dbr.setVersion(null);
@@ -871,8 +868,9 @@ public class SequenceFetcher extends JPanel implements Runnable
       {
         if (rs[r] != null)
         {
-          found = DBRefUtils.searchRefs(rs[r].getDBRefs(), accId);
-          if (found != null && found.length > 0)
+          List<DBRefEntry> found = DBRefUtils.searchRefs(rs[r].getDBRefs(),
+                  accId);
+          if (!found.isEmpty())
           {
             rfound = true;
             break;
index 427eb08..64fe053 100755 (executable)
@@ -85,6 +85,7 @@ public class SequenceRenderer implements jalview.api.SequenceRenderer
   @Override
   public Color getResidueBoxColour(SequenceI seq, int i)
   {
+    // rate limiting step when rendering overview for lots of groups
     allGroups = av.getAlignment().findAllGroups(seq);
 
     if (inCurrentSequenceGroup(i))
index e1e70dc..c3fec4f 100755 (executable)
@@ -220,7 +220,7 @@ public class SliderPanel extends GSliderPanel
     }
 
     PIDSlider.setTitle(MessageManager
-            .formatMessage("label.percentage_identity_thereshold",
+            .formatMessage("label.percentage_identity_threshold",
                     new String[] { source }));
 
     if (ap.av.getAlignment().getGroups() != null)
index 617224f..1bc85d2 100644 (file)
@@ -37,6 +37,8 @@ import java.awt.event.KeyAdapter;
 import java.awt.event.KeyEvent;
 import java.awt.event.KeyListener;
 import java.beans.PropertyVetoException;
+import java.util.Arrays;
+import java.util.List;
 import java.util.Map.Entry;
 
 import javax.swing.AbstractAction;
@@ -206,6 +208,7 @@ public class SplitFrame extends GSplitFrame implements SplitContainerI
     final AlignmentI bottomAlignment = bottomViewport.getAlignment();
     boolean topAnnotations = topViewport.isShowAnnotation();
     boolean bottomAnnotations = bottomViewport.isShowAnnotation();
+    // TODO need number of visible sequences here, not #sequences - how?
     int topCount = topAlignment.getHeight();
     int bottomCount = bottomAlignment.getHeight();
     int topCharHeight = topViewport.getViewStyle().getCharHeight();
@@ -223,6 +226,11 @@ public class SplitFrame extends GSplitFrame implements SplitContainerI
             + (bottomAnnotations ? bottomViewport.calcPanelHeight() : 0);
     double ratio = ((double) topHeight) / (topHeight + bottomHeight);
 
+    /*
+     * limit to 0.2 <= ratio <= 0.8 to avoid concealing all sequences
+     */
+    ratio = Math.min(ratio, 0.8d);
+    ratio = Math.max(ratio, 0.2d);
     setRelativeDividerLocation(ratio);
   }
 
@@ -328,6 +336,7 @@ public class SplitFrame extends GSplitFrame implements SplitContainerI
         actioned = true;
         e.consume();
       }
+      break;
     default:
     }
     return actioned;
@@ -704,6 +713,17 @@ public class SplitFrame extends GSplitFrame implements SplitContainerI
   }
 
   /**
+   * return the AlignFrames held by this container
+   * 
+   * @return { Top alignFrame (Usually CDS), Bottom AlignFrame (Usually
+   *         Protein)}
+   */
+  public List<AlignFrame> getAlignFrames()
+  {
+    return Arrays.asList(new AlignFrame[] { (AlignFrame) getTopFrame(),
+        (AlignFrame) getBottomFrame() });
+  }
+  /**
    * Replace Cmd-F Find action with our version. This is necessary because the
    * 'default' Finder searches in the first AlignFrame it finds. We need it to
    * search in the half of the SplitFrame that has the mouse.
index f1c6768..39d9c1d 100644 (file)
@@ -81,7 +81,7 @@ public class TextColourChooser
             new JLabel(
                     "<html>"
                             + MessageManager
-                                    .getString("label.select_dark_light_set_thereshold")
+                                    .getString("label.select_dark_light_set_threshold")
                             + "</html>"), BorderLayout.NORTH);
     panel.add(col1);
     panel.add(slider);
@@ -133,7 +133,7 @@ public class TextColourChooser
                     ap,
                     bigpanel,
                     MessageManager
-                            .getString("label.adjunst_foreground_text_colour_thereshold"),
+                            .getString("label.adjunst_foreground_text_colour_threshold"),
                     JOptionPane.OK_CANCEL_OPTION,
                     JOptionPane.QUESTION_MESSAGE, null, null, null);
 
index d78350d..af84dbc 100755 (executable)
@@ -42,6 +42,7 @@ import jalview.io.JalviewFileView;
 import jalview.io.NewickFile;
 import jalview.jbgui.GTreePanel;
 import jalview.schemes.ResidueProperties;
+import jalview.util.ImageMaker;
 import jalview.util.MessageManager;
 import jalview.viewmodel.AlignmentViewport;
 
@@ -520,8 +521,8 @@ public class TreePanel extends GTreePanel
     {
       // AlignmentOrder origorder = new AlignmentOrder(alAndColsel[0]);
 
-      Alignment al = new Alignment((SequenceI[]) alAndColsel[0]);
-      Alignment dataset = (av != null && av.getAlignment() != null) ? av
+      AlignmentI al = new Alignment((SequenceI[]) alAndColsel[0]);
+      AlignmentI dataset = (av != null && av.getAlignment() != null) ? av
               .getAlignment().getDataset() : null;
       if (dataset != null)
       {
@@ -747,24 +748,24 @@ public class TreePanel extends GTreePanel
 
     try
     {
-      jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
-              jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
-              { "eps" }, new String[] { "Encapsulated Postscript" },
-              "Encapsulated Postscript");
-      chooser.setFileView(new jalview.io.JalviewFileView());
+      JalviewFileChooser chooser = new JalviewFileChooser(
+              Cache.getProperty("LAST_DIRECTORY"),
+              ImageMaker.EPS_EXTENSION, ImageMaker.EPS_EXTENSION,
+              ImageMaker.EPS_EXTENSION);
+      chooser.setFileView(new JalviewFileView());
       chooser.setDialogTitle(MessageManager
               .getString("label.create_eps_from_tree"));
       chooser.setToolTipText(MessageManager.getString("action.save"));
 
       int value = chooser.showSaveDialog(this);
 
-      if (value != jalview.io.JalviewFileChooser.APPROVE_OPTION)
+      if (value != JalviewFileChooser.APPROVE_OPTION)
       {
         return;
       }
 
-      jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
-              .getSelectedFile().getParent());
+      Cache.setProperty("LAST_DIRECTORY", chooser.getSelectedFile()
+              .getParent());
 
       FileOutputStream out = new FileOutputStream(chooser.getSelectedFile());
       EpsGraphics2D pg = new EpsGraphics2D("Tree", out, 0, 0, width, height);
@@ -795,10 +796,10 @@ public class TreePanel extends GTreePanel
 
     try
     {
-      jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
-              jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
-              { "png" }, new String[] { "Portable network graphics" },
-              "Portable network graphics");
+      JalviewFileChooser chooser = new JalviewFileChooser(
+              Cache.getProperty("LAST_DIRECTORY"),
+              ImageMaker.PNG_EXTENSION, ImageMaker.PNG_DESCRIPTION,
+              ImageMaker.PNG_DESCRIPTION);
 
       chooser.setFileView(new jalview.io.JalviewFileView());
       chooser.setDialogTitle(MessageManager
index c9c1531..80fd5f6 100755 (executable)
@@ -21,6 +21,7 @@
 package jalview.gui;
 
 import jalview.api.structures.JalviewStructureDisplayI;
+import jalview.bin.Cache;
 import jalview.datamodel.SequenceGroup;
 import jalview.io.JalviewFileChooser;
 import jalview.jbgui.GUserDefinedColours;
@@ -597,9 +598,8 @@ public class UserDefinedColours extends GUserDefinedColours implements
     lowerCaseButtons = new ArrayList<JButton>();
 
     JalviewFileChooser chooser = new JalviewFileChooser(
-            jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
-            new String[] { "jc" }, new String[] { "Jalview User Colours" },
-            "Jalview User Colours");
+            Cache.getProperty("LAST_DIRECTORY"), "jc",
+            "Jalview User Colours", "Jalview User Colours");
     chooser.setFileView(new jalview.io.JalviewFileView());
     chooser.setDialogTitle(MessageManager
             .getString("label.load_colour_scheme"));
@@ -833,9 +833,8 @@ public class UserDefinedColours extends GUserDefinedColours implements
       userColourSchemes.remove(schemeName.getText());
     }
     JalviewFileChooser chooser = new JalviewFileChooser(
-            jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
-            new String[] { "jc" }, new String[] { "Jalview User Colours" },
-            "Jalview User Colours");
+            Cache.getProperty("LAST_DIRECTORY"), "jc",
+            "Jalview User Colours", "Jalview User Colours");
 
     chooser.setFileView(new jalview.io.JalviewFileView());
     chooser.setDialogTitle(MessageManager
index b6a7672..aec79e4 100644 (file)
@@ -22,6 +22,7 @@ package jalview.gui;
 
 import jalview.bin.Cache;
 import jalview.io.JalviewFileChooser;
+import jalview.io.JalviewFileView;
 import jalview.util.MessageManager;
 import jalview.ws.params.ParamDatastoreI;
 import jalview.ws.params.ParamManager;
@@ -185,11 +186,9 @@ public class WsParamSetManager implements ParamManager
     if (filename == null)
     {
       JalviewFileChooser chooser = new JalviewFileChooser(
-              jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
-              { "wsparams" },
-              new String[] { "Web Service Parameter File" },
-              "Web Service Parameter File");
-      chooser.setFileView(new jalview.io.JalviewFileView());
+              Cache.getProperty("LAST_DIRECTORY"), "wsparams",
+              "Web Service Parameter File", "Web Service Parameter File");
+      chooser.setFileView(new JalviewFileView());
       chooser.setDialogTitle(MessageManager
               .getString("label.choose_filename_for_param_file"));
       chooser.setToolTipText(MessageManager.getString("action.save"));
index d36a588..d333c64 100755 (executable)
@@ -370,8 +370,8 @@ public abstract class AlignFile extends FileParse implements AlignmentFileI
   }
 
   /**
-   * Creates the output id. Adds prefix Uniprot format source|id And suffix
-   * Jalview /start-end
+   * Creates the output id. Adds prefix Uniprot format source|id and optionally
+   * suffix Jalview /start-end
    * 
    * @param jvsuffix
    * 
@@ -382,6 +382,11 @@ public abstract class AlignFile extends FileParse implements AlignmentFileI
     return seq.getDisplayId(jvsuffix);
   }
 
+  String printId(SequenceI seq)
+  {
+    return printId(seq, true);
+  }
+
   /**
    * vector of String[] treeName, newickString pairs
    */
index 0c99d26..04d68e8 100755 (executable)
@@ -26,7 +26,9 @@ import jalview.datamodel.Alignment;
 import jalview.datamodel.AlignmentAnnotation;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.AlignmentView;
+import jalview.datamodel.PDBEntry.Type;
 import jalview.datamodel.SequenceI;
+import jalview.ext.jmol.JmolParser;
 import jalview.structure.StructureImportSettings;
 
 import java.io.File;
@@ -191,9 +193,32 @@ public class AppletFormatAdapter
     {
       if (fileFormat == FileFormat.PDB || fileFormat == FileFormat.MMCif)
       {
-        StructureImportSettings.addSettings(annotFromStructure,
-                localSecondaryStruct, serviceSecondaryStruct);
-        alignFile = fileFormat.getAlignmentFile(inFile, sourceType);
+        // TODO obtain config value from preference settings.
+        // Set value to 'true' to test PDB processing with Jmol: JAL-1213
+        boolean isParseWithJMOL = StructureImportSettings
+                .getDefaultPDBFileParser().equalsIgnoreCase(
+                        StructureImportSettings.StructureParser.JMOL_PARSER
+                                .toString());
+        if (isParseWithJMOL)
+        {
+          StructureImportSettings.addSettings(annotFromStructure,
+                  localSecondaryStruct, serviceSecondaryStruct);
+          alignFile = new JmolParser(annotFromStructure,
+                  localSecondaryStruct, serviceSecondaryStruct, inFile,
+                  sourceType);
+        }
+        else
+        {
+          StructureImportSettings.addSettings(annotFromStructure,
+                  localSecondaryStruct, serviceSecondaryStruct);
+          StructureImportSettings.setShowSeqFeatures(true);
+          alignFile = new MCview.PDBfile(annotFromStructure,
+                  localSecondaryStruct, serviceSecondaryStruct, inFile,
+                  sourceType);
+        }
+        ((StructureFile) alignFile)
+                .setDbRefType(fileFormat == FileFormat.PDB ? Type.PDB
+                        : Type.MMCIF);
       }
       else
       {
@@ -276,9 +301,22 @@ public class AppletFormatAdapter
     {
       if (format == FileFormat.PDB || format == FileFormat.MMCif)
       {
-        StructureImportSettings.addSettings(annotFromStructure,
-                localSecondaryStruct, serviceSecondaryStruct);
-        alignFile = format.getAlignmentFile(source);
+        // TODO obtain config value from preference settings
+        boolean isParseWithJMOL = false;
+        if (isParseWithJMOL)
+        {
+          StructureImportSettings.addSettings(annotFromStructure,
+                  localSecondaryStruct, serviceSecondaryStruct);
+          alignFile = new JmolParser(annotFromStructure,
+                  localSecondaryStruct, serviceSecondaryStruct, source);
+        }
+        else
+        {
+          StructureImportSettings.setShowSeqFeatures(true);
+          alignFile = new MCview.PDBfile(annotFromStructure,
+                  localSecondaryStruct, serviceSecondaryStruct, source);
+        }
+        ((StructureFile) alignFile).setDbRefType(Type.PDB);
       }
       else
       {
index 0ebebc2..80df097 100644 (file)
@@ -22,6 +22,7 @@ package jalview.io;
 
 import jalview.api.AlignExportSettingI;
 import jalview.api.AlignmentViewPanel;
+import jalview.bin.Cache;
 import jalview.datamodel.AlignmentExportData;
 import jalview.exceptions.NoFileSelectedException;
 import jalview.gui.AlignFrame;
@@ -29,6 +30,7 @@ import jalview.gui.IProgressIndicator;
 import jalview.gui.OOMWarning;
 import jalview.json.binding.biojs.BioJSReleasePojo;
 import jalview.json.binding.biojs.BioJSRepositoryPojo;
+import jalview.util.ImageMaker;
 import jalview.util.MessageManager;
 
 import java.io.BufferedInputStream;
@@ -177,9 +179,8 @@ public class BioJsHTMLOutput
     }
 
     JalviewFileChooser jvFileChooser = new JalviewFileChooser(
-            jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
-            new String[] { "html" }, new String[] { "HTML files" },
-            "HTML files");
+            Cache.getProperty("LAST_DIRECTORY"), ImageMaker.HTML_EXTENSION,
+            ImageMaker.HTML_EXTENSION, ImageMaker.HTML_EXTENSION);
     jvFileChooser.setFileView(new JalviewFileView());
 
     jvFileChooser.setDialogTitle(MessageManager
@@ -189,7 +190,7 @@ public class BioJsHTMLOutput
     int fileChooserOpt = jvFileChooser.showSaveDialog(null);
     if (fileChooserOpt == JalviewFileChooser.APPROVE_OPTION)
     {
-      jalview.bin.Cache.setProperty("LAST_DIRECTORY", jvFileChooser
+      Cache.setProperty("LAST_DIRECTORY", jvFileChooser
               .getSelectedFile().getParent());
       selectedFile = jvFileChooser.getSelectedFile().getPath();
     }
index bca365f..a7113f6 100644 (file)
@@ -1,5 +1,6 @@
 package jalview.io;
 
+import jalview.datamodel.PDBEntry;
 import jalview.ext.jmol.JmolParser;
 import jalview.structure.StructureImportSettings;
 
@@ -334,13 +335,13 @@ public enum FileFormat implements FileFormatI
     {
       // TODO obtain config value from preference settings.
       // Set value to 'true' to test PDB processing with Jmol: JAL-1213
-      boolean isParseWithJMOL = !StructureImportSettings
-              .getCurrentDefaultFormat().equalsIgnoreCase("PDB");
+      boolean isParseWithJMOL = StructureImportSettings
+              .getDefaultStructureFileFormat() != PDBEntry.Type.PDB;
       if (isParseWithJMOL)
       {
         return new JmolParser(
                 StructureImportSettings.isVisibleChainAnnotation(),
-                StructureImportSettings.isPredictSecondaryStructure(),
+                StructureImportSettings.isProcessSecondaryStructure(),
                 StructureImportSettings.isExternalSecondaryStructure(),
                 inFile,
                 sourceType);
@@ -350,7 +351,7 @@ public enum FileFormat implements FileFormatI
         StructureImportSettings.setShowSeqFeatures(true);
         return new MCview.PDBfile(
                 StructureImportSettings.isVisibleChainAnnotation(),
-                StructureImportSettings.isPredictSecondaryStructure(),
+                StructureImportSettings.isProcessSecondaryStructure(),
                 StructureImportSettings.isExternalSecondaryStructure(),
                 inFile,
                 sourceType);
@@ -361,13 +362,13 @@ public enum FileFormat implements FileFormatI
     public AlignmentFileI getAlignmentFile(FileParse source)
             throws IOException
     {
-      boolean isParseWithJMOL = !StructureImportSettings
-              .getCurrentDefaultFormat().equalsIgnoreCase("PDB");
+      boolean isParseWithJMOL = StructureImportSettings
+              .getDefaultStructureFileFormat() != PDBEntry.Type.PDB;
       if (isParseWithJMOL)
       {
         return new JmolParser(
                 StructureImportSettings.isVisibleChainAnnotation(),
-                StructureImportSettings.isPredictSecondaryStructure(),
+                StructureImportSettings.isProcessSecondaryStructure(),
                 StructureImportSettings.isExternalSecondaryStructure(),
                 source);
       }
@@ -376,7 +377,7 @@ public enum FileFormat implements FileFormatI
         StructureImportSettings.setShowSeqFeatures(true);
         return new MCview.PDBfile(
                 StructureImportSettings.isVisibleChainAnnotation(),
-                StructureImportSettings.isPredictSecondaryStructure(),
+                StructureImportSettings.isProcessSecondaryStructure(),
                 StructureImportSettings.isExternalSecondaryStructure(),
                 source);
       }
@@ -397,7 +398,7 @@ public enum FileFormat implements FileFormatI
     {
       return new JmolParser(
               StructureImportSettings.isVisibleChainAnnotation(),
-              StructureImportSettings.isPredictSecondaryStructure(),
+              StructureImportSettings.isProcessSecondaryStructure(),
               StructureImportSettings.isExternalSecondaryStructure(),
               inFile, sourceType);
     }
@@ -408,7 +409,7 @@ public enum FileFormat implements FileFormatI
     {
       return new JmolParser(
               StructureImportSettings.isVisibleChainAnnotation(),
-              StructureImportSettings.isPredictSecondaryStructure(),
+              StructureImportSettings.isProcessSecondaryStructure(),
               StructureImportSettings.isExternalSecondaryStructure(),
               source);
     }
index df0dc06..2e4a781 100755 (executable)
  */
 package jalview.io;
 
+import jalview.bin.Cache;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.SequenceI;
 import jalview.gui.AlignViewport;
 import jalview.gui.AlignmentPanel;
 import jalview.gui.FeatureRenderer;
 import jalview.gui.SequenceRenderer;
+import jalview.util.BrowserLauncher;
+import jalview.util.ImageMaker;
 import jalview.util.MessageManager;
 
 import java.awt.Color;
 import java.awt.Font;
+import java.io.FileWriter;
 import java.io.PrintWriter;
 
 public class HTMLOutput
@@ -52,9 +56,8 @@ public class HTMLOutput
     fr.transferSettings(fr1);
 
     JalviewFileChooser chooser = new JalviewFileChooser(
-            jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
-            new String[] { "html" }, new String[] { "HTML files" },
-            "HTML files");
+            Cache.getProperty("LAST_DIRECTORY"), ImageMaker.HTML_EXTENSION,
+            "HTML files", "HTML files");
 
     chooser.setFileView(new JalviewFileView());
     chooser.setDialogTitle(MessageManager.getString("label.save_as_html"));
@@ -65,13 +68,12 @@ public class HTMLOutput
     if (value == JalviewFileChooser.APPROVE_OPTION)
     {
       String choice = chooser.getSelectedFile().getPath();
-      jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
+      Cache.setProperty("LAST_DIRECTORY", chooser
               .getSelectedFile().getParent());
 
       try
       {
-        PrintWriter out = new java.io.PrintWriter(new java.io.FileWriter(
-                choice));
+        PrintWriter out = new PrintWriter(new FileWriter(choice));
         out.println("<HTML>");
         out.println("<style type=\"text/css\">");
         out.println("<!--");
@@ -106,7 +108,7 @@ public class HTMLOutput
 
         out.println("\n</body>\n</html>");
         out.close();
-        jalview.util.BrowserLauncher.openURL("file:///" + choice);
+        BrowserLauncher.openURL("file:///" + choice);
       } catch (Exception ex)
       {
         ex.printStackTrace();
index 2e4d8a1..0acddfd 100644 (file)
@@ -22,6 +22,7 @@ package jalview.io;
 
 import jalview.api.AlignExportSettingI;
 import jalview.api.FeatureRenderer;
+import jalview.bin.Cache;
 import jalview.datamodel.AlignmentExportData;
 import jalview.datamodel.SequenceI;
 import jalview.gui.AlignViewport;
@@ -30,6 +31,7 @@ import jalview.gui.HTMLOptions;
 import jalview.gui.IProgressIndicator;
 import jalview.gui.OOMWarning;
 import jalview.math.AlignmentDimension;
+import jalview.util.ImageMaker;
 import jalview.util.MessageManager;
 
 import java.awt.Color;
@@ -251,11 +253,9 @@ public class HtmlSvgOutput
 
   static JalviewFileChooser getHTMLChooser()
   {
-    return new jalview.io.JalviewFileChooser(
-            jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
-            new String[] { "html" },
-            new String[] { "Hypertext Markup Language" },
-            "Hypertext Markup Language");
+    return new JalviewFileChooser(Cache.getProperty("LAST_DIRECTORY"),
+            ImageMaker.HTML_EXTENSION, ImageMaker.HTML_EXTENSION,
+            ImageMaker.HTML_EXTENSION);
   }
 
   public int printUnwrapped(int pwidth, int pheight, int pi, Graphics... pg)
index ad44073..7a12076 100644 (file)
@@ -737,6 +737,10 @@ public class JSONFile extends AlignFile implements ComplexAlignFile
   @Override
   public void configureForView(AlignmentViewPanel avpanel)
   {
+    if (avpanel == null)
+    {
+      return;
+    }
     super.configureForView(avpanel);
     AlignViewportI viewport = avpanel.getAlignViewport();
     AlignmentI alignment = viewport.getAlignment();
index cad69ed..a4362dc 100755 (executable)
@@ -31,6 +31,9 @@ import java.awt.HeadlessException;
 import java.awt.event.MouseAdapter;
 import java.awt.event.MouseEvent;
 import java.io.File;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
 import java.util.StringTokenizer;
 import java.util.Vector;
 
@@ -41,6 +44,7 @@ import javax.swing.JOptionPane;
 import javax.swing.JPanel;
 import javax.swing.JScrollPane;
 import javax.swing.SpringLayout;
+import javax.swing.plaf.basic.BasicFileChooserUI;
 
 /**
  * Enhanced file chooser dialog box.
@@ -53,63 +57,132 @@ import javax.swing.SpringLayout;
  */
 public class JalviewFileChooser extends JFileChooser
 {
-  public JalviewFileChooser(String dir)
+  /**
+   * Factory method to return a file chooser that offers readable alignment file
+   * formats
+   * 
+   * @param directory
+   * @param selected
+   * @param selectAll
+   * @return
+   */
+  public static JalviewFileChooser forRead(String directory,
+          String selected, boolean selectAll)
   {
-    super(safePath(dir));
-    setAccessory(new RecentlyOpened());
+    List<String> extensions = new ArrayList<String>();
+    List<String> descs = new ArrayList<String>();
+    for (FileFormatI format : FileFormat.values())
+    {
+      if (format.isReadable())
+      {
+        extensions.add(format.getExtensions());
+        descs.add(format.getShortDescription());
+      }
+    }
+    return new JalviewFileChooser(directory,
+            extensions.toArray(new String[extensions.size()]),
+            descs.toArray(new String[descs.size()]),
+            selected);
   }
 
-  private static File safePath(String dir)
+  /**
+   * Factory method to return a file chooser that offers writable alignment file
+   * formats
+   * 
+   * @param directory
+   * @param selected
+   * @param selectAll
+   * @return
+   */
+  public static JalviewFileChooser forWrite(String directory,
+          String selected, boolean selectAll)
   {
-    if (dir == null)
+    // TODO in Java 8, forRead and forWrite can be a single method
+    // with a lambda expression parameter for isReadable/isWritable
+    List<String> extensions = new ArrayList<String>();
+    List<String> descs = new ArrayList<String>();
+    for (FileFormatI format : FileFormat.values())
     {
-      return null;
+      if (format.isWritable())
+      {
+        extensions.add(format.getExtensions());
+        descs.add(format.getShortDescription());
+      }
     }
+    return new JalviewFileChooser(directory,
+            extensions.toArray(new String[extensions.size()]),
+            descs.toArray(new String[descs.size()]), selected);
+  }
 
-    File f = new File(dir);
-    if (f.getName().indexOf(':') > -1)
-    {
-      return null;
-    }
-    return f;
+  public JalviewFileChooser(String dir)
+  {
+    super(safePath(dir));
+    setAccessory(new RecentlyOpened());
   }
 
-  public JalviewFileChooser(String dir, String[] suffix, String[] desc,
-          String selected, boolean selectAll)
+  public JalviewFileChooser(String dir, String extension, String desc,
+          String selected)
   {
     super(safePath(dir));
-    init(suffix, desc, selected, selectAll);
+    init(Collections.singletonList(new String[] { extension, desc }),
+            selected);
   }
 
-  public JalviewFileChooser(String dir, String[] suffix, String[] desc,
+  public JalviewFileChooser(String dir, String[] extensions, String[] descs,
           String selected)
   {
     super(safePath(dir));
-    init(suffix, desc, selected, true);
+    if (extensions.length == descs.length)
+    {
+      List<String[]> formats = new ArrayList<String[]>();
+      for (int i = 0; i < extensions.length; i++)
+      {
+        formats.add(new String[] { extensions[i], descs[i] });
+      }
+      init(formats, selected);
+    }
+    else
+    {
+      System.err.println("JalviewFileChooser arguments mismatch: "
+              + extensions + ", " + descs);
+    }
   }
 
-  public JalviewFileChooser(String property, FileFormatI currentFileFormat,
-          boolean b)
+  private static File safePath(String dir)
   {
-    todo write this
-    // TODO Auto-generated constructor stub
+    if (dir == null)
+    {
+      return null;
+    }
+
+    File f = new File(dir);
+    if (f.getName().indexOf(':') > -1)
+    {
+      return null;
+    }
+    return f;
   }
 
-  void init(String[] suffix, String[] desc, String selected,
-          boolean selectAll)
+  /**
+   * 
+   * @param formats
+   *          a list of {extensions, description} for each file format
+   * @param selected
+   */
+  void init(List<String[]> formats, String selected)
   {
 
     JalviewFileFilter chosen = null;
 
     // SelectAllFilter needs to be set first before adding further
     // file filters to fix bug on Mac OSX
-    setAcceptAllFileFilterUsed(selectAll);
+    setAcceptAllFileFilterUsed(true);
 
-    for (int i = 0; i < suffix.length; i++)
+    for (String[] format : formats)
     {
-      JalviewFileFilter jvf = new JalviewFileFilter(suffix[i], desc[i]);
+      JalviewFileFilter jvf = new JalviewFileFilter(format[0], format[1]);
       addChoosableFileFilter(jvf);
-      if ((selected != null) && selected.equalsIgnoreCase(desc[i]))
+      if ((selected != null) && selected.equalsIgnoreCase(format[1]))
       {
         chosen = jvf;
       }
@@ -130,10 +203,10 @@ public class JalviewFileChooser extends JFileChooser
 
     try
     {
-      if (getUI() instanceof javax.swing.plaf.basic.BasicFileChooserUI)
+      if (getUI() instanceof BasicFileChooserUI)
       {
-        final javax.swing.plaf.basic.BasicFileChooserUI ui = (javax.swing.plaf.basic.BasicFileChooserUI) getUI();
-        final String name = ui.getFileName().trim();
+        final BasicFileChooserUI fcui = (BasicFileChooserUI) getUI();
+        final String name = fcui.getFileName().trim();
 
         if ((name == null) || (name.length() == 0))
         {
@@ -145,10 +218,10 @@ public class JalviewFileChooser extends JFileChooser
           @Override
           public void run()
           {
-            String currentName = ui.getFileName();
+            String currentName = fcui.getFileName();
             if ((currentName == null) || (currentName.length() == 0))
             {
-              ui.setFileName(name);
+              fcui.setFileName(name);
             }
           }
         });
@@ -160,7 +233,7 @@ public class JalviewFileChooser extends JFileChooser
     }
   }
 
-  public FileFormat getSelectedFormat()
+  public FileFormatI getSelectedFormat()
   {
     if (getFileFilter() == null)
     {
index 1f28f49..aa8e406 100755 (executable)
@@ -26,9 +26,10 @@ import jalview.util.Comparison;
 import jalview.util.Format;
 
 import java.io.IOException;
+import java.util.ArrayList;
 import java.util.Hashtable;
+import java.util.List;
 import java.util.StringTokenizer;
-import java.util.Vector;
 
 /**
  * DOCUMENT ME!
@@ -51,16 +52,15 @@ public class MSFfile extends AlignFile
    * 
    * @param inFile
    *          DOCUMENT ME!
-   * @param sourceType
+   * @param type
    *          DOCUMENT ME!
    * 
    * @throws IOException
    *           DOCUMENT ME!
    */
-  public MSFfile(String inFile, DataSourceType sourceType)
-          throws IOException
+  public MSFfile(String inFile, DataSourceType type) throws IOException
   {
-    super(inFile, sourceType);
+    super(inFile, type);
   }
 
   public MSFfile(FileParse source) throws IOException
@@ -69,24 +69,23 @@ public class MSFfile extends AlignFile
   }
 
   /**
-   * DOCUMENT ME!
+   * Read and parse MSF sequence data
    */
   @Override
   public void parse() throws IOException
   {
-    int i = 0;
     boolean seqFlag = false;
-    String key = new String();
-    Vector headers = new Vector();
-    Hashtable seqhash = new Hashtable();
-    String line;
+    List<String> headers = new ArrayList<String>();
+    Hashtable<String, StringBuilder> seqhash = new Hashtable<String, StringBuilder>();
 
     try
     {
+      String line;
       while ((line = nextLine()) != null)
       {
         StringTokenizer str = new StringTokenizer(line);
 
+        String key = null;
         while (str.hasMoreTokens())
         {
           String inStr = str.nextToken();
@@ -95,31 +94,31 @@ public class MSFfile extends AlignFile
           if (inStr.indexOf("Name:") != -1)
           {
             key = str.nextToken();
-            headers.addElement(key);
+            headers.add(key);
           }
 
-          // if line has // set SeqFlag to 1 so we know sequences are coming
+          // if line has // set SeqFlag so we know sequences are coming
           if (inStr.indexOf("//") != -1)
           {
             seqFlag = true;
           }
 
           // Process lines as sequence lines if seqFlag is set
-          if ((inStr.indexOf("//") == -1) && (seqFlag == true))
+          if ((inStr.indexOf("//") == -1) && seqFlag)
           {
-            // seqeunce id is the first field
+            // sequence id is the first field
             key = inStr;
 
-            StringBuffer tempseq;
+            StringBuilder tempseq;
 
             // Get sequence from hash if it exists
             if (seqhash.containsKey(key))
             {
-              tempseq = (StringBuffer) seqhash.get(key);
+              tempseq = seqhash.get(key);
             }
             else
             {
-              tempseq = new StringBuffer();
+              tempseq = new StringBuilder(64);
               seqhash.put(key, tempseq);
             }
 
@@ -127,7 +126,8 @@ public class MSFfile extends AlignFile
             while (str.hasMoreTokens())
             {
               // append the word to the sequence
-              tempseq.append(str.nextToken());
+              String sequenceBlock = str.nextToken();
+              tempseq.append(sequenceBlock);
             }
           }
         }
@@ -141,11 +141,11 @@ public class MSFfile extends AlignFile
     this.noSeqs = headers.size();
 
     // Add sequences to the hash
-    for (i = 0; i < headers.size(); i++)
+    for (int i = 0; i < headers.size(); i++)
     {
-      if (seqhash.get(headers.elementAt(i)) != null)
+      if (seqhash.get(headers.get(i)) != null)
       {
-        String head = headers.elementAt(i).toString();
+        String head = headers.get(i);
         String seq = seqhash.get(head).toString();
 
         if (maxLength < head.length())
@@ -153,8 +153,11 @@ public class MSFfile extends AlignFile
           maxLength = head.length();
         }
 
-        // Replace ~ with a sensible gap character
-        seq = seq.replace('~', '-');
+        /*
+         * replace ~ (leading/trailing positions) with the gap character;
+         * use '.' as this is the internal gap character required by MSF
+         */
+        seq = seq.replace('~', '.');
 
         Sequence newSeq = parseId(head);
 
@@ -165,7 +168,7 @@ public class MSFfile extends AlignFile
       else
       {
         System.err.println("MSFFile Parser: Can't find sequence for "
-                + headers.elementAt(i));
+                + headers.get(i));
       }
     }
   }
@@ -203,16 +206,27 @@ public class MSFfile extends AlignFile
     return check % 10000;
   }
 
+  /**
+   * DOCUMENT ME!
+   * 
+   * @param s
+   *          DOCUMENT ME!
+   * @param is_NA
+   *          DOCUMENT ME!
+   * 
+   * @return DOCUMENT ME!
+   */
   @Override
-  public String print(SequenceI[] sqs, boolean jvsuffix)
+  public String print(SequenceI[] sqs, boolean jvSuffix)
   {
 
     boolean is_NA = Comparison.isNucleotide(sqs);
 
     SequenceI[] s = new SequenceI[sqs.length];
 
-    StringBuffer out = new StringBuffer("!!" + (is_NA ? "NA" : "AA")
-            + "_MULTIPLE_ALIGNMENT 1.0");
+    StringBuilder out = new StringBuilder(256);
+    out.append("!!").append(is_NA ? "NA" : "AA")
+            .append("_MULTIPLE_ALIGNMENT 1.0");
     // TODO: JBPNote : Jalview doesn't remember NA or AA yet.
     out.append(newline);
     out.append(newline);
@@ -222,12 +236,14 @@ public class MSFfile extends AlignFile
 
     while ((i < sqs.length) && (sqs[i] != null))
     {
-      // Replace all internal gaps with . and external spaces with ~
-      s[i] = new Sequence(sqs[i].getName(), sqs[i].getSequenceAsString()
-              .replace('-', '.'), sqs[i].getStart(), sqs[i].getEnd());
+      /*
+       * modify to MSF format: uses '.' for internal gaps, 
+       * and '~' for leading or trailing gaps
+       */
+      String seqString = sqs[i].getSequenceAsString()
+              .replace('-', '.');
 
-      StringBuffer sb = new StringBuffer();
-      sb.append(s[i].getSequence());
+      StringBuilder sb = new StringBuilder(seqString);
 
       for (int ii = 0; ii < sb.length(); ii++)
       {
@@ -252,12 +268,12 @@ public class MSFfile extends AlignFile
           break;
         }
       }
+      s[i] = new Sequence(sqs[i].getName(), sb.toString(),
+              sqs[i].getStart(), sqs[i].getEnd());
 
-      s[i].setSequence(sb.toString());
-
-      if (s[i].getSequence().length > max)
+      if (sb.length() > max)
       {
-        max = s[i].getSequence().length;
+        max = sb.length();
       }
 
       i++;
@@ -293,7 +309,7 @@ public class MSFfile extends AlignFile
     while ((i < s.length) && (s[i] != null))
     {
 
-      nameBlock[i] = new String("  Name: " + printId(s[i], jvsuffix) + " ");
+      nameBlock[i] = new String("  Name: " + printId(s[i], jvSuffix) + " ");
 
       idBlock[i] = new String("Len: "
               + maxLenpad.form(s[i].getSequence().length) + "  Check: "
@@ -345,7 +361,7 @@ public class MSFfile extends AlignFile
 
       while ((j < s.length) && (s[j] != null))
       {
-        String name = printId(s[j], jvsuffix);
+        String name = printId(s[j], jvSuffix);
 
         out.append(new Format("%-" + maxid + "s").form(name + " "));
 
index c6c10bd..05adb0e 100755 (executable)
@@ -109,7 +109,7 @@ public class PfamFile extends AlignFile
       }
       if (spces + 1 < line.length())
       {
-        tempseq.append(line.substring(spces + 1));
+        tempseq.append(line.substring(spces + 1).trim());
       }
     }
 
index 2de14b6..eb623d3 100644 (file)
@@ -20,7 +20,7 @@
  */
 package jalview.io;
 
-import jalview.analysis.SecStrConsensus.SimpleBP;
+import jalview.analysis.Rna;
 import jalview.datamodel.AlignmentAnnotation;
 import jalview.datamodel.Annotation;
 import jalview.datamodel.Sequence;
@@ -32,6 +32,7 @@ import java.io.FileNotFoundException;
 import java.io.FileReader;
 import java.io.IOException;
 import java.util.ArrayList;
+import java.util.List;
 
 import com.stevesoft.pat.Regex;
 
@@ -53,10 +54,9 @@ public class RnamlFile extends AlignFile
 
   }
 
-  public RnamlFile(String inFile, DataSourceType sourceType)
-          throws IOException
+  public RnamlFile(String inFile, DataSourceType type) throws IOException
   {
-    super(inFile, sourceType);
+    super(inFile, type);
 
   }
 
@@ -136,10 +136,10 @@ public class RnamlFile extends AlignFile
 
     result = RNAFactory.loadSecStrRNAML(getReader());
 
-    ArrayList<ArrayList> allarray = new ArrayList();
-    ArrayList<ArrayList<SimpleBP>> BP = new ArrayList();
-    ArrayList strucinarray = new ArrayList();
-    SequenceI[] seqs = new SequenceI[result.size()];
+    // ArrayList<ArrayList> allarray = new ArrayList();
+    // ArrayList<ArrayList<SimpleBP>> BP = new ArrayList();
+    // ArrayList strucinarray = new ArrayList();
+    SequenceI[] sqs = new SequenceI[result.size()];
 
     for (int i = 0; i < result.size(); i++)
     {
@@ -159,9 +159,9 @@ public class RnamlFile extends AlignFile
           id += "." + i;
         }
       }
-      seqs[i] = new Sequence(id, seq, begin, end);
+      sqs[i] = new Sequence(id, seq, begin, end);
 
-      seqs[i].setEnd(seqs[i].findPosition(seqs[i].getLength()));
+      sqs[i].setEnd(sqs[i].findPosition(sqs[i].getLength()));
       String[] annot = new String[rna.length()];
       Annotation[] ann = new Annotation[rna.length()];
 
@@ -172,9 +172,8 @@ public class RnamlFile extends AlignFile
       }
       for (int k = 0; k < rna.length(); k++)
       {
-        ann[k] = new Annotation(annot[k], "",
-                jalview.schemes.ResidueProperties.getRNASecStrucState(
-                        annot[k]).charAt(0), 0f);
+        ann[k] = new Annotation(annot[k], "", Rna.getRNASecStrucState(
+                annot[k]).charAt(0), 0f);
       }
 
       AlignmentAnnotation align = new AlignmentAnnotation(
@@ -183,26 +182,26 @@ public class RnamlFile extends AlignFile
                       + current.getID()
                       : "", ann);
 
-      seqs[i].addAlignmentAnnotation(align);
-      seqs[i].setRNA(result.get(i));
+      sqs[i].addAlignmentAnnotation(align);
+      sqs[i].setRNA(result.get(i));
 
-      allarray.add(strucinarray);
+      // allarray.add(strucinarray);
 
       annotations.addElement(align);
-      BP.add(align.bps);
+      // BP.add(align.bps);
 
     }
 
-    setSeqs(seqs);
+    setSeqs(sqs);
   }
 
   @Override
-  public String print(SequenceI[] sqs, boolean jvsuffix)
+  public String print(SequenceI[] s, boolean jvSuffix)
   {
     return "not yet implemented";
   }
 
-  public ArrayList getRNA()
+  public List<RNA> getRNA()
   {
     return result;
   }
index cb4c786..3fd0505 100644 (file)
@@ -23,6 +23,7 @@
  */
 package jalview.io;
 
+import jalview.analysis.Rna;
 import jalview.datamodel.AlignmentAnnotation;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.Annotation;
@@ -31,6 +32,7 @@ import jalview.datamodel.Mapping;
 import jalview.datamodel.Sequence;
 import jalview.datamodel.SequenceFeature;
 import jalview.datamodel.SequenceI;
+import jalview.schemes.ResidueProperties;
 import jalview.util.Format;
 import jalview.util.MessageManager;
 
@@ -72,8 +74,12 @@ import fr.orsay.lri.varna.models.rna.RNA;
  */
 public class StockholmFile extends AlignFile
 {
-  // static Logger logger = Logger.getLogger("jalview.io.StockholmFile");
-  protected ArrayList<RNA> result;
+  private static final Regex OPEN_PAREN = new Regex("(<|\\[)", "(");
+
+  private static final Regex CLOSE_PAREN = new Regex("(>|\\])", ")");
+
+  private static final Regex DETECT_BRACKETS = new Regex(
+          "(<|>|\\[|\\]|\\(|\\))");
 
   StringBuffer out; // output buffer
 
@@ -91,10 +97,10 @@ public class StockholmFile extends AlignFile
     this.al = al;
   }
 
-  public StockholmFile(String inFile, DataSourceType sourceType)
+  public StockholmFile(String inFile, DataSourceType type)
           throws IOException
   {
-    super(inFile, sourceType);
+    super(inFile, type);
   }
 
   public StockholmFile(FileParse source) throws IOException
@@ -120,7 +126,7 @@ public class StockholmFile extends AlignFile
     fr = new FileReader(inFile);
 
     BufferedReader r = new BufferedReader(fr);
-    result = null;
+    List<RNA> result = null;
     try
     {
       result = RNAFactory.loadSecStrStockholm(r);
@@ -157,9 +163,8 @@ public class StockholmFile extends AlignFile
 
       for (int k = 0; k < rna.length(); k++)
       {
-        ann[k] = new Annotation(annot[k], "",
-                jalview.schemes.ResidueProperties.getRNASecStrucState(
-                        annot[k]).charAt(0), 0f);
+        ann[k] = new Annotation(annot[k], "", Rna.getRNASecStrucState(
+                annot[k]).charAt(0), 0f);
 
       }
       AlignmentAnnotation align = new AlignmentAnnotation("Sec. str.",
@@ -536,8 +541,7 @@ public class StockholmFile extends AlignFile
           }
           else
           {
-            // throw new IOException(MessageManager.formatMessage(
-            // "exception.error_parsing_line", new String[] { line }));
+            // throw new IOException("Error parsing " + line);
             System.err.println(">> missing annotation: " + line);
           }
         }
@@ -791,19 +795,13 @@ public class StockholmFile extends AlignFile
   }
 
   protected static AlignmentAnnotation parseAnnotationRow(
-          Vector annotation, String label, String annots)
+          Vector<AlignmentAnnotation> annotation, String label,
+          String annots)
   {
     String convert1, convert2 = null;
 
-    // Convert all bracket types to parentheses
-    Regex openparen = new Regex("(<|\\[)", "(");
-    Regex closeparen = new Regex("(>|\\])", ")");
-
-    // Detect if file is RNA by looking for bracket types
-    Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
-
-    convert1 = openparen.replaceAll(annots);
-    convert2 = closeparen.replaceAll(convert1);
+    convert1 = OPEN_PAREN.replaceAll(annots);
+    convert2 = CLOSE_PAREN.replaceAll(convert1);
     annots = convert2;
 
     String type = label;
@@ -830,15 +828,15 @@ public class StockholmFile extends AlignFile
       {
         // if (" .-_".indexOf(pos) == -1)
         {
-          if (detectbrackets.search(pos))
+          if (DETECT_BRACKETS.search(pos))
           {
-            ann.secondaryStructure = jalview.schemes.ResidueProperties
-                    .getRNASecStrucState(pos).charAt(0);
+            ann.secondaryStructure = Rna.getRNASecStrucState(
+                    pos).charAt(0);
           }
           else
           {
-            ann.secondaryStructure = jalview.schemes.ResidueProperties
-                    .getDssp3state(pos).charAt(0);
+            ann.secondaryStructure = ResidueProperties.getDssp3state(pos)
+                    .charAt(0);
           }
 
           if (ann.secondaryStructure == pos.charAt(0))
@@ -856,10 +854,10 @@ public class StockholmFile extends AlignFile
       els[i] = ann;
     }
     AlignmentAnnotation annot = null;
-    Enumeration e = annotation.elements();
+    Enumeration<AlignmentAnnotation> e = annotation.elements();
     while (e.hasMoreElements())
     {
-      annot = (AlignmentAnnotation) e.nextElement();
+      annot = e.nextElement();
       if (annot.label.equals(type))
       {
         break;
@@ -885,10 +883,11 @@ public class StockholmFile extends AlignFile
   }
 
   @Override
-  public String print(SequenceI[] s, boolean jvsuffix)
+  public String print(SequenceI[] s, boolean jvSuffix)
   {
-    // out.append("# STOCKHOLM 1.0");
-    // out.append(newline);
+    out = new StringBuffer();
+    out.append("# STOCKHOLM 1.0");
+    out.append(newline);
 
     // find max length of id
     int max = 0;
@@ -897,7 +896,7 @@ public class StockholmFile extends AlignFile
     Hashtable dataRef = null;
     while ((in < s.length) && (s[in] != null))
     {
-      String tmp = printId(s[in], jvsuffix);
+      String tmp = printId(s[in], jvSuffix);
       if (s[in].getSequence().length > max)
       {
         max = s[in].getSequence().length;
@@ -994,7 +993,7 @@ public class StockholmFile extends AlignFile
 
             // out.append("#=GR ");
             out.append(new Format("%-" + maxid + "s").form("#=GR "
-                    + printId(s[i], jvsuffix) + " " + key + " "));
+                    + printId(s[i], jvSuffix) + " " + key + " "));
             ann = alAnot[j].annotations;
             boolean isrna = alAnot[j].isValidStruc();
             String seq = "";
@@ -1009,7 +1008,7 @@ public class StockholmFile extends AlignFile
       }
 
       out.append(new Format("%-" + maxid + "s")
-              .form(printId(s[i], jvsuffix) + " "));
+              .form(printId(s[i], jvSuffix) + " "));
       out.append(s[i].getSequenceAsString());
       out.append(newline);
       i++;
@@ -1062,8 +1061,10 @@ public class StockholmFile extends AlignFile
         out.append(newline);
       }
     }
-    // out.append("//");
-    // out.append(newline);
+
+    out.append("//");
+    out.append(newline);
+
     return out.toString();
   }
 
@@ -1116,7 +1117,20 @@ public class StockholmFile extends AlignFile
     return seq;
   }
 
+  public String print()
+  {
+    out = new StringBuffer();
+    out.append("# STOCKHOLM 1.0");
+    out.append(newline);
+    print(getSeqsAsArray(), false);
+
+    out.append("//");
+    out.append(newline);
+    return out.toString();
+  }
+
   private static Hashtable typeIds = null;
+
   static
   {
     if (typeIds == null)
index 7392f5b..152a2c0 100644 (file)
@@ -8,6 +8,7 @@ import jalview.datamodel.AlignmentI;
 import jalview.datamodel.DBRefEntry;
 import jalview.datamodel.DBRefSource;
 import jalview.datamodel.PDBEntry;
+import jalview.datamodel.PDBEntry.Type;
 import jalview.datamodel.SequenceI;
 import jalview.structure.StructureImportSettings;
 
@@ -25,7 +26,7 @@ public abstract class StructureFile extends AlignFile
 
   private String id;
 
-  private String dbRefType;
+  private PDBEntry.Type dbRefType;
 
   /**
    * set to true to add derived sequence annotations (temp factor read from
@@ -71,7 +72,7 @@ public abstract class StructureFile extends AlignFile
     this.visibleChainAnnotation = StructureImportSettings
             .isVisibleChainAnnotation();
     this.predictSecondaryStructure = StructureImportSettings
-            .isPredictSecondaryStructure();
+            .isProcessSecondaryStructure();
     this.externalSecondaryStructure = StructureImportSettings
             .isExternalSecondaryStructure();
 
@@ -117,8 +118,6 @@ public abstract class StructureFile extends AlignFile
     DBRefEntry sourceDBRef = new DBRefEntry();
     sourceDBRef.setAccessionId(getId());
     sourceDBRef.setSource(DBRefSource.PDB);
-    sourceDBRef.setStartRes(pdbSequence.getStart());
-    sourceDBRef.setEndRes(pdbSequence.getEnd());
     pdbSequence.setSourceDBRef(sourceDBRef);
     pdbSequence.addPDBId(entry);
     pdbSequence.addDBRef(sourceDBRef);
@@ -274,7 +273,7 @@ public abstract class StructureFile extends AlignFile
         StructureImportSettings.setShowSeqFeatures(false);
         StructureImportSettings.setVisibleChainAnnotation(false);
         StructureImportSettings
-                .setPredictSecondaryStructure(predictSecondaryStructure);
+                .setProcessSecondaryStructure(predictSecondaryStructure);
         StructureImportSettings
                 .setExternalSecondaryStructure(externalSecondaryStructure);
         Object jmf = constructor.newInstance(args);
@@ -305,7 +304,7 @@ public abstract class StructureFile extends AlignFile
   {
     for (PDBChain chain : getChains())
     {
-      if (chain.id.equalsIgnoreCase(id))
+      if (chain.id.equals(id))
       {
         return chain;
       }
@@ -402,13 +401,18 @@ public abstract class StructureFile extends AlignFile
     this.chains = chains;
   }
 
-  public String getDbRefType()
+  public Type getDbRefType()
   {
     return dbRefType;
   }
 
   public void setDbRefType(String dbRefType)
   {
+    this.dbRefType = Type.valueOf(dbRefType);
+  }
+
+  public void setDbRefType(Type dbRefType)
+  {
     this.dbRefType = dbRefType;
   }
 
index b2eb094..d7def6b 100755 (executable)
@@ -136,8 +136,6 @@ public class GAlignFrame extends JInternalFrame
 
   public JCheckBoxMenuItem showSeqFeatures = new JCheckBoxMenuItem();
 
-  public JCheckBoxMenuItem showSeqFeaturesHeight = new JCheckBoxMenuItem();
-
   JMenuItem copy = new JMenuItem();
 
   JMenuItem cut = new JMenuItem();
@@ -1591,7 +1589,7 @@ public class GAlignFrame extends JInternalFrame
     });
 
     JMenuItem modifyPID = new JMenuItem(
-            MessageManager.getString("label.modify_identity_thereshold"));
+            MessageManager.getString("label.modify_identity_threshold"));
     modifyPID.addActionListener(new ActionListener()
     {
       @Override
@@ -1601,7 +1599,7 @@ public class GAlignFrame extends JInternalFrame
       }
     });
     modifyConservation.setText(MessageManager
-            .getString("label.modify_conservation_thereshold"));
+            .getString("label.modify_conservation_threshold"));
     modifyConservation.addActionListener(new ActionListener()
     {
       @Override
@@ -2520,13 +2518,6 @@ public class GAlignFrame extends JInternalFrame
 
   }
 
-  protected void showSeqFeaturesHeight_actionPerformed(
-          ActionEvent actionEvent)
-  {
-    // TODO Auto-generated method stub
-
-  }
-
   protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
   {
     // TODO Auto-generated method stub
index df09a61..fef4568 100755 (executable)
@@ -21,6 +21,8 @@
 package jalview.jbgui;
 
 import jalview.datamodel.AlignmentI;
+import jalview.io.DataSourceType;
+import jalview.io.FileFormat;
 import jalview.io.FormatAdapter;
 import jalview.util.MessageManager;
 
@@ -99,6 +101,7 @@ public class GFinder extends JPanel
     findAll.setText(MessageManager.getString("action.find_all"));
     findAll.addActionListener(new java.awt.event.ActionListener()
     {
+      @Override
       public void actionPerformed(ActionEvent e)
       {
         findAll_actionPerformed(e);
@@ -108,6 +111,7 @@ public class GFinder extends JPanel
     findNext.setText(MessageManager.getString("action.find_next"));
     findNext.addActionListener(new java.awt.event.ActionListener()
     {
+      @Override
       public void actionPerformed(ActionEvent e)
       {
         findNext_actionPerformed(e);
@@ -123,6 +127,7 @@ public class GFinder extends JPanel
     createNewGroup.setText(MessageManager.getString("label.new_feature"));
     createNewGroup.addActionListener(new java.awt.event.ActionListener()
     {
+      @Override
       public void actionPerformed(ActionEvent e)
       {
         createNewGroup_actionPerformed(e);
@@ -133,6 +138,7 @@ public class GFinder extends JPanel
     textfield.setLineWrap(true);
     textfield.addCaretListener(new CaretListener()
     {
+      @Override
       public void caretUpdate(CaretEvent e)
       {
         textfield_caretUpdate(e);
@@ -140,6 +146,7 @@ public class GFinder extends JPanel
     });
     textfield.addKeyListener(new java.awt.event.KeyAdapter()
     {
+      @Override
       public void keyPressed(KeyEvent e)
       {
         textfield_keyPressed(e);
@@ -207,13 +214,15 @@ public class GFinder extends JPanel
     {
       SwingUtilities.invokeLater(new Runnable()
       {
+        @Override
         public void run()
         {
           String str = textfield.getText();
           AlignmentI al = null;
           try
           {
-            al = new FormatAdapter().readFile(str, "Paste", "FASTA");
+            al = new FormatAdapter().readFile(str, DataSourceType.PASTE,
+                    FileFormat.Fasta);
           } catch (Exception ex)
           {
           }
index e571064..1348e59 100644 (file)
@@ -379,6 +379,7 @@ public abstract class GStructureChooser extends JPanel implements
             }
           }
           evt.consume();
+          break;
         default:
           return;
         }
index 75099c2..82f6ffb 100644 (file)
@@ -22,6 +22,7 @@ package jalview.renderer;
 
 import jalview.analysis.AAFrequency;
 import jalview.analysis.CodingUtils;
+import jalview.analysis.Rna;
 import jalview.analysis.StructureFrequency;
 import jalview.api.AlignViewportI;
 import jalview.datamodel.AlignmentAnnotation;
@@ -43,8 +44,6 @@ import java.awt.image.ImageObserver;
 import java.util.BitSet;
 import java.util.Hashtable;
 
-import com.stevesoft.pat.Regex;
-
 public class AnnotationRenderer
 {
   private static final int UPPER_TO_LOWER = 'a' - 'A'; // 32
@@ -75,7 +74,7 @@ public class AnnotationRenderer
     this.debugRedraw = debugRedraw;
   }
 
-  public void drawStemAnnot(Graphics g, Annotation[] row_annotations,
+  void drawStemAnnot(Graphics g, Annotation[] row_annotations,
           int lastSSX, int x, int y, int iconOffset, int startRes,
           int column, boolean validRes, boolean validEnd)
   {
@@ -83,7 +82,6 @@ public class AnnotationRenderer
     int sCol = (lastSSX / charWidth) + startRes;
     int x1 = lastSSX;
     int x2 = (x * charWidth);
-    Regex closeparen = new Regex("(\\))");
 
     char dc = (column == 0 || row_annotations[column - 1] == null) ? ' '
             : row_annotations[column - 1].secondaryStructure;
@@ -93,15 +91,17 @@ public class AnnotationRenderer
     boolean diffdownstream = !validRes || !validEnd
             || row_annotations[column] == null
             || dc != row_annotations[column].secondaryStructure;
-    // System.out.println("Column "+column+" diff up: "+diffupstream+" down:"+diffdownstream);
-    // If a closing base pair half of the stem, display a backward arrow
-    if (column > 0 && ResidueProperties.isCloseParenRNA(dc))
-    {
 
+    if (column > 0 && Rna.isClosingParenthesis(dc))
+    {
       if (diffupstream)
       // if (validRes && column>1 && row_annotations[column-2]!=null &&
       // dc.equals(row_annotations[column-2].displayCharacter))
       {
+        /*
+         * if new annotation with a closing base pair half of the stem, 
+         * display a backward arrow
+         */
         g.fillPolygon(new int[] { lastSSX + 5, lastSSX + 5, lastSSX },
                 new int[] { y + iconOffset, y + 14 + iconOffset,
                     y + 8 + iconOffset }, 3);
@@ -114,10 +114,13 @@ public class AnnotationRenderer
     }
     else
     {
-
       // display a forward arrow
       if (diffdownstream)
       {
+        /*
+         * if annotation ending with an opeing base pair half of the stem, 
+         * display a forward arrow
+         */
         g.fillPolygon(new int[] { x2 - 5, x2 - 5, x2 }, new int[] {
             y + iconOffset, y + 14 + iconOffset, y + 8 + iconOffset }, 3);
         x2 -= 5;
@@ -195,7 +198,7 @@ public class AnnotationRenderer
    */
   private boolean canClip = false;
 
-  public void drawNotCanonicalAnnot(Graphics g, Color nonCanColor,
+  void drawNotCanonicalAnnot(Graphics g, Color nonCanColor,
           Annotation[] row_annotations, int lastSSX, int x, int y,
           int iconOffset, int startRes, int column, boolean validRes,
           boolean validEnd)
@@ -206,7 +209,6 @@ public class AnnotationRenderer
     int sCol = (lastSSX / charWidth) + startRes;
     int x1 = lastSSX;
     int x2 = (x * charWidth);
-    Regex closeparen = new Regex("}|]|<|[a-z]");
 
     String dc = (column == 0 || row_annotations[column - 1] == null) ? ""
             : row_annotations[column - 1].displayCharacter;
@@ -218,8 +220,7 @@ public class AnnotationRenderer
             || !dc.equals(row_annotations[column].displayCharacter);
     // System.out.println("Column "+column+" diff up: "+diffupstream+" down:"+diffdownstream);
     // If a closing base pair half of the stem, display a backward arrow
-    if (column > 0 && closeparen.search(dc))// closeletter_b.search(dc)||closeletter_c.search(dc)||closeletter_d.search(dc)||closecrochet.search(dc))
-                                            // )
+    if (column > 0 && Rna.isClosingParenthesis(dc))
     {
 
       if (diffupstream)
@@ -321,7 +322,7 @@ public class AnnotationRenderer
    * @param column
    * @return
    */
-  public int[] getProfileFor(AlignmentAnnotation aa, int column)
+  int[] getProfileFor(AlignmentAnnotation aa, int column)
   {
     // TODO : consider refactoring the global alignment calculation
     // properties/rendering attributes as a global 'alignment group' which holds
@@ -750,7 +751,7 @@ public class AnnotationRenderer
                             validEnd);
                     break;
                   }
-
+                  // no break if isRNA - falls through to drawNotCanonicalAnnot!
                 case 'E':
                   if (!isRNA)
                   {
@@ -759,6 +760,7 @@ public class AnnotationRenderer
                             validEnd);
                     break;
                   }
+                  // no break if isRNA - fall through to drawNotCanonicalAnnot!
 
                 case '{':
                 case '}':
@@ -866,7 +868,6 @@ public class AnnotationRenderer
         {
           validRes = true;
         }
-
         // x ++;
 
         if (row.hasIcons)
@@ -881,6 +882,7 @@ public class AnnotationRenderer
                       startRes, column, validRes, validEnd);
               break;
             }
+            // no break if isRNA - fall through to drawNotCanonicalAnnot!
 
           case 'E':
             if (!isRNA)
@@ -889,6 +891,7 @@ public class AnnotationRenderer
                       startRes, column, validRes, validEnd);
               break;
             }
+            // no break if isRNA - fall through to drawNotCanonicalAnnot!
 
           case '(':
           case ')': // Stem case for RNA secondary structure
@@ -1069,7 +1072,7 @@ public class AnnotationRenderer
 
   private Color sdNOTCANONICAL_COLOUR;
 
-  public void drawGlyphLine(Graphics g, Annotation[] row, int lastSSX,
+  void drawGlyphLine(Graphics g, Annotation[] row, int lastSSX,
           int x, int y, int iconOffset, int startRes, int column,
           boolean validRes, boolean validEnd)
   {
@@ -1077,7 +1080,7 @@ public class AnnotationRenderer
     g.fillRect(lastSSX, y + 6 + iconOffset, (x * charWidth) - lastSSX, 2);
   }
 
-  public void drawSheetAnnot(Graphics g, Annotation[] row,
+  void drawSheetAnnot(Graphics g, Annotation[] row,
 
   int lastSSX, int x, int y, int iconOffset, int startRes, int column,
           boolean validRes, boolean validEnd)
@@ -1101,7 +1104,7 @@ public class AnnotationRenderer
 
   }
 
-  public void drawHelixAnnot(Graphics g, Annotation[] row, int lastSSX,
+  void drawHelixAnnot(Graphics g, Annotation[] row, int lastSSX,
           int x, int y, int iconOffset, int startRes, int column,
           boolean validRes, boolean validEnd)
   {
@@ -1161,7 +1164,7 @@ public class AnnotationRenderer
     g.fillRect(x1, y + 4 + iconOffset, x2 - x1, 8);
   }
 
-  public void drawLineGraph(Graphics g, AlignmentAnnotation _aa,
+  void drawLineGraph(Graphics g, AlignmentAnnotation _aa,
           Annotation[] aa_annotations, int sRes, int eRes, int y,
           float min, float max, int graphHeight)
   {
@@ -1254,7 +1257,7 @@ public class AnnotationRenderer
     }
   }
 
-  public void drawBarGraph(Graphics g, AlignmentAnnotation _aa,
+  void drawBarGraph(Graphics g, AlignmentAnnotation _aa,
           Annotation[] aa_annotations, int sRes, int eRes, float min,
           float max, int y, boolean renderHistogram, boolean renderProfile,
           boolean normaliseProfile)
@@ -1385,8 +1388,9 @@ public class AnnotationRenderer
             scl = htn * scale * profl[c++];
             lm = ofont.getLineMetrics(dc, 0, 1, g.getFontMetrics()
                     .getFontRenderContext());
-            g.setFont(ofont.deriveFont(AffineTransform.getScaleInstance(
-                    wdth, scl / lm.getAscent())));
+            Font font = ofont.deriveFont(AffineTransform.getScaleInstance(
+                    wdth, scl / lm.getAscent()));
+            g.setFont(font);
             lm = g.getFontMetrics().getLineMetrics(dc, 0, 1, g);
 
             // Debug - render boxes around characters
index 7f1e074..6940f22 100644 (file)
@@ -34,6 +34,22 @@ import java.util.List;
  */
 public class ScaleRenderer
 {
+  public final class ScaleMark
+  {
+    public final boolean major;
+
+    public final int column;
+
+    public final String text;
+
+    ScaleMark(boolean isMajor, int col, String txt)
+    {
+      major = isMajor;
+      column = col;
+      text = txt;
+    }
+  }
+
   /**
    * calculate positions markers on the alignment ruler
    * 
@@ -42,15 +58,13 @@ public class ScaleRenderer
    *          left-most column in visible view
    * @param endx
    *          - right-most column in visible view
-   * @return List { Object { .. } } Boolean: true/false for major/minor mark,
-   *         Integer: marker position in alignment column coords, String: null
-   *         or a String to be rendered at the position.
+   * @return List of ScaleMark holding boolean: true/false for major/minor mark,
+   *         marker position in alignment column coords, a String to be rendered
+   *         at the position (or null)
    */
-  public static List<Object[]> calculateMarks(AlignViewportI av,
+  public List<ScaleMark> calculateMarks(AlignViewportI av,
           int startx, int endx)
   {
-    new ArrayList<Object[]>();
-
     int scalestartx = (startx / 10) * 10;
 
     SequenceI refSeq = av.getAlignment().getSeqrep();
@@ -72,13 +86,12 @@ public class ScaleRenderer
     {
       scalestartx += 5;
     }
-    List<Object[]> marks = new ArrayList<Object[]>();
+    List<ScaleMark> marks = new ArrayList<ScaleMark>();
     String string;
     int refN, iadj;
     // todo: add a 'reference origin column' to set column number relative to
     for (int i = scalestartx; i < endx; i += 5)
     {
-      Object[] amark = new Object[3];
       if (((i - refSp) % 10) == 0)
       {
         if (refSeq == null)
@@ -106,18 +119,12 @@ public class ScaleRenderer
             string = String.valueOf(refN) + refSeq.getCharAt(iadj);
           }
         }
-        amark[0] = Boolean.TRUE;
-        amark[1] = Integer.valueOf(i - startx - 1);
-        amark[2] = string;
-
+        marks.add(new ScaleMark(true, i - startx - 1, string));
       }
       else
       {
-        amark[0] = Boolean.FALSE;
-        amark[1] = Integer.valueOf(i - startx - 1);
-        amark[2] = null;
+        marks.add(new ScaleMark(false, i - startx - 1, null));
       }
-      marks.add(amark);
     }
     return marks;
   }
index 5d3aa2d..b007365 100644 (file)
@@ -20,6 +20,7 @@
  */
 package jalview.renderer.seqfeatures;
 
+import jalview.api.AlignViewportI;
 import jalview.datamodel.SequenceFeature;
 import jalview.datamodel.SequenceI;
 import jalview.viewmodel.seqfeatures.FeatureRendererModel;
@@ -52,6 +53,16 @@ public class FeatureRenderer extends FeatureRendererModel
 
   private Integer currentColour;
 
+  /**
+   * Constructor given a viewport
+   * 
+   * @param viewport
+   */
+  public FeatureRenderer(AlignViewportI viewport)
+  {
+    this.av = viewport;
+  }
+
   protected void updateAvConfig()
   {
     av_charHeight = av.getCharHeight();
index 2aa24a1..d0d26b0 100755 (executable)
@@ -1603,87 +1603,6 @@ public class ResidueProperties
     return ss.toString();
   }
 
-  /**
-   * Used by getRNASecStrucState
-   * 
-   */
-  public static Hashtable<String, String> toRNAssState;
-
-  public static boolean RNAcloseParen[] = new boolean[255];
-  static
-  {
-    toRNAssState = new Hashtable<String, String>();
-    toRNAssState.put(")", "(");
-    toRNAssState.put("(", "(");
-    toRNAssState.put("]", "[");
-    toRNAssState.put("[", "[");
-    toRNAssState.put("{", "{");
-    toRNAssState.put("}", "{");
-    toRNAssState.put(">", ">");
-    toRNAssState.put("<", ">");
-    toRNAssState.put("A", "A");
-    toRNAssState.put("a", "A");
-    toRNAssState.put("B", "B");
-    toRNAssState.put("b", "B");
-    toRNAssState.put("C", "C");
-    toRNAssState.put("c", "C");
-    toRNAssState.put("D", "D");
-    toRNAssState.put("d", "D");
-    toRNAssState.put("E", "E");
-    toRNAssState.put("e", "E");
-    toRNAssState.put("F", "F");
-    toRNAssState.put("f", "F");
-    toRNAssState.put("G", "G");
-    toRNAssState.put("g", "G");
-    toRNAssState.put("H", "H");
-    toRNAssState.put("h", "H");
-    toRNAssState.put("I", "I");
-    toRNAssState.put("i", "I");
-    toRNAssState.put("J", "J");
-    toRNAssState.put("j", "J");
-    toRNAssState.put("K", "K");
-    toRNAssState.put("k", "K");
-    toRNAssState.put("L", "L");
-    toRNAssState.put("l", "L");
-    toRNAssState.put("M", "M");
-    toRNAssState.put("m", "M");
-    toRNAssState.put("N", "N");
-    toRNAssState.put("n", "N");
-    toRNAssState.put("O", "O");
-    toRNAssState.put("o", "O");
-    toRNAssState.put("P", "P");
-    toRNAssState.put("p", "P");
-    toRNAssState.put("Q", "Q");
-    toRNAssState.put("q", "Q");
-    toRNAssState.put("R", "R");
-    toRNAssState.put("r", "R");
-    toRNAssState.put("S", "S");
-    toRNAssState.put("s", "S");
-    toRNAssState.put("T", "T");
-    toRNAssState.put("t", "T");
-    toRNAssState.put("U", "U");
-    toRNAssState.put("u", "U");
-    toRNAssState.put("V", "V");
-    toRNAssState.put("v", "V");
-    toRNAssState.put("W", "W");
-    toRNAssState.put("w", "W");
-    toRNAssState.put("X", "X");
-    toRNAssState.put("x", "X");
-    toRNAssState.put("Y", "Y");
-    toRNAssState.put("y", "Y");
-    toRNAssState.put("Z", "Z");
-    toRNAssState.put("z", "Z");
-    for (int p = 0; p < RNAcloseParen.length; p++)
-    {
-      RNAcloseParen[p] = false;
-    }
-    for (String k : toRNAssState.keySet())
-    {
-      RNAcloseParen[k.charAt(0)] = k.charAt(0) != toRNAssState.get(k)
-              .charAt(0);
-    }
-  }
-
   static
   {
     modifications.put("MSE", "MET"); // Selenomethionine
@@ -3008,40 +2927,6 @@ public class ResidueProperties
     return canonical == null ? aa : canonical;
   }
 
-  /**
-   * translate to RNA secondary structure representation
-   * 
-   * @param ssstring
-   * @return ssstring as a RNA-state secondary structure assignment.
-   */
-  public static String getRNASecStrucState(String ssstring)
-  {
-    if (ssstring == null)
-    {
-      return null;
-    }
-    StringBuffer ss = new StringBuffer();
-    for (int i = 0; i < ssstring.length(); i++)
-    {
-      String ssc = ssstring.substring(i, i + 1);
-      if (toRNAssState.containsKey(ssc))
-      {
-        // valid ss character - so return it
-        ss.append(ssc); // (String) toRNAssState.get(ssc));
-      }
-      else
-      {
-        ss.append(" ");
-      }
-    }
-    return ss.toString();
-  }
-
-  public static boolean isCloseParenRNA(char dc)
-  {
-    return RNAcloseParen[dc];
-  }
-
   // main method generates perl representation of residue property hash
   // / cut here
   public static void main(String[] args)
index b23fd53..f5963de 100644 (file)
@@ -1,7 +1,15 @@
 package jalview.structure;
 
-import jalview.datamodel.DBRefSource;
-
+import jalview.datamodel.PDBEntry;
+import jalview.datamodel.PDBEntry.Type;
+
+/**
+ * bean holding settings for structure IO. TODO: tests for validation of values
+ * TODO: tests for race conditions (all fields are static, is that correct ?)
+ * 
+ * @author tcofoegbu
+ *
+ */
 public class StructureImportSettings
 {
   /**
@@ -14,7 +22,7 @@ public class StructureImportSettings
    * Set true to predict secondary structure (using JMol for protein, Annotate3D
    * for RNA)
    */
-  private static boolean predictSecStr = false;
+  private static boolean processSecStr = false;
 
   /**
    * Set true (with predictSecondaryStructure=true) to predict secondary
@@ -24,15 +32,28 @@ public class StructureImportSettings
 
   private static boolean showSeqFeatures = true;
 
-  private static boolean processHETATMs = false;
+  public enum StructureParser
+  {
+    JMOL_PARSER, JALVIEW_PARSER
+  }
+
 
-  private static String currentDefaultFormat = DBRefSource.PDB;
+  /**
+   * Determines the default file format for structure files to be downloaded
+   * from the PDB sequence fetcher. Possible options include: PDB|mmCIF
+   */
+  private static PDBEntry.Type defaultStructureFileFormat = Type.PDB;
 
+  /**
+   * Determines the parser used for parsing PDB format file. Possible options
+   * are : JMolParser|JalveiwParser
+   */
+  private static StructureParser defaultPDBFileParser = StructureParser.JMOL_PARSER;
   public static void addSettings(boolean addAlignmentAnnotations,
-          boolean predictSecStr, boolean externalSecStr)
+          boolean processSecStr, boolean externalSecStr)
   {
     StructureImportSettings.visibleChainAnnotation = addAlignmentAnnotations;
-    StructureImportSettings.predictSecStr = predictSecStr;
+    StructureImportSettings.processSecStr = processSecStr;
     StructureImportSettings.externalSecondaryStructure = externalSecStr;
     StructureImportSettings.showSeqFeatures = true;
   }
@@ -48,15 +69,15 @@ public class StructureImportSettings
     StructureImportSettings.visibleChainAnnotation = visibleChainAnnotation;
   }
 
-  public static boolean isPredictSecondaryStructure()
+  public static boolean isProcessSecondaryStructure()
   {
-    return predictSecStr;
+    return processSecStr;
   }
 
-  public static void setPredictSecondaryStructure(
-          boolean predictSecondaryStructure)
+  public static void setProcessSecondaryStructure(
+          boolean processSecondaryStructure)
   {
-    StructureImportSettings.predictSecStr = predictSecondaryStructure;
+    StructureImportSettings.processSecStr = processSecondaryStructure;
   }
 
   public static boolean isExternalSecondaryStructure()
@@ -80,24 +101,33 @@ public class StructureImportSettings
     StructureImportSettings.showSeqFeatures = showSeqFeatures;
   }
 
-  public static String getCurrentDefaultFormat()
+  public static PDBEntry.Type getDefaultStructureFileFormat()
+  {
+    return defaultStructureFileFormat;
+  }
+
+  public static void setDefaultStructureFileFormat(
+          String defaultStructureFileFormat)
   {
-    return currentDefaultFormat;
+    StructureImportSettings.defaultStructureFileFormat = PDBEntry.Type
+            .valueOf(defaultStructureFileFormat.toUpperCase());
   }
 
-  public static void setCurrentDefaultFormat(String currentDefaultFormat)
+  public static String getDefaultPDBFileParser()
   {
-    StructureImportSettings.currentDefaultFormat = currentDefaultFormat;
+    return defaultPDBFileParser.toString();
   }
 
-  public static boolean isProcessHETATMs()
+  public static void setDefaultPDBFileParser(
+          StructureParser defaultPDBFileParser)
   {
-    return processHETATMs;
+    StructureImportSettings.defaultPDBFileParser = defaultPDBFileParser;
   }
 
-  public static void setProcessHETATMs(boolean processHETATMs)
+  public static void setDefaultPDBFileParser(String defaultPDBFileParser)
   {
-    StructureImportSettings.processHETATMs = processHETATMs;
+    StructureImportSettings.defaultPDBFileParser = StructureParser
+            .valueOf(defaultPDBFileParser.toUpperCase());
   }
 
 }
index 1a29cbf..1738f99 100644 (file)
@@ -386,7 +386,11 @@ public class StructureSelectionManager
     try
     {
 
-      if (pdbFile != null && isCIFFile(pdbFile))
+      boolean isParseWithJMOL = StructureImportSettings
+              .getDefaultPDBFileParser().equalsIgnoreCase(
+                      StructureImportSettings.StructureParser.JMOL_PARSER
+                              .toString());
+      if (isParseWithJMOL || (pdbFile != null && isCIFFile(pdbFile)))
       {
         pdb = new JmolParser(addTempFacAnnot, parseSecStr,
                 secStructServices, pdbFile, sourceType);
index 5605a53..0beb45b 100644 (file)
@@ -249,6 +249,18 @@ public class Comparison
   }
 
   /**
+   * Overloaded method signature to test whether a single sequence is nucleotide
+   * (that is, more than 85% CGTA)
+   * 
+   * @param seq
+   * @return
+   */
+  public static final boolean isNucleotide(SequenceI seq)
+  {
+    return isNucleotide(new SequenceI[] { seq });
+  }
+
+  /**
    * Answers true if more than 85% of the sequence residues (ignoring gaps) are
    * A, G, C, T or U, else false. This is just a heuristic guess and may give a
    * wrong answer (as AGCT are also amino acid codes).
index 424d40b..d5d0cf5 100755 (executable)
@@ -67,11 +67,14 @@ public class DBRefUtils
   }
 
   /**
+   * Returns those DBRefEntry objects whose source identifier (once converted to
+   * Jalview's canonical form) is in the list of sources to search for. Returns
+   * null if no matches found.
    * 
    * @param dbrefs
-   *          array of DBRef objects to search
+   *          DBRefEntry objects to search
    * @param sources
-   *          String[] array of source DBRef IDs to retrieve
+   *          array of sources to select
    * @return
    */
   public static DBRefEntry[] selectRefs(DBRefEntry[] dbrefs,
@@ -148,8 +151,8 @@ public class DBRefUtils
   }
 
   /**
-   * Returns an array of those references that match the given entry, or null if
-   * no matches. Currently uses a comparator which matches if
+   * Returns a (possibly empty) list of those references that match the given
+   * entry. Currently uses a comparator which matches if
    * <ul>
    * <li>database sources are the same</li>
    * <li>accession ids are the same</li>
@@ -162,34 +165,35 @@ public class DBRefUtils
    *          pattern to match
    * @return
    */
-  public static DBRefEntry[] searchRefs(DBRefEntry[] ref, DBRefEntry entry)
+  public static List<DBRefEntry> searchRefs(DBRefEntry[] ref,
+          DBRefEntry entry)
   {
     return searchRefs(ref, entry,
             matchDbAndIdAndEitherMapOrEquivalentMapList);
   }
 
   /**
-   * Returns an array of those references that match the given accession id
+   * Returns a list of those references that match the given accession id
    * <ul>
    * <li>database sources are the same</li>
    * <li>accession ids are the same</li>
    * <li>both have no mapping, or the mappings are the same</li>
    * </ul>
    * 
-   * @param ref
+   * @param refs
    *          Set of references to search
-   * @param entry
-   *          pattern to match
+   * @param accId
+   *          accession id to match
    * @return
    */
-  public static DBRefEntry[] searchRefs(DBRefEntry[] ref, String accId)
+  public static List<DBRefEntry> searchRefs(DBRefEntry[] refs, String accId)
   {
-    return searchRefs(ref, new DBRefEntry("", "", accId), matchId);
+    return searchRefs(refs, new DBRefEntry("", "", accId), matchId);
   }
 
   /**
-   * Returns an array of those references that match the given entry, according
-   * to the given comparator. Returns null if no matches.
+   * Returns a (possibly empty) list of those references that match the given
+   * entry, according to the given comparator.
    * 
    * @param refs
    *          an array of database references to search
@@ -198,14 +202,14 @@ public class DBRefUtils
    * @param comparator
    * @return
    */
-  static DBRefEntry[] searchRefs(DBRefEntry[] refs, DBRefEntry entry,
+  static List<DBRefEntry> searchRefs(DBRefEntry[] refs, DBRefEntry entry,
           DbRefComp comparator)
   {
+    List<DBRefEntry> rfs = new ArrayList<DBRefEntry>();
     if (refs == null || entry == null)
     {
-      return null;
+      return rfs;
     }
-    List<DBRefEntry> rfs = new ArrayList<DBRefEntry>();
     for (int i = 0; i < refs.length; i++)
     {
       if (comparator.matches(entry, refs[i]))
@@ -213,7 +217,7 @@ public class DBRefUtils
         rfs.add(refs[i]);
       }
     }
-    return rfs.size() == 0 ? null : rfs.toArray(new DBRefEntry[rfs.size()]);
+    return rfs;
   }
 
   interface DbRefComp
@@ -380,9 +384,9 @@ public class DBRefUtils
   };
 
   /**
-   * accession ID and DB must be identical. Version is ignored. No map on either
-   * or map but no maplist on either or maplist of map on a is equivalent to the
-   * maplist of map on b.
+   * accession ID and DB must be identical, or null on a. Version is ignored. No
+   * map on either or map but no maplist on either or maplist of map on a is
+   * equivalent to the maplist of map on b.
    */
   public static DbRefComp matchDbAndIdAndEitherMapOrEquivalentMapList = new DbRefComp()
   {
@@ -393,8 +397,9 @@ public class DBRefUtils
               && refb.getSource().equals(refa.getSource()))
       {
         // We dont care about version
-        if (refa.getAccessionId() != null && refb.getAccessionId() != null
-                && refb.getAccessionId().equals(refa.getAccessionId()))
+
+        if (refa.getAccessionId() == null
+                || refa.getAccessionId().equals(refb.getAccessionId()))
         {
           if (refa.getMap() == null || refb.getMap() == null)
           {
@@ -406,7 +411,7 @@ public class DBRefUtils
                   || (refb.getMap().getMap() != null
                           && refa.getMap().getMap() != null && (refb
                           .getMap().getMap().equals(refa.getMap().getMap()))))
-          { // getMap().getMap().containsEither(false,refa.getMap().getMap())
+          {
             return true;
           }
         }
@@ -519,4 +524,49 @@ public class DBRefUtils
     return (o1 == null ? o2.equals(o1) : o1.equals(o2));
   }
 
+  /**
+   * Selects just the DNA or protein references from a set of references
+   * 
+   * @param selectDna
+   *          if true, select references to 'standard' DNA databases, else to
+   *          'standard' peptide databases
+   * @param refs
+   *          a set of references to select from
+   * @return
+   */
+  public static DBRefEntry[] selectDbRefs(boolean selectDna,
+          DBRefEntry[] refs)
+  {
+    return selectRefs(refs, selectDna ? DBRefSource.DNACODINGDBS
+            : DBRefSource.PROTEINDBS);
+    // could attempt to find other cross
+    // refs here - ie PDB xrefs
+    // (not dna, not protein seq)
+  }
+
+  /**
+   * Returns the (possibly empty) list of those supplied dbrefs which have the
+   * specified source database, with a case-insensitive match of source name
+   * 
+   * @param dbRefs
+   * @param source
+   * @return
+   */
+  public static List<DBRefEntry> searchRefsForSource(DBRefEntry[] dbRefs,
+          String source)
+  {
+    List<DBRefEntry> matches = new ArrayList<DBRefEntry>();
+    if (dbRefs != null && source != null)
+    {
+      for (DBRefEntry dbref : dbRefs)
+      {
+        if (source.equalsIgnoreCase(dbref.getSource()))
+        {
+          matches.add(dbref);
+        }
+      }
+    }
+    return matches;
+  }
+
 }
index fcea21d..d8b6a7b 100755 (executable)
@@ -20,6 +20,7 @@
  */
 package jalview.util;
 
+import jalview.bin.Cache;
 import jalview.bin.Jalview;
 import jalview.gui.EPSOptions;
 import jalview.gui.IProgressIndicator;
@@ -42,6 +43,22 @@ import org.jibble.epsgraphics.EpsGraphics2D;
 
 public class ImageMaker
 {
+  public static final String SVG_DESCRIPTION = "Scalable Vector Graphics";
+
+  public static final String SVG_EXTENSION = "svg";
+
+  public static final String EPS_DESCRIPTION = "Encapsulated Postscript";
+
+  public static final String EPS_EXTENSION = "eps";
+
+  public static final String PNG_EXTENSION = "png";
+
+  public static final String PNG_DESCRIPTION = "Portable  network graphics";
+
+  public static final String HTML_EXTENSION = "html";
+
+  public static final String HTML_DESCRIPTION = "Hypertext Markup Language";
+
   EpsGraphics2D pg;
 
   SVGGraphics2D g2;
@@ -181,7 +198,7 @@ public class ImageMaker
         out.close();
         break;
       case PNG:
-        ImageIO.write(bi, "png", out);
+        ImageIO.write(bi, PNG_EXTENSION, out);
         out.flush();
         out.close();
         break;
@@ -293,11 +310,8 @@ public class ImageMaker
     {
       return null;
     }
-    return new jalview.io.JalviewFileChooser(
-            jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
-            new String[] { "png" },
-            new String[] { "Portable network graphics" },
-            "Portable network graphics");
+    return new JalviewFileChooser(Cache.getProperty("LAST_DIRECTORY"),
+            PNG_EXTENSION, PNG_DESCRIPTION, PNG_DESCRIPTION);
   }
 
   static JalviewFileChooser getEPSChooser()
@@ -306,11 +320,8 @@ public class ImageMaker
     {
       return null;
     }
-    return new jalview.io.JalviewFileChooser(
-            jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
-            new String[] { "eps" },
-            new String[] { "Encapsulated Postscript" },
-            "Encapsulated Postscript");
+    return new JalviewFileChooser(Cache.getProperty("LAST_DIRECTORY"),
+            EPS_EXTENSION, EPS_DESCRIPTION, EPS_DESCRIPTION);
   }
 
   private void setProgressMessage(String message)
@@ -327,10 +338,7 @@ public class ImageMaker
     {
       return null;
     }
-    return new jalview.io.JalviewFileChooser(
-            jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
-            new String[] { "svg" },
-            new String[] { "Scalable Vector Graphics" },
-            "Scalable Vector Graphics");
+    return new JalviewFileChooser(Cache.getProperty("LAST_DIRECTORY"),
+            SVG_EXTENSION, SVG_DESCRIPTION, SVG_DESCRIPTION);
   }
 }
index e51442c..cae968e 100644 (file)
@@ -88,8 +88,6 @@ public class MapList
   @Override
   public boolean equals(Object o)
   {
-    // TODO should also override hashCode to ensure equal objects have equal
-    // hashcodes
     if (o == null || !(o instanceof MapList))
     {
       return false;
@@ -112,6 +110,19 @@ public class MapList
   }
 
   /**
+   * Returns a hashcode made from the fromRatio, toRatio, and from/to ranges
+   */
+  @Override
+  public int hashCode()
+  {
+    int hashCode = 31 * fromRatio;
+    hashCode = 31 * hashCode + toRatio;
+    hashCode = 31 * hashCode + fromShifts.toArray().hashCode();
+    hashCode = 31 * hashCode + toShifts.toArray().hashCode();
+    return hashCode;
+  }
+
+  /**
    * Returns the 'from' ranges as {[start1, end1], [start2, end2], ...}
    * 
    * @return
@@ -215,7 +226,7 @@ public class MapList
     {
       /*
        * note lowest and highest values - bearing in mind the
-       * direction may be revesed
+       * direction may be reversed
        */
       fromLowest = Math.min(fromLowest, Math.min(from[i], from[i + 1]));
       fromHighest = Math.max(fromHighest, Math.max(from[i], from[i + 1]));
@@ -992,6 +1003,10 @@ public class MapList
    */
   public void addMapList(MapList map)
   {
+    if (this.equals(map))
+    {
+      return;
+    }
     this.fromLowest = Math.min(fromLowest, map.fromLowest);
     this.toLowest = Math.min(toLowest, map.toLowest);
     this.fromHighest = Math.max(fromHighest, map.fromHighest);
@@ -1087,4 +1102,5 @@ public class MapList
     }
     return forwardStrand;
   }
+
 }
index ae4e55d..515ff51 100644 (file)
@@ -754,6 +754,13 @@ public final class MappingUtils
   public static List<AlignedCodonFrame> findMappingsForSequence(
           SequenceI sequence, List<AlignedCodonFrame> mappings)
   {
+    return findMappingsForSequenceAndOthers(sequence, mappings, null);
+  }
+
+  public static List<AlignedCodonFrame> findMappingsForSequenceAndOthers(
+          SequenceI sequence, List<AlignedCodonFrame> mappings,
+          AlignmentI alignment)
+  {
     List<AlignedCodonFrame> result = new ArrayList<AlignedCodonFrame>();
     if (sequence == null || mappings == null)
     {
@@ -763,7 +770,31 @@ public final class MappingUtils
     {
       if (mapping.involvesSequence(sequence))
       {
-        result.add(mapping);
+        if (alignment != null)
+        {
+          for (SequenceI otherseq : alignment.getSequences())
+          {
+            if (otherseq == sequence
+                    || (otherseq.getDatasetSequence() != null && (otherseq
+                            .getDatasetSequence() == sequence || otherseq
+                            .getDatasetSequence() == sequence
+                            .getDatasetSequence())))
+            {
+              // skip sequences in subset which directly relate to sequence
+              continue;
+            }
+            if (mapping.involvesSequence(otherseq))
+            {
+              // selected a mapping contained in subselect alignment
+              result.add(mapping);
+              break;
+            }
+          }
+        }
+        else
+        {
+          result.add(mapping);
+        }
       }
     }
     return result;
index 786f5bf..85a27f6 100644 (file)
@@ -78,10 +78,21 @@ public class Platform
     return f.toString();
   }
 
+  /**
+   * Answers true if the mouse event has Meta-down (on Mac) or Ctrl-down (on
+   * other o/s)
+   * 
+   * @param e
+   * @return
+   */
   public static boolean isControlDown(MouseEvent e)
   {
-    return (jalview.util.Platform.isAMac() ? (Toolkit.getDefaultToolkit()
-            .getMenuShortcutKeyMask() & e.getModifiers()) != 0 : e
-            .isControlDown());
+    if (isAMac())
+    {
+      return (Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() & e
+              .getModifiers()) != 0;
+      // could we use e.isMetaDown() here?
+    }
+    return e.isControlDown();
   }
 }
index eab4aa5..19ebf45 100644 (file)
@@ -844,14 +844,22 @@ public abstract class AlignmentViewport implements AlignViewportI,
             && !al.getCodonFrames().isEmpty())
     {
       /*
-       * fudge - check first mapping is protein-to-nucleotide
+       * fudge - check first for protein-to-nucleotide mappings
        * (we don't want to do this for protein-to-protein)
        */
-      AlignedCodonFrame mapping = al.getCodonFrames().iterator().next();
-      // TODO hold mapping type e.g. dna-to-protein in AlignedCodonFrame?
-      MapList[] mapLists = mapping.getdnaToProt();
-      // mapLists can be empty if project load has not finished resolving seqs
-      if (mapLists.length > 0 && mapLists[0].getFromRatio() == 3)
+      boolean doConsensus = false;
+      for (AlignedCodonFrame mapping : al.getCodonFrames())
+      {
+        // TODO hold mapping type e.g. dna-to-protein in AlignedCodonFrame?
+        MapList[] mapLists = mapping.getdnaToProt();
+        // mapLists can be empty if project load has not finished resolving seqs
+        if (mapLists.length > 0 && mapLists[0].getFromRatio() == 3)
+        {
+          doConsensus = true;
+          break;
+        }
+      }
+      if (doConsensus)
       {
         if (calculator
                 .getRegisteredWorkersOfClass(ComplementConsensusThread.class) == null)
@@ -1872,12 +1880,20 @@ public abstract class AlignmentViewport implements AlignViewportI,
               .getCodonFrames();
       if (codonMappings != null && !codonMappings.isEmpty())
       {
-        // fudge: check mappings are not protein-to-protein
-        // TODO: nicer
-        AlignedCodonFrame mapping = codonMappings.iterator().next();
-        MapList[] mapLists = mapping.getdnaToProt();
-        // mapLists can be empty if project load has not finished resolving seqs
-        if (mapLists.length > 0 && mapLists[0].getFromRatio() == 3)
+        boolean doConsensus = false;
+        for (AlignedCodonFrame mapping : codonMappings)
+        {
+          // TODO hold mapping type e.g. dna-to-protein in AlignedCodonFrame?
+          MapList[] mapLists = mapping.getdnaToProt();
+          // mapLists can be empty if project load has not finished resolving
+          // seqs
+          if (mapLists.length > 0 && mapLists[0].getFromRatio() == 3)
+          {
+            doConsensus = true;
+            break;
+          }
+        }
+        if (doConsensus)
         {
           complementConsensus = new AlignmentAnnotation("cDNA Consensus",
                   "PID for cDNA", new Annotation[1], 0f, 100f,
@@ -2700,6 +2716,7 @@ public abstract class AlignmentViewport implements AlignViewportI,
      * all gapped visible regions
      */
     int lastSeq = alignment.getHeight() - 1;
+    List<AlignedCodonFrame> seqMappings = null;
     for (int seqNo = getStartSeq(); seqNo < lastSeq; seqNo++, seqOffset++)
     {
       sequence = getAlignment().getSequenceAt(seqNo);
@@ -2711,15 +2728,16 @@ public abstract class AlignmentViewport implements AlignViewportI,
       {
         continue;
       }
-      List<AlignedCodonFrame> seqMappings = MappingUtils
-              .findMappingsForSequence(sequence, mappings);
+      seqMappings = MappingUtils
+              .findMappingsForSequenceAndOthers(sequence, mappings,
+                      getCodingComplement().getAlignment());
       if (!seqMappings.isEmpty())
       {
         break;
       }
     }
 
-    if (sequence == null)
+    if (sequence == null || seqMappings == null || seqMappings.isEmpty())
     {
       /*
        * No ungapped mapped sequence in middle column - do nothing
@@ -2727,7 +2745,7 @@ public abstract class AlignmentViewport implements AlignViewportI,
       return 0;
     }
     MappingUtils.addSearchResults(sr, sequence,
-            sequence.findPosition(middleColumn), mappings);
+            sequence.findPosition(middleColumn), seqMappings);
     return seqOffset;
   }
 
index a4e4348..d813fe2 100644 (file)
@@ -29,7 +29,6 @@ import jalview.datamodel.SequenceI;
 import jalview.renderer.seqfeatures.FeatureRenderer;
 import jalview.schemes.FeatureColour;
 import jalview.schemes.UserColourScheme;
-import jalview.viewmodel.AlignmentViewport;
 
 import java.awt.Color;
 import java.beans.PropertyChangeListener;
@@ -64,7 +63,7 @@ public abstract class FeatureRendererModel implements
   protected PropertyChangeSupport changeSupport = new PropertyChangeSupport(
           this);
 
-  protected AlignmentViewport av;
+  protected AlignViewportI av;
 
   @Override
   public AlignViewportI getViewport()
index 1063706..addb372 100644 (file)
@@ -34,23 +34,48 @@ import java.util.Set;
 
 public class AlignCalcManager implements AlignCalcManagerI
 {
-  private volatile List<AlignCalcWorkerI> restartable = Collections
-          .synchronizedList(new ArrayList<AlignCalcWorkerI>());
+  /*
+   * list of registered workers
+   */
+  private volatile List<AlignCalcWorkerI> restartable;
 
-  private volatile List<Class> blackList = Collections
-          .synchronizedList(new ArrayList<Class>());
+  /*
+   * types of worker _not_ to run (for example, because they have
+   * previously thrown errors)
+   */
+  private volatile List<Class<? extends AlignCalcWorkerI>> blackList;
 
-  /**
+  /*
    * global record of calculations in progress
    */
-  private volatile Map<Class, AlignCalcWorkerI> inProgress = Collections
-          .synchronizedMap(new Hashtable<Class, AlignCalcWorkerI>());
+  private volatile List<AlignCalcWorkerI> inProgress;
 
-  /**
+  /*
    * record of calculations pending or in progress in the current context
    */
-  private volatile Map<Class, List<AlignCalcWorkerI>> updating = Collections
-          .synchronizedMap(new Hashtable<Class, List<AlignCalcWorkerI>>());
+  private volatile Map<Class<? extends AlignCalcWorkerI>, List<AlignCalcWorkerI>> updating;
+
+  /*
+   * workers that have run to completion so are candidates for visual-only 
+   * update of their results
+   */
+  private HashSet<AlignCalcWorkerI> canUpdate;
+
+  /**
+   * Constructor
+   */
+  public AlignCalcManager()
+  {
+    restartable = Collections
+            .synchronizedList(new ArrayList<AlignCalcWorkerI>());
+    blackList = Collections
+            .synchronizedList(new ArrayList<Class<? extends AlignCalcWorkerI>>());
+    inProgress = Collections
+            .synchronizedList(new ArrayList<AlignCalcWorkerI>());
+    updating = Collections
+            .synchronizedMap(new Hashtable<Class<? extends AlignCalcWorkerI>, List<AlignCalcWorkerI>>());
+    canUpdate = new HashSet<AlignCalcWorkerI>();
+  }
 
   @Override
   public void notifyStart(AlignCalcWorkerI worker)
@@ -72,15 +97,6 @@ public class AlignCalcManager implements AlignCalcManagerI
     }
   }
 
-  @Override
-  public boolean alreadyDoing(AlignCalcWorkerI worker)
-  {
-    synchronized (inProgress)
-    {
-      return inProgress.containsKey(worker.getClass());
-    }
-  }
-
   /*
    * (non-Javadoc)
    * 
@@ -108,52 +124,30 @@ public class AlignCalcManager implements AlignCalcManagerI
     }
   }
 
-  // TODO make into api method if needed ?
-  public int numberLive(AlignCalcWorkerI worker)
-  {
-    synchronized (updating)
-    {
-      List<AlignCalcWorkerI> upd = updating.get(worker.getClass());
-      if (upd == null)
-      {
-        return 0;
-      }
-      ;
-      return upd.size();
-    }
-  }
-
   @Override
   public boolean notifyWorking(AlignCalcWorkerI worker)
   {
     synchronized (inProgress)
     {
-      // TODO: decide if we should throw exceptions here if multiple workers
-      // start to work
-      if (inProgress.get(worker.getClass()) != null)
+      if (inProgress.contains(worker))
       {
-        if (false)
-        {
-          System.err
-                  .println("Warning: Multiple workers are running of type "
-                          + worker.getClass());
-        }
-        return false;
+        return false; // worker is already working, so ask caller to wait around
+      }
+      else
+      {
+        inProgress.add(worker);
       }
-      inProgress.put(worker.getClass(), worker);
     }
     return true;
   }
 
-  private final HashSet<AlignCalcWorkerI> canUpdate = new HashSet<AlignCalcWorkerI>();
-
   @Override
   public void workerComplete(AlignCalcWorkerI worker)
   {
     synchronized (inProgress)
     {
-      // System.err.println("Worker "+worker.getClass()+" marked as complete.");
-      inProgress.remove(worker.getClass());
+      // System.err.println("Worker " + worker + " marked as complete.");
+      inProgress.remove(worker);
       List<AlignCalcWorkerI> upd = updating.get(worker.getClass());
       if (upd != null)
       {
@@ -167,7 +161,7 @@ public class AlignCalcManager implements AlignCalcManagerI
   }
 
   @Override
-  public void workerCannotRun(AlignCalcWorkerI worker)
+  public void disableWorker(AlignCalcWorkerI worker)
   {
     synchronized (blackList)
     {
@@ -175,22 +169,24 @@ public class AlignCalcManager implements AlignCalcManagerI
     }
   }
 
-  public boolean isBlackListed(Class workerType)
+  @Override
+  public boolean isDisabled(AlignCalcWorkerI worker)
   {
     synchronized (blackList)
     {
-      return blackList.contains(workerType);
+      return blackList.contains(worker.getClass());
     }
   }
 
   @Override
   public void startWorker(AlignCalcWorkerI worker)
   {
-    // System.err.println("Starting "+worker.getClass());
-    // new Exception("").printStackTrace();
-    Thread tw = new Thread(worker);
-    tw.setName(worker.getClass().toString());
-    tw.start();
+    if (!isDisabled(worker))
+    {
+      Thread tw = new Thread(worker);
+      tw.setName(worker.getClass().toString());
+      tw.start();
+    }
   }
 
   @Override
@@ -199,7 +195,7 @@ public class AlignCalcManager implements AlignCalcManagerI
     synchronized (inProgress)
     {// System.err.println("isWorking : worker "+(worker!=null ?
      // worker.getClass():"null")+ " "+hashCode());
-      return worker != null && inProgress.get(worker.getClass()) == worker;
+      return worker != null && inProgress.contains(worker);
     }
   }
 
@@ -243,7 +239,7 @@ public class AlignCalcManager implements AlignCalcManagerI
   {
     synchronized (inProgress)
     {
-      for (AlignCalcWorkerI worker : inProgress.values())
+      for (AlignCalcWorkerI worker : inProgress)
       {
         if (worker.involves(alignmentAnnotation))
         {
@@ -268,7 +264,8 @@ public class AlignCalcManager implements AlignCalcManagerI
   }
 
   @Override
-  public void updateAnnotationFor(Class workerClass)
+  public void updateAnnotationFor(
+          Class<? extends AlignCalcWorkerI> workerClass)
   {
 
     AlignCalcWorkerI[] workers;
@@ -287,62 +284,35 @@ public class AlignCalcManager implements AlignCalcManagerI
 
   @Override
   public List<AlignCalcWorkerI> getRegisteredWorkersOfClass(
-          Class workerClass)
+          Class<? extends AlignCalcWorkerI> workerClass)
   {
     List<AlignCalcWorkerI> workingClass = new ArrayList<AlignCalcWorkerI>();
-    AlignCalcWorkerI[] workers;
     synchronized (canUpdate)
     {
-      workers = canUpdate.toArray(new AlignCalcWorkerI[canUpdate.size()]);
-    }
-    for (AlignCalcWorkerI worker : workers)
-    {
-      if (workerClass.equals(worker.getClass()))
+      for (AlignCalcWorkerI worker : canUpdate)
       {
-        workingClass.add(worker);
+        if (workerClass.equals(worker.getClass()))
+        {
+          workingClass.add(worker);
+        }
       }
     }
     return (workingClass.size() == 0) ? null : workingClass;
   }
 
   @Override
-  public boolean startRegisteredWorkersOfClass(Class workerClass)
-  {
-    List<AlignCalcWorkerI> workers = getRegisteredWorkersOfClass(workerClass);
-    if (workers == null)
-    {
-      return false;
-    }
-    for (AlignCalcWorkerI worker : workers)
-    {
-      if (!isPending(worker))
-      {
-        startWorker(worker);
-      }
-      else
-      {
-        System.err.println("Pending exists for " + workerClass);
-      }
-    }
-    return true;
-  }
-
-  @Override
-  public void workerMayRun(AlignCalcWorkerI worker)
+  public void enableWorker(AlignCalcWorkerI worker)
   {
     synchronized (blackList)
     {
-      if (blackList.contains(worker.getClass()))
-      {
-        blackList.remove(worker.getClass());
-      }
+      blackList.remove(worker.getClass());
     }
   }
 
   @Override
-  public void removeRegisteredWorkersOfClass(Class typeToRemove)
+  public void removeRegisteredWorkersOfClass(
+          Class<? extends AlignCalcWorkerI> typeToRemove)
   {
-    List<AlignCalcWorkerI> workers = getRegisteredWorkersOfClass(typeToRemove);
     List<AlignCalcWorkerI> removable = new ArrayList<AlignCalcWorkerI>();
     Set<AlignCalcWorkerI> toremovannot = new HashSet<AlignCalcWorkerI>();
     synchronized (restartable)
@@ -382,4 +352,48 @@ public class AlignCalcManager implements AlignCalcManagerI
      * else { System.err.println("Pending exists for " + workerClass); } }
      */
   }
+
+  /**
+   * Deletes the worker that update the given annotation, provided it is marked
+   * as deletable.
+   */
+  @Override
+  public void removeWorkerForAnnotation(AlignmentAnnotation ann)
+  {
+    /*
+     * first just find those to remove (to avoid
+     * ConcurrentModificationException)
+     */
+    List<AlignCalcWorkerI> toRemove = new ArrayList<AlignCalcWorkerI>();
+    for (AlignCalcWorkerI worker : restartable)
+    {
+      if (worker.involves(ann))
+      {
+        if (worker.isDeletable())
+        {
+          toRemove.add(worker);
+        }
+      }
+    }
+
+    /*
+     * remove all references to deleted workers so any references 
+     * they hold to annotation data can be garbage collected 
+     */
+    for (AlignCalcWorkerI worker : toRemove)
+    {
+      restartable.remove(worker);
+      blackList.remove(worker.getClass());
+      inProgress.remove(worker);
+      canUpdate.remove(worker);
+      synchronized (updating)
+      {
+        List<AlignCalcWorkerI> upd = updating.get(worker.getClass());
+        if (upd != null)
+        {
+          upd.remove(worker);
+        }
+      }
+    }
+  }
 }
index 48e3604..771c492 100644 (file)
@@ -26,6 +26,7 @@ import jalview.api.AlignViewportI;
 import jalview.api.AlignmentViewPanel;
 import jalview.datamodel.AlignmentAnnotation;
 import jalview.datamodel.AlignmentI;
+import jalview.datamodel.Annotation;
 
 import java.util.List;
 
@@ -97,4 +98,39 @@ public abstract class AlignCalcWorker implements AlignCalcWorkerI
   // TODO: allow GUI to query workers associated with annotation to add items to
   // annotation label panel popup menu
 
+  @Override
+  public boolean isDeletable()
+  {
+    return false;
+  }
+
+  /**
+   * Calculate min and max values of annotations and set as graphMin, graphMax
+   * on the AlignmentAnnotation. This is needed because otherwise, well, bad
+   * things happen.
+   * 
+   * @param ann
+   * @param anns
+   */
+  protected void setGraphMinMax(AlignmentAnnotation ann, Annotation[] anns)
+  {
+    // TODO feels like this belongs inside AlignmentAnnotation!
+    float max = Float.MIN_VALUE;
+    float min = Float.MAX_VALUE;
+    boolean set = false;
+    for (Annotation a : anns) {
+      if (a != null) {
+        set = true;
+        float val = a.value;
+        max = Math.max(max, val);
+        min = Math.min(min, val);
+      }
+    }
+    if (set)
+    {
+      ann.graphMin = min;
+      ann.graphMax = max;
+    }
+  }
+
 }
index 520b232..f804a19 100644 (file)
@@ -1,5 +1,7 @@
 package jalview.workers;
 
+import jalview.api.AlignViewportI;
+import jalview.api.AlignmentViewPanel;
 import jalview.bin.Jalview;
 import jalview.datamodel.AlignmentAnnotation;
 import jalview.datamodel.Annotation;
@@ -12,9 +14,9 @@ import java.awt.Color;
  * such as Groovy) to 'register and forget' an alignment annotation calculator. <br>
  * Currently supports two flavours of calculator:
  * <ul>
- * <li>a 'feature counter' which can count any desired property derivable from
+ * <li>a simple 'feature counter' which counts any desired score derivable from
  * residue value and any sequence features at each position of the alignment</li>
- * <li>a 'general purpose' calculator which computes one more complete
+ * <li>a 'general purpose' calculator which computes one or more complete
  * AlignmentAnnotation objects</li>
  * </ul>
  */
@@ -28,9 +30,13 @@ public class AlignmentAnnotationFactory
    */
   public static void newCalculator(FeatureCounterI counter)
   {
-    if (Jalview.getCurrentAlignFrame() != null)
+    // TODO need an interface for AlignFrame by which to access
+    // its AlignViewportI and AlignmentViewPanel
+    AlignFrame currentAlignFrame = Jalview.getCurrentAlignFrame() ;
+    if (currentAlignFrame != null)
     {
-      newCalculator(Jalview.getCurrentAlignFrame(), counter);
+      newCalculator(currentAlignFrame.getViewport(), currentAlignFrame
+              .getAlignPanels().get(0), counter);
     }
     else
     {
@@ -42,14 +48,15 @@ public class AlignmentAnnotationFactory
   /**
    * Constructs and registers a new alignment annotation worker
    * 
-   * @param af
-   *          the AlignFrame for which the annotation is to be calculated
+   * @param viewport
+   * @param panel
    * @param counter
    *          provider of feature counts per alignment position
    */
-  public static void newCalculator(AlignFrame af, FeatureCounterI counter)
+  public static void newCalculator(AlignViewportI viewport,
+          AlignmentViewPanel panel, FeatureCounterI counter)
   {
-    new ColumnCounterWorker(af, counter);
+    new ColumnCounterWorker(viewport, panel, counter);
   }
 
   /**
@@ -60,9 +67,13 @@ public class AlignmentAnnotationFactory
    */
   public static void newCalculator(AnnotationProviderI calculator)
   {
-    if (Jalview.getCurrentAlignFrame() != null)
+    // TODO need an interface for AlignFrame by which to access
+    // its AlignViewportI and AlignmentViewPanel
+    AlignFrame currentAlignFrame = Jalview.getCurrentAlignFrame() ;
+    if (currentAlignFrame != null)
     {
-      newCalculator(Jalview.getCurrentAlignFrame(), calculator);
+      newCalculator(currentAlignFrame.getViewport(), currentAlignFrame
+              .getAlignPanels().get(0), calculator);
     }
     else
     {
@@ -74,15 +85,16 @@ public class AlignmentAnnotationFactory
   /**
    * Constructs and registers a new alignment annotation worker
    * 
-   * @param af
-   *          the AlignFrame for which the annotation is to be calculated
+   * @param viewport
+   * @param panel
    * @param calculator
    *          provider of AlignmentAnnotation for the alignment
    */
-  public static void newCalculator(AlignFrame af,
+  public static void newCalculator(AlignViewportI viewport,
+          AlignmentViewPanel panel,
           AnnotationProviderI calculator)
   {
-    new AnnotationWorker(af, calculator);
+    new AnnotationWorker(viewport, panel, calculator);
   }
 
   /**
index 653ff04..bd24461 100644 (file)
@@ -1,8 +1,8 @@
 package jalview.workers;
 
+import jalview.api.FeatureRenderer;
 import jalview.datamodel.AlignmentAnnotation;
 import jalview.datamodel.AlignmentI;
-import jalview.gui.FeatureRenderer;
 
 import java.util.List;
 
index fbf7531..4d81307 100644 (file)
  */
 package jalview.workers;
 
+import jalview.api.AlignViewportI;
+import jalview.api.AlignmentViewPanel;
 import jalview.datamodel.AlignmentAnnotation;
 import jalview.datamodel.AlignmentI;
-import jalview.gui.AlignFrame;
-import jalview.gui.AlignmentPanel;
-import jalview.gui.FeatureRenderer;
+import jalview.renderer.seqfeatures.FeatureRenderer;
 
 import java.util.ArrayList;
 import java.util.List;
 
 /**
  * A class to create and update one or more alignment annotations, given a
- * 'calculator'.
- * 
+ * 'calculator'. Intended to support a 'plug-in' annotation worker which
+ * implements the AnnotationProviderI interface.
  */
 class AnnotationWorker extends AlignCalcWorker
 {
@@ -47,9 +47,10 @@ class AnnotationWorker extends AlignCalcWorker
    * @param af
    * @param counter
    */
-  public AnnotationWorker(AlignFrame af, AnnotationProviderI counter)
+  public AnnotationWorker(AlignViewportI viewport,
+          AlignmentViewPanel panel, AnnotationProviderI counter)
   {
-    super(af.getViewport(), af.alignPanel);
+    super(viewport, panel);
     ourAnnots = new ArrayList<AlignmentAnnotation>();
     this.counter = counter;
     calcMan.registerWorker(this);
@@ -78,20 +79,29 @@ class AnnotationWorker extends AlignCalcWorker
         return;
       }
 
-      removeAnnotations();
+      // removeAnnotation();
       AlignmentI alignment = alignViewport.getAlignment();
       if (alignment != null)
       {
         try
         {
           List<AlignmentAnnotation> anns = counter.calculateAnnotation(
-                  alignment, new FeatureRenderer((AlignmentPanel) ap));
+                  alignment, new FeatureRenderer(alignViewport));
           for (AlignmentAnnotation ann : anns)
           {
-            ann.showAllColLabels = true;
-            ann.graph = AlignmentAnnotation.BAR_GRAPH;
-            ourAnnots.add(ann);
-            alignment.addAnnotation(ann);
+            AlignmentAnnotation theAnn = alignment.findOrCreateAnnotation(
+                    ann.label, ann.description, false, null, null);
+            theAnn.showAllColLabels = true;
+            theAnn.graph = AlignmentAnnotation.BAR_GRAPH;
+            theAnn.scaleColLabel = true;
+            theAnn.annotations = ann.annotations;
+            setGraphMinMax(theAnn, theAnn.annotations);
+            theAnn.validateRangeAndDisplay();
+            if (!ourAnnots.contains(theAnn))
+            {
+              ourAnnots.add(theAnn);
+            }
+            // alignment.addAnnotation(ann);
           }
         } catch (IndexOutOfBoundsException x)
         {
@@ -102,7 +112,7 @@ class AnnotationWorker extends AlignCalcWorker
     } catch (OutOfMemoryError error)
     {
       ap.raiseOOMWarning("calculating annotations", error);
-      calcMan.workerCannotRun(this);
+      calcMan.disableWorker(this);
     } finally
     {
       calcMan.workerComplete(this);
@@ -113,24 +123,22 @@ class AnnotationWorker extends AlignCalcWorker
       ap.adjustAnnotationHeight();
       ap.paintAlignment(true);
     }
-
   }
 
-  /**
-   * Remove all our annotations before re-calculating them
-   */
-  void removeAnnotations()
+  @Override
+  public void updateAnnotation()
   {
-    for (AlignmentAnnotation ann : ourAnnots)
-    {
-      alignViewport.getAlignment().deleteAnnotation(ann);
-    }
-    ourAnnots.clear();
+    // do nothing
   }
 
+  /**
+   * Answers true to indicate that if this worker's annotation is deleted from
+   * the display, the worker should also be removed. This prevents it running
+   * and recreating the annotation when the alignment changes.
+   */
   @Override
-  public void updateAnnotation()
+  public boolean isDeletable()
   {
-    // do nothing
+    return true;
   }
 }
index 6f4a4f3..2f73cb5 100644 (file)
  */
 package jalview.workers;
 
+import jalview.api.AlignViewportI;
+import jalview.api.AlignmentViewPanel;
 import jalview.datamodel.AlignmentAnnotation;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.Annotation;
 import jalview.datamodel.SequenceFeature;
 import jalview.datamodel.SequenceI;
-import jalview.gui.AlignFrame;
-import jalview.gui.AlignmentPanel;
-import jalview.gui.FeatureRenderer;
+import jalview.renderer.seqfeatures.FeatureRenderer;
 import jalview.util.ColorUtils;
 import jalview.util.Comparison;
 
@@ -53,9 +53,10 @@ class ColumnCounterWorker extends AlignCalcWorker
    * @param af
    * @param counter
    */
-  public ColumnCounterWorker(AlignFrame af, FeatureCounterI counter)
+  public ColumnCounterWorker(AlignViewportI viewport,
+          AlignmentViewPanel panel, FeatureCounterI counter)
   {
-    super(af.getViewport(), af.alignPanel);
+    super(viewport, panel);
     ourAnnots = new ArrayList<AlignmentAnnotation>();
     this.counter = counter;
     calcMan.registerWorker(this);
@@ -88,7 +89,6 @@ class ColumnCounterWorker extends AlignCalcWorker
         return;
       }
 
-      removeAnnotation();
       if (alignViewport.getAlignment() != null)
       {
         try
@@ -103,7 +103,7 @@ class ColumnCounterWorker extends AlignCalcWorker
     } catch (OutOfMemoryError error)
     {
       ap.raiseOOMWarning("calculating feature counts", error);
-      calcMan.workerCannotRun(this);
+      calcMan.disableWorker(this);
     } finally
     {
       calcMan.workerComplete(this);
@@ -123,7 +123,7 @@ class ColumnCounterWorker extends AlignCalcWorker
    */
   void computeAnnotations()
   {
-    FeatureRenderer fr = new FeatureRenderer((AlignmentPanel) ap);
+    FeatureRenderer fr = new FeatureRenderer(alignViewport);
     // TODO use the commented out code once JAL-2075 is fixed
     // to get adequate performance on genomic length sequence
     AlignmentI alignment = alignViewport.getAlignment();
@@ -158,20 +158,29 @@ class ColumnCounterWorker extends AlignCalcWorker
       {
         Color color = ColorUtils.getGraduatedColour(count, 0, Color.cyan,
                 max, Color.blue);
-        anns[i] = new Annotation(String.valueOf(count),
-                String.valueOf(count), '0', count, color);
+        String str = String.valueOf(count);
+        anns[i] = new Annotation(str, str, '0', count, color);
       }
     }
 
     /*
-     * construct the annotation, save it and add it to the displayed alignment
+     * construct or update the annotation
      */
-    AlignmentAnnotation ann = new AlignmentAnnotation(counter.getName(),
-            counter.getDescription(), anns);
+    AlignmentAnnotation ann = alignViewport.getAlignment()
+            .findOrCreateAnnotation(counter.getName(),
+                    counter.getDescription(), false, null,
+                    null);
+    ann.description = counter.getDescription();
     ann.showAllColLabels = true;
+    ann.scaleColLabel = true;
     ann.graph = AlignmentAnnotation.BAR_GRAPH;
-    ourAnnots.add(ann);
-    alignViewport.getAlignment().addAnnotation(ann);
+    ann.annotations = anns;
+    setGraphMinMax(ann, anns);
+    ann.validateRangeAndDisplay();
+    if (!ourAnnots.contains(ann))
+    {
+      ourAnnots.add(ann);
+    }
   }
 
   /**
@@ -222,4 +231,15 @@ class ColumnCounterWorker extends AlignCalcWorker
   {
     // do nothing
   }
+
+  /**
+   * Answers true to indicate that if this worker's annotation is deleted from
+   * the display, the worker should also be removed. This prevents it running
+   * and recreating the annotation when the alignment changes.
+   */
+  @Override
+  public boolean isDeletable()
+  {
+    return true;
+  }
 }
index 14e2a31..5f0ec84 100644 (file)
@@ -96,7 +96,7 @@ public class ConsensusThread extends AlignCalcWorker
       }
     } catch (OutOfMemoryError error)
     {
-      calcMan.workerCannotRun(this);
+      calcMan.disableWorker(this);
       ap.raiseOOMWarning("calculating consensus", error);
     } finally
     {
index 1075e4d..5c303fd 100644 (file)
@@ -108,7 +108,7 @@ public class ConservationThread extends AlignCalcWorker
     } catch (OutOfMemoryError error)
     {
       ap.raiseOOMWarning("calculating conservation", error);
-      calcMan.workerCannotRun(this);
+      calcMan.disableWorker(this);
       // alignViewport.conservation = null;
       // this.alignViewport.quality = null;
 
index 4249112..5ed2885 100644 (file)
@@ -129,7 +129,7 @@ public class StrucConsensusThread extends AlignCalcWorker
       updateResultAnnotation(true);
     } catch (OutOfMemoryError error)
     {
-      calcMan.workerCannotRun(this);
+      calcMan.disableWorker(this);
 
       // consensus = null;
       // hconsensus = null;
index b158448..2ef5256 100644 (file)
@@ -31,9 +31,8 @@ import jalview.gui.WebserviceInfo;
 import jalview.util.MessageManager;
 import jalview.viewmodel.seqfeatures.FeatureRendererSettings;
 
-import java.util.LinkedHashSet;
+import java.util.ArrayList;
 import java.util.List;
-import java.util.Set;
 
 public abstract class AWSThread extends Thread
 {
@@ -61,7 +60,7 @@ public abstract class AWSThread extends Thread
   /**
    * dataset sequence relationships to be propagated onto new results
    */
-  protected Set<AlignedCodonFrame> codonframe = null;
+  protected List<AlignedCodonFrame> codonframe = null;
 
   /**
    * are there jobs still running in this thread.
@@ -384,7 +383,7 @@ public abstract class AWSThread extends Thread
               .getCodonFrames();
       if (cf != null)
       {
-        codonframe = new LinkedHashSet<AlignedCodonFrame>();
+        codonframe = new ArrayList<AlignedCodonFrame>();
         codonframe.addAll(cf);
       }
     }
index 65179a2..37946b1 100644 (file)
@@ -27,10 +27,8 @@ import jalview.ws.dbsources.EmblSource;
 import jalview.ws.dbsources.Pdb;
 import jalview.ws.dbsources.PfamFull;
 import jalview.ws.dbsources.PfamSeed;
-import jalview.ws.dbsources.RfamFull;
 import jalview.ws.dbsources.RfamSeed;
 import jalview.ws.dbsources.Uniprot;
-import jalview.ws.dbsources.UniprotName;
 import jalview.ws.dbsources.das.api.jalviewSourceI;
 import jalview.ws.seqfetcher.ASequenceFetcher;
 import jalview.ws.seqfetcher.DbSourceProxy;
@@ -62,11 +60,11 @@ public class SequenceFetcher extends ASequenceFetcher
     addDBRefSourceImpl(EmblSource.class);
     addDBRefSourceImpl(EmblCdsSource.class);
     addDBRefSourceImpl(Uniprot.class);
-    addDBRefSourceImpl(UniprotName.class);
     addDBRefSourceImpl(Pdb.class);
     addDBRefSourceImpl(PfamFull.class);
     addDBRefSourceImpl(PfamSeed.class);
     addDBRefSourceImpl(RfamSeed.class);
+
     if (addDas)
     {
       registerDasSequenceSources();
diff --git a/src/jalview/ws/SequenceFetcherFactory.java b/src/jalview/ws/SequenceFetcherFactory.java
new file mode 100644 (file)
index 0000000..2b8f364
--- /dev/null
@@ -0,0 +1,32 @@
+package jalview.ws;
+
+import jalview.ws.seqfetcher.ASequenceFetcher;
+
+public class SequenceFetcherFactory
+{
+
+  private static SequenceFetcher instance;
+
+  /**
+   * Returns a new SequenceFetcher object, or a mock object if one has been set
+   * 
+   * @return
+   */
+  public static ASequenceFetcher getSequenceFetcher()
+  {
+    return instance == null ? new SequenceFetcher() : instance;
+  }
+
+  /**
+   * Set the instance object to use (intended for unit testing with mock
+   * objects).
+   * 
+   * Be sure to reset to null in the tearDown method of any tests!
+   * 
+   * @param sf
+   */
+  public static void setSequenceFetcher(SequenceFetcher sf)
+  {
+    instance = sf;
+  }
+}
index 6f266dd..757ab83 100644 (file)
@@ -27,7 +27,11 @@ import jalview.datamodel.AlignmentI;
 import jalview.datamodel.DBRefEntry;
 import jalview.datamodel.DBRefSource;
 import jalview.datamodel.PDBEntry;
+import jalview.datamodel.PDBEntry.Type;
 import jalview.datamodel.SequenceI;
+import jalview.io.DataSourceType;
+import jalview.io.FileFormat;
+import jalview.io.FileFormatI;
 import jalview.io.FormatAdapter;
 import jalview.io.PDBFeatureSettings;
 import jalview.structure.StructureImportSettings;
@@ -132,13 +136,11 @@ public class Pdb extends EbiFileRetrievedProxy
       stopQuery();
       return null;
     }
-    String ext = StructureImportSettings.getCurrentDefaultFormat()
-            .equalsIgnoreCase("mmcif") ? ".cif"
-            : ".xml";
+    Type pdbFileFormat = StructureImportSettings
+            .getDefaultStructureFileFormat();
+    String ext = "." + pdbFileFormat.getExtension();
     EBIFetchClient ebi = new EBIFetchClient();
-    file = ebi.fetchDataAsFile("pdb:" + id,
-            StructureImportSettings.getCurrentDefaultFormat().toLowerCase(),
-            ext)
+    file = ebi.fetchDataAsFile("pdb:" + id, pdbFileFormat.getFormat(), ext)
             .getAbsolutePath();
     stopQuery();
     if (file == null)
@@ -147,10 +149,11 @@ public class Pdb extends EbiFileRetrievedProxy
     }
     try
     {
-
+      // convert Type.PDB/MMCIF to FileFormat.PDB/MMCIF
+      // todo get rid of Type?
+      FileFormatI fileFormat = FileFormat.valueOf(pdbFileFormat.toString());
       pdbAlignment = new FormatAdapter().readFile(file,
-              jalview.io.DataSourceType.FILE,
-              StructureImportSettings.getCurrentDefaultFormat());
+              DataSourceType.FILE, fileFormat);
       if (pdbAlignment != null)
       {
         List<SequenceI> toremove = new ArrayList<SequenceI>();
index 8c30c69..bae0357 100644 (file)
@@ -21,6 +21,7 @@
 package jalview.ws.jws1;
 
 import jalview.datamodel.AlignmentI;
+import jalview.io.FileFormat;
 import jalview.io.FileParse;
 import jalview.io.FormatAdapter;
 import jalview.io.InputStreamParser;
@@ -86,7 +87,8 @@ public class Annotate3D
       while (r.hasNext())
       {
         FileParse fp = new InputStreamParser(r.next(), source.getDataName());
-        AlignmentI nal = new FormatAdapter().readFromFile(fp, "RNAML");
+        AlignmentI nal = new FormatAdapter().readFromFile(fp,
+                FileFormat.Rnaml);
         if (al == null)
         {
           al = nal;
index bb4fc37..4e5cadc 100644 (file)
@@ -365,7 +365,7 @@ class JPredThread extends JWS1Thread implements WSClientI
         {
           msa = new vamsas.objects.simple.Msfalignment();
           PileUpfile pileup = new PileUpfile();
-          msa.setMsf(pileup.print(msf));
+          msa.setMsf(pileup.print(msf, true));
         }
       }
     }
index 95f5527..aad72b1 100644 (file)
@@ -20,7 +20,7 @@
  */
 package jalview.ws.jws1;
 
-import jalview.datamodel.Alignment;
+import jalview.datamodel.AlignmentI;
 import jalview.datamodel.AlignmentView;
 import jalview.gui.AlignFrame;
 import jalview.gui.Desktop;
@@ -34,7 +34,6 @@ import javax.swing.JMenu;
 import javax.swing.JMenuItem;
 import javax.swing.JOptionPane;
 
-import ext.vamsas.MuscleWS;
 import ext.vamsas.MuscleWSServiceLocator;
 import ext.vamsas.MuscleWSSoapBindingStub;
 import ext.vamsas.ServiceHandle;
@@ -72,7 +71,7 @@ public class MsaWSClient extends WS1Client
 
   public MsaWSClient(ext.vamsas.ServiceHandle sh, String altitle,
           jalview.datamodel.AlignmentView msa, boolean submitGaps,
-          boolean preserveOrder, Alignment seqdataset,
+          boolean preserveOrder, AlignmentI seqdataset,
           AlignFrame _alignFrame)
   {
     super();
@@ -109,7 +108,7 @@ public class MsaWSClient extends WS1Client
   }
 
   private void startMsaWSClient(String altitle, AlignmentView msa,
-          boolean submitGaps, boolean preserveOrder, Alignment seqdataset)
+          boolean submitGaps, boolean preserveOrder, AlignmentI seqdataset)
   {
     if (!locateWebService())
     {
@@ -159,7 +158,7 @@ public class MsaWSClient extends WS1Client
 
     try
     {
-      this.server = (MuscleWS) loc.getMuscleWS(new java.net.URL(WsURL));
+      this.server = loc.getMuscleWS(new java.net.URL(WsURL));
       ((MuscleWSSoapBindingStub) this.server).setTimeout(60000); // One minute
       // timeout
     } catch (Exception ex)
@@ -201,6 +200,7 @@ public class MsaWSClient extends WS1Client
     return (WebServiceName.indexOf("lustal") > -1); // cheat!
   }
 
+  @Override
   public void attachWSMenuEntry(JMenu msawsmenu,
           final ServiceHandle serviceHandle, final AlignFrame alignFrame)
   {
@@ -209,6 +209,7 @@ public class MsaWSClient extends WS1Client
     method.setToolTipText(WsURL);
     method.addActionListener(new ActionListener()
     {
+      @Override
       public void actionPerformed(ActionEvent e)
       {
         AlignmentView msa = alignFrame.gatherSequencesForAlignment();
@@ -228,6 +229,7 @@ public class MsaWSClient extends WS1Client
       methodR.setToolTipText(WsURL);
       methodR.addActionListener(new ActionListener()
       {
+        @Override
         public void actionPerformed(ActionEvent e)
         {
           AlignmentView msa = alignFrame.gatherSequencesForAlignment();
index be21de7..3fd7c5a 100644 (file)
@@ -23,6 +23,7 @@ package jalview.ws.jws1;
 import jalview.analysis.AlignSeq;
 import jalview.bin.Cache;
 import jalview.datamodel.Alignment;
+import jalview.datamodel.AlignmentI;
 import jalview.datamodel.AlignmentOrder;
 import jalview.datamodel.AlignmentView;
 import jalview.datamodel.ColumnSelection;
@@ -147,6 +148,7 @@ class MsaWSThread extends JWS1Thread implements WSClientI
      * 
      * @return true if getAlignment will return a valid alignment result.
      */
+    @Override
     public boolean hasResults()
     {
       if (subjobComplete && result != null && result.isFinished()
@@ -273,6 +275,7 @@ class MsaWSThread extends JWS1Thread implements WSClientI
      * 
      * @return boolean true if job can be submitted.
      */
+    @Override
     public boolean hasValidInput()
     {
       if (seqs.getSeqs() != null)
@@ -285,7 +288,7 @@ class MsaWSThread extends JWS1Thread implements WSClientI
 
   String alTitle; // name which will be used to form new alignment window.
 
-  Alignment dataset; // dataset to which the new alignment will be
+  AlignmentI dataset; // dataset to which the new alignment will be
 
   // associated.
 
@@ -327,7 +330,7 @@ class MsaWSThread extends JWS1Thread implements WSClientI
   MsaWSThread(ext.vamsas.MuscleWS server, String wsUrl,
           WebserviceInfo wsinfo, jalview.gui.AlignFrame alFrame,
           String wsname, String title, AlignmentView _msa, boolean subgaps,
-          boolean presorder, Alignment seqset)
+          boolean presorder, AlignmentI seqset)
   {
     this(server, wsUrl, wsinfo, alFrame, _msa, wsname, subgaps, presorder);
     OutputHeader = wsInfo.getProgressText();
@@ -359,11 +362,13 @@ class MsaWSThread extends JWS1Thread implements WSClientI
     }
   }
 
+  @Override
   public boolean isCancellable()
   {
     return true;
   }
 
+  @Override
   public void cancelJob()
   {
     if (!jobComplete && jobs != null)
@@ -430,11 +435,13 @@ class MsaWSThread extends JWS1Thread implements WSClientI
     }
   }
 
+  @Override
   public void pollJob(AWsJob job) throws Exception
   {
     ((MsaWSJob) job).result = server.getResult(((MsaWSJob) job).getJobId());
   }
 
+  @Override
   public void StartJob(AWsJob job)
   {
     if (!(job instanceof MsaWSJob))
@@ -521,6 +528,7 @@ class MsaWSThread extends JWS1Thread implements WSClientI
     return msa;
   }
 
+  @Override
   public void parseResult()
   {
     int results = 0; // number of result sets received
@@ -571,6 +579,7 @@ class MsaWSThread extends JWS1Thread implements WSClientI
       wsInfo.showResultsNewFrame
               .addActionListener(new java.awt.event.ActionListener()
               {
+                @Override
                 public void actionPerformed(java.awt.event.ActionEvent evt)
                 {
                   displayResults(true);
@@ -579,6 +588,7 @@ class MsaWSThread extends JWS1Thread implements WSClientI
       wsInfo.mergeResults
               .addActionListener(new java.awt.event.ActionListener()
               {
+                @Override
                 public void actionPerformed(java.awt.event.ActionEvent evt)
                 {
                   displayResults(false);
@@ -661,7 +671,7 @@ class MsaWSThread extends JWS1Thread implements WSClientI
             while (j < l)
             {
               if (((AlignmentOrder) alorders.get(i))
-                      .equals(((AlignmentOrder) alorders.get(j))))
+                      .equals((alorders.get(j))))
               {
                 alorders.remove(j);
                 l--;
@@ -704,6 +714,7 @@ class MsaWSThread extends JWS1Thread implements WSClientI
     }
   }
 
+  @Override
   public boolean canMergeResults()
   {
     return false;
index d731ced..2d83bf9 100644 (file)
@@ -20,7 +20,7 @@
  */
 package jalview.ws.jws1;
 
-import jalview.datamodel.Alignment;
+import jalview.datamodel.AlignmentI;
 import jalview.datamodel.AlignmentView;
 import jalview.gui.AlignFrame;
 import jalview.gui.Desktop;
@@ -39,7 +39,6 @@ import javax.swing.JMenu;
 import javax.swing.JMenuItem;
 import javax.swing.JOptionPane;
 
-import ext.vamsas.SeqSearchI;
 import ext.vamsas.SeqSearchServiceLocator;
 import ext.vamsas.SeqSearchServiceSoapBindingStub;
 import ext.vamsas.ServiceHandle;
@@ -77,7 +76,7 @@ public class SeqSearchWSClient extends WS1Client
 
   public SeqSearchWSClient(ext.vamsas.ServiceHandle sh, String altitle,
           jalview.datamodel.AlignmentView msa, String db,
-          Alignment seqdataset, AlignFrame _alignFrame)
+          AlignmentI seqdataset, AlignFrame _alignFrame)
   {
     super();
     alignFrame = _alignFrame;
@@ -128,7 +127,7 @@ public class SeqSearchWSClient extends WS1Client
   }
 
   private void startSeqSearchClient(String altitle, AlignmentView msa,
-          String db, Alignment seqdataset)
+          String db, AlignmentI seqdataset)
   {
     if (!locateWebService())
     {
@@ -173,7 +172,7 @@ public class SeqSearchWSClient extends WS1Client
 
     try
     {
-      this.server = (SeqSearchI) loc.getSeqSearchService(new java.net.URL(
+      this.server = loc.getSeqSearchService(new java.net.URL(
               WsURL));
       ((SeqSearchServiceSoapBindingStub) this.server).setTimeout(60000); // One
       // minute
@@ -241,6 +240,7 @@ public class SeqSearchWSClient extends WS1Client
     return dbs;
   }
 
+  @Override
   public void attachWSMenuEntry(JMenu wsmenu, final ServiceHandle sh,
           final AlignFrame af)
   {
@@ -281,6 +281,7 @@ public class SeqSearchWSClient extends WS1Client
     method.setToolTipText(sh.getEndpointURL());
     method.addActionListener(new ActionListener()
     {
+      @Override
       public void actionPerformed(ActionEvent e)
       {
         // use same input gatherer as for secondary structure prediction
@@ -305,6 +306,7 @@ public class SeqSearchWSClient extends WS1Client
       final String searchdb = dbs[db];
       method.addActionListener(new ActionListener()
       {
+        @Override
         public void actionPerformed(ActionEvent e)
         {
           AlignmentView msa = af.gatherSeqOrMsaForSecStrPrediction();
index 0f7904a..b14917e 100644 (file)
@@ -24,6 +24,7 @@ import jalview.analysis.AlignSeq;
 import jalview.api.FeatureColourI;
 import jalview.bin.Cache;
 import jalview.datamodel.Alignment;
+import jalview.datamodel.AlignmentI;
 import jalview.datamodel.AlignmentView;
 import jalview.datamodel.SequenceI;
 import jalview.gui.AlignFrame;
@@ -172,7 +173,7 @@ class SeqSearchWSThread extends JWS1Thread implements WSClientI
      * 
      * @return null or { Alignment(+features and annotation), NewickFile)}
      */
-    public Object[] getAlignment(Alignment dataset,
+    public Object[] getAlignment(AlignmentI dataset,
             Map<String, FeatureColourI> featureColours)
     {
 
@@ -303,7 +304,7 @@ class SeqSearchWSThread extends JWS1Thread implements WSClientI
 
   String alTitle; // name which will be used to form new alignment window.
 
-  Alignment dataset; // dataset to which the new alignment will be
+  AlignmentI dataset; // dataset to which the new alignment will be
 
   // associated.
 
@@ -345,7 +346,7 @@ class SeqSearchWSThread extends JWS1Thread implements WSClientI
   SeqSearchWSThread(ext.vamsas.SeqSearchI server, String wsUrl,
           WebserviceInfo wsinfo, jalview.gui.AlignFrame alFrame,
           String wsname, String title, AlignmentView _msa, String db,
-          Alignment seqset)
+          AlignmentI seqset)
   {
     this(server, wsUrl, wsinfo, alFrame, _msa, wsname, db);
     OutputHeader = wsInfo.getProgressText();
index 897aa1e..b33df0c 100644 (file)
@@ -331,23 +331,23 @@ public abstract class AbstractJabaCalcWorker extends AlignCalcWorker
       System.err.println("submission error with " + getServiceActionText()
               + " :");
       x.printStackTrace();
-      calcMan.workerCannotRun(this);
+      calcMan.disableWorker(this);
     } catch (ResultNotAvailableException x)
     {
       System.err.println("collection error:\nJob ID: " + rslt);
       x.printStackTrace();
-      calcMan.workerCannotRun(this);
+      calcMan.disableWorker(this);
 
     } catch (OutOfMemoryError error)
     {
-      calcMan.workerCannotRun(this);
+      calcMan.disableWorker(this);
 
       // consensus = null;
       // hconsensus = null;
       ap.raiseOOMWarning(getServiceActionText(), error);
     } catch (Exception x)
     {
-      calcMan.workerCannotRun(this);
+      calcMan.disableWorker(this);
 
       // consensus = null;
       // hconsensus = null;
index c83ef0f..758d941 100644 (file)
@@ -20,7 +20,7 @@
  */
 package jalview.ws.jws2;
 
-import jalview.datamodel.Alignment;
+import jalview.datamodel.AlignmentI;
 import jalview.datamodel.AlignmentView;
 import jalview.gui.AlignFrame;
 import jalview.gui.Desktop;
@@ -58,7 +58,7 @@ public class MsaWSClient extends Jws2Client
 
   public MsaWSClient(Jws2Instance sh, String altitle,
           jalview.datamodel.AlignmentView msa, boolean submitGaps,
-          boolean preserveOrder, Alignment seqdataset,
+          boolean preserveOrder, AlignmentI seqdataset,
           AlignFrame _alignFrame)
   {
     this(sh, null, null, false, altitle, msa, submitGaps, preserveOrder,
@@ -68,7 +68,7 @@ public class MsaWSClient extends Jws2Client
 
   public MsaWSClient(Jws2Instance sh, WsParamSetI preset, String altitle,
           jalview.datamodel.AlignmentView msa, boolean submitGaps,
-          boolean preserveOrder, Alignment seqdataset,
+          boolean preserveOrder, AlignmentI seqdataset,
           AlignFrame _alignFrame)
   {
     this(sh, preset, null, false, altitle, msa, submitGaps, preserveOrder,
@@ -95,7 +95,7 @@ public class MsaWSClient extends Jws2Client
   public MsaWSClient(Jws2Instance sh, WsParamSetI preset,
           List<Argument> arguments, boolean editParams, String altitle,
           jalview.datamodel.AlignmentView msa, boolean submitGaps,
-          boolean preserveOrder, Alignment seqdataset,
+          boolean preserveOrder, AlignmentI seqdataset,
           AlignFrame _alignFrame)
   {
     super(_alignFrame, preset, arguments);
@@ -138,7 +138,7 @@ public class MsaWSClient extends Jws2Client
   }
 
   private void startMsaWSClient(String altitle, AlignmentView msa,
-          boolean submitGaps, boolean preserveOrder, Alignment seqdataset)
+          boolean submitGaps, boolean preserveOrder, AlignmentI seqdataset)
   {
     // if (!locateWebService())
     // {
index e2f3a7c..e425624 100644 (file)
@@ -176,6 +176,7 @@ class MsaWSThread extends AWS2Thread implements WSClientI
      * 
      * @return true if getAlignment will return a valid alignment result.
      */
+    @Override
     public boolean hasResults()
     {
       if (subjobComplete
@@ -316,6 +317,7 @@ class MsaWSThread extends AWS2Thread implements WSClientI
      * 
      * @return boolean true if job can be submitted.
      */
+    @Override
     public boolean hasValidInput()
     {
       // TODO: get attributes for this MsaWS instance to check if it can do two
@@ -436,7 +438,7 @@ class MsaWSThread extends AWS2Thread implements WSClientI
 
   String alTitle; // name which will be used to form new alignment window.
 
-  Alignment dataset; // dataset to which the new alignment will be
+  AlignmentI dataset; // dataset to which the new alignment will be
 
   // associated.
 
@@ -479,7 +481,7 @@ class MsaWSThread extends AWS2Thread implements WSClientI
           String wsUrl, WebserviceInfo wsinfo,
           jalview.gui.AlignFrame alFrame, String wsname, String title,
           AlignmentView _msa, boolean subgaps, boolean presorder,
-          Alignment seqset)
+          AlignmentI seqset)
   {
     this(server2, wsUrl, wsinfo, alFrame, _msa, wsname, subgaps, presorder);
     OutputHeader = wsInfo.getProgressText();
@@ -530,11 +532,13 @@ class MsaWSThread extends AWS2Thread implements WSClientI
     return validInput;
   }
 
+  @Override
   public boolean isCancellable()
   {
     return true;
   }
 
+  @Override
   public void cancelJob()
   {
     if (!jobComplete && jobs != null)
@@ -605,6 +609,7 @@ class MsaWSThread extends AWS2Thread implements WSClientI
     }
   }
 
+  @Override
   public void pollJob(AWsJob job) throws Exception
   {
     // TODO: investigate if we still need to cast here in J1.6
@@ -650,6 +655,7 @@ class MsaWSThread extends AWS2Thread implements WSClientI
     return changed;
   }
 
+  @Override
   public void StartJob(AWsJob job)
   {
     Exception lex = null;
@@ -775,6 +781,7 @@ class MsaWSThread extends AWS2Thread implements WSClientI
     }
   }
 
+  @Override
   public void parseResult()
   {
     long progbar = System.currentTimeMillis();
@@ -889,6 +896,7 @@ class MsaWSThread extends AWS2Thread implements WSClientI
       wsInfo.showResultsNewFrame
               .addActionListener(new java.awt.event.ActionListener()
               {
+                @Override
                 public void actionPerformed(java.awt.event.ActionEvent evt)
                 {
                   displayResults(true);
@@ -897,6 +905,7 @@ class MsaWSThread extends AWS2Thread implements WSClientI
       wsInfo.mergeResults
               .addActionListener(new java.awt.event.ActionListener()
               {
+                @Override
                 public void actionPerformed(java.awt.event.ActionEvent evt)
                 {
                   displayResults(false);
@@ -1023,6 +1032,10 @@ class MsaWSThread extends AWS2Thread implements WSClientI
       // becomes null if the alignment window was closed before the alignment
       // job finished.
       AlignmentI copyComplement = new Alignment(complement);
+      // todo should this be done by copy constructor?
+      copyComplement.setGapCharacter(complement.getGapCharacter());
+      // share the same dataset (and the mappings it holds)
+      copyComplement.setDataset(complement.getDataset());
       copyComplement.alignAs(al);
       if (copyComplement.getHeight() > 0)
       {
@@ -1101,6 +1114,7 @@ class MsaWSThread extends AWS2Thread implements WSClientI
     }
   }
 
+  @Override
   public boolean canMergeResults()
   {
     return false;
index 187540c..2af31bb 100644 (file)
@@ -122,7 +122,7 @@ public class SequenceAnnotationWSClient extends Jws2Client
         }
         // reinstate worker if it was blacklisted (might have happened due to
         // invalid parameters)
-        alignFrame.getViewport().getCalcManager().workerMayRun(worker);
+        alignFrame.getViewport().getCalcManager().enableWorker(worker);
         worker.updateParameters(this.preset, paramset);
       }
     }
index 306c40d..c78bced 100644 (file)
@@ -148,9 +148,9 @@ public class Alignment extends InputType
 
     if (tok.startsWith("format"))
     {
-      for (String fmt : jalview.io.FormatAdapter.WRITEABLE_FORMATS)
+      for (FileFormatI fmt : FileFormat.values())
       {
-        if (val.equalsIgnoreCase(fmt))
+        if (fmt.isWritable() && val.equalsIgnoreCase(fmt.toString()))
         {
           format = fmt;
           return true;
@@ -158,9 +158,12 @@ public class Alignment extends InputType
       }
       warnings.append("Invalid alignment format '" + val
               + "'. Must be one of (");
-      for (String fmt : jalview.io.FormatAdapter.WRITEABLE_FORMATS)
+      for (FileFormatI fmt : FileFormat.values())
       {
-        warnings.append(" " + fmt);
+        if (fmt.isWritable())
+        {
+          warnings.append(" " + fmt).toString();
+        }
       }
       warnings.append(")\n");
     }
@@ -195,8 +198,9 @@ public class Alignment extends InputType
             "Append jalview style /start-end suffix to ID", false, false,
             writeAsFile, null));
 
-    lst.add(new Option("format", "Alignment upload format", true, "FASTA",
-            format, Arrays
+    lst.add(new Option("format", "Alignment upload format", true,
+            FileFormat.Fasta.toString(),
+ format.toString(), Arrays
                     .asList(jalview.io.FormatAdapter.WRITEABLE_FORMATS),
             null));
     lst.add(createMolTypeOption("type", "Sequence type", false, type, null));
index 2392476..33a917e 100644 (file)
@@ -55,7 +55,7 @@ public class ASequenceFetcher
   /**
    * Constructor
    */
-  public ASequenceFetcher()
+  protected ASequenceFetcher()
   {
     super();
 
@@ -125,20 +125,20 @@ public class ASequenceFetcher
    *          if true, only fetch from nucleotide data sources, else peptide
    * @return
    */
-  public SequenceI[] getSequences(DBRefEntry[] refs, boolean dna)
+  public SequenceI[] getSequences(List<DBRefEntry> refs, boolean dna)
   {
     Vector<SequenceI> rseqs = new Vector<SequenceI>();
     Hashtable<String, List<String>> queries = new Hashtable<String, List<String>>();
-    for (int r = 0; r < refs.length; r++)
+    for (DBRefEntry ref : refs)
     {
-      if (!queries.containsKey(refs[r].getSource()))
+      if (!queries.containsKey(ref.getSource()))
       {
-        queries.put(refs[r].getSource(), new ArrayList<String>());
+        queries.put(ref.getSource(), new ArrayList<String>());
       }
-      List<String> qset = queries.get(refs[r].getSource());
-      if (!qset.contains(refs[r].getAccessionId()))
+      List<String> qset = queries.get(ref.getSource());
+      if (!qset.contains(ref.getAccessionId()))
       {
-        qset.add(refs[r].getAccessionId());
+        qset.add(ref.getAccessionId());
       }
     }
     Enumeration<String> e = queries.keys();
@@ -205,15 +205,12 @@ public class ASequenceFetcher
                 for (int is = 0; is < seqs.length; is++)
                 {
                   rseqs.addElement(seqs[is]);
-                  DBRefEntry[] frefs = DBRefUtils.searchRefs(seqs[is]
+                  List<DBRefEntry> frefs = DBRefUtils.searchRefs(seqs[is]
                           .getDBRefs(), new DBRefEntry(db, null, null));
-                  if (frefs != null)
+                  for (DBRefEntry dbr : frefs)
                   {
-                    for (DBRefEntry dbr : frefs)
-                    {
-                      queriesFound.add(dbr.getAccessionId());
-                      queriesMade.remove(dbr.getAccessionId());
-                    }
+                    queriesFound.add(dbr.getAccessionId());
+                    queriesMade.remove(dbr.getAccessionId());
                   }
                   seqs[is] = null;
                 }
index 33d332a..21a79fe 100644 (file)
@@ -42,7 +42,7 @@ public class AtomTest
     assertEquals("GLN", a.resName);
     assertEquals("A", a.chain);
     assertEquals(48, a.resNumber);
-    assertEquals("  48 ", a.resNumIns);
+    assertEquals("48", a.resNumIns);
     assertEquals(' ', a.insCode);
     assertEquals(22.290, a.x, 0.00001);
     assertEquals(8.595, a.y, 0.00001);
index eccfe50..f74e456 100644 (file)
@@ -22,6 +22,7 @@ package jalview.analysis;
 
 import static org.testng.AssertJUnit.assertEquals;
 import static org.testng.AssertJUnit.assertFalse;
+import static org.testng.AssertJUnit.assertNotNull;
 import static org.testng.AssertJUnit.assertNull;
 import static org.testng.AssertJUnit.assertSame;
 import static org.testng.AssertJUnit.assertTrue;
@@ -50,7 +51,6 @@ import jalview.util.MappingUtils;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.Iterator;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
@@ -978,117 +978,167 @@ public class AlignmentUtilsTests
   @Test(groups = { "Functional" })
   public void testMakeCdsAlignment()
   {
+    /*
+     * scenario:
+     *     dna1 --> [4, 6] [10,12]        --> pep1 
+     *     dna2 --> [1, 3] [7, 9] [13,15] --> pep1 
+     */
     SequenceI dna1 = new Sequence("dna1", "aaaGGGcccTTTaaa");
     SequenceI dna2 = new Sequence("dna2", "GGGcccTTTaaaCCC");
     SequenceI pep1 = new Sequence("pep1", "GF");
     SequenceI pep2 = new Sequence("pep2", "GFP");
+    pep1.addDBRef(new DBRefEntry("UNIPROT", "0", "pep1"));
+    pep2.addDBRef(new DBRefEntry("UNIPROT", "0", "pep2"));
     dna1.createDatasetSequence();
     dna2.createDatasetSequence();
     pep1.createDatasetSequence();
     pep2.createDatasetSequence();
-    dna1.addSequenceFeature(new SequenceFeature("CDS", "cds1", 4, 6, 0f,
-            null));
-    dna1.addSequenceFeature(new SequenceFeature("CDS", "cds2", 10, 12, 0f,
-            null));
-    dna2.addSequenceFeature(new SequenceFeature("CDS", "cds3", 1, 3, 0f,
-            null));
-    dna2.addSequenceFeature(new SequenceFeature("CDS", "cds4", 7, 9, 0f,
-            null));
-    dna2.addSequenceFeature(new SequenceFeature("CDS", "cds5", 13, 15, 0f,
-            null));
     AlignmentI dna = new Alignment(new SequenceI[] { dna1, dna2 });
     dna.setDataset(null);
 
-    List<AlignedCodonFrame> mappings = new ArrayList<AlignedCodonFrame>();
+    /*
+     * need a sourceDbRef if we are to construct dbrefs to the CDS
+     * sequence
+     */
+    DBRefEntry dbref = new DBRefEntry("ENSEMBL", "0", "dna1");
+    dna1.getDatasetSequence().setSourceDBRef(dbref);
+    dbref = new DBRefEntry("ENSEMBL", "0", "dna2");
+    dna2.getDatasetSequence().setSourceDBRef(dbref);
+
+    /*
+     * CDS sequences are 'discovered' from dna-to-protein mappings on the alignment
+     * dataset (e.g. added from dbrefs by CrossRef.findXrefSequences)
+     */
     MapList map = new MapList(new int[] { 4, 6, 10, 12 },
             new int[] { 1, 2 }, 3, 1);
     AlignedCodonFrame acf = new AlignedCodonFrame();
     acf.addMap(dna1.getDatasetSequence(), pep1.getDatasetSequence(), map);
-    mappings.add(acf);
+    dna.addCodonFrame(acf);
     map = new MapList(new int[] { 1, 3, 7, 9, 13, 15 }, new int[] { 1, 3 },
             3, 1);
     acf = new AlignedCodonFrame();
     acf.addMap(dna2.getDatasetSequence(), pep2.getDatasetSequence(), map);
-    mappings.add(acf);
+    dna.addCodonFrame(acf);
 
     /*
      * execute method under test:
      */
     AlignmentI cds = AlignmentUtils.makeCdsAlignment(new SequenceI[] {
-        dna1, dna2 }, mappings, dna);
+        dna1, dna2 }, dna.getDataset(), null);
 
+    /*
+     * verify cds sequences
+     */
     assertEquals(2, cds.getSequences().size());
-    assertEquals("GGGTTT", cds.getSequenceAt(0)
-            .getSequenceAsString());
-    assertEquals("GGGTTTCCC", cds.getSequenceAt(1)
-            .getSequenceAsString());
+    assertEquals("GGGTTT", cds.getSequenceAt(0).getSequenceAsString());
+    assertEquals("GGGTTTCCC", cds.getSequenceAt(1).getSequenceAsString());
 
     /*
      * verify shared, extended alignment dataset
      */
     assertSame(dna.getDataset(), cds.getDataset());
-    assertTrue(dna.getDataset().getSequences()
-            .contains(cds.getSequenceAt(0).getDatasetSequence()));
-    assertTrue(dna.getDataset().getSequences()
-            .contains(cds.getSequenceAt(1).getDatasetSequence()));
+    SequenceI cds1Dss = cds.getSequenceAt(0).getDatasetSequence();
+    SequenceI cds2Dss = cds.getSequenceAt(1).getDatasetSequence();
+    assertTrue(dna.getDataset().getSequences().contains(cds1Dss));
+    assertTrue(dna.getDataset().getSequences().contains(cds2Dss));
+
+    /*
+     * verify CDS has a dbref with mapping to peptide
+     */
+    assertNotNull(cds1Dss.getDBRefs());
+    assertEquals(1, cds1Dss.getDBRefs().length);
+    dbref = cds1Dss.getDBRefs()[0];
+    assertEquals("UNIPROT", dbref.getSource());
+    assertEquals("0", dbref.getVersion());
+    assertEquals("pep1", dbref.getAccessionId());
+    assertNotNull(dbref.getMap());
+    assertSame(pep1.getDatasetSequence(), dbref.getMap().getTo());
+    MapList cdsMapping = new MapList(new int[] { 1, 6 },
+            new int[] { 1, 2 }, 3, 1);
+    assertEquals(cdsMapping, dbref.getMap().getMap());
+
+    /*
+     * verify peptide has added a dbref with reverse mapping to CDS
+     */
+    assertNotNull(pep1.getDBRefs());
+    assertEquals(2, pep1.getDBRefs().length);
+    dbref = pep1.getDBRefs()[1];
+    assertEquals("ENSEMBL", dbref.getSource());
+    assertEquals("0", dbref.getVersion());
+    assertEquals("CDS|dna1", dbref.getAccessionId());
+    assertNotNull(dbref.getMap());
+    assertSame(cds1Dss, dbref.getMap().getTo());
+    assertEquals(cdsMapping.getInverse(), dbref.getMap().getMap());
 
     /*
-     * Verify mappings from CDS to peptide and cDNA to CDS
+     * Verify mappings from CDS to peptide, cDNA to CDS, and cDNA to peptide
      * the mappings are on the shared alignment dataset
+     * 6 mappings, 2*(DNA->CDS), 2*(DNA->Pep), 2*(CDS->Pep) 
      */
-    assertSame(dna.getCodonFrames(), cds.getCodonFrames());
-    List<AlignedCodonFrame> cdsMappings = cds.getCodonFrames();
-    assertEquals(2, cdsMappings.size());
-    
+    List<AlignedCodonFrame> cdsMappings = cds.getDataset().getCodonFrames();
+    assertEquals(6, cdsMappings.size());
+
+    /*
+     * verify that mapping sets for dna and cds alignments are different
+     * [not current behaviour - all mappings are on the alignment dataset]  
+     */
+    // select -> subselect type to test.
+    // Assert.assertNotSame(dna.getCodonFrames(), cds.getCodonFrames());
+    // assertEquals(4, dna.getCodonFrames().size());
+    // assertEquals(4, cds.getCodonFrames().size());
+
     /*
+     * Two mappings involve pep1 (dna to pep1, cds to pep1)
      * Mapping from pep1 to GGGTTT in first new exon sequence
      */
-    List<AlignedCodonFrame> pep1Mapping = MappingUtils
+    List<AlignedCodonFrame> pep1Mappings = MappingUtils
             .findMappingsForSequence(pep1, cdsMappings);
-    assertEquals(1, pep1Mapping.size());
+    assertEquals(2, pep1Mappings.size());
+    List<AlignedCodonFrame> mappings = MappingUtils
+            .findMappingsForSequence(cds.getSequenceAt(0), pep1Mappings);
+    assertEquals(1, mappings.size());
+
     // map G to GGG
-    SearchResults sr = MappingUtils
-            .buildSearchResults(pep1, 1, cdsMappings);
+    SearchResults sr = MappingUtils.buildSearchResults(pep1, 1, mappings);
     assertEquals(1, sr.getResults().size());
     Match m = sr.getResults().get(0);
-    assertSame(cds.getSequenceAt(0).getDatasetSequence(),
-            m.getSequence());
+    assertSame(cds1Dss, m.getSequence());
     assertEquals(1, m.getStart());
     assertEquals(3, m.getEnd());
     // map F to TTT
-    sr = MappingUtils.buildSearchResults(pep1, 2, cdsMappings);
+    sr = MappingUtils.buildSearchResults(pep1, 2, mappings);
     m = sr.getResults().get(0);
-    assertSame(cds.getSequenceAt(0).getDatasetSequence(),
-            m.getSequence());
+    assertSame(cds1Dss, m.getSequence());
     assertEquals(4, m.getStart());
     assertEquals(6, m.getEnd());
 
     /*
-     * Mapping from pep2 to GGGTTTCCC in second new exon sequence
+     * Two mappings involve pep2 (dna to pep2, cds to pep2)
+     * Verify mapping from pep2 to GGGTTTCCC in second new exon sequence
      */
-    List<AlignedCodonFrame> pep2Mapping = MappingUtils
+    List<AlignedCodonFrame> pep2Mappings = MappingUtils
             .findMappingsForSequence(pep2, cdsMappings);
-    assertEquals(1, pep2Mapping.size());
+    assertEquals(2, pep2Mappings.size());
+    mappings = MappingUtils.findMappingsForSequence(cds.getSequenceAt(1),
+            pep2Mappings);
+    assertEquals(1, mappings.size());
     // map G to GGG
-    sr = MappingUtils.buildSearchResults(pep2, 1, cdsMappings);
+    sr = MappingUtils.buildSearchResults(pep2, 1, mappings);
     assertEquals(1, sr.getResults().size());
     m = sr.getResults().get(0);
-    assertSame(cds.getSequenceAt(1).getDatasetSequence(),
-            m.getSequence());
+    assertSame(cds2Dss, m.getSequence());
     assertEquals(1, m.getStart());
     assertEquals(3, m.getEnd());
     // map F to TTT
-    sr = MappingUtils.buildSearchResults(pep2, 2, cdsMappings);
+    sr = MappingUtils.buildSearchResults(pep2, 2, mappings);
     m = sr.getResults().get(0);
-    assertSame(cds.getSequenceAt(1).getDatasetSequence(),
-            m.getSequence());
+    assertSame(cds2Dss, m.getSequence());
     assertEquals(4, m.getStart());
     assertEquals(6, m.getEnd());
     // map P to CCC
-    sr = MappingUtils.buildSearchResults(pep2, 3, cdsMappings);
+    sr = MappingUtils.buildSearchResults(pep2, 3, mappings);
     m = sr.getResults().get(0);
-    assertSame(cds.getSequenceAt(1).getDatasetSequence(),
-            m.getSequence());
+    assertSame(cds2Dss, m.getSequence());
     assertEquals(7, m.getStart());
     assertEquals(9, m.getEnd());
   }
@@ -1109,18 +1159,6 @@ public class AlignmentUtilsTests
     pep1.createDatasetSequence();
     pep2.createDatasetSequence();
     pep3.createDatasetSequence();
-    dna1.addSequenceFeature(new SequenceFeature("CDS", "cds1", 4, 6, 0f,
-            null));
-    dna1.addSequenceFeature(new SequenceFeature("CDS", "cds2", 10, 12, 0f,
-            null));
-    dna1.addSequenceFeature(new SequenceFeature("CDS", "cds3", 1, 3, 0f,
-            null));
-    dna1.addSequenceFeature(new SequenceFeature("CDS", "cds4", 7, 9, 0f,
-            null));
-    dna1.addSequenceFeature(new SequenceFeature("CDS", "cds5", 1, 3, 0f,
-            null));
-    dna1.addSequenceFeature(new SequenceFeature("CDS", "cds6", 10, 12, 0f,
-            null));
     pep1.getDatasetSequence().addDBRef(
             new DBRefEntry("EMBLCDS", "2", "A12345"));
     pep2.getDatasetSequence().addDBRef(
@@ -1129,40 +1167,38 @@ public class AlignmentUtilsTests
             new DBRefEntry("EMBLCDS", "4", "A12347"));
 
     /*
+     * Create the CDS alignment
+     */
+    AlignmentI dna = new Alignment(new SequenceI[] { dna1 });
+    dna.setDataset(null);
+
+    /*
      * Make the mappings from dna to protein
      */
-    List<AlignedCodonFrame> mappings = new ArrayList<AlignedCodonFrame>();
     // map ...GGG...TTT to GF
     MapList map = new MapList(new int[] { 4, 6, 10, 12 },
             new int[] { 1, 2 }, 3, 1);
     AlignedCodonFrame acf = new AlignedCodonFrame();
     acf.addMap(dna1.getDatasetSequence(), pep1.getDatasetSequence(), map);
-    mappings.add(acf);
+    dna.addCodonFrame(acf);
 
     // map aaa...ccc to KP
     map = new MapList(new int[] { 1, 3, 7, 9 }, new int[] { 1, 2 }, 3, 1);
     acf = new AlignedCodonFrame();
     acf.addMap(dna1.getDatasetSequence(), pep2.getDatasetSequence(), map);
-    mappings.add(acf);
+    dna.addCodonFrame(acf);
 
     // map aaa......TTT to KF
     map = new MapList(new int[] { 1, 3, 10, 12 }, new int[] { 1, 2 }, 3, 1);
     acf = new AlignedCodonFrame();
     acf.addMap(dna1.getDatasetSequence(), pep3.getDatasetSequence(), map);
-    mappings.add(acf);
-
-    /*
-     * Create the CDS alignment; also augments the dna-to-protein mappings with
-     * exon-to-protein and exon-to-dna mappings
-     */
-    AlignmentI dna = new Alignment(new SequenceI[] { dna1 });
-    dna.setDataset(null);
+    dna.addCodonFrame(acf);
 
     /*
      * execute method under test
      */
     AlignmentI cdsal = AlignmentUtils.makeCdsAlignment(
-            new SequenceI[] { dna1 }, mappings, dna);
+            new SequenceI[] { dna1 }, dna.getDataset(), null);
 
     /*
      * Verify we have 3 cds sequences, mapped to pep1/2/3 respectively
@@ -1187,7 +1223,7 @@ public class AlignmentUtilsTests
     SequenceI cdsSeq = cds.get(0);
     assertEquals("GGGTTT", cdsSeq.getSequenceAsString());
     // assertEquals("dna1|A12345", cdsSeq.getName());
-    assertEquals("dna1|pep1", cdsSeq.getName());
+    assertEquals("CDS|dna1", cdsSeq.getName());
     // assertEquals(1, cdsSeq.getDBRefs().length);
     // DBRefEntry cdsRef = cdsSeq.getDBRefs()[0];
     // assertEquals("EMBLCDS", cdsRef.getSource());
@@ -1197,7 +1233,7 @@ public class AlignmentUtilsTests
     cdsSeq = cds.get(1);
     assertEquals("aaaccc", cdsSeq.getSequenceAsString());
     // assertEquals("dna1|A12346", cdsSeq.getName());
-    assertEquals("dna1|pep2", cdsSeq.getName());
+    assertEquals("CDS|dna1", cdsSeq.getName());
     // assertEquals(1, cdsSeq.getDBRefs().length);
     // cdsRef = cdsSeq.getDBRefs()[0];
     // assertEquals("EMBLCDS", cdsRef.getSource());
@@ -1207,7 +1243,7 @@ public class AlignmentUtilsTests
     cdsSeq = cds.get(2);
     assertEquals("aaaTTT", cdsSeq.getSequenceAsString());
     // assertEquals("dna1|A12347", cdsSeq.getName());
-    assertEquals("dna1|pep3", cdsSeq.getName());
+    assertEquals("CDS|dna1", cdsSeq.getName());
     // assertEquals(1, cdsSeq.getDBRefs().length);
     // cdsRef = cdsSeq.getDBRefs()[0];
     // assertEquals("EMBLCDS", cdsRef.getSource());
@@ -1218,41 +1254,74 @@ public class AlignmentUtilsTests
      * Verify there are mappings from each cds sequence to its protein product
      * and also to its dna source
      */
-    Iterator<AlignedCodonFrame> newMappingsIterator = cdsal
-            .getCodonFrames().iterator();
+    List<AlignedCodonFrame> newMappings = cdsal.getCodonFrames();
 
-    // mappings for dna1 - exon1 - pep1
-    AlignedCodonFrame cdsMapping = newMappingsIterator.next();
-    List<Mapping> dnaMappings = cdsMapping.getMappingsFromSequence(dna1);
-    assertEquals(3, dnaMappings.size());
-    assertSame(cds.get(0).getDatasetSequence(), dnaMappings.get(0)
-            .getTo());
-    assertEquals("G(1) in CDS should map to G(4) in DNA", 4, dnaMappings
-            .get(0).getMap().getToPosition(1));
-    List<Mapping> peptideMappings = cdsMapping.getMappingsFromSequence(cds
-            .get(0).getDatasetSequence());
-    assertEquals(1, peptideMappings.size());
-    assertSame(pep1.getDatasetSequence(), peptideMappings.get(0).getTo());
-
-    // mappings for dna1 - cds2 - pep2
-    assertSame(cds.get(1).getDatasetSequence(), dnaMappings.get(1)
-            .getTo());
-    assertEquals("c(4) in CDS should map to c(7) in DNA", 7, dnaMappings
-            .get(1).getMap().getToPosition(4));
-    peptideMappings = cdsMapping.getMappingsFromSequence(cds.get(1)
-            .getDatasetSequence());
-    assertEquals(1, peptideMappings.size());
-    assertSame(pep2.getDatasetSequence(), peptideMappings.get(0).getTo());
-
-    // mappings for dna1 - cds3 - pep3
-    assertSame(cds.get(2).getDatasetSequence(), dnaMappings.get(2)
+    /*
+     * 6 mappings involve dna1 (to pep1/2/3, cds1/2/3) 
+     */
+    List<AlignedCodonFrame> dnaMappings = MappingUtils
+            .findMappingsForSequence(dna1, newMappings);
+    assertEquals(6, dnaMappings.size());
+
+    /*
+     * dna1 to pep1
+     */
+    List<AlignedCodonFrame> mappings = MappingUtils
+            .findMappingsForSequence(pep1, dnaMappings);
+    assertEquals(1, mappings.size());
+    assertEquals(1, mappings.get(0).getMappings().size());
+    assertSame(pep1.getDatasetSequence(), mappings.get(0).getMappings()
+            .get(0).getMapping().getTo());
+
+    /*
+     * dna1 to cds1
+     */
+    List<AlignedCodonFrame> dnaToCds1Mappings = MappingUtils
+            .findMappingsForSequence(cds.get(0), dnaMappings);
+    Mapping mapping = dnaToCds1Mappings.get(0).getMappings().get(0)
+            .getMapping();
+    assertSame(cds.get(0).getDatasetSequence(), mapping
             .getTo());
-    assertEquals("T(4) in CDS should map to T(10) in DNA", 10, dnaMappings
-            .get(2).getMap().getToPosition(4));
-    peptideMappings = cdsMapping.getMappingsFromSequence(cds.get(2)
-            .getDatasetSequence());
-    assertEquals(1, peptideMappings.size());
-    assertSame(pep3.getDatasetSequence(), peptideMappings.get(0).getTo());
+    assertEquals("G(1) in CDS should map to G(4) in DNA", 4, mapping
+            .getMap().getToPosition(1));
+
+    /*
+     * dna1 to pep2
+     */
+    mappings = MappingUtils.findMappingsForSequence(pep2, dnaMappings);
+    assertEquals(1, mappings.size());
+    assertEquals(1, mappings.get(0).getMappings().size());
+    assertSame(pep2.getDatasetSequence(), mappings.get(0).getMappings()
+            .get(0).getMapping().getTo());
+
+    /*
+     * dna1 to cds2
+     */
+    List<AlignedCodonFrame> dnaToCds2Mappings = MappingUtils
+            .findMappingsForSequence(cds.get(1), dnaMappings);
+    mapping = dnaToCds2Mappings.get(0).getMappings().get(0).getMapping();
+    assertSame(cds.get(1).getDatasetSequence(), mapping.getTo());
+    assertEquals("c(4) in CDS should map to c(7) in DNA", 7, mapping
+            .getMap().getToPosition(4));
+
+    /*
+     * dna1 to pep3
+     */
+    mappings = MappingUtils.findMappingsForSequence(pep3, dnaMappings);
+    assertEquals(1, mappings.size());
+    assertEquals(1, mappings.get(0).getMappings().size());
+    assertSame(pep3.getDatasetSequence(), mappings.get(0).getMappings()
+            .get(0).getMapping().getTo());
+
+    /*
+     * dna1 to cds3
+     */
+    List<AlignedCodonFrame> dnaToCds3Mappings = MappingUtils
+            .findMappingsForSequence(cds.get(2), dnaMappings);
+    mapping = dnaToCds3Mappings.get(0).getMappings().get(0).getMapping();
+    assertSame(cds.get(2).getDatasetSequence(), mapping.getTo());
+    assertEquals("T(4) in CDS should map to T(10) in DNA", 10, mapping
+            .getMap().getToPosition(4));
   }
 
   @Test(groups = { "Functional" })
@@ -1501,36 +1570,24 @@ public class AlignmentUtilsTests
     dna3.createDatasetSequence();
     pep1.createDatasetSequence();
     pep2.createDatasetSequence();
-    dna1.addSequenceFeature(new SequenceFeature("CDS", "cds1", 4, 8, 0f,
-            null));
-    dna1.addSequenceFeature(new SequenceFeature("CDS", "cds2", 9, 12, 0f,
-            null));
-    dna1.addSequenceFeature(new SequenceFeature("CDS", "cds3", 16, 18, 0f,
-            null));
-    dna2.addSequenceFeature(new SequenceFeature("CDS", "cds", 4, 8, 0f,
-            null));
-    dna2.addSequenceFeature(new SequenceFeature("CDS", "cds", 12, 12, 0f,
-            null));
-    dna2.addSequenceFeature(new SequenceFeature("CDS", "cds", 16, 18, 0f,
-            null));
+
+    AlignmentI dna = new Alignment(new SequenceI[] { dna1, dna2, dna3 });
+    dna.setDataset(null);
   
-    List<AlignedCodonFrame> mappings = new ArrayList<AlignedCodonFrame>();
     MapList map = new MapList(new int[] { 4, 12, 16, 18 },
             new int[] { 1, 4 }, 3, 1);
     AlignedCodonFrame acf = new AlignedCodonFrame();
     acf.addMap(dna1.getDatasetSequence(), pep1.getDatasetSequence(), map);
-    mappings.add(acf);
+    dna.addCodonFrame(acf);
     map = new MapList(new int[] { 4, 8, 12, 12, 16, 18 },
             new int[] { 1, 3 },
             3, 1);
     acf = new AlignedCodonFrame();
     acf.addMap(dna2.getDatasetSequence(), pep2.getDatasetSequence(), map);
-    mappings.add(acf);
+    dna.addCodonFrame(acf);
   
-    AlignmentI dna = new Alignment(new SequenceI[] { dna1, dna2, dna3 });
-    dna.setDataset(null);
     AlignmentI cds = AlignmentUtils.makeCdsAlignment(new SequenceI[] {
-        dna1, dna2, dna3 }, mappings, dna);
+        dna1, dna2, dna3 }, dna.getDataset(), null);
     List<SequenceI> cdsSeqs = cds.getSequences();
     assertEquals(2, cdsSeqs.size());
     assertEquals("GGGCCCTTTGGG", cdsSeqs.get(0).getSequenceAsString());
@@ -1546,59 +1603,69 @@ public class AlignmentUtilsTests
             .contains(cdsSeqs.get(1).getDatasetSequence()));
 
     /*
-     * Verify updated mappings
+     * Verify 6 mappings: dna1 to cds1, cds1 to pep1, dna1 to pep1
+     * and the same for dna2/cds2/pep2
      */
-    List<AlignedCodonFrame> cdsMappings = cds.getCodonFrames();
-    assertEquals(2, cdsMappings.size());
+    List<AlignedCodonFrame> mappings = cds.getCodonFrames();
+    assertEquals(6, mappings.size());
   
     /*
-     * Mapping from pep1 to GGGTTT in first new CDS sequence
+     * 2 mappings involve pep1
      */
-    List<AlignedCodonFrame> pep1Mapping = MappingUtils
-            .findMappingsForSequence(pep1, cdsMappings);
-    assertEquals(1, pep1Mapping.size());
+    List<AlignedCodonFrame> pep1Mappings = MappingUtils
+            .findMappingsForSequence(pep1, mappings);
+    assertEquals(2, pep1Mappings.size());
+
     /*
+     * Get mapping of pep1 to cds1 and verify it
      * maps GPFG to 1-3,4-6,7-9,10-12
      */
-    SearchResults sr = MappingUtils
-            .buildSearchResults(pep1, 1, cdsMappings);
+    List<AlignedCodonFrame> pep1CdsMappings = MappingUtils
+            .findMappingsForSequence(cds.getSequenceAt(0), pep1Mappings);
+    assertEquals(1, pep1CdsMappings.size());
+    SearchResults sr = MappingUtils.buildSearchResults(pep1, 1,
+            pep1CdsMappings);
     assertEquals(1, sr.getResults().size());
     Match m = sr.getResults().get(0);
     assertEquals(cds.getSequenceAt(0).getDatasetSequence(),
             m.getSequence());
     assertEquals(1, m.getStart());
     assertEquals(3, m.getEnd());
-    sr = MappingUtils.buildSearchResults(pep1, 2, cdsMappings);
+    sr = MappingUtils.buildSearchResults(pep1, 2, pep1CdsMappings);
     m = sr.getResults().get(0);
     assertEquals(4, m.getStart());
     assertEquals(6, m.getEnd());
-    sr = MappingUtils.buildSearchResults(pep1, 3, cdsMappings);
+    sr = MappingUtils.buildSearchResults(pep1, 3, pep1CdsMappings);
     m = sr.getResults().get(0);
     assertEquals(7, m.getStart());
     assertEquals(9, m.getEnd());
-    sr = MappingUtils.buildSearchResults(pep1, 4, cdsMappings);
+    sr = MappingUtils.buildSearchResults(pep1, 4, pep1CdsMappings);
     m = sr.getResults().get(0);
     assertEquals(10, m.getStart());
     assertEquals(12, m.getEnd());
   
     /*
-     * GPG in pep2 map to 1-3,4-6,7-9 in second CDS sequence
+     * Get mapping of pep2 to cds2 and verify it
+     * maps GPG in pep2 to 1-3,4-6,7-9 in second CDS sequence
      */
-    List<AlignedCodonFrame> pep2Mapping = MappingUtils
-            .findMappingsForSequence(pep2, cdsMappings);
-    assertEquals(1, pep2Mapping.size());
-    sr = MappingUtils.buildSearchResults(pep2, 1, cdsMappings);
+    List<AlignedCodonFrame> pep2Mappings = MappingUtils
+            .findMappingsForSequence(pep2, mappings);
+    assertEquals(2, pep2Mappings.size());
+    List<AlignedCodonFrame> pep2CdsMappings = MappingUtils
+            .findMappingsForSequence(cds.getSequenceAt(1), pep2Mappings);
+    assertEquals(1, pep2CdsMappings.size());
+    sr = MappingUtils.buildSearchResults(pep2, 1, pep2CdsMappings);
     assertEquals(1, sr.getResults().size());
     m = sr.getResults().get(0);
     assertEquals(cds.getSequenceAt(1).getDatasetSequence(),
             m.getSequence());
     assertEquals(1, m.getStart());
     assertEquals(3, m.getEnd());
-    sr = MappingUtils.buildSearchResults(pep2, 2, cdsMappings);
+    sr = MappingUtils.buildSearchResults(pep2, 2, pep2CdsMappings);
     m = sr.getResults().get(0);
     assertEquals(4, m.getStart());
     assertEquals(6, m.getEnd());
-    sr = MappingUtils.buildSearchResults(pep2, 3, cdsMappings);
+    sr = MappingUtils.buildSearchResults(pep2, 3, pep2CdsMappings);
     m = sr.getResults().get(0);
     assertEquals(7, m.getStart());
     assertEquals(9, m.getEnd());
@@ -1874,13 +1941,15 @@ public class AlignmentUtilsTests
   public void testComputePeptideVariants()
   {
     /*
-     * scenario: AAATTTCCC codes for KFP, with variants
-     *           GAA -> E
-     *           CAA -> Q
-     *           AAG synonymous
-     *           AAT -> N
-     *              TTC synonymous
-     *                 CAC,CGC -> H,R (as one variant)
+     * scenario: AAATTTCCC codes for KFP
+     * variants:
+     *           GAA -> E             source: Ensembl
+     *           CAA -> Q             source: dbSNP
+     *           AAG synonymous       source: COSMIC
+     *           AAT -> N             source: Ensembl
+     *           ...TTC synonymous    source: dbSNP
+     *           ......CAC,CGC -> H,R source: COSMIC
+     *                 (one variant with two alleles)
      */
     SequenceI peptide = new Sequence("pep/10-12", "KFP");
 
@@ -1888,32 +1957,35 @@ public class AlignmentUtilsTests
      * two distinct variants for codon 1 position 1
      * second one has clinical significance
      */
+    String ensembl = "Ensembl";
+    String dbSnp = "dbSNP";
+    String cosmic = "COSMIC";
     SequenceFeature sf1 = new SequenceFeature("sequence_variant", "", 1, 1,
-            0f, null);
+            0f, ensembl);
     sf1.setValue("alleles", "A,G"); // GAA -> E
     sf1.setValue("ID", "var1.125A>G");
     SequenceFeature sf2 = new SequenceFeature("sequence_variant", "", 1, 1,
-            0f, null);
+            0f, dbSnp);
     sf2.setValue("alleles", "A,C"); // CAA -> Q
     sf2.setValue("ID", "var2");
     sf2.setValue("clinical_significance", "Dodgy");
     SequenceFeature sf3 = new SequenceFeature("sequence_variant", "", 3, 3,
-            0f, null);
+            0f, cosmic);
     sf3.setValue("alleles", "A,G"); // synonymous
     sf3.setValue("ID", "var3");
     sf3.setValue("clinical_significance", "None");
     SequenceFeature sf4 = new SequenceFeature("sequence_variant", "", 3, 3,
-            0f, null);
+            0f, ensembl);
     sf4.setValue("alleles", "A,T"); // AAT -> N
     sf4.setValue("ID", "sequence_variant:var4"); // prefix gets stripped off
     sf4.setValue("clinical_significance", "Benign");
     SequenceFeature sf5 = new SequenceFeature("sequence_variant", "", 6, 6,
-            0f, null);
+            0f, dbSnp);
     sf5.setValue("alleles", "T,C"); // synonymous
     sf5.setValue("ID", "var5");
     sf5.setValue("clinical_significance", "Bad");
     SequenceFeature sf6 = new SequenceFeature("sequence_variant", "", 8, 8,
-            0f, null);
+            0f, cosmic);
     sf6.setValue("alleles", "C,A,G"); // CAC,CGC -> H,R
     sf6.setValue("ID", "var6");
     sf6.setValue("clinical_significance", "Good");
@@ -1961,14 +2033,15 @@ public class AlignmentUtilsTests
 
     /*
      * verify added sequence features for
-     * var1 K -> E
-     * var2 K -> Q
-     * var4 K -> N
-     * var6 P -> H
-     * var6 P -> R
+     * var1 K -> E Ensembl
+     * var2 K -> Q dbSNP
+     * var4 K -> N Ensembl
+     * var6 P -> H COSMIC
+     * var6 P -> R COSMIC
      */
     SequenceFeature[] sfs = peptide.getSequenceFeatures();
     assertEquals(5, sfs.length);
+
     SequenceFeature sf = sfs[0];
     assertEquals(1, sf.getBegin());
     assertEquals(1, sf.getEnd());
@@ -1981,7 +2054,8 @@ public class AlignmentUtilsTests
     assertEquals(
             "p.Lys1Glu var1.125A>G|http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=var1.125A%3EG",
             sf.links.get(0));
-    assertEquals("Jalview", sf.getFeatureGroup());
+    assertEquals(ensembl, sf.getFeatureGroup());
+
     sf = sfs[1];
     assertEquals(1, sf.getBegin());
     assertEquals(1, sf.getEnd());
@@ -1993,7 +2067,8 @@ public class AlignmentUtilsTests
     assertEquals(
             "p.Lys1Gln var2|http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=var2",
             sf.links.get(0));
-    assertEquals("Jalview", sf.getFeatureGroup());
+    assertEquals(dbSnp, sf.getFeatureGroup());
+
     sf = sfs[2];
     assertEquals(1, sf.getBegin());
     assertEquals(1, sf.getEnd());
@@ -2005,7 +2080,9 @@ public class AlignmentUtilsTests
     assertEquals(
             "p.Lys1Asn var4|http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=var4",
             sf.links.get(0));
-    assertEquals("Jalview", sf.getFeatureGroup());
+    assertEquals(ensembl, sf.getFeatureGroup());
+
+    // var5 generates two distinct protein variant features
     sf = sfs[3];
     assertEquals(3, sf.getBegin());
     assertEquals(3, sf.getEnd());
@@ -2017,8 +2094,8 @@ public class AlignmentUtilsTests
     assertEquals(
             "p.Pro3His var6|http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=var6",
             sf.links.get(0));
-    // var5 generates two distinct protein variant features
-    assertEquals("Jalview", sf.getFeatureGroup());
+    assertEquals(cosmic, sf.getFeatureGroup());
+
     sf = sfs[4];
     assertEquals(3, sf.getBegin());
     assertEquals(3, sf.getEnd());
@@ -2030,7 +2107,7 @@ public class AlignmentUtilsTests
     assertEquals(
             "p.Pro3Arg var6|http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=var6",
             sf.links.get(0));
-    assertEquals("Jalview", sf.getFeatureGroup());
+    assertEquals(cosmic, sf.getFeatureGroup());
   }
 
   /**
@@ -2197,4 +2274,219 @@ public class AlignmentUtilsTests
     assertEquals('T', map.get(11).get(seq1).charValue());
     assertEquals('T', map.get(12).get(seq1).charValue());
   }
+
+  /**
+   * Test for the case where the products for which we want CDS are specified.
+   * This is to represent the case where EMBL has CDS mappings to both Uniprot
+   * and EMBLCDSPROTEIN. makeCdsAlignment() should only return the mappings for
+   * the protein sequences specified.
+   */
+  @Test(groups = { "Functional" })
+  public void testMakeCdsAlignment_filterProducts()
+  {
+    SequenceI dna1 = new Sequence("dna1", "aaaGGGcccTTTaaa");
+    SequenceI dna2 = new Sequence("dna2", "GGGcccTTTaaaCCC");
+    SequenceI pep1 = new Sequence("Uniprot|pep1", "GF");
+    SequenceI pep2 = new Sequence("Uniprot|pep2", "GFP");
+    SequenceI pep3 = new Sequence("EMBL|pep3", "GF");
+    SequenceI pep4 = new Sequence("EMBL|pep4", "GFP");
+    dna1.createDatasetSequence();
+    dna2.createDatasetSequence();
+    pep1.createDatasetSequence();
+    pep2.createDatasetSequence();
+    pep3.createDatasetSequence();
+    pep4.createDatasetSequence();
+    AlignmentI dna = new Alignment(new SequenceI[] { dna1, dna2 });
+    dna.setDataset(null);
+    AlignmentI emblPeptides = new Alignment(new SequenceI[] { pep3, pep4 });
+    emblPeptides.setDataset(null);
+  
+    AlignedCodonFrame acf = new AlignedCodonFrame();
+    MapList map = new MapList(new int[] { 4, 6, 10, 12 },
+            new int[] { 1, 2 }, 3, 1);
+    acf.addMap(dna1.getDatasetSequence(), pep1.getDatasetSequence(), map);
+    acf.addMap(dna1.getDatasetSequence(), pep3.getDatasetSequence(), map);
+    dna.addCodonFrame(acf);
+
+    acf = new AlignedCodonFrame();
+    map = new MapList(new int[] { 1, 3, 7, 9, 13, 15 }, new int[] { 1, 3 },
+            3, 1);
+    acf.addMap(dna2.getDatasetSequence(), pep2.getDatasetSequence(), map);
+    acf.addMap(dna2.getDatasetSequence(), pep4.getDatasetSequence(), map);
+    dna.addCodonFrame(acf);
+  
+    /*
+     * execute method under test to find CDS for EMBL peptides only
+     */
+    AlignmentI cds = AlignmentUtils.makeCdsAlignment(new SequenceI[] {
+        dna1, dna2 }, dna.getDataset(), emblPeptides.getSequencesArray());
+  
+    assertEquals(2, cds.getSequences().size());
+    assertEquals("GGGTTT", cds.getSequenceAt(0).getSequenceAsString());
+    assertEquals("GGGTTTCCC", cds.getSequenceAt(1).getSequenceAsString());
+  
+    /*
+     * verify shared, extended alignment dataset
+     */
+    assertSame(dna.getDataset(), cds.getDataset());
+    assertTrue(dna.getDataset().getSequences()
+            .contains(cds.getSequenceAt(0).getDatasetSequence()));
+    assertTrue(dna.getDataset().getSequences()
+            .contains(cds.getSequenceAt(1).getDatasetSequence()));
+  
+    /*
+     * Verify mappings from CDS to peptide, cDNA to CDS, and cDNA to peptide
+     * the mappings are on the shared alignment dataset
+     */
+    List<AlignedCodonFrame> cdsMappings = cds.getDataset().getCodonFrames();
+    /*
+     * 6 mappings, 2*(DNA->CDS), 2*(DNA->Pep), 2*(CDS->Pep) 
+     */
+    assertEquals(6, cdsMappings.size());
+  
+    /*
+     * verify that mapping sets for dna and cds alignments are different
+     * [not current behaviour - all mappings are on the alignment dataset]  
+     */
+    // select -> subselect type to test.
+    // Assert.assertNotSame(dna.getCodonFrames(), cds.getCodonFrames());
+    // assertEquals(4, dna.getCodonFrames().size());
+    // assertEquals(4, cds.getCodonFrames().size());
+  
+    /*
+     * Two mappings involve pep3 (dna to pep3, cds to pep3)
+     * Mapping from pep3 to GGGTTT in first new exon sequence
+     */
+    List<AlignedCodonFrame> pep3Mappings = MappingUtils
+            .findMappingsForSequence(pep3, cdsMappings);
+    assertEquals(2, pep3Mappings.size());
+    List<AlignedCodonFrame> mappings = MappingUtils
+            .findMappingsForSequence(cds.getSequenceAt(0), pep3Mappings);
+    assertEquals(1, mappings.size());
+  
+    // map G to GGG
+    SearchResults sr = MappingUtils.buildSearchResults(pep3, 1, mappings);
+    assertEquals(1, sr.getResults().size());
+    Match m = sr.getResults().get(0);
+    assertSame(cds.getSequenceAt(0).getDatasetSequence(), m.getSequence());
+    assertEquals(1, m.getStart());
+    assertEquals(3, m.getEnd());
+    // map F to TTT
+    sr = MappingUtils.buildSearchResults(pep3, 2, mappings);
+    m = sr.getResults().get(0);
+    assertSame(cds.getSequenceAt(0).getDatasetSequence(), m.getSequence());
+    assertEquals(4, m.getStart());
+    assertEquals(6, m.getEnd());
+  
+    /*
+     * Two mappings involve pep4 (dna to pep4, cds to pep4)
+     * Verify mapping from pep4 to GGGTTTCCC in second new exon sequence
+     */
+    List<AlignedCodonFrame> pep4Mappings = MappingUtils
+            .findMappingsForSequence(pep4, cdsMappings);
+    assertEquals(2, pep4Mappings.size());
+    mappings = MappingUtils.findMappingsForSequence(cds.getSequenceAt(1),
+            pep4Mappings);
+    assertEquals(1, mappings.size());
+    // map G to GGG
+    sr = MappingUtils.buildSearchResults(pep4, 1, mappings);
+    assertEquals(1, sr.getResults().size());
+    m = sr.getResults().get(0);
+    assertSame(cds.getSequenceAt(1).getDatasetSequence(), m.getSequence());
+    assertEquals(1, m.getStart());
+    assertEquals(3, m.getEnd());
+    // map F to TTT
+    sr = MappingUtils.buildSearchResults(pep4, 2, mappings);
+    m = sr.getResults().get(0);
+    assertSame(cds.getSequenceAt(1).getDatasetSequence(), m.getSequence());
+    assertEquals(4, m.getStart());
+    assertEquals(6, m.getEnd());
+    // map P to CCC
+    sr = MappingUtils.buildSearchResults(pep4, 3, mappings);
+    m = sr.getResults().get(0);
+    assertSame(cds.getSequenceAt(1).getDatasetSequence(), m.getSequence());
+    assertEquals(7, m.getStart());
+    assertEquals(9, m.getEnd());
+  }
+
+  /**
+   * Test the method that just copies aligned sequences, provided all sequences
+   * to be aligned share the aligned sequence's dataset
+   */
+  @Test(groups = "Functional")
+  public void testAlignAsSameSequences()
+  {
+    SequenceI dna1 = new Sequence("dna1", "cccGGGTTTaaa");
+    SequenceI dna2 = new Sequence("dna2", "CCCgggtttAAA");
+    AlignmentI al1 = new Alignment(new SequenceI[] { dna1, dna2 });
+    ((Alignment) al1).createDatasetAlignment();
+
+    SequenceI dna3 = new Sequence(dna1);
+    SequenceI dna4 = new Sequence(dna2);
+    assertSame(dna3.getDatasetSequence(), dna1.getDatasetSequence());
+    assertSame(dna4.getDatasetSequence(), dna2.getDatasetSequence());
+    String seq1 = "-cc-GG-GT-TT--aaa";
+    dna3.setSequence(seq1);
+    String seq2 = "C--C-Cgg--gtt-tAA-A-";
+    dna4.setSequence(seq2);
+    AlignmentI al2 = new Alignment(new SequenceI[] { dna3, dna4 });
+    ((Alignment) al2).createDatasetAlignment();
+    
+    assertTrue(AlignmentUtils.alignAsSameSequences(al1, al2));
+    assertEquals(seq1, al1.getSequenceAt(0).getSequenceAsString());
+    assertEquals(seq2, al1.getSequenceAt(1).getSequenceAsString());
+
+    /*
+     * add another sequence to 'aligned' - should still succeed, since
+     * unaligned sequences still share a dataset with aligned sequences
+     */
+    SequenceI dna5 = new Sequence("dna5", "CCCgggtttAAA");
+    dna5.createDatasetSequence();
+    al2.addSequence(dna5);
+    assertTrue(AlignmentUtils.alignAsSameSequences(al1, al2));
+    assertEquals(seq1, al1.getSequenceAt(0).getSequenceAsString());
+    assertEquals(seq2, al1.getSequenceAt(1).getSequenceAsString());
+
+    /*
+     * add another sequence to 'unaligned' - should fail, since now not
+     * all unaligned sequences share a dataset with aligned sequences
+     */
+    SequenceI dna6 = new Sequence("dna6", "CCCgggtttAAA");
+    dna6.createDatasetSequence();
+    al1.addSequence(dna6);
+    // JAL-2110 JBP Comment: what's the use case for this behaviour ?
+    assertFalse(AlignmentUtils.alignAsSameSequences(al1, al2));
+  }
+
+  @Test(groups = "Functional")
+  public void testAlignAsSameSequencesMultipleSubSeq()
+  {
+    SequenceI dna1 = new Sequence("dna1", "cccGGGTTTaaa");
+    SequenceI dna2 = new Sequence("dna2", "CCCgggtttAAA");
+    SequenceI as1 = dna1.deriveSequence();
+    SequenceI as2 = dna1.deriveSequence().getSubSequence(3, 7);
+    SequenceI as3 = dna2.deriveSequence();
+    as1.insertCharAt(6, 5, '-');
+    String s_as1 = as1.getSequenceAsString();
+    as2.insertCharAt(6, 5, '-');
+    String s_as2 = as2.getSequenceAsString();
+    as3.insertCharAt(6, 5, '-');
+    String s_as3 = as3.getSequenceAsString();
+    AlignmentI aligned = new Alignment(new SequenceI[] { as1, as2, as3 });
+
+    // why do we need to cast this still ?
+    ((Alignment) aligned).createDatasetAlignment();
+    SequenceI uas1 = dna1.deriveSequence();
+    SequenceI uas2 = dna1.deriveSequence().getSubSequence(3, 7);
+    SequenceI uas3 = dna2.deriveSequence();
+    AlignmentI tobealigned = new Alignment(new SequenceI[] { uas1, uas2,
+        uas3 });
+    ((Alignment) tobealigned).createDatasetAlignment();
+
+    assertTrue(AlignmentUtils.alignAsSameSequences(tobealigned, aligned));
+    assertEquals(s_as1, uas1.getSequenceAsString());
+    assertEquals(s_as2, uas2.getSequenceAsString());
+    assertEquals(s_as3, uas3.getSequenceAsString());
+  }
+    
 }
index bbc23e5..62bcae8 100644 (file)
 package jalview.analysis;
 
 import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertFalse;
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertNotSame;
+import static org.testng.AssertJUnit.assertNull;
 import static org.testng.AssertJUnit.assertSame;
+import static org.testng.AssertJUnit.assertTrue;
 
+import jalview.datamodel.AlignedCodonFrame;
+import jalview.datamodel.AlignedCodonFrame.SequenceToSequenceMapping;
+import jalview.datamodel.Alignment;
+import jalview.datamodel.AlignmentI;
 import jalview.datamodel.DBRefEntry;
+import jalview.datamodel.Mapping;
+import jalview.datamodel.Sequence;
+import jalview.datamodel.SequenceFeature;
+import jalview.datamodel.SequenceI;
+import jalview.util.DBRefUtils;
+import jalview.util.MapList;
+import jalview.ws.SequenceFetcher;
+import jalview.ws.SequenceFetcherFactory;
 
+import java.util.ArrayList;
+import java.util.List;
+
+import org.testng.annotations.AfterClass;
 import org.testng.annotations.Test;
 
 public class CrossRefTest
@@ -40,27 +61,674 @@ public class CrossRefTest
     DBRefEntry ref6 = new DBRefEntry("emblCDS", "1", "A123");
     DBRefEntry ref7 = new DBRefEntry("GeneDB", "1", "A123");
     DBRefEntry ref8 = new DBRefEntry("PFAM", "1", "A123");
+    // ENSEMBL is a source of either dna or protein sequence data
+    DBRefEntry ref9 = new DBRefEntry("ENSEMBL", "1", "A123");
     DBRefEntry[] refs = new DBRefEntry[] { ref1, ref2, ref3, ref4, ref5,
-        ref6, ref7, ref8 };
+        ref6, ref7, ref8, ref9 };
 
     /*
      * Just the DNA refs:
      */
-    DBRefEntry[] found = CrossRef.findXDbRefs(false, refs);
-    assertEquals(3, found.length);
+    DBRefEntry[] found = DBRefUtils.selectDbRefs(true, refs);
+    assertEquals(4, found.length);
     assertSame(ref5, found[0]);
     assertSame(ref6, found[1]);
     assertSame(ref7, found[2]);
+    assertSame(ref9, found[3]);
 
     /*
      * Just the protein refs:
      */
-    found = CrossRef.findXDbRefs(true, refs);
-    assertEquals(4, found.length);
+    found = DBRefUtils.selectDbRefs(false, refs);
+    assertEquals(5, found.length);
     assertSame(ref1, found[0]);
     assertSame(ref2, found[1]);
     assertSame(ref3, found[2]);
     assertSame(ref4, found[3]);
+    assertSame(ref9, found[4]);
+  }
+
+  /**
+   * Test the method that finds a sequence's "product" xref source databases,
+   * which may be direct (dbrefs on the sequence), or indirect (dbrefs on
+   * sequences which share a dbref with the sequence
+   */
+  @Test(groups = { "Functional" }, enabled = true)
+  public void testFindXrefSourcesForSequence_proteinToDna()
+  {
+    SequenceI seq = new Sequence("Seq1", "MGKYQARLSS");
+    List<String> sources = new ArrayList<String>();
+    AlignmentI al = new Alignment(new SequenceI[] {});
+
+    /*
+     * first with no dbrefs to search
+     */
+    sources = new CrossRef(new SequenceI[] { seq }, al)
+            .findXrefSourcesForSequences(false);
+    assertTrue(sources.isEmpty());
+
+    /*
+     * add some dbrefs to sequence
+     */
+    // protein db is not a candidate for findXrefSources
+    seq.addDBRef(new DBRefEntry("UNIPROT", "0", "A1234"));
+    // dna coding databatases are
+    seq.addDBRef(new DBRefEntry("EMBL", "0", "E2345"));
+    // a second EMBL xref should not result in a duplicate
+    seq.addDBRef(new DBRefEntry("EMBL", "0", "E2346"));
+    seq.addDBRef(new DBRefEntry("EMBLCDS", "0", "E2347"));
+    seq.addDBRef(new DBRefEntry("GENEDB", "0", "E2348"));
+    seq.addDBRef(new DBRefEntry("ENSEMBL", "0", "E2349"));
+    seq.addDBRef(new DBRefEntry("ENSEMBLGENOMES", "0", "E2350"));
+    sources = new CrossRef(new SequenceI[] { seq }, al)
+            .findXrefSourcesForSequences(false);
+    assertEquals(4, sources.size());
+    assertEquals("[EMBL, EMBLCDS, GENEDB, ENSEMBL]", sources.toString());
+
+    /*
+     * add a sequence to the alignment which has a dbref to UNIPROT|A1234
+     * and others to dna coding databases
+     */
+    sources.clear();
+    seq.setDBRefs(null);
+    seq.addDBRef(new DBRefEntry("UNIPROT", "0", "A1234"));
+    seq.addDBRef(new DBRefEntry("EMBLCDS", "0", "E2347"));
+    SequenceI seq2 = new Sequence("Seq2", "MGKYQARLSS");
+    seq2.addDBRef(new DBRefEntry("UNIPROT", "0", "A1234"));
+    seq2.addDBRef(new DBRefEntry("EMBL", "0", "E2345"));
+    seq2.addDBRef(new DBRefEntry("GENEDB", "0", "E2348"));
+    // TODO include ENSEMBLGENOMES in DBRefSource.DNACODINGDBS ?
+    al.addSequence(seq2);
+    sources = new CrossRef(new SequenceI[] { seq, seq2 }, al)
+            .findXrefSourcesForSequences(false);
+    assertEquals(3, sources.size());
+    assertEquals("[EMBLCDS, EMBL, GENEDB]", sources.toString());
   }
 
+  /**
+   * Test for finding 'product' sequences for the case where only an indirect
+   * xref is found - not on the nucleotide sequence but on a peptide sequence in
+   * the alignment which which it shares a nucleotide dbref
+   */
+  @Test(groups = { "Functional" }, enabled = true)
+  public void testFindXrefSequences_indirectDbrefToProtein()
+  {
+    /*
+     * Alignment setup:
+     *   - nucleotide dbref  EMBL|AF039662
+     *   - peptide    dbrefs EMBL|AF039662, UNIPROT|Q9ZTS2
+     */
+    SequenceI emblSeq = new Sequence("AF039662", "GGGGCAGCACAAGAAC");
+    emblSeq.addDBRef(new DBRefEntry("EMBL", "0", "AF039662"));
+    SequenceI uniprotSeq = new Sequence("Q9ZTS2", "MASVSATMISTS");
+    uniprotSeq.addDBRef(new DBRefEntry("EMBL", "0", "AF039662"));
+    uniprotSeq.addDBRef(new DBRefEntry("UNIPROT", "0", "Q9ZTS2"));
+
+    /*
+     * Find UNIPROT xrefs for nucleotide 
+     * - it has no UNIPROT dbref of its own
+     * - but peptide with matching nucleotide dbref does, so is returned
+     */
+    AlignmentI al = new Alignment(new SequenceI[] { emblSeq, uniprotSeq });
+    Alignment xrefs = new CrossRef(new SequenceI[] { emblSeq }, al)
+            .findXrefSequences("UNIPROT", true);
+    assertEquals(1, xrefs.getHeight());
+    assertSame(uniprotSeq, xrefs.getSequenceAt(0));
+  }
+
+  /**
+   * Test for finding 'product' sequences for the case where only an indirect
+   * xref is found - not on the peptide sequence but on a nucleotide sequence in
+   * the alignment which which it shares a protein dbref
+   */
+  @Test(groups = { "Functional" }, enabled = true)
+  public void testFindXrefSequences_indirectDbrefToNucleotide()
+  {
+    /*
+     * Alignment setup:
+     *   - peptide    dbref  UNIPROT|Q9ZTS2
+     *   - nucleotide dbref  EMBL|AF039662, UNIPROT|Q9ZTS2
+     */
+    SequenceI uniprotSeq = new Sequence("Q9ZTS2", "MASVSATMISTS");
+    uniprotSeq.addDBRef(new DBRefEntry("UNIPROT", "0", "Q9ZTS2"));
+    SequenceI emblSeq = new Sequence("AF039662", "GGGGCAGCACAAGAAC");
+    emblSeq.addDBRef(new DBRefEntry("EMBL", "0", "AF039662"));
+    emblSeq.addDBRef(new DBRefEntry("UNIPROT", "0", "Q9ZTS2"));
+
+    /*
+     * find EMBL xrefs for peptide sequence - it has no direct
+     * dbrefs, but the 'corresponding' nucleotide sequence does, so is returned
+     */
+    /*
+     * Find EMBL xrefs for peptide 
+     * - it has no EMBL dbref of its own
+     * - but nucleotide with matching peptide dbref does, so is returned
+     */
+    AlignmentI al = new Alignment(new SequenceI[] { emblSeq, uniprotSeq });
+    Alignment xrefs = new CrossRef(new SequenceI[] { uniprotSeq }, al)
+            .findXrefSequences("EMBL", false);
+    assertEquals(1, xrefs.getHeight());
+    assertSame(emblSeq, xrefs.getSequenceAt(0));
+  }
+
+  /**
+   * Test for finding 'product' sequences for the case where the selected
+   * sequence has no dbref to the desired source, and there are no indirect
+   * references via another sequence in the alignment
+   */
+  @Test(groups = { "Functional" })
+  public void testFindXrefSequences_noDbrefs()
+  {
+    /*
+     * two nucleotide sequences, one with UNIPROT dbref
+     */
+    SequenceI dna1 = new Sequence("AF039662", "GGGGCAGCACAAGAAC");
+    dna1.addDBRef(new DBRefEntry("UNIPROT", "0", "Q9ZTS2"));
+    SequenceI dna2 = new Sequence("AJ307031", "AAACCCTTT");
+
+    /*
+     * find UNIPROT xrefs for peptide sequence - it has no direct
+     * dbrefs, and the other sequence (which has a UNIPROT dbref) is not 
+     * equatable to it, so no results found
+     */
+    AlignmentI al = new Alignment(new SequenceI[] { dna1, dna2 });
+    Alignment xrefs = new CrossRef(new SequenceI[] { dna2 }, al)
+            .findXrefSequences("UNIPROT", true);
+    assertNull(xrefs);
+  }
+
+  /**
+   * Tests for the method that searches an alignment (with one sequence
+   * excluded) for protein/nucleotide sequences with a given cross-reference
+   */
+  @Test(groups = { "Functional" }, enabled = true)
+  public void testSearchDataset()
+  {
+    /*
+     * nucleotide sequence with UNIPROT AND EMBL dbref
+     * peptide sequence with UNIPROT dbref
+     */
+    SequenceI dna1 = new Sequence("AF039662", "GGGGCAGCACAAGAAC");
+    Mapping map = new Mapping(new Sequence("pep2", "MLAVSRG"), new MapList(
+            new int[] { 1, 21 }, new int[] {
+        1, 7 }, 3, 1));
+    DBRefEntry dbref = new DBRefEntry("UNIPROT", "0", "Q9ZTS2", map);
+    dna1.addDBRef(dbref);
+    dna1.addDBRef(new DBRefEntry("EMBL", "0", "AF039662"));
+    SequenceI pep1 = new Sequence("Q9ZTS2", "MLAVSRGQ");
+    dbref = new DBRefEntry("UNIPROT", "0", "Q9ZTS2");
+    pep1.addDBRef(new DBRefEntry("UNIPROT", "0", "Q9ZTS2"));
+    AlignmentI al = new Alignment(new SequenceI[] { dna1, pep1 });
+
+    List<SequenceI> result = new ArrayList<SequenceI>();
+
+    /*
+     * first search for a dbref nowhere on the alignment:
+     */
+    dbref = new DBRefEntry("UNIPROT", "0", "P30419");
+    CrossRef testee = new CrossRef(al.getSequencesArray(), al);
+    AlignedCodonFrame acf = new AlignedCodonFrame();
+    boolean found = testee.searchDataset(true, dna1, dbref, result, acf,
+            true);
+    assertFalse(found);
+    assertTrue(result.isEmpty());
+    assertTrue(acf.isEmpty());
+
+    /*
+     * search for a protein sequence with dbref UNIPROT:Q9ZTS2
+     */
+    acf = new AlignedCodonFrame();
+    dbref = new DBRefEntry("UNIPROT", "0", "Q9ZTS2");
+    found = testee.searchDataset(!dna1.isProtein(), dna1, dbref, result,
+            acf, false); // search dataset with a protein xref from a dna
+                          // sequence to locate the protein product
+    assertTrue(found);
+    assertEquals(1, result.size());
+    assertSame(pep1, result.get(0));
+    assertTrue(acf.isEmpty());
+
+    /*
+     * search for a nucleotide sequence with dbref UNIPROT:Q9ZTS2
+     */
+    result.clear();
+    acf = new AlignedCodonFrame();
+    dbref = new DBRefEntry("UNIPROT", "0", "Q9ZTS2");
+    found = testee.searchDataset(!pep1.isProtein(), pep1, dbref, result,
+            acf, false); // search dataset with a protein's direct dbref to
+                          // locate dna sequences with matching xref
+    assertTrue(found);
+    assertEquals(1, result.size());
+    assertSame(dna1, result.get(0));
+    // should now have a mapping from dna to pep1
+    List<SequenceToSequenceMapping> mappings = acf.getMappings();
+    assertEquals(1, mappings.size());
+    SequenceToSequenceMapping mapping = mappings.get(0);
+    assertSame(dna1, mapping.getFromSeq());
+    assertSame(pep1, mapping.getMapping().getTo());
+    MapList mapList = mapping.getMapping().getMap();
+    assertEquals(1, mapList.getToRatio());
+    assertEquals(3, mapList.getFromRatio());
+    assertEquals(1, mapList.getFromRanges().size());
+    assertEquals(1, mapList.getFromRanges().get(0)[0]);
+    assertEquals(21, mapList.getFromRanges().get(0)[1]);
+    assertEquals(1, mapList.getToRanges().size());
+    assertEquals(1, mapList.getToRanges().get(0)[0]);
+    assertEquals(7, mapList.getToRanges().get(0)[1]);
+  }
+
+  /**
+   * Test for finding 'product' sequences for the case where the selected
+   * sequence has a dbref with a mapping to a sequence. This represents the case
+   * where either
+   * <ul>
+   * <li>a fetched sequence is already decorated with its cross-reference (e.g.
+   * EMBL + translation), or</li>
+   * <li>Get Cross-References has been done once resulting in instantiated
+   * cross-reference mappings</li>
+   * </ul>
+   */
+  @Test(groups = { "Functional" })
+  public void testFindXrefSequences_fromDbRefMap()
+  {
+    /*
+     * scenario: nucleotide sequence AF039662
+     *   with dbref + mapping to Q9ZTS2 and P30419
+     *     which themselves each have a dbref and feature
+     */
+    SequenceI dna1 = new Sequence("AF039662", "GGGGCAGCACAAGAAC");
+    SequenceI pep1 = new Sequence("Q9ZTS2", "MALFQRSV");
+    SequenceI pep2 = new Sequence("P30419", "MTRRSQIF");
+    dna1.createDatasetSequence();
+    pep1.createDatasetSequence();
+    pep2.createDatasetSequence();
+
+    pep1.getDatasetSequence().addDBRef(
+            new DBRefEntry("Pfam", "0", "PF00111"));
+    pep1.addSequenceFeature(new SequenceFeature("type", "desc", 12, 14, 1f,
+            "group"));
+    pep2.getDatasetSequence().addDBRef(new DBRefEntry("PDB", "0", "3JTK"));
+    pep2.addSequenceFeature(new SequenceFeature("type2", "desc2", 13, 15,
+            12f, "group2"));
+
+    MapList mapList = new MapList(new int[] { 1, 24 }, new int[] { 1, 3 },
+            3, 1);
+    Mapping map = new Mapping(pep1, mapList);
+    DBRefEntry dbRef1 = new DBRefEntry("UNIPROT", "0", "Q9ZTS2", map);
+    dna1.getDatasetSequence().addDBRef(dbRef1);
+    mapList = new MapList(new int[] { 1, 24 }, new int[] { 1, 3 }, 3, 1);
+    map = new Mapping(pep2, mapList);
+    DBRefEntry dbRef2 = new DBRefEntry("UNIPROT", "0", "P30419", map);
+    dna1.getDatasetSequence().addDBRef(dbRef2);
+
+    /*
+     * find UNIPROT xrefs for nucleotide sequence - it should pick up 
+     * mapped sequences
+     */
+    AlignmentI al = new Alignment(new SequenceI[] { dna1 });
+    Alignment xrefs = new CrossRef(new SequenceI[] { dna1 }, al)
+            .findXrefSequences("UNIPROT", true);
+    assertEquals(2, xrefs.getHeight());
+
+    /*
+     * cross-refs alignment holds copies of the mapped sequences
+     * including copies of their dbrefs and features
+     */
+    checkCopySequence(pep1, xrefs.getSequenceAt(0));
+    checkCopySequence(pep2, xrefs.getSequenceAt(1));
+  }
+
+  /**
+   * Helper method that verifies that 'copy' has the same name, start, end,
+   * sequence and dataset sequence object as 'original' (but is not the same
+   * object)
+   * 
+   * @param copy
+   * @param original
+   */
+  private void checkCopySequence(SequenceI copy, SequenceI original)
+  {
+    assertNotSame(copy, original);
+    assertSame(copy.getDatasetSequence(), original.getDatasetSequence());
+    assertEquals(copy.getName(), original.getName());
+    assertEquals(copy.getStart(), original.getStart());
+    assertEquals(copy.getEnd(), original.getEnd());
+    assertEquals(copy.getSequenceAsString(), original.getSequenceAsString());
+  }
+
+  /**
+   * Test for finding 'product' sequences for the case where the selected
+   * sequence has a dbref with no mapping, triggering a fetch from database
+   */
+  @Test(groups = { "Functional" })
+  public void testFindXrefSequences_withFetch()
+  {
+    SequenceI dna1 = new Sequence("AF039662", "GGGGCAGCACAAGAAC");
+    dna1.addDBRef(new DBRefEntry("UNIPROT", "0", "Q9ZTS2"));
+    dna1.addDBRef(new DBRefEntry("UNIPROT", "0", "P30419"));
+    dna1.addDBRef(new DBRefEntry("UNIPROT", "0", "P00314"));
+    final SequenceI pep1 = new Sequence("Q9ZTS2", "MYQLIRSSW");
+    final SequenceI pep2 = new Sequence("P00314", "MRKLLAASG");
+
+    /*
+     * argument false suppresses adding DAS sources
+     * todo: define an interface type SequenceFetcherI and mock that
+     */
+    SequenceFetcher mockFetcher = new SequenceFetcher(false)
+    {
+      @Override
+      public boolean isFetchable(String source)
+      {
+        return true;
+      }
+
+      @Override
+      public SequenceI[] getSequences(List<DBRefEntry> refs, boolean dna)
+      {
+        return new SequenceI[] { pep1, pep2 };
+      }
+    };
+    SequenceFetcherFactory.setSequenceFetcher(mockFetcher);
+
+    /*
+     * find UNIPROT xrefs for nucleotide sequence
+     */
+    AlignmentI al = new Alignment(new SequenceI[] { dna1 });
+    Alignment xrefs = new CrossRef(new SequenceI[] { dna1 }, al)
+            .findXrefSequences("UNIPROT", true);
+    assertEquals(2, xrefs.getHeight());
+    assertSame(pep1, xrefs.getSequenceAt(0));
+    assertSame(pep2, xrefs.getSequenceAt(1));
+  }
+
+  @AfterClass
+  public void tearDown()
+  {
+    SequenceFetcherFactory.setSequenceFetcher(null);
+  }
+
+  /**
+   * Test for finding 'product' sequences for the case where both gene and
+   * transcript sequences have dbrefs to Uniprot.
+   */
+  @Test(groups = { "Functional" })
+  public void testFindXrefSequences_forGeneAndTranscripts()
+  {
+    /*
+     * 'gene' sequence
+     */
+    SequenceI gene = new Sequence("ENSG00000157764", "CGCCTCCCTTCCCC");
+    gene.addDBRef(new DBRefEntry("UNIPROT", "0", "P15056"));
+    gene.addDBRef(new DBRefEntry("UNIPROT", "0", "H7C5K3"));
+
+    /*
+     * 'transcript' with CDS feature (supports mapping to protein)
+     */
+    SequenceI braf001 = new Sequence("ENST00000288602", "taagATGGCGGCGCTGa");
+    braf001.addDBRef(new DBRefEntry("UNIPROT", "0", "P15056"));
+    braf001.addSequenceFeature(new SequenceFeature("CDS", "", 5, 16, 0f,
+            null));
+
+    /*
+     * 'spliced transcript' with CDS ranges
+     */
+    SequenceI braf002 = new Sequence("ENST00000497784", "gCAGGCtaTCTGTTCaa");
+    braf002.addDBRef(new DBRefEntry("UNIPROT", "0", "H7C5K3"));
+    braf002.addSequenceFeature(new SequenceFeature("CDS", "", 2, 6, 0f,
+            null));
+    braf002.addSequenceFeature(new SequenceFeature("CDS", "", 9, 15, 0f,
+            null));
+
+    /*
+     * TODO code is fragile - use of SequenceIdMatcher depends on fetched
+     * sequences having a name starting Source|Accession
+     * which happens to be true for Uniprot,PDB,EMBL but not Pfam,Rfam,Ensembl 
+     */
+    final SequenceI pep1 = new Sequence("UNIPROT|P15056", "MAAL");
+    final SequenceI pep2 = new Sequence("UNIPROT|H7C5K3", "QALF");
+
+    /*
+     * argument false suppresses adding DAS sources
+     * todo: define an interface type SequenceFetcherI and mock that
+     */
+    SequenceFetcher mockFetcher = new SequenceFetcher(false)
+    {
+      @Override
+      public boolean isFetchable(String source)
+      {
+        return true;
+      }
+
+      @Override
+      public SequenceI[] getSequences(List<DBRefEntry> refs, boolean dna)
+      {
+        return new SequenceI[] { pep1, pep2 };
+      }
+    };
+    SequenceFetcherFactory.setSequenceFetcher(mockFetcher);
+
+    /*
+     * find UNIPROT xrefs for gene and transcripts
+     * verify that
+     * - the two proteins are retrieved but not duplicated
+     * - mappings are built from transcript (CDS) to proteins
+     * - no mappings from gene to proteins
+     */
+    SequenceI[] seqs = new SequenceI[] { gene, braf001, braf002 };
+    AlignmentI al = new Alignment(seqs);
+    Alignment xrefs = new CrossRef(seqs, al).findXrefSequences("UNIPROT",
+            true);
+    assertEquals(2, xrefs.getHeight());
+    assertSame(pep1, xrefs.getSequenceAt(0));
+    assertSame(pep2, xrefs.getSequenceAt(1));
+  }
+
+  /**
+   * <pre>
+   * Test that emulates this (real but simplified) case:
+   * Alignment:          DBrefs
+   *     UNIPROT|P0CE19  EMBL|J03321, EMBL|X06707, EMBL|M19487
+   *     UNIPROT|P0CE20  EMBL|J03321, EMBL|X06707, EMBL|X07547
+   * Find cross-references for EMBL. These are mocked here as
+   *     EMBL|J03321     with mappings to P0CE18, P0CE19, P0CE20
+   *     EMBL|X06707     with mappings to P0CE17, P0CE19, P0CE20
+   *     EMBL|M19487     with mappings to P0CE19, Q46432
+   *     EMBL|X07547     with mappings to P0CE20, B0BCM4
+   * EMBL sequences are first 'fetched' (mocked here) for P0CE19.
+   * The 3 EMBL sequences are added to the alignment dataset.
+   * Their dbrefs to Uniprot products P0CE19 and P0CE20 should be matched in the
+   * alignment dataset and updated to reference the original Uniprot sequences.
+   * For the second Uniprot sequence, the J03321 and X06707 xrefs should be 
+   * resolved from the dataset, and only the X07547 dbref fetched.
+   * So the end state to verify is:
+   * - 4 cross-ref sequences returned: J03321, X06707,  M19487, X07547
+   * - P0CE19/20 dbrefs to EMBL sequences now have mappings
+   * - J03321 dbrefs to P0CE19/20 mapped to original Uniprot sequences
+   * - X06707 dbrefs to P0CE19/20 mapped to original Uniprot sequences
+   * </pre>
+   */
+  @Test(groups = { "Functional" })
+  public void testFindXrefSequences_uniprotEmblManyToMany()
+  {
+    /*
+     * Uniprot sequences, both with xrefs to EMBL|J03321 
+     * and EMBL|X07547
+     */
+    SequenceI p0ce19 = new Sequence("UNIPROT|P0CE19", "KPFG");
+    p0ce19.addDBRef(new DBRefEntry("EMBL", "0", "J03321"));
+    p0ce19.addDBRef(new DBRefEntry("EMBL", "0", "X06707"));
+    p0ce19.addDBRef(new DBRefEntry("EMBL", "0", "M19487"));
+    SequenceI p0ce20 = new Sequence("UNIPROT|P0CE20", "PFGK");
+    p0ce20.addDBRef(new DBRefEntry("EMBL", "0", "J03321"));
+    p0ce20.addDBRef(new DBRefEntry("EMBL", "0", "X06707"));
+    p0ce20.addDBRef(new DBRefEntry("EMBL", "0", "X07547"));
+
+    /*
+     * EMBL sequences to be 'fetched', complete with dbrefs and mappings
+     * to their protein products (CDS location  and translations  are provided
+     * in  EMBL XML); these should be matched to, and replaced with,
+     * the corresponding uniprot sequences after fetching
+     */
+
+    /*
+     * J03321 with mappings to P0CE19 and P0CE20
+     */
+    final SequenceI j03321 = new Sequence("EMBL|J03321", "AAACCCTTTGGGAAAA");
+    DBRefEntry dbref1 = new DBRefEntry("UNIPROT", "0", "P0CE19");
+    MapList mapList = new MapList(new int[] { 1, 12 }, new int[] { 1, 4 },
+            3, 1);
+    Mapping map = new Mapping(new Sequence("UNIPROT|P0CE19", "KPFG"),
+            mapList);
+    // add a dbref to the mapped to sequence - should get copied to p0ce19
+    map.getTo().addDBRef(new DBRefEntry("PIR", "0", "S01875"));
+    dbref1.setMap(map);
+    j03321.addDBRef(dbref1);
+    DBRefEntry dbref2 = new DBRefEntry("UNIPROT", "0", "P0CE20");
+    mapList = new MapList(new int[] { 4, 15 }, new int[] { 2, 5 }, 3, 1);
+    dbref2.setMap(new Mapping(new Sequence("UNIPROT|P0CE20", "PFGK"),
+            new MapList(mapList)));
+    j03321.addDBRef(dbref2);
+
+    /*
+     * X06707 with mappings to P0CE19 and P0CE20
+     */
+    final SequenceI x06707 = new Sequence("EMBL|X06707", "atgAAACCCTTTGGG");
+    DBRefEntry dbref3 = new DBRefEntry("UNIPROT", "0", "P0CE19");
+    MapList map2 = new MapList(new int[] { 4, 15 }, new int[] { 1, 4 }, 3,
+            1);
+    dbref3.setMap(new Mapping(new Sequence("UNIPROT|P0CE19", "KPFG"), map2));
+    x06707.addDBRef(dbref3);
+    DBRefEntry dbref4 = new DBRefEntry("UNIPROT", "0", "P0CE20");
+    MapList map3 = new MapList(new int[] { 4, 15 }, new int[] { 1, 4 }, 3,
+            1);
+    dbref4.setMap(new Mapping(new Sequence("UNIPROT|P0CE20", "PFGK"), map3));
+    x06707.addDBRef(dbref4);
+
+    /*
+     * M19487 with mapping to P0CE19 and Q46432
+     */
+    final SequenceI m19487 = new Sequence("EMBL|M19487", "AAACCCTTTGGG");
+    DBRefEntry dbref5 = new DBRefEntry("UNIPROT", "0", "P0CE19");
+    dbref5.setMap(new Mapping(new Sequence("UNIPROT|P0CE19", "KPFG"),
+            new MapList(mapList)));
+    m19487.addDBRef(dbref5);
+    DBRefEntry dbref6 = new DBRefEntry("UNIPROT", "0", "Q46432");
+    dbref6.setMap(new Mapping(new Sequence("UNIPROT|Q46432", "KPFG"),
+            new MapList(mapList)));
+    m19487.addDBRef(dbref6);
+
+    /*
+     * X07547 with mapping to P0CE20 and B0BCM4
+     */
+    final SequenceI x07547 = new Sequence("EMBL|X07547", "cccAAACCCTTTGGG");
+    DBRefEntry dbref7 = new DBRefEntry("UNIPROT", "0", "P0CE20");
+    dbref7.setMap(new Mapping(new Sequence("UNIPROT|P0CE19", "KPFG"),
+            new MapList(map2)));
+    x07547.addDBRef(dbref7);
+    DBRefEntry dbref8 = new DBRefEntry("UNIPROT", "0", "B0BCM4");
+    dbref8.setMap(new Mapping(new Sequence("UNIPROT|B0BCM4", "KPFG"),
+            new MapList(map2)));
+    x07547.addDBRef(dbref8);
+
+    /*
+     * mock sequence fetcher to 'return' the EMBL sequences
+     * TODO: Mockito would allow .thenReturn().thenReturn() here, 
+     * and also capture and verification of the parameters
+     * passed in calls to getSequences() - important to verify that
+     * duplicate sequence fetches are not requested
+     */
+    SequenceFetcher mockFetcher = new SequenceFetcher(false)
+    {
+      int call = 0;
+
+      @Override
+      public boolean isFetchable(String source)
+      {
+        return true;
+      }
+
+      @Override
+      public SequenceI[] getSequences(List<DBRefEntry> refs, boolean dna)
+      {
+        call++;
+        if (call == 1)
+        {
+          assertEquals("Expected 3 embl seqs in first fetch", 3,
+                  refs.size());
+          return new SequenceI[] { j03321, x06707, m19487 };
+        }
+        else
+        {
+          assertEquals("Expected 1 embl seq in second fetch", 1,
+                  refs.size());
+          return new SequenceI[] { x07547 };
+        }
+      }
+    };
+    SequenceFetcherFactory.setSequenceFetcher(mockFetcher);
+
+    /*
+     * find EMBL xrefs for Uniprot seqs and verify that
+     * - the EMBL xref'd sequences are retrieved without duplicates
+     * - mappings are added to the Uniprot dbrefs
+     * - mappings in the EMBL-to-Uniprot dbrefs are updated to the 
+     *   alignment sequences
+     * - dbrefs on the EMBL sequences are added to the original dbrefs
+     */
+    SequenceI[] seqs = new SequenceI[] { p0ce19, p0ce20 };
+    AlignmentI al = new Alignment(seqs);
+    Alignment xrefs = new CrossRef(seqs, al).findXrefSequences("EMBL",
+            false);
+
+    /*
+     * verify retrieved sequences
+     */
+    assertNotNull(xrefs);
+    assertEquals(4, xrefs.getHeight());
+    assertSame(j03321, xrefs.getSequenceAt(0));
+    assertSame(x06707, xrefs.getSequenceAt(1));
+    assertSame(m19487, xrefs.getSequenceAt(2));
+    assertSame(x07547, xrefs.getSequenceAt(3));
+
+    /*
+     * verify mappings added to Uniprot-to-EMBL dbrefs
+     */
+    Mapping mapping = p0ce19.getDBRefs()[0].getMap();
+    assertSame(j03321, mapping.getTo());
+    mapping = p0ce19.getDBRefs()[1].getMap();
+    assertSame(x06707, mapping.getTo());
+    mapping = p0ce20.getDBRefs()[0].getMap();
+    assertSame(j03321, mapping.getTo());
+    mapping = p0ce20.getDBRefs()[1].getMap();
+    assertSame(x06707, mapping.getTo());
+
+    /*
+     * verify dbrefs on EMBL are mapped to alignment seqs
+     */
+    assertSame(p0ce19, j03321.getDBRefs()[0].getMap().getTo());
+    assertSame(p0ce20, j03321.getDBRefs()[1].getMap().getTo());
+    assertSame(p0ce19, x06707.getDBRefs()[0].getMap().getTo());
+    assertSame(p0ce20, x06707.getDBRefs()[1].getMap().getTo());
+
+    /*
+     * verify new dbref on EMBL dbref mapping is copied to the
+     * original Uniprot sequence
+     */
+    assertEquals(4, p0ce19.getDBRefs().length);
+    assertEquals("PIR", p0ce19.getDBRefs()[3].getSource());
+    assertEquals("S01875", p0ce19.getDBRefs()[3].getAccessionId());
+  }
+
+  @Test(groups = "Functional")
+  public void testSameSequence()
+  {
+    assertTrue(CrossRef.sameSequence(null, null));
+    SequenceI seq1 = new Sequence("seq1", "ABCDEF");
+    assertFalse(CrossRef.sameSequence(seq1, null));
+    assertFalse(CrossRef.sameSequence(null, seq1));
+    assertTrue(CrossRef.sameSequence(seq1, new Sequence("seq2", "ABCDEF")));
+    assertTrue(CrossRef.sameSequence(seq1, new Sequence("seq2", "abcdef")));
+    assertFalse(CrossRef
+            .sameSequence(seq1, new Sequence("seq2", "ABCDE-F")));
+    assertFalse(CrossRef.sameSequence(seq1, new Sequence("seq2", "BCDEF")));
+  }
 }
index 13dae11..31c9839 100644 (file)
@@ -29,6 +29,7 @@ import jalview.datamodel.AlignedCodon;
 import jalview.datamodel.Alignment;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.ColumnSelection;
+import jalview.datamodel.Sequence;
 import jalview.datamodel.SequenceI;
 import jalview.gui.AlignViewport;
 import jalview.io.DataSourceType;
@@ -500,17 +501,44 @@ public class DnaTest
   @Test(groups = "Functional")
   public void testReverseSequence()
   {
-    String seq = "AcGtUrYkMbVdHNX";
+    String seq = "-Ac-GtU--rYkMbVdHNX-";
+    String seqRev = new StringBuilder(seq).reverse().toString();
 
     // reverse:
     SequenceI reversed = Dna.reverseSequence("Seq1", seq, false);
-    assertEquals(new StringBuilder(seq).reverse()
-            .toString(), reversed.getSequenceAsString());
+    assertEquals(1, reversed.getStart());
+    assertEquals(15, reversed.getEnd());
+    assertEquals(20, reversed.getLength());
+    assertEquals(seqRev, reversed.getSequenceAsString());
     assertEquals("Seq1|rev", reversed.getName());
 
     // reverse complement:
     SequenceI revcomp = Dna.reverseSequence("Seq1", seq, true);
-    assertEquals("XNDhBvKmRyAaCgT", revcomp.getSequenceAsString());
+    assertEquals("-XNDhBvKmRy--AaC-gT-", revcomp.getSequenceAsString());
     assertEquals("Seq1|revcomp", revcomp.getName());
   }
+
+  @Test(groups = "Functional")
+  public void testReverseCdna()
+  {
+    String seq = "-Ac-GtU--rYkMbVdHNX-";
+    String seqRev = new StringBuilder(seq).reverse().toString();
+    String seqDs = seq.replaceAll("-", "");
+    String seqDsRev = new StringBuilder(seqDs).reverse().toString();
+
+    SequenceI dna = new Sequence("Seq1", seq);
+    Alignment al = new Alignment(new SequenceI[] {dna});
+    al.createDatasetAlignment();
+    assertEquals(seqDs, al.getSequenceAt(0).getDatasetSequence()
+            .getSequenceAsString());
+
+    ColumnSelection cs = new ColumnSelection();
+    AlignViewportI av = new AlignViewport(al, cs);
+    Dna testee = new Dna(av, new int[] { 0, al.getWidth() - 1 });
+    AlignmentI reversed = testee.reverseCdna(false);
+    assertEquals(1, reversed.getHeight());
+    assertEquals(seqRev, reversed.getSequenceAt(0).getSequenceAsString());
+    assertEquals(seqDsRev, reversed.getSequenceAt(0).getDatasetSequence()
+            .getSequenceAsString());
+  }
 }
index 55823e4..df39b81 100644 (file)
@@ -27,7 +27,6 @@ import jalview.datamodel.Sequence;
 import jalview.datamodel.SequenceGroup;
 import jalview.datamodel.SequenceI;
 
-import java.util.ArrayList;
 import java.util.Arrays;
 
 import org.testng.AssertJUnit;
@@ -45,21 +44,26 @@ public class GroupingTest
 
   Sequence s5 = new Sequence("s5", "AAAADDEDTTEE");
 
-  SequenceGroup sg1 = new SequenceGroup(Arrays.asList(new SequenceI[] { s1,
+  SequenceGroup sg_12 = new SequenceGroup(Arrays.asList(new SequenceI[] { s1,
       s2 }), "Group1", null, false, false, false, 0, 5);
 
-  SequenceGroup sg2 = new SequenceGroup(Arrays.asList(new SequenceI[] { s3,
+  SequenceGroup sg_345 = new SequenceGroup(Arrays.asList(new SequenceI[] { s3,
       s4, s5 }), "Group2", null, false, false, false, 0, 5);
 
   AlignmentI alignment = new Alignment(
           new SequenceI[] { s1, s2, s3, s4, s5 });
 
-  int[] positions = new int[] { 1, 7, 9 };
+  /*
+   * test for the case where column selections are not added in
+   * left to right order
+   */
+  int[] positions = new int[] { 7, 9, 1 };
 
   @Test(groups = { "Functional" })
   public void testMakeGroupsWithBoth()
   {
-    ArrayList<String> str = new ArrayList<String>();
+    String[] str = new String[alignment.getHeight()];
+    int seq = 0;
     for (SequenceI s : alignment.getSequences())
     {
       StringBuilder sb = new StringBuilder();
@@ -67,12 +71,12 @@ public class GroupingTest
       {
         sb.append(s.getCharAt(p));
       }
-      str.add(sb.toString());
+      str[seq++] = sb.toString();
     }
     SequenceGroup[] seqgroupsString = Grouping.makeGroupsFrom(
-            alignment.getSequencesArray(),
-            str.toArray(new String[str.size()]),
-            Arrays.asList(new SequenceGroup[] { sg1, sg2 }));
+            alignment.getSequencesArray(), str,
+            Arrays.asList(new SequenceGroup[] { sg_12, sg_345 }));
+
     ColumnSelection cs = new ColumnSelection();
     for (int p : positions)
     {
@@ -80,7 +84,7 @@ public class GroupingTest
     }
     SequenceGroup[] seqgroupsColSel = Grouping.makeGroupsFromCols(
             alignment.getSequencesArray(), cs,
-            Arrays.asList(new SequenceGroup[] { sg1, sg2 }));
+            Arrays.asList(new SequenceGroup[] { sg_12, sg_345 }));
     AssertJUnit
             .assertEquals(seqgroupsString.length, seqgroupsColSel.length);
     for (int p = 0; p < seqgroupsString.length; p++)
index 5801437..f33525f 100644 (file)
@@ -21,6 +21,9 @@
 package jalview.analysis;
 
 import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertFalse;
+import static org.testng.AssertJUnit.assertNull;
+import static org.testng.AssertJUnit.assertTrue;
 import static org.testng.AssertJUnit.fail;
 
 import jalview.analysis.SecStrConsensus.SimpleBP;
@@ -35,11 +38,12 @@ public class RnaTest
   public void testGetSimpleBPs() throws WUSSParseException
   {
     String rna = "([{})]"; // JAL-1081 example
-    Vector<SimpleBP> bps = Rna.GetSimpleBPs(rna);
+    Vector<SimpleBP> bps = Rna.getSimpleBPs(rna);
     assertEquals(3, bps.size());
 
     /*
      * the base pairs are added in the order in which the matching base is found
+     * (popping the stack of unmatched opening brackets)
      */
     assertEquals(2, bps.get(0).bp5); // {
     assertEquals(3, bps.get(0).bp3); // }
@@ -55,25 +59,221 @@ public class RnaTest
     String rna = "(([{})]";
     try
     {
-      Rna.GetSimpleBPs(rna);
+      Rna.getSimpleBPs(rna);
       fail("expected exception");
     } catch (WUSSParseException e)
     {
-      // expected
+      // error reported as after end of input string
+      assertEquals(rna.length(), e.getProblemPos());
     }
   }
 
   @Test(groups = { "Functional" })
   public void testGetSimpleBPs_unmatchedCloser()
   {
-    String rna = "([{})]]";
+    String rna = "([{})]]]";
     try
     {
-      Rna.GetSimpleBPs(rna);
+      Rna.getSimpleBPs(rna);
       fail("expected exception");
     } catch (WUSSParseException e)
     {
-      // expected
+      // error reported as at first unmatched close
+      assertEquals(6, e.getProblemPos());
+    }
+
+    /*
+     * a variant where we have no opening bracket of the same type
+     * as the unmatched closing bracket (no stack rather than empty stack)
+     */
+    rna = "((()])";
+    try
+    {
+      Rna.getSimpleBPs(rna);
+      fail("expected exception");
+    } catch (WUSSParseException e)
+    {
+      assertEquals(4, e.getProblemPos());
+    }
+  }
+
+  @Test(groups = { "Functional" })
+  public void testGetRNASecStrucState()
+  {
+    assertNull(Rna.getRNASecStrucState(null));
+    for (int i = 0; i <= 255; i++)
+    {
+      String s = String.valueOf((char) i);
+      String ss = Rna.getRNASecStrucState(s);
+  
+      /*
+       * valid SS chars are a-z, A-Z, and various brackets;
+       * anything else is returned as a space
+       */
+      if ((i >= 'a' && i <= 'z') || (i >= 'A' && i <= 'Z')
+              || "()[]{}<>".indexOf(s) > -1)
+      {
+        assertEquals("" + i, s, ss);
+      }
+      else
+      {
+        assertEquals(" ", ss);
+      }
+    }
+  
+    /*
+     * a string is processed character by character
+     */
+    assertEquals("a [K ]z} {Q b(w)p><i",
+            Rna.getRNASecStrucState("a.[K-]z}?{Q b(w)p><i"));
+  }
+
+  /**
+   * Tests for isClosingParenthesis with char or String argument
+   */
+  @Test(groups = { "Functional" })
+  public void testIsClosingParenthesis()
+  {
+    assertFalse(Rna.isClosingParenthesis(null));
+
+    /*
+     * only a-z, )]}> are closing bracket symbols
+     */
+    for (int i = 0; i <= 255; i++)
+    {
+      boolean isClosingChar = Rna.isClosingParenthesis((char) i);
+      boolean isClosingString = Rna.isClosingParenthesis(String
+              .valueOf((char) i));
+      if ((i >= 'a' && i <= 'z') || i == ')' || i == '}' || i == ']'
+              || i == '>')
+      {
+        assertTrue(String.format("close base pair %c", i), isClosingChar);
+        assertTrue(String.format("close base pair %c", i), isClosingString);
+      }
+      else
+      {
+        assertFalse(String.format("close base pair %c", i), isClosingChar);
+        assertFalse(String.format("close base pair %c", i), isClosingString);
+      }
+      assertFalse(Rna.isClosingParenthesis(String.valueOf((char) i) + " "));
+    }
+  }
+
+  @Test(groups = { "Functional" })
+  public void testIsCanonicalOrWobblePair()
+  {
+    String bases = "acgtuACGTU";
+    for (int i = 0; i < bases.length(); i++)
+    {
+      for (int j = 0; j < bases.length(); j++)
+      {
+        char first = bases.charAt(i);
+        char second = bases.charAt(j);
+        boolean result = Rna.isCanonicalOrWobblePair(first, second);
+        String pair = new String(new char[] { first, second })
+                .toUpperCase();
+        if (pair.equals("AT") || pair.equals("TA") || pair.equals("AU")
+                || pair.equals("UA") || pair.equals("GC")
+                || pair.equals("CG") || pair.equals("GT")
+                || pair.equals("TG") || pair.equals("GU")
+                || pair.equals("UG"))
+        {
+          assertTrue(pair + " should be valid", result);
+        }
+        else
+        {
+          assertFalse(pair + " should be invalid", result);
+        }
+      }
+    }
+  }
+
+  /**
+   * Tests for isOpeningParenthesis with char or String argument
+   */
+  @Test(groups = { "Functional" })
+  public void testIsOpeningParenthesis()
+  {
+    /*
+     * only A-Z, ([{< are opening bracket symbols
+     */
+    for (int i = 0; i <= 255; i++)
+    {
+      boolean isOpeningChar = Rna.isOpeningParenthesis((char) i);
+      boolean isOpeningString = Rna.isOpeningParenthesis(String
+              .valueOf((char) i));
+      if ((i >= 'A' && i <= 'Z') || i == '(' || i == '{' || i == '['
+              || i == '<')
+      {
+        assertTrue(String.format("Open base pair %c", i), isOpeningChar);
+        assertTrue(String.format("Open base pair %c", i), isOpeningString);
+      }
+      else
+      {
+        assertFalse(String.format("Open base pair %c", i), isOpeningChar);
+        assertFalse(String.format("Open base pair %c", i), isOpeningString);
+      }
+      assertFalse(Rna.isOpeningParenthesis(String.valueOf((char) i) + " "));
+    }
+  }
+
+  @Test(groups = { "Functional" })
+  public void testGetMatchingOpeningParenthesis() throws WUSSParseException
+  {
+    for (int i = 0; i <= 255; i++)
+    {
+      boolean isClosing = Rna.isClosingParenthesis((char) i);
+      if (isClosing)
+      {
+        char opening = Rna.getMatchingOpeningParenthesis((char) i);
+        if (i >= 'a' && i <= 'z')
+        {
+          assertEquals(i + 'A' - 'a', opening);
+        }
+        else if (i == ')' && opening == '(' || i == ']' && opening == '['
+                || i == '}' && opening == '{' || i == '>' && opening == '<')
+        {
+          // ok
+        }
+        else
+        {
+          fail("Got " + opening + " as opening bracket pair for "
+                  + ((char) i));
+        }
+      }
+    }
+  }
+
+  /**
+   * Tests for isRnaSecondaryStructureSymbol with char or String argument
+   */
+  @Test(groups = { "Functional" })
+  public void testIsRnaSecondaryStructureSymbol()
+  {
+    assertFalse(Rna.isRnaSecondaryStructureSymbol(null));
+  
+    /*
+     * only A-Z,  a-z, ()[]{}<> are valid symbols
+     */
+    for (int i = 0; i <= 255; i++)
+    {
+      boolean isValidChar = Rna.isRnaSecondaryStructureSymbol((char) i);
+      boolean isValidString = Rna.isRnaSecondaryStructureSymbol(String
+              .valueOf((char) i));
+      if ((i >= 'A' && i <= 'Z') || (i >= 'a' && i <= 'z') || i == '('
+              || i == ')' || i == '{' || i == '}' || i == '[' || i == ']'
+              || i == '<' || i == '>')
+      {
+        assertTrue(String.format("close base pair %c", i), isValidChar);
+        assertTrue(String.format("close base pair %c", i), isValidString);
+      }
+      else
+      {
+        assertFalse(String.format("close base pair %c", i), isValidChar);
+        assertFalse(String.format("close base pair %c", i), isValidString);
+      }
+      assertFalse(Rna.isRnaSecondaryStructureSymbol(String
+              .valueOf((char) i) + " "));
     }
   }
 }
index 9d3e3b6..a17270d 100644 (file)
@@ -90,5 +90,11 @@ public class SequenceIdMatcherTest
      * case insensitive matching
      */
     assertTrue(testee.equals("a12345"));
+
+    testee = sequenceIdMatcher.new SeqIdName("UNIPROT|A12345");
+    assertFalse(testee.equals("A12345"));
+    assertFalse(testee.equals("UNIPROT|B98765"));
+    assertFalse(testee.equals("UNIPROT|"));
+    assertTrue(testee.equals("UNIPROT"));
   }
 }
diff --git a/test/jalview/bin/CacheTest.java b/test/jalview/bin/CacheTest.java
new file mode 100644 (file)
index 0000000..a37370f
--- /dev/null
@@ -0,0 +1,48 @@
+package jalview.bin;
+
+import static org.testng.AssertJUnit.assertEquals;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.Locale;
+
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+public class CacheTest
+{
+  private Locale locale;
+
+  @BeforeClass(alwaysRun = true)
+  public void setUpBeforeClass()
+  {
+    locale = Locale.getDefault();
+  }
+
+  @AfterClass(alwaysRun = true)
+  public void tearDownAfterClass()
+  {
+    Locale.setDefault(locale);
+  }
+
+  /**
+   * Test that saved date format does not vary with current locale
+   */
+  @Test(groups = "Functional")
+  public void testSetDateProperty()
+  {
+    Date now = new Date();
+    Locale.setDefault(Locale.FRENCH);
+    String formattedDate = Cache.setDateProperty("test", now);
+    Locale.setDefault(Locale.UK);
+    String formattedDate2 = Cache.setDateProperty("test", now);
+    assertEquals(formattedDate, formattedDate2);
+
+    // currently using Locale.UK to format dates:
+    assertEquals(
+            formattedDate2,
+            SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.MEDIUM,
+                    SimpleDateFormat.MEDIUM, Locale.UK).format(now));
+  }
+}
diff --git a/test/jalview/controller/AlignViewControllerTest.java b/test/jalview/controller/AlignViewControllerTest.java
new file mode 100644 (file)
index 0000000..3eefada
--- /dev/null
@@ -0,0 +1,100 @@
+package jalview.controller;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertTrue;
+
+import jalview.datamodel.Sequence;
+import jalview.datamodel.SequenceFeature;
+import jalview.datamodel.SequenceGroup;
+import jalview.datamodel.SequenceI;
+
+import java.util.BitSet;
+
+import org.testng.annotations.Test;
+
+public class AlignViewControllerTest
+{
+  @Test(groups = "Functional")
+  public void testFindColumnsWithFeature()
+  {
+    SequenceI seq1 = new Sequence("seq1", "aMMMaaaaaaaaaaaaaaaa");
+    SequenceI seq2 = new Sequence("seq2", "aaaMMMMMMMaaaaaaaaaa");
+    SequenceI seq3 = new Sequence("seq3", "aaaaaaaaaaMMMMMaaaaa");
+    SequenceI seq4 = new Sequence("seq3", "aaaaaaaaaaaaaaaaaaaa");
+
+    /*
+     * features start/end are base 1
+     */
+    seq1.addSequenceFeature(new SequenceFeature("Metal", "desc", 2, 4, 0f,
+            null));
+    seq1.addSequenceFeature(new SequenceFeature("Helix", "desc", 1, 15, 0f,
+            null));
+    seq2.addSequenceFeature(new SequenceFeature("Metal", "desc", 4, 10, 0f,
+            null));
+    seq3.addSequenceFeature(new SequenceFeature("Metal", "desc", 11, 15,
+            0f, null));
+
+    /*
+     * select the first three columns --> Metal in seq1 2-3
+     */
+    SequenceGroup sg = new SequenceGroup();
+    sg.setStartRes(0); // base 0
+    sg.setEndRes(2);
+    sg.addSequence(seq1, false);
+    sg.addSequence(seq2, false);
+    sg.addSequence(seq3, false);
+    sg.addSequence(seq4, false);
+
+    BitSet bs = new BitSet();
+    int seqCount = AlignViewController.findColumnsWithFeature("Metal", sg,
+            bs);
+    assertEquals(1, seqCount);
+    assertEquals(2, bs.cardinality());
+    assertTrue(bs.get(1));
+    assertTrue(bs.get(2));
+    
+    /*
+     * select the first four columns: Metal in seq1 2:4, seq2 4:4
+     */
+    sg.setEndRes(3);
+    bs.clear();
+    seqCount = AlignViewController.findColumnsWithFeature("Metal", sg,
+            bs);
+    assertEquals(2, seqCount);
+    assertEquals(3, bs.cardinality());
+    assertTrue(bs.get(1));
+    assertTrue(bs.get(2));
+    assertTrue(bs.get(3));
+
+    /*
+     * select column 11: Metal in seq3 only
+     */
+    sg.setStartRes(10);
+    sg.setEndRes(10);
+    bs.clear();
+    seqCount = AlignViewController.findColumnsWithFeature("Metal", sg, bs);
+    assertEquals(1, seqCount);
+    assertEquals(1, bs.cardinality());
+    assertTrue(bs.get(10));
+
+    /*
+     * select columns 16-20: no Metal feature
+     */
+    sg.setStartRes(15);
+    sg.setEndRes(19);
+    bs.clear();
+    seqCount = AlignViewController.findColumnsWithFeature("Metal", sg, bs);
+    assertEquals(0, seqCount);
+    assertEquals(0, bs.cardinality());
+
+    /*
+     * look for a feature that isn't there
+     */
+    sg.setStartRes(0);
+    sg.setEndRes(19);
+    bs.clear();
+    seqCount = AlignViewController.findColumnsWithFeature("Pfam", sg, bs);
+    assertEquals(0, seqCount);
+    assertEquals(0, bs.cardinality());
+  }
+}
index cd8a1e3..f2dd968 100644 (file)
@@ -451,4 +451,30 @@ public class AlignedCodonFrameTest
     assertArrayEquals(new int[] { 2, 2 },
             acf.getMappedRegion(seq2, seq1, 6));
   }
+
+  /**
+   * Tests for addMap. See also tests for MapList.addMapList
+   */
+  @Test(groups = { "Functional" })
+  public void testAddMap()
+  {
+    final Sequence seq1 = new Sequence("Seq1", "c-G-TA-gC-gT-T");
+    seq1.createDatasetSequence();
+    final Sequence aseq1 = new Sequence("Seq1", "-V-L");
+    aseq1.createDatasetSequence();
+  
+    AlignedCodonFrame acf = new AlignedCodonFrame();
+    MapList map = new MapList(new int[] { 2, 4, 6, 6, 8, 9 }, new int[] {
+        1, 2 }, 3, 1);
+    acf.addMap(seq1.getDatasetSequence(), aseq1.getDatasetSequence(), map);
+    assertEquals(1, acf.getMappingsFromSequence(seq1).size());
+    Mapping before = acf.getMappingsFromSequence(seq1).get(0);
+
+    /*
+     * add the same map again, verify it doesn't get duplicated
+     */
+    acf.addMap(seq1.getDatasetSequence(), aseq1.getDatasetSequence(), map);
+    assertEquals(1, acf.getMappingsFromSequence(seq1).size());
+    assertSame(before, acf.getMappingsFromSequence(seq1).get(0));
+  }
 }
index 4041825..fb02166 100644 (file)
@@ -222,4 +222,65 @@ public class AlignmentAnnotationTests
     assertEquals(1, ann.annotations[1].value, 0.001);
     assertEquals(2, ann.annotations[2].value, 0.001);
   }
+
+  /**
+   * Test the method that defaults rna symbol to the one matching the preceding
+   * unmatched opening bracket (if any)
+   */
+  @Test(groups = { "Functional" })
+  public void testGetDefaultRnaHelixSymbol()
+  {
+    AlignmentAnnotation ann = new AlignmentAnnotation("SS",
+            "secondary structure", null);
+    assertEquals("(", ann.getDefaultRnaHelixSymbol(4));
+
+    Annotation[] anns = new Annotation[20];
+    ann.annotations = anns;
+    assertEquals("(", ann.getDefaultRnaHelixSymbol(4));
+
+    anns[1] = new Annotation("(", "S", '(', 0f);
+    assertEquals("(", ann.getDefaultRnaHelixSymbol(0));
+    assertEquals("(", ann.getDefaultRnaHelixSymbol(1));
+    assertEquals(")", ann.getDefaultRnaHelixSymbol(2));
+    assertEquals(")", ann.getDefaultRnaHelixSymbol(3));
+
+    /*
+     * .(.[.{.<.}.>.).].
+     */
+    anns[1] = new Annotation("(", "S", '(', 0f);
+    anns[3] = new Annotation("[", "S", '[', 0f);
+    anns[5] = new Annotation("{", "S", '{', 0f);
+    anns[7] = new Annotation("<", "S", '<', 0f);
+    anns[9] = new Annotation("}", "S", '}', 0f);
+    anns[11] = new Annotation(">", "S", '>', 0f);
+    anns[13] = new Annotation(")", "S", ')', 0f);
+    anns[15] = new Annotation("]", "S", ']', 0f);
+
+    String expected = "(())]]}}>>>>]]]](";
+    for (int i = 0; i < expected.length(); i++)
+    {
+      assertEquals("column " + i, String.valueOf(expected.charAt(i)),
+              ann.getDefaultRnaHelixSymbol(i));
+    }
+
+    /*
+     * .(.[.(.).{.}.<.].D.
+     */
+    anns[1] = new Annotation("(", "S", '(', 0f);
+    anns[3] = new Annotation("[", "S", '[', 0f);
+    anns[5] = new Annotation("(", "S", '(', 0f);
+    anns[7] = new Annotation(")", "S", ')', 0f);
+    anns[9] = new Annotation("{", "S", '{', 0f);
+    anns[11] = new Annotation("}", "S", '}', 0f);
+    anns[13] = new Annotation("<", "S", '>', 0f);
+    anns[15] = new Annotation("]", "S", ']', 0f);
+    anns[17] = new Annotation("D", "S", 'D', 0f);
+
+    expected = "(())]]))]]}}]]>>>>dd";
+    for (int i = 0; i < expected.length(); i++)
+    {
+      assertEquals("column " + i, String.valueOf(expected.charAt(i)),
+              ann.getDefaultRnaHelixSymbol(i));
+    }
+  }
 }
index 4dcf536..756bf71 100644 (file)
@@ -219,7 +219,7 @@ public class AlignmentTest
    * 
    * @throws IOException
    */
-  @Test(groups = { "Functional" }, enabled = false)
+  @Test(groups = { "Functional" }, enabled = true)
   // TODO review / update this test after redesign of alignAs method
   public void testAlignAs_cdnaAsProtein() throws IOException
   {
@@ -234,7 +234,7 @@ public class AlignmentTest
      * Realign DNA; currently keeping existing gaps in introns only
      */
     ((Alignment) al1).alignAs(al2, false, true);
-    assertEquals("ACG---GCUCCA------ACT", al1.getSequenceAt(0)
+    assertEquals("ACG---GCUCCA------ACT---", al1.getSequenceAt(0)
             .getSequenceAsString());
     assertEquals("---CGT---TAACGA---AGT---", al1.getSequenceAt(1)
             .getSequenceAsString());
@@ -245,7 +245,7 @@ public class AlignmentTest
    * 
    * @throws IOException
    */
-  @Test(groups = { "Functional" }, enabled = false)
+  @Test(groups = { "Functional" }, enabled = true)
   // TODO review / update this test after redesign of alignAs method
   public void testAlignAs_cdnaAsProtein_singleSequence() throws IOException
   {
@@ -317,7 +317,12 @@ public class AlignmentTest
       acf.addMap(seqFrom, seqTo, ml);
     }
 
+    /*
+     * not sure whether mappings 'belong' or protein or nucleotide
+     * alignment, so adding to both ;~)
+     */
     alFrom.addCodonFrame(acf);
+    alTo.addCodonFrame(acf);
   }
 
   /**
@@ -400,6 +405,8 @@ public class AlignmentTest
     // TODO should the copy constructor copy the dataset?
     // or make a new one referring to the same dataset sequences??
     assertNull(copy.getDataset());
+    // TODO test metadata is copied when AlignmentI is a dataset
+
     // assertArrayEquals(copy.getDataset().getSequencesArray(), protein
     // .getDataset().getSequencesArray());
   }
@@ -438,8 +445,7 @@ public class AlignmentTest
     // TODO promote this method to AlignmentI
     ((Alignment) protein).createDatasetAlignment();
 
-    // TODO this method should return AlignmentI not Alignment !!
-    Alignment ds = protein.getDataset();
+    AlignmentI ds = protein.getDataset();
 
     // side-effect: dataset created on second sequence
     assertNotNull(protein.getSequenceAt(1).getDatasetSequence());
index 1a7ae32..e59719c 100644 (file)
@@ -22,10 +22,12 @@ package jalview.datamodel;
 
 import static org.testng.AssertJUnit.assertEquals;
 import static org.testng.AssertJUnit.assertFalse;
+import static org.testng.AssertJUnit.assertNotSame;
 import static org.testng.AssertJUnit.assertSame;
 import static org.testng.AssertJUnit.assertTrue;
 
 import java.util.Arrays;
+import java.util.BitSet;
 import java.util.List;
 
 import org.testng.annotations.Test;
@@ -66,6 +68,9 @@ public class ColumnSelectionTest
 
     // removing an element in the list removes it
     cs.removeElement(2);
+    // ...but not from the copy list!
+    assertEquals(2, sel.size());
+    sel = cs.getSelected();
     assertEquals(1, sel.size());
     assertEquals(new Integer(5), sel.get(0));
   }
@@ -325,10 +330,14 @@ public class ColumnSelectionTest
    * this fails, HideSelectedColumns may also fail
    */
   @Test(groups = { "Functional" })
-  public void testgetSelectedRanges()
+  public void testGetSelectedRanges()
   {
+    /*
+     * getSelectedRanges returns ordered columns regardless
+     * of the order in which they are added
+     */
     ColumnSelection cs = new ColumnSelection();
-    int[] sel = { 2, 3, 4, 7, 8, 9, 20, 21, 22 };
+    int[] sel = { 4, 3, 7, 21, 9, 20, 8, 22, 2 };
     for (int col : sel)
     {
       cs.addElement(col);
@@ -527,4 +536,137 @@ public class ColumnSelectionTest
     cs.addElement(88);
     assertTrue(cs.equals(cs2));
   }
+
+  /**
+   * Test the method that returns selected columns, in the order in which they
+   * were added
+   */
+  @Test(groups = { "Functional" })
+  public void testGetSelection()
+  {
+    ColumnSelection cs = new ColumnSelection();
+    int[] sel = { 4, 3, 7, 21 };
+    for (int col : sel)
+    {
+      cs.addElement(col);
+    }
+
+    List<Integer> selected1 = cs.getSelected();
+    assertEquals(4, selected1.size());
+
+    /*
+     * getSelected returns a copy, verify the list
+     * is externally immutable
+     */
+    selected1.clear();
+    List<Integer> selected2 = cs.getSelected();
+    assertNotSame(selected1, selected2);
+    assertEquals(4, selected2.size());
+    int i = 0;
+    for (int col : sel)
+    {
+      assertEquals(col, selected2.get(i++).intValue());
+    }
+
+    cs.removeElement(7);
+    cs.addElement(1);
+    cs.removeElement(4);
+
+    List<Integer> selected3 = cs.getSelected();
+    assertEquals(3, selected3.size());
+    assertEquals(3, selected3.get(0).intValue());
+    assertEquals(21, selected3.get(1).intValue());
+    assertEquals(1, selected3.get(2).intValue());
+  }
+
+  @Test(groups = "Functional")
+  public void testMarkColumns()
+  {
+    ColumnSelection cs = new ColumnSelection();
+    cs.addElement(5); // this will be cleared
+    BitSet toMark = new BitSet();
+    toMark.set(1);
+    toMark.set(3);
+    toMark.set(6);
+    toMark.set(9);
+
+    assertTrue(cs.markColumns(toMark, 3, 8, false, false, false));
+    List<Integer> selected = cs.getSelected();
+    assertEquals(2, selected.size());
+    assertTrue(selected.contains(3));
+    assertTrue(selected.contains(6));
+  }
+
+  @Test(groups = "Functional")
+  public void testMarkColumns_extend()
+  {
+    ColumnSelection cs = new ColumnSelection();
+    cs.addElement(1);
+    cs.addElement(5);
+    BitSet toMark = new BitSet();
+    toMark.set(1);
+    toMark.set(3);
+    toMark.set(6);
+    toMark.set(9);
+
+    /*
+     * extending selection of {3, 6} should leave {1, 3, 5, 6} selected
+     */
+    assertTrue(cs.markColumns(toMark, 3, 8, false, true, false));
+    List<Integer> selected = cs.getSelected();
+    assertEquals(4, selected.size());
+    assertTrue(selected.contains(1));
+    assertTrue(selected.contains(3));
+    assertTrue(selected.contains(5));
+    assertTrue(selected.contains(6));
+  }
+
+  @Test(groups = "Functional")
+  public void testMarkColumns_invert()
+  {
+    ColumnSelection cs = new ColumnSelection();
+    cs.addElement(5); // this will be cleared
+    BitSet toMark = new BitSet();
+    toMark.set(1);
+    toMark.set(3);
+    toMark.set(6);
+    toMark.set(9);
+
+    /*
+     * inverted selection of {3, 6} should select {4, 5, 7, 8}
+     */
+    assertTrue(cs.markColumns(toMark, 3, 8, true, false, false));
+    List<Integer> selected = cs.getSelected();
+    assertEquals(4, selected.size());
+    assertTrue(selected.contains(4));
+    assertTrue(selected.contains(5));
+    assertTrue(selected.contains(7));
+    assertTrue(selected.contains(8));
+  }
+
+  @Test(groups = "Functional")
+  public void testMarkColumns_toggle()
+  {
+    ColumnSelection cs = new ColumnSelection();
+    cs.addElement(1); // outside change range
+    cs.addElement(3);
+    cs.addElement(4);
+    cs.addElement(10); // outside change range
+    BitSet toMark = new BitSet();
+    toMark.set(1);
+    toMark.set(3);
+    toMark.set(6);
+    toMark.set(9);
+
+    /*
+     * toggling state of {3, 6} should leave {1, 4, 6, 10} selected
+     */
+    assertTrue(cs.markColumns(toMark, 3, 8, false, false, true));
+    List<Integer> selected = cs.getSelected();
+    assertEquals(4, selected.size());
+    assertTrue(selected.contains(1));
+    assertTrue(selected.contains(4));
+    assertTrue(selected.contains(6));
+    assertTrue(selected.contains(10));
+  }
 }
index 3131ad7..b326d90 100644 (file)
@@ -21,6 +21,7 @@
 package jalview.datamodel;
 
 import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertSame;
 
 import jalview.util.MapList;
 
@@ -75,4 +76,18 @@ public class MappingTest
     m = new Mapping(seq, fk);
     assertEquals("[ [1, 6] [8, 13] ] 3:1 to [ [4, 7] ] Seq1", m.toString());
   }
+
+  @Test(groups = { "Functional" })
+  public void testCopyConstructor()
+  {
+    MapList ml = new MapList(new int[] { 1, 6, 8, 13 }, new int[] { 4, 7 },
+            3, 1);
+    SequenceI seq = new Sequence("seq1", "agtacg");
+    Mapping m = new Mapping(seq, ml);
+    m.setMappedFromId("abc");
+    Mapping copy = new Mapping(m);
+    assertEquals("abc", copy.getMappedFromId());
+    assertEquals(ml, copy.getMap());
+    assertSame(seq, copy.getTo());
+  }
 }
index 17dfcdc..cfc4cbb 100644 (file)
@@ -65,6 +65,30 @@ public class SequenceTest
     assertEquals("Gap interval 2 end wrong", 8, gapInt.get(1)[1]);
   }
 
+  @Test(groups = ("Functional"))
+  public void testIsProtein()
+  {
+    // test Protein
+    assertTrue(new Sequence("prot","ASDFASDFASDF").isProtein());
+    // test DNA
+    assertFalse(new Sequence("prot","ACGTACGTACGT").isProtein());
+    // test RNA
+    SequenceI sq = new Sequence("prot","ACGUACGUACGU");
+    assertFalse(sq.isProtein());
+    // change sequence, should trigger an update of cached result
+    sq.setSequence("ASDFASDFADSF");
+    assertTrue(sq.isProtein());
+    /*
+     * in situ change of sequence doesn't change hashcode :-O
+     * (sequence should not expose internal implementation)
+     */
+    for (int i = 0; i < sq.getSequence().length; i++)
+    {
+      sq.getSequence()[i] = "acgtu".charAt(i % 5);
+    }
+    assertTrue(sq.isProtein()); // but it isn't
+  }
+
   @Test(groups = { "Functional" })
   public void testGetAnnotation()
   {
@@ -86,8 +110,7 @@ public class SequenceTest
   {
     AlignmentAnnotation ann1 = addAnnotation("label1", "desc1", "calcId1",
             1f);
-    AlignmentAnnotation ann2 = addAnnotation("label2", "desc2", "calcId2",
-            1f);
+    addAnnotation("label2", "desc2", "calcId2", 1f);
     AlignmentAnnotation ann3 = addAnnotation("label1", "desc3", "calcId3",
             1f);
     AlignmentAnnotation[] anns = seq.getAnnotation("label1");
@@ -109,16 +132,15 @@ public class SequenceTest
   @Test(groups = { "Functional" })
   public void testGetAlignmentAnnotations_forCalcIdAndLabel()
   {
-    AlignmentAnnotation ann1 = addAnnotation("label1", "desc1", "calcId1",
-            1f);
+    addAnnotation("label1", "desc1", "calcId1", 1f);
     AlignmentAnnotation ann2 = addAnnotation("label2", "desc2", "calcId2",
             1f);
-    AlignmentAnnotation ann3 = addAnnotation("label2", "desc3", "calcId3",
-            1f);
+    addAnnotation("label2", "desc3", "calcId3", 1f);
     AlignmentAnnotation ann4 = addAnnotation("label2", "desc3", "calcId2",
             1f);
-    AlignmentAnnotation ann5 = addAnnotation("label5", "desc3", null, 1f);
-    AlignmentAnnotation ann6 = addAnnotation(null, "desc3", "calcId3", 1f);
+    addAnnotation("label5", "desc3", null, 1f);
+    addAnnotation(null, "desc3", "calcId3", 1f);
+
     List<AlignmentAnnotation> anns = seq.getAlignmentAnnotations("calcId2",
             "label2");
     assertEquals(2, anns.size());
@@ -388,6 +410,20 @@ public class SequenceTest
   }
 
   /**
+   * test createDatasetSequence behaves to doc
+   */
+  @Test(groups = { "Functional" })
+  public void testCreateDatasetSequence()
+  {
+    SequenceI sq = new Sequence("my","ASDASD");
+    assertNull(sq.getDatasetSequence());
+    SequenceI rds = sq.createDatasetSequence();
+    assertNotNull(rds);
+    assertNull(rds.getDatasetSequence());
+    assertEquals(sq.getDatasetSequence(), rds);
+  }
+
+  /**
    * Test for deriveSequence applied to a sequence with a dataset
    */
   @Test(groups = { "Functional" })
index 3de5e3f..4b71417 100644 (file)
@@ -1,12 +1,14 @@
 package jalview.datamodel.xdb.embl;
 
 import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNull;
 import static org.testng.AssertJUnit.assertSame;
 
 import jalview.analysis.SequenceIdMatcher;
 import jalview.datamodel.DBRefEntry;
-import jalview.datamodel.Sequence;
+import jalview.datamodel.DBRefSource;
 import jalview.datamodel.SequenceI;
+import jalview.util.MapList;
 
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -22,7 +24,7 @@ public class EmblEntryTest
     EmblEntry testee = new EmblEntry();
 
     /*
-     * Make a (CDS) Feature with 4 locations
+     * Make a (CDS) Feature with 5 locations
      */
     EmblFeature cds = new EmblFeature();
     cds.setLocation("join(10..20,complement(30..40),50..60,70..80,complement(110..120))");
@@ -36,30 +38,32 @@ public class EmblEntryTest
   public void testParseCodingFeature()
   {
     // not the whole sequence but enough for this test...
-    SequenceI dna = new Sequence("J03321", "GGATCCGTAAGTTAGACGAAATT");
     List<SequenceI> peptides = new ArrayList<SequenceI>();
     SequenceIdMatcher matcher = new SequenceIdMatcher(peptides);
     EmblFile ef = EmblTestHelper.getEmblFile();
+    assertEquals(1, ef.getEntries().size());
+    EmblEntry testee = ef.getEntries().get(0);
+    String sourceDb = "EMBL";
+    SequenceI dna = testee.makeSequence(sourceDb);
 
     /*
-     * parse two CDS features, one with two Uniprot cross-refs,
-     * the other with one
+     * parse three CDS features, with two/one/no Uniprot cross-refs
      */
-    EmblEntry testee = new EmblEntry();
     for (EmblFeature feature : ef.getEntries().get(0).getFeatures())
     {
       if ("CDS".equals(feature.getName()))
       {
-        testee.parseCodingFeature(feature, "EMBL", dna, peptides, matcher);
+        testee.parseCodingFeature(feature, sourceDb, dna, peptides, matcher);
       }
     }
 
     /*
      * peptides should now have five entries:
      * EMBL product and two Uniprot accessions for the first CDS / translation
-     * EMBL product and one Uniprot accession for the second CDS / translation
+     * EMBL product and one Uniprot accession for the second CDS / "
+     * EMBL product only for the third
      */
-    assertEquals(5, peptides.size());
+    assertEquals(6, peptides.size());
     assertEquals("CAA30420.1", peptides.get(0).getName());
     assertEquals("MLCF", peptides.get(0).getSequenceAsString());
     assertEquals("UNIPROT|B0BCM4", peptides.get(1).getName());
@@ -70,49 +74,161 @@ public class EmblEntryTest
     assertEquals("MSSS", peptides.get(3).getSequenceAsString());
     assertEquals("UNIPROT|B0BCM3", peptides.get(4).getName());
     assertEquals("MSSS", peptides.get(4).getSequenceAsString());
+    assertEquals("CAA12345.6", peptides.get(5).getName());
+    assertEquals("MSS", peptides.get(5).getSequenceAsString());
 
     /*
-     * verify dna sequence has dbrefs with mappings to the peptide 'products'
+     * verify dna sequence has dbrefs with CDS mappings to the peptide 'products'
      */
+    MapList cds1Map = new MapList(new int[] { 57, 46 }, new int[] { 1, 4 },
+            3, 1);
+    MapList cds2Map = new MapList(new int[] { 4, 15 }, new int[] { 1, 4 },
+            3, 1);
+    MapList cds3Map = new MapList(new int[] { 4, 6, 10, 15 }, new int[] {
+        1, 3 }, 3, 1);
     DBRefEntry[] dbrefs = dna.getDBRefs();
-    assertEquals(3, dbrefs.length);
+    assertEquals(4, dbrefs.length);
     DBRefEntry dbRefEntry = dbrefs[0];
     assertEquals("UNIPROT", dbRefEntry.getSource());
     assertEquals("B0BCM4", dbRefEntry.getAccessionId());
     assertSame(peptides.get(1), dbRefEntry.getMap().getTo());
-    List<int[]> fromRanges = dbRefEntry.getMap().getMap().getFromRanges();
-    assertEquals(1, fromRanges.size());
-    assertEquals(57, fromRanges.get(0)[0]);
-    assertEquals(46, fromRanges.get(0)[1]);
-    List<int[]> toRanges = dbRefEntry.getMap().getMap().getToRanges();
-    assertEquals(1, toRanges.size());
-    assertEquals(1, toRanges.get(0)[0]);
-    assertEquals(4, toRanges.get(0)[1]);
+    assertEquals(cds1Map, dbRefEntry.getMap().getMap());
 
     dbRefEntry = dbrefs[1];
     assertEquals("UNIPROT", dbRefEntry.getSource());
     assertEquals("P0CE20", dbRefEntry.getAccessionId());
     assertSame(peptides.get(2), dbRefEntry.getMap().getTo());
-    fromRanges = dbRefEntry.getMap().getMap().getFromRanges();
-    assertEquals(1, fromRanges.size());
-    assertEquals(57, fromRanges.get(0)[0]);
-    assertEquals(46, fromRanges.get(0)[1]);
-    toRanges = dbRefEntry.getMap().getMap().getToRanges();
-    assertEquals(1, toRanges.size());
-    assertEquals(1, toRanges.get(0)[0]);
-    assertEquals(4, toRanges.get(0)[1]);
+    assertEquals(cds1Map, dbRefEntry.getMap().getMap());
 
     dbRefEntry = dbrefs[2];
     assertEquals("UNIPROT", dbRefEntry.getSource());
     assertEquals("B0BCM3", dbRefEntry.getAccessionId());
     assertSame(peptides.get(4), dbRefEntry.getMap().getTo());
-    fromRanges = dbRefEntry.getMap().getMap().getFromRanges();
-    assertEquals(1, fromRanges.size());
-    assertEquals(4, fromRanges.get(0)[0]);
-    assertEquals(15, fromRanges.get(0)[1]);
-    toRanges = dbRefEntry.getMap().getMap().getToRanges();
-    assertEquals(1, toRanges.size());
-    assertEquals(1, toRanges.get(0)[0]);
-    assertEquals(4, toRanges.get(0)[1]);
+    assertEquals(cds2Map, dbRefEntry.getMap().getMap());
+
+    dbRefEntry = dbrefs[3];
+    assertEquals("EMBLCDSPROTEIN", dbRefEntry.getSource());
+    assertEquals("CAA12345.6", dbRefEntry.getAccessionId());
+    assertSame(peptides.get(5), dbRefEntry.getMap().getTo());
+    assertEquals(cds3Map, dbRefEntry.getMap().getMap());
+
+    /*
+     * verify peptides have dbrefs
+     * - to EMBL sequence (with inverse 1:3 cds mapping)
+     * - to EMBLCDS (with 1:3 mapping)
+     * - direct (no mapping) to other protein accessions
+     */
+    MapList proteinToCdsMap1 = new MapList(new int[] { 1, 4 }, new int[] {
+        1, 12 }, 1, 3);
+    MapList proteinToCdsMap2 = new MapList(new int[] { 1, 3 }, new int[] {
+        1, 9 }, 1, 3);
+
+    // dbrefs for first CDS EMBL product CAA30420.1
+    dbrefs = peptides.get(0).getDBRefs();
+    assertEquals(5, dbrefs.length);
+    assertEquals(DBRefSource.EMBL, dbrefs[0].getSource());
+    assertEquals("CAA30420.1", dbrefs[0].getAccessionId());
+    assertEquals(cds1Map.getInverse(), dbrefs[0].getMap().getMap());
+    assertEquals(DBRefSource.EMBLCDS, dbrefs[1].getSource());
+    assertEquals("CAA30420.1", dbrefs[1].getAccessionId());
+    assertEquals(proteinToCdsMap1, dbrefs[1].getMap().getMap());
+    assertEquals(DBRefSource.EMBLCDSProduct, dbrefs[2].getSource());
+    assertEquals("CAA30420.1", dbrefs[2].getAccessionId());
+    assertNull(dbrefs[2].getMap());
+    assertEquals(new DBRefEntry(DBRefSource.UNIPROT, "2.1", "B0BCM4"),
+            dbrefs[3]);
+    assertNull(dbrefs[3].getMap());
+    assertEquals(new DBRefEntry(DBRefSource.UNIPROT, "0", "P0CE20"),
+            dbrefs[4]);
+    assertNull(dbrefs[4].getMap());
+
+    // dbrefs for first CDS first Uniprot xref
+    dbrefs = peptides.get(1).getDBRefs();
+    assertEquals(2, dbrefs.length);
+    assertEquals(new DBRefEntry(DBRefSource.UNIPROT, "2.1", "B0BCM4"),
+            dbrefs[0]);
+    assertNull(dbrefs[0].getMap());
+    assertEquals(DBRefSource.EMBL, dbrefs[1].getSource());
+    assertEquals("X07547", dbrefs[1].getAccessionId());
+    assertEquals(cds1Map.getInverse(), dbrefs[1].getMap().getMap());
+
+    // dbrefs for first CDS second Uniprot xref
+    dbrefs = peptides.get(2).getDBRefs();
+    assertEquals(2, dbrefs.length);
+    assertEquals(new DBRefEntry(DBRefSource.UNIPROT, "0", "P0CE20"),
+            dbrefs[0]);
+    assertNull(dbrefs[0].getMap());
+    assertEquals(DBRefSource.EMBL, dbrefs[1].getSource());
+    assertEquals("X07547", dbrefs[1].getAccessionId());
+    assertEquals(cds1Map.getInverse(), dbrefs[1].getMap().getMap());
+
+    // dbrefs for second CDS EMBL product CAA30421.1
+    dbrefs = peptides.get(3).getDBRefs();
+    assertEquals(4, dbrefs.length);
+    assertEquals(DBRefSource.EMBL, dbrefs[0].getSource());
+    assertEquals("CAA30421.1", dbrefs[0].getAccessionId());
+    assertEquals(cds2Map.getInverse(), dbrefs[0].getMap().getMap());
+    assertEquals(DBRefSource.EMBLCDS, dbrefs[1].getSource());
+    assertEquals("CAA30421.1", dbrefs[1].getAccessionId());
+    assertEquals(proteinToCdsMap1, dbrefs[1].getMap().getMap());
+    assertEquals(DBRefSource.EMBLCDSProduct, dbrefs[2].getSource());
+    assertEquals("CAA30421.1", dbrefs[2].getAccessionId());
+    assertNull(dbrefs[2].getMap());
+    assertEquals(new DBRefEntry(DBRefSource.UNIPROT, "0", "B0BCM3"),
+            dbrefs[3]);
+    assertNull(dbrefs[3].getMap());
+
+    // dbrefs for second CDS second Uniprot xref
+    dbrefs = peptides.get(4).getDBRefs();
+    assertEquals(2, dbrefs.length);
+    assertEquals(new DBRefEntry(DBRefSource.UNIPROT, "0", "B0BCM3"),
+            dbrefs[0]);
+    assertNull(dbrefs[0].getMap());
+    assertEquals(DBRefSource.EMBL, dbrefs[1].getSource());
+    assertEquals("X07547", dbrefs[1].getAccessionId());
+    assertEquals(cds2Map.getInverse(), dbrefs[1].getMap().getMap());
+
+    // dbrefs for third CDS inferred EMBL product CAA12345.6
+    dbrefs = peptides.get(5).getDBRefs();
+    assertEquals(3, dbrefs.length);
+    assertEquals(DBRefSource.EMBL, dbrefs[0].getSource());
+    assertEquals("CAA12345.6", dbrefs[0].getAccessionId());
+    assertEquals(cds3Map.getInverse(), dbrefs[0].getMap().getMap());
+    assertEquals(DBRefSource.EMBLCDS, dbrefs[1].getSource());
+    assertEquals("CAA12345.6", dbrefs[1].getAccessionId());
+    assertEquals(proteinToCdsMap2, dbrefs[1].getMap().getMap());
+    assertEquals(DBRefSource.EMBLCDSProduct, dbrefs[2].getSource());
+    assertEquals("CAA12345.6", dbrefs[2].getAccessionId());
+    assertNull(dbrefs[2].getMap());
+  }
+
+  @Test(groups = "Functional")
+  public void testAdjustForProteinLength()
+  {
+    int[] exons = new int[] { 11, 15, 21, 25, 31, 38 }; // 18 bp
+
+    // exact length match:
+    assertSame(exons, EmblEntry.adjustForProteinLength(6, exons));
+
+    // match if we assume exons include stop codon not in protein:
+    assertSame(exons, EmblEntry.adjustForProteinLength(5, exons));
+
+    // truncate last exon by 6bp
+    int[] truncated = EmblEntry.adjustForProteinLength(4, exons);
+    assertEquals("[11, 15, 21, 25, 31, 32]",
+            Arrays.toString(truncated));
+
+    // remove last exon and truncate preceding by 1bp
+    truncated = EmblEntry.adjustForProteinLength(3, exons);
+    assertEquals("[11, 15, 21, 24]", Arrays.toString(truncated));
+
+    // exact removal of exon case:
+    exons = new int[] { 11, 15, 21, 27, 33, 38 }; // 18 bp
+    truncated = EmblEntry.adjustForProteinLength(4, exons);
+    assertEquals("[11, 15, 21, 27]", Arrays.toString(truncated));
+
+    // what if exons are too short for protein?
+    truncated = EmblEntry.adjustForProteinLength(7, exons);
+    assertSame(exons, truncated);
   }
 }
index 6955833..906436f 100644 (file)
@@ -80,9 +80,9 @@ public class EmblFileTest
     assertEquals("0", dbref.getVersion());
 
     /*
-     * two sequence features for CDS
+     * three sequence features for CDS
      */
-    assertEquals(2, entry.getFeatures().size());
+    assertEquals(3, entry.getFeatures().size());
     /*
      * first CDS
      */
@@ -140,6 +140,23 @@ public class EmblFileTest
     assertEquals("MSSS", q.getValues()[0]);
 
     /*
+     * third CDS
+     */
+    ef = entry.getFeatures().get(2);
+    assertEquals("CDS", ef.getName());
+    assertEquals("join(4..6,10..15)", ef.getLocation());
+    assertNull(ef.getDbRefs());
+    assertEquals(2, ef.getQualifiers().size());
+    q = ef.getQualifiers().get(0);
+    assertEquals("protein_id", q.getName());
+    assertEquals(1, q.getValues().length);
+    assertEquals("CAA12345.6", q.getValues()[0]);
+    q = ef.getQualifiers().get(1);
+    assertEquals("translation", q.getName());
+    assertEquals(1, q.getValues().length);
+    assertEquals("MSS", q.getValues()[0]);
+
+    /*
      * Sequence - verify newline not converted to space (JAL-2029)
      */
     EmblSequence seq = entry.getSequence();
index 9957c72..6349164 100644 (file)
@@ -38,6 +38,14 @@ public class EmblTestHelper
           + "<qualifier name=\"translation\"><value>MSSS</value></qualifier>"
           + "</feature>"
           /*
+           * third CDS is made up - has no xref - code should synthesize 
+           * one to an assumed EMBLCDSPROTEIN accession
+           */
+          + "<feature name=\"CDS\" location=\"join(4..6,10..15)\">"
+          + "<qualifier name=\"protein_id\"><value>CAA12345.6</value></qualifier>"
+          + "<qualifier name=\"translation\"><value>MSS</value></qualifier>"
+          + "</feature>"
+          /*
            * sequence (modified for test purposes)
            * emulates EMBL XML 1.2 which splits sequence data every 60 characters
            * see EmblSequence.setSequence
index 2a5dda4..f2b32c6 100644 (file)
@@ -28,10 +28,10 @@ import jalview.datamodel.Alignment;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.SequenceI;
 import jalview.gui.AlignFrame;
-import jalview.io.AppletFormatAdapter;
 import jalview.io.DataSourceType;
 import jalview.io.FileLoader;
 import jalview.structure.StructureImportSettings;
+import jalview.structure.StructureImportSettings.StructureParser;
 
 import java.util.Vector;
 
@@ -90,6 +90,9 @@ public class JmolParserTest
             Boolean.TRUE.toString());
     Cache.applicationProperties.setProperty("ADD_SS_ANN",
             Boolean.TRUE.toString());
+    StructureImportSettings.setDefaultStructureFileFormat("PDB");
+    StructureImportSettings
+            .setDefaultPDBFileParser(StructureParser.JALVIEW_PARSER);
   }
 
   @Test(groups = { "Functional" })
@@ -98,8 +101,7 @@ public class JmolParserTest
     for (String f : testFile)
     {
       FileLoader fl = new jalview.io.FileLoader(false);
-      AlignFrame af = fl
-              .LoadFileWaitTillLoaded(f, DataSourceType.FILE);
+      AlignFrame af = fl.LoadFileWaitTillLoaded(f, DataSourceType.FILE);
       validateSecStrRows(af.getViewport().getAlignment());
     }
   }
@@ -107,37 +109,12 @@ public class JmolParserTest
   @Test(groups = { "Functional" })
   public void testFileParser() throws Exception
   {
-    StructureImportSettings.setProcessHETATMs(false);
     for (String pdbStr : testFile)
     {
       PDBfile mctest = new PDBfile(false, false, false, pdbStr,
               DataSourceType.FILE);
       JmolParser jtest = new JmolParser(false, false, false, pdbStr,
-              jalview.io.DataSourceType.FILE);
-      Vector<SequenceI> seqs = jtest.getSeqs(), mcseqs = mctest.getSeqs();
-
-      assertTrue(
-              "No sequences extracted from testfile\n"
-                      + (jtest.hasWarningMessage() ? jtest.getWarningMessage()
-                              : "(No warnings raised)"), seqs != null
-                      && seqs.size() > 0);
-      for (SequenceI sq : seqs)
-      {
-        assertEquals("JMol didn't process " + pdbStr
-                + " to the same sequence as MCView",
-                sq.getSequenceAsString(), mcseqs.remove(0)
-                        .getSequenceAsString());
-        AlignmentI al = new Alignment(new SequenceI[] { sq });
-        validateSecStrRows(al);
-      }
-    }
-    StructureImportSettings.setProcessHETATMs(true);
-    for (String pdbStr : testFile)
-    {
-      PDBfile mctest = new PDBfile(false, false, false, pdbStr,
               DataSourceType.FILE);
-      JmolParser jtest = new JmolParser(false, false, false, pdbStr,
-              jalview.io.DataSourceType.FILE);
       Vector<SequenceI> seqs = jtest.getSeqs(), mcseqs = mctest.getSeqs();
 
       assertTrue(
@@ -155,6 +132,7 @@ public class JmolParserTest
         validateSecStrRows(al);
       }
     }
+
   }
 
   private void validateSecStrRows(AlignmentI al)
@@ -201,15 +179,13 @@ public class JmolParserTest
   public void testParse_missingResidues() throws Exception
   {
     PDBfile mctest = new PDBfile(false, false, false,
-            pastePDBDataWithChainBreak,
-            DataSourceType.PASTE);
+            pastePDBDataWithChainBreak, DataSourceType.PASTE);
     boolean annotFromStructure = false;
     boolean localSecondaryStruct = false;
     boolean serviceSecondaryStruct = false;
     JmolParser jtest = new JmolParser(annotFromStructure,
             localSecondaryStruct, serviceSecondaryStruct,
-            pastePDBDataWithChainBreak,
-            jalview.io.DataSourceType.PASTE);
+            pastePDBDataWithChainBreak, DataSourceType.PASTE);
     Vector<SequenceI> seqs = jtest.getSeqs();
     Vector<SequenceI> mcseqs = mctest.getSeqs();
 
@@ -236,7 +212,7 @@ public class JmolParserTest
     boolean serviceSecondaryStruct = false;
     JmolParser jtest = new JmolParser(annotFromStructure,
             localSecondaryStruct, serviceSecondaryStruct, pdbWithAltLoc,
-            jalview.io.DataSourceType.PASTE);
+            DataSourceType.PASTE);
     Vector<SequenceI> seqs = jtest.getSeqs();
     Vector<SequenceI> mcseqs = mctest.getSeqs();
   
diff --git a/test/jalview/ext/jmol/JmolVsJalviewPDBParserEndToEndTest.java b/test/jalview/ext/jmol/JmolVsJalviewPDBParserEndToEndTest.java
new file mode 100644 (file)
index 0000000..01b4adf
--- /dev/null
@@ -0,0 +1,102 @@
+package jalview.ext.jmol;
+
+import jalview.datamodel.SequenceI;
+import jalview.io.DataSourceType;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.Vector;
+
+import MCview.PDBfile;
+
+/**
+ * This is not a unit test, rather it is a bulk End-to-End scan for sequences
+ * consistency for PDB files parsed with JmolParser vs. Jalview's PDBfile
+ * parser. The directory of PDB files to test must be provided in the launch
+ * args.
+ * 
+ * @author tcnofoegbu
+ *
+ */
+public class JmolVsJalviewPDBParserEndToEndTest
+{
+
+  public static void main(String[] args)
+  {
+    if (args == null || args[0] == null)
+    {
+      System.err
+              .println("You must provide a PDB directory in the launch argument");
+      return;
+    }
+
+    // args[0] must provide the directory of PDB files to run the test with
+    String testDir = args[0];
+    System.out.println("PDB directory : " + testDir);
+    File pdbDir = new File(testDir);
+    String testFiles[] = pdbDir.list();
+    testFileParser(testDir, testFiles);
+  }
+
+  public static void testFileParser(String testDir, String[] testFiles)
+  {
+    Set<String> failedFiles = new HashSet<String>();
+    int totalSeqScanned = 0, totalFail = 0;
+    for (String pdbStr : testFiles)
+    {
+      String testFile = testDir + "/" + pdbStr;
+      PDBfile mctest = null;
+      JmolParser jtest = null;
+      try
+      {
+        mctest = new PDBfile(false, false, false, testFile,
+                DataSourceType.FILE);
+        jtest = new JmolParser(false, false, false, testFile,
+                DataSourceType.FILE);
+      } catch (IOException e)
+      {
+        System.err.println("Exception thrown while parsing : " + pdbStr);
+      }
+      Vector<SequenceI> seqs = jtest.getSeqs();
+      Vector<SequenceI> mcseqs = mctest.getSeqs();
+
+      for (SequenceI sq : seqs)
+      {
+        try
+        {
+        String testSeq = mcseqs.remove(0).getSequenceAsString();
+          if (!sq.getSequenceAsString().equals(testSeq))
+        {
+          ++totalFail;
+            System.err.println("Test Failed for " + pdbStr + ". Diff:");
+          System.err.println(sq.getSequenceAsString());
+          System.err.println(testSeq);
+          failedFiles.add(pdbStr);
+        }
+          ++totalSeqScanned;
+        } catch (Exception e)
+        {
+          e.printStackTrace();
+        }
+      }
+    }
+    int count = 0;
+
+    System.out.println("\n\nTotal sequence Scanned : " + totalSeqScanned);
+    System.out.println("Total sequence passed : "
+            + (totalSeqScanned - totalFail));
+    System.out.println("Total sequence failed : " + totalFail);
+    System.out
+            .println("Success rate: "
+                    + ((totalSeqScanned - totalFail) * 100)
+                    / totalSeqScanned + "%");
+    System.out.println("\nList of " + failedFiles.size()
+            + " file(s) with sequence diffs:");
+    for (String problemFile : failedFiles)
+    {
+      System.out.println(++count + ". " + problemFile);
+    }
+  }
+}
index aab67f6..8c540b0 100644 (file)
@@ -36,6 +36,7 @@ import jalview.datamodel.SequenceI;
 import jalview.io.DataSourceType;
 import jalview.io.FileLoader;
 import jalview.structure.StructureSelectionManager;
+import jalview.util.MapList;
 
 import java.util.ArrayList;
 import java.util.List;
@@ -133,8 +134,13 @@ public class AlignViewportTest
     AlignFrame af1 = new FileLoader().LoadFileWaitTillLoaded(
             ">Seq1\nCAGT\n", DataSourceType.PASTE);
 
+    SequenceI s1 = af1.getViewport().getAlignment().getSequenceAt(0);
     AlignedCodonFrame acf1 = new AlignedCodonFrame();
+    acf1.addMap(s1, s1, new MapList(new int[] { 1, 4 }, new int[] { 1, 4 },
+            1, 1));
     AlignedCodonFrame acf2 = new AlignedCodonFrame();
+    acf2.addMap(s1, s1, new MapList(new int[] { 1, 4 }, new int[] { 4, 1 },
+            1, 1));
 
     List<AlignedCodonFrame> mappings = new ArrayList<AlignedCodonFrame>();
     mappings.add(acf1);
@@ -178,10 +184,20 @@ public class AlignViewportTest
             ">Seq1\nRSVQ\n", DataSourceType.PASTE);
     AlignFrame af2 = new FileLoader().LoadFileWaitTillLoaded(
             ">Seq2\nDGEL\n", DataSourceType.PASTE);
-
+    SequenceI cs1 = new Sequence("cseq1", "CCCGGGTTTAAA");
+    SequenceI cs2 = new Sequence("cseq2", "CTTGAGTCTAGA");
+    SequenceI s1 = af1.getViewport().getAlignment().getSequenceAt(0);
+    SequenceI s2 = af2.getViewport().getAlignment().getSequenceAt(0);
+    // need to be distinct
     AlignedCodonFrame acf1 = new AlignedCodonFrame();
+    acf1.addMap(cs1, s1, new MapList(new int[] { 1, 4 },
+            new int[] { 1, 12 }, 1, 3));
     AlignedCodonFrame acf2 = new AlignedCodonFrame();
+    acf2.addMap(cs2, s2, new MapList(new int[] { 1, 4 },
+            new int[] { 1, 12 }, 1, 3));
     AlignedCodonFrame acf3 = new AlignedCodonFrame();
+    acf3.addMap(cs2, cs2, new MapList(new int[] { 1, 12 }, new int[] { 1,
+        12 }, 1, 1));
 
     List<AlignedCodonFrame> mappings1 = new ArrayList<AlignedCodonFrame>();
     mappings1.add(acf1);
@@ -231,10 +247,20 @@ public class AlignViewportTest
             ">Seq1\nRSVQ\n", DataSourceType.PASTE);
     AlignFrame af2 = new FileLoader().LoadFileWaitTillLoaded(
             ">Seq2\nDGEL\n", DataSourceType.PASTE);
-
+    SequenceI cs1 = new Sequence("cseq1", "CCCGGGTTTAAA");
+    SequenceI cs2 = new Sequence("cseq2", "CTTGAGTCTAGA");
+    SequenceI s1 = af1.getViewport().getAlignment().getSequenceAt(0);
+    SequenceI s2 = af2.getViewport().getAlignment().getSequenceAt(0);
+    // need to be distinct
     AlignedCodonFrame acf1 = new AlignedCodonFrame();
+    acf1.addMap(cs1, s1, new MapList(new int[] { 1, 4 },
+            new int[] { 1, 12 }, 1, 3));
     AlignedCodonFrame acf2 = new AlignedCodonFrame();
+    acf2.addMap(cs2, s2, new MapList(new int[] { 1, 4 },
+            new int[] { 1, 12 }, 1, 3));
     AlignedCodonFrame acf3 = new AlignedCodonFrame();
+    acf3.addMap(cs2, cs2, new MapList(new int[] { 1, 12 }, new int[] { 1,
+        12 }, 1, 1));
 
     List<AlignedCodonFrame> mappings1 = new ArrayList<AlignedCodonFrame>();
     mappings1.add(acf1);
index e8cd3ef..9a07ef7 100644 (file)
@@ -32,6 +32,7 @@ import jalview.datamodel.SequenceFeature;
 import jalview.datamodel.SequenceI;
 import jalview.gui.AlignFrame;
 import jalview.structure.StructureImportSettings;
+import jalview.structure.StructureImportSettings.StructureParser;
 
 import java.io.File;
 
@@ -66,7 +67,9 @@ public class AnnotatedPDBFileInputTest
     al = af.getViewport().getAlignment();
     pdbId = al.getSequenceAt(0).getDatasetSequence().getAllPDBEntries()
             .get(0).getId();
-    StructureImportSettings.setCurrentDefaultFormat("PDB");
+    StructureImportSettings.setDefaultStructureFileFormat("PDB");
+    // StructureImportSettings
+    // .setDefaultPDBFileParser(StructureParser.JALVIEW_PARSER);
   }
 
   @Test(groups = { "Functional" })
@@ -98,7 +101,11 @@ public class AnnotatedPDBFileInputTest
       {
 
         System.out.println("CalcId: " + aa.getCalcId());
+        if (StructureImportSettings.getDefaultPDBFileParser().equals(
+                StructureParser.JALVIEW_PARSER))
+        {
         assertTrue(MCview.PDBfile.isCalcIdForFile(aa, pdbId));
+        }
       }
     }
   }
@@ -115,9 +122,9 @@ public class AnnotatedPDBFileInputTest
     SequenceFeature[] sf = al.getSequenceAt(0).getSequenceFeatures();
     assertEquals(296, sf.length);
     assertEquals("RESNUM", sf[0].getType());
-    assertEquals("GLU:  19  1gaqA", sf[0].getDescription());
+    assertEquals("GLU:19 1gaqA", sf[0].getDescription());
     assertEquals("RESNUM", sf[295].getType());
-    assertEquals("TYR: 314  1gaqA", sf[295].getDescription());
+    assertEquals("TYR:314 1gaqA", sf[295].getDescription());
 
     /*
      * 1GAQ/B
@@ -125,9 +132,9 @@ public class AnnotatedPDBFileInputTest
     sf = al.getSequenceAt(1).getSequenceFeatures();
     assertEquals(98, sf.length);
     assertEquals("RESNUM", sf[0].getType());
-    assertEquals("ALA:   1  1gaqB", sf[0].getDescription());
+    assertEquals("ALA:1 1gaqB", sf[0].getDescription());
     assertEquals("RESNUM", sf[97].getType());
-    assertEquals("ALA:  98  1gaqB", sf[97].getDescription());
+    assertEquals("ALA:98 1gaqB", sf[97].getDescription());
 
     /*
      * 1GAQ/C
@@ -135,9 +142,9 @@ public class AnnotatedPDBFileInputTest
     sf = al.getSequenceAt(2).getSequenceFeatures();
     assertEquals(296, sf.length);
     assertEquals("RESNUM", sf[0].getType());
-    assertEquals("GLU:  19  1gaqC", sf[0].getDescription());
+    assertEquals("GLU:19 1gaqC", sf[0].getDescription());
     assertEquals("RESNUM", sf[295].getType());
-    assertEquals("TYR: 314  1gaqC", sf[295].getDescription());
+    assertEquals("TYR:314 1gaqC", sf[295].getDescription());
   }
 
   @Test(groups = { "Functional" })
diff --git a/test/jalview/io/FormatAdapterTest.java b/test/jalview/io/FormatAdapterTest.java
new file mode 100644 (file)
index 0000000..6bf954a
--- /dev/null
@@ -0,0 +1,135 @@
+package jalview.io;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.fail;
+
+import jalview.datamodel.AlignmentI;
+import jalview.datamodel.SequenceI;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+public class FormatAdapterTest
+{
+
+  /**
+   * Test saving and re-reading in a specified format
+   * 
+   * @throws IOException
+   */
+  @Test(groups = { "Functional" }, dataProvider = "formats")
+  public void testRoundTrip(FileFormatI format) throws IOException
+  {
+    try
+    {
+      AlignmentI al = new FormatAdapter().readFile("examples/uniref50.fa",
+              DataSourceType.FILE, FileFormat.Fasta);
+
+      /*
+       * 'gap' is the gap character used in the alignment data file here,
+       * not the user preferred gap character
+       */
+      char gap = al.getGapCharacter();
+      assertNotNull(al);
+
+      SequenceI[] seqs = al.getSequencesArray();
+      String formatted = new FormatAdapter().formatSequences(format, al,
+              false);
+
+      AlignmentI reloaded = new FormatAdapter().readFile(formatted,
+              DataSourceType.PASTE, format);
+      List<SequenceI> reread = reloaded.getSequences();
+      assertEquals("Wrong number of reloaded sequences", seqs.length,
+              reread.size());
+
+      int i = 0;
+      for (SequenceI seq : reread)
+      {
+        String sequenceString = seq.getSequenceAsString();
+
+        /*
+         * special case: MSF always uses '.' as gap character
+         */
+        sequenceString = adjustForGapTreatment(sequenceString, gap, format);
+        assertEquals(
+                String.format("Sequence %d: %s", i,
+                        seqs[i].getName()), seqs[i].getSequenceAsString(),
+                sequenceString);
+        i++;
+      }
+    } catch (IOException e)
+    {
+      fail(String
+              .format("Format %s failed with %s", format, e.getMessage()));
+    }
+  }
+
+  /**
+   * Optionally change the gap character in the string to the given character,
+   * depending on the sequence file format
+   * 
+   * @param sequenceString
+   *          a sequence (as written in 'format' format)
+   * @param gap
+   *          the sequence's original gap character
+   * @param format
+   * @return
+   */
+  String adjustForGapTreatment(String sequenceString, char gap,
+          FileFormatI format)
+  {
+    if (format == FileFormat.MSF)
+    {
+      /*
+       * MSF forces gap character to '.', so change it back
+       * for comparison purposes
+       */
+      sequenceString = sequenceString.replace('.', gap);
+    }
+    return sequenceString;
+  }
+
+  /**
+   * Data provider that serves alignment formats that are both readable and
+   * writable
+   * 
+   * @return
+   */
+  @DataProvider(name = "formats")
+  static Object[][] getFormats()
+  {
+    List<FileFormatI> both = new ArrayList<FileFormatI>();
+    for (FileFormat format : FileFormat.values())
+    {
+      if (format.isReadable() && format.isWritable())
+      {
+        both.add(format);
+      }
+    }
+
+    Object[][] formats = new Object[both.size()][];
+    int i = 0;
+    for (FileFormatI format : both)
+    {
+      formats[i] = new Object[] { format };
+      i++;
+    }
+    return formats;
+  }
+
+  /**
+   * Enable this to isolate testing to a single file format
+   * 
+   * @throws IOException
+   */
+  @Test(groups = { "Functional" }, enabled = false)
+  public void testOneFormatRoundTrip() throws IOException
+  {
+    testRoundTrip(FileFormat.Json);
+  }
+}
index 3281db1..266b0f8 100644 (file)
@@ -30,21 +30,26 @@ import jalview.api.AlignViewportI;
 import jalview.api.AlignmentViewPanel;
 import jalview.api.ViewStyleI;
 import jalview.bin.Cache;
+import jalview.bin.Jalview;
 import jalview.datamodel.AlignmentAnnotation;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.HiddenSequences;
+import jalview.datamodel.PDBEntry;
 import jalview.datamodel.SequenceCollectionI;
 import jalview.datamodel.SequenceGroup;
 import jalview.datamodel.SequenceI;
 import jalview.gui.AlignFrame;
+import jalview.gui.AlignmentPanel;
 import jalview.gui.Desktop;
 import jalview.gui.Jalview2XML;
 import jalview.schemes.AnnotationColourGradient;
 import jalview.schemes.ColourSchemeI;
+import jalview.structure.StructureImportSettings;
 import jalview.viewmodel.AlignmentViewport;
 
 import java.io.File;
 import java.util.ArrayList;
+import java.util.Date;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -65,8 +70,19 @@ public class Jalview2xmlTests
   @BeforeClass(alwaysRun = true)
   public static void setUpBeforeClass() throws Exception
   {
-    jalview.bin.Jalview.main(new String[] { "-props",
-        "test/jalview/io/testProps.jvprops" });
+    /*
+     * use read-only test properties file
+     */
+    Cache.loadProperties("test/jalview/io/testProps.jvprops");
+
+    /*
+     * set news feed last read to a future time to ensure no
+     * 'unread' news item is displayed
+     */
+    Date oneHourFromNow = new Date(System.currentTimeMillis() + 3600 * 1000);
+    Cache.setDateProperty("JALVIEW_NEWS_RSS_LASTMODIFIED", oneHourFromNow);
+
+    Jalview.main(new String[] {});
   }
 
   /**
@@ -75,7 +91,7 @@ public class Jalview2xmlTests
   @AfterClass(alwaysRun = true)
   public static void tearDownAfterClass() throws Exception
   {
-    jalview.gui.Desktop.instance.closeAll_actionPerformed(null);
+    Desktop.instance.closeAll_actionPerformed(null);
   }
 
   int countDsAnn(jalview.viewmodel.AlignmentViewport avp)
@@ -270,10 +286,11 @@ public class Jalview2xmlTests
   @Test(groups = { "Functional" })
   public void viewRefPdbAnnotation() throws Exception
   {
-    Cache.applicationProperties.setProperty("STRUCT_FROM_PDB",
-            Boolean.TRUE.toString());
-    Cache.applicationProperties.setProperty("ADD_SS_ANN",
-            Boolean.TRUE.toString());
+    // TODO: Make this pass without setting StructureParser.JALVIEW_PARSER
+    // StructureImportSettings
+    // .setDefaultPDBFileParser(StructureParser.JALVIEW_PARSER);
+    StructureImportSettings.setProcessSecondaryStructure(true);
+    StructureImportSettings.setVisibleChainAnnotation(true);
     AlignFrame af = new jalview.io.FileLoader().LoadFileWaitTillLoaded(
             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
     assertTrue("Didn't read in the example file correctly.", af != null);
@@ -364,37 +381,29 @@ public class Jalview2xmlTests
   }
 
   /**
-   * test store and recovery of expanded views - currently this is disabled
-   * since the Desktop.explodeViews method doesn't seem to result in the views
-   * being expanded to distinct align frames when executed programmatically.
+   * test store and recovery of expanded views
    * 
    * @throws Exception
    */
   @Test(groups = { "Functional" }, enabled = true)
   public void testStoreAndRecoverExpandedviews() throws Exception
   {
+    Desktop.instance.closeAll_actionPerformed(null);
+
     AlignFrame af = new jalview.io.FileLoader().LoadFileWaitTillLoaded(
             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
     assertTrue("Didn't read in the example file correctly.", af != null);
+    Assert.assertEquals(Desktop.getAlignFrames().length, 1);
     String afid = af.getViewport().getSequenceSetId();
-    {
-      final AlignFrame xaf = af;
-      af = null;
-      new Thread(new Runnable()
-      {
-        @Override
-        public void run()
-        {
-          Desktop.instance.explodeViews(xaf);
-        }
-      }).start();
-      Thread.sleep(1000);
-    }
-    // int times = 0;
-    // while (++times < 5 && Desktop.getAlignFrames().length < )
-    // {
-    // Thread.sleep(300);
-    // }
+
+    // check FileLoader returned a reference to the one alignFrame that is
+    // actually on the Desktop
+    assertTrue(
+            "Jalview2XML.loadAlignFrame() didn't return correct AlignFrame reference for multiple view window",
+            af == Desktop.getAlignFrameFor(af.getViewport()));
+
+    Desktop.explodeViews(af);
+
     int oldviews = Desktop.getAlignFrames().length;
     Assert.assertEquals(Desktop.getAlignFrames().length,
             Desktop.getAlignmentPanels(afid).length);
@@ -679,4 +688,92 @@ public class Jalview2xmlTests
               hidden.size(), hs.getSize());
     }
   }
+
+  /**
+   * Test save and reload of PDBEntry in Jalview project
+   * 
+   * @throws Exception
+   */
+  @Test(groups = { "Functional" })
+  public void testStoreAndRecoverPDBEntry() throws Exception
+  {
+    Desktop.instance.closeAll_actionPerformed(null);
+    String exampleFile = "examples/3W5V.pdb";
+    AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(exampleFile,
+            DataSourceType.FILE);
+    assertTrue("Didn't read in the example file correctly.", af != null);
+    String afid = af.getViewport().getSequenceSetId();
+
+    AlignmentPanel[] alignPanels = Desktop.getAlignmentPanels(afid);
+    System.out.println();
+    AlignmentViewPanel ap = alignPanels[0];
+    String tfileBase = new File(".").getAbsolutePath().replace(".", "");
+    String testFile = tfileBase + exampleFile;
+    AlignmentI alignment = ap.getAlignment();
+    System.out.println("blah");
+    SequenceI[] seqs = alignment.getSequencesArray();
+    Assert.assertNotNull(seqs[0]);
+    Assert.assertNotNull(seqs[1]);
+    Assert.assertNotNull(seqs[2]);
+    Assert.assertNotNull(seqs[3]);
+    Assert.assertNotNull(seqs[0].getDatasetSequence());
+    Assert.assertNotNull(seqs[1].getDatasetSequence());
+    Assert.assertNotNull(seqs[2].getDatasetSequence());
+    Assert.assertNotNull(seqs[3].getDatasetSequence());
+    PDBEntry[] pdbEntries = new PDBEntry[4];
+    pdbEntries[0] = new PDBEntry("3W5V", "A", null, testFile);
+    pdbEntries[1] = new PDBEntry("3W5V", "B", null, testFile);
+    pdbEntries[2] = new PDBEntry("3W5V", "C", null, testFile);
+    pdbEntries[3] = new PDBEntry("3W5V", "D", null, testFile);
+    Assert.assertTrue(seqs[0].getDatasetSequence().getAllPDBEntries()
+            .get(0).equals(pdbEntries[0]));
+    Assert.assertTrue(seqs[1].getDatasetSequence().getAllPDBEntries()
+            .get(0).equals(pdbEntries[1]));
+    Assert.assertTrue(seqs[2].getDatasetSequence().getAllPDBEntries()
+            .get(0).equals(pdbEntries[2]));
+    Assert.assertTrue(seqs[3].getDatasetSequence().getAllPDBEntries()
+            .get(0).equals(pdbEntries[3]));
+
+    File tfile = File.createTempFile("testStoreAndRecoverPDBEntry", ".jvp");
+    try
+    {
+      new Jalview2XML(false).saveState(tfile);
+    } catch (Throwable e)
+    {
+      Assert.fail("Didn't save the state", e);
+    }
+    Desktop.instance.closeAll_actionPerformed(null);
+    if (Desktop.getAlignFrames() != null)
+    {
+      Assert.assertEquals(Desktop.getAlignFrames().length, 0);
+    }
+
+    AlignFrame restoredFrame = new FileLoader().LoadFileWaitTillLoaded(
+            tfile.getAbsolutePath(), DataSourceType.FILE);
+    String rfid = restoredFrame.getViewport().getSequenceSetId();
+    AlignmentPanel[] rAlignPanels = Desktop.getAlignmentPanels(rfid);
+    AlignmentViewPanel rap = rAlignPanels[0];
+    AlignmentI rAlignment = rap.getAlignment();
+    System.out.println("blah");
+    SequenceI[] rseqs = rAlignment.getSequencesArray();
+    Assert.assertNotNull(rseqs[0]);
+    Assert.assertNotNull(rseqs[1]);
+    Assert.assertNotNull(rseqs[2]);
+    Assert.assertNotNull(rseqs[3]);
+    Assert.assertNotNull(rseqs[0].getDatasetSequence());
+    Assert.assertNotNull(rseqs[1].getDatasetSequence());
+    Assert.assertNotNull(rseqs[2].getDatasetSequence());
+    Assert.assertNotNull(rseqs[3].getDatasetSequence());
+
+    // The Asserts below are expected to fail until the PDB chainCode is
+    // recoverable from a Jalview projects
+    Assert.assertTrue(rseqs[0].getDatasetSequence().getAllPDBEntries()
+            .get(0).equals(pdbEntries[0]));
+    Assert.assertTrue(rseqs[1].getDatasetSequence().getAllPDBEntries()
+            .get(0).equals(pdbEntries[1]));
+    Assert.assertTrue(rseqs[2].getDatasetSequence().getAllPDBEntries()
+            .get(0).equals(pdbEntries[2]));
+    Assert.assertTrue(rseqs[3].getDatasetSequence().getAllPDBEntries()
+            .get(0).equals(pdbEntries[3]));
+  }
 }
index 897918f..bdd311b 100644 (file)
@@ -23,6 +23,7 @@ package jalview.io;
 import static org.testng.AssertJUnit.assertEquals;
 import static org.testng.AssertJUnit.assertNotNull;
 import static org.testng.AssertJUnit.assertTrue;
+import static org.testng.AssertJUnit.fail;
 
 import jalview.datamodel.AlignmentAnnotation;
 import jalview.datamodel.AlignmentI;
@@ -159,7 +160,7 @@ public class StockholmFileTest
    *          'secondary' or generated alignment from some datapreserving
    *          transformation
    * @param ignoreFeatures
-   *          when true, differences in seuqence feature annotation are ignored.
+   *          when true, differences in sequence feature annotation are ignored
    */
   public static void testAlignmentEquivalence(AlignmentI al,
           AlignmentI al_input, boolean ignoreFeatures)
@@ -167,12 +168,9 @@ public class StockholmFileTest
     assertNotNull("Original alignment was null", al);
     assertNotNull("Generated alignment was null", al_input);
 
-    assertTrue(
-            "Alignment dimension mismatch: originl contains "
-                    + al.getHeight() + " and generated has "
-                    + al_input.getHeight() + " sequences; original has "
-                    + al.getWidth() + " and generated has "
-                    + al_input.getWidth() + " columns.",
+    assertTrue("Alignment dimension mismatch: original: " + al.getHeight()
+            + "x" + al.getWidth() + ", generated: " + al_input.getHeight()
+            + "x" + al_input.getWidth(),
             al.getHeight() == al_input.getHeight()
                     && al.getWidth() == al_input.getWidth());
 
@@ -183,9 +181,10 @@ public class StockholmFileTest
     // note - at moment we do not distinguish between alignment without any
     // annotation rows and alignment with no annotation row vector
     // we might want to revise this in future
-    int aa_new_size = (aa_new == null ? 0 : aa_new.length), aa_original_size = (aa_original == null ? 0
-            : aa_original.length);
-    Map<Integer, java.util.BitSet> orig_groups = new HashMap<Integer, java.util.BitSet>(), new_groups = new HashMap<Integer, java.util.BitSet>();
+    int aa_new_size = (aa_new == null ? 0 : aa_new.length);
+    int aa_original_size = (aa_original == null ? 0 : aa_original.length);
+    Map<Integer, BitSet> orig_groups = new HashMap<Integer, BitSet>();
+    Map<Integer, BitSet> new_groups = new HashMap<Integer, BitSet>();
 
     if (aa_new != null && aa_original != null)
     {
@@ -196,20 +195,17 @@ public class StockholmFileTest
           assertTrue("Different alignment annotation at position " + i,
                   equalss(aa_original[i], aa_new[i]));
           // compare graphGroup or graph properties - needed to verify JAL-1299
-          assertTrue("Graph type not identical.",
-                  aa_original[i].graph == aa_new[i].graph);
-          assertTrue("Visibility not identical.",
-                  aa_original[i].visible == aa_new[i].visible);
-          assertTrue(
-                  "Threshold line not identical.",
-                  aa_original[i].threshold == null ? aa_new[i].threshold == null
-                          : aa_original[i].threshold
-                                  .equals(aa_new[i].threshold));
+          assertEquals("Graph type not identical.", aa_original[i].graph,
+                  aa_new[i].graph);
+          assertEquals("Visibility not identical.", aa_original[i].visible,
+                  aa_new[i].visible);
+          assertEquals("Threshold line not identical.",
+                  aa_original[i].threshold, aa_new[i].threshold);
           // graphGroup may differ, but pattern should be the same
-          Integer o_ggrp = new Integer(aa_original[i].graphGroup + 2), n_ggrp = new Integer(
-                  aa_new[i].graphGroup + 2);
-          BitSet orig_g = orig_groups.get(o_ggrp), new_g = new_groups
-                  .get(n_ggrp);
+          Integer o_ggrp = new Integer(aa_original[i].graphGroup + 2);
+          Integer n_ggrp = new Integer(aa_new[i].graphGroup + 2);
+          BitSet orig_g = orig_groups.get(o_ggrp);
+          BitSet new_g = new_groups.get(n_ggrp);
           if (orig_g == null)
           {
             orig_groups.put(o_ggrp, orig_g = new BitSet());
@@ -218,8 +214,8 @@ public class StockholmFileTest
           {
             new_groups.put(n_ggrp, new_g = new BitSet());
           }
-          assertTrue("Graph Group pattern differs at annotation " + i,
-                  orig_g.equals(new_g));
+          assertEquals("Graph Group pattern differs at annotation " + i,
+                  orig_g, new_g);
           orig_g.set(i);
           new_g.set(i);
         }
@@ -230,10 +226,9 @@ public class StockholmFileTest
         }
       }
     }
-    assertTrue(
-            "Generated and imported alignment have different annotation sets ("
-                    + aa_new_size + " != " + aa_original_size + ")",
-            aa_new_size == aa_original_size);
+    assertEquals(
+            "Generated and imported alignment have different annotation sets",
+            aa_new_size, aa_original_size);
 
     // check sequences, annotation and features
     SequenceI[] seq_original = new SequenceI[al.getSequencesArray().length];
@@ -260,8 +255,8 @@ public class StockholmFileTest
         {
           String ss_original = seq_original[i].getSequenceAsString();
           String ss_new = seq_new[in].getSequenceAsString();
-          assertTrue("The sequences " + name + "/" + start + "-" + end
-                  + " are not equal", ss_original.equals(ss_new));
+          assertEquals("The sequences " + name + "/" + start + "-" + end
+                  + " are not equal", ss_original, ss_new);
 
           assertTrue(
                   "Sequence Features were not equivalent"
@@ -284,15 +279,16 @@ public class StockholmFileTest
                     .getSequenceFeatures().length];
             sequenceFeatures_new = seq_new[in].getSequenceFeatures();
 
-            assertTrue("different number of features", seq_original[i]
-                    .getSequenceFeatures().length == seq_new[in]
+            assertEquals("different number of features",
+                    seq_original[i].getSequenceFeatures().length,
+                    seq_new[in]
                     .getSequenceFeatures().length);
 
             for (int feat = 0; feat < seq_original[i].getSequenceFeatures().length; feat++)
             {
-              assertTrue("Different features",
-                      sequenceFeatures_original[feat]
-                              .equals(sequenceFeatures_new[feat]));
+              assertEquals("Different features",
+                      sequenceFeatures_original[feat],
+                      sequenceFeatures_new[feat]);
             }
           }
           // compare alignment annotation
@@ -319,9 +315,9 @@ public class StockholmFileTest
           else if (al.getSequenceAt(i).getAnnotation() != null
                   && al_input.getSequenceAt(in).getAnnotation() == null)
           {
-            assertTrue("Annotations differed between sequences ("
+            fail("Annotations differed between sequences ("
                     + al.getSequenceAt(i).getName() + ") and ("
-                    + al_input.getSequenceAt(i).getName() + ")", false);
+                    + al_input.getSequenceAt(i).getName() + ")");
           }
           break;
         }
index 88f4331..e524cb4 100644 (file)
@@ -10,7 +10,7 @@ import org.testng.annotations.Test;
 public class UserColourSchemeTest
 {
 
-  @Test(groups = "functional")
+  @Test(groups = "Functional")
   public void testGetColourFromString()
   {
     /*
index d78e33e..aecdbf9 100644 (file)
@@ -29,6 +29,7 @@ import jalview.datamodel.SequenceFeature;
 import jalview.datamodel.SequenceI;
 import jalview.io.DataSourceType;
 import jalview.io.StructureFile;
+import jalview.util.MapList;
 
 import java.util.ArrayList;
 import java.util.List;
@@ -51,7 +52,11 @@ public class StructureSelectionManagerTest
   public void testRegisterMapping()
   {
     AlignedCodonFrame acf1 = new AlignedCodonFrame();
+    acf1.addMap(new Sequence("s1", "ttt"), new Sequence("p1", "p"),
+            new MapList(new int[] { 1, 3 }, new int[] { 1, 1 }, 1, 1));
     AlignedCodonFrame acf2 = new AlignedCodonFrame();
+    acf2.addMap(new Sequence("s2", "ttt"), new Sequence("p2", "p"),
+            new MapList(new int[] { 1, 3 }, new int[] { 1, 1 }, 1, 1));
 
     ssm.registerMapping(acf1);
     assertEquals(1, ssm.getSequenceMappings().size());
@@ -75,8 +80,14 @@ public class StructureSelectionManagerTest
   public void testRegisterMappings()
   {
     AlignedCodonFrame acf1 = new AlignedCodonFrame();
+    acf1.addMap(new Sequence("s1", "ttt"), new Sequence("p1", "p"),
+            new MapList(new int[] { 1, 3 }, new int[] { 1, 1 }, 1, 1));
     AlignedCodonFrame acf2 = new AlignedCodonFrame();
+    acf2.addMap(new Sequence("s2", "ttt"), new Sequence("p2", "p"),
+            new MapList(new int[] { 1, 3 }, new int[] { 1, 1 }, 1, 1));
     AlignedCodonFrame acf3 = new AlignedCodonFrame();
+    acf3.addMap(new Sequence("s3", "ttt"), new Sequence("p3", "p"),
+            new MapList(new int[] { 1, 3 }, new int[] { 1, 1 }, 1, 1));
 
     List<AlignedCodonFrame> set1 = new ArrayList<AlignedCodonFrame>();
     set1.add(acf1);
@@ -127,7 +138,7 @@ public class StructureSelectionManagerTest
     SequenceFeature sf = pmap.getSeqs().get(0).getSequenceFeatures()[0];
     assertEquals("RESNUM", sf.getType());
     assertEquals("1gaq", sf.getFeatureGroup());
-    assertEquals("GLU:  19  1gaqA", sf.getDescription());
+    assertEquals("GLU:19 1gaqA", sf.getDescription());
 
     /*
      * Verify a RESNUM sequence feature in the StructureSelectionManager mapped
@@ -137,6 +148,6 @@ public class StructureSelectionManagerTest
     sf = map.sequence.getSequenceFeatures()[0];
     assertEquals("RESNUM", sf.getType());
     assertEquals("1gaq", sf.getFeatureGroup());
-    assertEquals("ALA:   1  1gaqB", sf.getDescription());
+    assertEquals("ALA:1 1gaqB", sf.getDescription());
   }
 }
index c5e8ef5..96935ce 100644 (file)
@@ -33,6 +33,8 @@ import jalview.datamodel.PDBEntry;
 import jalview.datamodel.Sequence;
 import jalview.datamodel.SequenceI;
 
+import java.util.List;
+
 import org.testng.annotations.Test;
 
 public class DBRefUtilsTest
@@ -191,12 +193,13 @@ public class DBRefUtilsTest
     ref5.setMap(new Mapping(new MapList(new int[] { 1, 1 }, new int[] { 1,
         1 }, 1, 1)));
 
-    DBRefEntry[] matches = DBRefUtils.searchRefs(new DBRefEntry[] { ref1,
+    List<DBRefEntry> matches = DBRefUtils.searchRefs(new DBRefEntry[] {
+        ref1,
         ref2, ref3, ref4, ref5 }, target);
-    assertEquals(3, matches.length);
-    assertSame(ref1, matches[0]);
-    assertSame(ref2, matches[1]);
-    assertSame(ref5, matches[2]);
+    assertEquals(3, matches.size());
+    assertSame(ref1, matches.get(0));
+    assertSame(ref2, matches.get(1));
+    assertSame(ref5, matches.get(2));
   }
 
   /**
@@ -224,11 +227,12 @@ public class DBRefUtilsTest
             new int[] { 1, 1 }, 2, 2));
     ref3.setMap(map3);
 
-    DBRefEntry[] matches = DBRefUtils.searchRefs(new DBRefEntry[] { ref1,
+    List<DBRefEntry> matches = DBRefUtils.searchRefs(new DBRefEntry[] {
+        ref1,
         ref2, ref3 }, target);
-    assertEquals(2, matches.length);
-    assertSame(ref1, matches[0]);
-    assertSame(ref2, matches[1]);
+    assertEquals(2, matches.size());
+    assertSame(ref1, matches.get(0));
+    assertSame(ref2, matches.get(1));
   }
 
   /**
@@ -249,11 +253,42 @@ public class DBRefUtilsTest
     ref5.setMap(new Mapping(new MapList(new int[] { 1, 1 }, new int[] { 1,
         1 }, 1, 1)));
   
-    DBRefEntry[] matches = DBRefUtils.searchRefs(new DBRefEntry[] { ref1,
-        ref2, ref3, ref4, ref5 }, "A1234");
-    assertEquals(3, matches.length);
-    assertSame(ref1, matches[0]);
-    assertSame(ref2, matches[1]);
-    assertSame(ref5, matches[2]);
+    DBRefEntry[] dbrefs = new DBRefEntry[] { ref1,
+        ref2, ref3, ref4, ref5 };
+    List<DBRefEntry> matches = DBRefUtils.searchRefs(dbrefs, "A1234");
+    assertEquals(3, matches.size());
+    assertSame(ref1, matches.get(0));
+    assertSame(ref2, matches.get(1));
+    assertSame(ref5, matches.get(2));
+  }
+
+  /**
+   * Test the method that searches for matches references - case when we are
+   * matching a reference with null (any) accession id
+   */
+  @Test(groups = { "Functional" })
+  public void testSearchRefs_wildcardAccessionid()
+  {
+    DBRefEntry target = new DBRefEntry("EMBL", "2", null);
+  
+    DBRefEntry ref1 = new DBRefEntry("EMBL", "1", "A1234"); // matches
+    // constructor changes embl to EMBL
+    DBRefEntry ref2 = new DBRefEntry("embl", "1", "A1235"); // matches
+    // constructor does not upper-case accession id
+    DBRefEntry ref3 = new DBRefEntry("EMBL", "1", "A1236"); // matches
+    DBRefEntry ref4 = new DBRefEntry("EMBLCDS", "1", "A1234"); // no match
+    // ref5 matches although it has a mapping - ignored
+    DBRefEntry ref5 = new DBRefEntry("EMBL", "1", "A1237");
+    ref5.setMap(new Mapping(new MapList(new int[] { 1, 1 }, new int[] { 1,
+        1 }, 1, 1)));
+  
+    List<DBRefEntry> matches = DBRefUtils.searchRefs(new DBRefEntry[] {
+        ref1,
+        ref2, ref3, ref4, ref5 }, target);
+    assertEquals(4, matches.size());
+    assertSame(ref1, matches.get(0));
+    assertSame(ref2, matches.get(1));
+    assertSame(ref3, matches.get(2));
+    assertSame(ref5, matches.get(3));
   }
 }
index d4ed0ea..ba298c5 100644 (file)
@@ -563,6 +563,21 @@ public class MapListTest
             s);
   }
 
+  /**
+   * Test that confirms adding a map twice does nothing
+   */
+  @Test(groups = { "Functional" })
+  public void testAddMapList_sameMap()
+  {
+    MapList ml = new MapList(new int[] { 11, 15, 20, 25, 35, 30 },
+            new int[] { 72, 22 }, 1, 3);
+    String before = ml.toString();
+    ml.addMapList(ml);
+    assertEquals(before, ml.toString());
+    ml.addMapList(new MapList(ml));
+    assertEquals(before, ml.toString());
+  }
+
   @Test(groups = { "Functional" })
   public void testAddMapList_contiguous()
   {
index 492cbb6..6ba69b0 100644 (file)
@@ -706,6 +706,51 @@ public class MappingUtilsTest
     assertEquals(0, result.size());
   }
 
+  /**
+   * just like the one above, but this time, we provide a set of sequences to
+   * subselect the mapping search
+   */
+  @Test(groups = { "Functional" })
+  public void testFindMappingsBetweenSequenceAndOthers()
+  {
+    SequenceI seq1 = new Sequence("Seq1", "ABC");
+    SequenceI seq2 = new Sequence("Seq2", "ABC");
+    SequenceI seq3 = new Sequence("Seq3", "ABC");
+    SequenceI seq4 = new Sequence("Seq4", "ABC");
+    seq1.createDatasetSequence();
+    seq2.createDatasetSequence();
+    seq3.createDatasetSequence();
+    seq4.createDatasetSequence();
+
+    /*
+     * Create mappings from seq1 to seq2, seq2 to seq1, seq3 to seq1
+     */
+    AlignedCodonFrame acf1 = new AlignedCodonFrame();
+    MapList map = new MapList(new int[] { 1, 3 }, new int[] { 1, 3 }, 1, 1);
+    acf1.addMap(seq1.getDatasetSequence(), seq2.getDatasetSequence(), map);
+    AlignedCodonFrame acf2 = new AlignedCodonFrame();
+    acf2.addMap(seq2.getDatasetSequence(), seq1.getDatasetSequence(), map);
+    AlignedCodonFrame acf3 = new AlignedCodonFrame();
+    acf3.addMap(seq3.getDatasetSequence(), seq1.getDatasetSequence(), map);
+
+    List<AlignedCodonFrame> mappings = new ArrayList<AlignedCodonFrame>();
+    mappings.add(acf1);
+    mappings.add(acf2);
+    mappings.add(acf3);
+
+    /*
+     * Seq1 has three mappings
+     */
+    List<AlignedCodonFrame> result = MappingUtils
+            .findMappingsForSequenceAndOthers(seq1, mappings,
+                    new Alignment(new SequenceI[] { seq1, seq2 }));
+    assertTrue(result.contains(acf1));
+    assertTrue(result.contains(acf2));
+    assertFalse("Did not expect to find mapping acf3 - subselect failed",
+            result.contains(acf3));
+    assertEquals(2, result.size());
+  }
+
   @Test(groups = { "Functional" })
   public void testMapEditCommand()
   {
diff --git a/test/jalview/workers/AlignCalcManagerTest.java b/test/jalview/workers/AlignCalcManagerTest.java
new file mode 100644 (file)
index 0000000..735c75d
--- /dev/null
@@ -0,0 +1,147 @@
+package jalview.workers;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertFalse;
+import static org.testng.AssertJUnit.assertTrue;
+
+import jalview.api.AlignCalcManagerI;
+import jalview.api.AlignCalcWorkerI;
+import jalview.api.FeatureRenderer;
+import jalview.datamodel.Alignment;
+import jalview.datamodel.AlignmentAnnotation;
+import jalview.datamodel.AlignmentI;
+import jalview.datamodel.Annotation;
+import jalview.datamodel.Sequence;
+import jalview.datamodel.SequenceI;
+import jalview.gui.AlignFrame;
+
+import java.util.Collections;
+import java.util.List;
+
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class AlignCalcManagerTest
+{
+  private AlignFrame alignFrame;
+
+  /**
+   * Test the method that removes a worker associated with an annotation,
+   * provided the worker is marked as 'deletable' (some workers should continue
+   * to run even when their results are no longer displayed)
+   */
+  @Test(groups = "Functional")
+  public void testRemoveWorkerForAnnotation()
+  {
+    AlignCalcManagerI acm = alignFrame.getViewport().getCalcManager();
+    final AlignmentAnnotation ann1 = new AlignmentAnnotation("Ann1",
+            "desc",
+            new Annotation[] {});
+    final AlignmentAnnotation ann2 = new AlignmentAnnotation("Ann2",
+            "desc",
+            new Annotation[] {});
+
+    /*
+     * make two workers for ann1, one deletable, one not
+     * and no worker for ann2
+     */
+    AlignCalcWorkerI worker1 = makeWorker(ann1, true);
+    AlignCalcWorkerI worker2 = makeWorker(ann1, false);
+
+    /*
+     * The new workers will get run each in their own thread.
+     * We can't tell here whether they have finished, or not yet started.
+     * They have to finish to be 'seen' by getRegisteredWorkersOfClass()
+     *   registerWorker adds to the 'restartable' list but
+     *   getRegisteredWorkers reads from the 'canUpdate' list
+     *   (which is only updated after a worker has run) - why?
+     * So just give workers time to start and finish
+     */
+    synchronized (this)
+    {
+      try
+      {
+        wait(100);
+      } catch (InterruptedException e)
+      {
+        //
+      }
+    }
+
+    List<AlignCalcWorkerI> workers = acm.getRegisteredWorkersOfClass(worker1.getClass());
+    assertEquals(2, workers.size());
+    assertTrue(workers.contains(worker1));
+    assertTrue(workers.contains(worker2));
+    assertFalse(acm.isDisabled(worker1));
+    assertFalse(acm.isDisabled(worker2));
+
+    /*
+     * remove workers for ann2 (there aren't any)
+     */
+    acm.removeWorkerForAnnotation(ann2);
+    assertTrue(acm.getRegisteredWorkersOfClass(worker1.getClass())
+            .contains(worker1));
+    assertTrue(acm.getRegisteredWorkersOfClass(worker1.getClass())
+            .contains(worker2));
+    assertFalse(acm.isDisabled(worker1));
+    assertFalse(acm.isDisabled(worker2));
+
+    /*
+     * remove worker2 for ann1
+     * - should delete worker1 but not worker2
+     */
+    acm.removeWorkerForAnnotation(ann1);
+    assertEquals(1, acm.getRegisteredWorkersOfClass(worker1.getClass())
+            .size());
+    assertTrue(acm.getRegisteredWorkersOfClass(worker1.getClass())
+            .contains(worker2));
+    assertFalse(acm.isDisabled(worker1));
+    assertFalse(acm.isDisabled(worker2));
+  }
+
+  /**
+   * Make a worker linked to the given annotation
+   * 
+   * @param ann
+   * @param deletable
+   * @return
+   */
+  AnnotationWorker makeWorker(final AlignmentAnnotation ann,
+          final boolean deletable)
+  {
+    AnnotationProviderI annotationProvider = new AnnotationProviderI()
+    {
+      @Override
+      public List<AlignmentAnnotation> calculateAnnotation(AlignmentI al,
+              FeatureRenderer fr)
+      {
+        return Collections.singletonList(ann);
+      }
+    };
+    return new AnnotationWorker(alignFrame.getViewport(),
+            alignFrame.alignPanel,
+            annotationProvider)
+    {
+      @Override
+      public boolean isDeletable()
+      {
+        return deletable;
+      }
+
+      @Override
+      public boolean involves(AlignmentAnnotation ann1)
+      {
+        return ann == ann1;
+      }
+    };
+  }
+
+  @BeforeMethod(alwaysRun = true)
+  public void setUp()
+  {
+    AlignmentI al = new Alignment(new SequenceI[] { new Sequence("Seq1",
+            "ABC") });
+    al.setDataset(null);
+    alignFrame = new AlignFrame(al, 3, 1);
+  }
+}
index 0c810a3..fda0198 100644 (file)
@@ -26,6 +26,7 @@ import jalview.bin.Cache;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.SequenceI;
 import jalview.structure.StructureImportSettings;
+import jalview.structure.StructureImportSettings.StructureParser;
 import jalview.ws.seqfetcher.DbSourceProxy;
 
 import java.util.List;
@@ -86,7 +87,9 @@ public class PDBSequenceFetcherTest
   {
     Cache.applicationProperties.setProperty("STRUCT_FROM_PDB",
             Boolean.TRUE.toString());
-    StructureImportSettings.setCurrentDefaultFormat("PDB");
+    StructureImportSettings.setDefaultStructureFileFormat("PDB");
+    StructureImportSettings
+            .setDefaultPDBFileParser(StructureParser.JALVIEW_PARSER);
 
     testRetrieveProteinSeqFromPDB();
   }
@@ -96,7 +99,7 @@ public class PDBSequenceFetcherTest
   {
     Cache.applicationProperties.setProperty("STRUCT_FROM_PDB",
             Boolean.TRUE.toString());
-    StructureImportSettings.setCurrentDefaultFormat("mmCIF");
+    StructureImportSettings.setDefaultStructureFileFormat("mmCIF");
     testRetrieveProteinSeqFromPDB();
   }
 
index a54ce8b..94bf979 100644 (file)
@@ -1,5 +1,6 @@
 package jalview.ws;
 
+import jalview.analysis.CrossRef;
 import jalview.datamodel.Alignment;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.DBRefSource;
@@ -24,8 +25,6 @@ public class SequenceFetcherTest
     // TODO: extracted from SequenceFetcher - convert to proper unit test with
     // assertions
 
-    AlignmentI ds = null;
-    Vector<Object[]> noProds = new Vector<Object[]>();
     String usage = "SequenceFetcher.main [-nodas] [<DBNAME> [<ACCNO>]]\n"
             + "With no arguments, all DbSources will be queried with their test Accession number.\n"
             + "With one argument, the argument will be resolved to one or more db sources and each will be queried with their test accession only.\n"
@@ -44,7 +43,7 @@ public class SequenceFetcherTest
     {
       List<DbSourceProxy> sps = new SequenceFetcher(withDas)
               .getSourceProxy(argv[0]);
-  
+
       if (sps != null)
       {
         for (DbSourceProxy sp : sps)
@@ -52,7 +51,8 @@ public class SequenceFetcherTest
           AlignmentI al = null;
           try
           {
-            al = sp.getSequenceRecords(argv.length > 1 ? argv[1] : sp
+            testRetrieval(argv[0], sp,
+                    argv.length > 1 ? argv[1] : sp
                     .getTestQuery());
           } catch (Exception e)
           {
@@ -61,16 +61,6 @@ public class SequenceFetcherTest
                     + (argv.length > 1 ? argv[1] : sp.getTestQuery())
                     + " from " + argv[0] + "\nUsage: " + usage);
           }
-          SequenceI[] prod = al.getSequencesArray();
-          if (al != null)
-          {
-            for (int p = 0; p < prod.length; p++)
-            {
-              System.out.println("Prod " + p + ": "
-                      + prod[p].getDisplayId(true) + " : "
-                      + prod[p].getDescription());
-            }
-          }
         }
         return;
       }
@@ -95,139 +85,135 @@ public class SequenceFetcherTest
       }
       for (DbSourceProxy sp : sfetcher.getSourceProxy(db))
       {
-        System.out.println("Source: " + sp.getDbName() + " (" + db
-                + "): retrieving test:" + sp.getTestQuery());
-        AlignmentI al = null;
-        try
+        testRetrieval(db, sp, sp.getTestQuery());
+      }
+    }
+
+  }
+
+  private static void testRetrieval(String db, DbSourceProxy sp,
+          String testQuery)
+  {
+    AlignmentI ds = null;
+    Vector<Object[]> noProds = new Vector<Object[]>();
+    System.out.println("Source: " + sp.getDbName() + " (" + db
+            + "): retrieving test:" + sp.getTestQuery());
+    {
+      AlignmentI al = null;
+      try
+      {
+        al = sp.getSequenceRecords(testQuery);
+        if (al != null && al.getHeight() > 0)
         {
-          al = sp.getSequenceRecords(sp.getTestQuery());
-          if (al != null && al.getHeight() > 0)
+          boolean dna = sp.isDnaCoding();
+          al.setDataset(null);
+          AlignmentI alds = al.getDataset();
+          // try and find products
+          CrossRef crossRef = new CrossRef(al.getSequencesArray(), alds);
+          List<String> types = crossRef.findXrefSourcesForSequences(dna);
+          if (types != null)
           {
-            boolean dna = sp.isDnaCoding();
-            // try and find products
-            String types[] = jalview.analysis.CrossRef
-                    .findSequenceXrefTypes(dna, al.getSequencesArray());
-            if (types != null)
+            System.out.println("Xref Types for: " + (dna ? "dna" : "prot"));
+            for (String source : types)
             {
-              System.out.println("Xref Types for: "
-                      + (dna ? "dna" : "prot"));
-              for (int t = 0; t < types.length; t++)
+              System.out.println("Type: " + source);
+              SequenceI[] prod = crossRef.findXrefSequences(source, dna)
+                      .getSequencesArray();
+              System.out.println("Found "
+                      + ((prod == null) ? "no" : "" + prod.length)
+                      + " products");
+              if (prod != null)
               {
-                System.out.println("Type: " + types[t]);
-                SequenceI[] prod = jalview.analysis.CrossRef
-                        .findXrefSequences(al.getSequencesArray(), dna,
-                                types[t], null)
-                        .getSequencesArray();
-                System.out.println("Found "
-                        + ((prod == null) ? "no" : "" + prod.length)
-                        + " products");
-                if (prod != null)
+                for (int p = 0; p < prod.length; p++)
                 {
-                  for (int p = 0; p < prod.length; p++)
-                  {
-                    System.out.println("Prod " + p + ": "
-                            + prod[p].getDisplayId(true));
-                  }
+                  System.out.println("Prod " + p + ": "
+                          + prod[p].getDisplayId(true));
                 }
               }
             }
-            else
-            {
-              noProds.addElement((dna ? new Object[] { al, al }
-                      : new Object[] { al }));
-            }
-  
-          }
-        } catch (Exception ex)
-        {
-          System.out.println("ERROR:Failed to retrieve test query.");
-          ex.printStackTrace(System.out);
-        }
-  
-        if (al == null)
-        {
-          System.out.println("ERROR:No alignment retrieved.");
-          StringBuffer raw = sp.getRawRecords();
-          if (raw != null)
-          {
-            System.out.println(raw.toString());
           }
           else
           {
-            System.out.println("ERROR:No Raw results.");
+            noProds.addElement((dna ? new Object[] { al, al }
+                    : new Object[] { al }));
           }
+
+        }
+      } catch (Exception ex)
+      {
+        System.out.println("ERROR:Failed to retrieve test query.");
+        ex.printStackTrace(System.out);
+      }
+
+      if (al == null)
+      {
+        System.out.println("ERROR:No alignment retrieved.");
+        StringBuffer raw = sp.getRawRecords();
+        if (raw != null)
+        {
+          System.out.println(raw.toString());
         }
         else
         {
-          System.out.println("Retrieved " + al.getHeight() + " sequences.");
-          for (int s = 0; s < al.getHeight(); s++)
-          {
-            SequenceI sq = al.getSequenceAt(s);
-            while (sq.getDatasetSequence() != null)
-            {
-              sq = sq.getDatasetSequence();
-  
-            }
-            if (ds == null)
-            {
-              ds = new Alignment(new SequenceI[] { sq });
-  
-            }
-            else
-            {
-              ds.addSequence(sq);
-            }
-          }
+          System.out.println("ERROR:No Raw results.");
+        }
+      }
+      else
+      {
+        System.out.println("Retrieved " + al.getHeight() + " sequences.");
+        if (ds == null)
+        {
+          ds = al.getDataset();
+        }
+        else
+        {
+          ds.append(al.getDataset());
+          al.setDataset(ds);
         }
-        System.out.flush();
-        System.err.flush();
-  
       }
-      if (noProds.size() > 0)
+      System.out.flush();
+      System.err.flush();
+    }
+    if (noProds.size() > 0)
+    {
+      Enumeration<Object[]> ts = noProds.elements();
+      while (ts.hasMoreElements())
+
       {
-        Enumeration<Object[]> ts = noProds.elements();
-        while (ts.hasMoreElements())
-  
+        Object[] typeSq = ts.nextElement();
+        boolean dna = (typeSq.length > 1);
+        AlignmentI al = (AlignmentI) typeSq[0];
+        System.out.println("Trying getProducts for "
+                + al.getSequenceAt(0).getDisplayId(true));
+        System.out.println("Search DS Xref for: " + (dna ? "dna" : "prot"));
+        // have a bash at finding the products amongst all the retrieved
+        // sequences.
+        SequenceI[] seqs = al.getSequencesArray();
+        Alignment prodal = new CrossRef(seqs, ds).findXrefSequences(null,
+                dna);
+        System.out.println("Found "
+                + ((prodal == null) ? "no" : "" + prodal.getHeight())
+                + " products");
+        if (prodal != null)
         {
-          Object[] typeSq = ts.nextElement();
-          boolean dna = (typeSq.length > 1);
-          AlignmentI al = (AlignmentI) typeSq[0];
-          System.out.println("Trying getProducts for "
-                  + al.getSequenceAt(0).getDisplayId(true));
-          System.out.println("Search DS Xref for: "
-                  + (dna ? "dna" : "prot"));
-          // have a bash at finding the products amongst all the retrieved
-          // sequences.
-          SequenceI[] seqs = al.getSequencesArray();
-          Alignment prodal = jalview.analysis.CrossRef.findXrefSequences(
-                  seqs, dna, null, ds);
-          System.out.println("Found "
-                  + ((prodal == null) ? "no" : "" + prodal.getHeight())
-                  + " products");
-          if (prodal != null)
+          SequenceI[] prod = prodal.getSequencesArray(); // note
+          // should
+          // test
+          // rather
+          // than
+          // throw
+          // away
+          // codon
+          // mapping
+          // (if
+          // present)
+          for (int p = 0; p < prod.length; p++)
           {
-            SequenceI[] prod = prodal.getSequencesArray(); // note
-            // should
-            // test
-            // rather
-            // than
-            // throw
-            // away
-            // codon
-            // mapping
-            // (if
-            // present)
-            for (int p = 0; p < prod.length; p++)
-            {
-              System.out.println("Prod " + p + ": "
-                      + prod[p].getDisplayId(true));
-            }
+            System.out.println("Prod " + p + ": "
+                    + prod[p].getDisplayId(true));
           }
         }
-  
       }
-  
     }
   }
-
 }
index 9dc5303..fbee3a7 100644 (file)
@@ -51,6 +51,7 @@ import org.testng.annotations.AfterClass;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
 
+import compbio.metadata.Argument;
 import compbio.metadata.WrongParameterException;
 
 public class RNAStructExportImport
@@ -145,7 +146,6 @@ public class RNAStructExportImport
       } catch (InterruptedException x)
       {
       }
-      ;
     } while (af.getViewport().getCalcManager().isWorking());
 
     AlignmentI orig_alig = af.getViewport().getAlignment();
@@ -179,7 +179,6 @@ public class RNAStructExportImport
       } catch (InterruptedException x)
       {
       }
-      ;
     } while (af.getViewport().getCalcManager().isWorking());
 
     AlignmentI orig_alig = af.getViewport().getAlignment();
@@ -198,11 +197,11 @@ public class RNAStructExportImport
 
       String anfileout = new AnnotationFile()
               .printAnnotationsForAlignment(al);
-      assertTrue(
+      assertNotNull(
               "Test "
                       + testname
                       + "\nAlignment annotation file was not regenerated. Null string",
-              anfileout != null);
+              anfileout);
       assertTrue(
               "Test "
                       + testname
@@ -237,8 +236,8 @@ public class RNAStructExportImport
   @Test(groups = { "Functional" })
   public void testRnaalifoldSettingsRecovery()
   {
-    List<compbio.metadata.Argument> opts = new ArrayList<compbio.metadata.Argument>();
-    for (compbio.metadata.Argument rg : (List<compbio.metadata.Argument>) rnaalifoldws
+    List<Argument> opts = new ArrayList<Argument>();
+    for (Argument rg : (List<Argument>) rnaalifoldws
             .getRunnerConfig().getArguments())
     {
       if (rg.getDescription().contains("emperature"))
index 341d9ef..b3c7e10 100644 (file)
@@ -178,8 +178,8 @@ public class DbRefFetcherTest
             .getMap().getMappedWidth(), 1);
     assertEquals("Expected local reference map to be 3 nucleotides", dr[0]
             .getMap().getWidth(), 3);
-    AlignmentI sprods = CrossRef.findXrefSequences(
-            alsq.getSequencesArray(), true, dr[0].getSource(), alsq);
+    AlignmentI sprods = new CrossRef(alsq.getSequencesArray(), alsq)
+            .findXrefSequences(dr[0].getSource(), true);
     assertNotNull(
             "Couldn't recover cross reference sequence from dataset. Was it ever added ?",
             sprods);
index 27e5004..9d59b78 100644 (file)
@@ -251,8 +251,6 @@ public class SiftsClientTest
 
     // TODO delete when auto-fetching of DBRefEntry is implemented
     DBRefEntry dbRef = new DBRefEntry("uniprot", "", "P00221");
-    dbRef.setStartRes(1);
-    dbRef.setEndRes(147);
     testSeq.addDBRef(dbRef);
     // testSeq.setSourceDBRef(dbRef);
 
@@ -327,8 +325,6 @@ public class SiftsClientTest
       DBRefEntryI expectedDBRef = new DBRefEntry();
       expectedDBRef.setSource(DBRefSource.UNIPROT);
       expectedDBRef.setAccessionId("P00221");
-      expectedDBRef.setStartRes(1);
-      expectedDBRef.setEndRes(147);
       expectedDBRef.setVersion("");
       Assert.assertEquals(actualValidSrcDBRef, expectedDBRef);
     } catch (Exception e)
@@ -376,8 +372,6 @@ public class SiftsClientTest
     DBRefEntryI validDBRef = new DBRefEntry();
     validDBRef.setSource(DBRefSource.UNIPROT);
     validDBRef.setAccessionId("P00221");
-    validDBRef.setStartRes(1);
-    validDBRef.setEndRes(147);
     validDBRef.setVersion("");
     Assert.assertTrue(siftsClient.isValidDBRefEntry(validDBRef));
   }
index 1f666a4..1ad5322 100644 (file)
@@ -90,7 +90,7 @@ public class HelpLinksChecker
       return;
     }
 
-    internetAvailable &= connectToUrl("http://www.example.com");
+    internetAvailable &= connectToUrl("http://www.example.org");
 
     Map<String, String> tocTargets = checkHelpMappings(helpFolder);
 
index 7850eb5..9d322df 100644 (file)
@@ -5,6 +5,7 @@ import java.io.IOException;
 import java.util.HashSet;
 import java.util.Properties;
 import java.util.TreeSet;
+import java.util.regex.Pattern;
 
 /**
  * This class scans Java source files for calls to MessageManager and reports
@@ -22,18 +23,32 @@ import java.util.TreeSet;
 public class MessageBundleChecker
 {
   /*
+   * regex ^"[^"]*"$
+   * opening quote, closing quote, no quotes in between
+   */
+  static Pattern STRING_PATTERN = Pattern.compile("^\"[^\"]*\"$");
+
+  /*
    * number of text lines to read at a time in order to parse
    * code that is split over several lines
    */
   static int bufferSize = 3;
 
+  /*
+   * resource bundle key is arg0 for these methods
+   */
   static final String METHOD1 = "MessageManager.getString(";
 
-  static final String METHOD2 = "MessageManager.getStringOrReturn(";
+  static final String METHOD2 = "MessageManager.formatMessage(";
 
-  static final String METHOD3 = "MessageManager.formatMessage(";
+  static final String METHOD3 = "MessageManager.getStringOrReturn(";
 
-  static final String[] METHODS = { METHOD1, METHOD2, METHOD3 };
+  /*
+   * resource bundle key is arg1 for this method
+   */
+  static final String JVINIT = "JvSwingUtils.jvInitComponent(";
+
+  static final String[] METHODS = { METHOD1, METHOD2, METHOD3, JVINIT };
 
   /*
    * root of the Java source folders we want to scan
@@ -123,7 +138,7 @@ public class MessageBundleChecker
             + " possibly invalid parameter calls");
 
     System.out.println(messageKeys.size()
-            + " keys not found, possibly unused");
+            + " keys not found, either unused or constructed dynamically");
     for (String key : messageKeys)
     {
       System.out.println("    " + key);
@@ -169,6 +184,14 @@ public class MessageBundleChecker
     }
     javaCount++;
 
+    /*
+     * skip class with designed dynamic lookup call
+     */
+    if (path.endsWith("gui/JvSwingUtils.java"))
+    {
+      return;
+    }
+
     String[] lines = new String[bufferSize];
     BufferedReader br = new BufferedReader(new FileReader(f));
     for (int i = 0; i < bufferSize; i++)
@@ -231,30 +254,61 @@ public class MessageBundleChecker
       {
         continue;
       }
-      String methodArgs = combined.substring(pos + method.length());
+
+      /*
+       * extract what follows the opening bracket of the method call
+       */
+      String methodArgs = combined.substring(pos + method.length()).trim();
       if ("".equals(methodArgs))
       {
         /*
-         * continues on next line - catch in the next read loop iteration
+         * arguments are on next line - catch in the next read loop iteration
          */
         continue;
       }
-      if (!methodArgs.startsWith("\""))
+      if (methodArgs.indexOf(",") == -1 && methodArgs.indexOf(")") == -1)
       {
-        System.out.println(String.format(
-                "Possible dynamic key at %s line %s %s",
+        /*
+         * arguments continue on next line - catch in the next read loop iteration
+         */
+        continue;
+      }
+
+      if (JVINIT == method && methodArgs.indexOf(",") == -1)
+      {
+        /*
+         * not interested in 1-arg calls to jvInitComponent
+         */
+        continue;
+      }
+
+      if (METHOD3 == method)
+      {
+        System.out.println(String.format("Dynamic key at %s line %s %s",
                 path.substring(sourcePath.length()), lineNos, combined));
         continue;
       }
-      methodArgs = methodArgs.substring(1);
-      int quotePos = methodArgs.indexOf("\"");
-      if (quotePos == -1)
+
+      String messageKey = getMessageKey(method, methodArgs);
+      if (messageKey == null)
       {
         System.out.println(String.format("Trouble parsing %s line %s %s",
                 path.substring(sourcePath.length()), lineNos, combined));
         continue;
       }
-      String messageKey = methodArgs.substring(0, quotePos);
+
+      if (!(STRING_PATTERN.matcher(messageKey).matches()))
+      {
+        System.out.println(String.format("Dynamic key at %s line %s %s",
+                path.substring(sourcePath.length()), lineNos, combined));
+        continue;
+      }
+
+      /*
+       * strip leading and trailing quote
+       */
+      messageKey = messageKey.substring(1, messageKey.length() - 1);
+
       if (!this.messages.containsKey(messageKey))
       {
         System.out.println(String.format(
@@ -269,6 +323,47 @@ public class MessageBundleChecker
     }
   }
 
+  /**
+   * Helper method to parse out the resource bundle key parameter of a method
+   * call
+   * 
+   * @param method
+   * @param methodArgs
+   *          the rest of the source line starting with arguments to method
+   * @return
+   */
+  private String getMessageKey(String method, String methodArgs)
+  {
+    String key = methodArgs;
+
+    /*
+     * locate second argument if calling jvInitComponent()
+     */
+    if (method == JVINIT)
+    {
+      int commaLoc = methodArgs.indexOf(",");
+      if (commaLoc == -1)
+      {
+        return null;
+      }
+      key = key.substring(commaLoc + 1).trim();
+    }
+
+    /*
+     * take up to next comma or ) or end of line
+     */
+    int commaPos = key.indexOf(",");
+    int bracePos = key.indexOf(")");
+    int endPos = commaPos == -1 ? bracePos : (bracePos == -1 ? commaPos
+            : Math.min(commaPos, bracePos));
+    if (endPos == -1 && key.length() > 1 && key.endsWith("\""))
+    {
+      endPos = key.length();
+    }
+
+    return endPos == -1 ? null : key.substring(0, endPos);
+  }
+
   private String combineLines(String[] lines)
   {
     String combined = "";
diff --git a/utils/checkstyle/README.txt b/utils/checkstyle/README.txt
new file mode 100644 (file)
index 0000000..e38064e
--- /dev/null
@@ -0,0 +1,85 @@
+Checkstyle for Jalview
+----------------------
+
+http://checkstyle.sourceforge.net/
+GNU LGPL
+
+To get the Eclipse Checkstyle plugin
+------------------------------------
+       - Help | Eclipse Marketplace
+       - search for checkstyle
+       - install eclipse-cs checkstyle plugin
+The current version is 6.19.1 (August 2016).
+
+Config
+------
+
+       File Jalview/.checkstyle holds configuration for the "JalviewCheckstyle" ruleset.
+       This includes confining its scope to src/*.java and resources/*.properties.
+       This can be modified interactively through the checkstyle properties editor.
+       
+       Checkstyle config files in utils/checkstyle:
+               checkstyle.xml          : main configuration file with selected checkstyle modules
+               checkstyle-suppress.xml : rules to exclude certain checks / files
+               import-control.xml      : package import rules
+       
+       Checkstyle error messages can be customised. See TypeName for an example.
+
+How to use checkstyle
+---------------------
+
+       Option 1: enable it for the Jalview project
+               - right-click on project | Checkstyle | Activate Checkstyle
+               - notice CheckstyleNature gets added to the .project file
+               - don't commit this file unless we all agree to!
+               - Checkstyle will run as you recompile changed code
+
+       Option 2: on demand on selected code
+               - right-click on a class or package and Checkstyle | Check code with checkstyle
+               - (or Clear Checkstyle violations to remove checkstyle warnings)
+
+Checkstyle rules
+----------------
+       Documented at http://checkstyle.sourceforge.net/checks.html
+       Should be self-documenting in checkstyle.xml
+       Open for discussion:
+       - which rules to use
+       - what naming and layout standards to apply
+       - settings for complexity metrics
+       - whether any rules should report an error instead of a warning  
+       
+Suppressing findings
+--------------------
+       If there are warnings you judge it ok to suppress (false positives), 
+       your options are (from most global to most local impact):
+       - remove the rule entirely
+       - adjust its properties
+       - add an entry in checkstyle-suppress.xml to skip the file for the rule
+       - add comments around the reported source lines
+               // CHECKSTYLE.OFF: RuleName 'a comment to justify suppression'
+               source code here
+               // CHECKSTYLE.ON: RuleName
+       The suppression should be as localised as possible, to avoid false negatives.
+       
+Tips
+----
+       Sometimes checkstyle needs a kick before it will refresh its findings.
+       A whitespace edit in checkstyle.xml usually does this. There may be better ways.
+       
+       Invalid configuration files may result in checkstyle failing with an error reported
+       in the Eclipse log file. 
+       Help | Installation Details | Configuration takes you to a screen with a 
+       'View Error Log' button.
+       
+       Sometimes checkstyle can fail silently. Try 'touching' (editing) config files, failing
+       that, carefully check / back out / redo any recent changes to its config.
+       
+       Putting <!-- XML comments --> inside a checkstyle <module> causes it to be ignored!
+       
+       If a rule doesn't behave as you expected, read its documentation carefully, including
+       the use and default value of any properties.
+       
+       To highlight a single rule's findings, you can 'Configure Contents' of the Problems view
+       and filter on Text Contains <rule name> (case-sensitive). 
+       Here you should select 'Use item limits' with a value of, say, 500,     or Eclipse may 
+       labour to display all warnings.
diff --git a/utils/checkstyle/checkstyle-suppress.xml b/utils/checkstyle/checkstyle-suppress.xml
new file mode 100644 (file)
index 0000000..ac9e260
--- /dev/null
@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!DOCTYPE suppressions PUBLIC
+    "-//Puppy Crawl//DTD Suppressions 1.1//EN"
+    "http://www.puppycrawl.com/dtds/suppressions_1_1.dtd">
+
+<suppressions>
+       <!-- 
+               Do not put individual file-level suppressions here.
+               Instead use embedded comments to switch checks on and off.
+    -->
+        
+    <!-- 
+        Suppress check of XML binding generated code packages 
+    --> 
+    <suppress checks="[a-zA-Z0-9]*" files="jalview[\\/]schemabinding[\\/]*"/>
+    <suppress checks="[a-zA-Z0-9]*" files="jalview[\\/]binding[\\/]*"/>
+    <suppress checks="[a-zA-Z0-9]*" files="jalview[\\/]json[\\/]binding[\\/]*"/>
+    <suppress checks="[a-zA-Z0-9]*" files="jalview[\\/]xml[\\/]binding[\\/]*"/>
+        
+    <!-- 
+       Suppress check of externally sourced code 
+    --> 
+    <suppress checks="[a-zA-Z0-9]*" files="com[\\/]*"/>
+    <suppress checks="[a-zA-Z0-9]*" files="ext[\\/]*"/>
+    <suppress checks="[a-zA-Z0-9]*" files="org[\\/]*"/>
+    <suppress checks="[a-zA-Z0-9]*" files="uk[\\/]*"/>
+    
+    <!-- 
+       ImportControl can only handle one top level package
+    -->
+    <suppress checks="ImportControl" files="MCview[\\/]*" />
+    <suppress checks="ImportControl" files="vamsas[\\/]*" />
+    
+    <!--  
+       Suppress checks by name 
+    -->
+       <suppress checks="FinalLocalVariable" files=".*\.java"/>
+    
+    <!--  
+       Suppress checks by id 
+    -->
+       <suppress id="InterfaceNaming" files=".*\.java"/>
+       <suppress id="NoStaticInitialization" files=".*\.java"/>
+         
+</suppressions>
\ No newline at end of file
diff --git a/utils/checkstyle/checkstyle.xml b/utils/checkstyle/checkstyle.xml
new file mode 100644 (file)
index 0000000..8a5f14f
--- /dev/null
@@ -0,0 +1,601 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.3//EN" "http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
+<!--
+       Jalview Checkstyle configuration file
+-->
+<module name="Checker">
+       <!-- Default severity is warning -->
+       <property name="severity" value="warning"/>
+       <property name="fileExtensions" value="java,properties"/>
+
+       <!-- 
+               Add any metrics that you wish to suppress to the following file.
+       -->
+       <module name="SuppressionFilter">
+               <property name="file" value="${basedir}/utils/checkstyle/checkstyle-suppress.xml"/>
+       </module>
+
+       <!-- 
+               Allow suppression of rules by comments, e.g.:
+               // CHECKSTYLE.OFF: ParameterNumber
+               ..method declaration
+               // CHECKSTYLE.ON: ParameterNumber
+       -->
+       <module name="SuppressionCommentFilter">
+               <property name="offCommentFormat" value="CHECKSTYLE.OFF\: ([\w\|]+)"/>
+               <property name="onCommentFormat" value="CHECKSTYLE.ON\: ([\w\|]+)"/>
+               <property name="checkFormat" value="$1"/>
+       </module>
+
+       <!-- 
+               Check language bundles have the same keys and no duplicates
+               (ensure Checkstyle is configured to scan non-source files)
+        -->
+       <module name="Translation">
+               <property name="fileExtensions" value="properties"/>
+               <property name="baseName" value="^Messages.*$"/>
+       </module>
+       <module name="UniqueProperties">
+           <property name="fileExtensions" value="properties" />
+               <property name="severity" value="error"/>
+       </module>
+
+       <!--
+               Maximum line count for source files
+               (note this can't be inside TreeWalker)
+       -->
+       <module name="FileLength">
+               <property name="max" value="1200"/>
+               <property name="fileExtensions" value="java"/>
+       </module>
+       
+       <module name="TreeWalker">
+
+               <property name="tabWidth" value="4"/>
+
+               <!-- 
+                       Enables parsing of suppressions comments
+                       see http://checkstyle.sourceforge.net/config_filters.html#SuppressionCommentFilter 
+               -->
+               <module name="FileContentsHolder"/>
+
+       <!-- ****************************** -->
+       <!--         NAMING STANDARDS       -->
+       <!-- ****************************** -->
+               
+               <!--
+                       Naming convention for member fields. Start with (optional) underscore, then
+                       lower case, then camel case; no internal underscores
+               -->
+               <module name="MemberName">
+                       <property name="format" value="^_?[a-z][a-zA-Z0-9]*$"/>
+               </module>
+
+               <!-- 
+                       Naming convention for methods. Start with (optional) underscore, then
+                       lower case, then camel case; no internal underscores
+               -->
+               <module name="MethodName">
+                       <property name="format" value="^_?[a-z]([a-zA-Z0-9]+)*$"/>
+               </module>
+
+               <!--
+                       Name pattern for local final variables.
+               -->
+               <module name="LocalFinalVariableName">
+                       <property name="format" value="^[a-z][a-zA-Z0-9]*$"/>
+               </module>
+
+               <!--
+                       Name pattern for local variables
+               -->
+               <module name="LocalVariableName">
+                       <property name="format" value="^[a-z][a-zA-Z0-9]*$"/>
+               </module>
+               
+               <!--
+                       Name pattern for constants (static final fields)
+               -->
+               <module name="ConstantName">
+                       <property name="format" value="^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$"/>
+               </module>
+
+               <!--
+                       Name pattern for parameters (note no underscores allowed)
+               -->
+               <module name="ParameterName">
+                       <property name="format" value="^[a-z][a-zA-Z0-9]*$"/>
+               </module>
+               
+               <!--
+                       Name pattern for static (non-final) fields
+               -->
+               <module name="StaticVariableName">
+                       <property name="format" value="^[a-z][a-zA-Z0-9_]*$"/>
+               </module>
+               
+               <!--
+                       Name pattern for classes
+               -->
+               <module name="TypeName">
+                       <property name="format" value="[A-Z][a-zA-Z0-9]*$"/>
+                       <property name="tokens" value="CLASS_DEF"/>
+               </module>
+               
+               <!--
+                       Name pattern for interfaces. All interfaces names must end with 'I'.
+                       ** currently suppressed in checkstyle-suppress.xml **
+               -->
+               <module name="TypeName">
+                       <property name="id" value="InterfaceNaming"/>
+                       <property name="format" value="^[A-Z][a-zA-Z0-9]*I$"/>
+                       <property name="tokens" value="INTERFACE_DEF"/>
+                       <message key="name.invalidPattern" value="Interface names should end in a I"/>
+               </module>
+
+               <!--
+                       Java package name pattern 
+               -->
+               <module name="PackageName">
+                       <property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$"/>
+               </module>
+
+       <!-- ****************************** -->
+       <!--         LAYOUT AND STYLE       -->
+       <!-- ****************************** -->
+
+               <!-- 
+                       Only one top level type per source file
+               -->
+               <module name="OuterTypeNumber"/>
+               
+               <!-- 
+                       Ensure a class has a package declaration
+                -->
+               <module name="PackageDeclaration"/>
+               
+               <!--
+                       see http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141855.html#1852
+                       1. Class (static) variables: public, protected, package, private
+                       2. Instance variables: public, protected, package, private
+                       3. Constructors
+                       4. Methods
+                -->
+               <module name="DeclarationOrder"/>
+               
+               <!-- 
+                       Modifier order should conform to JLS
+                       see http://checkstyle.sourceforge.net/config_modifier.html#ModifierOrder 
+                       public protected private abstract static final transient volatile synchronized native strictfp          
+               -->
+               <module name="ModifierOrder"/>
+               
+               <!-- 
+                       Declare variables in separate statements, for readability and bug avoidance
+                -->
+               <module name="MultipleVariableDeclarations"/>
+               
+               <!-- 
+                       Don't have more than one statement on a line
+                       (code formatting on save may enforce this anyway)
+                -->
+               <module name="OneStatementPerLine"/>
+
+               <!-- 
+                       Declare variables close to their point of first use 
+                       (doesn't handle variables used inside loops very well) 
+               -->
+               <module name="VariableDeclarationUsageDistance">
+                       <property name="allowedDistance" value="5" />
+                       <message key="variable.declaration.usage.distance.extend"
+                               value="Distance between declaration of ''{0}'' and its first use is {1}, suggested maximum is {2}. Consider moving, or make final if it may not be modified." />
+               </module>
+       
+               <!-- 
+                       Only use blocks within control statements 
+               -->
+               <module name="AvoidNestedBlocks" />
+
+               <!-- 
+                       Require at least a comment within a block. 
+                       Note this will accept auto-generated // TODO comments, 
+                       (but they should be flagged up by the TodoComment rule) 
+               -->
+               <module name="EmptyBlock">
+                       <property name="option" value="text"/>
+               </module>
+               
+               <!-- 
+                       Require braces round all code blocks within if/else/for/do/while 
+               -->
+               <module name="NeedBraces"/>
+               
+               <!--
+                       Disallow empty ';' statements
+               -->
+               <module name="EmptyStatement"/>
+
+               <!-- 
+                       Maximum number of return statements for a method
+               -->
+               <module name="ReturnCount">
+                       <property name="max" value="4"/>
+               </module>
+
+               <!-- 
+                       Don't use modifiers in contexts where their value is not optional,
+                       for example all interface methods are always public
+                       see http://checkstyle.sourceforge.net/config_modifier.html#RedundantModifier
+               -->
+               <module name="RedundantModifier"/>
+               
+               <!-- 
+                       Variables whose value is not modified should be declared final, both to show the
+                   program's intent, and to  allow compiler optimisation
+                   ** currently suppressed in checkstyle-suppress.xml **
+                -->            
+               <module name="FinalLocalVariable">
+                       <property name="tokens" value="VARIABLE_DEF" />
+               </module>
+
+               <!-- 
+                       Disallows shorthand of assigning values within an expression 
+               -->
+               <module name="InnerAssignment"/>
+
+               <!-- 
+                       Use Java style array declarations to assist in readability 
+               -->
+               <module name="ArrayTypeStyle"/>
+
+               <!-- 
+                       Use L not l to define a long constant 
+               -->
+               <module name="UpperEll"/>
+
+       <!-- ****************************** -->
+       <!--           SIZE LIMITS          -->
+       <!-- ****************************** -->
+
+               <!--
+                       Maximum line count for methods
+               -->
+               <module name="MethodLength">
+                       <property name="tokens" value="METHOD_DEF"/>
+                       <property name="max" value="50"/>
+                       <property name="countEmpty" value="false"/>
+               </module>
+
+               <!--
+                       Maximum statement count for methods, constructors,
+                       instance initialisation and static initialisation blocks
+               -->
+               <module name="ExecutableStatementCount">
+                       <property name="max" value="30"/>
+                       <property name="tokens" value="METHOD_DEF"/>
+               </module>
+               <module name="ExecutableStatementCount">
+                       <property name="max" value="30"/>
+                       <property name="tokens" value="CTOR_DEF"/>
+               </module>
+               <module name="ExecutableStatementCount">
+                       <property name="max" value="4"/>
+                       <property name="tokens" value="INSTANCE_INIT"/>
+               </module>
+               <module name="ExecutableStatementCount">
+                       <property name="id" value="NoStaticInitialization"/>
+                       <property name="max" value="0"/>
+                       <property name="tokens" value="STATIC_INIT"/>
+               </module>
+
+               <!--
+                       Maximum parameter count for methods 
+               -->
+               <module name="ParameterNumber">
+                       <property name="max" value="5"/>
+               </module>
+
+               <!--
+                       Maximum line length for anonymous inner classes
+               -->
+               <module name="AnonInnerLength">
+                       <property name="max" value="40"/>
+               </module>
+
+       <!-- ****************************** -->
+       <!--            IMPORTS             -->
+       <!-- ****************************** -->
+
+               <!-- 
+                       Ensures that there are no redundant or unused imports.
+                    Should be handled by Save actions if using Eclipse 
+               -->
+               <module name="RedundantImport"/>
+               <module name="UnusedImports"/>
+
+               <!--
+                       Disallow * imports; may also be enforced by IDE Save Actions
+               -->
+               <module name="AvoidStarImport"/>
+
+               <!-- 
+                       Disallow import of sun.* packages as they are not portable 
+               -->
+               <module name="IllegalImport"/>
+
+               <!--
+                       rules as to what packages each package may (not) import
+                       see http://checkstyle.sourceforge.net/config_imports.html#ImportControl 
+               -->
+               <module name="ImportControl">
+                   <property name="file" value="${basedir}/utils/checkstyle/import-control.xml"/>
+                       <property name="severity" value="error"/>
+               </module>
+               
+       <!-- ****************************** -->
+       <!--         CATCH and THROW        -->
+       <!-- ****************************** -->
+
+               <!-- 
+                       Disallow catch of Exception, RunTimeException or Error 
+               -->
+               <module name="IllegalCatch"/>
+
+               <!-- 
+                       Disallow throw of Exception, RunTimeException or Error 
+               -->
+               <module name="IllegalThrows"/>
+
+       <!-- ****************************** -->
+       <!--          CODING CHECKS         -->
+       <!-- ****************************** -->
+
+               <!-- 
+                       Check for use of factory method rather than constructor for specified classes
+                       e.g. Boolean.valueOf(true) rather than new Boolean(true)
+               -->
+               <module name="IllegalInstantiation">
+                       <property name="classes" value="java.lang.Boolean"/>
+               </module>
+               
+               <!--
+                       Check that "string".equals(value) is used rather than value.equals("string")
+               -->
+               <module name="EqualsAvoidNull"/>
+
+               <!--
+                       Check that equals() and hashCode() are always overridden together
+               -->
+               <module name="EqualsHashCode"/>
+               
+               <!-- 
+                       Require switch statements to include a default 
+               -->
+               <module name="MissingSwitchDefault"/>
+               
+               <!-- 
+                       Check that switch default follows all case statements
+                -->
+               <module name="DefaultComesLast">
+                       <property name="severity" value="error"/>
+               </module>
+               
+               <!-- 
+                       Disallows fall-through in switch statements 
+                       i.e. a case without a break, return, throw or continue 
+                       NB a comment with the words "fall[s] through" suppresses this message
+                -->
+               <module name="FallThrough">
+                       <property name="severity" value="error" />
+               </module>
+               
+               <!-- 
+                       Warn if boolean expressions can be simplified 
+               -->
+               <module name="SimplifyBooleanExpression"/>
+
+               <!-- 
+                       Warn if boolean return expressions can be simplified 
+               -->
+               <module name="SimplifyBooleanReturn"/>
+
+               <!--
+                       Classes with only private constructors should be declared final
+               -->
+               <module name="FinalClass"/>
+               
+               <!-- 
+                       Classes with only static methods should not be instantiable,
+                       so should declare a private default constructor.
+               -->
+               <module name="HideUtilityClassConstructor"/>
+               
+               <!-- 
+                       An Interface should declare methods (do not use to define constants only) 
+               -->
+               <module name="InterfaceIsType"/>
+               
+               <!-- 
+                       Disallow public fields in classes (other than constants) 
+               -->
+               <module name="VisibilityModifier">
+                       <property name="packageAllowed" value="true"/>
+                       <property name="allowPublicImmutableFields" value="true"/>
+               </module>
+               
+               <!-- 
+                       Checks that a local variable or a parameter does not shadow a field that is defined in the same class.
+                       Note this should also be configured as a compiler warning in the IDE. 
+               -->
+               <module name="HiddenField"/> 
+
+               <!-- 
+                       Check that proper logging is used.
+                       This may be suppressed in the class that provides logging functions.
+               -->
+               <module name="RegexpSinglelineJava">
+                       <property name="id" value="NoSysout" />
+                       <property name="format" value="System\.out\.println"/>
+                       <property name="ignoreComments" value="true"/>
+                       <message key="regexp.exceeded" value="Should use jalview.bin.Cache.log for logging"/>
+               </module>
+               <module name="RegexpSinglelineJava">
+                       <property name="id" value="NoSyserr" />
+                       <property name="format" value="System\.err\.println"/>
+                       <property name="ignoreComments" value="true"/>
+                       <message key="regexp.exceeded" value="Should use jalview.bin.Cache.log for logging"/>
+               </module>
+
+               <!--
+                       Checks that classes that define a covariant equals() method also override 
+                       method equals(java.lang.Object).
+                -->
+               <module name="CovariantEquals"/>
+               
+               <!-- 
+                       Checks that there are no "magic numbers" (numeric literals) 
+               -->
+               <module name="MagicNumber">
+                       <property name="ignoreNumbers" value="-1,0,1,2"/>
+               </module>
+               
+               <!-- 
+                       Check that  loop control variables are not modified inside the for block
+                -->
+               <module name="ModifiedControlVariable">
+               </module>
+               
+               <!-- 
+                       Checks that string literals are not used with == or !=.
+                -->
+               <module name="StringLiteralEquality">
+               </module>
+               
+               <!-- 
+                       Don't override clone - it never works! 
+                -->
+               <module name="NoClone"/>
+               
+               <!-- 
+                       Checks that clone() invokes super.clone()
+                       (for classes that break the NoClone rule)
+                -->
+               <module name="SuperClone"/>
+               
+               <!-- 
+                       Checks that finalize() invokes super.finalize()
+                -->
+               <module name="SuperFinalize"/>
+               
+               <!-- 
+                       Disallow assignment of parameters.
+                -->
+               <module name="ParameterAssignment"/>
+
+               <!-- 
+                       Checks for multiple occurrences of the same string literal within a single file.
+                       NB - does not check for the same string in different files.
+                -->
+               <module name="MultipleStringLiterals">
+                       <property name="allowedDuplicates" value="1"/>
+               </module>
+               
+               <!-- 
+                       Checks that exceptions are immutable (have only final fields)
+                -->
+               <module name="MutableException"/>
+               
+               <!-- 
+                       A general rule to check for source text tokens that shouldn't be there
+                       see http://checkstyle.sourceforge.net/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html
+                -->
+               <module name="IllegalToken">
+                  <property name="tokens" value="LITERAL_ASSERT"/>
+               </module>
+
+       <!-- ****************************** -->
+       <!--           COMPLEXITY           -->
+       <!-- ****************************** -->
+               
+               <!-- 
+                       Restrict the number of number of &&, ||, &, |  and ^ in an expression.
+                       Note that the operators & and | are not only integer bitwise operators, they are also the 
+                       non-shortcut versions of the boolean operators && and ||.
+                -->
+               <module name="BooleanExpressionComplexity">
+                       <property name="max" value="3"/>
+               </module>
+               
+               <!-- 
+                       This metric measures the number of instantiations of other classes within the given class. 
+                       The higher the DAC, the more complex the data structure of the system.
+                -->
+               <module name="ClassDataAbstractionCoupling">
+                       <property name="max" value="7"/>
+               </module>
+               
+               <!-- 
+                       The number of other classes a class relies on. A high number indicates over-complex
+                       class interdependencies that might benefit from refactoring.
+                -->
+               <module name="ClassFanOutComplexity">
+               <property name="max" value="10"/>
+       </module>
+               
+               <!-- 
+                       Checks cyclomatic complexity against a specified limit. The complexity is a measure 
+                       of the minimum number of possible paths through the source and therefore the number of required 
+                       tests. Consider re-factoring if at or above 10.
+                -->
+               <module name="CyclomaticComplexity">
+                       <property name="max" value="15"/>
+               </module>
+               
+               <!-- 
+                       The NPATH metric computes the number of possible execution paths through a function. It takes 
+                       into account the nesting of conditional statements and multi-part boolean expressions 
+                       (e.g., A && B, C || D, etc.).
+                -->
+               <module name="NPathComplexity">
+                       <property name="max" value="200"/>
+               </module>
+
+               <!-- 
+                       Maximum number of throws statements in a method
+                -->
+               <module name="ThrowsCount">
+                       <property name="max" value="2"/>
+               </module>
+               
+               <!-- 
+                       Maximum if-else depth
+                -->
+               <module name="NestedIfDepth">
+                       <property name="max" value="4"/>
+               </module>
+
+               <!-- 
+                       Restricts nested try blocks to a specified depth. 
+                -->
+               <module name="NestedTryDepth">
+                       <property name="max" value="2"/>
+               </module>
+
+       <!-- ****************************** -->
+       <!--              TODO              -->
+       <!-- ****************************** -->
+
+               <!-- 
+                       Checks for uncommented main() methods (debugging leftovers)
+                -->
+               <module name="UncommentedMain"/>
+
+               <!-- 
+                       Check for TODO and similar comments 
+               -->
+               <module name="TodoComment">
+                       <property name="format" value="(TODO)|(FIXME)|(DOCUMENT ME)"/>
+               </module>
+
+       </module>
+</module>
diff --git a/utils/checkstyle/import-control.xml b/utils/checkstyle/import-control.xml
new file mode 100644 (file)
index 0000000..b11b567
--- /dev/null
@@ -0,0 +1,128 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!DOCTYPE import-control PUBLIC
+    "-//Puppy Crawl//DTD Import Control 1.1//EN"
+    "http://www.puppycrawl.com/dtds/import_control_1_1.dtd">
+    
+    <!--
+       see http://checkstyle.sourceforge.net/config_imports.html#ImportControl
+       allow/disallow rules propagate to sub-packages 
+       unless local-only="true" is specified
+       
+       note this can handle only one top-level package, so ImportControl is
+       suppressed for MCview and vamsas in checkstyle-suppress.xml
+       (all rules are suppressed for com/ext/org/uk)
+    -->
+   <import-control pkg="jalview">
+   
+               <allow pkg="java"/>
+               <allow pkg="jalview"/>
+               <allow pkg="com.stevesoft.pat"/>
+               
+               <subpackage name="appletgui">
+               <disallow pkg="jalview.gui"/>
+               <disallow pkg="jalview.ws"/>
+               <allow pkg="org.jmol"/>
+               <allow pkg="javajs.awt" class="jalview.appletgui.AppletJmolBinding"/>
+           </subpackage>
+               
+               <subpackage name="bin">
+               <allow pkg="groovy"/>
+               <allow pkg="org.apache.log4j" class="jalview.bin.Cache"/>
+               <allow pkg="javax.swing" class="jalview.bin.Jalview"/>
+               <allow pkg="netscape.javascript" class="jalview.bin.JalviewLite"/>
+           </subpackage>
+               
+               <subpackage name="datamodel">
+               <disallow pkg="jalview.gui"/>
+               <allow pkg="fr.orsay.lri.varna"/>
+                       <subpackage name="xdb">
+                               <subpackage name="embl">
+                               <allow pkg="org.exolab.castor"/>
+                           </subpackage>
+                   </subpackage>
+           </subpackage>
+               
+               <subpackage name="fts">
+               <allow pkg="javax.swing"/>
+               <allow pkg="javax.ws"/>
+               <allow pkg="org.json"/>
+               <allow pkg="com.sun.jersey"/>
+           </subpackage>
+               
+               <subpackage name="gui">
+               <allow pkg="javax.swing"/>
+               <allow pkg="javax.help"/>
+               <allow pkg="javax.imageio"/>
+               <allow pkg="ext.edu.ucsf"/>
+               <allow pkg="net.miginfocom"/>
+               <allow pkg="org.jibble"/>
+               <allow pkg="org.jmol"/>
+               <allow pkg="org.openscience"/>
+               <allow pkg="org.exolab.castor" class="jalview.gui.Jalview2XML"/>
+               <allow pkg="org.robsite" class="jalview.gui.BlogReader"/>
+               <allow pkg="org.apache.log4j" class="jalview.gui.Console"/>
+               <allow pkg="org.apache.log4j" class="jalview.gui.JalviewAppender"/>
+               <allow pkg="org.biodas" class="jalview.gui.DasSourceBrowser"/>
+               <allow pkg="compbio.metadata" class="jalview.gui.WsJobParameters"/>
+               <allow pkg="fr.orsay.lri.varna" class="jalview.gui.AppVarna"/>
+               <allow pkg="fr.orsay.lri.varna" class="jalview.gui.AppVarnaBinding"/>
+               <allow pkg="uk.ac.vamsas" class="jalview.gui.VamsasApplication"/>
+           </subpackage>
+               
+               <subpackage name="jbgui">
+               <allow pkg="javax.swing"/>
+               <allow pkg="net.miginfocom"/>
+           </subpackage>
+
+               <subpackage name="httpserver">
+               <allow pkg="javax.servlet"/>
+               <allow pkg="org.eclipse.jetty"/>
+           </subpackage>
+
+               <subpackage name="io">
+               <allow pkg="javax.swing"/>
+               <allow pkg="org.jfree"/>
+               <allow pkg="org.json"/>
+               <allow pkg="org.jsoup"/>
+               <allow pkg="uk.ac.ebi"/>
+               <allow pkg="uk.ac.vamsas"/>
+               <allow pkg="fr.orsay.lri.varna"/>
+               <allow pkg="MCview"/>
+               </subpackage>       
+                               
+               <subpackage name="javascript">
+               <allow pkg="netscape.javascript"/>
+           </subpackage>
+
+               <subpackage name="rest">
+               <allow pkg="javax.servlet"/>
+               </subpackage>
+
+               <subpackage name="structure">
+               <allow pkg="MCview"/>
+               </subpackage>
+
+               <subpackage name="util">
+               <allow pkg="javax.swing"/>
+               <allow pkg="javax.imageio"/>
+               <allow pkg="org.jfree"/>
+               <allow pkg="org.jibble"/>
+               </subpackage>
+
+               <subpackage name="ws">
+               <allow pkg="javax.swing"/>
+               <allow pkg="javax.xml"/>
+               <allow pkg="ext.vamsas"/>
+               <allow pkg="compbio"/>
+               <allow pkg="MCview"/>
+               <allow pkg="org.apache.http"/>
+               <allow pkg="org.apache.james"/>
+               <allow pkg="org.apache.axis"/>
+               <allow pkg="org.biodas.jdas"/>
+               <allow pkg="org.exolab.castor"/>
+               <allow pkg="uk.ac.ebi"/>
+               <allow pkg="vamsas.objects"/>
+               </subpackage>
+
+   </import-control>
\ No newline at end of file
index 47c404e..01973d2 100755 (executable)
@@ -19,8 +19,7 @@
         var logger = project.getBuildListeners( ).firstElement( );
         logger.setMessageOutputLevel( 1 );
     </script>
-       <echo message="Missing message labels compared to Messages.properties"/>
-       <foreach target="compareProperties" param="file2">
+       <foreach target="compareBundles" param="file2">
                <path>
                        <fileset dir="${basedir}/resources/lang">
                                <exclude name="Messages.properties" />
        </foreach>
 </target>
 
+<target name="compareBundles" description="compare a properties file with Messages.properties and vice versa">
+       <echo message=" "/>
+       <echo message="Missing message labels in ${file2} compared to Messages.properties"/>
+       <antcall target="compareProperties">
+               <param name="file1" value="resources/lang/Messages.properties"/>
+               <param name="file2" value="${file2}" />
+       </antcall>
+       <echo message=" "/>
+       <echo message="Missing message labels in Messages.properties compare to ${file2}"/>
+       <antcall target="compareProperties">
+               <param name="file2" value="resources/lang/Messages.properties"/>
+               <param name="file1" value="${file2}" />
+       </antcall>
+</target>
+               
 <target name="compareProperties" description="reports missing entries in one message bundle">
-    <loadproperties srcFile="resources/lang/Messages.properties" prefix="prefixfile1"/>
+    <loadproperties srcFile="${file1}" prefix="prefixfile1"/>
     <loadproperties srcFile="${file2}" prefix="prefixfile2"/>
 
     <propertyselector property="file1.list" delimiter="," match="prefixfile1\.(.+)" select="\1"/>
     <propertyselector property="file2.list" delimiter="," match="prefixfile2\.(.+)" select="\1"/>
        
-       <echo message=" "/>
-       <echo message="*** ${file2}:" />
     <for list="${file1.list}" param="file1.property">
         <sequential>
             <if>