JAL-1713 don’t close an automatically created overview window for projects from Jalvi...
[jalview.git] / src / jalview / project / Jalview2XML.java
index 4f92736..8d2efe0 100644 (file)
@@ -28,13 +28,14 @@ import java.awt.Color;
 import java.awt.Font;
 import java.awt.Rectangle;
 import java.io.BufferedReader;
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
+import java.io.ByteArrayInputStream;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
+import java.io.InputStream;
 import java.io.InputStreamReader;
+import java.io.OutputStream;
 import java.io.OutputStreamWriter;
 import java.io.PrintWriter;
 import java.lang.reflect.InvocationTargetException;
@@ -83,6 +84,7 @@ 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;
@@ -107,10 +109,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;
@@ -184,6 +186,7 @@ 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;
@@ -212,6 +215,15 @@ import jalview.xml.binding.jalview.VAMSAS;
  */
 public class Jalview2XML
 {
+
+  // BH 2018 we add the .jvp binary extension to J2S so that
+  // it will declare that binary when we do the file save from the browser
+
+  static
+  {
+    Platform.addJ2SBinaryType(".jvp?");
+  }
+
   private static final String VIEWER_PREFIX = "viewer_";
 
   private static final String RNA_PREFIX = "rna_";
@@ -219,6 +231,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
    */
@@ -455,7 +472,7 @@ public class Jalview2XML
       public boolean isResolvable()
       {
         return super.isResolvable() && mp.getTo() != null;
-      };
+      }
 
       @Override
       boolean resolve()
@@ -567,7 +584,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)
@@ -606,6 +623,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;
@@ -687,7 +725,6 @@ public class Jalview2XML
       } catch (Exception foo)
       {
       }
-      ;
       jout.close();
     } catch (Exception ex)
     {
@@ -749,9 +786,29 @@ public class Jalview2XML
     try
     {
       // create backupfiles object and get new temp filename destination
-      BackupFiles backupfiles = new BackupFiles(jarFile);
+      boolean doBackup = BackupFiles.getEnabled();
+      BackupFiles backupfiles = doBackup ? new BackupFiles(jarFile) : null;
       FileOutputStream fos = new FileOutputStream(
-              backupfiles.getTempFilePath());
+              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<>();
@@ -772,12 +829,14 @@ public class Jalview2XML
       } catch (Exception foo)
       {
       }
-      ;
       jout.close();
       boolean success = true;
 
-      backupfiles.setWriteSuccess(success);
-      success = backupfiles.rollBackupsAndRenameTempFile();
+      if (doBackup)
+      {
+        backupfiles.setWriteSuccess(success);
+        success = backupfiles.rollBackupsAndRenameTempFile();
+      }
 
       return success;
     } catch (Exception ex)
@@ -870,8 +929,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
@@ -1079,25 +1137,27 @@ public class Jalview2XML
             if (frames[f] instanceof StructureViewerBase)
             {
               StructureViewerBase viewFrame = (StructureViewerBase) frames[f];
-              matchedFile = saveStructureState(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)
                */
               String viewId = viewFrame.getViewId();
+              String viewerType = viewFrame.getViewerType().toString();
               if (!storeDS && !viewIds.contains(viewId))
               {
                 viewIds.add(viewId);
-                try
+                File viewerState = viewFrame.saveSession();
+                if (viewerState != null)
                 {
-                  String viewerState = viewFrame.getStateInfo();
-                  writeJarEntry(jout, getViewerJarEntryName(viewId),
-                          viewerState.getBytes());
-                } catch (IOException e)
+                  copyFileToJar(jout, viewerState.getPath(),
+                          getViewerJarEntryName(viewId), viewerType);
+                }
+                else
                 {
-                  System.err.println(
-                          "Error saving viewer state: " + e.getMessage());
+                  Console.error(
+                          "Failed to save viewer state for " + viewerType);
                 }
               }
             }
@@ -1119,7 +1179,7 @@ public class Jalview2XML
             if (!pdbfiles.contains(pdbId))
             {
               pdbfiles.add(pdbId);
-              copyFileToJar(jout, matchedFile, pdbId);
+              copyFileToJar(jout, matchedFile, pdbId, pdbId);
             }
           }
 
@@ -1434,6 +1494,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(),
@@ -1619,7 +1696,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
         {
@@ -1666,6 +1744,7 @@ public class Jalview2XML
       // using save and then load
       try
       {
+        fileName = fileName.replace('\\', '/');
         System.out.println("Writing jar entry " + fileName);
         JarEntry entry = new JarEntry(fileName);
         jout.putNextEntry(entry);
@@ -1787,7 +1866,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());
     }
   }
 
@@ -1966,7 +2045,7 @@ public class Jalview2XML
 
                 String varnaStateFile = varna.getStateInfo(model.rna);
                 jarEntryName = RNA_PREFIX + viewId + "_" + nextCounter();
-                copyFileToJar(jout, varnaStateFile, jarEntryName);
+                copyFileToJar(jout, varnaStateFile, jarEntryName, "Varna");
                 rnaSessions.put(model, jarEntryName);
               }
               SecondaryStructure ss = new SecondaryStructure();
@@ -1990,58 +2069,48 @@ public class Jalview2XML
    * @param jout
    * @param infilePath
    * @param jarEntryName
+   * @param msg
+   *          additional identifying info to log to the console
    */
   protected void copyFileToJar(JarOutputStream jout, String infilePath,
-          String jarEntryName)
+          String jarEntryName, String msg)
   {
-    DataInputStream dis = null;
-    try
+    try (InputStream is = new FileInputStream(infilePath))
     {
       File file = new File(infilePath);
       if (file.exists() && jout != null)
       {
-        dis = new DataInputStream(new FileInputStream(file));
-        byte[] data = new byte[(int) file.length()];
-        dis.readFully(data);
-        writeJarEntry(jout, jarEntryName, data);
+        System.out.println(
+                "Writing jar entry " + jarEntryName + " (" + msg + ")");
+        jout.putNextEntry(new JarEntry(jarEntryName));
+        copyAll(is, jout);
+        jout.closeEntry();
+        // dis = new DataInputStream(new FileInputStream(file));
+        // byte[] data = new byte[(int) file.length()];
+        // dis.readFully(data);
+        // writeJarEntry(jout, jarEntryName, data);
       }
     } catch (Exception ex)
     {
       ex.printStackTrace();
-    } finally
-    {
-      if (dis != null)
-      {
-        try
-        {
-          dis.close();
-        } catch (IOException e)
-        {
-          // ignore
-        }
-      }
     }
   }
 
   /**
-   * Write the data to a new entry of given name in the output jar file
+   * Copies input to output, in 4K buffers; handles any data (text or binary)
    * 
-   * @param jout
-   * @param jarEntryName
-   * @param data
+   * @param in
+   * @param out
    * @throws IOException
    */
-  protected void writeJarEntry(JarOutputStream jout, String jarEntryName,
-          byte[] data) throws IOException
+  protected void copyAll(InputStream in, OutputStream out)
+          throws IOException
   {
-    if (jout != null)
+    byte[] buffer = new byte[4096];
+    int bytesRead = 0;
+    while ((bytesRead = in.read(buffer)) != -1)
     {
-      System.out.println("Writing jar entry " + jarEntryName);
-      jout.putNextEntry(new JarEntry(jarEntryName));
-      DataOutputStream dout = new DataOutputStream(jout);
-      dout.write(data, 0, data.length);
-      dout.flush();
-      jout.closeEntry();
+      out.write(buffer, 0, bytesRead);
     }
   }
 
@@ -2058,7 +2127,7 @@ public class Jalview2XML
    * @param viewFrame
    * @return
    */
-  protected String saveStructureState(AlignmentPanel ap, SequenceI jds,
+  protected String saveStructureViewer(AlignmentPanel ap, SequenceI jds,
           Pdbids pdb, PDBEntry entry, List<String> viewIds,
           String matchedFile, StructureViewerBase viewFrame)
   {
@@ -2087,7 +2156,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());
       }
@@ -2112,7 +2181,7 @@ public class Jalview2XML
           final String viewId = viewFrame.getViewId();
           state.setViewId(viewId);
           state.setAlignwithAlignPanel(viewFrame.isUsedforaligment(ap));
-          state.setColourwithAlignPanel(viewFrame.isUsedforcolourby(ap));
+          state.setColourwithAlignPanel(viewFrame.isUsedForColourBy(ap));
           state.setColourByJmol(viewFrame.isColouredByViewer());
           state.setType(viewFrame.getViewerType().toString());
           // pdb.addStructureState(state);
@@ -2385,7 +2454,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;
         }
@@ -2413,7 +2482,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;
       }
     }
@@ -2457,7 +2527,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;
   }
@@ -2497,7 +2568,7 @@ public class Jalview2XML
     vamsasSeq.setName(jds.getName());
     vamsasSeq.setSequence(jds.getSequenceAsString());
     vamsasSeq.setDescription(jds.getDescription());
-    jalview.datamodel.DBRefEntry[] dbrefs = null;
+    List<DBRefEntry> dbrefs = null;
     if (jds.getDatasetSequence() != null)
     {
       vamsasSeq.setDsseqid(seqHash(jds.getDatasetSequence()));
@@ -2519,21 +2590,22 @@ public class Jalview2XML
      */
     if (dbrefs != null)
     {
-      for (int d = 0; d < dbrefs.length; d++)
+      for (int d = 0, nd = dbrefs.size(); d < nd; d++)
       {
         DBRef dbref = new DBRef();
-        DBRefEntry dbRefEntry = dbrefs[d];
-        dbref.setSource(dbRefEntry.getSource());
-        dbref.setVersion(dbRefEntry.getVersion());
-        dbref.setAccessionId(dbRefEntry.getAccessionId());
-        if (dbRefEntry instanceof GeneLocus)
+        DBRefEntry ref = dbrefs.get(d);
+        dbref.setSource(ref.getSource());
+        dbref.setVersion(ref.getVersion());
+        dbref.setAccessionId(ref.getAccessionId());
+        dbref.setCanonical(ref.isCanonical());
+        if (ref instanceof GeneLocus)
         {
           dbref.setLocus(true);
         }
-        if (dbRefEntry.hasMap())
+        if (ref.hasMap())
         {
-          Mapping mp = createVamsasMapping(dbRefEntry.getMap(), parentseq,
-                  jds, recurse);
+          Mapping mp = createVamsasMapping(ref.getMap(), parentseq, jds,
+                  recurse);
           dbref.setMapping(mp);
         }
         vamsasSeq.getDBRef().add(dbref);
@@ -2593,12 +2665,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);
@@ -2641,7 +2713,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);
@@ -2726,7 +2798,7 @@ public class Jalview2XML
    * @param file
    *          - HTTP URL or filename
    */
-  public AlignFrame loadJalviewAlign(final String file)
+  public AlignFrame loadJalviewAlign(final Object file)
   {
 
     jalview.gui.AlignFrame af = null;
@@ -2760,7 +2832,7 @@ public class Jalview2XML
           public void run()
           {
             setLoadingFinishedForNewStructureViewers();
-          };
+          }
         });
       } catch (Exception x)
       {
@@ -2770,43 +2842,68 @@ public class Jalview2XML
     return af;
   }
 
+  @SuppressWarnings("unused")
   private jarInputStreamProvider createjarInputStreamProvider(
-          final String file) throws MalformedURLException
+          final Object ofile) throws MalformedURLException
   {
-    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()
+    // 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;
 
-      @Override
-      public JarInputStream getJarInputStream() throws IOException
+      if (HttpUtils.startsWithHttpOrHttps(file))
       {
-        if (_url != null)
+        url = new URL(file);
+      }
+      final URL _url = url;
+      return new jarInputStreamProvider()
+      {
+
+        @Override
+        public JarInputStream getJarInputStream() throws IOException
         {
-          return new JarInputStream(_url.openStream());
+          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));
+          }
         }
-        else
+
+        @Override
+        public String getFilename()
         {
-          return new JarInputStream(new FileInputStream(file));
+          return file;
         }
-      }
-
-      @Override
-      public String getFilename()
-      {
-        return file;
-      }
-    };
+      };
+    } catch (IOException e)
+    {
+      e.printStackTrace();
+      return null;
+    }
   }
 
   /**
@@ -2849,9 +2946,6 @@ public class Jalview2XML
 
         if (jarentry != null && jarentry.getName().endsWith(".xml"))
         {
-          InputStreamReader in = new InputStreamReader(jin, UTF_8);
-          // JalviewModel object = new JalviewModel();
-
           JAXBContext jc = JAXBContext
                   .newInstance("jalview.xml.binding.jalview");
           XMLStreamReader streamReader = XMLInputFactory.newInstance()
@@ -2861,11 +2955,6 @@ public class Jalview2XML
                   JalviewModel.class);
           JalviewModel object = jbe.getValue();
 
-          /*
-          Unmarshaller unmar = new Unmarshaller(object);
-          unmar.setValidation(false);
-          object = (JalviewModel) unmar.unmarshal(in);
-          */
           if (true) // !skipViewport(object))
           {
             _af = loadFromObject(object, file, true, jprovider);
@@ -3174,8 +3263,6 @@ public class Jalview2XML
   protected String copyJarEntry(jarInputStreamProvider jprovider,
           String jarEntryName, String prefix, String suffixModel)
   {
-    BufferedReader in = null;
-    PrintWriter out = null;
     String suffix = ".tmp";
     if (suffixModel == null)
     {
@@ -3186,59 +3273,35 @@ public class Jalview2XML
     {
       suffix = "." + suffixModel.substring(sfpos + 1);
     }
-    try
-    {
-      JarInputStream jin = jprovider.getJarInputStream();
-      /*
-       * if (jprovider.startsWith("http://")) { jin = new JarInputStream(new
-       * URL(jprovider).openStream()); } else { jin = new JarInputStream(new
-       * FileInputStream(jprovider)); }
-       */
 
+    try (JarInputStream jin = jprovider.getJarInputStream())
+    {
       JarEntry entry = null;
       do
       {
         entry = jin.getNextJarEntry();
       } while (entry != null && !entry.getName().equals(jarEntryName));
+
       if (entry != null)
       {
-        in = new BufferedReader(new InputStreamReader(jin, UTF_8));
+        // in = new BufferedReader(new InputStreamReader(jin, UTF_8));
         File outFile = File.createTempFile(prefix, suffix);
         outFile.deleteOnExit();
-        out = new PrintWriter(new FileOutputStream(outFile));
-        String data;
-
-        while ((data = in.readLine()) != null)
+        try (OutputStream os = new FileOutputStream(outFile))
         {
-          out.println(data);
+          copyAll(jin, os);
         }
-        out.flush();
         String t = outFile.getAbsolutePath();
         return t;
       }
       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)
     {
       ex.printStackTrace();
-    } finally
-    {
-      if (in != null)
-      {
-        try
-        {
-          in.close();
-        } catch (IOException e)
-        {
-          // ignore
-        }
-      }
-      if (out != null)
-      {
-        out.close();
-      }
     }
 
     return null;
@@ -4049,7 +4112,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)
      */
@@ -4059,12 +4122,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.
@@ -4209,8 +4309,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;
         }
 
@@ -4309,10 +4410,15 @@ public class Jalview2XML
             }
             if (!structureViewers.containsKey(sviewid))
             {
+              String viewerType = structureState.getType();
+              if (viewerType == null) // pre Jalview 2.9
+              {
+                viewerType = ViewerType.JMOL.toString();
+              }
               structureViewers.put(sviewid,
                       new StructureViewerModel(x, y, width, height, false,
                               false, true, structureState.getViewId(),
-                              structureState.getType()));
+                              viewerType));
               // Legacy pre-2.7 conversion JAL-823 :
               // do not assume any view has to be linked for colour by
               // sequence
@@ -4366,7 +4472,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);
             }
           }
         }
@@ -4413,247 +4519,16 @@ public class Jalview2XML
       return;
     }
 
-    /*
-     * From 2.9: stateData.type contains JMOL or CHIMERA, data is in jar entry
-     * "viewer_"+stateData.viewId
-     */
-    if (ViewerType.CHIMERA.toString().equals(stateData.getType()))
-    {
-      createChimeraViewer(viewerData, af, jprovider);
-    }
-    else
-    {
-      /*
-       * else Jmol (if pre-2.9, stateData contains JMOL state string)
-       */
-      createJmolViewer(viewerData, af, jprovider);
-    }
-  }
-
-  /**
-   * Create a new Chimera viewer.
-   * 
-   * @param data
-   * @param af
-   * @param jprovider
-   */
-  protected void createChimeraViewer(
-          Entry<String, StructureViewerModel> viewerData, AlignFrame af,
-          jarInputStreamProvider jprovider)
-  {
-    StructureViewerModel data = viewerData.getValue();
-    String chimeraSessionFile = data.getStateData();
-
-    /*
-     * Copy Chimera session from jar entry "viewer_"+viewId to a temporary file
-     * 
-     * NB this is the 'saved' viewId as in the project file XML, _not_ the
-     * 'uniquified' sviewid used to reconstruct the viewer here
-     */
-    String viewerJarEntryName = getViewerJarEntryName(data.getViewId());
-    chimeraSessionFile = copyJarEntry(jprovider, viewerJarEntryName,
-            "chimera", ".py");
-
-    Set<Entry<File, StructureData>> fileData = data.getFileData()
-            .entrySet();
-    List<PDBEntry> pdbs = new ArrayList<>();
-    List<SequenceI[]> allseqs = new ArrayList<>();
-    for (Entry<File, StructureData> pdb : fileData)
-    {
-      String filePath = pdb.getValue().getFilePath();
-      String pdbId = pdb.getValue().getPdbId();
-      // pdbs.add(new PDBEntry(filePath, pdbId));
-      pdbs.add(new PDBEntry(pdbId, null, PDBEntry.Type.PDB, filePath));
-      final List<SequenceI> seqList = pdb.getValue().getSeqList();
-      SequenceI[] seqs = seqList.toArray(new SequenceI[seqList.size()]);
-      allseqs.add(seqs);
-    }
-
-    boolean colourByChimera = data.isColourByViewer();
-    boolean colourBySequence = data.isColourWithAlignPanel();
-
-    // TODO use StructureViewer as a factory here, see JAL-1761
-    final PDBEntry[] pdbArray = pdbs.toArray(new PDBEntry[pdbs.size()]);
-    final SequenceI[][] seqsArray = allseqs
-            .toArray(new SequenceI[allseqs.size()][]);
-    String newViewId = viewerData.getKey();
-
-    ChimeraViewFrame cvf = new ChimeraViewFrame(chimeraSessionFile,
-            af.alignPanel, pdbArray, seqsArray, colourByChimera,
-            colourBySequence, newViewId);
-    cvf.setSize(data.getWidth(), data.getHeight());
-    cvf.setLocation(data.getX(), data.getY());
-  }
-
-  /**
-   * Create a new Jmol window. First parse the Jmol state to translate filenames
-   * loaded into the view, and record the order in which files are shown in the
-   * Jmol view, so we can add the sequence mappings in same order.
-   * 
-   * @param viewerData
-   * @param af
-   * @param jprovider
-   */
-  protected void createJmolViewer(
-          final Entry<String, StructureViewerModel> viewerData,
-          AlignFrame af, jarInputStreamProvider jprovider)
-  {
-    final StructureViewerModel svattrib = viewerData.getValue();
-    String state = svattrib.getStateData();
-
-    /*
-     * Pre-2.9: state element value is the Jmol state string
-     * 
-     * 2.9+: @type is "JMOL", state data is in a Jar file member named "viewer_"
-     * + viewId
-     */
-    if (ViewerType.JMOL.toString().equals(svattrib.getType()))
-    {
-      state = readJarEntry(jprovider,
-              getViewerJarEntryName(svattrib.getViewId()));
-    }
-
-    List<String> pdbfilenames = new ArrayList<>();
-    List<SequenceI[]> seqmaps = new ArrayList<>();
-    List<String> pdbids = new ArrayList<>();
-    StringBuilder newFileLoc = new StringBuilder(64);
-    int cp = 0, ncp, ecp;
-    Map<File, StructureData> oldFiles = svattrib.getFileData();
-    while ((ncp = state.indexOf("load ", cp)) > -1)
-    {
-      do
-      {
-        // look for next filename in load statement
-        newFileLoc.append(state.substring(cp,
-                ncp = (state.indexOf("\"", ncp + 1) + 1)));
-        String oldfilenam = state.substring(ncp,
-                ecp = state.indexOf("\"", ncp));
-        // recover the new mapping data for this old filename
-        // have to normalize filename - since Jmol and jalview do
-        // filename
-        // translation differently.
-        StructureData filedat = oldFiles.get(new File(oldfilenam));
-        if (filedat == null)
-        {
-          String reformatedOldFilename = oldfilenam.replaceAll("/", "\\\\");
-          filedat = oldFiles.get(new File(reformatedOldFilename));
-        }
-        newFileLoc
-                .append(Platform.escapeBackslashes(filedat.getFilePath()));
-        pdbfilenames.add(filedat.getFilePath());
-        pdbids.add(filedat.getPdbId());
-        seqmaps.add(filedat.getSeqList().toArray(new SequenceI[0]));
-        newFileLoc.append("\"");
-        cp = ecp + 1; // advance beyond last \" and set cursor so we can
-                      // look for next file statement.
-      } while ((ncp = state.indexOf("/*file*/", cp)) > -1);
-    }
-    if (cp > 0)
-    {
-      // just append rest of state
-      newFileLoc.append(state.substring(cp));
-    }
-    else
-    {
-      System.err.print("Ignoring incomplete Jmol state for PDB ids: ");
-      newFileLoc = new StringBuilder(state);
-      newFileLoc.append("; load append ");
-      for (File id : oldFiles.keySet())
-      {
-        // add this and any other pdb files that should be present in
-        // the viewer
-        StructureData filedat = oldFiles.get(id);
-        newFileLoc.append(filedat.getFilePath());
-        pdbfilenames.add(filedat.getFilePath());
-        pdbids.add(filedat.getPdbId());
-        seqmaps.add(filedat.getSeqList().toArray(new SequenceI[0]));
-        newFileLoc.append(" \"");
-        newFileLoc.append(filedat.getFilePath());
-        newFileLoc.append("\"");
-
-      }
-      newFileLoc.append(";");
-    }
-
-    if (newFileLoc.length() == 0)
-    {
-      return;
-    }
-    int histbug = newFileLoc.indexOf("history = ");
-    if (histbug > -1)
-    {
-      /*
-       * change "history = [true|false];" to "history = [1|0];"
-       */
-      histbug += 10;
-      int diff = histbug == -1 ? -1 : newFileLoc.indexOf(";", histbug);
-      String val = (diff == -1) ? null
-              : newFileLoc.substring(histbug, diff);
-      if (val != null && val.length() >= 4)
-      {
-        if (val.contains("e")) // eh? what can it be?
-        {
-          if (val.trim().equals("true"))
-          {
-            val = "1";
-          }
-          else
-          {
-            val = "0";
-          }
-          newFileLoc.replace(histbug, diff, val);
-        }
-      }
-    }
-
-    final String[] pdbf = pdbfilenames
-            .toArray(new String[pdbfilenames.size()]);
-    final String[] id = pdbids.toArray(new String[pdbids.size()]);
-    final SequenceI[][] sq = seqmaps
-            .toArray(new SequenceI[seqmaps.size()][]);
-    final String fileloc = newFileLoc.toString();
-    final String sviewid = viewerData.getKey();
-    final AlignFrame alf = af;
-    final Rectangle rect = new Rectangle(svattrib.getX(), svattrib.getY(),
-            svattrib.getWidth(), svattrib.getHeight());
+    String type = stateData.getType();
     try
     {
-      javax.swing.SwingUtilities.invokeAndWait(new Runnable()
-      {
-        @Override
-        public void run()
-        {
-          JalviewStructureDisplayI sview = null;
-          try
-          {
-            sview = new StructureViewer(
-                    alf.alignPanel.getStructureSelectionManager())
-                            .createView(StructureViewer.ViewerType.JMOL,
-                                    pdbf, id, sq, alf.alignPanel, svattrib,
-                                    fileloc, rect, sviewid);
-            addNewStructureViewer(sview);
-          } catch (OutOfMemoryError ex)
-          {
-            new OOMWarning("restoring structure view for PDB id " + id,
-                    (OutOfMemoryError) ex.getCause());
-            if (sview != null && sview.isVisible())
-            {
-              sview.closeViewer(false);
-              sview.setVisible(false);
-              sview.dispose();
-            }
-          }
-        }
-      });
-    } catch (InvocationTargetException ex)
+      ViewerType viewerType = ViewerType.valueOf(type);
+      createStructureViewer(viewerType, viewerData, af, jprovider);
+    } catch (IllegalArgumentException | NullPointerException e)
     {
-      warn("Unexpected error when opening Jmol view.", ex);
-
-    } catch (InterruptedException e)
-    {
-      // e.printStackTrace();
+      // TODO JAL-3619 show error dialog / offer an alternative viewer
+      Console.error("Invalid structure viewer type: " + type);
     }
-
   }
 
   /**
@@ -4806,7 +4681,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)
@@ -4858,7 +4733,18 @@ public class Jalview2XML
   {
     AlignFrame af = null;
     af = new AlignFrame(al, safeInt(view.getWidth()),
-            safeInt(view.getHeight()), uniqueSeqSetId, viewId);
+            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);
 
@@ -5173,7 +5059,7 @@ public class Jalview2XML
           }
           else
           {
-            warn("Couldn't recover parameters for "
+            Console.warn("Couldn't recover parameters for "
                     + calcIdParam.getCalcId());
           }
         }
@@ -5201,6 +5087,7 @@ public class Jalview2XML
     {
       splitFrameCandidates.put(view, af);
     }
+
     return af;
   }
 
@@ -5264,7 +5151,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()),
@@ -5449,10 +5339,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;
@@ -5495,7 +5382,7 @@ public class Jalview2XML
         addDatasetRef(vamsasSet.getDatasetId(), ds);
       }
     }
-    Vector dseqs = null;
+    Vector<SequenceI> dseqs = null;
     if (!ignoreUnrefed)
     {
       // recovering an alignment View
@@ -5504,14 +5391,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;
@@ -5523,7 +5412,7 @@ public class Jalview2XML
       // try even harder to restore dataset
       AlignmentI xtantDS = checkIfHasDataset(vamsasSet.getSequence());
       // create a list of new dataset sequences
-      dseqs = new Vector();
+      dseqs = new Vector<>();
     }
     for (int i = 0, iSize = vamsasSet.getSequence().size(); i < iSize; i++)
     {
@@ -5536,7 +5425,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);
     }
@@ -5589,7 +5478,7 @@ 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!
       }
@@ -5612,7 +5501,8 @@ public class Jalview2XML
    *          vamsasSeq array ordering, to preserve ordering of dataset
    */
   private void ensureJalviewDatasetSequence(Sequence vamsasSeq,
-          AlignmentI ds, Vector dseqs, boolean ignoreUnrefed, int vseqpos)
+          AlignmentI ds, Vector<SequenceI> dseqs, boolean ignoreUnrefed,
+          int vseqpos)
   {
     // JBP TODO: Check this is called for AlCodonFrames to support recovery of
     // xRef Codon Maps
@@ -5794,7 +5684,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)
@@ -5844,6 +5735,7 @@ public class Jalview2XML
       {
         entry.setMap(addMapping(dr.getMapping()));
       }
+      entry.setCanonical(dr.isCanonical());
       datasetSequence.addDBRef(entry);
     }
   }
@@ -5929,7 +5821,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);
 
     }
@@ -5982,62 +5874,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
@@ -6096,7 +5932,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;
         }
@@ -6111,7 +5947,7 @@ public class Jalview2XML
       }
       else
       {
-        Cache.log.debug("Ignoring " + jvobj.getClass() + " (ID = " + id);
+        Console.debug("Ignoring " + jvobj.getClass() + " (ID = " + id);
       }
     }
   }
@@ -6181,7 +6017,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)
     {
@@ -6331,11 +6168,179 @@ public class Jalview2XML
       }
     } catch (Exception ex)
     {
-      Cache.log.error("Error loading PCA: " + ex.toString());
+      Console.error("Error loading PCA: " + ex.toString());
     }
   }
 
   /**
+   * Creates a new structure viewer window
+   * 
+   * @param viewerType
+   * @param viewerData
+   * @param af
+   * @param jprovider
+   */
+  protected void createStructureViewer(ViewerType viewerType,
+          final Entry<String, StructureViewerModel> viewerData,
+          AlignFrame af, jarInputStreamProvider jprovider)
+  {
+    final StructureViewerModel viewerModel = viewerData.getValue();
+    String sessionFilePath = null;
+
+    if (viewerType == ViewerType.JMOL)
+    {
+      sessionFilePath = rewriteJmolSession(viewerModel, jprovider);
+    }
+    else
+    {
+      String viewerJarEntryName = getViewerJarEntryName(
+              viewerModel.getViewId());
+      sessionFilePath = copyJarEntry(jprovider, viewerJarEntryName,
+              "viewerSession", ".tmp");
+    }
+    final String sessionPath = sessionFilePath;
+    final String sviewid = viewerData.getKey();
+    try
+    {
+      SwingUtilities.invokeAndWait(new Runnable()
+      {
+        @Override
+        public void run()
+        {
+          JalviewStructureDisplayI sview = null;
+          try
+          {
+            sview = StructureViewer.createView(viewerType, af.alignPanel,
+                    viewerModel, sessionPath, sviewid);
+            addNewStructureViewer(sview);
+          } catch (OutOfMemoryError ex)
+          {
+            new OOMWarning("Restoring structure view for " + viewerType,
+                    (OutOfMemoryError) ex.getCause());
+            if (sview != null && sview.isVisible())
+            {
+              sview.closeViewer(false);
+              sview.setVisible(false);
+              sview.dispose();
+            }
+          }
+        }
+      });
+    } catch (InvocationTargetException | InterruptedException ex)
+    {
+      Console.warn("Unexpected error when opening " + viewerType
+              + " structure viewer", ex);
+    }
+  }
+
+  /**
+   * Rewrites a Jmol session script, saves it to a temporary file, and returns
+   * the path of the file. "load file" commands are rewritten to change the
+   * original PDB file names to those created as the Jalview project is loaded.
+   * 
+   * @param svattrib
+   * @param jprovider
+   * @return
+   */
+  private String rewriteJmolSession(StructureViewerModel svattrib,
+          jarInputStreamProvider jprovider)
+  {
+    String state = svattrib.getStateData(); // Jalview < 2.9
+    if (state == null || state.isEmpty()) // Jalview >= 2.9
+    {
+      String jarEntryName = getViewerJarEntryName(svattrib.getViewId());
+      state = readJarEntry(jprovider, jarEntryName);
+    }
+    // TODO or simpler? for each key in oldFiles,
+    // replace key.getPath() in state with oldFiles.get(key).getFilePath()
+    // (allowing for different path escapings)
+    StringBuilder rewritten = new StringBuilder(state.length());
+    int cp = 0, ncp, ecp;
+    Map<File, StructureData> oldFiles = svattrib.getFileData();
+    while ((ncp = state.indexOf("load ", cp)) > -1)
+    {
+      do
+      {
+        // look for next filename in load statement
+        rewritten.append(state.substring(cp,
+                ncp = (state.indexOf("\"", ncp + 1) + 1)));
+        String oldfilenam = state.substring(ncp,
+                ecp = state.indexOf("\"", ncp));
+        // recover the new mapping data for this old filename
+        // have to normalize filename - since Jmol and jalview do
+        // filename translation differently.
+        StructureData filedat = oldFiles.get(new File(oldfilenam));
+        if (filedat == null)
+        {
+          String reformatedOldFilename = oldfilenam.replaceAll("/", "\\\\");
+          filedat = oldFiles.get(new File(reformatedOldFilename));
+        }
+        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.
+      } while ((ncp = state.indexOf("/*file*/", cp)) > -1);
+    }
+    if (cp > 0)
+    {
+      // just append rest of state
+      rewritten.append(state.substring(cp));
+    }
+    else
+    {
+      System.err.print("Ignoring incomplete Jmol state for PDB ids: ");
+      rewritten = new StringBuilder(state);
+      rewritten.append("; load append ");
+      for (File id : oldFiles.keySet())
+      {
+        // add pdb files that should be present in the viewer
+        StructureData filedat = oldFiles.get(id);
+        rewritten.append(" \"").append(filedat.getFilePath()).append("\"");
+      }
+      rewritten.append(";");
+    }
+
+    if (rewritten.length() == 0)
+    {
+      return null;
+    }
+    final String history = "history = ";
+    int historyIndex = rewritten.indexOf(history);
+    if (historyIndex > -1)
+    {
+      /*
+       * change "history = [true|false];" to "history = [1|0];"
+       */
+      historyIndex += history.length();
+      String val = rewritten.substring(historyIndex, historyIndex + 5);
+      if (val.startsWith("true"))
+      {
+        rewritten.replace(historyIndex, historyIndex + 4, "1");
+      }
+      else if (val.startsWith("false"))
+      {
+        rewritten.replace(historyIndex, historyIndex + 5, "0");
+      }
+    }
+
+    try
+    {
+      File tmp = File.createTempFile("viewerSession", ".tmp");
+      try (OutputStream os = new FileOutputStream(tmp))
+      {
+        InputStream is = new ByteArrayInputStream(
+                rewritten.toString().getBytes());
+        copyAll(is, os);
+        return tmp.getAbsolutePath();
+      }
+    } catch (IOException e)
+    {
+      Console.error("Error restoring Jmol session: " + e.toString());
+    }
+    return null;
+  }
+
+  /**
    * Populates an XML model of the feature colour scheme for one feature type
    * 
    * @param featureType
@@ -6583,7 +6588,7 @@ public class Jalview2XML
         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();
@@ -6637,4 +6642,44 @@ public class Jalview2XML
 
     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;
+  }
 }