JAL-1988 Added a saves in progress check for quit
[jalview.git] / src / jalview / jbgui / QuitHandler.java
1 package jalview.jbgui;
2
3 import java.io.File;
4
5 import javax.swing.JFrame;
6 import javax.swing.JOptionPane;
7
8 import com.formdev.flatlaf.extras.FlatDesktop;
9
10 import jalview.io.BackupFiles;
11 import jalview.util.MessageManager;
12
13 public class QuitHandler
14 {
15   public static void setQuitHandler()
16   {
17     FlatDesktop.setQuitHandler(response -> {
18       // confirm quit if needed and wanted
19       boolean confirmQuit = jalview.bin.Cache
20               .getDefault(jalview.gui.Desktop.CONFIRM_KEYBOARD_QUIT, true);
21       /* 
22          if undostack is empty
23            confirmQuit = false
24        */
25       int n = confirmQuit ? JOptionPane.CANCEL_OPTION
26               : JOptionPane.OK_OPTION;
27
28       // if going to confirm, do it before the save in progress check to give
29       // the save time to finish!
30       if (confirmQuit)
31       {
32         n = frameOnTop(MessageManager.getString("label.quit_jalview"),
33                 MessageManager.getString("action.quit"),
34                 JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
35
36       }
37
38       if (BackupFiles.hasSavesInProgress())
39       {
40         // sleep 1
41         // ...
42
43         StringBuilder messageSB = new StringBuilder(
44                 MessageManager.getString("label.save_in_progress"));
45         for (File file : BackupFiles.savesInProgressFiles())
46         {
47           messageSB.append("\n");
48           messageSB.append(file.getName());
49         }
50         n = frameOnTop(messageSB.toString(),
51                 MessageManager.getString("action.force_quit"),
52                 JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
53       }
54
55       boolean canQuit = (n == JOptionPane.OK_OPTION);
56       if (canQuit)
57       {
58         response.performQuit();
59       }
60       else
61       {
62         response.cancelQuit();
63       }
64     });
65   }
66
67   public static int frameOnTop(String label, String actionString,
68           int JOPTIONPANE_OPTION, int JOPTIONPANE_MESSAGETYPE)
69   {
70     // ensure Jalview window is brought to front for Quit confirmation
71     // window to be visible
72
73     // this method of raising the Jalview window is broken in java
74     // jalviewDesktop.setVisible(true);
75     // jalviewDesktop.toFront();
76
77     // a better hack which works instead
78
79     JFrame dialogParent = new JFrame();
80     dialogParent.setAlwaysOnTop(true);
81
82     int n = JOptionPane.showConfirmDialog(dialogParent, label, actionString,
83             JOPTIONPANE_OPTION, JOPTIONPANE_MESSAGETYPE);
84
85     dialogParent.setAlwaysOnTop(false);
86     dialogParent.dispose();
87
88     return n;
89   }
90
91 }