package net.sourceforge.pain.plugin.shutdown; import net.sourceforge.pain.*; import net.sourceforge.pain.plugin.*; import net.sourceforge.pain.util.*; /** * PAiN Date: 20.05.2003 Time: 0:48:58 */ public final class ShutdownTimer extends Plugin implements TimeListener { // in seconds private final int[] shutdownWarningTime = new int[]{60 * 60, 30 * 60, 20 * 60, 10 * 60, 5 * 60, 2 * 60, 60, 30, 5}; private int[] pulseWarningTimes; private int pos; private int shutdownPulseTime; public ShutdownTimer() { } public void init() throws Exception { pulseWarningTimes = new int[shutdownWarningTime.length]; shutdownPulseTime = 0; } public void reset(int secondsTillShutdown, boolean broadcast) { boolean warRunned = isShutdownInProcess(); Log.debug("reset:" + secondsTillShutdown + " broadcast:" + broadcast); pos = 0; final int currentTime = Core.getTime().getTime(); shutdownPulseTime = currentTime + secondsTillShutdown * Time.PULSE_PER_SCD; for (int i = 0; i < shutdownWarningTime.length; i++) { int secondsTillWarn = shutdownWarningTime[i]; pulseWarningTimes[i] = shutdownPulseTime - secondsTillWarn * Time.PULSE_PER_SCD; if (pulseWarningTimes[i] < currentTime || (broadcast && pulseWarningTimes[i] == currentTime)) { // skip this warn pos = i + 1; } } if (!warRunned) { Core.getTime().addListener(this); } if (broadcast) { event(secondsTillShutdown); } } public void deinit() { cancel(true); } public void cancel(boolean broadcast) { if (broadcast) { event(-1); } Core.getTime().removeListener(this); shutdownPulseTime = 0; } private void event(int seconds) { Log.debug("Shutdown in " + seconds + " seconds"); try { Core.processEvent("ShutdownWarn", new Integer(seconds)); } catch (Exception e) { Log.error(e); } } public void pulse(int time) { if (pos < shutdownWarningTime.length) { if (time < pulseWarningTimes[pos]) { return; } event(shutdownWarningTime[pos]); pos++; } else if (time >= shutdownPulseTime) { event(0); Core.shutdown(); } } public void now() { if (!isShutdownInProcess()) { reset(0, false); } pos = shutdownWarningTime.length; shutdownPulseTime = Core.getTime().getTime(); } public boolean isShutdownInProcess() { return shutdownPulseTime != 0; } public int getTimeBeforeShutdown() { if (!isShutdownInProcess()) { return -1; } return (shutdownPulseTime - Core.getTime().getTime()) / Time.PULSE_PER_SCD; } }