// This may look like C code, but it's really -*- C++ -*-
/*
 * Copyright (C) 2008 Emweb bvba, Kessel-Lo, Belgium.
 *
 * See the LICENSE file for terms of use.
 */
#ifndef WAPPLICATION_
#define WAPPLICATION_

#include <vector>
#include <string>
#include <set>

// even boost/poolfwd.hpp includes <windows.h> ...
namespace boost {
  struct default_user_allocator_new_delete;

  template <typename UserAllocator>
  class pool;
}

#include <Wt/WObject>
#include <Wt/WCssStyleSheet>
#include <Wt/WEvent>
#include <Wt/WMessageResourceBundle>
#include <Wt/WSignal>
#include <Wt/WString>

/*! \file WApplication
 */

namespace Wt {

class WApplication;
class WContainerWidget;
class WEnvironment;
class WEvent;
class WLoadingIndicator;
class WLogEntry;
class WResource;
class WText;

namespace Ext {
  class Dialog;
  class MessageBox;
}

class WebSession;
class UpdateLockImpl;
class SoundManager;

class WResponseEvent
#ifdef WT_TARGET_JAVA
                     : public WAbstractEvent
#endif // WT_TARGET_JAVA
{
public:
  WResponseEvent();
  const std::string& response() { return jsEvent_.response; }

#ifdef WT_TARGET_JAVA
  virtual WAbstractEvent *createFromJSEvent(const JavaScriptEvent& jsEvent)
  {
    return new WResponseEvent(jsEvent);
  }
#endif // WT_TARGET_JAVA

private:
  JavaScriptEvent jsEvent_;

  WResponseEvent(const JavaScriptEvent& jsEvent);

  friend class EventSignal<WResponseEvent>;
};

#ifndef WT_TARGET_JAVA
/*! \brief Typedef for a function that creates WApplication objects.
 *
 * \sa WRun()
 *
 * \relates WApplication
 */
typedef WApplication* (*ApplicationCreator)(const WEnvironment& env);
#endif // !WT_TARGET_JAVA

/*! \class WApplication Wt/WApplication Wt/WApplication
 *  \brief A class that represents an instance of a %Wt Application,
 *         corresponding to a single session.
 *
 * \if cpp
 * Each user session of your application has a corresponding
 * WApplication instance. This instance must be created, before
 * creating widgets, and is returned as the result of the callback
 * function passed to WRun(). The instance is the main entry point
 * into information pertaining to a single session, and holds
 * a reference to the root() of the widget tree.
 * \elseif java
 * Each user session of your application has a corresponding
 * WApplication instance. This instance must be created, before
 * creating widgets, and is returned by the function 
 * {javadoclink WtServlet#createApplication(WEnvironment)}. 
 * The instance is the main entry point into information pertaining 
 * to a single session, and holds a reference to the root() 
 * of the widget tree.
 * \endif
 *
 *
 * The recipe for a %Wt web application, which allocates new
 * WApplication instances for every user visiting the application is
 * thus:
 *
 * \if cpp
 * \code
 *   WApplication *createApplication(const WEnvironment WEnvironment& env)
 *   {
 *     //
 *     // Optionally, check the environment and redirect to an error page.
 *     //
 *     bool valid = ...;
 *
 *     WApplication *app;
 *     if (!valid) {
 *       app = new WApplication(env);
 *       app->redirect("error.html");
 *       app->quit();
 *     } else {
 *       // usually you will specialize your application class
 *       app = new WApplication(env);
 *
 *       //
 *       // Add widgets to app->root() and return the application object.
 *       //
 *     }
 *
 *     return app;
 *   }
 * \endcode
 * \endif
 *
 * \if cpp
 * Throughout the application, the instance is available through
 * WApplication::instance() (or through #wApp). The application may be
 * quited either using the method quit(), or because of a timeout
 * (when the user has closed the window, or crashed its computer or
 * was eaten by a virus -- but not because the user does not interact:
 * keep-alive messages in the background will keep the session around
 * as long as the user has the page opened). In either case, the
 * application object is deleted, allowing for cleanup of the entire
 * widget tree, and any other resources.
 * \elseif java
 * Throughout the application, the instance is available through
 * WApplication::instance(). The application may be
 * quited either using the method quit(), or because of a timeout
 * (when the user has closed the window, or crashed its computer or
 * was eaten by a virus -- but not because the user does not interact:
 * keep-alive messages in the background will keep the session around
 * as long as the user has the page opened). 
 * \endif
 *
 * The %WApplication object provides access to:
 * <ul>
 *   <li>WEnvironment information through environment(), which gives
 *     details about the user, start-up arguments, and user agent
 *     capabilities.</li>
 *   <li>inline and external style sheets using styleSheet() and
 *     useStyleSheet() respectively.</li>
 *   <li>the top-level widget (using root() for a plain application) or
 *     widgets (using bindWidget() for widget set mode), which contains
 *     the widget hierarchy.</li>
 *   \if cpp
 *   <li>localization information and message resources bundles, with
 *     setLocale(), locale() and messageResourceBundle().
 *   \elseif java
 *   <li>localization information and message resources bundles, with
 *     setLocale(), locale() and setLocalizedStrings(WLocalizedStrings).
 *   \endif
 *   <li>the maximum configured request size (maximumRequestSize()) and
 *     a signal requestTooLarge() to react to too large requests.</li>
 *   <li>defining cookies using setCookie() to persist information across
 *     sessions. These cookies may provide context across sessions, and may
 *     be inspected using WEnvironment::getCookie() in a future session.</li>
 *   <li>support for internal application paths that enable browser
 *     history (back and forward buttons), and bookmarks, using the
 *     setInternalPath() and related methods.</li>
 *   \if cpp
 *   <li>support for server-initiated updates with enableUpdates(),
 *     triggerUpdate() and getUpdateLock().</li>
 *   \endif
 * </ul>
 */
class WT_API WApplication : public WObject
{
public:
  /*! \brief Enumeration that indicates the Ajax communication method.
   *
   * \sa setAjaxMethod()
   */
  enum AjaxMethod {
    XMLHttpRequest,  //!< Use the XMLHttpRequest object (real AJAX)
    DynamicScriptTag //!< Use dynamic script tags (for cross-domain AJAX)
  };

#ifndef WT_TARGET_JAVA
  /*! \brief Typedef for a function that creates WApplication objects.
   *
   * \sa WRun()
   */
  typedef Wt::ApplicationCreator ApplicationCreator;
#endif // WT_TARGET_JAVA

  /*! \brief Construct a WApplication
   */
  WApplication(const WEnvironment& environment);

  /*! \brief Destructor.
   *
   * The destructor deletes the root() container, and as a consequence
   * the entire widget tree.
   */
  ~WApplication();

  /*! \brief Returns the current application instance.
   *
   * \if cpp
   * This is the same as the global variable #wApp. In a
   * multi-threaded server, it returns the thread-specific application
   * instance (using thread-specific storage).
   * \elseif java
   * In a multi-threaded server, it returns the thread-specific application
   * instance (using thread-specific storage).
   * \endif
   */
  static WApplication *instance();

  /*! \brief Returns the application environment.
   *
   * This is the environment that was used when constructing the
   * application. The environment contains all settings that constrain
   * the application from outside.
   */
  const WEnvironment& environment() const;

  /*! \brief Returns the root container.
   *
   * This is the top-level widget container of the application, and
   * corresponds to entire browser window. The user interface of your
   * application is represented by the content of this container.
   *
   * \if cpp
   * \note The root() is only defined in normal application mode. For
   * \link Wt::WidgetSet WidgetSet\endlink mode, there is no
   * root() container, and 0 is returned. Instead, use bindWidget() to
   * bind root widgets to existing HTML &lt;div&gt; elements on the
   * page.
   * \elseif java
   * \note The root() is only defined in normal Application mode.
   *  For WidgetSet mode there is no root() container, and null is 
   *  returned. Instead, use bindWidget() to bind root widgets 
   *  to existing HTML &lt;div&gt; elements on the page.
   *  \endif
   */
  WContainerWidget *root() const { return widgetRoot_; }

  /*! \brief Returns a reference to the inline style sheet.
   *
   * Widgets may allow configuration of their look and feel through
   * style classes. These may be defined in this inline stylesheet, or
   * in external style sheets.
   *
   * \sa useStyleSheet()
   */
  WCssStyleSheet& styleSheet() { return styleSheet_; }

  /*! \brief Adds an external style sheet.
   *
   * Widgets may allow configuration of their look and feel through
   * style classes. These may be defined in an inline stylesheet,
   * or in external style sheets.
   *
   * The <i>uri</i> indicates a relative or absolute URL to the
   * stylesheet.
   *
   * External stylesheets are inserted after the internal style sheet,
   * and can therefore override default styles set by widgets in the
   * internal style sheet.
   *
   * \sa styleSheet(), useStyleSheet(const std::string&, const std::string&)
   */
  void useStyleSheet(const std::string& uri);

  /*! \brief Adds an external style sheet, conditional for IE
   *
   * <i>condition</i> is a string that is used to apply the stylesheet
   * to specific versions of IE. Only a limited subset of the IE
   * conditional comments syntax is supported. Examples are:
   * - "IE gte 6": only for IE version 6 or later. 
   * - "!IE gte 6": only for IE versions prior to IE6.
   * - "IE lte 7": only for IE versions prior to IE7.
   *
   * The <i>uri</i> indicates a relative or absolute URL to the
   * stylesheet.
   *
   * \sa useStyleSheet(const std::string&)
   */
  void useStyleSheet(const std::string& uri, const std::string& condition);

 /*! \brief Set the title.
   *
   * Set the title that appears as the browser window title.
   *
   * The default title is "".
   *
   * \sa title()
   */
  void setTitle(const WString& title);

  /*! \brief Returns the title.
   *
   * \sa setTitle(const WString&)
   */
  const WString& title() const { return title_; }

  /*! \brief Returns the object that provides localized strings.
   *
   * \if cpp
   * The default value is a WMessageResourceBundle instance, which
   * uses XML files to resolve localized strings, but you can set a
   * custom class using setLocalizedStrings().
   * \elseif java
   * You can set a class implementing WLocalizedStrings using setLocalizedStrings().
   * \endif
   * 
   * \if cpp
   * \sa WString::tr(), messageResourceBundle()
   * \elseif java
   * \sa WString::tr()
   * \endif
   */
  WLocalizedStrings *localizedStrings() { return localizedStrings_; }

  /*! \brief Set the string translator.
   *
   * The string translator resolves localized strings in the current
   * locale. The previous string translator is deleted, and ownership is
   * transferred to the application.
   *
   * \sa localizedStrings(), WString::tr(const char *key)
   */
  void setLocalizedStrings(WLocalizedStrings *translator);

#ifndef WT_TARGET_JAVA
  /*! \brief Returns the message resource bundle.
   *
   * The message resource bundle defines the list of external XML
   * files that are used to lookup localized strings.
   *
   * The default localizedStrings() is a WMessageResourceBundle
   * object, and this method returns localizedStrings() upcasted to
   * this type.
   *
   * \sa WString::tr(const char *key)
   */
  WMessageResourceBundle& messageResourceBundle() const;
#endif // WT_TARGET_JAVA

  /*! \brief Changes the locale.
   *
   * By passing a <i>locale</i> that is an empty string, the default
   * locale is chosen. The locale is used by the string translator to
   * resolve internationalized strings.
   *
   * When the locale gets changed, refresh() is called, which will
   * resolve the strings in the new locale.
   *
   * The default locale is copied from the environment
   * (WEnvironment::locale()), and is the locale that was configured
   * by the user in his browser preferences.
   *
   * \sa localizedStrings(), WString::tr()
   */
  void setLocale(const WT_LOCALE& locale);

  /*! \brief Returns the currently used locale.
   *
   * \sa setLocale(const std::string&)
   */
  WT_LOCALE locale() const { return locale_; }

  /*! \brief Refresh the application.
   *
   * Causes the application to refresh its data, including messages
   * from message-resource bundles. This done by propagating
   * WWidget::refresh() through the widget hierarchy.
   *
   * This method is also called when the user hits the refresh (or
   * reload) button, in case the application is configured to not
   * create a new session in response.
   *
   * \sa WWidget::refresh()
   */
  virtual void refresh();

  /*! \brief Bind a top-level widget for a WidgetSet deployment.
   *
   * This method binds a widget to an existing element on the page.
   * The element type should correspond with the widget type (e.g. it
   * should be a &lt;div&gt; for a WContainerWidget, or a
   * &lt;table&gt; for a WTable).
   *
   * \sa root()
   * \sa Wt::WidgetSet
   */
  void bindWidget(WWidget *widget, const std::string& domId);

  /*! \brief Returns a URL for the current session
   *
   * Returns the (relative) URL for this application session
   * (including the session ID if necessary). The URL includes the
   * full application path, and is expanded by the browser into a full
   * URL.
   *
   * For example, for an application deployed at
   * \code
   * http://www.mydomain.com/stuff/app.wt
   * \endcode
   * this method would return <tt>"/stuff/app.wt?wtd=AbCdEf"</tt>,
   * when using URL rewriting for session-tracking or
   * <tt>"/stuff/app.wt?a=a"</tt> when using cookies for
   * session-tracking 
   * \if cpp
   * (see also \ref config_session for configuring
   * the session-tracking method)
   * \endif
   * . As in each case, a query is
   * appended at the end of the URL, additional query parameters can
   * be appended in the form of <tt>"&param1=value&param2=value"</tt>.
   *
   * To obtain a URL that is suitable for bookmarking the current
   * application state, to be used across sessions, use bookmarkUrl()
   * instead.
   *
   * \sa redirect(), WEnvironment::hostName(), WEnvironment::urlScheme()
   * \sa bookmarkUrl()
   */
  std::string url() const;

  /*! \brief Returns a bookmarkable URL, including the internal path.
   *
   * Is equivalent to <tt>bookmarkUrl(internalPath())</tt>, see
   * bookmarkUrl(const std::string&) const.
   *
   * To obtain a URL that is refers to the current session of the
   * application, use url() instead.
   *
   * \sa url(), bookmarkUrl(const std::string&) const
   */
  std::string bookmarkUrl() const;

  /*! \brief Returns a bookmarkable URL for a given internal path.
   *
   * Returns the (relative) URL for this application that includes the
   * internal path <i>internalPath</i>, usable across sessions. The
   * URL is relative and expanded into a full URL by the browser.
   *
   * For example, for an application with current URL:
   * \code
   * http://www.mydomain.com/stuff/app.wt#/project/internal/
   * \endcode
   * when called with <tt>"/project/external"</tt>, this method would
   * return:
   *  - <tt>"app.wt/project/external/"</tt> when JavaScript is available, or
   *    the agent is a web spider, or
   *  - <tt>"app.wt/project/external/?wtd=AbCdEf"</tt> when no JavaScript
   *    is available and URL rewriting is used for session-tracking
   *    \if cpp
   *    (see also \ref config_session for configuring the session-tracking 
   *    method).
   *    \endif
   *
   * When the application is deployed at a folder (ending with '/'),
   * this style of URLs is not possible, and URLs are of the form:
   *  - <tt>"?_=/project/external/"</tt> when JavaScript is available, or
   *    the agent is a web spider, or
   *  - <tt>"?_=/project/external/&wtd=AbCdEf"</tt> when no JavaScript
   *    is available and URL rewriting is used for session-tracking.
   *
   * You can use bookmarkUrl() as the destination for a WAnchor, and
   * listen to a click event is attached to a slot that switches to
   * the internal path <i>internalPath</i> (see
   * WAnchor::setRefInternalPath()). In this way, an anchor can be
   * used to switch between internal paths within an application
   * regardless of the situation (browser with or without Ajax
   * support, or a web spider bot), but still generates suitable URLs
   * across sessions, which can be used for bookmarking, opening in a
   * new window/tab, or indexing.
   *
   * To obtain a URL that refers to the current session of the
   * application, use url() instead.
   *
   * \sa url(), bookmarkUrl()
   */
  std::string bookmarkUrl(const std::string& internalPath) const;

  /*! \brief Change the internal path.
   *
   * A %Wt application may manage multiple virtual paths. The virtual
   * path is appended to the application URL. Depending on the
   * situation, the path is directly appended to the application URL
   * or it is appended using a name anchor (#).
   *
   * For example, for an application deployed at:
   * \code
   * http://www.mydomain.com/stuff/app.wt
   * \endcode
   * for which an <i>internalPath</i> <tt>"/project/z3cbc/details/"</tt> is
   * set, the two forms for the application URL are:
   * <ul>
   * <li> in a browser with AJAX:
   * \code
   * http://www.mydomain.com/stuff/app.wt#/project/z3cbc/details/
   * \endcode
   * </li><li>
   * or in other situations (no JavaScript):
   * \code
   * http://www.mydomain.com/stuff/app.wt/project/z3cbc/details/
   * \endcode
   *    This has as major consequence that from the browser stand point,
   *    the application now serves many different URLs. As a consequence,
   *    relative URLs will break. Still, you can specify relative URLs
   *    within your application (in for example WAnchor::setRef() or
   *    WImage::setImageRef()) since %Wt will transform them
   *    to absolute URLs when needed. But, this in turn may break deployments
   *    behind reverse proxies when the context paths differ. For the same
   *    reason, you will need to use absolute URLs in any XHTML or CSS you
   *    write manually. <br>
   *    This type of URLs are only used when the your application is
   *    deployed at a location that does not end with
   *    a '/'. Otherwise, %Wt will generate URLS like:
   * \code
   * http://www.mydomain.com/stuff/?_=/project/z3cbc/details/
   * \endcode
   * </li></ul>
   *
   * When the internal path is changed, an entry is added to the
   * browser history. When the user navigates back and forward through
   * this history (using the browser back/forward buttons), an
   * internalPathChanged() event is emitted. You should listen to this
   * signal to switch the application to the corresponding state. When
   * <i>emitChange</i> is true, this signal is also emitted by setting
   * the path.
   *
   * A url that includes the internal path may be obtained using
   * bookmarkUrl().
   *
   * The <i>internalPath</i> must start with a '/'. In this way, you
   * can still use normal anchors in your HTML. Internal path changes
   * initiated in the browser to paths that do not start with a '/'
   * are ignored.
   *
   * \sa bookmarkUrl(), internalPath(), internalPathChanged()
   */
  void setInternalPath(const std::string& path, bool emitChange = false);

  /*! \brief Returns the current internal path.
   *
   * When the application is just created, this is equal to
   * WEnvironment::internalPath().
   *
   * \sa setInternalPath(), internalPathNextPart(), internalPathMatches()
   */
  std::string internalPath() const;

  /*! \brief Returns part of the current internal path.
   *
   * This is a convenience method which returns the next folder in the
   * internal path, after the given <i>path</i>.
   *
   * For example, when the current internal path is
   * <tt>"/project/z3cbc/details"</tt>, this method returns
   * <tt>"details"</tt> when called with <tt>"/project/z3cbc/"</tt> as
   * <i>path</i> argument.
   *
   * The <i>path</i> must start with a '/', and internalPathMatches()
   * should evaluate to <i>true</i> for the given <i>path</i>. If not,
   * an empty string is returned and an error message is logged.
   *
   * \sa internalPath(), internalPathChanged()
   */
  std::string internalPathNextPart(const std::string& path) const;

  /*! \brief Checks if the internal path matches a given path.
   *
   * Returns whether the current internalPath() starts with
   * <i>path</i> (or is equal to <i>path</i>). You will typically use
   * this method within a slot conneted to the internalPathChanged()
   * signal, to check that an internal path change affects the
   * widget. It may also be useful before changing <i>path</i> using
   * setInternalPath() if you do not intend to remove sub paths when
   * the current internal path already matches <i>path</i>.
   *
   * The <i>path</i> must start with a '/'.
   *
   * \sa setInternalPath(), internalPath()
   */
  bool internalPathMatches(const std::string& path) const;

  /*! \brief %Signal which indicates that the user changes the internal path.
   *
   * This signal indicates a change to the internal path, which is
   * usually triggered by the user using the browser back/forward
   * buttons.
   *
   * The argument contains the new internal path.
   *
   * \sa setInternalPath()
   */
  Signal<std::string>& internalPathChanged() { return internalPathChanged_; }

  /*! \brief Redirects the application to another location.
   *
   * The client will be redirected to a new location. Use this in
   * conjunction with quit() if you want to the application to be
   * terminated as well.
   *
   * Calling redirect() does not imply quit() since it may be useful
   * to switch between a non-secure and secure (SSL) transport
   * connection.
   */
  void redirect(const std::string& url);

  /*! \brief Returns the unique identifier for the current session.
   *
   * The session id is a string that uniquely identifies the current session.
   * Note that the actual contents has no particular meaning and client
   * applications should in no way try to interpret its value.
   */
  std::string sessionId() const;

  WebSession *session() { return session_; }

#ifndef WT_TARGET_JAVA
  /*! \brief Enable server-initiated updates.
   *
   * By default, updates to the user interface are possible only at
   * startup, during any event (in a slot), or at regular time points
   * using WTimer. This is the normal %Wt event loop.
   *
   * In some cases, one may want to modify the user interface from a
   * second thread, outside the event loop, or from socket events
   * (using the WSocketNotifier). While this may be worked around by
   * the WTimer, in some cases, there are bandwidth and processing
   * overheads associated which may be unnecessary, and which create a
   * trade-off with time resolution of the updates.
   *
   * When <i>enabled</i> is true, this enables "server push" (what is
   * called 'comet' in AJAX terminology). Widgets may then be
   * modified, created or deleted outside of the event loop (e.g. in
   * response to execution of another thread), and these changes are
   * propagated by calling triggerUpdate().
   *
   * An example of how to modify the widget tree outside the event loop
   * and propagate changes is:
   * \code
   * // You need to have a reference to the application whose state you are about to manipulate.
   * // You should prevent the application from being deleted somehow, before you could grab the application lock.
   * Wt::WApplication *app = ...;
   *
   * {
   *   // Grab the application lock. It is a scoped lock.
   *   Wt::WApplication::UpdateLock lock = app->getUpdateLock();
   *
   *   // We now have exclusive access to the application: we can safely modify the widget tree for example.
   *   app->root()->addWidget(new Wt::WText("Something happened!"));
   *
   *   // Push the changes to the browser
   *   app->triggerUpdate();
   * }
   * \endcode
   *
   * \note This works only if JavaScript is available on the client.
   *
   * \sa triggerUpdate()
   */
  void enableUpdates(bool enabled = true);

  /*! \brief Returns whether server-initiated updates are enabled.
   *
   * True if server-initiated updates were enabled by a previous call to
   * enableUpdates().
   */
  bool updatesEnabled() const { return serverPush_; }

  /*! \brief Propagate server-initiated updates.
   *
   * Propagate changes made to the user interface outside of the main
   * event loop. This is only possible after a call to
   * enableUpdates(), and must be done while holding the UpdateLock
   * (or from within a socket event, see WSocketNotifier).
   *
   * \sa enableUpdates(), getUpdateLock()
   */
  void triggerUpdate();

  /*! \brief A synchronisation lock for manipulating and updating the
   *         application and its widgets outside of the event loop.
   *
   * You need to get this lock only when you want to manipulate
   * widgets outside of the event loop. Inside the event loop, this
   * lock is already held by the library itself.
   *
   * \sa getUpdateLock();
   */
  class WT_API UpdateLock {
  public:
    /*! \brief Copy constructor.
     *
     * By copying the lock, the lock is transferred. The original
     * object becomes empty, and its destructor has no effect of
     * releasing the lock.
     */
    UpdateLock(const UpdateLock&);

    /*! \brief Releases and destroys the scope dependent lock
     */
    ~UpdateLock();

  private:
    UpdateLock(WApplication& app);

    mutable UpdateLockImpl *impl_;

    friend class WApplication;
  };

  /*! \brief Grabs and returns the lock for manipulating widgets outside
   *         the event loop.
   *
   * You need to keep this lock in scope while manipulating widgets
   * outside of the event loop. In normal cases, inside the %Wt event loop,
   * you do not need to care about it.
   *
   * \sa enableUpdates(), triggerUpdate()
   */
  UpdateLock getUpdateLock();
#endif // WT_TARGET_JAVA

  /*! \brief Attach an auxiliary thread to this application.
   *
   * In a multi-threaded environment, WApplication::instance() uses
   * thread-local data to retrieve the application object that
   * corresponds to the session currently being handled by the
   * thread. This is set automatically by the library whenever an
   * event is delivered to the application, or when you use the
   * getUpdateLock() to modify the application from an auxiliary
   * thread outside the normal event loop.
   *
   * When you want to manipulate the widget tree inside the main event
   * loop, but from within an auxiliary thread, then you cannot use
   * the getUpdateLock() since this will create an immediate dead
   * lock. Instead, you may attach the auxiliary thread to the
   * application, by calling this method from the auxiliary thread,
   * and in this way you can modify the application from within that
   * thread without needing the update lock.
   */
  void attachThread();

  /*! \brief Executes some JavaScript code.
   *
   * This method may be used to call some custom JavaScript code as
   * part of an event response.
   *
   * This function does not wait until the JavaScript is run, but
   * returns immediately. The JavaScript will be run after the normal
   * event handling, unless <i>afterLoaded</i> is set to false.
   */
  void doJavaScript(const std::string& javascript, bool afterLoaded = true);

  void addAutoJavaScript(const std::string& javascript);

  void declareJavaScriptFunction(const std::string& name,
				 const std::string& function);

  /*! \brief Load a JavaScript library.
   *
   * Attempt to load a JavaScript library. When <i>symbol</i> is not
   * empty, the library is only inserted in the page if the given
   * symbol is not yet defined.
   *
   * Returns true when the library was not yet loaded for this
   * application.
   *
   * JavaScript libraries may be loaded at any point in time. They
   * will be loaded before evaluating the normal event handling code,
   * but after javaScript that has been executed using
   * doJavaScript(..., false).
   */
  bool require(const std::string& uri,
	       const std::string& symbol = std::string());

  /*! \brief Process UI events.
   *
   * You may call this method during a long operation to:
   * <ul>
   *   <li>Propagate widget changes to the client.</li>
   *   <li>Process UI events.</li>
   * </ul>
   *
   * This method starts a recursive event loop, blocking the current
   * thread, and resumes when all events have been processed.
   */
  void processEvents();

  /*! \brief Read a configuration property.
   *
   * Tries to read a configured value for the property
   * <i>name</i>. The method returns whether a value is defined for
   * the property, and sets it to <i>value</i>.
   */
  static bool readConfigurationProperty(const std::string& name,
					std::string& value);
#ifdef WT_TARGET_JAVA
  static std::string *readConfigurationProperty(const std::string& name,
						const std::string& value);
#endif // WT_TARGET_JAVA

  /*! \brief Set the Ajax communication method.
   *
   * You may change the communication method only from within the
   * application constructor.
   *
   * The default method depends on your application deployment
   * type.
   *
   * \if cpp
   * For \link WServer::Application plain\endlink applications, \link
   * WApplication::XMLHttpRequest XMLHttpRequest\endlink is used,
   * while for \link Wt::WidgetSet widget set\endlink
   * applications, \link WApplication::DynamicScriptTag
   * DynamicScriptTag\endlink is used. The latter is less efficient,
   * but has the benefit to allow serving the application from a
   * different server than the page that hosts the embedded widgets.
   * \elseif java
   * For plain applications, \link WApplication::XMLHttpRequest 
   * XMLHttpRequest\endlink is used, while for WidgetSet 
   * applications, \link WApplication::DynamicScriptTag
   * DynamicScriptTag\endlink is used. The latter is less efficient,
   * but has the benefit to allow serving the application from a
   * different server than the page that hosts the embedded widgets.
   * \endif
   */
  void setAjaxMethod(AjaxMethod method);

  /*! \brief Returns the Ajax communication method.
   *
   * \sa setAjaxMethod()
   */
  AjaxMethod ajaxMethod() const { return ajaxMethod_; }

  /*
   * The instance name of the JavaScript class that encapsulates all
   * JavaScript methods specific to this application instance.
   */
  std::string javaScriptClass() { return javaScriptClass_; }

  /*
   * The DOM root object. This contains not only the application root but
   * also other invisible objects (timers, dialog covers, ...).
   */
  WContainerWidget *domRoot() const { return domRoot_; }

  /*
   * A phony DOM root object, used to logically contain all widgets bound
   * in widgetset mode.
   */
  WContainerWidget *domRoot2() const { return domRoot2_; }

  /*
   * Encode an object to a string, to make it referencable from JavaScript.
   * Currently only used to encode the drag object in drag & drop.
   *
   * FIXME: provide a way to remove the encoding!
   *
   * \see decodeObject()
   */
  std::string encodeObject(WObject *object);

  /*
   * Decode an object.
   *
   * \see encodeObject()
   */
  WObject *decodeObject(const std::string& objectId) const;

  /*
   * Check if the url needs to be modified when it should be a
   * url relative to the application path, but the query info will make
   * it point to some internal path.
   */
  std::string fixRelativeUrl(const std::string& url) const;

  /*
   * Returns the value of the 'resources' property set in the configuration
   * file.
   */
  static std::string resourcesUrl();

  /*! \brief Initialize the application, post-construction.
   *
   * This method is invoked by the %Wt library after construction of a
   * new application. You may reimplement this method to do additional
   * initialization that is not possible from the constructor
   * (e.g. which uses virtual methods).
   */
  virtual void initialize();

  /*! \brief Finalize the application, pre-destruction.
   *
   * This method is invoked by the %Wt library before destruction of a
   * new application. You may reimplement this method to do additional
   * finalization that is not possible from the destructor (e.g. which
   * uses virtual methods).
   */
  virtual void finalize();

  /*! \brief Change the threshold for two-phase rendering.
   *
   * This changes the threshold for the communication size (in bytes) to
   * render invisible changes in one go. If the bandwidth for
   * rendering the invisible changes exceed the threshold, they will
   * be fetched in a second communication, after the visible changes
   * have been rendered.
   *
   * The value is a trade-off: setting it smaller will always use
   * two-phase rendering, increasing the total render time but
   * reducing the latency for the visible changes. Setting it too
   * large will increase the latency to render the visible changes,
   * since first also all invisible changes need to be computed and
   * received in the browser.
   *
   * \if cpp
   * The initial value is read from the configuration file, see \ref
   * config_general.
   * \endif
   */
  void setTwoPhaseRenderingThreshold(int size);

  /*! \brief Set a new cookie.
   *
   * Use cookies to transfer information across different sessions
   * (e.g. a user name). In a subsequent session you will be able to
   * read this cookie using WEnvironment::getCookie(). You cannot use
   * a cookie to store information in the current session.
   *
   * The name must be a valid cookie name (of type 'token': no special
   * characters or separators, see RFC2616 page 16). The value may be
   * anything. Specify the maximum age (in seconds) after which the
   * client must discard the cookie. To delete a cookie, use a value of '0'.
   *
   * By default the cookie only applies to the current path on the
   * current domain. To set a proper value for domain, see also RFC2109.
   *
   * \note %Wt provides session tracking automatically (and may be configured
   *       to use a cookie for this). You only need this method if you want
   *       to remember information <i>across</i> sessions.
   *
   * \sa WEnvironment::supportsCookies(), WEnvironment::getCookie()
   */
  void setCookie(const std::string& name, const std::string& value,
		 int maxAge, const std::string& domain = "",
		 const std::string& path = "");

  /*! \brief Returns the current maximum size of a request to the application.
   *
   * \if cpp
   * The maximum request size is configured in the configuration file,
   * see \ref config_general.
   * \endif
   *
   * \sa requestTooLarge()
   */
  int maximumRequestSize() const;

  /*! \brief Add an entry to the application log.
   *
   * Starts a new log entry of the given <i>type</i> in the %Wt
   * application log file. This method returns a stream-like object to
   * which the message may be streamed.
   * 
   * \if cpp
   * A typical usage would be:
   * \code
   *  wApp->log("notice") << "User " << userName << " logged in successfully.";
   * \endcode
   *
   * This would create a log entry that looks like:
   * \verbatim
[2008-Jul-13 14:01:17.817348] 16879 [/app.wt Z2gCmSxIGjLHD73L] [notice] "User bart logged in successfully." \endverbatim
   * \endif
   *
   * \if cpp
   * \sa \ref config_general
   * \endif
   */
  WLogEntry log(const std::string& type) const;

  /*! \brief Set the loading indicator.
   *
   * The loading indicator is shown to indicate that a response from
   * the server is pending or JavaScript is being evaluated.
   *
   * The default loading indicator is a WDefaultLoadingIndicator.
   *
   * When setting a new loading indicator, the previous one is
   * deleted.
   */
  void setLoadingIndicator(WLoadingIndicator *indicator);

  /*! \brief Returns the loading indicator.
   *
   * \sa setLoadingIndicator()
   */
  WLoadingIndicator *loadingIndicator() const { return loadingIndicator_; }

  /*
   * A url to a resource that provides a one pixel gif. This is sometimes
   * useful for CSS hackery to make IE behave.
   */
  std::string onePixelGifUrl();

  /*
   * The doctype used to deliver the application.
   */
  std::string docType() const;

  /*! \brief Quit the application.
   *
   * The method returns immediately, but has as effect that the
   * application will be terminated after the current event is
   * completed.
   *
   * The current widget tree (including any modifications still
   * pending and applied during the current event handling) will still
   * be rendered, after which the application is terminated.
   *
   * You might want to make sure no more events can be received from
   * the user, by not having anything clickable, for example by
   * displaying only text. Even better is to redirect() the user to
   * another, static, page in conjunction with quit().
   *
   * \sa redirect()
   */
  void quit();

  /*! \brief Returns whether the application is quited.
   *
   * \sa quit()
   */
  bool isQuited() const { return quited_; }

  /*! \brief %Signal which indicates that too a large POST was received.
   *
   * The integer parameter is the request that was received in bytes.
   */
  Signal<int>& requestTooLarge() { return requestTooLarge_; }

  /*
   * For persistent sessions only: redirect to another session.
   */
  void redirectToSession(const std::string& sessionId);

  /*
   * For persistent sessions only: return whether the persistent session
   * is connected to a browser.
   */
  bool isConnected() const { return connected_; }

  /*
   * Set a style class to the entire page &lt;body&gt;.
   * (should be public API ?)
   */
  void setBodyClass(const std::string& styleClass);

  /*
   * Set a style class to the entire page.
   * (should be public API ?)
   */
  void setHtmlClass(const std::string& styleClass);

  /*
   * Returns whether debug was configured.
   * (should be public API ?)
   */
  bool debug() const;

protected:
  /*! \brief Notifies an event to the application.
   *
   * This method is called by the event loop for propagating an event
   * to the application. It provides a single point of entry for
   * events to the application.
   *
   * You may want to reimplement this method for two reasons:
   * - for having a single point for exception handling (you may want to catch
   *   specialized exceptions at specific points, but general (fatal)
   *   exceptions may be caught here.
   * - you want to manage resource usage during requests. For example, at
   *   the end of request handling, you want to return a database session
   *   back to the pool.
   *
   * In either case, you will need to call the base class
   * implementation WApplication::notify(), as otherwise no events
   * will be delivered to your application.
   *
   * \if cpp
   * For example, the following shows a generic template for reimplementhing
   * this method.
   *
   * \code
   * MyApplication::notify(const WEvent& e)
   * {
   *    // Grab resources for during request handling
   *    try {
   *      WApplication::notify(e);
   *    } catch (MyException& exception) {
   *      // handle this exception in a central place
   *    }
   *    // Free resources used during request handling
   * }
   * \endcode
   *
   * Note that any uncaught exception throw during event handling
   * terminates the session.
   * \endif
   */
  virtual void notify(const WEvent& e);

  /*! \brief Returns whether a widget is exposed in the interface.
   *
   * The default implementation simply returns true, unless a modal
   * dialog is active, in which case it returns true only for widgets
   * that are inside the dialog.
   *
   * You may want to reimplement this method if you wish to disallow
   * events from certain widgets even when they are inserted in the
   * widget hierachy.
   */
  virtual bool isExposed(WWidget *w) const;

  /*! \brief Progress to an Ajax-enabled user interface.
   *
   * This method is called when the progressive bootstrap method is used, and
   * support for AJAX has been detected. The default behavior will propagate
   * the WWidget::enableAjax() method through the widget hierarchy.
   *
   * You may want to reimplement this method if you want to make
   * changes to the user-interface when AJAX is enabled. You should
   * always call the base implementation.
   *
   * \sa WWidget::enableAjax()
   */
  virtual void enableAjax();

  void exposeOnly(WWidget *w);

private:
  Signal<int> requestTooLarge_;

  /*
   * Struct to handle library loading, which delays subsequent JS calls
   * until the library has effectively been loaded.
   */
  struct ScriptLibrary {
    ScriptLibrary(const std::string& uri, const std::string& symbol);

    std::string uri, symbol, beforeLoadJS;
    bool operator< (const ScriptLibrary& other) const;
    bool operator== (const ScriptLibrary& other) const;
  };

  typedef std::map<std::string, EventSignalBase *> SignalMap;
  typedef std::map<std::string, WResource *> ResourceMap;
  typedef std::map<std::string, WObject *> ObjectMap;

  /*
   * Basic application stuff
   */
  WebSession            *session_;     // session owning this application
  WString                title_;
  bool                   titleChanged_;
  WContainerWidget      *widgetRoot_;  // widgets in main DOM root
  WContainerWidget      *domRoot_;     // main DOM root
  WContainerWidget      *domRoot2_;    // other virtual root for WidgetSet mode
  WContainerWidget      *timerRoot_;   // timers in main DOM root
  WCssStyleSheet         styleSheet_;  // internal style sheet
  WLocalizedStrings     *localizedStrings_;
  WT_LOCALE              locale_;
  std::string            oldInternalPath_, newInternalPath_;
  Signal<std::string>    internalPathChanged_;
  bool                   internalPathIsChanged_;
#ifndef WT_TARGET_JAVA
  bool                   serverPush_;
  boost::pool<boost::default_user_allocator_new_delete> *eventSignalPool_;
  bool			 shouldTriggerUpdate_;
#endif // WT_TARGET_JAVA
  std::string            javaScriptClass_;
  AjaxMethod             ajaxMethod_;
  WContainerWidget      *dialogCover_;
  bool                   quited_;
  std::string            onePixelGifUrl_;
  bool                   rshLoaded_;
  WWidget               *exposedOnly_;
  WLoadingIndicator     *loadingIndicator_;
  WWidget               *loadingIndicatorWidget_;
  bool                   connected_;
  std::string            htmlClass_, bodyClass_;
  bool                   bodyHtmlClassChanged_;
  bool                   enableAjax_;

  std::vector<ScriptLibrary> scriptLibraries_;
  int                        scriptLibrariesAdded_;

  std::vector<std::string> styleSheets_;
  int                      styleSheetsAdded_;

  SignalMap   exposedSignals_;   // signals that may be accessed
  ResourceMap exposedResources_; // resources that may be accessed
  ObjectMap   encodedObjects_;   // objects encoded for internal purposes
                                 // like 'virtual pointers' (see D&D)

  bool exposeSignals_;           // if we are currently exposing signals
                                 // (see WViewWidget)

  std::string afterLoadJavaScript_, beforeLoadJavaScript_,
    newBeforeLoadJavaScript_, autoJavaScript_;
  bool autoJavaScriptChanged_;

  EventSignal<WResponseEvent> *javaScriptResponse_;
  EventSignal<> *showLoadingIndicator_, *hideLoadingIndicator_;

  WContainerWidget *timerRoot() const { return timerRoot_; }
  WContainerWidget *dialogCover(bool create = true);

  WEnvironment&     env();       // short-hand for session_->env()

  /*
   * Functions for exposed signals, resources, and objects
   */
  void              addExposedSignal(EventSignalBase* signal);
  void              removeExposedSignal(EventSignalBase* signal);
  EventSignalBase  *decodeExposedSignal(const std::string& signalName) const;
  EventSignalBase  *decodeExposedSignal(const std::string& objectId,
				       const std::string& name);
  const SignalMap&  exposedSignals() const;

  std::string       addExposedResource(WResource *resource);
  void              removeExposedResource(WResource *resource);
  WResource        *decodeExposedResource(const std::string& resourceName)
    const;

  /*
   * Methods for application state handling
   */
  bool loadRsh();
  void changeInternalPath(const std::string& path);

#ifdef WT_WITH_OLD_INTERNALPATH_API
  bool oldInternalPathAPI() const;
#endif // WT_WITH_OLD_INTERNALPATH_API

  void handleJavaScriptResponse(WResponseEvent event);

  /*
   * Methods for accessing javaScript, which may have erase-on-read
   * semantics
   */
  std::string afterLoadJavaScript();
  std::string beforeLoadJavaScript();
  std::string newBeforeLoadJavaScript();

  /*
   * Methods for accessing exposeSignals_
   */
  void setExposeSignals(bool how) { exposeSignals_ = how; }
  bool exposeSignals() const { return exposeSignals_; }

  static bool pathMatches(const std::string& path, const std::string& query);

  /*
   * Methods for audio handling
   */
  SoundManager *getSoundManager();
  SoundManager *soundManager_;

  friend class WebRenderer;
  friend class WebSession;
  friend class WebController;
  friend class EventSignalBase;
  friend class JavaScriptEvent;
  friend class UpdateLockImpl;
  friend class WWidget;
  friend class WMenu;
  friend class WTimer;
  friend class WResource;
  friend class WFileUpload;
  friend class WInteractWidget;
  friend class WServerPushResource;
  friend class WViewWidget;
  friend class WDialog;
  friend class WSound;
  friend class Ext::Dialog;
  friend class Ext::MessageBox;
};

#ifdef WIN32
  #ifdef WTHTTP_STATIC
    #define WTCONNECTOR_API
  #else
    #ifdef wthttp_EXPORTS
      #define WTCONNECTOR_API __declspec(dllexport)
    #else
      #define WTCONNECTOR_API __declspec(dllimport)
    #endif
  #endif
#else
  #define WTCONNECTOR_API
#endif

#ifndef WT_TARGET_JAVA
#ifdef DOXYGEN_ONLY
/*! \brief Runs the %Wt application server.
 *
 * This function runs the application server, and should be called
 * only once (e.g. from within your main function).
 *
 * The <i>createApplication</i> argument is a function pointer to
 * create new application instances for each new user surfing to your application.
 *
 * When using the built-in httpd, the implementation listens for POSIX
 * termination signals (or console CTRL-C) event. You can use the
 * WServer class for more flexible control on starting and stopping
 * the server.
 *
 * \relates WServer
 * \sa WApplication
 */
extern int WRun(int argc, char** argv,
		ApplicationCreator createApplication = 0);
#else // DOXYGEN_ONLY
extern int WTCONNECTOR_API WRun(int argc, char** argv,
				ApplicationCreator createApplication = 0);

#endif // DOXYGEN_ONLY
#endif // WT_TARGET_JAVA

/*! \def wApp
 *  \brief Global constant for accessing the application instance.
 *
 * This is equivalent to WApplication::instance()
 *
 * \relates WApplication
 */
#define wApp Wt::WApplication::instance()

}

#endif // WAPPLICATION_
