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