JAL-1988 JAL-3772 wait timer working first time but blocking desktop gui updates
[jalview.git] / src / jalview / io / BackupFiles.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.io;
22
23 import java.io.File;
24 import java.io.IOException;
25 import java.nio.file.Files;
26 import java.nio.file.Path;
27 import java.nio.file.Paths;
28 import java.nio.file.StandardCopyOption;
29 import java.text.SimpleDateFormat;
30 import java.util.ArrayList;
31 import java.util.HashMap;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.TreeMap;
35 import java.util.concurrent.CompletableFuture;
36 import java.util.concurrent.ExecutionException;
37 import java.util.concurrent.ExecutorService;
38 import java.util.concurrent.Executors;
39 import java.util.concurrent.Future;
40
41 import jalview.bin.Cache;
42 import jalview.bin.Console;
43 import jalview.gui.Desktop;
44 import jalview.gui.JvOptionPane;
45 import jalview.util.MessageManager;
46 import jalview.util.Platform;
47
48 /*
49  * BackupFiles used for manipulating (naming rolling/deleting) backup/version files when an alignment or project file is saved.
50  * User configurable options are:
51  * BACKUPFILES_ENABLED - boolean flag as to whether to use this mechanism or act as before, including overwriting files as saved.
52  * The rest of the options are now saved as BACKUPFILES_PRESET, BACKUPFILES_SAVED and BACKUPFILES_CUSTOM
53  * (see BackupFilesPresetEntry)
54  */
55
56 public class BackupFiles
57 {
58
59   // labels for saved params in Cache and .jalview_properties
60   public static final String NS = "BACKUPFILES";
61
62   public static final String ENABLED = NS + "_ENABLED";
63
64   public static final String NUM_PLACEHOLDER = "%n";
65
66   private static final String DEFAULT_TEMP_FILE = "jalview_temp_file_" + NS;
67
68   private static final String TEMP_FILE_EXT = ".tmp";
69
70   // file - File object to be backed up and then updated (written over)
71   private File file;
72
73   // enabled - default flag as to whether to do the backup file roll (if not
74   // defined in preferences)
75   private static boolean enabled;
76
77   // confirmDelete - default flag as to whether to confirm with the user before
78   // deleting old backup/version files
79   private static boolean confirmDelete;
80
81   // defaultSuffix - default template to use to append to basename of file
82   private String suffix;
83
84   // noMax - flag to turn off a maximum number of files
85   private boolean noMax;
86
87   // defaultMax - default max number of backup files
88   private int max;
89
90   // defaultDigits - number of zero-led digits to use in the filename
91   private int digits;
92
93   // reverseOrder - set to true to make newest (latest) files lowest number
94   // (like rolled log files)
95   private boolean reverseOrder;
96
97   // temp saved file to become new saved file
98   private File tempFile;
99
100   // flag set to see if file save to temp file was successful
101   private boolean tempFileWriteSuccess;
102
103   // array of files to be deleted, with extra information
104   private ArrayList<File> deleteFiles = new ArrayList<>();
105
106   // date formatting for modification times
107   private static final SimpleDateFormat sdf = new SimpleDateFormat(
108           "yyyy-MM-dd HH:mm:ss");
109
110   private static final String newTempFileSuffix = "_newfile";
111
112   private static final String oldTempFileSuffix = "_oldfile_tobedeleted";
113
114   // thread pool used for completablefutures
115   private static final ExecutorService executorService = Executors
116           .newFixedThreadPool(3);
117
118   private static List<BackupFiles> savesInProgress = new ArrayList<>();
119
120   private CompletableFuture<Boolean> myFuture = null;
121
122   private boolean addSaveInProgress()
123   {
124     if (savesInProgress.contains(this))
125     {
126       return false;
127     }
128     else
129     {
130       this.setMyFuture();
131       savesInProgress.add(this);
132       return true;
133     }
134   }
135
136   private boolean removeSaveInProgress(boolean ret)
137   {
138     if (savesInProgress.contains(this))
139     {
140       this.getMyFuture().complete(ret);
141       // remove all occurrences
142       while (savesInProgress.remove(this))
143       {
144       }
145       return true;
146     }
147     return false;
148   }
149
150   private static CompletableFuture<Boolean> getNewFuture()
151   {
152     return new CompletableFuture<Boolean>()
153     {
154     };
155   }
156
157   private CompletableFuture<Boolean> getMyFuture()
158   {
159     return this.myFuture;
160   }
161
162   private void setMyFuture()
163   {
164     this.myFuture = getNewFuture();
165   }
166
167   public static boolean hasSavesInProgress()
168   {
169     boolean has = false;
170     for (CompletableFuture cf : savesInProgressCompletableFutures())
171     {
172       has |= !cf.isDone();
173     }
174     return has;
175   }
176
177   public static List<File> savesInProgressFiles()
178   {
179     List<File> files = new ArrayList<>();
180     for (BackupFiles bfile : savesInProgress)
181     {
182       files.add(bfile.getFile());
183     }
184     return files;
185   }
186
187   public static List<CompletableFuture<Boolean>> savesInProgressCompletableFutures()
188   {
189     List<CompletableFuture<Boolean>> cfs = new ArrayList<>();
190     for (BackupFiles bfile : savesInProgress)
191     {
192       cfs.add(bfile.getMyFuture());
193     }
194     return cfs;
195   }
196
197   public static Future<Boolean> allSaved()
198   {
199     CompletableFuture<Boolean> f = new CompletableFuture<>();
200
201     executorService.submit(() -> {
202       for (BackupFiles buf : savesInProgress)
203       {
204         boolean allSaved = true;
205         try
206         {
207           allSaved &= buf.getMyFuture().get();
208         } catch (InterruptedException e)
209         {
210           Console.debug("InterruptedException waiting for files to save",
211                   e);
212         } catch (ExecutionException e)
213         {
214           Console.debug("ExecutionException waiting for files to save", e);
215         }
216         f.complete(allSaved);
217       }
218     });
219     return f;
220   }
221
222   public BackupFiles(String filename)
223   {
224     this(new File(filename));
225   }
226
227   // first time defaults for SUFFIX, NO_MAX, ROLL_MAX, SUFFIX_DIGITS and
228   // REVERSE_ORDER
229   public BackupFiles(File file)
230   {
231     classInit();
232     this.file = file;
233
234     // add this file from the save in progress stack
235     addSaveInProgress();
236
237     BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
238             .getSavedBackupEntry();
239     this.suffix = bfpe.suffix;
240     this.noMax = bfpe.keepAll;
241     this.max = bfpe.rollMax;
242     this.digits = bfpe.digits;
243     this.reverseOrder = bfpe.reverse;
244
245     // create a temp file to save new data in
246     File temp = null;
247     try
248     {
249       if (file != null)
250       {
251         String tempfilename = file.getName();
252         File tempdir = file.getParentFile();
253         Console.trace(
254                 "BACKUPFILES [file!=null] attempting to create temp file for "
255                         + tempfilename + " in dir " + tempdir);
256         temp = File.createTempFile(tempfilename,
257                 TEMP_FILE_EXT + newTempFileSuffix, tempdir);
258         Console.debug(
259                 "BACKUPFILES using temp file " + temp.getAbsolutePath());
260       }
261       else
262       {
263         Console.trace(
264                 "BACKUPFILES [file==null] attempting to create default temp file "
265                         + DEFAULT_TEMP_FILE + " with extension "
266                         + TEMP_FILE_EXT);
267         temp = File.createTempFile(DEFAULT_TEMP_FILE, TEMP_FILE_EXT);
268       }
269     } catch (IOException e)
270     {
271       Console.error("Could not create temp file to save to (IOException)");
272       Console.error(e.getMessage());
273       Console.debug(Cache.getStackTraceString(e));
274     } catch (Exception e)
275     {
276       Console.error("Exception creating temp file for saving");
277       Console.debug(Cache.getStackTraceString(e));
278     }
279     this.setTempFile(temp);
280   }
281
282   public static void classInit()
283   {
284     Console.initLogger();
285     Console.trace("BACKUPFILES classInit");
286     boolean e = Cache.getDefault(ENABLED, !Platform.isJS());
287     setEnabled(e);
288     Console.trace("BACKUPFILES " + (e ? "enabled" : "disabled"));
289     BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
290             .getSavedBackupEntry();
291     Console.trace("BACKUPFILES preset scheme " + bfpe.toString());
292     setConfirmDelete(bfpe.confirmDelete);
293     Console.trace("BACKUPFILES confirm delete " + bfpe.confirmDelete);
294   }
295
296   public static void setEnabled(boolean flag)
297   {
298     enabled = flag;
299   }
300
301   public static boolean getEnabled()
302   {
303     classInit();
304     return enabled;
305   }
306
307   public static void setConfirmDelete(boolean flag)
308   {
309     confirmDelete = flag;
310   }
311
312   public static boolean getConfirmDelete()
313   {
314     classInit();
315     return confirmDelete;
316   }
317
318   // set, get and rename temp file into place
319   public void setTempFile(File temp)
320   {
321     this.tempFile = temp;
322   }
323
324   public File getTempFile()
325   {
326     return tempFile;
327   }
328
329   public String getTempFilePath()
330   {
331     String path = null;
332     try
333     {
334       path = this.getTempFile().getCanonicalPath();
335     } catch (IOException e)
336     {
337       Console.error("IOException when getting Canonical Path of temp file '"
338               + this.getTempFile().getName() + "'");
339       Console.debug(Cache.getStackTraceString(e));
340     }
341     return path;
342   }
343
344   public boolean setWriteSuccess(boolean flag)
345   {
346     boolean old = this.tempFileWriteSuccess;
347     this.tempFileWriteSuccess = flag;
348     return old;
349   }
350
351   public boolean getWriteSuccess()
352   {
353     return this.tempFileWriteSuccess;
354   }
355
356   public boolean renameTempFile()
357   {
358     return moveFileToFile(tempFile, file);
359   }
360
361   // roll the backupfiles
362   public boolean rollBackupFiles()
363   {
364     return this.rollBackupFiles(true);
365   }
366
367   public boolean rollBackupFiles(boolean tidyUp)
368   {
369     // file doesn't yet exist or backups are not enabled or template is null or
370     // empty
371     if ((!file.exists()) || (!enabled) || max < 0 || suffix == null
372             || suffix.length() == 0)
373     {
374       // nothing to do
375       Console.debug("BACKUPFILES rollBackupFiles nothing to do." + ", "
376               + "filename: " + (file != null ? file.getName() : "null")
377               + ", " + "file exists: " + file.exists() + ", " + "enabled: "
378               + enabled + ", " + "max: " + max + ", " + "suffix: '" + suffix
379               + "'");
380       return true;
381     }
382
383     Console.trace("BACKUPFILES rollBackupFiles starting");
384
385     String dir = "";
386     File dirFile;
387     try
388     {
389       dirFile = file.getParentFile();
390       dir = dirFile.getCanonicalPath();
391       Console.trace("BACKUPFILES dir: " + dir);
392     } catch (Exception e)
393     {
394       Console.error("Could not get canonical path for file '" + file + "'");
395       Console.error(e.getMessage());
396       Console.debug(Cache.getStackTraceString(e));
397       return false;
398     }
399     String filename = file.getName();
400     String basename = filename;
401
402     Console.trace("BACKUPFILES filename is " + filename);
403     boolean ret = true;
404     // Create/move backups up one
405
406     deleteFiles.clear();
407
408     // find existing backup files
409     BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
410             digits);
411     File[] backupFiles = dirFile.listFiles(bff);
412     int nextIndexNum = 0;
413
414     Console.trace("BACKUPFILES backupFiles.length: " + backupFiles.length);
415     if (backupFiles.length == 0)
416     {
417       // No other backup files. Just need to move existing file to backupfile_1
418       Console.trace(
419               "BACKUPFILES no existing backup files, setting index to 1");
420       nextIndexNum = 1;
421     }
422     else
423     {
424       TreeMap<Integer, File> bfTreeMap = sortBackupFilesAsTreeMap(
425               backupFiles, basename);
426       // bfTreeMap now a sorted list of <Integer index>,<File backupfile>
427       // mappings
428
429       if (reverseOrder)
430       {
431         // backup style numbering
432         Console.trace("BACKUPFILES rolling files in reverse order");
433
434         int tempMax = noMax ? -1 : max;
435         // noMax == true means no limits
436         // look for first "gap" in backupFiles
437         // if tempMax is -1 at this stage just keep going until there's a gap,
438         // then hopefully tempMax gets set to the right index (a positive
439         // integer so the loop breaks)...
440         // why do I feel a little uneasy about this loop?..
441         for (int i = 1; tempMax < 0 || i <= max; i++)
442         {
443           if (!bfTreeMap.containsKey(i)) // first index without existent
444                                          // backupfile
445           {
446             tempMax = i;
447           }
448         }
449
450         File previousFile = null;
451         File fileToBeDeleted = null;
452         for (int n = tempMax; n > 0; n--)
453         {
454           String backupfilename = dir + File.separatorChar
455                   + BackupFilenameParts.getBackupFilename(n, basename,
456                           suffix, digits);
457           File backupfile_n = new File(backupfilename);
458
459           if (!backupfile_n.exists())
460           {
461             // no "oldest" file to delete
462             previousFile = backupfile_n;
463             fileToBeDeleted = null;
464             Console.trace("BACKUPFILES No oldest file to delete");
465             continue;
466           }
467
468           // check the modification time of this (backupfile_n) and the previous
469           // file (fileToBeDeleted) if the previous file is going to be deleted
470           if (fileToBeDeleted != null)
471           {
472             File replacementFile = backupfile_n;
473             long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
474             long replacementFileLMT = replacementFile.lastModified();
475             Console.trace("BACKUPFILES fileToBeDeleted is "
476                     + fileToBeDeleted.getAbsolutePath());
477             Console.trace("BACKUPFILES replacementFile is "
478                     + backupfile_n.getAbsolutePath());
479
480             try
481             {
482               File oldestTempFile = nextTempFile(fileToBeDeleted.getName(),
483                       dirFile);
484
485               if (fileToBeDeletedLMT > replacementFileLMT)
486               {
487                 String fileToBeDeletedLMTString = sdf
488                         .format(fileToBeDeletedLMT);
489                 String replacementFileLMTString = sdf
490                         .format(replacementFileLMT);
491                 Console.warn("WARNING! I am set to delete backupfile "
492                         + fileToBeDeleted.getName()
493                         + " has modification time "
494                         + fileToBeDeletedLMTString
495                         + " which is newer than its replacement "
496                         + replacementFile.getName()
497                         + " with modification time "
498                         + replacementFileLMTString);
499
500                 boolean delete = confirmNewerDeleteFile(fileToBeDeleted,
501                         replacementFile, true);
502                 Console.trace("BACKUPFILES "
503                         + (delete ? "confirmed" : "not") + " deleting file "
504                         + fileToBeDeleted.getAbsolutePath()
505                         + " which is newer than "
506                         + replacementFile.getAbsolutePath());
507
508                 if (delete)
509                 {
510                   // User has confirmed delete -- no need to add it to the list
511                   fileToBeDeleted.delete();
512                 }
513                 else
514                 {
515                   Console.debug("BACKUPFILES moving "
516                           + fileToBeDeleted.getAbsolutePath() + " to "
517                           + oldestTempFile.getAbsolutePath());
518                   moveFileToFile(fileToBeDeleted, oldestTempFile);
519                 }
520               }
521               else
522               {
523                 Console.debug("BACKUPFILES going to move "
524                         + fileToBeDeleted.getAbsolutePath() + " to "
525                         + oldestTempFile.getAbsolutePath());
526                 moveFileToFile(fileToBeDeleted, oldestTempFile);
527                 addDeleteFile(oldestTempFile);
528               }
529
530             } catch (Exception e)
531             {
532               Console.error(
533                       "Error occurred, probably making new temp file for '"
534                               + fileToBeDeleted.getName() + "'");
535               Console.error(Cache.getStackTraceString(e));
536             }
537
538             // reset
539             fileToBeDeleted = null;
540           }
541
542           if (!noMax && n == tempMax && backupfile_n.exists())
543           {
544             fileToBeDeleted = backupfile_n;
545           }
546           else
547           {
548             if (previousFile != null)
549             {
550               // using boolean '&' instead of '&&' as don't want moveFileToFile
551               // attempt to be conditional (short-circuit)
552               ret = ret & moveFileToFile(backupfile_n, previousFile);
553             }
554           }
555
556           previousFile = backupfile_n;
557         }
558
559         // index to use for the latest backup
560         nextIndexNum = 1;
561       }
562       else // not reverse numbering
563       {
564         // version style numbering (with earliest file deletion if max files
565         // reached)
566
567         bfTreeMap.values().toArray(backupFiles);
568         StringBuilder bfsb = new StringBuilder();
569         for (int i = 0; i < backupFiles.length; i++)
570         {
571           if (bfsb.length() > 0)
572           {
573             bfsb.append(", ");
574           }
575           bfsb.append(backupFiles[i].getName());
576         }
577         Console.trace("BACKUPFILES backupFiles: " + bfsb.toString());
578
579         // noMax == true means keep all backup files
580         if ((!noMax) && bfTreeMap.size() >= max)
581         {
582           Console.trace("BACKUPFILES noMax: " + noMax + ", " + "max: " + max
583                   + ", " + "bfTreeMap.size(): " + bfTreeMap.size());
584           // need to delete some files to keep number of backups to designated
585           // max.
586           // Note that if the suffix is not numbered then do not delete any
587           // backup files later or we'll delete the new backup file (there can
588           // be only one).
589           int numToDelete = suffix.indexOf(NUM_PLACEHOLDER) > -1
590                   ? bfTreeMap.size() - max + 1
591                   : 0;
592           Console.trace("BACKUPFILES numToDelete: " + numToDelete);
593           // the "replacement" file is the latest backup file being kept (it's
594           // not replacing though)
595           File replacementFile = numToDelete < backupFiles.length
596                   ? backupFiles[numToDelete]
597                   : null;
598           for (int i = 0; i < numToDelete; i++)
599           {
600             // check the deletion files for modification time of the last
601             // backupfile being saved
602             File fileToBeDeleted = backupFiles[i];
603             boolean delete = true;
604
605             Console.trace(
606                     "BACKUPFILES fileToBeDeleted: " + fileToBeDeleted);
607
608             boolean newer = false;
609             if (replacementFile != null)
610             {
611               long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
612               long replacementFileLMT = replacementFile != null
613                       ? replacementFile.lastModified()
614                       : Long.MAX_VALUE;
615               if (fileToBeDeletedLMT > replacementFileLMT)
616               {
617                 String fileToBeDeletedLMTString = sdf
618                         .format(fileToBeDeletedLMT);
619                 String replacementFileLMTString = sdf
620                         .format(replacementFileLMT);
621
622                 Console.warn("WARNING! I am set to delete backupfile '"
623                         + fileToBeDeleted.getName()
624                         + "' has modification time "
625                         + fileToBeDeletedLMTString
626                         + " which is newer than the oldest backupfile being kept '"
627                         + replacementFile.getName()
628                         + "' with modification time "
629                         + replacementFileLMTString);
630
631                 delete = confirmNewerDeleteFile(fileToBeDeleted,
632                         replacementFile, false);
633                 if (delete)
634                 {
635                   // User has confirmed delete -- no need to add it to the list
636                   fileToBeDeleted.delete();
637                   Console.debug("BACKUPFILES deleting fileToBeDeleted: "
638                           + fileToBeDeleted);
639                   delete = false;
640                 }
641                 else
642                 {
643                   // keeping file, nothing to do!
644                   Console.debug("BACKUPFILES keeping fileToBeDeleted: "
645                           + fileToBeDeleted);
646                 }
647               }
648             }
649             if (delete)
650             {
651               addDeleteFile(fileToBeDeleted);
652               Console.debug("BACKUPFILES addDeleteFile(fileToBeDeleted): "
653                       + fileToBeDeleted);
654             }
655
656           }
657
658         }
659
660         nextIndexNum = bfTreeMap.lastKey() + 1;
661       }
662     }
663
664     // Let's make the new backup file!! yay, got there at last!
665     String latestBackupFilename = dir + File.separatorChar
666             + BackupFilenameParts.getBackupFilename(nextIndexNum, basename,
667                     suffix, digits);
668     Console.trace("BACKUPFILES Moving old file [" + file
669             + "] to latestBackupFilename [" + latestBackupFilename + "]");
670     // using boolean '&' instead of '&&' as don't want moveFileToFile attempt to
671     // be conditional (short-circuit)
672     ret = ret & moveFileToFile(file, new File(latestBackupFilename));
673     Console.debug(
674             "BACKUPFILES moving " + file + " to " + latestBackupFilename
675                     + " was " + (ret ? "" : "NOT ") + "successful");
676     if (tidyUp)
677     {
678       Console.debug("BACKUPFILES tidying up files");
679       tidyUpFiles();
680     }
681
682     return ret;
683   }
684
685   private static File nextTempFile(String filename, File dirFile)
686           throws IOException
687   {
688     File temp = null;
689     COUNT: for (int i = 1; i < 1000; i++)
690     {
691       File trythis = new File(dirFile,
692               filename + '~' + Integer.toString(i));
693       if (!trythis.exists())
694       {
695         temp = trythis;
696         break COUNT;
697       }
698
699     }
700     if (temp == null)
701     {
702       temp = File.createTempFile(filename, TEMP_FILE_EXT, dirFile);
703     }
704     return temp;
705   }
706
707   private void tidyUpFiles()
708   {
709     deleteOldFiles();
710   }
711
712   private static boolean confirmNewerDeleteFile(File fileToBeDeleted,
713           File replacementFile, boolean replace)
714   {
715     StringBuilder messageSB = new StringBuilder();
716
717     File ftbd = fileToBeDeleted;
718     String ftbdLMT = sdf.format(ftbd.lastModified());
719     String ftbdSize = Long.toString(ftbd.length());
720
721     File rf = replacementFile;
722     String rfLMT = sdf.format(rf.lastModified());
723     String rfSize = Long.toString(rf.length());
724
725     int confirmButton = JvOptionPane.NO_OPTION;
726     if (replace)
727     {
728       File saveFile = null;
729       try
730       {
731         saveFile = nextTempFile(ftbd.getName(), ftbd.getParentFile());
732       } catch (Exception e)
733       {
734         Console.error(
735                 "Error when confirming to keep backup file newer than other backup files.");
736         e.printStackTrace();
737       }
738       messageSB.append(MessageManager.formatMessage(
739               "label.newerdelete_replacement_line", new String[]
740               { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
741                   rfSize }));
742       // "Backup file\n''{0}''\t(modified {2}, size {4})\nis to be deleted and
743       // replaced by apparently older file \n''{1}''\t(modified {3}, size
744       // {5}).""
745       messageSB.append("\n\n");
746       messageSB.append(MessageManager.formatMessage(
747               "label.confirm_deletion_or_rename", new String[]
748               { ftbd.getName(), saveFile.getName() }));
749       // "Confirm deletion of ''{0}'' or rename to ''{1}''?"
750       String[] options = new String[] {
751           MessageManager.getString("label.delete"),
752           MessageManager.getString("label.rename") };
753
754       confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
755               : JvOptionPane.showOptionDialog(Desktop.desktop,
756                       messageSB.toString(),
757                       MessageManager.getString(
758                               "label.backupfiles_confirm_delete"),
759                       // "Confirm delete"
760                       JvOptionPane.YES_NO_OPTION,
761                       JvOptionPane.WARNING_MESSAGE, null, options,
762                       options[0]);
763     }
764     else
765     {
766       messageSB.append(MessageManager
767               .formatMessage("label.newerdelete_line", new String[]
768               { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
769                   rfSize }));
770       // "Backup file\n''{0}''\t(modified {2}, size {4})\nis to be deleted but
771       // is newer than the oldest remaining backup file \n''{1}''\t(modified
772       // {3}, size {5})."
773       messageSB.append("\n\n");
774       messageSB.append(MessageManager
775               .formatMessage("label.confirm_deletion", new String[]
776               { ftbd.getName() }));
777       // "Confirm deletion of ''{0}''?"
778       String[] options = new String[] {
779           MessageManager.getString("label.delete"),
780           MessageManager.getString("label.keep") };
781
782       confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
783               : JvOptionPane.showOptionDialog(Desktop.desktop,
784                       messageSB.toString(),
785                       MessageManager.getString(
786                               "label.backupfiles_confirm_delete"),
787                       // "Confirm delete"
788                       JvOptionPane.YES_NO_OPTION,
789                       JvOptionPane.WARNING_MESSAGE, null, options,
790                       options[0]);
791     }
792
793     // return should be TRUE if file is to be deleted
794     return (confirmButton == JvOptionPane.YES_OPTION);
795   }
796
797   private void deleteOldFiles()
798   {
799     if (deleteFiles != null && !deleteFiles.isEmpty())
800     {
801       boolean doDelete = false;
802       StringBuilder messageSB = null;
803       if (confirmDelete && deleteFiles.size() > 0)
804       {
805         messageSB = new StringBuilder();
806         messageSB.append(MessageManager
807                 .getString("label.backupfiles_confirm_delete_old_files"));
808         // "Delete the following older backup files? (see the Backups tab in
809         // Preferences for more options)"
810         for (int i = 0; i < deleteFiles.size(); i++)
811         {
812           File df = deleteFiles.get(i);
813           messageSB.append("\n");
814           messageSB.append(df.getName());
815           messageSB.append(" ");
816           messageSB.append(MessageManager.formatMessage("label.file_info",
817                   new String[]
818                   { sdf.format(df.lastModified()),
819                       Long.toString(df.length()) }));
820           // "(modified {0}, size {1})"
821         }
822
823         int confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
824                 : JvOptionPane.showConfirmDialog(Desktop.desktop,
825                         messageSB.toString(),
826                         MessageManager.getString(
827                                 "label.backupfiles_confirm_delete"),
828                         // "Confirm delete"
829                         JvOptionPane.YES_NO_OPTION,
830                         JvOptionPane.WARNING_MESSAGE);
831
832         doDelete = (confirmButton == JvOptionPane.YES_OPTION);
833       }
834       else
835       {
836         doDelete = true;
837       }
838
839       if (doDelete)
840       {
841         for (int i = 0; i < deleteFiles.size(); i++)
842         {
843           File fileToDelete = deleteFiles.get(i);
844           Console.trace("BACKUPFILES about to delete fileToDelete:"
845                   + fileToDelete);
846           fileToDelete.delete();
847           Console.warn("deleted '" + fileToDelete.getName() + "'");
848         }
849       }
850
851     }
852
853     deleteFiles.clear();
854   }
855
856   private TreeMap<Integer, File> sortBackupFilesAsTreeMap(
857           File[] backupFiles, String basename)
858   {
859     // sort the backup files (based on integer found in the suffix) using a
860     // precomputed Hashmap for speed
861     Map<Integer, File> bfHashMap = new HashMap<>();
862     for (int i = 0; i < backupFiles.length; i++)
863     {
864       File f = backupFiles[i];
865       BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
866               digits);
867       bfHashMap.put(bfp.indexNum(), f);
868     }
869     TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
870     bfTreeMap.putAll(bfHashMap);
871     return bfTreeMap;
872   }
873
874   public boolean rollBackupsAndRenameTempFile()
875   {
876     boolean write = this.getWriteSuccess();
877
878     boolean roll = false;
879     boolean rename = false;
880     if (write)
881     {
882       roll = this.rollBackupFiles(false); // tidyUpFiles at the end
883       rename = this.renameTempFile();
884     }
885
886     /*
887      * Not sure that this confirmation is desirable.  By this stage the new file is
888      * already written successfully, but something (e.g. disk full) has happened while 
889      * trying to roll the backup files, and most likely the filename needed will already
890      * be vacant so renaming the temp file is nearly always correct!
891      */
892     boolean okay = roll && rename;
893     if (!okay)
894     {
895       StringBuilder messageSB = new StringBuilder();
896       messageSB.append(MessageManager.getString(
897               "label.backupfiles_confirm_save_file_backupfiles_roll_wrong"));
898       // "Something possibly went wrong with the backups of this file."
899       if (rename)
900       {
901         if (messageSB.length() > 0)
902         {
903           messageSB.append("\n");
904         }
905         messageSB.append(MessageManager.getString(
906                 "label.backupfiles_confirm_save_new_saved_file_ok"));
907         // "The new saved file seems okay."
908       }
909       else
910       {
911         if (messageSB.length() > 0)
912         {
913           messageSB.append("\n");
914         }
915         messageSB.append(MessageManager.getString(
916                 "label.backupfiles_confirm_save_new_saved_file_not_ok"));
917         // "The new saved file might not be okay."
918       }
919       if (messageSB.length() > 0)
920       {
921         messageSB.append("\n");
922       }
923       messageSB
924               .append(MessageManager.getString("label.continue_operation"));
925
926       int confirmButton = Platform.isHeadless() ? JvOptionPane.OK_OPTION
927               : JvOptionPane.showConfirmDialog(Desktop.desktop,
928                       messageSB.toString(),
929                       MessageManager.getString(
930                               "label.backupfiles_confirm_save_file"),
931                       // "Confirm save file"
932                       JvOptionPane.OK_OPTION, JvOptionPane.WARNING_MESSAGE);
933       okay = confirmButton == JvOptionPane.OK_OPTION;
934     }
935     if (okay)
936     {
937       tidyUpFiles();
938     }
939
940     // remove this file from the save in progress stack
941     removeSaveInProgress(rename);
942
943     return rename;
944   }
945
946   public static TreeMap<Integer, File> getBackupFilesAsTreeMap(
947           String fileName, String suffix, int digits)
948   {
949     File[] backupFiles = null;
950
951     File file = new File(fileName);
952
953     File dirFile;
954     try
955     {
956       dirFile = file.getParentFile();
957     } catch (Exception e)
958     {
959       Console.error("Could not get canonical path for file '" + file + "'");
960       return new TreeMap<>();
961     }
962
963     String filename = file.getName();
964     String basename = filename;
965
966     // find existing backup files
967     BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
968             digits);
969     backupFiles = dirFile.listFiles(bff); // is clone needed?
970
971     // sort the backup files (based on integer found in the suffix) using a
972     // precomputed Hashmap for speed
973     Map<Integer, File> bfHashMap = new HashMap<>();
974     for (int i = 0; i < backupFiles.length; i++)
975     {
976       File f = backupFiles[i];
977       BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
978               digits);
979       bfHashMap.put(bfp.indexNum(), f);
980     }
981     TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
982     bfTreeMap.putAll(bfHashMap);
983
984     return bfTreeMap;
985   }
986
987   /*
988   private boolean addDeleteFile(File fileToBeDeleted, File originalFile,
989           boolean delete, boolean newer)
990   {
991     return addDeleteFile(fileToBeDeleted, originalFile, null, delete, newer);
992   }
993   */
994   private boolean addDeleteFile(File fileToBeDeleted)
995   {
996     boolean ret = false;
997     int pos = deleteFiles.indexOf(fileToBeDeleted);
998     if (pos > -1)
999     {
1000       Console.debug("BACKUPFILES not adding file "
1001               + fileToBeDeleted.getAbsolutePath()
1002               + " to the delete list (already at index" + pos + ")");
1003       return true;
1004     }
1005     else
1006     {
1007       Console.debug("BACKUPFILES adding file "
1008               + fileToBeDeleted.getAbsolutePath() + " to the delete list");
1009       deleteFiles.add(fileToBeDeleted);
1010     }
1011     return ret;
1012   }
1013
1014   public File getFile()
1015   {
1016     return file;
1017   }
1018
1019   public static boolean moveFileToFile(File oldFile, File newFile)
1020   {
1021     Console.initLogger();
1022     boolean ret = false;
1023     Path oldPath = Paths.get(oldFile.getAbsolutePath());
1024     Path newPath = Paths.get(newFile.getAbsolutePath());
1025     try
1026     {
1027       // delete destination file - not usually necessary but Just In Case...
1028       Console.trace("BACKUPFILES deleting " + newFile.getAbsolutePath());
1029       newFile.delete();
1030       Console.trace("BACKUPFILES moving " + oldFile.getAbsolutePath()
1031               + " to " + newFile.getAbsolutePath());
1032       Files.move(oldPath, newPath, StandardCopyOption.REPLACE_EXISTING);
1033       ret = true;
1034       Console.trace("BACKUPFILES move seems to have succeeded");
1035     } catch (IOException e)
1036     {
1037       Console.warn("Could not move file '" + oldPath.toString() + "' to '"
1038               + newPath.toString() + "'");
1039       Console.error(e.getMessage());
1040       Console.debug(Cache.getStackTraceString(e));
1041       ret = false;
1042     } catch (Exception e)
1043     {
1044       Console.error(e.getMessage());
1045       Console.debug(Cache.getStackTraceString(e));
1046       ret = false;
1047     }
1048     return ret;
1049   }
1050 }