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