Project

General

Profile

Bug #2603 » test_quit_restart.C

Bruce Toll, 01/24/2014 11:46 PM

 
#include <Wt/WServer>
#include <Wt/WPushButton>
#include <Wt/WTextArea>
#include <Wt/WEvent>
#include <Wt/WTimer>
#include "boost/date_time/posix_time/posix_time.hpp"

using namespace Wt;

static const int ONESHOT_TIMER_MS = 1000 * 10; // 10 seconds to enter some initial text
static const int MAX_IDLE_TIME_BEFORE_QUIT = 10; // 10 second idle timeout

class TestApp : public WApplication
{
public:

TestApp(const WEnvironment& env) : WApplication(env)
{
new WText("Press button to quit now, or wait for timeout to expire<br/>", root());
button_ = new WPushButton(root());
button_->setText("Press to quit now.");
button_->clicked().connect(std::bind([=](){
if (!hasQuit()) {
testQuit();
}
}));
new WBreak(root());
text_area_ = new WTextArea(root());
text_area_->setColumns(80);
WTimer::singleShot(ONESHOT_TIMER_MS, std::bind([=]() {
new WText("<br/>Note: Text entered after this time will be captured on button press, but lost on session timeout...", root());
}));
}

void notify(const WEvent& event)
{
boost::posix_time::ptime
time_now = boost::posix_time::microsec_clock::local_time();

if (last_active_.is_not_a_date_time()) {
last_active_ = time_now;
}

if (event.eventType() == OtherEvent) {
long idle_time = (time_now - last_active_).total_seconds();
if (idle_time >= MAX_IDLE_TIME_BEFORE_QUIT) {
if (!hasQuit()) {
log("notice") << "notify: idle time expired (" << idle_time
<< " seconds), quitting session";
testQuit();
}
}
}
else {
last_active_ = time_now;
}
WApplication::notify(event);
}

void testQuit()
{
button_->setText("Press should now offer to restart (one-time only).");
new WText("<br/><br/>Quitting...WTextArea value is: '" + text_area_->valueText() + "'.<br/><br/>", root());
new WText("NOTE: This approach is not recommended. Documentation suggests a redirect or a page without interactive elements on quit().", root());
quit();
}

private:
boost::posix_time::ptime last_active_;
WPushButton* button_ {nullptr};
WTextArea* text_area_ {nullptr};
};

int main(int argc, char **argv)
{
return WRun(argc, argv, [](const WEnvironment& env) {return new TestApp(env);});
}
(1-1/3)