Wt 3.1.10
Classes | Public Types | Public Member Functions | Static Public Member Functions | Protected Member Functions | Related Functions
Wt::WApplication Class Reference

Represents an application instance for a single session. More...

#include <Wt/WApplication>

Inheritance diagram for Wt::WApplication:
Inheritance graph
[legend]

List of all members.

Classes

class  UpdateLock
 A RAII lock for manipulating and updating the application and its widgets outside of the event loop. More...

Public Types

enum  AjaxMethod { XMLHttpRequest, DynamicScriptTag }
 Enumeration that indicates the method for dynamic (AJAX-alike) updates ((deprecated). More...
typedef Wt::ApplicationCreator ApplicationCreator
 Typedef for a function that creates WApplication objects.

Public Member Functions

 WApplication (const WEnvironment &environment)
 Creates a new application instance.
 ~WApplication ()
 Destructor.
const WEnvironmentenvironment () const
 Returns the environment information.
WContainerWidgetroot () const
 Returns the root container.
WWidgetfindWidget (const std::string &name)
 Finds a widget by name.
void setTitle (const WString &title)
 Sets the window title.
const WStringtitle () const
 Returns the window title.
const WStringcloseMessage () const
 Returns the close message.
WLocalizedStringslocalizedStrings ()
 Returns the resource object that provides localized strings.
void setLocalizedStrings (WLocalizedStrings *stringResolver)
 Sets the resource object that provides localized strings.
WMessageResourceBundlemessageResourceBundle () const
 Returns the message resource bundle.
void setLocale (const std::string &locale)
 Changes the locale.
std::string locale () const
 Returns the current locale.
virtual void refresh ()
 Refreshes the application.
void bindWidget (WWidget *widget, const std::string &domId)
 Binds a top-level widget for a WidgetSet deployment.
std::string sessionId () const
 Returns the unique identifier for the current session.
void changeSessionId ()
 Changes the session id.
void processEvents ()
 Processes UI events.
void setAjaxMethod (AjaxMethod method)
 Sets the Ajax communication method (deprecated).
AjaxMethod ajaxMethod () const
 Returns the Ajax communication method (deprecated).
virtual void initialize ()
 Initializes the application, post-construction.
virtual void finalize ()
 Finalizes the application, pre-destruction.
void setTwoPhaseRenderingThreshold (int size)
 Changes the threshold for two-phase rendering.
void setCookie (const std::string &name, const std::string &value, int maxAge, const std::string &domain="", const std::string &path="")
 Sets a new cookie.
void addMetaHeader (const std::string &name, const WString &content, const std::string &lang="")
 Adds an HTML meta header.
void addMetaHeader (MetaHeaderType type, const std::string &name, const WString &content, const std::string &lang="")
 Adds an HTML meta header.
void removeMetaHeader (MetaHeaderType type, const std::string &name="")
 Removes one or all meta headers.
WLogEntry log (const std::string &type) const
 Adds an entry to the application log.
void setLoadingIndicator (WLoadingIndicator *indicator)
 Sets the loading indicator.
WLoadingIndicatorloadingIndicator () const
 Returns the loading indicator.
void quit ()
 Quits the application.
bool isQuited () const
 Returns whether the application is quited.
::int64_t maximumRequestSize () const
 Returns the current maximum size of a request to the application.
Signal< int > & requestTooLarge ()
 Signal which indicates that too a large request was received.
void setConfirmCloseMessage (const WString &message)
 Sets the message for the user to confirm closing of the application window/tab.
Style sheets and CSS
WCssStyleSheetstyleSheet ()
 Returns a reference to the inline style sheet.
void useStyleSheet (const std::string &url)
 Adds an external style sheet.
void useStyleSheet (const std::string &url, const std::string &condition, const std::string &media="all")
 Adds an external style sheet, constrained with conditions.
void setCssTheme (const std::string &theme)
 Sets the theme.
std::string cssTheme () const
 Returns the theme.
void setLayoutDirection (LayoutDirection direction)
 Sets the layout direction.
LayoutDirection layoutDirection () const
 Returns the layout direction.
void setBodyClass (const std::string &styleClass)
 Sets a style class to the entire page <body>.
std::string bodyClass () const
 Returns the style class set for the entire page <body>.
void setHtmlClass (const std::string &styleClass)
 Sets a style class to the entire page <html>.
std::string htmlClass () const
 Returns the style class set for the entire page <html>.
URLs and internal paths
std::string url () const
 Returns a URL for the current session.
std::string makeAbsoluteUrl (const std::string &url) const
 Makes an absolute URL.
std::string resolveRelativeUrl (const std::string &url) const
 "Resolves" a relative URL taking into account internal paths.
std::string bookmarkUrl () const
 Returns a bookmarkable URL for the current internal path.
std::string bookmarkUrl (const std::string &internalPath) const
 Returns a bookmarkable URL for a given internal path.
void setInternalPath (const std::string &path, bool emitChange=false)
 Changes the internal path.
std::string internalPath () const
 Returns the current internal path.
std::string internalPathNextPart (const std::string &path) const
 Returns a part of the current internal path.
std::string internalSubPath (const std::string &path) const
 Returns a URL for the current session.
bool internalPathMatches (const std::string &path) const
 Checks if the internal path matches a given path.
Signal< std::string > & internalPathChanged ()
 Signal which indicates that the user changes the internal path.
void redirect (const std::string &url)
 Redirects the application to another location.
Manipulation outside the main event loop
void enableUpdates (bool enabled=true)
 Enables server-initiated updates.
bool updatesEnabled () const
 Returns whether server-initiated updates are enabled.
void triggerUpdate ()
 Propagates server-initiated updates.
UpdateLock getUpdateLock ()
 Grabs and returns the lock for manipulating widgets outside the event loop (deprecated).
void attachThread (bool attach=true)
 Attach an auxiliary thread to this application.
Invoking JavaScript or including scripts
void doJavaScript (const std::string &javascript, bool afterLoaded=true)
 Executes some JavaScript code.
void addAutoJavaScript (const std::string &javascript)
 Adds JavaScript statements that should be run continuously.
void declareJavaScriptFunction (const std::string &name, const std::string &function)
 Declares an application-wide JavaScript function.
bool require (const std::string &url, const std::string &symbol=std::string())
 Loads a JavaScript library.
void setJavaScriptClass (const std::string &className)
 Sets the name of the application JavaScript class.
std::string javaScriptClass ()
 Returns the name of the application JavaScript class.
Global keyboard and mouse events
EventSignal< WKeyEvent > & globalKeyWentDown ()
 Event signal emitted when a keyboard key is pushed down.
EventSignal< WKeyEvent > & globalKeyPressed ()
 Event signal emitted when a "character" was entered.
EventSignal< WKeyEvent > & globalKeyWentUp ()
 Event signal emitted when a keyboard key is released.
EventSignalglobalEnterPressed ()
 Event signal emitted when enter was pressed.
EventSignalglobalEscapePressed ()
 Event signal emitted when escape was pressed.

Static Public Member Functions

static WApplicationinstance ()
 Returns the current application instance.
static std::string resourcesUrl ()
 Returns the URL at which the resources are deployed.
static std::string appRoot ()
 Returns the approot special property.
static bool readConfigurationProperty (const std::string &name, std::string &value)
 Reads a configuration property.

Protected Member Functions

virtual void notify (const WEvent &e)
 Notifies an event to the application.
virtual bool isExposed (WWidget *w) const
 Returns whether a widget is exposed in the interface.
virtual void enableAjax ()
 Progresses to an Ajax-enabled user interface.
virtual void unload ()
 Handles a browser unload event.

Related Functions

(Note that these are not member functions.)

typedef boost::function
< WApplication *(const
WEnvironment &)> 
ApplicationCreator
 Typedef for a function that creates WApplication objects.

Detailed Description

Represents an application instance for a single session.

Each user session of your application has a corresponding WApplication instance. You need to create a new instance and return it as the result of the callback function passed to WRun(). The instance is the main entry point to session information, and holds a reference to the root() of the widget tree.

The recipe for a Wt web application, which allocates new WApplication instances for every user visiting the application is thus:

 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;
 }

Throughout the session, 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 after the user has closed the window, 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.

The WApplication object provides access to session-wide settings, including:


Member Typedef Documentation

typedef Wt::ApplicationCreator Wt::WApplication::ApplicationCreator

Typedef for a function that creates WApplication objects.

See also:
WRun()

Member Enumeration Documentation

Enumeration that indicates the method for dynamic (AJAX-alike) updates ((deprecated).

See also:
setAjaxMethod()
Enumerator:
XMLHttpRequest 

Using the XMLHttpRequest object (real AJAX)

DynamicScriptTag 

Using dynamic script tags (for cross-domain AJAX)


Constructor & Destructor Documentation

Wt::WApplication::WApplication ( const WEnvironment environment)

Creates a new application instance.

The environment provides information on the initial request, user agent, and deployment-related information.

Wt::WApplication::~WApplication ( )

Destructor.

The destructor deletes the root() container, and as a consequence the entire widget tree.


Member Function Documentation

void Wt::WApplication::addAutoJavaScript ( const std::string &  javascript)

Adds JavaScript statements that should be run continuously.

This is an internal method.

It is used by for example layout managers to adjust the layout whenever the DOM tree is manipulated.

See also:
doJavaScript()
void Wt::WApplication::addMetaHeader ( const std::string &  name,
const WString content,
const std::string &  lang = "" 
)

Adds an HTML meta header.

A meta header can only be added in the following situations:

  • when a plain HTML session is used (including when the user agent is a bot), you can add meta headers at any time.
  • or, when progressive bootstrap is used, you can set meta headers for any type of session, from within the application constructor (which corresponds to the initial request).
  • but never for a Wt::WidgetSet mode application since then the application is hosted within a foreign HTML page.

When a header was previously set for the same name, its contents is replaced.

These situations coincide with WEnvironment::ajax() returning false (see environment()).

void Wt::WApplication::addMetaHeader ( MetaHeaderType  type,
const std::string &  name,
const WString content,
const std::string &  lang = "" 
)

Adds an HTML meta header.

This overloaded method allows to define both "name" meta headers, relating to document properties as well as "http-equiv" meta headers, which define HTTP headers.

See also:
removeMetaHeader()
AjaxMethod Wt::WApplication::ajaxMethod ( ) const

Returns the Ajax communication method (deprecated).

See also:
setAjaxMethod()
std::string Wt::WApplication::appRoot ( ) [static]

Returns the approot special property.

This returns the "approot" property, with a trailing slash added to the end if it was not yet present.

The property "approot" was introduced as a generalization of the working directory for the location of files that do not need to be served over http to the client, but are required by the program to run properly. Typically, these are message resource bundles (xml), CSV files, database files (e.g. SQLite files for Wt::Dbo), ...

Some connectors do not allow you to control what the current working directory (CWD) is set to (fcgi, isapi). Instead of referring to files assuming a sensible CWD, it is therefore better to refer to them relative to the application root.

The approot property is special in the sense that it can be set implicitly by the connector (see the connector documentation for more info). If it was not set by the connector, it can be set as a normal property in the configuration file (the default wt_config.xml describes how to set properties). If the property is not set at all, it is assumed that the approot is CWD and this function will return an empty string.

Usage example:

 messageResourceBundle().use(appRoot() + "text");
 messageResourceBundle().use(appRoot() + "charts");

 Wt::Dbo::backend::Sqlite3 sqlite3_(approot() + "planner.db");
See also:
WServer::appRoot()
void Wt::WApplication::attachThread ( bool  attach = true)

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 UpdateLock 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 UpdateLock 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.

Calling attachThread() with attach = false, detaches the current thread.

void Wt::WApplication::bindWidget ( WWidget widget,
const std::string &  domId 
)

Binds a top-level widget for a WidgetSet deployment.

This method binds a widget to an existing element with DOM id domId on the page. The element type should correspond with the widget type (e.g. it should be a <div> for a WContainerWidget, or a <table> for a WTable).

See also:
root()
Wt::WidgetSet
std::string Wt::WApplication::bodyClass ( ) const

Returns the style class set for the entire page <body>.

See also:
setBodyClass()
std::string Wt::WApplication::bookmarkUrl ( ) const

Returns a bookmarkable URL for the current internal path.

Is equivalent to bookmarkUrl(internalPath()), see bookmarkUrl(const std::string&) const.

To obtain a URL that is refers to the current session of the application, use url() instead.

See also:
url(), bookmarkUrl(const std::string&) const
std::string Wt::WApplication::bookmarkUrl ( const std::string &  internalPath) const

Returns a bookmarkable URL for a given internal path.

Returns the (relative) URL for this application that includes the internal path internalPath, usable across sessions.

The returned URL concatenates the internal path to the application base URL, and when no JavaScript is available and URL rewriting is used for session-tracking, a session Id is appended to reuse an existing session if available.

See also 10.1 Session management (wt_config.xml) for configuring the session-tracking method.

For the built-in httpd, when the application is deployed at a folder (ending with '/'), only an exact matching path is routed to the application (this can be changed since Wt 3.1.9, see 9.2 Built-in httpd ), making clean URLs impossible. Returned URLs then include a "?_=" encoding for the internal path.

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 internalPath (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.

See also:
url(), bookmarkUrl()
void Wt::WApplication::changeSessionId ( )

Changes the session id.

To mitigate session ID fixation attacks, you should use this method to change the session ID to a new random value after a user has authenticated himself.

See also:
sessionId()
std::string Wt::WApplication::cssTheme ( ) const

Returns the theme.

See also:
setCssTheme()
void Wt::WApplication::declareJavaScriptFunction ( const std::string &  name,
const std::string &  function 
)

Declares an application-wide JavaScript function.

This is an internal method.

void Wt::WApplication::doJavaScript ( const std::string &  javascript,
bool  afterLoaded = true 
)

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 afterLoaded is set to false.

See also:
addAutoJavaScript(), declareJavaScriptFunction()
void Wt::WApplication::enableAjax ( ) [protected, virtual]

Progresses 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.

See also:
WWidget::enableAjax()
void Wt::WApplication::enableUpdates ( bool  enabled = true)

Enables 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. 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 enabled 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().

There are two ways for safely manipulating a session's UI, with respect to thread-safety and application life-time (the library can decide to terminate an application if it lost connectivity with the browser).

WServer::post()

The easiest and less error-prone solution is to post an event, represented by a function/method call, to a session using WServer::post().

The method is non-blocking: it returns immediately, avoiding dead-lock scenarios. The function is called from within a thread of the server's thread pool, and not if the session has been or is being terminated. The function is called in the context of the targeted application session, and with exclusive access to the session.

WApplication::UpdateLock

A more direct approach is to grab the application's update lock and manipulate the application's state directly from another thread.

At any time, the application may be deleted (e.g. because of a time out or because the user closes the application window). You should thus make sure you do no longer reference an application after it has been deleted. When Wt decides to delete an application, it first runs WApplication::finalize() and then invokes the destructor. While doing this, any other thread trying to grab the update lock will unblock, but the lock will return false. You should therefore always check whether the lock is valid.

An example of how to modify the widget tree outside the event loop and propagate changes is:

 // 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);

   if (lock) {
     // 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();
   }
 }
Note:
This works only if JavaScript is available on the client.
See also:
triggerUpdate()
const WEnvironment & Wt::WApplication::environment ( ) const

Returns the environment information.

This method returns the environment object that was used when constructing the application. The environment provides information on the initial request, user agent, and deployment-related information.

See also:
url(), sessionId()
void Wt::WApplication::finalize ( ) [virtual]

Finalizes 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).

WWidget * Wt::WApplication::findWidget ( const std::string &  name)

Finds a widget by name.

This finds a widget in the application's widget hierarchy. It does not only consider widgets in the root(), but also widgets that are placed outside this root, such as in dialogs, or other "roots" such as all the bound widgets in a widgetset application.

See also:
WWidget::setObjectName(), WWidget::find()
WApplication::UpdateLock Wt::WApplication::getUpdateLock ( )

Grabs and returns the lock for manipulating widgets outside the event loop (deprecated).

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.

See also:
enableUpdates(), triggerUpdate()
Deprecated:
Use the RAII-style UpdateLock(WApplication *) constructor instead.
EventSignal & Wt::WApplication::globalEnterPressed ( )

Event signal emitted when enter was pressed.

The application receives key events when no widget currently has focus. Otherwise, key events are handled by the widget in focus, and its ancestors.

See also:
See WInteractWidget::enterPressed()
EventSignal & Wt::WApplication::globalEscapePressed ( )

Event signal emitted when escape was pressed.

The application receives key events when no widget currently has focus. Otherwise, key events are handled by the widget in focus, and its ancestors.

See also:
See WInteractWidget::escapePressed()
EventSignal< WKeyEvent > & Wt::WApplication::globalKeyPressed ( )

Event signal emitted when a "character" was entered.

The application receives key events when no widget currently has focus. Otherwise, key events are handled by the widget in focus, and its ancestors.

See also:
See WInteractWidget::keyPressed()
EventSignal< WKeyEvent > & Wt::WApplication::globalKeyWentDown ( )

Event signal emitted when a keyboard key is pushed down.

The application receives key events when no widget currently has focus. Otherwise, key events are handled by the widget in focus, and its ancestors.

See also:
See WInteractWidget::keyWentDown()
EventSignal< WKeyEvent > & Wt::WApplication::globalKeyWentUp ( )

Event signal emitted when a keyboard key is released.

The application receives key events when no widget currently has focus. Otherwise, key events are handled by the widget in focus, and its ancestors.

See also:
See WInteractWidget::keyWentUp()
std::string Wt::WApplication::htmlClass ( ) const

Returns the style class set for the entire page <html>.

See also:
setHtmlClass()
void Wt::WApplication::initialize ( ) [virtual]

Initializes 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).

WApplication * Wt::WApplication::instance ( ) [static]

Returns the current application instance.

This is the same as the global define #wApp. In a multi-threaded server, this method uses thread-specific storage to fetch the current session.

std::string Wt::WApplication::internalPath ( ) const

Returns the current internal path.

When the application is just created, this is equal to WEnvironment::internalPath().

See also:
setInternalPath(), internalPathNextPart(), internalPathMatches()
Signal< std::string > & Wt::WApplication::internalPathChanged ( )

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.

See also:
setInternalPath()
bool Wt::WApplication::internalPathMatches ( const std::string &  path) const

Checks if the internal path matches a given path.

Returns whether the current internalPath() starts with path (or is equal to path). 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 path using setInternalPath() if you do not intend to remove sub paths when the current internal path already matches path.

The path must start with a '/'.

See also:
setInternalPath(), internalPath()
std::string Wt::WApplication::internalPathNextPart ( const std::string &  path) const

Returns a part of the current internal path.

This is a convenience method which returns the next folder in the internal path, after the given path.

For example, when the current internal path is "/project/z3cbc/details", this method returns "details" when called with "/project/z3cbc/" as path argument.

The path must start with a '/', and internalPathMatches() should evaluate to true for the given path. If not, an empty string is returned and an error message is logged.

See also:
internalPath(), internalPathChanged()
std::string Wt::WApplication::internalSubPath ( const std::string &  path) const

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

 http://www.mydomain.com/stuff/app.wt 

this method would return "/stuff/app.wt?wtd=AbCdEf". Additional query parameters can be appended in the form of "&param1=value&param2=value".

To obtain a URL that is suitable for bookmarking the current application state, to be used across sessions, use bookmarkUrl() instead.

See also:
redirect(), WEnvironment::hostName(), WEnvironment::urlScheme()
bookmarkUrl()
bool Wt::WApplication::isExposed ( WWidget w) const [protected, virtual]

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.

bool Wt::WApplication::isQuited ( ) const

Returns whether the application is quited.

See also:
quit()
std::string Wt::WApplication::javaScriptClass ( )

Returns the name of the application JavaScript class.

This JavaScript class encapsulates all JavaScript methods specific to this application instance. The method is foreseen to allow multiple applications to run simultaneously on the same page in Wt::WidgtSet mode, without interfering.

LayoutDirection Wt::WApplication::layoutDirection ( ) const

Returns the layout direction.

See also:
setLayoutDirection()
WLoadingIndicator* Wt::WApplication::loadingIndicator ( ) const

Returns the loading indicator.

See also:
setLoadingIndicator()
std::string Wt::WApplication::locale ( ) const

Returns the current locale.

See also:
setLocale(const std::string&)
WLocalizedStrings * Wt::WApplication::localizedStrings ( )

Returns the resource object that provides localized strings.

The default value is a WMessageResourceBundle instance, which uses XML files to resolve localized strings, but you can set a custom class using setLocalizedStrings().

WString::tr() is used to create localized strings, whose localized translation is looked up through this object, using a key.

See also:
WString::tr(), messageResourceBundle()
WLogEntry Wt::WApplication::log ( const std::string &  type) const

Adds an entry to the application log.

Starts a new log entry of the given type in the Wt application log file. This method returns a stream-like object to which the message may be streamed.

A typical usage would be:

  wApp->log("notice") << "User " << userName << " logged in successfully.";

This would create a log entry that looks like:

[2008-Jul-13 14:01:17.817348] 16879 [/app.wt Z2gCmSxIGjLHD73L] [notice] "User bart logged in successfully." 
See also:
10.2 General application settings (wt_config.xml)
std::string Wt::WApplication::makeAbsoluteUrl ( const std::string &  url) const

Makes an absolute URL.

Returns an absolute URL for a given (relative url) by including the schema, hostname, and deployment path.

If url is "", then the absolute base URL is returned. This is the absolute URL at which the application is deployed, up to the last '/'.

int64_t Wt::WApplication::maximumRequestSize ( ) const

Returns the current maximum size of a request to the application.

The maximum request size is configured in the configuration file, see 10.2 General application settings (wt_config.xml).

See also:
requestTooLarge()
WMessageResourceBundle & Wt::WApplication::messageResourceBundle ( ) const

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.

See also:
WString::tr(const char *key)
void Wt::WApplication::notify ( const WEvent e) [protected, virtual]

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, besides the application constructor.

You may want to reimplement this method for two reasons:

  • for having a single point for exception handling: while you may want to catch recoverable exceptions in a more appropriate place, general (usually fatal) exceptions may be caught here. You will in probably also want to catch the same exceptions in the application constructor in the same way.
  • 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. Since notify() is also used for rendering right after the application is created, this will also clean up resources after application construction.

In either case, you will need to call the base class implementation of notify(), as otherwise no events will be delivered to your application.

The following shows a generic template for reimplementhing this method for both managing request resources and generic exception handling.

 MyApplication::notify(const WEvent& event)
 {
    // Grab resources for during request handling
    try {
      WApplication::notify(event);
    } catch (MyException& exception) {
      // handle this exception in a central place
    }
    // Free resources used during request handling
 }

Note that any uncaught exception throw during event handling terminates the session.

void Wt::WApplication::processEvents ( )

Processes UI events.

You may call this method during a long operation to:

  • propagate widget changes to the client.
  • process UI events.

This method starts a recursive event loop, blocking the current thread, and resumes when all pending user interface events have been processed.

Because a thread is blocked, this may affect your application scalability.

void Wt::WApplication::quit ( )

Quits 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().

See also:
redirect()
bool Wt::WApplication::readConfigurationProperty ( const std::string &  name,
std::string &  value 
) [static]

Reads a configuration property.

Tries to read a configured value for the property name. The method returns whether a value is defined for the property, and sets it to value.

See also:
WServer::readConfigurationProperty()
void Wt::WApplication::redirect ( const std::string &  url)

Redirects the application to another location.

The client will be redirected to a new location identified by url. 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 Wt::WApplication::refresh ( ) [virtual]

Refreshes the application.

This lets the application to refresh its data, including strings 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, if this can be caught within the current session.

The reload button may only be caught when Wt is configured so that reload should not spawn a new session. When URL rewriting is used for session tracking, this will cause an ugly session ID to be added to the URL. See 10.1 Session management (wt_config.xml) for configuring the reload behavior ("<reload-is-new-session>").

See also:
WWidget::refresh()
void Wt::WApplication::removeMetaHeader ( MetaHeaderType  type,
const std::string &  name = "" 
)

Removes one or all meta headers.

Removes the meta header with given type and name (if it is present). If name is empty, all meta headers of the given type are removed.

See also:
addMetaHeader()
Signal<int>& Wt::WApplication::requestTooLarge ( )

Signal which indicates that too a large request was received.

The integer parameter is the request size that was received in bytes.

bool Wt::WApplication::require ( const std::string &  url,
const std::string &  symbol = std::string() 
)

Loads a JavaScript library.

Loads a JavaScript library located at the URL url. Wt keeps track of libraries (with the same URL) that already have been loaded, and will load a library only once. In addition, you may provide a symbol which if already defined will also indicate that the library was already loaded (possibly outside of Wt when in WidgetSet mode).

This method returns true only when the library is loaded for the first time.

JavaScript libraries may be loaded at any point in time. Any JavaScript code is deferred until the library is loaded, except for JavaScript that was defined to load before, passing false as second parameter to doJavaScript().

std::string Wt::WApplication::resolveRelativeUrl ( const std::string &  url) const

"Resolves" a relative URL taking into account internal paths.

Using HTML5 History API or in a plain HTML session (without ugly internal paths), the internal path is present as a full part of the URL. This has a consequence that relative URLs, if not dealt with, would be resolved against the last 'folder' name of the internal path, rather than against the application deployment path (which is what you probably want).

When using a widgetset mode deployment, or when configuring a baseURL property in the configuration, this method will make an absolute URL so that the property is fetched from the right server.

Otherwise, this method will fixup a relative URL so that it resolves correctly against the base path of an application. This does not necessarily mean that the URL is resolved into an absolute URL. In fact, Wt will simply prepend a sequence of "../" path elements to correct for the internal path. When passed an absolute URL (i.e. starting with '/'), the url is returned unchanged.

For URLs passed to the Wt API (and of which the library knows it is represents a URL) this method is called internally by the library. But it may be useful for URLs which are set e.g. inside a WTemplate.

std::string Wt::WApplication::resourcesUrl ( ) [static]

Returns the URL at which the resources are deployed.

This returns the value of the 'resources' property set in the configuration file.

WContainerWidget* Wt::WApplication::root ( ) const

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.

The root() widget is only defined when the application manages the entire window. When deployed as a WidgetSet application, there is no root() container, and 0 is returned. Instead, use bindWidget() to bind one or more root widgets to existing HTML <div> (or other) elements on the page.

std::string Wt::WApplication::sessionId ( ) const

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.

void Wt::WApplication::setAjaxMethod ( AjaxMethod  method)

Sets the Ajax communication method (deprecated).

This method has no effect.

Since Wt 3.1.8, a communication method that works is detected at run time. For widget set mode, cross-domain Ajax is chosen if available.

Deprecated:
this setting is no longer needed.
void Wt::WApplication::setBodyClass ( const std::string &  styleClass)

Sets a style class to the entire page <body>.

See also:
setHtmlClass()
void Wt::WApplication::setConfirmCloseMessage ( const WString message)

Sets the message for the user to confirm closing of the application window/tab.

If the message is empty, then the user may navigate away from the page without confirmation.

Otherwise the user will be prompted with a browser-specific dialog asking him to confirm leaving the page. This message is added to the page.

See also:
unload()
void Wt::WApplication::setCookie ( const std::string &  name,
const std::string &  value,
int  maxAge,
const std::string &  domain = "",
const std::string &  path = "" 
)

Sets 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 to use cookies yourself if you want to remember information across sessions.
See also:
WEnvironment::supportsCookies(), WEnvironment::getCookie()
void Wt::WApplication::setCssTheme ( const std::string &  theme)

Sets the theme.

The theme provides the look and feel of several built-in widgets, using CSS style rules. Rules for each theme are defined in the resources/themes/theme/ folder.

The default theme is "default". When setting "", the external style sheets related to the theme are not loaded.

void Wt::WApplication::setHtmlClass ( const std::string &  styleClass)

Sets a style class to the entire page <html>.

See also:
setBodyClass()
void Wt::WApplication::setInternalPath ( const std::string &  path,
bool  emitChange = false 
)

Changes 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:

 http://www.mydomain.com/stuff/app.wt

for which an internalPath "/project/z3cbc/details/" is set, the two forms for the application URL are:

  • in an AJAX session (HTML5):
     http://www.mydomain.com/stuff/app.wt/project/z3cbc/details/
    
  • in an AJAX session (HTML4):
     http://www.mydomain.com/stuff/app.wt#/project/z3cbc/details/
    
  • in a plain HTML session:
     http://www.mydomain.com/stuff/app.wt/project/z3cbc/details/
    

Note, since Wt 3.1.9, the actual form of the URL no longer affects relative URL resolution, since now Wt includes an HTML meta base tag which points to the deployment path, regardless of the current internal path. This does break deployments behind a reverse proxy which changes paths.

For the built-in httpd, when the application is deployed at a folder (ending with '/'), only an exact matching path is routed to the application (this can be changed since Wt 3.1.9, see 9.2 Built-in httpd ), making clean URLs impossible. Returned URLs then include a "?_=" encoding for the internal path:

 http://www.mydomain.com/stuff/?_=/project/z3cbc/details/

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 emitChange is true, this signal is also emitted by setting the path.

A url that includes the internal path may be obtained using bookmarkUrl().

The internalPath 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.

See also:
bookmarkUrl(), internalPath(), internalPathChanged()
void Wt::WApplication::setJavaScriptClass ( const std::string &  className)

Sets the name of the application JavaScript class.

This should be called right after construction of the application, and changing the JavaScript class is only supported for WidgetSet mode applications. The className should be a valid JavaScript identifier, and should also be unique in a single page.

void Wt::WApplication::setLayoutDirection ( LayoutDirection  direction)

Sets the layout direction.

The default direction is LeftToRight.

This sets the language text direction, which by itself sets the default text alignment and reverse the column orders of <table> elements.

In addition, Wt will take this setting into account in WTextEdit, WTableView and WTreeView (so that columns are reverted), and swap the behaviour of WWidget::setFloatSide() and WWidget::setOffsets() for RightToLeft languages. Note that CSS settings themselves are not affected by this setting, and thus for example "float: right" will move a box to the right, irrespective of the layout direction.

The library sets "Wt-ltr" or "Wt-rtl" as style classes for the document body. You may use this if to override certain style rules for a Right-to-Left document.

For example:

 body.Wt-ltr .sidebar { float: right; }
 body.Wt-rtl .sidebar { float: left; }
Note:
The layout direction can be set only at application startup and does not have the effect of rerendering the entire UI.
void Wt::WApplication::setLoadingIndicator ( WLoadingIndicator indicator)

Sets 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 Wt::WApplication::setLocale ( const std::string &  locale)

Changes the locale.

The locale is used by the localized strings resource to resolve localized strings.

By passing an empty locale, the default locale is chosen.

When the locale is changed, refresh() is called, which will resolve the strings of the current user-interface in the new locale.

At construction, the locale is copied from the environment (WEnvironment::locale()), and this is the locale that was configured by the user in his browser preferences, and passed using an HTTP request header.

See also:
localizedStrings(), WString::tr()
void Wt::WApplication::setLocalizedStrings ( WLocalizedStrings stringResolver)

Sets the resource object that provides localized strings.

The translator resolves localized strings within the current application locale.

The previous resource is deleted, and ownership of the new resource passes to the application.

See also:
localizedStrings(), WString::tr(const char *key)
void Wt::WApplication::setTitle ( const WString title)

Sets the window title.

Sets the browser window title to title.

The default title is "".

See also:
title()
void Wt::WApplication::setTwoPhaseRenderingThreshold ( int  size)

Changes the threshold for two-phase rendering.

This changes the threshold for the size of a JavaScript response (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.

The initial value is read from the configuration file, see 10.2 General application settings (wt_config.xml).

WCssStyleSheet& Wt::WApplication::styleSheet ( )

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.

It is usually preferable to use external stylesheets (and consider more accessible). Still, the internal stylesheet has as benefit that style rules may be dynamically updated, and it is easier to manage logistically.

See also:
useStyleSheet()
WWidget::setStyleClass()
const WString& Wt::WApplication::title ( ) const

Returns the window title.

See also:
setTitle(const WString&)
void Wt::WApplication::triggerUpdate ( )

Propagates server-initiated updates.

This propagate changes made to the user interface outside of the main event loop, e.g. from another thread or from within WServer::post(). This call only has an effect after updates have been enabled (from within the normal event loop), using enableUpdates().

See also:
enableUpdates()
void Wt::WApplication::unload ( ) [protected, virtual]

Handles a browser unload event.

The browser unloads the application when the user navigates away or when he closes the window or tab.

When reload-is-new-session is set to true, then the default implementation of this method terminates this session by calling quit(), otherwise the session is scheduled to expire within seconds (since it may be a refresh).

You may want to reimplement this if you want to keep the application running until it times out (as was the behaviour before Wt 3.1.6).

bool Wt::WApplication::updatesEnabled ( ) const

Returns whether server-initiated updates are enabled.

See also:
enableUpdates()
std::string Wt::WApplication::url ( ) const

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

 http://www.mydomain.com/stuff/app.wt 

this method would return "/stuff/app.wt?wtd=AbCdEf". Additional query parameters can be appended in the form of "&param1=value&param2=value".

To obtain a URL that is suitable for bookmarking the current application state, to be used across sessions, use bookmarkUrl() instead.

See also:
redirect(), WEnvironment::hostName(), WEnvironment::urlScheme()
bookmarkUrl()
void Wt::WApplication::useStyleSheet ( const std::string &  url)

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 url 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.

See also:
styleSheet(), useStyleSheet(const std::string&, const std::string&)
WWidget::setStyleClass()
void Wt::WApplication::useStyleSheet ( const std::string &  url,
const std::string &  condition,
const std::string &  media = "all" 
)

Adds an external style sheet, constrained with conditions.

If not empty, condition 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 (since these are in fact interpreted server-side instead of client-side). 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 media indicates the CSS media to which this stylesheet applies. This may be a comma separated list of media. The default value is "all" indicating all media.

The url indicates a relative or absolute URL to the stylesheet.

See also:
useStyleSheet()

Friends And Related Function Documentation

typedef boost::function<WApplication* (const WEnvironment&)> ApplicationCreator [related]

Typedef for a function that creates WApplication objects.

See also:
WRun()
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator

Generated on Wed Jul 27 2011 for the C++ Web Toolkit (Wt) by doxygen 1.7.4