Web Tools (for use with Emscripten)

D3 Data Visualization Tools

Animations

Manage animations on a web site.

To build an animation, you must provide a function to be run repeatedly. When Start() is triggered, the function will be called 60 time per second (or as close as possible), until Stop() is caled.

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2018

namespace emp

If we are in emscripten, make sure to include the header.

namespace web
class Animate
#include <Animate.hpp>

An object that, when active, repeatedly calls a function as fast as possible, to a maximum of 60 frames per second.

Parameters to the animation function can be:

  • double (representing time since the last frame)

  • a const reference to the animation object itself

  • nothing

Control methods: void Start() void Stop() void Step() void ToggleActive()

Access methods: bool GetActive() const bool GetDoStep() const double GetStartTime() const double GetPrevTime() const double GetCurTime() const double GetStepTime() const double GetRunTime() const int GetFrameCount() const

Config methods: void SetCallback(const std::function<void(const Animate &)> & fun) void SetCallback(const std::function<void(double)> & fun) void SetCallback(const std::function<void()> & fun)

Public Functions

Animate()

Setup an Animate object to call an anim_fun as fast as possible, at most 60 times a second. Call virtual function DoFrame() if no other functon is provided (which can be overridden if you derive a new class from Animate)

template<typename ...W_TYPES>
Animate(const anim_fun_t &fun, W_TYPES&... targets)

Construct an Animate object with the function to run each animation step and zero or more UI elements that should be updated after each frame.

template<typename ...W_TYPES>
Animate(const std::function<void(double)> &fun, W_TYPES&... targets, )
template<typename ...W_TYPES>
Animate(const std::function<void()> &funW_TYPES&... targets, )
~Animate()
Animate(const Animate&) = delete

Do not copy animations directly.

Animate &operator=(const Animate&) = delete
void Start()

Start this animation running.

void Stop()

Halt this animation for now.

void Step()

Take a single step in this animation.

void ToggleActive()

Toggle whether this animation is running or paused.

bool GetActive() const

Determine if this animation is currently running.

bool GetDoStep() const

Determine if this animation is currently in the process of running a single step.

double GetStartTime() const

Return the time point that this animation started MOST RECENTLY.

double GetPrevTime() const

Determine the time point when this animation last updated a frame.

double GetCurTime() const

Get the current time of the animation.

double GetStepTime() const

Determine how long the last step between frames took.

double GetRunTime() const

Determine the total amount of time that this animation has run.

int GetFrameCount() const

Determine how many total frames have existed thus far in this animation.

void SetCallback(const anim_fun_t &fun)

Set a new function for this animation to call when running that takes a const reference to the Animation object as an argument.

void SetCallback(const std::function<void(double)> &fun)

Set a new function for this animation to call when running that takes the amount of time since the last frame (a double) as an argument.

void SetCallback(const std::function<void()> &fun)

Set a new function for this animation to call when running that takes no arguments.

Button GetToggleButton(const std::string &but_name, const std::string &start_label = "Start", const std::string &stop_label = "Stop")

Get a toggle button that will start/stop this animation.

Parameters
  • but_name: The HTML identifier used for this button.

  • start_label: The name on the button when it will start the animation (default=”Start”)

  • stop_label: The name on the button when it will halt the animation (default=”Stop”)

Button GetStepButton(const std::string &but_name, const std::string &label = "Step")

Get a step button that will advance this animation one frame.

Parameters
  • but_name: The HTML identifier used for this button.

  • label: The name shown on the button.

Protected Types

using anim_fun_t = std::function<void(const Animate&)>

The full version of the animate function takes a const reference to the animate object.

Protected Functions

void LoadTargets()
template<typename ...T>
void LoadTargets(const web::Widget &target1, const T&... other_targets)
void AdvanceFrame()
void DoFrame()

DoFrame() is called by default if no animation function is provided. As such, an animation can be built by deriving a class from Animate and overriding this function.

Protected Attributes

anim_fun_t anim_fun

Function to repeatedly run for animation.

emp::vector<web::Widget> targets

What widgets should be refreshed after each frame?

bool active

Is this animation currently running?

bool do_step

Should this animation take just a single step?

size_t callback_id

Intenral ID for javascript to call back AdvanceFrame()

double start_time

At what time did this animation most recently start?

double prev_time

What was the time point of the previous frame?

double cur_time

What time did the current frame start?

double run_time

How much run time has accumulated?

int frame_count

How many animation frames have gone by?

Button toggle_but

A button to start/stop this animation.

Button step_but

A button to advance this animation one step.

Attributes

An Attributes class for tracking non-style features about HTML objects.

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2017

namespace emp

If we are in emscripten, make sure to include the header.

namespace web
class Attributes
#include <Attributes.hpp>

Maintains a map of attribute names to values for use in JavaScript Closely related to Style.h, which is for CSS-values.

Public Functions

Attributes()
Attributes(const Attributes&) = default
Attributes &operator=(const Attributes&) = default
int GetSize() const

Return a count of the number of attributes that have been set.

Attributes &DoSet(const std::string &in_set, const std::string &in_val)
Attributes &DoAddAttr(const std::string in_attr, const std::string &in_val)

Append a new value to an existing attribute

Parameters
  • in_attr: attribute name

  • in_val: attribute value to be added

std::string GetAttrValue(const std::string &in_set)
template<typename SET_TYPE>
Attributes &Set(const std::string &s, SET_TYPE v)

Record that attribute “a” is set to value “v” (converted to string) and return this object.

Attributes &Insert(const Attributes &in_attr)

Set all values from in_attr here as well. Return this object.

bool Has(const std::string &setting) const

Return true/false based on whether “setting” has been given a value in this Attributes obj.

const std::string &Get(const std::string &setting) const

Return the (string) value of “setting” that has been recorded in this Attributes obj.

const std::map<std::string, std::string> &GetMap() const
void Remove(const std::string &setting)
void Clear()

Remove all setting values.

void Apply(const std::string &widget_id)

Apply ALL of the Attribute’s settings to dom element “widget_id”.

void Apply(const std::string &widget_id, const std::string &setting)

Apply only a SPECIFIC attributes setting from the setting library to widget_id.

operator bool() const

Convert to true if there are any setting, false otherwise.

Public Static Functions

void Apply(const std::string &widget_id, const std::string &setting, const std::string &value)

Apply onlay a SPECIFIC attributes setting with a specifid value!

Private Members

std::map<std::string, std::string> settings

Buttons

Create/control an HTML button and call a specified function when that button is clicked.

Use example:

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2018.

emp::web::Button my_button(MyFun, “Button Name”, “html_id”);

Where my_button is the C++ object linking to the button, MyFun is the function you want to call on clicks, “Button Name” is the label on the button itself, and “html_id” is the optional id you want it to use in the HTML code (otherwise it will generate a unique name on its own.)

Member functions to set state: Button & SetCallback(const std::function<void()> & in_callback) Button & SetLabel(const std::string & in_label) Button & SetAutofocus(bool in_af) Button & SetDisabled(bool in_dis)

Retriving current state: const std::string & GetLabel() const bool HasAutofocus() const bool IsDisabled() const

namespace emp

If we are in emscripten, make sure to include the header.

namespace web
class Button : public internal::WidgetFacet<Button>
#include <Button.hpp>

Create or control an HTML Button object that you can manipulate and update as needed.

Public Types

using INFO_TYPE = ButtonInfo

Public Functions

Button(const std::function<void()> &in_cbconst std::string &in_label, const std::string &in_id = "", )

Create a new button.

Parameters
  • in_cb: The function to call when the button is clicked.

  • in_label: The label that should appear on the button.

  • in_id: The HTML ID to use for this button (leave blank for auto-generated)

Button(const Button &in)

Link to an existing button.

Button(const Widget &in)
Button()
~Button()
Button &SetCallback(const std::function<void()> &in_cb)

Set a new callback function to trigger when the button is clicked.

Button &SetLabel(const std::string &in_label)

Set a new label to appear on this Button.

Button &SetAutofocus(bool _in = true)

Setup this button to have autofocus (or remove it!)

Button &SetDisabled(bool _in = true)

Setup this button to be disabled (or re-enable it!)

const std::string &GetLabel() const

Get the current label on this button.

bool HasAutofocus() const

Determine if this button currently has autofocus.

bool IsDisabled() const

Determine if this button is currently disabled.

Protected Functions

ButtonInfo *Info()
const ButtonInfo *Info() const
Button(ButtonInfo *in_info)

Friends

friend class ButtonInfo

Canvas

Manage an HTML canvas object.

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2018

namespace emp

If we are in emscripten, make sure to include the header.

namespace web
class Canvas : public internal::WidgetFacet<Canvas>
#include <Canvas.hpp>

Manage an HTML Canvas object.

Public Types

using INFO_TYPE = CanvasInfo

Public Functions

Canvas(double w, double h, const std::string &in_id = "")

Create a new canvas with the specified size and optional HTML identifier.

Canvas(const Canvas &in)

Link to an existing canvas.

Canvas(const Widget &in)
Canvas()
~Canvas()
double GetWidth() const

Get the pixel width of this Canvas.

double GetHeight() const

Get the pixel height of this Canvas.

void SetWidth(double w)

Set a new width for this Canvas.

void SetHeight(double h)

Set a new height for this Canvas.

void SetSize(double w, double h)

Set Canvas size.

template<typename ...Ts>
Canvas &Circle(Point center, double _r, Ts&&... vals)

Add a Circle to this canvas; provide constructor for the CanvasCircle with a position and radius as well as optional face color, line color, and line width.

template<typename ...Ts>
Canvas &Circle(double _x, double _y, double _r, Ts&&... vals)
template<typename ...Ts>
Canvas &Rect(Point corner, double w, double h, Ts&&... vals)

Add a Rectangle to this canvas at x,y with width w and heigh h. Optional face color and line color.

template<typename ...Ts>
Canvas &Rect(double x, double y, double w, double h, Ts&&... vals)
template<typename ...Ts>
Canvas &Image(const emp::RawImage &image, Point corner, Ts&&... vals)

Add an Image to this canvas at x,y with width w and heigh h.

template<typename ...Ts>
Canvas &Image(const emp::RawImage &image, double x, double y, Ts&&... vals)
template<typename ...Ts>
Canvas &Line(double x1, double y1, double x2, double y2, Ts&&... vals)

Add a Line from x1,y1 to x2,y2. Optional face color and line color.

template<typename ...Ts>
Canvas &Line(emp::Point p1, emp::Point p2, Ts&&... vals)
template<typename ...Ts>
Canvas &MultiLine(emp::Point p1, const emp::vector<emp::Point> &points, Ts&&... vals)

Add a Line from x1,y1 to x2,y2. Optional face color and line color.

template<typename ...Ts>
Canvas &Text(emp::Point p, Ts&&... vals)

Add a string to this canvas at x,y with specified text. Optional face color and line color.

template<typename ...Ts>
Canvas &Text(double x, double y, Ts&&... vals)
template<typename ...Ts>
Canvas &CenterText(emp::Point p, Ts&&... vals)

Add a string to this canvas centered at x,y with specified text. Optional face color and line color.

template<typename ...Ts>
Canvas &CenterText(double x, double y, Ts&&... vals)
Canvas &Font(const std::string font)

Update the default font for text.

Canvas &Draw(const emp::Circle &circle, const std::string &fc = "", const std::string &lc = "")

Draw a circle onto this canvas.

Canvas &Draw(const CanvasShape &shape)

Draw an arbitrary shape onto this canvas.

Canvas &StrokeColor(std::string c)

Change the default stroke color.

Canvas &Rotate(double angle)

Rotate the entire canvas.

Canvas &Clear()

Clear everything off of this canvas.

Canvas &Clear(const std::string &bg_color)

Clear to a specific background color.

void DownloadPNG() const

Download a PNG image of a canvas.

void DownloadPNG(const std::string &fname) const

Download a PNG image of a canvas.

void SavePNG(const std::string &fname) const

Save a PNG image of a canvas with node.js.

Protected Functions

CanvasInfo *Info()
const CanvasInfo *Info() const
Canvas(CanvasInfo *in_info)

Friends

friend class CanvasInfo

Canvas Utilities

Various versions of the Draw() function to draw images onto a canvas.

Each version of

Draw() takes a canvas widget and some form of data to be drawn on the widget, such as a circle, a bit matrix, or a geometric surface.
Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2018

namespace emp

If we are in emscripten, make sure to include the header.

namespace web

Functions

void Draw(Canvas canvas, const emp::Circle &circle, const std::string &fill = "", const std::string &line = "")

Draw a Circle onto the canvas.

template<size_t COLS, size_t ROWS>
void Draw(Canvas canvas, const BitMatrix<COLS, ROWS> &matrix, double w, double h)

Draw a BitMatrix onto a canvas using black and white squares (can specify cell width and height)

template<typename ...BODY_TYPES>
void Draw(Canvas canvas, const Surface<BODY_TYPES...> &surface, const emp::vector<std::string> &color_map)

Draw a Surface, specifying the full colormap to be used. The surface has a range of circle bodies, each with a color id.

Parameters
  • canvas: The Canvas to draw on.

  • surface: A surface containing a set of shapes to draw.

  • color_map: Mapping of values to the colors with which they should be associated.

template<typename ...BODY_TYPES>
void Draw(Canvas canvas, const Surface<BODY_TYPES...> &surface, size_t num_colors)

Draw a Surface, just specifying the number of colors (and using a generated hue map). The surface has a range of circle bodies, each with a color id.

Parameters
  • canvas: The Canvas to draw on.

  • surface: A surface containing a set of shapes to draw.

  • num_colors: The number of distinct colors to use in visualization.

template<typename BODY_TYPE>
void Draw(Canvas canvas, const Surface2D<BODY_TYPE> &surface, const emp::vector<std::string> &color_map)

Draw a Surface2D, specifying the full colormap to be used. The surface has a range of circle bodies, each with a color id.

Parameters
  • canvas: The Canvas to draw on.

  • surface: A surface containing a set of shapes to draw.

  • color_map: Mapping of values to the colors with which they should be associated.

template<typename BODY_TYPE>
void Draw(Canvas canvas, const Surface2D<BODY_TYPE> &surface, size_t num_colors)

Draw a Surface2D, just specifying the number of colors (and using a generated hue map). The surface has a range of circle bodies, each with a color id.

Parameters
  • canvas: The Canvas to draw on.

  • surface: A surface containing a set of shapes to draw.

  • num_colors: The number of distinct colors to use in visualization.

void Draw(Canvas canvas, const emp::vector<emp::vector<size_t>> &grid, const emp::vector<std::string> &color_map, std::string line_color, double cell_width, double cell_height, double offset_x, double offset_y)

Draw a grid onto a canvas.

Parameters
  • canvas: The Canvas to draw on.

  • grid: A vector of vectors of color IDs.

  • color_map: Mapping of values to the colors with which they should be associated.

  • line_color: The background line color for the grid.

  • cell_width: How many pixels wide is each cell to draw?

  • cell_height: How many pixels tall is each cell to draw?

  • offset_x: How far should we shift the grid relative to the left side of the canvas?

  • offset_y: How far should we shift the grid relative to the top of the canvas?

void Draw(Canvas canvas, const emp::vector<emp::vector<size_t>> &grid, const emp::vector<std::string> &color_map, std::string line_color, double cell_w, double cell_h)

Draw a grid onto a canvas, but without offsets provided the grid is centered.

Parameters
  • canvas: The Canvas to draw on.

  • grid: A vector of vectors of color IDs.

  • color_map: Mapping of values to the colors with which they should be associated.

  • line_color: The background line color for the grid.

  • cell_w: How many pixels wide is each cell to draw?

  • cell_h: How many pixels tall is each cell to draw?

void Draw(Canvas canvas, const emp::vector<emp::vector<size_t>> &grid, const emp::vector<std::string> &color_map, std::string line_color = "black")

Draw a grid onto a canvas, but without cell size provided maximize to fill the canvas!

Parameters
  • canvas: The Canvas to draw on.

  • grid: A vector of vectors of color IDs.

  • color_map: Mapping of values to the colors with which they should be associated.

  • line_color: The background line color for the grid.

void Draw(Canvas canvas, const emp::vector<size_t> &grid, size_t grid_cols, const emp::vector<std::string> &color_map, std::string line_color, double cell_width, double cell_height, double offset_x, double offset_y)

Draw a vector onto a canvas as a grid.

Parameters
  • canvas: The Canvas to draw on.

  • grid: A vector of vectors of color IDs

  • grid_cols: Number of columns in the grid

  • color_map: Mapping of values to the colors with which they should be associated.

  • line_color: The background line color for the grid

  • cell_width: How many pixels wide is each cell to draw?

  • cell_height: How many pixels tall is each cell to draw?

  • offset_x: How far should we shift the grid relative to the left side of the canvas?

  • offset_y: How far should we shift the grid relative to the top of the canvas?

void Draw(Canvas canvas, const StateGrid &state_grid, const emp::vector<std::string> &color_map, std::string line_color = "black")

Draw a state grid onto a canvas.

Parameters
  • canvas: The Canvas to draw on.

  • state_grid: A StateGrid object.

  • color_map: Mapping of values to the colors with which they should be associated.

  • line_color: The background line color for the grid.

void DrawGridBG(Canvas canvas, size_t rows, size_t cols, const std::string &bg_color, const std::string &line_color)

Draw a grid as the background of a canvas. Since this is a BG, clear the canvas first.

Parameters
  • canvas: The Canvas to draw on.

  • rows: Number of rows to draw in the grid.

  • cols: Number of columns to draw in the grid.

  • bg_color: The background color for the grid.

  • line_color: The color of the liens on the grid.

template<typename CONTAINER_T, typename POINT_FUN_T, typename COLOR_FUN_T>
void DrawPoints(Canvas canvas, CONTAINER_T &&container, double radius, POINT_FUN_T &&point_fun, COLOR_FUN_T &&color_fun, const std::string &line_color = "black")

Canvas Actions

Define a base class for all actions that can be done to widgets, plus simple actions.

CanvasAction objects modify the appearance of a canvas and can be tracked to reconstruct the state of the canvas from scratch.

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2018

Other, more specific actions defined here are: CanvasStrokeColor CanvasRotate CanvasFont

See also CanvasShape.h for more actions.

namespace emp

If we are in emscripten, make sure to include the header.

namespace web
class CanvasAction
#include <CanvasAction.hpp>

Base class to maintain canvas actions.

Subclassed by emp::web::CanvasFont, emp::web::CanvasImage, emp::web::CanvasRotate, emp::web::CanvasShape, emp::web::CanvasStrokeColor

Public Functions

CanvasAction()
CanvasAction(const CanvasAction&)
~CanvasAction()
void Apply() = 0

Apply current action to emp_i.ctx.

CanvasAction *Clone() const = 0

Make a copy of the current action.

Protected Functions

void Fill(const std::string &style = "")

Helper function to set the fill status.

void Stroke(const std::string &style = "")

Helper function to set the stroke status.

void LineWidth(double line_width = 1.0)

Helper function to set the stroke status.

class CanvasFont : public emp::web::CanvasAction
#include <CanvasAction.hpp>

Change the default font to be used.

Public Functions

CanvasFont(const std::string &f)
void Apply()

Apply current action to emp_i.ctx.

CanvasAction *Clone() const

Make a copy of the current action.

Protected Attributes

std::string font
class CanvasImage : public emp::web::CanvasAction
#include <CanvasAction.hpp>

Change the default font to be used.

Public Functions

CanvasImage(const RawImage &raw_image, double _x = 0.0, double _y = 0.0, double _w = 0.0, double _h = 0.0)
CanvasImage(const RawImage &raw_image, Point _p, double _w = 0.0, double _h = 0.0)
CanvasImage(const std::string &url, double _x = 0.0, double _y = 0.0, double _w = 0.0, double _h = 0.0)
CanvasImage(const std::string &url, Point _p, double _w = 0.0, double _h = 0.0)
void Apply()

Apply current action to emp_i.ctx.

CanvasAction *Clone() const

Make a copy of the current action.

Protected Attributes

RawImage image
Point position
double width
double height
class CanvasRotate : public emp::web::CanvasAction
#include <CanvasAction.hpp>

Rotate the entire canvas for subsequent drawings.

Public Functions

CanvasRotate(double a)
void Apply()

Apply current action to emp_i.ctx.

CanvasAction *Clone() const

Make a copy of the current action.

Protected Attributes

double angle
class CanvasStrokeColor : public emp::web::CanvasAction
#include <CanvasAction.hpp>

Set the line color on subsequent draw-related actions.

Public Functions

CanvasStrokeColor(const std::string &c)
void Apply()

Apply current action to emp_i.ctx.

CanvasAction *Clone() const

Make a copy of the current action.

Protected Attributes

std::string color

Color to use.

Canvas Shapes

Define simple shapes to draw on a canvas.

Canvas shapes can be definied in detail, describing how they modify a canvas.

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2017

Other, more specific actions defined here are: CanvasCircle CanvasRect

namespace emp

If we are in emscripten, make sure to include the header.

namespace web
class CanvasCircle : public emp::web::CanvasShape
#include <CanvasShape.hpp>

Track a circle shape to be drawn on a canvas.

Public Functions

CanvasCircle(double _x, double _y, double _r, const std::string &fc = "", const std::string &lc = "", double lw = 1.0)
CanvasCircle(Point _p, double _r, const std::string &fc = "", const std::string &lc = "", double lw = 1.0)
CanvasCircle(emp::Circle circle, const std::string &fc = "", const std::string &lc = "", double lw = 1.0)
void Apply()

Apply current action to emp_i.ctx.

CanvasAction *Clone() const

Make a copy of the current action.

Private Members

double radius

Circle radius.

class CanvasClearRect : public emp::web::CanvasShape
#include <CanvasShape.hpp>

Clear a rectangular area in a canvas.

Public Functions

CanvasClearRect(Point _p, double _w, double _h)
void Apply()

Apply current action to emp_i.ctx.

CanvasAction *Clone() const

Make a copy of the current action.

Private Members

double w

Rectangle widgth.

double h

Rectangle height.

class CanvasLine : public emp::web::CanvasShape
#include <CanvasShape.hpp>

A line segment on the canvas.

Public Functions

CanvasLine(double _x1, double _y1, double _x2, double _y2, const std::string &lc = "", double lw = 1.0)

Y-position for second point of line segment.

CanvasLine(Point p1, Point p2, const std::string &lc = "", double lw = 1.0)
void Apply()

Apply current action to emp_i.ctx.

CanvasAction *Clone() const

Make a copy of the current action.

Private Members

double x2
double y2

X-position for second point of line segment.

class CanvasMultiLine : public emp::web::CanvasShape
#include <CanvasShape.hpp>

A whole series of line segments on the canvas. Currently not working…

Public Functions

CanvasMultiLine(double _x1, double _y1, const emp::vector<Point> &_points, const std::string &lc = "", double lw = 1.0)
CanvasMultiLine(Point p1, const emp::vector<Point> &_points, const std::string &lc = "", double lw = 1.0)
void Apply()

Apply current action to emp_i.ctx.

CanvasAction *Clone() const

Make a copy of the current action.

Private Members

emp::vector<Point> points
class CanvasPolygon : public emp::web::CanvasShape
#include <CanvasShape.hpp>

An arbitrary-sized polygon to be drawn on a canvas.

Public Functions

CanvasPolygon(const std::string &fc = "", const std::string &lc = "")
CanvasPolygon(const emp::vector<Point> &p, const std::string &fc = "", const std::string &lc = "")
CanvasPolygon(Point _p, const std::string &fc = "", const std::string &lc = "")
CanvasPolygon(double _x, double _y, const std::string &fc = "", const std::string &lc = "")
CanvasPolygon &AddPoint(double x, double y)
CanvasPolygon &AddPoint(Point p)
void Apply()

Apply current action to emp_i.ctx.

CanvasAction *Clone() const

Make a copy of the current action.

Private Members

emp::vector<Point> points

Series of points defining the perimiter of the Polygon.

class CanvasRect : public emp::web::CanvasShape
#include <CanvasShape.hpp>

Track a rectangle shape to be drawn on a canvas.

Public Functions

CanvasRect(Point _p, double _w, double _h, const std::string &fc = "", const std::string &lc = "")
CanvasRect(double _x, double _y, double _w, double _h, const std::string &fc = "", const std::string &lc = "")
void Apply()

Apply current action to emp_i.ctx.

CanvasAction *Clone() const

Make a copy of the current action.

Private Members

double w

Rectangle widgth.

double h

Rectangle height.

class CanvasShape : public emp::web::CanvasAction
#include <CanvasShape.hpp>

Define an arbitrary shape to draw on a canvas (base clase)

Subclassed by emp::web::CanvasCircle, emp::web::CanvasClearRect, emp::web::CanvasLine, emp::web::CanvasMultiLine, emp::web::CanvasPolygon, emp::web::CanvasRect, emp::web::CanvasText

Public Functions

CanvasShape(double _x, double _y, const std::string &fc = "", const std::string &lc = "", double lw = 1.0)
CanvasShape(Point _p, const std::string &fc = "", const std::string &lc = "", double lw = 1.0)
~CanvasShape()
void MoveTo(Point _p)

Shift the position of this shape to a point.

void MoveTo(double _x, double _y)

Shift the position of this shape to coordinates.

void SetLineWidth(double lw = 1.0)

Setup details needed before drawing lines.

void SetFillColor(const std::string &color)

Change the fill color of this shape.

void SetLineColor(const std::string &color)

Change the stroke color of this shape.

void ApplyColor()

Actually change the color on screen.

Protected Attributes

Point p

Anchor point for this shape.

std::string fill_color

Internal color to fill shape with.

std::string line_color

Border color for shape.

double line_width

How wide should lines be?

class CanvasText : public emp::web::CanvasShape
#include <CanvasShape.hpp>

Text to be written on a canvas.

Public Functions

CanvasText(Point p, const std::string &_text, const std::string &fc = "", const std::string &lc = "")
void Apply()

Apply current action to emp_i.ctx.

void Center(bool c = true)

Center this text.

bool GetCenter() const

Identify if text is centered.

CanvasAction *Clone() const

Make a copy of the current action.

Protected Attributes

std::string text

Specific text to be written.

bool center

Should this text be centered (or is anchor on left side)?

Color maps

Tools to dynamically build (and cache) color maps.

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2017

namespace emp

If we are in emscripten, make sure to include the header.

Functions

std::string ColorHSL(double h, double s, double l)

Generate a string to describe a JS color out of HSL values.

std::string ColorRGB(int r, int g, int b)

Generate a string to describe a JS color out of RGB values.

std::string ColorRGB(int r, int g, int b, double a)

Generate a string to describe a JS color with an alpha channel.

std::string ColorHSV(double h, double s, double v)

Generate a string to describe a JS color out of HSV values.

const emp::vector<std::string> &GetHueMap(size_t map_size, double min_h = 0.0, double max_h = 360.0, int s = 100, int l = 50)

Generate a vector of color strings with a specified range of hues, and fixed satuation and luminosity,

emp::vector<std::string> GetHSLMap(size_t map_size, double min_h = 0.0, double max_h = 360.0, int min_s = 100, int max_s = 100, int min_l = 50, int max_l = 50)

Generate a vector of color strings providing ranges of all of hue, satuation and luminosity.

Commands

A set of command-defining classes that can be fed into widgets using the << operator.

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2017

namespace emp

If we are in emscripten, make sure to include the header.

namespace web

Variables

const PrintStr endl ("<br>")

Pre-define emp::endl to insert a “<br>” and thus acting like a newline.

class Close : public WidgetCommand
#include <commands.hpp>

The Close command will prevent the specified widget from accepting further appends (and instead revert to trying parents)

Public Functions

Close(const std::string &id)
bool Trigger(internal::WidgetInfo &w) const override
const std::string &GetID() const

Private Members

std::string close_id
class PrintStr : public WidgetCommand
#include <commands.hpp>

The PrintStr command will print a pre-specified string to a widget.

Public Functions

PrintStr(const std::string &_s)
bool Trigger(internal::WidgetInfo &w) const override
const std::string &GetStr() const

Private Members

std::string str

Divs

Div Widgets maintain an ordered collection of other widgets in an HTML div.

When printed to the web page, these internal widgets are presented in order.

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2018

To create a Div:

emp::web::Div my_div(“name”);

To use a Div:

my_div << “Add this text!” << emp::web::Image(“my_image.png”) << “<br>”;

To register a Div in a Document:

my_doc << my_div;

Note

Formerly called Slate.h

namespace emp

If we are in emscripten, make sure to include the header.

namespace web
class Div : public internal::WidgetFacet<Div>
#include <Div.hpp>

A widget to track a div in an HTML file, and all of its contents.

Subclassed by emp::prefab::Card, emp::prefab::CommentBox, emp::prefab::ConfigPanel, emp::prefab::Modal, emp::prefab::ValueBox, emp::web::Document, emp::web::Element

Public Types

using INFO_TYPE = internal::DivInfo

Public Functions

Div(const std::string &in_name = "")
Div(const Div &in)
Div(const Widget &in)
~Div()
double ScrollTop() const

Where is the top of the scroll region?

Div &ScrollTop(double in_top)

Set the scroll position.

void Clear()

Clear the contents of this div.

void ClearChildren()

Remove all child widgets from this div.

bool HasChild(const Widget &test_child) const

Determine if a specified widget is internal to this one.

void Deactivate(bool top_level) override

Remove this widget from the current document.

Widget &Find(const std::string &test_name)

Get an internal widget to this div, by the specified name.

bool HasChild(const std::string &test_name) const

Determine if a specified widget is internal to this one.

emp::vector<Widget> &Children()

Get all direct child widgets to this div.

template<class ...T>
web::Animate &AddAnimation(const std::string &name, T&&... args)

Shortcut adder for animations.

web::Animate &Animate(const std::string &in_id)

Protected Functions

internal::DivInfo *Info()
const internal::DivInfo *Info() const
Div(internal::DivInfo *in_info)

Documents

Manage an entire document.

The Document class is built off of Div, but initializes the EMP web framework, if neeeded, and activates itself. It also provides quick ways to add and lookup widgets.

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2018

For example, you can use doc.AddButon(…) to add a new button to the document, where the … can be any of the mechanisms to build a new button. This technique works for any widget type.

You can also look up any widget by name. For example, if you previously created a Canvas widget with the HTML id “my_canvas”, you can look it up later by using doc.Canvas(“my_canvas”)

Defines

emp_main
namespace emp

If we are in emscripten, make sure to include the header.

namespace web
class Document : public emp::web::Div

Public Functions

Document(const std::string &doc_id)
~Document()
template<class ...T>
web::Button AddButton(T&&... args)
template<class ...T>
web::Canvas AddCanvas(T&&... args)
template<class ...T>
web::FileInput AddFileInput(T&&... args)
template<class ...T>
web::Image AddImage(T&&... args)
template<class ...T>
web::Selector AddSelector(T&&... args)
template<class ...T>
web::Div AddDiv(T&&... args)
template<class ...T>
web::Table AddTable(T&&... args)
template<class ...T>
web::Text AddText(T&&... args)
template<class ...T>
web::TextArea AddTextArea(T&&... args)
web::Button Button(const std::string &in_id)
web::Canvas Canvas(const std::string &in_id)
web::Element Element(const std::string &in_id)
web::FileInput FileInput(const std::string &in_id)
web::Input Input(const std::string &in_id)
web::Image Image(const std::string &in_id)
web::Selector Selector(const std::string &in_id)
web::Div Div(const std::string &in_id)
web::Table Table(const std::string &in_id)
web::Text Text(const std::string &in_id)
web::TextArea TextArea(const std::string &in_id)

Useful functions for emscripten

Specialized, useful function for Empirical.

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2017

Defines

AlertVar(VAR)
namespace emp

If we are in emscripten, make sure to include the header.

Functions

void DelayCall(const std::function<void()> &in_funint delay, )

Call a function after a specified amount of time.

void OnResize(const std::function<void()> &in_fun)

Provide a function to call whenever a window’s size changes (no arguments).

void OnResize(const std::function<void(int, int)> &in_fun)

Provide a function to call whenever a window’s size changes (new size as arguments)

double GetTime()

Get the current time, as provided by the web browser.

int GetWindowInnerWidth()

Determine with width of the current window.

int GetWindowInnerHeight()

Determine with height of the current window.

void SetBackgroundColor(const std::string color)

Set the background color of this web page.

void SetColor(const std::string color)
void SetCursor(const char *type)
void OpenWindow(const std::string &url)
std::string text2html(const std::string &text)
std::string GetElementAttribute(const std::string &id, const std::string &attribute)

Get the value of.

Parameters
  • attribute: in the element with

  • id: as its id.

Event Handling

Event handlers that use JQuery.

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2017

namespace emp

If we are in emscripten, make sure to include the header.

namespace web

Functions

template<typename FUN_TYPE>
void OnDocumentReady(FUN_TYPE &&fun)

Runs the specified function when the document is finished loading and being set up.

template<typename FUN_TYPE>
void OnDocumentLoad(FUN_TYPE &&fun)

Runs the specified function when the document is finished loading.

struct Event
#include <events.hpp>

Data common to all web events.

Subclassed by emp::web::KeyboardEvent, emp::web::MouseEvent, emp::web::WheelEvent

Public Functions

template<int ARG_ID>
void LoadFromArg()

Public Members

bool bubbles

Is this a bubbling event?

bool cancelable

Can the default action be prevented?

struct KeyboardEvent : public emp::web::Event
#include <events.hpp>

Keyboard-specific information about web events.

Public Functions

template<int ARG_ID>
void LoadFromArg()

Public Members

bool altKey

Was “ALT” key was pressed?

bool ctrlKey

Was “CTRL” key pressed?

bool metaKey

Was “META” key pressed?

bool shiftKey

Was “SHIFT” key pressed?

int charCode

Unicode character pressed.

int keyCode

Which key was pressed on the keyboard (e.g., ‘a’ and ‘A’ are the same)

struct MouseEvent : public emp::web::Event
#include <events.hpp>

Mouse-specific information about web events.

Public Functions

template<int ARG_ID>
void LoadFromArg()

Public Members

bool altKey

Was “ALT” key was pressed?

bool ctrlKey

Was “CTRL” key pressed?

bool metaKey

Was “META” key pressed?

bool shiftKey

Was “SHIFT” key pressed?

int button

Which mouse button was pressed? -1=none (0/1/2)

int detail

How many clicks happened in short succession?

int clientX

X-mouse postion, relative to current window.

int clientY

Y-mouse postion, relative to current window.

int screenX

X-mouse position, relative to the screen.

int screenY

Y-mouse position, relative to the screen.

struct WheelEvent : public emp::web::Event
#include <events.hpp>

Mouse-wheel-specific information about web events.

Public Functions

template<int ARG_ID>
void LoadFromArg()

Public Members

int deltaX

Horizontal scroll amount.

int deltaY

Vertical scroll amount.

int deltaZ

Scroll amount of a mouse wheel for the z-axis.

int deltaMode

The unit of measurements for delta values (pixels, lines or pages)

File Input

Specs for the FileInput widget (click on to upload a file)

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2018

namespace emp

If we are in emscripten, make sure to include the header.

namespace web
class FileInput : public internal::WidgetFacet<FileInput>
#include <FileInput.hpp>

FileInput will convert the file to a std::string and pass the result to a designated function.

To create a new file input, you must pass it a void function that takes a const std::string & as its only argument. When a file is loaded, the specified function is called and the body of the file is passed in as the string.

Public Types

using INFO_TYPE = FileInputInfo

Public Functions

FileInput(const std::function<void(const std::string&)> &in_cb, const std::string &in_id = "", )

Create a new Fileinput; supply the function to call with the file contents as a string (and optionally the HTML identifier to be used).

FileInput(const std::function<void(const emp::File&)> &cb, const std::string &in_id = "", )

Create a new FileInput; supply the function to call with the file contents as a File object (and optionally the HTML identifier to be used).

FileInput(const FileInput &in)

Load a pre-existing FileInput object.

FileInput(const Widget &in)
~FileInput()
FileInput &Callback(const std::function<void(const std::string&)> &in_cb)

Change the callback function to use when a new file is loaded.

FileInput &Autofocus(bool in_af)

Set this FileInput object to have autofocus (or not)

FileInput &Disabled(bool in_dis)

Set this FileInput object to be disabled (or renable it.)

bool HasAutofocus() const

Determine if this object currently has autofocus.

bool IsDisabled() const

Determine if this object is currently disabled.

Protected Functions

FileInputInfo *Info()
const FileInputInfo *Info() const
FileInput(FileInputInfo *in_info)

Friends

friend class FileInputInfo

Font

Maintains basic information about a font to be used in HTML.

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2017

namespace emp

If we are in emscripten, make sure to include the header.

namespace web
class Font
#include <Font.hpp>

Maintain information about an HTML font.

Public Functions

Font(const Font&) = default
Font(Font&&) = default
Font(const std::string &_family = "Helvetica", int _size = 15, const std::string &_color = "black", bool _bold = false, bool _italic = false)
Font(int _size, const std::string &_color = "black", bool _bold = false, bool _italic = false)
~Font()
Font &operator=(const Font&) = default
Font &operator=(Font&&) = default
const std::string &GetFamily() const

Return

font family

int GetSize() const

Return

font size (in pixels)

const std::string &GetColor() const

Return

font color

const std::string &GetLineColor() const

Return

color of lines through text (underline or strikethrough)

bool IsBold() const

Return

boolean indicating whether font is bold

bool IsItalic() const

Return

boolean indicating whether font is italic

bool IsSmallcaps() const

Return

boolean indicating whether font is in small caps

bool IsUnderlined() const

Return

boolean indicating whether font is underlined

bool IsOverlined() const

Return

boolean indicating whether font is overlined

bool IsStrikethrough() const

Return

boolean indicating whether font is strikethrough

bool IsWavyLine() const

Return

boolean indicating whether font is wavy line

bool HasLine() const

Return

boolean indicating whether font has any kind of line (underline, overline, or strikethrough)

Font &SetFamily(const std::string &_family)

Sets font family to specified value

Return

reference to this font for easy chaining

Font &SetSize(int _size)

Sets font size to specified value

Return

reference to this font for easy chaining

Font &SetColor(const std::string &_color)

Sets font color to specified value

Return

reference to this font for easy chaining

Font &SetLineColor(const std::string &_color)

Sets color of any lines through, under, or over this font

Return

reference to this font for easy chaining

Font &SetBold(bool _in = true)

Sets whether font is bold

Return

reference to this font for easy chaining

Font &SetItalic(bool _in = true)

Sets whether font is italic

Return

reference to this font for easy chaining

Font &SetSmallcaps(bool _in = true)

Sets whether font is small caps

Return

reference to this font for easy chaining

Font &SetUnderlined(bool _in = true)

Sets whether font is underlined

Return

reference to this font for easy chaining

Font &SetOverlined(bool _in = true)

Sets whether font is overlined

Return

reference to this font for easy chaining

Font &SetStrikethrough(bool _in = true)

Sets whether font is strikethrough-ed

Return

reference to this font for easy chaining

Font &SetWavyLine(bool _in = true)

Sets whether font is wavy line

Return

reference to this font for easy chaining

void ConfigStyle(Style &style) const

Take a Style object an fill it out based on this font information.

Style AsStyle() const

Return

a style object filled out according to this font information

std::string GetHTMLStart()

Return

a string containing the html necessary to open a span element using this font.

std::string GetHTMLEnd()

Return

a string containing the html necessary to close a span element created by GetHTMLStart()

bool operator==(const Font &_in) const

Fonts will evaluate to equal if all of their properties are the same.

bool operator!=(const Font &_in) const

Fonts will evaluate to equal if all of their properties are the same.

Protected Attributes

std::string family

Font family to use.

int size

Font size (in px) to use.

std::string color

Font color.

std::string line_color

Color of lines through the text (underline, linethrough, etc.)

bool is_bold

Is this font bold?

bool is_italic

Is this font italic?

bool is_smallcaps

Should this text be in small caps?

bool is_underlined

Should this text be underlined?

bool is_overlined

Should this text have a line above it?

bool is_linethrough

Should this text have a line through it?

bool is_wavy_line

Should lines be made wavy?

Images

Easily load an image and place it in a document.

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2018

namespace emp

If we are in emscripten, make sure to include the header.

namespace web
class Image : public internal::WidgetFacet<Image>
#include <Image.hpp>

The Image widget will load an image from a specified URL. For example, you can use emp::web::Image(“http://kripken.github.io/emscripten-site/_static/Emscripten_logo_full.png”) to load the emscripten logo from its website. These can be easily inserted into a web document using << and all JS callbacks (after loading) will be handled automatically.

You can also set the Alt-text with the Alt() function.

Public Types

using INFO_TYPE = ImageInfo

Public Functions

Image(const std::string &in_url, const std::string &in_id = "")

Create a new image, indicating the URL to load from.

Image(const Image &in)

Link to an existing Image widget.

Image(const Widget &in)
~Image()
Image &URL(const std::string &in_url)

Update the URL for this image.

Image &Alt(const std::string &in_alt)

Add Alt-text for this image.

Protected Functions

ImageInfo *Info()
const ImageInfo *Info() const
Image(ImageInfo *in_info)

Friends

friend class ImageInfo

Initialization

Define Initialize() and other functions to set up Empirical to build Emscripten projects.

Init.hpp should always be included if you are compiling Empirical’s web tools with Emscripten. It handles making sure that behind the scenes stuff is all set up properly. It also defines some useful stubs and dummy functions so that your code will still be possible to comple with a normal C++ compiler (although the web part won’t do anything, of course). These stubs are also helpful for avoiding confusion in linters and IDEs.

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2018.

Javascript Utilities

Tools for passing data between C++ and Javascript.

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2018

namespace emp

If we are in emscripten, make sure to include the header.

Functions

std::map<std::string, std::string> get_type_to_string_map()

This function returns a std::map mapping typeid names to the appropriate strings to describe those types in Javscript. This is useful when using getValue() from within MAIN_THREAD_EM_ASM macros.

For example, say we have a templated function that takes a pointer to type T. We find out the appropriate string for type T: std::map<const char*, std::string> type_map = GetTypeToStringMap(); std::string type_string = type_map[typeid(T).name()];

Now we can pass type_string.c_str() into MAIN_THREAD_EM_ASM: `MAIN_THREAD_EM_ASM({ var value = getValue($0, $1); }, pointer, type_string.c_str();`

template<typename C, class = typename C::value_type>
void pass_array_to_javascript(C values)

This function can be called to pass an array, vector, or other container with contiguously stored data into Javascript. The array will be stored in emp.__incoming_array. Currently supports arrays containing all of the types defined in get_type_to_string_map, which are also all of the types that emscripten supports getting via pointer. This function also supports nested arrays, and arrays of objects created with introspective tuple structs.

template<std::size_t SIZE, typename T>
void pass_array_to_cpp(emp::array<T, SIZE> &arr, bool recurse = false)

This function lets you pass an array from javascript to C++! It takes a reference to the array as an argument and populates it with the contents of emp.__outgoing_array.

Currently accepts arrays of ints, floats, doubles, chars, and std::strings The size of the passed array must be equal to the size of the array stored in emp.__outgoing_array

template<typename T>
void pass_vector_to_cpp(emp::vector<T> &arr, bool recurse = false)

Same as pass_array_to_cpp, but lets you store values in a vector instead.

template<typename KEY_T, typename VAL_T>
void pass_map_to_javascript(const emp::map<KEY_T, VAL_T> &dict)

This function can be called to pass a map into JavaScript. The resulting JavaScript object will be stored in emp.__incoming_map.

Parameters
  • dict: the map being passed into JavaScript

template<typename KEY_T, typename VAL_T, size_t SIZE>
void pass_map_to_javascript(const emp::array<KEY_T, SIZE> &keys, const emp::array<VAL_T, SIZE> &values)

This function can be called to pass two arrays of the same length into JavaScript (where a map is then created) One array should hold keys, and the other should hold values (note that the key-value pairs must line up across the arrays) The resulting JavaScript object will be stored in emp.__incoming_map.

Parameters
  • keys: an array holding the keys to the map

  • values: an array holding the values to the map

int GetViewPortSize()

Helper function that returns DOM view port size in pixels.

JSWrap

Wrap a C++ function and convert it to an integer that can be called from Javascript.

To wrap a function, call:

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2018

uint32_t fun_id = emp::JSWrap(FunctionToBeWrapped, "JS_Function_Name");`

To manually callback a function from Javascript, first set emp_i.cb_args to an array of function arguments, then call empCppCallback( fun_id ); This all happens automatically if you use the emp.Callback(fun_id, args...) function from Javascript.

The JS_Function_Name string is optional, but if you use it, the appropriate function will be automatically generated in Javascript by JSWrap, in the emp class.

For example, if you have:

int AddPair(int x, int y) { return x + y; }`

You can wrap it with:

size_t fun_id = emp::JSWrap(AddPair, "AddPair");

And then in Javascript, you can simply call it as:

emp.AddPair(4, 5); // will return 9.

Functions

void empDoCppCallback(const size_t cb_id)

This function is dispatched by empCppCallback. It should be dispatched on the thread hosting the main Empirical runtime. If running with Emscripten pthreads, that would be the worker thread hosting the main Empirical runtime. If not running with Emscripten pthreads, that would be the main browser thread. (In a few limited cases when running with Emscripten pthreads, this function is called on the main browser thread.)

void empCppCallback(const size_t cb_id)

Once you use JSWrap to create an ID, you can call the wrapped function from Javascript by supplying CPPCallback with the id and all args. If running with Emscripten pthreads, this method is to be called from the DOM and it will forward the call to empDoCppCallback on the web worker hosting Empirical runtime. If not running with Emscripten pthreads, this method simply calls empDoCppCallback (on the main browser thread).

namespace emp

If we are in emscripten, make sure to include the header.

Functions

template<typename FUN_TYPE>
size_t JSWrap(const FUN_TYPE &in_fun, const std::string &fun_name = "", bool dispose_on_use = false)

JSWrap takes a C++ function and wraps it in Javascript for easy calling in web code

Return

the id of the function on the Javascript side

Parameters
  • in_fun: a C++ function to wrap

  • fun_name: optionally, a name to call the function on the Javascript size

  • dispose_on_use: should we delete this function after using it?

template<typename FUN_TYPE>
size_t JSWrapOnce(FUN_TYPE &&in_fun)

If we want a quick, unnammed, disposable function, use JSWrapOnce.

void JSDelete(size_t fun_id)

Cleanup a function pointer when finished with it.

Keypress Manager

KeypressManager is a tracker for keypresses in HTML5 pages.

When a KeypressManager is created, it can be given functions to run in response to different types of key presses via overloaded version of the AddKeydownCallback method. Each of these accepts an order parameter that is optional and, if provided, will indicate the order in which tests should be performed to resolve a keypress. If order is not provided, tests will occur in the order that they were given to the manager.

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2017

The specific versions of AddKeydownCallback are:

void AddKeydownCallback(std::function<bool(const emp::web::KeyboardEvent &)> cb_fun, int order=-1)

Link a function to the KeypressManager that is called for any unresolved keypress. The function must take in an emp::web::KeyboardEvent (which includes information about the specific key pressed as well as any modifiers such as SHIFT or CTRL) and it must return a boolean value indicating whether it has resolved the keypress.

void AddKeydownCallback(char key, std::function<void()> cb_fun, int order=-1)

Link a specific key to a target function to be called when that key is pressed. The function my return a void and take no arguments.

void AddKeydownCallback(const std::string & key_set, std::function<void()> cb_fun, int order=-1)

Same as the previous method, but will respond to any of the keys in the provided string.

namespace emp

If we are in emscripten, make sure to include the header.

namespace web
class KeypressManager

Public Functions

KeypressManager()
~KeypressManager()
int GetFunCount() const
int GetNextOrder() const
void AddKeydownCallback(std::function<bool(const KeyboardEvent&)> cb_fun, int order = -1, )

Link a function to the KeypressManager that is called for any unresolved keypress. The function must take in an emp::web::KeyboardEvent (which includes information about the specific key pressed as well as any modifiers such as SHIFT or CTRL) and it must return a boolean value indicating whether it has resolved the keypress.

void AddKeydownCallback(char key, std::function<void()> cb_funint order = -1, )

Link a specific key to a target function to be called when that key is pressed. The function my return a void and take no arguments. Specify keys as lowercase characters. To sepcify uppercase, you’ll need to monitor fo rthe shift modifier associated with a KeypressEvent.

void AddKeydownCallback(const std::string &key_set, const std::function<void()> &cb_funint order, )

Provide a whole set of keys that should all trigger the same function, including an ordering for priority. Specify keys as lowercase characters. To sepcify uppercase, you’ll need to monitor fo rthe shift modifier associated with a KeypressEvent.

void AddKeydownCallback(const std::string &key_set, const std::function<void()> &cb_fun)

Provide a whole set of keys that should all trigger the same function; use default ordering.

Private Functions

bool DoCallback(const KeyboardEvent &evt_info)

Private Members

std::map<int, std::function<bool(const KeyboardEvent&)>> fun_map
int next_order
uint32_t callback_id

Listeners

A class for tracking font event listeners for Widgets.

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2017

namespace emp

If we are in emscripten, make sure to include the header.

namespace web
class Listeners
#include <Listeners.hpp>

Track a set of JavaScript Listeners with their callback IDs.

Public Functions

Listeners()
Listeners(const Listeners&) = default
Listeners &operator=(const Listeners&) = default
size_t GetSize() const

How many listeners are we tracking?

Listeners &Set(const std::string &name, size_t fun_id)

Use a pre-calculated function ID with a new listener.

template<typename ...Ts>
Listeners &Set(const std::string &name, const std::function<void(Ts... args)> &in_fun)

Calculate its own function ID with JSWrap.

bool Has(const std::string &event_name) const

Determine if a specified listener exists.

size_t GetID(const std::string &event_name)

Get the ID associated with a specific listener.

const std::map<std::string, size_t> &GetMap() const
void Clear()

Remove all listeners.

void Remove(const std::string &event_name)

Remove a specific listener.

void Apply(const std::string &widget_id)

Apply all of the listeners being tracked.

operator bool() const

true/false : do any listeners exist?

Public Static Functions

void Apply(const std::string &widget_id, const std::string event_name, size_t fun_id)

Apply a SPECIFIC listener.

Private Members

std::map<std::string, size_t> listeners

Map triggers to callback IDs.

Raw Image

Handle the fundamental loading of an image (without Widget tracking)

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2018

namespace emp

If we are in emscripten, make sure to include the header.

class RawImage
#include <RawImage.hpp>

Fundamental information about a single image.

Public Functions

RawImage(const std::string &url)
RawImage(const RawImage&) = default
~RawImage()
RawImage &operator=(const RawImage&) = default
int GetID() const
const std::string &GetURL() const
bool HasLoaded() const
bool HasError() const
void OnLoad(const std::function<void()> &callback_fun)

Add a new function to be called when the image finishes loading.

void OnError(const std::function<void()> &callback_fun)

Add a new function to be called if an image load has an error.

Private Members

Ptr<internal::ImageInfo> info

Private Static Functions

internal::ImageManager &GetManager()

Selector

Specs for the Selector widget.

A Selector widget provides the user with a pull-down menu. It can be examined at any time (via GetSelectID()) or else alerts call a designated function when a particular option is chosen.

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2018

UI::Selector sel(“sel”);

sel.SetOption(“Option 1”); sel.SetOption(“Option B”, TriggerB) ; sel.SetOption(“Option the Third”, [](){ emp::Alert(“3 chosen!”} ); sel.SetOption(“Option IV”);

In this example, the second option will call TriggerB when it is chosen, while the third option will call the provided lambda function.

namespace emp

If we are in emscripten, make sure to include the header.

namespace web
class Selector : public internal::WidgetFacet<Selector>

Public Types

using INFO_TYPE = SelectorInfo

Public Functions

Selector(const std::string &in_id = "")
Selector(const Selector &in)
Selector(const Widget &in)
~Selector()
size_t GetSelectID() const

Get the ID of the currently active selection.

size_t GetNumOptions() const

Get the total number of options setup in the selector.

const std::string &GetOption(size_t id) const

Get the label associated with a specific option ID.

bool HasAutofocus() const

Determine if the selector has autofocus.

bool IsDisabled() const

Is the selector currently disabled?

Selector &SelectID(size_t id)

Set a specific ID as currently active.

Selector &SetOption(const std::string &in_option, const std::function<void()> &in_cb)

Add a new option to the selector and the function to be called if it is chosen.

Selector &SetOption(const std::string &in_option, const std::function<void()> &in_cbsize_t opt_id, )

Add an option to the selector associated with a specific ID (and the function to be called if it is chosen)

Selector &SetOption(const std::string &in_option)

Set a selector option name, but no function to be called.

Selector &SetOption(const std::string &in_option, size_t opt_id)

Set a specific selection option name, determined by the ID, but no function to call.

Selector &Autofocus(bool in_af)

Update autofocus setting.

Selector &Disabled(bool in_dis)

Update disabled status.

Protected Functions

SelectorInfo *Info()
const SelectorInfo *Info() const
Selector(SelectorInfo *in_info)

Friends

friend class SelectorInfo

Styles

A CSS class for tracking font style, etc.

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2018

namespace emp

If we are in emscripten, make sure to include the header.

namespace web
class Style
#include <Style.hpp>

Class to maintain a map of setting names to values that can be easily ported over to JavaScript. A companial class, Attributes, also exists.

Public Functions

Style()
Style(const Style&) = default
Style(Style&&) = default
Style &operator=(const Style&) = default
Style &operator=(Style&&) = default
size_t GetSize() const

Return a count of the number of settings that have been set.

size_t GetNClasses() const

Return a count of the number of classes that have been added.

Style &AddClass(const std::string &in_clss)
Style &DoSet(const std::string &in_set, const std::string &in_val)
template<typename SET_TYPE>
Style &Set(const std::string &s, SET_TYPE v)

Record that setting “s” is set to value “v” (converted to string) and return this object.

Style &Insert(const Style &in_css)

Set all values from in_css here as well. Return this object.

bool Has(const std::string &setting) const

Return true/false based on whether “setting” has been given a value in this Style.

const std::string &Get(const std::string &setting) const

Return the (string) value of “setting” that has been recorded in this Style.

const std::map<std::string, std::string> &GetMap() const
const std::set<std::string> &GetClasses() const
void Clear()

Remove all setting values and all classes.

void Remove(const std::string &setting)

Remove a specific setting value.

void RemoveClass(const std::string &clss)

Remove a specific class.

void Apply(const std::string &widget_id)

Apply ALL of the style settings to a specified widget.

void Apply(const std::string &widget_id, const std::string &setting)

Apply only a SPECIFIC style setting from the setting library.

operator bool() const

Have any settings be set?

Public Static Functions

void Apply(const std::string &widget_id, const std::string &setting, const std::string &value)

Apply onlay a SPECIFIC style setting with a specifid value!

void ApplyClass(const std::string &widget_id, const std::string &clss)
void ApplyRemoveClass(const std::string &widget_id, const std::string &clss)

Private Members

std::map<std::string, std::string> settings

CSS Setting values being tracked.

std::set<std::string> classes

CSS classes.

Tables

Specs for the Table widget.

TableInfo is the core information for a table and has two helper classes: TableRowInfo and TableDataInfo. The Table class is a smart pointer to a TableInfo object.

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2018

A Table is composed of a series of rows, each with the same number of columns. TableDataInfo may be muliple cells wide/tall, masking other cells.

namespace emp

If we are in emscripten, make sure to include the header.

namespace web
class Table : public emp::web::TableWidget

Public Functions

Table(size_t r, size_t c, const std::string &in_id = "")
Table(const TableWidget &in)
Table(const Widget &in)
Table(internal::TableInfo *in_info, size_t _row, size_t _col)
Table()
Table &Clear()
Table &ClearStyle()
Table &ClearAttr()
Table &ClearListen()
Table &ClearExtras()
Table &ClearChildren()
Table &Rows(size_t r)

Resize the number of rows in the table.

Table &Cols(size_t c)

Resize the number of columns in the table.

Table &Resize(size_t r, size_t c)

Fully resize the table (both rows and columns)

Table &SetColSpan(size_t new_span)

Setup the number of columns the current column group.

template<typename SETTING_TYPE>
Table &RowCSS(size_t row_id, const std::string &setting, SETTING_TYPE &&value)

Apply CSS to target row.

template<typename SETTING_TYPE>
Table &CellCSS(size_t row_id, size_t col_id, const std::string &setting, SETTING_TYPE &&value)

Apply CSS to target cell.

template<typename SETTING_TYPE>
Table &RowsCSS(const std::string &setting, SETTING_TYPE &&value)

Apply CSS to all rows. (: Should we use fancier jquery here?)

template<typename SETTING_TYPE>
Table &CellsCSS(const std::string &setting, SETTING_TYPE &&value)

Apply CSS to all cells.

class TableWidget : public internal::WidgetFacet<TableWidget>

Subclassed by emp::web::Table

Public Types

using INFO_TYPE = internal::TableInfo

Public Functions

TableWidget(size_t r, size_t c, const std::string &in_id = "")
TableWidget(const TableWidget &in)
TableWidget(const Widget &in)
TableWidget()
~TableWidget()
size_t GetNumCols() const
size_t GetNumRows() const
size_t GetNumCells() const
void PrepareAppend() override
size_t GetCurRow() const

Determine which row currently has focus.

size_t GetCurCol() const

Determine which column currently has focus.

void ClearTable()
void ClearRows()
void ClearRow(size_t r)
void ClearCol(size_t c)
void ClearRowGroup(size_t r)
void ClearColGroup(size_t c)
void ClearCells()
void ClearCell(size_t r, size_t c)
TableCell GetCell(size_t r, size_t c) const

Focus on a specifc cell in the table.

TableRow GetRow(size_t r) const

Focus on a specifc row in the table.

TableCol GetCol(size_t c) const

Focus on a specifc column in the table.

TableRowGroup GetRowGroup(size_t r) const

Focus on a specifc group of rows in the table.

TableColGroup GetColGroup(size_t c) const

Focus on a specifc group of columns in the table.

Table GetTable() const

Focus on a the entire table.

web::Text GetTextWidget()

Get the TExt widget assoited with the currently active cell.

Widget AddText(size_t r, size_t c, const std::string &text)

Add text to a specified cell in the table.

Widget AddHeader(size_t r, size_t c, const std::string &text)

Set a specified cell to be a table header.

const std::string &GetCSS(const std::string &setting) const override

Get a CSS value for the currently active cell.

bool OK(std::stringstream &ss, bool verbose = false, const std::string &prefix = "")

Debugging function.

Protected Types

using parent_t = internal::WidgetFacet<TableWidget>

Protected Functions

internal::TableInfo *Info()

Get a properly cast version of info.

internal::TableInfo *const Info() const
TableWidget(internal::TableInfo *in_info, size_t _row = 0, size_t _col = 0)
void DoCSS(const std::string &setting, const std::string &value) override

Apply CSS to appropriate component based on current state.

void DoAttr(const std::string &setting, const std::string &value) override

Apply CSS to appropriate component based on current state.

void DoListen(const std::string &event_name, size_t fun_id) override

Apply CSS to appropriate component based on current state.

Protected Attributes

size_t cur_row
size_t cur_col

Friends

friend class internal::TableInfo

Text

Specs for the Text widget.

A representation of text on a web page. Text Widgets can be included inside of Divs or Tables to cordon off a section of text (and will be automatically created when text is streamed into these other widgets). The primary benefit of explicitly creating your own text widget is to control the text style.

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2018

namespace emp

If we are in emscripten, make sure to include the header.

namespace web
class Text : public internal::WidgetFacet<Text>
#include <Text.hpp>

A Text widget handles putting text on a web page that can be controlled and modified.

Public Types

using INFO_TYPE = TextInfo

Public Functions

Text(const std::string &in_id = "")
Text(const Text &in)
Text(const Widget &in)
~Text()
size_t GetSize() const

How many text items are contained?

Text &Clear()

Erase current text.

Protected Functions

TextInfo *Info()
const TextInfo *Info() const
Text(TextInfo *in_info)

Friends

friend class TextInfo
class TextInfo : public WidgetInfo

Public Functions

std::string GetType() override

Protected Functions

TextInfo(const std::string &in_id = "")
TextInfo(const TextInfo&) = delete
TextInfo &operator=(const TextInfo&) = delete
~TextInfo()
std::string GetTypeName() const override
bool AppendOK() const override
void PreventAppend() override
Widget Append(const std::string &in_text) override

Add new text to this string.

Widget Append(const std::function<std::string()> &in_fun) override

Add a function that produces text to this widget. Every time the widget is re-drawn, the function will be re-run to get the latest version of the text. When a Live() function wraps a variable it simply makes sure that this version of Append is called so that the value of the variable is kept live.

void GetHTML(std::stringstream &HTML) override

Protected Attributes

DynamicString strings

All string (and functions returning strings) in Text widget.

bool append_ok

Can this Text widget be extended?

Private Members

friend Text

Text Areas

Specs for the TextArea widget.

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2018

namespace emp

If we are in emscripten, make sure to include the header.

namespace web
class TextArea : public internal::WidgetFacet<TextArea>
#include <TextArea.hpp>

An input field for text data. A function provided at creation time will be called each time the contents of the TextWidget are changed. The current text contents can also always be accessed with the GetText() member function.

Public Types

using INFO_TYPE = TextAreaInfo

Public Functions

TextArea(const std::string &in_id = "")

Build a text area with a specified HTML identifier.

TextArea(std::function<void(const std::string&)> in_cb, const std::string &in_id = "", )

Build a text area with a specified function to call with every change.

TextArea(const TextArea &in)

Connect to an existing TextArea.

TextArea(const Widget &in)
~TextArea()
const std::string &GetText() const

Get the current text in this TextArea.

TextArea &SetAutofocus(bool in_af)

Make this text area have focus by default.

TextArea &SetCallback(const std::function<void(const std::string&)> &in_cb)

Change the callback function for this TextArea.

TextArea &SetDisabled(bool in_dis)

Gray out this text area.

TextArea &SetText(const std::string &in_text)

Set the text contained in the text area.

bool HasAutofocus() const

Does this widget have auto focus set?

bool IsDisabled() const

Is this widget currently disabled?

Protected Functions

TextAreaInfo *Info()
const TextAreaInfo *Info() const
TextArea(TextAreaInfo *in_info)

Friends

friend class TextAreaInfo

Tweens

A Tween manages the gradual shift in properties of one or more widgets over time.

To create a Tween, a duration must be specified, along with an optional default target. Once a Tween is setup, paths can be added to it, which represent the changes that should occur over the specified duration.

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2017

A path can be a function to call (with the 0.0 to 1.0 fraction of the time that’s gone by) or a variable to set to the current fraction. Dependants can also be set to refresh with each Tween update.

Available methods include: Tween & AddPath(std::function<void(double)> set_fun, double start_val, double end_val, std::function<double(double)> timing=LINEAR); Tween & AddPath(double & set_var, double start_val, double end_val, std::function<double(double)> timing=LINEAR); Tween & AddDependant(Widget w); void Start(); void Stop();

namespace emp

If we are in emscripten, make sure to include the header.

namespace web
class Tween

Public Functions

Tween(double d = 1.0, const Widget &t = nullptr)

Build a new tween, specifying the duration it should run for and the widget it should modify.

~Tween()
double GetDuration() const

Retrieve the full duration of this Tween.

Widget GetDefaultTarget() const

Which widget does this Tween modify?

Tween &SetDuration(double d)

Change the duration of this Tween.

Tween &SetDefaultTarget(const Widget &w)

Change the target of this tween.

Tween &AddPath(std::function<void(double)> set_fun, double start_val, double end_val, std::function<double(double)> timing = LINEAR)

Alter the path of the change that this tween should take and the function it should call.

Tween &AddPath(double &set_var, double start_val, double end_val, std::function<double(double)> timing = LINEAR)

Alter the path of the change that this tween should take and the variable it should modify.

Tween &AddPath(Widget w, std::string setting, double start_val, double end_val)

Alter the path of the change that this tween should take and the widget setting it should alter. (TODO!)

Tween &AddUpdate(std::function<void(void)> ud_fun)

Add an additional function to update as the Tween runs.

Tween &AddDependant(Widget w)

Add a dependant Widget to update as the Tween runs.

void Start()

Start running this Tween, as configured.

void Stop()

Pause this Tween.

Private Functions

void AdvanceFrame()

Private Members

double duration
Widget default_target
emp::vector<Path*> paths
emp::vector<Event*> events
emp::vector<std::function<void()>> update_funs
emp::vector<Widget> dependants
bool running
size_t callback_id
double start_time
double cur_time
double run_time

Private Static Functions

double LINEAR(double in)
struct Event

Public Members

double time
std::function<void()> trigger
struct Path

Public Functions

void Set(const double frac)

Public Members

std::function<void(double)> set_fun
double start_val
double end_val
std::function<double(double)> timing

Widgets

A collection of extra details about HTML Widgets (attributes, style, listerns)

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2015-2017

namespace emp

If we are in emscripten, make sure to include the header.

namespace web
struct WidgetExtras

Public Functions

template<typename SET_TYPE>
void SetStyle(const std::string &s, SET_TYPE v)
bool HasStyle(const std::string &setting) const
const std::string &GetStyle(const std::string &setting) const
void RemoveStyle(const std::string &setting)
template<typename SET_TYPE>
void SetAttr(const std::string &s, SET_TYPE v)
bool HasAttr(const std::string &setting) const
const std::string &GetAttr(const std::string &setting) const
void RemoveAttr(const std::string &setting)
void Apply(const std::string &name)

Apply all HTML details associated with this widget.

void Clear()

Clear all of style, attributes, and listeners.

operator bool() const

Have any details been set?

Public Members

Style style

CSS Style.

Attributes attr

HTML Attributes about a cell.

Listeners listen

Listen for web events.