JAL-4133 store/restore alignment view’s charWidth and charHeight in Jalview project
[jalview.git] / src / jalview / project / Jalview2XML.java
index aa4cd6c..8142435 100644 (file)
@@ -29,8 +29,6 @@ import java.awt.Font;
 import java.awt.Rectangle;
 import java.io.BufferedReader;
 import java.io.ByteArrayInputStream;
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
@@ -56,6 +54,7 @@ import java.util.IdentityHashMap;
 import java.util.Iterator;
 import java.util.LinkedHashMap;
 import java.util.List;
+import java.util.Locale;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Set;
@@ -85,10 +84,13 @@ import jalview.api.analysis.ScoreModelI;
 import jalview.api.analysis.SimilarityParamsI;
 import jalview.api.structures.JalviewStructureDisplayI;
 import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.AlignedCodonFrame;
 import jalview.datamodel.Alignment;
 import jalview.datamodel.AlignmentAnnotation;
 import jalview.datamodel.AlignmentI;
+import jalview.datamodel.ContactMatrix;
+import jalview.datamodel.ContactMatrixI;
 import jalview.datamodel.DBRefEntry;
 import jalview.datamodel.GeneLocus;
 import jalview.datamodel.GraphLine;
@@ -109,10 +111,10 @@ import jalview.gui.AlignFrame;
 import jalview.gui.AlignViewport;
 import jalview.gui.AlignmentPanel;
 import jalview.gui.AppVarna;
-import jalview.gui.ChimeraViewFrame;
 import jalview.gui.Desktop;
 import jalview.gui.JvOptionPane;
 import jalview.gui.OOMWarning;
+import jalview.gui.OverviewPanel;
 import jalview.gui.PCAPanel;
 import jalview.gui.PaintRefresher;
 import jalview.gui.SplitFrame;
@@ -148,6 +150,7 @@ import jalview.viewmodel.ViewportRanges;
 import jalview.viewmodel.seqfeatures.FeatureRendererModel;
 import jalview.viewmodel.seqfeatures.FeatureRendererSettings;
 import jalview.viewmodel.seqfeatures.FeaturesDisplayed;
+import jalview.ws.datamodel.alphafold.PAEContactMatrix;
 import jalview.ws.jws2.Jws2Discoverer;
 import jalview.ws.jws2.dm.AAConSettings;
 import jalview.ws.jws2.jabaws2.Jws2Instance;
@@ -186,11 +189,13 @@ import jalview.xml.binding.jalview.JalviewModel.UserColours;
 import jalview.xml.binding.jalview.JalviewModel.Viewport;
 import jalview.xml.binding.jalview.JalviewModel.Viewport.CalcIdParam;
 import jalview.xml.binding.jalview.JalviewModel.Viewport.HiddenColumns;
+import jalview.xml.binding.jalview.JalviewModel.Viewport.Overview;
 import jalview.xml.binding.jalview.JalviewUserColours;
 import jalview.xml.binding.jalview.JalviewUserColours.Colour;
 import jalview.xml.binding.jalview.MapListType.MapListFrom;
 import jalview.xml.binding.jalview.MapListType.MapListTo;
 import jalview.xml.binding.jalview.Mapping;
+import jalview.xml.binding.jalview.MatrixType;
 import jalview.xml.binding.jalview.NoValueColour;
 import jalview.xml.binding.jalview.ObjectFactory;
 import jalview.xml.binding.jalview.PcaDataType;
@@ -230,6 +235,11 @@ public class Jalview2XML
   private static final String UTF_8 = "UTF-8";
 
   /**
+   * used in decision if quit confirmation should be issued
+   */
+  private static boolean stateSavedUpToDate = false;
+
+  /**
    * prefix for recovering datasets for alignments with multiple views where
    * non-existent dataset IDs were written for some views
    */
@@ -578,7 +588,7 @@ public class Jalview2XML
 
     } catch (Exception e)
     {
-      Cache.log.error("Couln't write Jalview state to " + statefile, e);
+      Console.error("Couln't write Jalview state to " + statefile, e);
       // TODO: inform user of the problem - they need to know if their data was
       // not saved !
       if (errorMessage == null)
@@ -617,6 +627,27 @@ public class Jalview2XML
   {
     AlignFrame[] frames = Desktop.getAlignFrames();
 
+    setStateSavedUpToDate(true);
+
+    if (Cache.getDefault("DEBUG_DELAY_SAVE", false))
+    {
+      int n = debugDelaySave;
+      int i = 0;
+      while (i < n)
+      {
+        Console.debug("***** debugging save sleep " + i + "/" + n);
+        try
+        {
+          Thread.sleep(1000);
+        } catch (InterruptedException e)
+        {
+          // TODO Auto-generated catch block
+          e.printStackTrace();
+        }
+        i++;
+      }
+    }
+
     if (frames == null)
     {
       return;
@@ -761,8 +792,27 @@ public class Jalview2XML
       // create backupfiles object and get new temp filename destination
       boolean doBackup = BackupFiles.getEnabled();
       BackupFiles backupfiles = doBackup ? new BackupFiles(jarFile) : null;
-      FileOutputStream fos = new FileOutputStream(doBackup ? 
-              backupfiles.getTempFilePath() : jarFile);
+      FileOutputStream fos = new FileOutputStream(
+              doBackup ? backupfiles.getTempFilePath() : jarFile);
+
+      if (Cache.getDefault("DEBUG_DELAY_SAVE", false))
+      {
+        int n = debugDelaySave;
+        int i = 0;
+        while (i < n)
+        {
+          Console.debug("***** debugging save sleep " + i + "/" + n);
+          try
+          {
+            Thread.sleep(1000);
+          } catch (InterruptedException e)
+          {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+          }
+          i++;
+        }
+      }
 
       JarOutputStream jout = new JarOutputStream(fos);
       List<AlignFrame> frames = new ArrayList<>();
@@ -883,8 +933,7 @@ public class Jalview2XML
     {
       System.err.println("error writing date: " + e.toString());
     }
-    object.setVersion(
-            jalview.bin.Cache.getDefault("VERSION", "Development Build"));
+    object.setVersion(Cache.getDefault("VERSION", "Development Build"));
 
     /**
      * rjal is full height alignment, jal is actual alignment with full metadata
@@ -1092,8 +1141,8 @@ public class Jalview2XML
             if (frames[f] instanceof StructureViewerBase)
             {
               StructureViewerBase viewFrame = (StructureViewerBase) frames[f];
-              matchedFile = saveStructureViewer(ap, jds, pdb, entry, viewIds,
-                      matchedFile, viewFrame);
+              matchedFile = saveStructureViewer(ap, jds, pdb, entry,
+                      viewIds, matchedFile, viewFrame);
               /*
                * Only store each structure viewer's state once in the project
                * jar. First time through only (storeDS==false)
@@ -1111,9 +1160,8 @@ public class Jalview2XML
                 }
                 else
                 {
-                  Cache.log.error("Failed to save viewer state for "
-                          +
-                          viewerType);
+                  Console.error(
+                          "Failed to save viewer state for " + viewerType);
                 }
               }
             }
@@ -1357,9 +1405,8 @@ public class Jalview2XML
 
             if (colourScheme instanceof jalview.schemes.UserColourScheme)
             {
-              jGroup.setColour(
-                      setUserColourScheme(colourScheme, userColours,
-                              object));
+              jGroup.setColour(setUserColourScheme(colourScheme,
+                      userColours, object));
             }
             else
             {
@@ -1451,6 +1498,23 @@ public class Jalview2XML
       view.setStartRes(vpRanges.getStartRes());
       view.setStartSeq(vpRanges.getStartSeq());
 
+      OverviewPanel ov = ap.getOverviewPanel();
+      if (ov != null)
+      {
+        Overview overview = new Overview();
+        overview.setTitle(ov.getTitle());
+        Rectangle bounds = ov.getFrameBounds();
+        overview.setXpos(bounds.x);
+        overview.setYpos(bounds.y);
+        overview.setWidth(bounds.width);
+        overview.setHeight(bounds.height);
+        overview.setShowHidden(ov.isShowHiddenRegions());
+        overview.setGapColour(ov.getCanvas().getGapColour().getRGB());
+        overview.setResidueColour(
+                ov.getCanvas().getResidueColour().getRGB());
+        overview.setHiddenColour(ov.getCanvas().getHiddenColour().getRGB());
+        view.setOverview(overview);
+      } 
       if (av.getGlobalColourScheme() instanceof jalview.schemes.UserColourScheme)
       {
         view.setBgColour(setUserColourScheme(av.getGlobalColourScheme(),
@@ -1491,6 +1555,8 @@ public class Jalview2XML
 
       view.setConservationSelected(av.getConservationSelected());
       view.setPidSelected(av.getAbovePIDThreshold());
+      view.setCharHeight(av.getCharHeight());
+      view.setCharWidth(av.getCharWidth());
       final Font font = av.getFont();
       view.setFontName(font.getName());
       view.setFontSize(font.getSize());
@@ -1542,11 +1608,13 @@ public class Jalview2XML
              * save any filter for the feature type
              */
             FeatureMatcherSetI filter = fr.getFeatureFilter(featureType);
-            if (filter != null)  {
-              Iterator<FeatureMatcherI> filters = filter.getMatchers().iterator();
+            if (filter != null)
+            {
+              Iterator<FeatureMatcherI> filters = filter.getMatchers()
+                      .iterator();
               FeatureMatcherI firstFilter = filters.next();
-              setting.setMatcherSet(Jalview2XML.marshalFilter(
-                      firstFilter, filters, filter.isAnded()));
+              setting.setMatcherSet(Jalview2XML.marshalFilter(firstFilter,
+                      filters, filter.isAnded()));
             }
 
             /*
@@ -1595,8 +1663,7 @@ public class Jalview2XML
 
             setting.setDisplay(
                     av.getFeaturesDisplayed().isVisible(featureType));
-            float rorder = fr
-                    .getOrder(featureType);
+            float rorder = fr.getOrder(featureType);
             if (rorder > -1)
             {
               setting.setOrder(rorder);
@@ -1620,7 +1687,7 @@ public class Jalview2XML
           Group g = new Group();
           g.setName(grp);
           g.setDisplay(((Boolean) fr.checkGroupVisibility(grp, false))
-                          .booleanValue());
+                  .booleanValue());
           // fs.addGroup(g);
           fs.getGroup().add(g);
           groupsAdded.addElement(grp);
@@ -1635,7 +1702,8 @@ public class Jalview2XML
                 .getHiddenColumns();
         if (hidden == null)
         {
-          warn("REPORT BUG: avoided null columnselection bug (DMAM reported). Please contact Jim about this.");
+          Console.warn(
+                  "REPORT BUG: avoided null columnselection bug (DMAM reported). Please contact Jim about this.");
         }
         else
         {
@@ -1804,7 +1872,7 @@ public class Jalview2XML
       object.getPcaViewer().add(viewer);
     } catch (Throwable t)
     {
-      Cache.log.error("Error saving PCA: " + t.getMessage());
+      Console.error("Error saving PCA: " + t.getMessage());
     }
   }
 
@@ -2079,9 +2147,9 @@ public class Jalview2XML
     {
       final PDBEntry pdbentry = bindingModel.getPdbEntry(peid);
       final String pdbId = pdbentry.getId();
-      if (!pdbId.equals(entry.getId())
-              && !(entry.getId().length() > 4 && entry.getId().toLowerCase()
-                      .startsWith(pdbId.toLowerCase())))
+      if (!pdbId.equals(entry.getId()) && !(entry.getId().length() > 4
+              && entry.getId().toLowerCase(Locale.ROOT)
+                      .startsWith(pdbId.toLowerCase(Locale.ROOT))))
       {
         /*
          * not interested in a binding to a different PDB entry here
@@ -2094,7 +2162,7 @@ public class Jalview2XML
       }
       else if (!matchedFile.equals(pdbentry.getFile()))
       {
-        Cache.log.warn(
+        Console.warn(
                 "Probably lost some PDB-Sequence mappings for this structure file (which apparently has same PDB Entry code): "
                         + pdbentry.getFile());
       }
@@ -2227,6 +2295,22 @@ public class Jalview2XML
           line.setColour(annotation.getThreshold().colour.getRGB());
           an.setThresholdLine(line);
         }
+        if (annotation.graph==AlignmentAnnotation.CONTACT_MAP)
+        {
+          if (annotation.sequenceRef.getContactMaps()!=null)
+          {
+            ContactMatrixI cm = annotation.sequenceRef.getContactMatrixFor(annotation);
+            if (cm!=null)
+            {
+              MatrixType xmlmat = new MatrixType();
+              xmlmat.setType(cm.getType());
+              xmlmat.setRows(BigInteger.valueOf(cm.getWidth()));
+              xmlmat.setCols(BigInteger.valueOf(cm.getHeight()));
+              xmlmat.setValue(ContactMatrix.contactToFloatString(cm));
+              an.getContactmatrix().add(xmlmat);
+            }
+          }
+        }
       }
       else
       {
@@ -2377,7 +2461,8 @@ public class Jalview2XML
   {
     if (calcIdParam.getVersion().equals("1.0"))
     {
-      final String[] calcIds = calcIdParam.getServiceURL().toArray(new String[0]);
+      final String[] calcIds = calcIdParam.getServiceURL()
+              .toArray(new String[0]);
       Jws2Instance service = Jws2Discoverer.getDiscoverer()
               .getPreferredServiceFor(calcIds);
       if (service != null)
@@ -2391,7 +2476,7 @@ public class Jalview2XML
                   calcIdParam.getParameters().replace("|\\n|", "\n"));
         } catch (IOException x)
         {
-          warn("Couldn't parse parameter data for "
+          Console.warn("Couldn't parse parameter data for "
                   + calcIdParam.getCalcId(), x);
           return false;
         }
@@ -2419,7 +2504,8 @@ public class Jalview2XML
       }
       else
       {
-        warn("Cannot resolve a service for the parameters used in this project. Try configuring a JABAWS server.");
+        Console.warn(
+                "Cannot resolve a service for the parameters used in this project. Try configuring a JABAWS server.");
         return false;
       }
     }
@@ -2463,7 +2549,8 @@ public class Jalview2XML
         return id.toString();
       }
       // give up and warn that something has gone wrong
-      warn("Cannot find ID for object in external mapping : " + jvobj);
+      Console.warn(
+              "Cannot find ID for object in external mapping : " + jvobj);
     }
     return altCode;
   }
@@ -2532,14 +2619,15 @@ public class Jalview2XML
         dbref.setSource(ref.getSource());
         dbref.setVersion(ref.getVersion());
         dbref.setAccessionId(ref.getAccessionId());
+        dbref.setCanonical(ref.isCanonical());
         if (ref instanceof GeneLocus)
         {
           dbref.setLocus(true);
         }
         if (ref.hasMap())
         {
-          Mapping mp = createVamsasMapping(ref.getMap(), parentseq,
-                  jds, recurse);
+          Mapping mp = createVamsasMapping(ref.getMap(), parentseq, jds,
+                  recurse);
           dbref.setMapping(mp);
         }
         vamsasSeq.getDBRef().add(dbref);
@@ -2599,12 +2687,12 @@ public class Jalview2XML
         mp.setDseqFor(jmpid);
         if (!seqRefIds.containsKey(jmpid))
         {
-          jalview.bin.Cache.log.debug("creatign new DseqFor ID");
+          Console.debug("creatign new DseqFor ID");
           seqRefIds.put(jmpid, ps);
         }
         else
         {
-          jalview.bin.Cache.log.debug("reusing DseqFor ID");
+          Console.debug("reusing DseqFor ID");
         }
 
         // mp.setMappingChoice(mpc);
@@ -2647,7 +2735,7 @@ public class Jalview2XML
         for (int i = 0; i < colours.length; i++)
         {
           Colour col = new Colour();
-          col.setName(ResidueProperties.aa[i].toLowerCase());
+          col.setName(ResidueProperties.aa[i].toLowerCase(Locale.ROOT));
           col.setRGB(jalview.util.Format.getHexString(colours[i]));
           // jbucs.addColour(col);
           jbucs.getColour().add(col);
@@ -2663,12 +2751,12 @@ public class Jalview2XML
     return id;
   }
 
-  jalview.schemes.UserColourScheme getUserColourScheme(
-          JalviewModel jm, String id)
+  jalview.schemes.UserColourScheme getUserColourScheme(JalviewModel jm,
+          String id)
   {
     List<UserColours> uc = jm.getUserColours();
     UserColours colours = null;
-/*
+    /*
     for (int i = 0; i < uc.length; i++)
     {
       if (uc[i].getId().equals(id))
@@ -2677,7 +2765,7 @@ public class Jalview2XML
         break;
       }
     }
-*/
+    */
     for (UserColours c : uc)
     {
       if (c.getId().equals(id))
@@ -2705,10 +2793,9 @@ public class Jalview2XML
       newColours = new java.awt.Color[23];
       for (int i = 0; i < 23; i++)
       {
-        newColours[i] = new java.awt.Color(Integer.parseInt(
-                colours.getUserColourScheme().getColour().get(i + 24)
-                        .getRGB(),
-                16));
+        newColours[i] = new java.awt.Color(
+                Integer.parseInt(colours.getUserColourScheme().getColour()
+                        .get(i + 24).getRGB(), 16));
       }
       ucs.setLowerCaseColours(newColours);
     }
@@ -2777,54 +2864,69 @@ public class Jalview2XML
     return af;
   }
 
-       @SuppressWarnings("unused")
-       private jarInputStreamProvider createjarInputStreamProvider(final Object ofile) throws MalformedURLException {
+  @SuppressWarnings("unused")
+  private jarInputStreamProvider createjarInputStreamProvider(
+          final Object ofile) throws MalformedURLException
+  {
 
-               // BH 2018 allow for bytes already attached to File object
-               try {
-                       String file = (ofile instanceof File ? ((File) ofile).getCanonicalPath() : ofile.toString());
+    // BH 2018 allow for bytes already attached to File object
+    try
+    {
+      String file = (ofile instanceof File
+              ? ((File) ofile).getCanonicalPath()
+              : ofile.toString());
       byte[] bytes = Platform.isJS() ? Platform.getFileBytes((File) ofile)
               : null;
-                       URL url = null;
-                       errorMessage = null;
-                       uniqueSetSuffix = null;
-                       seqRefIds = null;
-                       viewportsAdded.clear();
-                       frefedSequence = null;
-
-    if (HttpUtils.startsWithHttpOrHttps(file))
-    {
-      url = new URL(file);
-    }
-    final URL _url = url;
-    return new jarInputStreamProvider()
-    {
-
-                               @Override
-                               public JarInputStream getJarInputStream() throws IOException {
-                                       if (bytes != null) {
-//                                             System.out.println("Jalview2XML: opening byte jarInputStream for bytes.length=" + bytes.length);
-                                               return new JarInputStream(new ByteArrayInputStream(bytes));
-                                       }
-                                       if (_url != null) {
-//                                             System.out.println("Jalview2XML: opening url jarInputStream for " + _url);
-                                               return new JarInputStream(_url.openStream());
-                                       } else {
-//                                             System.out.println("Jalview2XML: opening file jarInputStream for " + file);
-                                               return new JarInputStream(new FileInputStream(file));
-                                       }
-                               }
-
-                               @Override
-                               public String getFilename() {
-                                       return file;
-                               }
-                       };
-               } catch (IOException e) {
-                       e.printStackTrace();
-                       return null;
-               }
-       }
+      URL url = null;
+      errorMessage = null;
+      uniqueSetSuffix = null;
+      seqRefIds = null;
+      viewportsAdded.clear();
+      frefedSequence = null;
+
+      if (HttpUtils.startsWithHttpOrHttps(file))
+      {
+        url = new URL(file);
+      }
+      final URL _url = url;
+      return new jarInputStreamProvider()
+      {
+
+        @Override
+        public JarInputStream getJarInputStream() throws IOException
+        {
+          if (bytes != null)
+          {
+            // System.out.println("Jalview2XML: opening byte jarInputStream for
+            // bytes.length=" + bytes.length);
+            return new JarInputStream(new ByteArrayInputStream(bytes));
+          }
+          if (_url != null)
+          {
+            // System.out.println("Jalview2XML: opening url jarInputStream for "
+            // + _url);
+            return new JarInputStream(_url.openStream());
+          }
+          else
+          {
+            // System.out.println("Jalview2XML: opening file jarInputStream for
+            // " + file);
+            return new JarInputStream(new FileInputStream(file));
+          }
+        }
+
+        @Override
+        public String getFilename()
+        {
+          return file;
+        }
+      };
+    } catch (IOException e)
+    {
+      e.printStackTrace();
+      return null;
+    }
+  }
 
   /**
    * Recover jalview session from a jalview project archive. Caller may
@@ -2871,8 +2973,8 @@ public class Jalview2XML
           XMLStreamReader streamReader = XMLInputFactory.newInstance()
                   .createXMLStreamReader(jin);
           javax.xml.bind.Unmarshaller um = jc.createUnmarshaller();
-          JAXBElement<JalviewModel> jbe = um
-                  .unmarshal(streamReader, JalviewModel.class);
+          JAXBElement<JalviewModel> jbe = um.unmarshal(streamReader,
+                  JalviewModel.class);
           JalviewModel object = jbe.getValue();
 
           if (true) // !skipViewport(object))
@@ -2908,6 +3010,7 @@ public class Jalview2XML
           entryCount++;
         }
       } while (jarentry != null);
+      jin.close();
       resolveFrefedSequences();
     } catch (IOException ex)
     {
@@ -3215,7 +3318,8 @@ public class Jalview2XML
       }
       else
       {
-        warn("Couldn't find entry in Jalview Jar for " + jarEntryName);
+        Console.warn(
+                "Couldn't find entry in Jalview Jar for " + jarEntryName);
       }
     } catch (Exception ex)
     {
@@ -3260,7 +3364,8 @@ public class Jalview2XML
   AlignFrame loadFromObject(JalviewModel jalviewModel, String file,
           boolean loadTreesAndStructures, jarInputStreamProvider jprovider)
   {
-    SequenceSet vamsasSet = jalviewModel.getVamsasModel().getSequenceSet().get(0);
+    SequenceSet vamsasSet = jalviewModel.getVamsasModel().getSequenceSet()
+            .get(0);
     List<Sequence> vamsasSeqs = vamsasSet.getSequence();
 
     // JalviewModelSequence jms = object.getJalviewModelSequence();
@@ -3319,11 +3424,10 @@ public class Jalview2XML
           if (tmpSeq.getStart() != jseq.getStart()
                   || tmpSeq.getEnd() != jseq.getEnd())
           {
-            System.err.println(
-                    String.format("Warning JAL-2154 regression: updating start/end for sequence %s from %d/%d to %d/%d",
-                            tmpSeq.getName(), tmpSeq.getStart(),
-                            tmpSeq.getEnd(), jseq.getStart(),
-                            jseq.getEnd()));
+            System.err.println(String.format(
+                    "Warning JAL-2154 regression: updating start/end for sequence %s from %d/%d to %d/%d",
+                    tmpSeq.getName(), tmpSeq.getStart(), tmpSeq.getEnd(),
+                    jseq.getStart(), jseq.getEnd()));
           }
         }
         else
@@ -3606,8 +3710,8 @@ public class Jalview2XML
               else
               {
                 // defer to later
-                frefedSequence.add(
-                        newAlcodMapRef(map.getDnasq(), cf, mapping));
+                frefedSequence
+                        .add(newAlcodMapRef(map.getDnasq(), cf, mapping));
               }
             }
           }
@@ -3815,12 +3919,45 @@ public class Jalview2XML
         jaa.setCalcId(annotation.getCalcId());
         if (annotation.getProperty().size() > 0)
         {
-          for (Annotation.Property prop : annotation
-                  .getProperty())
+          for (Annotation.Property prop : annotation.getProperty())
           {
             jaa.setProperty(prop.getName(), prop.getValue());
           }
         }
+        if (jaa.graph == AlignmentAnnotation.CONTACT_MAP)
+        {
+          if (annotation.getContactmatrix() != null
+                  && annotation.getContactmatrix().size() > 0)
+          {
+            for (MatrixType xmlmat : annotation.getContactmatrix())
+            {
+              if (PAEContactMatrix.PAEMATRIX.equals(xmlmat.getType()))
+              {
+                if (!xmlmat.getRows().equals(xmlmat.getCols()))
+                {
+                  Console.error("Can't handle non square PAE Matrices");
+                }
+                else
+                {
+                  float[][] elements = ContactMatrix
+                          .fromFloatStringToContacts(xmlmat.getValue(),
+                                  xmlmat.getCols().intValue(),
+                                  xmlmat.getRows().intValue());
+
+                  PAEContactMatrix newpae = new PAEContactMatrix(
+                          jaa.sequenceRef, elements);
+                  jaa.sequenceRef.addContactListFor(jaa, newpae);
+                }
+              }
+              else
+              {
+                Console.error("Ignoring CONTACT_MAP annotation with type "
+                        + xmlmat.getType());
+              }
+            }
+          }
+        }
+
         if (jaa.autoCalculated)
         {
           autoAlan.add(new JvAnnotRow(i, jaa));
@@ -3897,9 +4034,9 @@ public class Jalview2XML
         sg.setShowNonconserved(safeBoolean(jGroup.isShowUnconserved()));
         sg.thresholdTextColour = safeInt(jGroup.getTextColThreshold());
         // attributes with a default in the schema are never null
-          sg.setShowConsensusHistogram(jGroup.isShowConsensusHistogram());
-          sg.setshowSequenceLogo(jGroup.isShowSequenceLogo());
-          sg.setNormaliseSequenceLogo(jGroup.isNormaliseSequenceLogo());
+        sg.setShowConsensusHistogram(jGroup.isShowConsensusHistogram());
+        sg.setshowSequenceLogo(jGroup.isShowSequenceLogo());
+        sg.setNormaliseSequenceLogo(jGroup.isNormaliseSequenceLogo());
         sg.setIgnoreGapsConsensus(jGroup.isIgnoreGapsinConsensus());
         if (jGroup.getConsThreshold() != null
                 && jGroup.getConsThreshold().intValue() != 0)
@@ -3943,8 +4080,9 @@ public class Jalview2XML
         if (addAnnotSchemeGroup)
         {
           // reconstruct the annotation colourscheme
-          sg.setColourScheme(constructAnnotationColour(
-                  jGroup.getAnnotationColours(), null, al, jalviewModel, false));
+          sg.setColourScheme(
+                  constructAnnotationColour(jGroup.getAnnotationColours(),
+                          null, al, jalviewModel, false));
         }
       }
     }
@@ -4030,7 +4168,7 @@ public class Jalview2XML
     }
 
     /*
-     * Load any trees, PDB structures and viewers
+     * Load any trees, PDB structures and viewers, Overview
      * 
      * Not done if flag is false (when this method is used for New View)
      */
@@ -4040,12 +4178,49 @@ public class Jalview2XML
       loadPCAViewers(jalviewModel, ap);
       loadPDBStructures(jprovider, jseqs, af, ap);
       loadRnaViewers(jprovider, jseqs, ap);
+      loadOverview(view, jalviewModel.getVersion(), af);
     }
     // and finally return.
     return af;
   }
 
   /**
+   * Load Overview window, restoring colours, 'show hidden regions' flag, title
+   * and geometry as saved
+   * 
+   * @param view
+   * @param af
+   */
+  protected void loadOverview(Viewport view, String version, AlignFrame af)
+  {
+    if (!isVersionStringLaterThan("2.11.3",
+            version) && view.getOverview()==null)
+    {
+      return;
+    }
+    /*
+     * first close any Overview that was opened automatically
+     * (if so configured in Preferences) so that the view is
+     * restored in the same state as saved
+     */
+    af.alignPanel.closeOverviewPanel();
+
+    Overview overview = view.getOverview();
+    if (overview != null)
+    {
+      OverviewPanel overviewPanel = af
+              .openOverviewPanel(overview.isShowHidden());
+      overviewPanel.setTitle(overview.getTitle());
+      overviewPanel.setFrameBounds(overview.getXpos(), overview.getYpos(),
+              overview.getWidth(), overview.getHeight());
+      Color gap = new Color(overview.getGapColour());
+      Color residue = new Color(overview.getResidueColour());
+      Color hidden = new Color(overview.getHiddenColour());
+      overviewPanel.getCanvas().setColours(gap, residue, hidden);
+    }
+  }
+
+  /**
    * Instantiate and link any saved RNA (Varna) viewers. The state of the Varna
    * panel is restored from separate jar entries, two (gapped and trimmed) per
    * sequence and secondary structure.
@@ -4150,8 +4325,8 @@ public class Jalview2XML
    * @param av
    * @param ap
    */
-  protected void loadTrees(JalviewModel jm, Viewport view,
-          AlignFrame af, AlignViewport av, AlignmentPanel ap)
+  protected void loadTrees(JalviewModel jm, Viewport view, AlignFrame af,
+          AlignViewport av, AlignmentPanel ap)
   {
     // TODO result of automated refactoring - are all these parameters needed?
     try
@@ -4190,8 +4365,9 @@ public class Jalview2XML
         tp.getTreeCanvas().setApplyToAllViews(tree.isLinkToAllViews());
         if (tp == null)
         {
-          warn("There was a problem recovering stored Newick tree: \n"
-                  + tree.getNewick());
+          Console.warn(
+                  "There was a problem recovering stored Newick tree: \n"
+                          + tree.getNewick());
           continue;
         }
 
@@ -4259,8 +4435,8 @@ public class Jalview2XML
           for (int s = 0; s < structureStateCount; s++)
           {
             // check to see if we haven't already created this structure view
-            final StructureState structureState = pdbid
-                    .getStructureState().get(s);
+            final StructureState structureState = pdbid.getStructureState()
+                    .get(s);
             String sviewid = (structureState.getViewId() == null) ? null
                     : structureState.getViewId() + uniqueSetSuffix;
             jalview.datamodel.PDBEntry jpdb = new jalview.datamodel.PDBEntry();
@@ -4328,8 +4504,8 @@ public class Jalview2XML
             colourByViewer &= structureState.isColourByJmol();
             jmoldat.setColourByViewer(colourByViewer);
 
-            if (jmoldat.getStateData().length() < structureState
-                    .getValue()/*Content()*/.length())
+            if (jmoldat.getStateData().length() < structureState.getValue()
+                    /*Content()*/.length())
             {
               jmoldat.setStateData(structureState.getValue());// Content());
             }
@@ -4352,7 +4528,7 @@ public class Jalview2XML
             else
             {
               errorMessage = ("The Jmol views in this project were imported\nfrom an older version of Jalview.\nPlease review the sequence colour associations\nin the Colour by section of the Jmol View menu.\n\nIn the case of problems, see note at\nhttp://issues.jalview.org/browse/JAL-747");
-              warn(errorMessage);
+              Console.warn(errorMessage);
             }
           }
         }
@@ -4407,8 +4583,7 @@ public class Jalview2XML
     } catch (IllegalArgumentException | NullPointerException e)
     {
       // TODO JAL-3619 show error dialog / offer an alternative viewer
-      Cache.log.error(
-              "Invalid structure viewer type: " + type);
+      Console.error("Invalid structure viewer type: " + type);
     }
   }
 
@@ -4562,7 +4737,7 @@ public class Jalview2XML
    *          - minimum version we are comparing against
    * @param version
    *          - version of data being processsed
-   * @return
+   * @return true if version is equal to or later than supported
    */
   public static boolean isVersionStringLaterThan(String supported,
           String version)
@@ -4608,23 +4783,23 @@ public class Jalview2XML
   }
 
   AlignFrame loadViewport(String file, List<JSeq> JSEQ,
-          List<SequenceI> hiddenSeqs, AlignmentI al,
-          JalviewModel jm, Viewport view, String uniqueSeqSetId,
-          String viewId, List<JvAnnotRow> autoAlan)
+          List<SequenceI> hiddenSeqs, AlignmentI al, JalviewModel jm,
+          Viewport view, String uniqueSeqSetId, String viewId,
+          List<JvAnnotRow> autoAlan)
   {
     AlignFrame af = null;
     af = new AlignFrame(al, safeInt(view.getWidth()),
-            safeInt(view.getHeight()), uniqueSeqSetId, viewId) 
-//    {
-//     
-//     @Override
-//     protected void processKeyEvent(java.awt.event.KeyEvent e) {
-//             System.out.println("Jalview2XML   AF " + e);
-//             super.processKeyEvent(e);
-//             
-//     }
-//     
-//    }
+            safeInt(view.getHeight()), uniqueSeqSetId, viewId)
+    // {
+    //
+    // @Override
+    // protected void processKeyEvent(java.awt.event.KeyEvent e) {
+    // System.out.println("Jalview2XML AF " + e);
+    // super.processKeyEvent(e);
+    //
+    // }
+    //
+    // }
     ;
 
     af.setFileName(file, FileFormat.Jalview);
@@ -4702,12 +4877,16 @@ public class Jalview2XML
 
     viewport.setColourText(safeBoolean(view.isShowColourText()));
 
-    viewport
-            .setConservationSelected(
-                    safeBoolean(view.isConservationSelected()));
+    viewport.setConservationSelected(
+            safeBoolean(view.isConservationSelected()));
     viewport.setIncrement(safeInt(view.getConsThreshold()));
     viewport.setShowJVSuffix(safeBoolean(view.isShowFullId()));
     viewport.setRightAlignIds(safeBoolean(view.isRightAlignIds()));
+    if (view.getCharWidth()!=null)
+    {
+      viewport.setCharWidth(view.getCharWidth());
+      viewport.setCharHeight(view.getCharHeight());
+    }
     viewport.setFont(new Font(view.getFontName(),
             safeInt(view.getFontStyle()), safeInt(view.getFontSize())),
             true);
@@ -4780,9 +4959,8 @@ public class Jalview2XML
     af.changeColour(cs);
     viewport.setColourAppliesToAllGroups(true);
 
-    viewport
-            .setShowSequenceFeatures(
-                    safeBoolean(view.isShowSequenceFeatures()));
+    viewport.setShowSequenceFeatures(
+            safeBoolean(view.isShowSequenceFeatures()));
 
     viewport.setCentreColumnLabels(view.isCentreColumnLabels());
     viewport.setIgnoreGapsConsensus(view.isIgnoreGapsinConsensus(), null);
@@ -4806,13 +4984,13 @@ public class Jalview2XML
               .getFeatureRenderer();
       FeaturesDisplayed fdi;
       viewport.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
-      String[] renderOrder = new String[jm.getFeatureSettings()
-              .getSetting().size()];
+      String[] renderOrder = new String[jm.getFeatureSettings().getSetting()
+              .size()];
       Map<String, FeatureColourI> featureColours = new Hashtable<>();
       Map<String, Float> featureOrder = new Hashtable<>();
 
-      for (int fs = 0; fs < jm.getFeatureSettings()
-              .getSetting().size(); fs++)
+      for (int fs = 0; fs < jm.getFeatureSettings().getSetting()
+              .size(); fs++)
       {
         Setting setting = jm.getFeatureSettings().getSetting().get(fs);
         String featureType = setting.getType();
@@ -4824,8 +5002,8 @@ public class Jalview2XML
                 .getMatcherSet();
         if (filters != null)
         {
-          FeatureMatcherSetI filter = Jalview2XML
-                  .parseFilter(featureType, filters);
+          FeatureMatcherSetI filter = Jalview2XML.parseFilter(featureType,
+                  filters);
           if (!filter.isEmpty())
           {
             fr.setFeatureFilter(featureType, filter);
@@ -4857,8 +5035,7 @@ public class Jalview2XML
           float max = setting.getMax() == null ? 1f
                   : setting.getMax().floatValue();
           FeatureColourI gc = new FeatureColour(maxColour, minColour,
-                  maxColour,
-                  noValueColour, min, max);
+                  maxColour, noValueColour, min, max);
           if (setting.getAttributeName().size() > 0)
           {
             gc.setAttributeName(setting.getAttributeName().toArray(
@@ -4892,8 +5069,7 @@ public class Jalview2XML
         }
         else
         {
-          featureColours.put(featureType,
-                  new FeatureColour(maxColour));
+          featureColours.put(featureType, new FeatureColour(maxColour));
         }
         renderOrder[fs] = featureType;
         if (setting.getOrder() != null)
@@ -4944,7 +5120,7 @@ public class Jalview2XML
           }
           else
           {
-            warn("Couldn't recover parameters for "
+            Console.warn("Couldn't recover parameters for "
                     + calcIdParam.getCalcId());
           }
         }
@@ -4972,6 +5148,7 @@ public class Jalview2XML
     {
       splitFrameCandidates.put(view, af);
     }
+
     return af;
   }
 
@@ -5035,7 +5212,10 @@ public class Jalview2XML
               + annotationId);
       return null;
     }
-    if (matchedAnnotation.getThreshold() == null)
+    // belt-and-braces create a threshold line if the 
+    // colourscheme needs one but the matchedAnnotation doesn't have one
+    if (safeInt(viewAnnColour.getAboveThreshold()) != 0
+            && matchedAnnotation.getThreshold() == null)
     {
       matchedAnnotation.setThreshold(
               new GraphLine(safeFloat(viewAnnColour.getThreshold()),
@@ -5220,10 +5400,7 @@ public class Jalview2XML
     String id = object.getViewport().get(0).getSequenceSetId();
     if (skipList.containsKey(id))
     {
-      if (Cache.log != null && Cache.log.isDebugEnabled())
-      {
-        Cache.log.debug("Skipping seuqence set id " + id);
-      }
+      Console.debug("Skipping seuqence set id " + id);
       return true;
     }
     return false;
@@ -5275,14 +5452,16 @@ public class Jalview2XML
       {
         if (ds != null && ds != seqSetDS)
         {
-          warn("JAL-3171 regression: Overwriting a dataset reference for an alignment"
-                  + " - CDS/Protein crossreference data may be lost");
+          Console.warn(
+                  "JAL-3171 regression: Overwriting a dataset reference for an alignment"
+                          + " - CDS/Protein crossreference data may be lost");
           if (xtant_ds != null)
           {
             // This can only happen if the unique sequence set ID was bound to a
             // dataset that did not contain any of the sequences in the view
             // currently being restored.
-            warn("JAL-3171 SERIOUS!  TOTAL CONFUSION - please consider contacting the Jalview Development team so they can investigate why your project caused this message to be displayed.");
+            Console.warn(
+                    "JAL-3171 SERIOUS!  TOTAL CONFUSION - please consider contacting the Jalview Development team so they can investigate why your project caused this message to be displayed.");
           }
         }
         ds = seqSetDS;
@@ -5307,7 +5486,7 @@ public class Jalview2XML
       SequenceI[] dsseqs = new SequenceI[dseqs.size()];
       dseqs.copyInto(dsseqs);
       ds = new jalview.datamodel.Alignment(dsseqs);
-      debug("Created new dataset " + vamsasSet.getDatasetId()
+      Console.debug("Created new dataset " + vamsasSet.getDatasetId()
               + " for alignment " + System.identityHashCode(al));
       addDatasetRef(vamsasSet.getDatasetId(), ds);
     }
@@ -5360,12 +5539,13 @@ public class Jalview2XML
       AlignmentI prevDS = seqToDataset.put(restoredSeq.getDsseqid(), ds);
       if (prevDS != null && prevDS != ds)
       {
-        warn("Dataset sequence appears in many datasets: "
+        Console.warn("Dataset sequence appears in many datasets: "
                 + restoredSeq.getDsseqid());
         // TODO: try to merge!
       }
     }
   }
+
   /**
    * 
    * @param vamsasSeq
@@ -5565,7 +5745,8 @@ public class Jalview2XML
   {
     if (dataset.getDataset() != null)
     {
-      warn("Serious issue!  Dataset Object passed to getDatasetIdRef is not a Jalview DATASET alignment...");
+      Console.warn(
+              "Serious issue!  Dataset Object passed to getDatasetIdRef is not a Jalview DATASET alignment...");
     }
     String datasetId = makeHashCode(dataset, null);
     if (datasetId == null)
@@ -5615,6 +5796,7 @@ public class Jalview2XML
       {
         entry.setMap(addMapping(dr.getMapping()));
       }
+      entry.setCanonical(dr.isCanonical());
       datasetSequence.addDBRef(entry);
     }
   }
@@ -5700,7 +5882,7 @@ public class Jalview2XML
         seqRefIds.put(sqid, djs);
 
       }
-      jalview.bin.Cache.log.debug("about to recurse on addDBRefs.");
+      Console.debug("about to recurse on addDBRefs.");
       addDBRefs(djs, ms);
 
     }
@@ -5753,62 +5935,6 @@ public class Jalview2XML
 
   private Hashtable jvids2vobj;
 
-  private void warn(String msg)
-  {
-    warn(msg, null);
-  }
-
-  private void warn(String msg, Exception e)
-  {
-    if (Cache.log != null)
-    {
-      if (e != null)
-      {
-        Cache.log.warn(msg, e);
-      }
-      else
-      {
-        Cache.log.warn(msg);
-      }
-    }
-    else
-    {
-      System.err.println("Warning: " + msg);
-      if (e != null)
-      {
-        e.printStackTrace();
-      }
-    }
-  }
-
-  private void debug(String string)
-  {
-    debug(string, null);
-  }
-
-  private void debug(String msg, Exception e)
-  {
-    if (Cache.log != null)
-    {
-      if (e != null)
-      {
-        Cache.log.debug(msg, e);
-      }
-      else
-      {
-        Cache.log.debug(msg);
-      }
-    }
-    else
-    {
-      System.err.println("Warning: " + msg);
-      if (e != null)
-      {
-        e.printStackTrace();
-      }
-    }
-  }
-
   /**
    * set the object to ID mapping tables used to write/recover objects and XML
    * ID strings for the jalview project. If external tables are provided then
@@ -5867,7 +5993,7 @@ public class Jalview2XML
         if (!jvann.annotationId.equals(anid))
         {
           // TODO verify that this is the correct behaviour
-          this.warn("Overriding Annotation ID for " + anid
+          Console.warn("Overriding Annotation ID for " + anid
                   + " from different id : " + jvann.annotationId);
           jvann.annotationId = anid;
         }
@@ -5882,7 +6008,7 @@ public class Jalview2XML
       }
       else
       {
-        Cache.log.debug("Ignoring " + jvobj.getClass() + " (ID = " + id);
+        Console.debug("Ignoring " + jvobj.getClass() + " (ID = " + id);
       }
     }
   }
@@ -5952,7 +6078,8 @@ public class Jalview2XML
       }
       else
       {
-        warn("Couldn't find entry in Jalview Jar for " + jarEntryName);
+        Console.warn(
+                "Couldn't find entry in Jalview Jar for " + jarEntryName);
       }
     } catch (Exception ex)
     {
@@ -6102,7 +6229,7 @@ public class Jalview2XML
       }
     } catch (Exception ex)
     {
-      Cache.log.error("Error loading PCA: " + ex.toString());
+      Console.error("Error loading PCA: " + ex.toString());
     }
   }
 
@@ -6114,8 +6241,8 @@ public class Jalview2XML
    * @param af
    * @param jprovider
    */
-  protected void createStructureViewer(
-          ViewerType viewerType, final Entry<String, StructureViewerModel> viewerData,
+  protected void createStructureViewer(ViewerType viewerType,
+          final Entry<String, StructureViewerModel> viewerData,
           AlignFrame af, jarInputStreamProvider jprovider)
   {
     final StructureViewerModel viewerModel = viewerData.getValue();
@@ -6129,8 +6256,7 @@ public class Jalview2XML
     {
       String viewerJarEntryName = getViewerJarEntryName(
               viewerModel.getViewId());
-      sessionFilePath = copyJarEntry(jprovider,
-              viewerJarEntryName,
+      sessionFilePath = copyJarEntry(jprovider, viewerJarEntryName,
               "viewerSession", ".tmp");
     }
     final String sessionPath = sessionFilePath;
@@ -6150,8 +6276,7 @@ public class Jalview2XML
             addNewStructureViewer(sview);
           } catch (OutOfMemoryError ex)
           {
-            new OOMWarning("Restoring structure view for "
-                    + viewerType,
+            new OOMWarning("Restoring structure view for " + viewerType,
                     (OutOfMemoryError) ex.getCause());
             if (sview != null && sview.isVisible())
             {
@@ -6164,7 +6289,7 @@ public class Jalview2XML
       });
     } catch (InvocationTargetException | InterruptedException ex)
     {
-      warn("Unexpected error when opening " + viewerType
+      Console.warn("Unexpected error when opening " + viewerType
               + " structure viewer", ex);
     }
   }
@@ -6211,8 +6336,7 @@ public class Jalview2XML
           String reformatedOldFilename = oldfilenam.replaceAll("/", "\\\\");
           filedat = oldFiles.get(new File(reformatedOldFilename));
         }
-        rewritten
-                .append(Platform.escapeBackslashes(filedat.getFilePath()));
+        rewritten.append(Platform.escapeBackslashes(filedat.getFilePath()));
         rewritten.append("\"");
         cp = ecp + 1; // advance beyond last \" and set cursor so we can
                       // look for next file statement.
@@ -6272,7 +6396,7 @@ public class Jalview2XML
       }
     } catch (IOException e)
     {
-      Cache.log.error("Error restoring Jmol session: " + e.toString());
+      Console.error("Error restoring Jmol session: " + e.toString());
     }
     return null;
   }
@@ -6284,8 +6408,8 @@ public class Jalview2XML
    * @param fcol
    * @return
    */
-  public static Colour marshalColour(
-          String featureType, FeatureColourI fcol)
+  public static Colour marshalColour(String featureType,
+          FeatureColourI fcol)
   {
     Colour col = new Colour();
     if (fcol.isSimpleColour())
@@ -6346,7 +6470,7 @@ public class Jalview2XML
           boolean and)
   {
     jalview.xml.binding.jalview.FeatureMatcherSet result = new jalview.xml.binding.jalview.FeatureMatcherSet();
-  
+
     if (filters.hasNext())
     {
       /*
@@ -6396,7 +6520,7 @@ public class Jalview2XML
       }
       result.setMatchCondition(matcherModel);
     }
-  
+
     return result;
   }
 
@@ -6407,8 +6531,7 @@ public class Jalview2XML
    * @param matcherSetModel
    * @return
    */
-  public static FeatureMatcherSetI parseFilter(
-          String featureType,
+  public static FeatureMatcherSetI parseFilter(String featureType,
           jalview.xml.binding.jalview.FeatureMatcherSet matcherSetModel)
   {
     FeatureMatcherSetI result = new FeatureMatcherSet();
@@ -6423,7 +6546,7 @@ public class Jalview2XML
                       featureType, e.getMessage()));
       // return as much as was parsed up to the error
     }
-  
+
     return result;
   }
 
@@ -6438,8 +6561,7 @@ public class Jalview2XML
    * @throws IllegalStateException
    *           if AND and OR conditions are mixed
    */
-  protected static void parseFilterConditions(
-          FeatureMatcherSetI matcherSet,
+  protected static void parseFilterConditions(FeatureMatcherSetI matcherSet,
           jalview.xml.binding.jalview.FeatureMatcherSet matcherSetModel,
           boolean and)
   {
@@ -6461,7 +6583,7 @@ public class Jalview2XML
       else if (filterBy == FilterBy.BY_SCORE)
       {
         matchCondition = FeatureMatcher.byScore(cond, pattern);
-  
+
       }
       else if (filterBy == FilterBy.BY_ATTRIBUTE)
       {
@@ -6471,7 +6593,7 @@ public class Jalview2XML
         matchCondition = FeatureMatcher.byAttribute(cond, pattern,
                 attNames);
       }
-  
+
       /*
        * note this throws IllegalStateException if AND-ing to a 
        * previously OR-ed compound condition, or vice versa
@@ -6514,22 +6636,22 @@ public class Jalview2XML
   public static FeatureColourI parseColour(Colour colourModel)
   {
     FeatureColourI colour = null;
-  
+
     if (colourModel.getMax() != null)
     {
       Color mincol = null;
       Color maxcol = null;
       Color noValueColour = null;
-  
+
       try
       {
         mincol = new Color(Integer.parseInt(colourModel.getMinRGB(), 16));
         maxcol = new Color(Integer.parseInt(colourModel.getRGB(), 16));
       } catch (Exception e)
       {
-        Cache.log.warn("Couldn't parse out graduated feature color.", e);
+        Console.warn("Couldn't parse out graduated feature color.", e);
       }
-  
+
       NoValueColour noCol = colourModel.getNoValueColour();
       if (noCol == NoValueColour.MIN)
       {
@@ -6539,7 +6661,7 @@ public class Jalview2XML
       {
         noValueColour = maxcol;
       }
-  
+
       colour = new FeatureColour(maxcol, mincol, maxcol, noValueColour,
               safeFloat(colourModel.getMin()),
               safeFloat(colourModel.getMax()));
@@ -6578,7 +6700,47 @@ public class Jalview2XML
       Color color = new Color(Integer.parseInt(colourModel.getRGB(), 16));
       colour = new FeatureColour(color);
     }
-  
+
     return colour;
   }
+
+  public static void setStateSavedUpToDate(boolean s)
+  {
+    Console.debug("Setting overall stateSavedUpToDate to " + s);
+    stateSavedUpToDate = s;
+  }
+
+  public static boolean stateSavedUpToDate()
+  {
+    Console.debug("Returning overall stateSavedUpToDate value: "
+            + stateSavedUpToDate);
+    return stateSavedUpToDate;
+  }
+
+  public static boolean allSavedUpToDate()
+  {
+    if (stateSavedUpToDate()) // nothing happened since last project save
+      return true;
+
+    AlignFrame[] frames = Desktop.getAlignFrames();
+    if (frames != null)
+    {
+      for (int i = 0; i < frames.length; i++)
+      {
+        if (frames[i] == null)
+          continue;
+        if (!frames[i].getViewport().savedUpToDate())
+          return false; // at least one alignment is not individually saved
+      }
+    }
+    return true;
+  }
+
+  // used for debugging and tests
+  private static int debugDelaySave = 20;
+
+  public static void setDebugDelaySave(int n)
+  {
+    debugDelaySave = n;
+  }
 }