/** @module core */ /** * Main component of the PsychoJS library. * * @author Alain Pitiot * @version 3.2.0 * @copyright (c) 2019 Ilixa Ltd. ({@link http://ilixa.com}) * @license Distributed under the terms of the MIT License */ import { Scheduler } from '../util/Scheduler'; import { ServerManager } from './ServerManager'; import { ExperimentHandler } from '../data/ExperimentHandler'; import { EventManager } from './EventManager'; import { Window } from './Window'; import { GUI } from './GUI'; import { MonotonicClock } from '../util/Clock'; import { Logger } from '../util/Logger'; import * as util from '../util/Util'; /** *

PsychoJS manages the lifecycle of an experiment. It initialises the PsychoJS library and its various components (e.g. the {@link ServerManager}, the {@link EventManager}), and is used by the experiment to schedule the various tasks.

* * @class * @param {Object} options * @param {boolean} [options.debug= true] whether or not to log debug information in the browser console * @param {boolean} [options.collectIP= false] whether or not to collect the IP information of the participant */ export class PsychoJS { /** * Properties */ get status() { return this._status; } set status(status) { this._status = status; } get config() { return this._config; } get window() { return this._window; } get serverManager() { return this._serverManager; } get experiment() { return this._experiment; } get scheduler() { return this._scheduler; } get monotonicClock() { return this._monotonicClock; } get logger() { return this._logger.consoleLogger; } get eventManager() { return this._eventManager; } get gui() { return this._gui; } get IP() { return this._IP; } // this._serverMsg is a bi-directional message board for communications with the pavlovia.org server: get serverMsg() { return this._serverMsg; } /** * @constructor * @public */ constructor({ debug = true, collectIP = false, topLevelStatus = true } = {}) { // logging: this._logger = new Logger((debug) ? log4javascript.Level.DEBUG : log4javascript.Level.INFO); this._captureErrors(); // core clock: this._monotonicClock = new MonotonicClock(); // managers: this._eventManager = new EventManager(this); this._serverManager = new ServerManager({ psychoJS: this }); // GUI: this._gui = new GUI(this); // IP: this._collectIP = collectIP; // main scheduler: this._scheduler = new Scheduler(this); // Window: this._window = undefined; // redirection URLs: this._cancellationUrl = undefined; this._completionUrl = undefined; // status: this._status = PsychoJS.Status.NOT_CONFIGURED; // make the PsychoJS.Status accessible from the top level of the generated experiment script // in order to accommodate PsychoPy's Code Components if (topLevelStatus) this._makeStatusTopLevel(); this.logger.info('[PsychoJS] Initialised.'); } /** * Get the experiment's environment. * * @returns {PsychoJS.Environment | undefined} the environment of the experiment, or undefined */ getEnvironment() { if (typeof this._config === 'undefined') return undefined; return this._config.environment; } /** * Open a PsychoJS Window. * *

This opens a PIXI canvas.

*

Note: we can only open one window.

* * @param {Object} options * @param {string} [options.name] the name of the window * @param {boolean} [options.fullscr] whether or not to go fullscreen * @param {Color} [options.color] the background color of the window * @param {string} [options.units] the units of the window * @param {boolean} [options.autoLog] whether or not to log * @param {boolean} [options.waitBlanking] whether or not to wait for all rendering operations to be done * before flipping * @throws {Object.} exception if a window has already been opened * * @public */ openWindow({ name, fullscr, color, units, waitBlanking, autoLog } = {}) { this.logger.info('[PsychoJS] Open Window.'); if (typeof this._window !== 'undefined') throw { origin : 'PsychoJS.openWindow', context : 'when opening a Window', error : 'A Window has already been opened.' }; this._window = new Window({ psychoJS: this, name, fullscr, color, units, waitBlanking, autoLog }); } /** * Set the completion and cancellation URL to which the participant will be redirect at the end of the experiment. * * @param {string} completionUrl - the completion URL * @param {string} cancellationUrl - the cancellation URL */ setRedirectUrls(completionUrl, cancellationUrl) { this._completionUrl = completionUrl; this._cancellationUrl = cancellationUrl; } /** * Schedule a task. * * @param task - the task to be scheduled * @param args - arguments for that task * @public */ schedule(task, args) { this.logger.debug('schedule task: ', task.toString().substring(0, 50), '...'); this._scheduler.add(task, args); } /** * @callback PsychoJS.condition * @return {boolean} true if the thenScheduler is to be run, false if the elseScheduler is to be run */ /** * Schedule a series of task based on a condition. * * @param {PsychoJS.condition} condition * @param {Scheduler} thenScheduler scheduler to run if the condition is true * @param {Scheduler} elseScheduler scheduler to run if the condition is false * @public */ scheduleCondition(condition, thenScheduler, elseScheduler) { this.logger.debug('schedule condition: ', condition.toString().substring(0, 50), '...'); this._scheduler.addConditional(condition, thenScheduler, elseScheduler); } /** * Start the experiment. * * @param {Object} options * @param {string} [options.configURL=config.json] - the URL of the configuration file * @param {string} [options.expName=UNKNOWN] - the name of the experiment * @param {Object.} [options.expInfo] - additional information about the experiment * @param {Array.<{name: string, path: string}>} [resources=[]] - the list of resources * @async * @public * * @todo: close session on window or tab close */ async start({ configURL = 'config.json', expName = 'UNKNOWN', expInfo, resources = [] } = {}) { this.logger.debug(); const response = { origin: 'PsychoJS.start', context: 'when starting the experiment' }; try { // configure the experiment: await this._configure(configURL, expName); // get the participant IP: if (this._collectIP) this._getParticipantIPInfo(); else { this._IP = { IP: 'X', hostname : 'X', city : 'X', region : 'X', country : 'X', location : 'X' }; } // setup the experiment handler: this._experiment = new ExperimentHandler({ psychoJS: this, extraInfo: expInfo }); // setup the logger: //my.logger.console.setLevel(psychoJS.logging.WARNING); //my.logger.server.set({'level':psychoJS.logging.WARNING, 'experimentInfo': my.expInfo}); // if the experiment is running on the server, we open a session: if (this.getEnvironment() === PsychoJS.Environment.SERVER) await this._serverManager.openSession(); // attempt to close the session on onunload: const self = this; window.addEventListener("unload",() => { // we need to use either the Beacon API (https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon) // or synchronous requests // TODO }); // start the asynchronous download of resources: this._serverManager.downloadResources(resources); // start the experiment: this.logger.info('[PsychoJS] Start Experiment.'); this._scheduler.start(); } catch (error) { // this._gui.dialog({ error: { ...response, error } }); this._gui.dialog({ error: Object.assign(response, { error }) }); } } /** * Synchronously download resources for the experiment. * *