text:
(function ($) {
    // var baseUrl = 'http://solaris:8080/api/v1/',
    var baseUrl = 'http://solaris/girder/api/v1/',
    pvwebBaseUrl = 'http://solaris/apps/Visualizer/?',
    topLevelFolderId = '52f84a067bee040aa2335afc', // solaris
    // topLevelFolderId = '5356a4947bee047b8183d5b5', // tukey
    // topLevelFolderId = '52f908af7bee040bfaeee127', // mayall
    remoteConnectionsFolder = '52fe97757bee040fc657a371',
    // mySessionMgrUrlKeyVal = 'sessionManagerURL=http://solaris/girder/api/v1/remoteconnection&',
    mySessionMgrUrlKeyVal = '',
    token = null,
    imgFilePattern = new RegExp('vtk_([^_]+)_neg-([^-])-up'),
    titlePattern = new RegExp('(region[\\d]+)\\.vtk'),
    filePathPattern = new RegExp('(postProcessedRegions[^\\.]+\\.vtk)'),
    overviewPngUrl = null,
    pHash = '',
    jobDescriptor = { "schedulerType": "ANLCobalt",
                      "wallTime": "5",
                      "numberOfNodes": "1",
                      "queue": "pubnet",
                      "project": "SkySurvey" },
    jobString = "#!/bin/sh%0A%0Aexport PATH=/home/scottwit/software/python-2.7.3/bin:\\$PATH ; export LD_LIBRARY_PATH=/home/scottwit/software/python-2.7.3/lib:\\$LD_LIBRARY_PATH ; /home/scottwit/ParaView/release-4.1.0/build/bin/pvpython /home/scottwit/ParaView/release-4.1.0/build/lib/site-packages/paraview/web/pv_web_visualizer.py --port 8000 --content /home/scottwit/ParaView/release-4.1.0/build/www --data-dir /gpfs/mira-fs0/projects/SkySurvey/scottwit/pvLaunchDemo/haloregions -f --load-file ",

    // Does the work of figuring out the argument to send to visualizer
    launchPvwebFile = function(filepath, hostname) {
        var match = filePathPattern.exec(filepath);
        if (match !== null) {
            getSshCredentials(hostname, function(name, pass) {
                var url = pvwebBaseUrl + mySessionMgrUrlKeyVal +
                    'sshuser=' + name + '&sshpass=' + pass +
                    '&relFileName=' + match[1];
                console.log('pvweb points launch url: ' + url);
                $('.pvweb-iframe').attr('src', url);
                $('.pvweb-iframe-pane').show();
            });
        }
    },

    // Use the appropriate RemoteConnection to launch a pvweb instance,
    // create a secure tunnel, then connect to the pvweb instance through
    // the tunnel
    securePvwebLaunch = function(filepath, host) {
        console.log("Attempting a secure remote launch on host: " + host);

        var match = filePathPattern.exec(filepath);
        var relFilePath = '';
        if (match !== null) {
            relFilePath = match[1];
        }

        var d = findRemoteConnectionDetails(host);

        function launch(connId) {
            var url = pvwebBaseUrl +
                'sessionManagerURL=http://solaris/girder/api/v1/remoteconnection/tunnellaunch&' +
                'relFileName=' + relFilePath + '&' +
                'connectionId=' + connId + '&' +
                'remoteHost=' + host;

            console.log('pvweb launch url: ' + url);

            $('.pvweb-iframe').attr('src', url);
            $('.pvweb-iframe-pane').show();
        }

        if (d['targetConnId'] === 'none' || d['targetConnId'] === '' || d['targetConnected'] === false) {
            console.log("you are not connected, attempting to connect using following params:");
            console.log('host: ' + d['targetFqhn'] + ', connId: ' + d['targetConnId'] + ', itemId: ' + d['targetItemId']);
            connectToRemote(d['targetFqhn'], d['targetConnId'], d['targetItemId'], launch);
        } else {
            launch(d['targetConnId']);
        }
    },

    // Similar to securePvwebLaunch, except in this case we have to qsub our paraviewweb
    // job and then qstat until it's ready and running.
    scheduledPvwebLaunch = function(filepath, host) {
        console.log("Attempting a secure scheduled remote launch on host: " + host);

        var match = filePathPattern.exec(filepath);
        var relFilePath = '';
        if (match !== null) {
            relFilePath = match[1];
        }

        var d = findRemoteConnectionDetails(host);

        function interpretStatusResult(connId, jobInfo, result) {
            var jobId = jobInfo['hpcJobId'];
            var jsonResult = JSON.parse(result[0][0]);
            console.log(jsonResult);
            var statusString = jsonResult[0];
            var indicatorElt = $('.job-status-indicator.' + jobId);
            var nextCheck = 5000;

            if (statusString === 'running') {
                var readyBtn = $('.job-status-ready-btn', indicatorElt);
                $('.job-status-busy-spinner', indicatorElt).hide();
                $('.job-status-remove-btn', indicatorElt).hide();
                readyBtn.show();
                $('.job-status-label-status', indicatorElt).text(statusString);
                if (readyBtn.hasClass('fresh')) {
                    readyBtn.unbind('click');
                    readyBtn.bind('click', function(event) {
                        console.log("You have requested to connect to your running pvweb process...");
                        var btn = $(this);
                        btn.unbind('click');
                        btn.removeClass('fresh');
                        btn.css('color', 'grey');
                        // Example url:
                        //        http://vs28.tukey.alcf.anl.gov:8000/apps/Visualizer/
                        var hostnamePrefix = jsonResult[1]['hostnames'];
                        // var hostnameSuffix = "blah.blah";
                        var hostnameSuffix = "alcf.anl.gov";
                        var connectPort = 8000;
                        var connectUrl = "http://" + hostnamePrefix + "." + hostnameSuffix +
                            ":" + connectPort + "/apps/Visualizer/";
                        console.log('pvweb launch url: ' + connectUrl);
                        $('.pvweb-iframe').attr('src', connectUrl);
                        $('.pvweb-iframe-pane').show();
                        event.stopPropagation();
                        event.preventDefault();
                    });
                }
                nextCheck = 5000;
            } else if (statusString === 'starting' || statusString === 'queued') {
                $('.job-status-busy-spinner', indicatorElt).show();
                $('.job-status-remove-btn', indicatorElt).hide();
                $('.job-status-ready-btn', indicatorElt).hide();
                $('.job-status-label-status', indicatorElt).text(statusString);
            } else if (statusString === 'killing' || statusString == 'exiting') {
                $('.job-status-label-status', indicatorElt).text('Finished');
            } else if (statusString === 'NO_SUCH_JOB') {
                $('.job-status-busy-spinner', indicatorElt).hide();
                $('.job-status-ready-btn', indicatorElt).hide();
                $('.job-status-remove-btn', indicatorElt).show();
                $('.job-status-label-status', indicatorElt).text('Finished');
                $('.job-status-remove-btn', indicatorElt).bind('click', function(event) {
                    // Ask Girder to do some job cleanup for us.
                    var requestData = { 'connId': connId,
                                        'girderDir': '/home/scottwit/.girder',
                                        'jobUuid': jobInfo['girderJobId'],
                                        'userHomeDir': '/home/scottwit' };
                    $.ajax({
                        type: 'POST',
                        url: baseUrl + 'remoteconnection/jobcleanup',
                        dataType: 'json',
                        data: requestData,
                        success: function(result) {
                            console.log('Returned from cleanup request:');
                            console.log(result);
                            // Then remove the ui for this job
                            indicatorElt.remove();
                        },
                        error: function(result) {
                            console.log("Error making jobcleanup POST request:");
                            console.log(result);
                            alert("Unsuccessful job cleanup result, see console.");
                        }
                    });
                    event.stopPropagation();
                    event.preventDefault();
                });
                nextCheck = -1;
            }  else {
                // Noticed this could be "killing" or "exiting" as well as above options
                console.log("OH BUMMER, what do I do with " + statusString + "?");
            }

            return nextCheck;
        }

        // Make a POST request to girder to run qstat on the remote machine
        // (currently via the remotely installed HPCJobScheduler python module)
        // and return the status of the identified job.
        function checkStatus(connId, jobInfo) {
            var jobId = jobInfo['hpcJobId'];
            console.log('Checking status, connId: ' + connId + ', jobId: ' + jobId);
            var requestData = { 'connId': connId,
                                'girderDir': '/home/scottwit/.girder',
                                'jobUuid': jobInfo['girderJobId'],
                                'jobDescriptor': JSON.stringify(jobDescriptor) }
            $.ajax({
                type: 'POST',
                url: baseUrl + 'remoteconnection/jobstatus',
                dataType: 'json',
                data: requestData,
                success: function(statResult) {
                    console.log('Got job status for jobid: ' + jobId + ', status:');
                    console.log(statResult[0][0]);
                    var nextCheck = interpretStatusResult(connId, jobInfo, statResult);
                    if (nextCheck > 0) {
                        setTimeout(function() {
                            checkStatus(connId, jobInfo);
                        }, nextCheck);
                    }
                },
                error: function(result) {
                    console.log("Error making jobschedule POST request:");
                    console.log(result);
                    alert("Unsuccessful job schedule result, see console.");
                }
            });
        }

        // Once the job has been scheduled, we want to add some ui to remind
        // us of it's existence, to give us a way to interact once the job is
        // running, as well as to give us an indicator when it is finished.
        function scheduled(connId, result) {
            console.log('Successfully scheduled job:');
            console.log(result);
            var jobId = result['hpcJobId'];
            console.log("Now I have just the job id: " + jobId);

            // clone the status indicator
            var newDiv = $('#job-status-indicator-template')
                .clone()
                .removeAttr('id')
                .addClass(jobId);
            $('.header-bar').append(newDiv);
            $('.job-status-busy-spinner', newDiv).show();
            $('.job-status-label-id', newDiv).text(jobId);
            $('.job-status-label-status', newDiv).text('Pending...');
            $('.job-status-ready-btn', newDiv).addClass('fresh');

            newDiv.bind('click', function(event) {
                event.stopPropagation();
                event.preventDefault();
            });

            setTimeout(function() {
                checkStatus(connId, result);
            }, 5000);
        }

        // POST a girder request to 'remoteconnection/jobschedule' with connId in
        // the params.  This rest api route will result in qsub getting called on
        // the remote connection, and we should get a jobid back from the request
        function launch(connId) {
            // Some of this stuff can be retrieved from Girder (either here or
            // inside the Girder plugin) eventually.  For now, we'll just put
            // in enough to get the demo working.
            var match = filePathPattern.exec(filepath);
            if (match !== null) {
                filepath = match[1];
            }
            console.log("Launching a pvweb job to visualize: " + filepath);
            var launchData = { 'connId': connId,
                               'girderDir': '/home/scottwit/.girder',
                               'userHomeDir': '/home/scottwit',
                               'jobDescriptor': JSON.stringify(jobDescriptor),
                               'jobString': jobString + filepath + "%0A"};
            $.ajax({
                type: 'POST',
                url: baseUrl + 'remoteconnection/jobschedule',
                dataType: 'json',
                data: launchData,
                success: function(result) {
                    scheduled(connId, result);
                },
                error: function(result) {
                    console.log("Error making jobschedule POST request:");
                    console.log(result);
                    alert("Unsuccessful job schedule result, see console.");
                }
            });
        }

        // Kick things off: If we're not already connected, connect and then
        // launch.  Otherwise, just launch.
        if (d['targetConnId'] === 'none' || d['targetConnId'] === '' || d['targetConnected'] === false) {
            console.log("you are not connected, attempting to connect using following params:");
            console.log('host: ' + d['targetFqhn'] + ', connId: ' + d['targetConnId'] + ', itemId: ' + d['targetItemId']);
            connectToRemote(d['targetFqhn'], d['targetConnId'], d['targetItemId'], launch);
        } else {
            launch(d['targetConnId']);
        }
    },

    /// This is where I can choose from the various forms of launching
    /// with which I have experimented in this prototype application
    //launchFunction = launchPvwebFile,
    //launchFunction = securePvwebLaunch,
    launchFunction = scheduledPvwebLaunch,

    // Update the number of items showing in the results column
    updateResultsCount = function(count) {
        $('.search-results-count').text(count);
    },

    // An object which stores all the girder items so that later I can
    // reload them all into my collection if the filter is cleared,
    // without having to query them from Girder again
    cosmoDatum = {},

    // Define the CosmoData model to extend Backbone.Model
    CosmoData = Backbone.Model.extend({}),

    // Remote connection model
    RemoteConnection = Backbone.Model.extend({}),

    // Define the CosmoView to extend Backbone.View
    CosmoView = Backbone.View.extend({
        tagName: 'div',

        // Cache the template function for a single item.
        todoTpl: _.template( $('.cosmodata-template').html() ),

        events: {
            'click .image-thumb': 'loadImage',
            'click .launch-pvweb-button-magvel': 'launchPtsViz',
            'click .launch-pvweb-button-volren': 'launchVolViz'
        },

        // Re-render the titles of the todo item.
        render: function() {
            // console.log('rendering a cosmodata');
            this.$el.html( this.todoTpl( this.model.toJSON() ) );
            return this;
        },

        // Called to load the full size image in the viewer when thumb is clicked
        loadImage: function(e) {
            $('.pvweb-iframe').attr('src', '');
            $('.pvweb-iframe-pane').hide();
            $('.full-size-image').attr('src', e.target.src);
        },

        // Called to launch paraviewweb to visualize the magnitude of velocity points data
        launchPtsViz: function(e) {
            launchFunction(this.model.attributes.velocityMagnitudeVtkFile,
                           this.model.attributes.hostname);
        },

        // Called to launch paraviewweb to visualize the volume data
        launchVolViz: function(e) {
            launchFunction(this.model.attributes.volumeVtkFile,
                           this.model.attributes.hostname);
        }
    }),

    // Define the RemoteConnectionView to extend Backbone.View
    RemoteConnectionView = Backbone.View.extend({
        tagName: 'tr',

        // Cache the template function for a single item.
        tpl: _.template( $('.remote-connection-template').html() ),

        // Re-render the titles of the todo item.
        render: function() {
            // console.log('rendering a cosmodata');
            this.$el.html( this.tpl( this.model.toJSON() ) );
            return this;
        }
    }),

    // Define a simple collection for the CosmoData objects, with just a filter
    CosmoCollection = Backbone.Collection.extend({
        model: CosmoData,

        filterBySpatialAttr: function(minAttrName, maxAttrName, attrValue){
            return this.models.filter(
                function(c) {
                    if (c.attributes[minAttrName] <= attrValue &&
                        c.attributes[maxAttrName] >= attrValue) {
                        return true;
                    } else {
                        return false;
                    }
                });
        }
    }),

    // Define a collection for the RemoteConnection objects
    RemoteConnectionCollection = Backbone.Collection.extend({
        model: RemoteConnection
    }),

    // A collection instance
    cosmoDataCollection = new CosmoCollection(),

    // Another collection instance, for remote connections
    remoteConnCollection = new RemoteConnectionCollection(),

    // Our overall **AppView** is the top-level piece of UI.
    AppView = Backbone.View.extend({
        // Instead of generating a new element, bind to the existing skeleton of
        // the App already present in the HTML.
        el: '.viewport-container',

        // At initialization we bind to the relevant events on the `Todos`
        // collection, when items are added or changed.
        initialize: function() {
            this.listenTo(cosmoDataCollection, 'add', this.addOne);
            this.listenTo(cosmoDataCollection, 'reset', this.addAll);
        },

        // Add a single todo item to the list by creating a view for it, and
        // appending its element to the `<ul>`.
        addOne: function( modelObj ) {
            var view = new CosmoView({ model: modelObj });
            $('.cosmodata').append(view.render().el);
            updateResultsCount(cosmoDataCollection.length);
        },

        // Add all items in the cosmoDataCollection collection at once.
        addAll: function() {
            this.$('.cosmodata').html('');
            cosmoDataCollection.each(this.addOne, this);
            updateResultsCount(cosmoDataCollection.length);
        }
    }),

    // A list view ui component
    RemoteConnectionListView = Backbone.View.extend({
        // Instead of generating a new element, bind to the existing skeleton of
        // the App already present in the HTML.
        el: '.viewport-container',

        // At initialization we bind to the relevant events on the
        // collection, when items are added or changed.
        initialize: function() {
            this.listenTo(remoteConnCollection, 'add', this.addOne);
            this.listenTo(remoteConnCollection, 'reset', this.reset);
        },

        // Add a single item to the list by creating a view for it, and
        // appending its element to the parent div.
        addOne: function( modelObj ) {
            var view = new RemoteConnectionView({ model: modelObj });
            $('.cosmo-remote-connection-table').append(view.render().el);
        },

        // Empty the list of html elements
        reset: function() {
            // $('.cosmo-remote-connection-table').html('
Hostname	Connected	Options
');
            $('.cosmo-remote-connection-table').html('');
        }
    }),

    // An instance of a list view for the RemoteConnection items
    myRconView = new RemoteConnectionListView(),

    // An instance of the top-level list view of CosmoData items
    myAppView = new AppView();

    /*
     * Find the remote connection that matches the hostname and return
     * an object containing it's details.
     */
    function findRemoteConnectionDetails(host) {
        var details = {
            'targetConnId': 'none',
            'targetFqhn': '',
            'targetConnected': 'false',
            'targetItemId': ''
        };

        console.log("Iterating over remote connections");
        remoteConnCollection.each(function(rc) {
            // console.log(rc);
            if (rc.attributes.hostname === host) {
                console.log('Found remote connection, host: ' + host);
                details['targetConnId'] = rc.attributes.connectionId;
                details['targetFqhn'] = rc.attributes.hostname;
                details['targetConnected'] = rc.attributes.connected;
                details['targetItemId'] = rc.attributes.itemId;
            }
        });

        return details;
    }

    /*
     * Present dialog to collect ssh user name and password, then invoke
     * the callback with that information.  Callback should be defined to
     * take two args: username and password.
     */
    function getSshCredentials(hostname, callback) {
        $('.ssh-authenticate-button').unbind().bind('click', function(evt) {
            $('.ssh-authentication-widget').hide();
            var name = $('.ssh-username-input-field').val();
            var pass = $('.ssh-password-input-field').val();
            callback(name, pass);
        });
        $('.remote-ssh-host').text(hostname);
        $('.ssh-authentication-widget').show();
    }

    /*
     * Connect to a secure remote connection given the hostname to connect to,
     * the connection id generated and returned by the Girder remoteconnection
     * endpoint, and the id of the Girder item which contains the information
     * about the remote connection.
     */
    function connectToRemote(hostname, connectionId, itemId, onConnected) {
        console.log('Connect to host: ' + hostname + ', connId: ' + connectionId);

        function connected(connectResult, connId) {
            // 3) when (2) returns, update Girder: /item/{id}/metadata?connected=yes&connectionId={connId}
            $.ajax({
                type: 'PUT',
                url: baseUrl + 'item/' + itemId + '/metadata',
                dataType: 'json',
                headers: {'Content-Type': 'application/json; charset=UTF-8',
                          'Accept': 'application/json' },
                data: JSON.stringify({ "connected": "yes", "connectionId": connId }),
                processData: false,
                // contentType: 'application/json; charset=UTF-8',
                success: function() {
                    updateRemoteConnections();
                    if (onConnected) {
                        onConnected(connId);
                    }
                },
                error: function(result) {
                    console.log("Error making PUT request to update connection metadata:");
                    console.log(result);
                }
            });
        }

        function remoteConnect(connId) {
            // 1) show ssh password prompt
            getSshCredentials(hostname, function(name, pass) {
                // 2) make Girder call to /remoteconnection/connect.  Make it
                // a POST request to keep sensitive information out of the log
                // files.
                $.ajax({
                    type: 'POST',
                    url: baseUrl + 'remoteconnection/connect',
                    dataType: 'json',
                    data: { 'connId': connId,
                            'username': name,
                            'password': pass },
                    success: function(connectResult) {
                        connected(connectResult, connId);
                    },
                    error: function(result) {
                        console.log("Error making connect POST request:");
                        console.log(result);
                        alert("Unable to make remote connection, see console for information");
                    }
                });
            });
        }

        // If there is not yet a connection id for this remote, we need
        // to create one.  Once we have that (and also if we already
        // have one) we can make the connection
        if (connectionId === 'none' || connectionId === '') {
            // Attempt to create a remote connection
            makeGirderRequest('GET',
                              'remoteconnection/create',
                              {'fqhn': hostname},
                              function(response) {
                                  if ('connId' in response) {
                                      remoteConnect(response['connId']);
                                  } else {
                                      alert('Unable to create remote ' +
                                            'connection to ' + hostname);
                                  }
                              });
        } else {
            remoteConnect(connectionId);
        }
    }

    /*
     * Interact with (send commands to and receive results from) a
     * secure remote connection.
     */
    function interactWithRemote(hostname, connectionId) {
        console.log('Interact with host: ' + hostname + ', connId: ' + connectionId);
        $('.remote-connection-list').hide();
        $('.console-hostname').text(hostname);
        $('.remote-interact-panel').show();

        $('.command-entry-field').keypress(function(e) {
            var me = $(this);
            var command = me.val();
            if (e.keyCode == 13 && !e.shiftKey) {
                e.preventDefault();
                console.log('You entered: ' + me.val());
                makeGirderRequest('GET',
                                  'remoteconnection/command',
                                  { 'connId': connectionId,
                                    'cmdStr': command },
                                  function(result) {
                                      console.log('Result of running "' + command + '" on remote:');
                                      console.log(result);
                                      var outputContents = ""
                                      for (var idx in result[0]) {
                                          outputContents += result[0][idx];
                                      }
                                      $('.command-results-field').val(outputContents);
                                  });
            }
        });
    }

    /*
     * Disconnect the remote referenced by connectionId
     */
    function disconnectFromRemote(connectionId, itemId) {
        function updateConnectionRecord(result) {
            console.log('Result of disconnecting remote:');
            console.log(result);

            $.ajax({
                type: 'PUT',
                url: baseUrl + 'item/' + itemId + '/metadata',
                dataType: 'json',
                headers: {'Content-Type': 'application/json; charset=UTF-8',
                          'Accept': 'application/json' },
                data: JSON.stringify({ "connected": "no" }),
                processData: false,
                success: updateRemoteConnections,
                error: function(result) {
                    console.log("Error making PUT request to update connection metadata:");
                    console.log(result);
                }
            });
        }

        makeGirderRequest('GET',
                          'remoteconnection/disconnect',
                          { 'connId': connectionId },
                          updateConnectionRecord);
    }

    /*
     * Retrieve the remote connection items, use them to repopulate the
     * collection, which will result in their re-rendering.
     */
    function updateRemoteConnections() {

        function gotRemoteConnections(data) {
            remoteConnCollection.reset();
            for (var idx in data) {
                var rconItem = data[idx];
                var rcon = new RemoteConnection({
                    hostname: rconItem['meta']['fqhn'],
                    connected: (rconItem['meta']['connected'] === 'yes' ? true : false),
                    connectionId: rconItem['meta']['connectionId'],
                    itemId: rconItem['_id']
                });
                remoteConnCollection.add(rcon);
            }

            $('.conn-interact-btn').bind('click', function() {
                var me = $(this);
                interactWithRemote(me.attr('data-fqhn'), me.attr('data-connection-id'));
            });

            $('.conn-connect-btn').bind('click', function() {
                var me = $(this);
                if (me.hasClass('connect')) {
                    // console.log('Connecting');
                    connectToRemote(me.attr('data-fqhn'),
                                    me.attr('data-connection-id'),
                                    me.attr('data-item-id'));
                } else {
                    // console.log('Disconnecting');
                    disconnectFromRemote(me.attr('data-connection-id'),
                                         me.attr('data-item-id'));
                }
            });
        }

        // Attempt to get this user's remote connections
        makeGirderRequest('GET',
                          'item/',
                          {'folderId': remoteConnectionsFolder},
                          gotRemoteConnections);
    }

    /*
     * This function can be called once we have successfully authenticated
     * and got our token to use in all subsequent requests.  Here we query
     * Girder in two steps and initialize the ui with the results.
     */
    function initialize() {
        // This function iterates over the files associated with an item
        // and constructs a url to retrieve each file.  We assume all of
        // the files that match the regular expression are png images.
        function handleItemFiles(fileArray) {
            var itemId = null;
            for (var idx in fileArray) {
                var iFile = fileArray[idx];
                itemId = iFile['itemId'];
                var filename = iFile['name'];
                var fileId = iFile['_id'];
                var match = imgFilePattern.exec(filename);
                if (match.length === 3) {
                    var keystr = match[1] + '_p' + match[2];
                    var url = baseUrl + "file/" + fileId + "/download?token=" + token;
                    if ('imageUrls' in cosmoDatum[itemId]['attributes']) {
                        cosmoDatum[itemId]['attributes']['imageUrls'][keystr] = url;
                    }
                }
            }
            if (itemId !== null) {
                cosmoDataCollection.add(cosmoDatum[itemId]);
            }
        }

        // This function iterates over the returned items, and for each one,
        // sends another Girder request to retrieve the files for the item.
        function handleItems(itemArray) {
            for (var idx in itemArray) {
                // Get files associated with item: /item/{itemId}/files
                var item = itemArray[idx];
                var dataObj = convertItemToCosmoData(item['meta']);
                if (dataObj !== null) {
                    cosmoDatum[item['_id']] = dataObj;
                    makeGirderRequest('GET', 'item/' + item['_id'] + '/files', {}, handleItemFiles);
                }
            }
        }

        // Trigger an asynchronous grab of all the items in the top level folder
        makeGirderRequest('GET',
                          'item/',
                          {'folderId': topLevelFolderId},
                          handleItems);

        // Set up the search button action
        $('.search-button').click(function() {
            var attrName = $('.attr-name-field').val();
            var attrValue = $('.attr-value-field').val();

            if (attrName === '' || attrValue === '') {
                clearSearchFilter();
            } else {
                var minAttrName = 'min_' + attrName;
                var maxAttrName = 'max_' + attrName;
                var value = parseFloat(attrValue);
                console.log('minAttrName: ' + minAttrName + ', maxAttrName: ' +
                            maxAttrName + ', numeric value: ' + value);
                cosmoDataCollection.reset(cosmoDataCollection.filterBySpatialAttr(minAttrName, maxAttrName, attrValue));
            }
        });

        // When clear button is clicked, full results should be shown again
        $('.clear-button').click(function() {
            clearSearchFilter();
        });

        // When an image is loaded into the viewer, it should possibly be centered
        $('.full-size-image').load(moveImageIntoPosition);

        // To start things off, load the overview.png image into the viewer
        overviewPngUrl = baseUrl + "file/52f8fe9d7bee040bfaeee126/download?token=" + token;
        $('.full-size-image').attr('src', overviewPngUrl);

        // As a convenience, if we click the header bar, reload the overview image
        $('.header-bar').click(function() {
            $('.pvweb-iframe').attr('src', '');
            $('.pvweb-iframe-pane').hide();
            $('.full-size-image').attr('src', overviewPngUrl);
        });

        // The search bar was hidden until login was complete, now show it
        $('.cosmo-search-bar').show();

        // This button shows or hides the remote connections listed in the
        // single remote connection folder id for this application.  It also
        // causes the list of remotes to be re-rendered based on the state of
        // the database.
        $('.show-remotes-list-btn').bind('click', function(evt) {
            evt.stopPropagation();
            var selected = $(this).toggleClass("selected").hasClass("selected");
            $('.remote-connection-container').animate({
                left: (selected ? "+=740" : "-=740")
            }, 500, function() { /* Animation complete */ });
            if (selected) {
                updateRemoteConnections();
            }
        }).show();

        // Make sure we have all the remote connections set up in memory when
        // we get started.
        updateRemoteConnections();

        // Click handler for a button on the remote interaction panel
        $('.close-interact-btn').bind('click', function() {
            $('.remote-interact-panel').hide();
            $('.remote-connection-list').show();
            $('.command-entry-field').unbind('keypress');
        });
    }

    /*
     * Clear out the search fields and load all the items into the collection
     * again.
     */
    function clearSearchFilter() {
        $('.attr-name-field').val('');
        $('.attr-value-field').val('');
        cosmoDataCollection.reset();
        for (itemId in cosmoDatum) {
            cosmoDataCollection.add(cosmoDatum[itemId]);
        }
    }

    /*
     * Create and return a new CosmoData given an item returned from Girder
     */
    function convertItemToCosmoData(item) {
        title = null;
        if (item !== null && item !== undefined) {
            var origFile = item['originalFile'];
            if (origFile !== undefined) {
                var titleMatch =  titlePattern.exec(origFile);
                title = titleMatch[1];
            }
        }
        // var magVelUrl = ;
        // var volRenUrl = ;
        if (title !== null) {
            return new CosmoData({
                title: titleMatch[1],
                max_fof_halo_tag: item['max_fof_halo_tag'],
                max_id: item['max_id'],
                max_vel_mag: item['max_vel_mag'],
                max_vx: item['max_vx'],
                max_vy: item['max_vy'],
                max_vz: item['max_vz'],
                max_x: item['max_x'],
                max_y: item['max_y'],
                max_z: item['max_z'],
                min_fof_halo_tag: item['min_fof_halo_tag'],
                min_id: item['min_id'],
                min_vel_mag: item['min_vel_mag'],
                min_vx: item['min_vx'],
                min_vy: item['min_vy'],
                min_vz: item['min_vz'],
                min_x: item['min_x'],
                min_y: item['min_y'],
                min_z: item['min_z'],
                hostname: item['hostname'],
                originalFile: item['originalFile'],
                outputImageDir: item['outputImageDir'],
                velocityMagnitudeVtkFile: item['velocityMagnitudeVtkFile'],
                volumeVtkFile: item['volumeVtkFile'],
                imageUrls: { 'vol_px': '',
                             'pts_px': '',
                             'vol_py': '',
                             'pts_py': '',
                             'vol_pz': '',
                             'pts_pz': '' }
            });
        } else {
            return null;
        }
    }

    /*
     * Convenience function to make a girder request.  This function
     * builds the query string out of the params object, then makes
     * an ajax request to the method and url given.  When the ajax
     * call returns successfully, the successCallback is called with
     * the result.
     */
    function makeGirderRequest(method, path, params, successCallback) {
        // All methods require the token=<token> parameter to be added
        // params['token'] = token;

        // Build the query string from the key value pairs in params
        queryString = ""
        sep = "?"
        for (key in params) {
            queryString += sep + key + "=" + params[key]
            sep = "&"
        }

        // Now make the asynchronous request
        $.ajax({
            type: method,
            url: baseUrl + path + queryString,
            dataType: 'json',
            success: successCallback,
            error: function(result) {
                console.log("Rest request error: method = " + method +
                            ", path = " + path + ", query = " + queryString);
                console.log(result);
            }
        });
    }

    /*
     * This function moves the image into the center of it's container in
     * the dimensions in which the container is larger than the image.
     * Where the image is larger than it's container, it is positioned at
     * the top or left.
     */
    function moveImageIntoPosition() {
        var container = $('.cosmology-image-pane');
        var containerWidth = container.width();
        var containerHeight = container.height();
        var imageElt = $('.full-size-image');
        var imageWidth = imageElt.width();
        var imageHeight = imageElt.height();

        if (containerWidth > imageWidth) {
            imageElt.css('left', ((containerWidth - imageWidth) / 2.0));
        }

        if (containerHeight > imageHeight) {
            imageElt.css('top', ((containerHeight - imageHeight) / 2.0));
        }
    }

    /*
     * When the page has loaded, we first need to authenticate.  If
     * that process completes successfully, we can initialize the
     * application.
     */
    $( document ).ready( function() {
        $('.login-screen').hide();
        $('.cosmo-search-bar').hide();
        $('.ssh-authentication-widget').hide();
        $('.show-remotes-list-btn').hide();
        $('.attr-name-field').val('');
        $('.attr-value-field').val('');
        // $('.title-element').text("Cosmo Test Now Ready");

        $('.authenticate-button').bind('click', function() {
            var name = $('.name-input-field').val();
            var password = $('.password-input-field').val();
            console.log("You entered: " + name + ", " + password);

            pHash = btoa(name + ":" + password);

            $.ajax ({
                type: 'GET',
                url: baseUrl + 'user/authentication',
                dataType: 'json',
                async: false,
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("Authorization", "Basic " + btoa(name + ":" + password));
                },
                success: function (result) {
                    console.log('Authentication succeeded');
                    console.log(result);
                    $('.login-screen').hide();
                    token = result['authToken']['token'];
                    initialize();
                },
                error: function( result ) {
                    console.log("Authentication failed");
                    console.log(result);
                    alert("Authentication failure");
                    $('.login-screen').hide();
                }
            });
        });

        $( window ).resize(moveImageIntoPosition);

        if (token === null) {
            console.log('Showing login screen');
            $('.login-screen').show();
        }
    });
}(jQuery));


text:
  <md-toolbar>

        Sync Kubernetes Tokens to selected cluster

  </md-toolbar>

  <loading-indicator loading="$ctrl.loading || $ctrl.saving"></loading-indicator>

  <md-content layout-padding ng-if="!$ctrl.loading">

      <md-content layout-padding>

          <md-input-container class="md-block">
            Cluster:
            <md-select ng-model="$ctrl.cluster"
              name="cluster"
              required
              placeholder="Select the cluster"
              ng-change="$ctrl.getChangeset()"
              >
              <md-option
                ng-repeat="c in $ctrl.KubernetesClusters.all"
                value="{{c.name}}">
                {{c.name}} ({{c.description}})
              </md-option>
            </md-select>

This is required.

          </md-input-container>

      </md-content>

      <md-content layout-padding ng-if="!$ctrl.loading && $ctrl.changes.length > 0">

Changelog:

        <md-card ng-repeat="c in $ctrl.changes track by c.created_at">
          <md-card-title>
            <md-card-title-text>

                Changed made by: {{c.user_name}}

                Description: {{c.comment}}

                Date: {{c.created_at | date:'EEE MMM d y HH:mm UTC':'UTC'}}

            </md-card-title-text>
          </md-card-title>

        </md-card>

        <md-button
          class="md-primary"
          aria-label="Sync kubernetes tokens"
          ng-disabled="!$ctrl.cluster"
          ng-click="$ctrl.syncTokens($ctrl.cluster, $event)">
          Sync
        </md-button>

      </md-content>

      <md-content layout-padding ng-if="!$ctrl.loading && $ctrl.changes.length == 0">
        <md-card>
          <md-card-title>
            <md-card-title-text>

                There is no changes to be applied since last upload.

            </md-card-title-text>
          </md-card-title>
        </md-card>

        <md-button
          class="md-primary"
          aria-label="Sync kubernetes tokens"
          ng-disabled="!$ctrl.cluster"
          ng-click="$ctrl.syncTokens($ctrl.cluster, $event)">
          Re-sync
        </md-button>
      </md-content>

  </md-content>

redpajama_set_name: RedPajamaGithub


text:
require 'mongoid'

class Synchronization
  include Mongoid::Document

  field :time, type: Time

  field :commit_hash, type: String
  field :commit_time, type: Time
end


text:
#include "thrift/perf/cpp/AsyncLoadHandler2.h"
#include "thrift/perf/cpp/LoadHandler.h"

#include <thrift/lib/cpp2/server/ThriftServer.h>

#include <thrift/lib/cpp/async/TSyncToAsyncProcessor.h>
#include <thrift/lib/cpp/concurrency/ThreadManager.h>
#include <thrift/lib/cpp/concurrency/PosixThreadFactory.h>
#include <thrift/lib/cpp/protocol/TBinaryProtocol.h>
#include <thrift/lib/cpp/protocol/THeaderProtocol.h>
#include <thrift/lib/cpp/transport/TSSLSocket.h>

#include "common/init/Init.h"
#include "common/services/cpp/ServiceFramework.h"

#include <iostream>
#include <signal.h>

using std::cout;
using namespace boost;
using namespace apache::thrift::async;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::test;
using namespace apache::thrift::transport;
using namespace apache::thrift::concurrency;

DEFINE_bool(enable_service_framework, false,
            "Run ServiceFramework to track service stats");
DEFINE_int32(port, 1234, "server port");
DEFINE_int64(num_threads, 4, "number of worker threads");
DEFINE_int64(num_queue_threads, 4, "number of task queue threads");
DEFINE_int32(max_conn_pool_size, 0, "maximum size of idle connection pool");
DEFINE_int32(idle_timeout, 0, "idle timeout (in milliseconds)");
DEFINE_int32(task_timeout, 0, "task timeout (in milliseconds)");
DEFINE_int32(max_connections, 0, "max active connections");
DEFINE_int32(max_requests, 0, "max active requests");
DEFINE_string(cert, "", "SSL certificate file");
DEFINE_string(key, "", "SSL private key file");
DEFINE_bool(queue_sends, true, "Queue sends for better throughput");

void setTunables(ThriftServer* server) {
  if (FLAGS_idle_timeout > 0) {
    server->setIdleTimeout(std::chrono::milliseconds(FLAGS_idle_timeout));
  }
  if (FLAGS_task_timeout > 0) {
    server->setTaskExpireTime(std::chrono::milliseconds(FLAGS_task_timeout));
  }
}

ThriftServer *g_server = nullptr;

void sigHandler(int signo) {
  g_server->stop();
  exit(0);
}

int main(int argc, char* argv[]) {
  facebook::initFacebook(&argc, &argv);

  if (argc != 1) {
    fprintf(stderr, "error: unhandled arguments:");
    for (int n = 1; n < argc; ++n) {
      fprintf(stderr, " %s", argv[n]);
    }
    fprintf(stderr, "\n");
    return 1;
  }

  // Optionally run under ServiceFramework to enable testing stats handlers
  // Once ServiceFramework is running, it will hook any new thrift services that
  // get created, and attach a collect/report their fb303 stats.
  std::unique_ptr<facebook::services::ServiceFramework> fwk;
  if (FLAGS_enable_service_framework) {
    fwk.reset(
        new facebook::services::ServiceFramework("ThriftServer Load Tester"));
    fwk->go(false /* waitUntilStop */);
  }

  auto handler = std::make_shared<AsyncLoadHandler2>();

  std::shared_ptr<ThriftServer> server;
  server.reset(new ThriftServer());
  server->setInterface(handler);
  server->setPort(FLAGS_port);
  server->setNWorkerThreads(FLAGS_num_threads);
  server->setNPoolThreads(FLAGS_num_queue_threads);
  server->setMaxConnections(FLAGS_max_connections);
  server->setMaxRequests(FLAGS_max_requests);
  server->setQueueSends(FLAGS_queue_sends);

  if (FLAGS_cert.length() > 0 && FLAGS_key.length() > 0) {
    std::shared_ptr<folly::SSLContextConfig> sslContext(new folly::SSLContextConfig());
    sslContext->setCertificate(FLAGS_cert.c_str(),
                               FLAGS_key.c_str(),
                              "");
    server->setSSLConfig(sslContext);
  }

  // Set tunable server parameters
  setTunables(server.get());

  g_server = server.get();
  signal(SIGINT, sigHandler);

  cout << "Serving requests on port " << FLAGS_port << "...\n";
  if (FLAGS_enable_service_framework) {
    fwk.reset(
        new facebook::services::ServiceFramework("ThriftServer Load Tester"));
    fwk->addThriftService(server, handler.get(), FLAGS_port);
    fwk->go();
  } else {
    server->serve();
  }

  cout << "Exiting normally" << std::endl;
  fwk->stop();

  return 0;
}


text:
#include "WindowImp.h"

#include <new>
#include <iostream>
#include <boost/version.hpp>
#include <boost/bind.hpp>

#include "BeforeUnloadEventImp.h"
#include "DOMImplementationImp.h"
#include "DocumentImp.h"
#include "KeyboardEventImp.h"
#include "MouseEventImp.h"
#include "NodeImp.h"
#include "css/BoxImage.h"
#include "css/Ico.h"
#include "css/ViewCSSImp.h"
#include "html/HTMLIFrameElementImp.h"
#include "html/HTMLLinkElementImp.h"
#include "html/HTMLScriptElementImp.h"
#include "http/HTTPConnection.h"

#include "Test.util.h"

namespace org { namespace w3c { namespace dom { namespace bootstrap {

WindowImp::Parser::Parser(DocumentImp* document, int fd, const std::string& optionalEncoding) :
    stream(fd, boost::iostreams::never_close_handle),   // TODO: never_close_handle?
    htmlInputStream(stream, optionalEncoding),
    tokenizer(&htmlInputStream),
    parser(document, &tokenizer)
{
    stream.seekg(0, std::ios::beg);
}

WindowImp::WindowImp(WindowImp* parent, ElementImp* frameElement) :
    request(parent ? parent->getLocation().getHref() : u""),
    history(this),
    backgroundTask(this),
    thread(std::ref(backgroundTask)),
    window(0),
    view(0),
    viewFlags(0),
    parent(parent),
    frameElement(frameElement),
    parser(0),
    clickTarget(0),
    detail(0),
    buttons(0),
    scrollWidth(0),
    scrollHeight(0),
    width(816),     // US letter size, 96 DPI
    height(1056),
    redisplay(false),
    zoomable(true),
    zoom(1.0f),
    faviconOverridable(false),
    windowDepth(0)
{
    if (parent) {
        parent->childWindows.push_back(this);
        windowDepth = parent->windowDepth + 1;
    }
}

WindowImp::~WindowImp()
{
    if (parent) {
        for (auto i = parent->childWindows.begin(); i != parent->childWindows.end(); ++i) {
            if (*i == this) {
                parent->childWindows.erase(i);
                break;
            }
        }
    }
    backgroundTask.abort();
    thread.join();
}

void WindowImp::setSize(unsigned w, unsigned h)
{
    if (width != w || height != h) {
        width = w;
        height = h;
        setFlags(Box::NEED_REFLOW);
    }
}

void WindowImp::setFlags(unsigned f)
{
    if (view) {
        view->setFlags(f | viewFlags);
        viewFlags = 0;
    } else
        viewFlags |= f;
}

DocumentWindowPtr WindowImp::activate()
{
    if (window) {
        window->activate(this);
        return window;
    }
    return 0;
}

void WindowImp::enableZoom(bool value)
{
    zoomable = value;
}

float WindowImp::getZoom() const
{
    return zoom;
}

void WindowImp::setZoom(float value)
{
    if (zoomable) {
        zoom = value;
        if (view) {
            view->setZoom(zoom);
            redisplay = true;
        }
    }
}

void WindowImp::updateView(ViewCSSImp* next)
{
    if (!next || view == next || !window || !window->getDocument())
        return;

    unsigned flags = 0;
    if (view) {
        flags |= view->gatherFlags();
        delete view;
    }
    view = next;
    if (viewFlags)
        setFlags(flags | viewFlags);
    view->setZoom(zoom);
    detail = 0;
    redisplay = true;

    if (!view->getTree()) {
        // cf. http://test.csswg.org/suites/css2.1/20110323/html4/root-box-003.htm
        canvas.shutdown();
        canvas.setup(width, height);
        canvas.beginRender(view->getBackgroundColor());
        canvas.endRender();
    }

    if (!parent) {
        std::u16string title = view->getDocument().getTitle();
        setWindowTitle(utfconv(title).c_str());
    }
}

void WindowImp::setDocumentWindow(const DocumentWindowPtr& window)
{
    this->window = window;
    delete view;
    view = 0;
    viewFlags = 0;
    if (window)
        backgroundTask.restart(BackgroundTask::Cascade);
    detail = 0;
    redisplay = true;
    setFavicon();
}

bool WindowImp::isBindingDocumentWindow() const
{
    if (!parent)
        return false;
    DocumentImp* document = dynamic_cast<DocumentImp*>(parent->getDocument().self());
    return document->isBindingDocumentWindow(this);
}

bool WindowImp::poll()
{
    if (!window)
        return false;
    DocumentImp* document = dynamic_cast<DocumentImp*>(window->getDocument().self());

    // Update the canvas before processing events.
    if (request.getReadyState() == HttpRequest::DONE && document && backgroundTask.getState() == BackgroundTask::Done) {
        ViewCSSImp* next = backgroundTask.getView();
        updateView(next);
        if (view && (view->gatherFlags() & Box::NEED_REPAINT)) {
            redisplay = true;
            render(0);
        }
    }

    while (backgroundTask.getState() == BackgroundTask::Done && !eventQueue.empty()) {
        const EventTask task = eventQueue.front();
        switch (task.type) {
        case EventTask::MouseDown:
        case EventTask::MouseUp:
            mouse(task);
            break;
        case EventTask::MouseMove:
            mouseMove(task);
            break;
        case EventTask::KeyDown:
            keydown(task);
            break;
        case EventTask::KeyUp:
            keyup(task);
            break;
        default:
            break;
        }
        eventQueue.pop_front();
    }

    for (auto i = childWindows.begin(); i != childWindows.end(); ++i) {
        WindowImp* child = *i;
        if (child->poll()) {
            redisplay |= true;
            if (view) {
                if (document && document->isBindingDocumentWindow(child))
                    view->setFlags(Box::NEED_SELECTOR_REMATCHING);
                else
                    view->setFlags(Box::NEED_REPAINT);
            }
        }
    }

    switch (request.getReadyState())
    {
    case HttpRequest::UNSENT:
        break;
    case HttpRequest::OPENED:
    case HttpRequest::HEADERS_RECEIVED:
    case HttpRequest::LOADING:
        break;
    case HttpRequest::DONE:
        if (!document) {
            recordTime("%*shttp request done", windowDepth * 2, "");
            // TODO: Check header
            Document newDocument = getDOMImplementation()->createDocument(u"", u"", 0);
            if (document = dynamic_cast<DocumentImp*>(newDocument.self())) {
                // TODO: Fire a simple unload event.
                window->setDocument(newDocument);
                document->setDefaultView(this);
                document->setURL(request.getRequestMessage().getURL());
                if (!request.getError())
                    history.update(window);
                else
                    document->setError(request.getError());
                parser = new(std::nothrow) Parser(document, request.getContentDescriptor(), request.getResponseMessage().getContentCharset());
                if (!parser)
                    break;  // TODO: error handling
            } else
                break;  // TODO: error handling
        }
        if (document->getReadyState() == u"loading") {
            // TODO: Note white it would be nice to parse the HTML docucment in
            // the background task, firstly we need to check if we can run JS
            // in the background.
            activate();

            HTMLScriptElementImp* script = document->getPendingParsingBlockingScript();
            if (script) {
                if (!script->isReadyToBeParserExecuted())
                    break;
                script->execute();
                document->setPendingParsingBlockingScript(0);
            }

            // TODO: run this in the background
            Token token;
            do {
                token = parser->getToken();
                parser->processToken(token);
            } while (token.getType() != Token::Type::EndOfFile && !document->getPendingParsingBlockingScript());
            if (document->getPendingParsingBlockingScript())
                break;
            document->setCharset(utfconv(parser->getEncoding()));

            // TODO: Check if the parser has been aborted.
            NodeImp::evalTree(document);
            document->resetStyleSheets();
            recordTime("%*shtml parsed", windowDepth * 2, "");
            if (4 <= getLogLevel())
                dumpTree(std::cerr, document);
        }
        switch (backgroundTask.getState()) {
        case BackgroundTask::Cascaded:
            HTMLElementImp::xblEnteredDocument(document);
            backgroundTask.wakeUp(BackgroundTask::Layout);
            break;
        case BackgroundTask::Init:
        case BackgroundTask::Done: {
            ViewCSSImp* next = backgroundTask.getView();
            updateView(next);
            if (document->getReadyState() == u"interactive") {
                // TODO: Check if the parser has been aborted.

                // Run from the step 3. of 'stops parsing'.
                // cf. http://www.whatwg.org/specs/web-apps/current-work/multipage/the-end.html#the-end

                // Process scripts that will execute when the document has finished parsing (i.e., defer).
                // TODO: Check there's no style sheet that is blocking scripts.
                if (document->processDeferScripts()) {
                    if (!document->hasContentLoaded()) {
                        if (events::Event event = new(std::nothrow) EventImp) {
                            event.initEvent(u"DOMContentLoaded", true, false);
                            document->dispatchEvent(event);
                        }
                        document->decrementLoadEventDelayCount();
                        document->setContentLoaded();

                        backgroundTask.restart(BackgroundTask::Cascade);
                    }
                }
            }
            if (document->getReadyState() == u"complete") {
            }
            if (view) {
                if (unsigned flags = view->gatherFlags()) {
                    if (flags & Box::NEED_SELECTOR_REMATCHING) {
                        recordTime("%*strigger selector rematching", windowDepth * 2, "");
                        backgroundTask.restart(BackgroundTask::Cascade);
                        view = 0;
                    } else if (flags & Box::NEED_SELECTOR_MATCHING) {
                        recordTime("%*strigger restyling", windowDepth * 2, "");
                        backgroundTask.wakeUp(BackgroundTask::Cascade);
                        view = 0;
                    } else if (flags & (Box::NEED_STYLE_RECALCULATION | Box::NEED_EXPANSION | Box::NEED_CHILD_REFLOW | Box::NEED_REFLOW)) {
                        recordTime("%*strigger reflow", windowDepth * 2, "");
                        backgroundTask.wakeUp(BackgroundTask::Layout);
                        view = 0;
                    } else if (flags & Box::NEED_REPAINT)
                        redisplay = true;
                }
            }
            break;
        }
        default:
            break;
        }
        break;
    default:
        break;
    }
    bool result = redisplay;
    redisplay = false;
    if (!result && view && view->hasExpired(getTick())) {
        view->setFlags(Box::NEED_REPAINT);
        result = true;
    }
    if (result)
        recordTime("%*strigger repaint", windowDepth * 2, "");
    return result;
}

void WindowImp::render(ViewCSSImp* parentView)
{
    recordTime("%*srepaint begin: %s (%s)", windowDepth * 2, "", utfconv(window->getDocument().getReadyState()).c_str(), view ? "render" : "canvas");
    if (view) {
        if (view->gatherFlags() & Box::NEED_REPAINT) {
            view->clearFlags(Box::NEED_REPAINT);
            canvas.shutdown();
            canvas.setup(width, height);
            canvas.beginRender(view->getBackgroundColor());
            view->render(parentView ? parentView->getClipCount() : 0);
            scrollWidth = view->getScrollWidth();
            scrollHeight = view->getScrollHeight();
            canvas.endRender();
        }
        if (2 <= getLogLevel() && backgroundTask.isIdle() && !view->gatherFlags()) {
            unsigned depth = 1;
            for (WindowImp* w = this; w->parent; w = w->parent)
                ++depth;
            std::cout << "\n## " << window->getDocument().getReadyState();
            if (1 < depth)
                std::cout << " (" << depth << ')';
            std::cout << '\n';
            view->dump();
            std::cout << "##\n";
            std::cout.flush();
        }
    }
    canvas.render(width, height);
    recordTime("%*srepaint end", windowDepth * 2, "");
}

void WindowImp::mouse(int button, int up, int x, int y, int modifiers)
{
    eventQueue.emplace_back(up ? EventTask::MouseUp : EventTask::MouseDown, modifiers, x, y, button);
}

void WindowImp::mouseMove(int x, int y, int modifiers)
{
    if (!eventQueue.empty()) {
        EventTask& back = eventQueue.back();
        if (back.type == EventTask::MouseMove) {
            back.x = x;
            back.y = y;
            back.modifiers = modifiers;
            return;
        }
    }
    eventQueue.emplace_back(EventTask::MouseMove, modifiers, x, y);
}

void WindowImp::keydown(unsigned charCode, unsigned keyCode, int modifiers)
{
    eventQueue.emplace_back(EventTask::KeyDown, modifiers, charCode, keyCode);
}

void WindowImp::keyup(unsigned charCode, unsigned keyCode, int modifiers)
{
    eventQueue.emplace_back(EventTask::KeyUp, modifiers, charCode, keyCode);
}

void WindowImp::mouse(const EventTask& task)
{
    int button = task.button;
    int up = (task.type == task.MouseUp) ? true : false;
    int x = task.x;
    int y = task.y;
    int modifiers = task.modifiers;

    if (!view)
        return;

    recordTime("%*smouse (%d, %d)", windowDepth * 2, "", x, y);

    int shift = button;
    if (shift == 1)
        shift = 2;
    else if (shift == 2)
        shift = 1;
    if (up)
        buttons &= ~(1u << shift);
    else
        buttons |= (1u << shift);

    events::MouseEvent event(0);
    MouseEventImp* imp = 0;

    Box* box = view->boxFromPoint(x, y);
    if (!box)
        return;
    if (WindowImp* childWindow = box->getChildWindow()) {
        childWindow->mouse(button, up,
                           x - box->getX() - box->getBlankLeft(), y - box->getY() - box->getBlankTop(),
                           modifiers);
    }

    Element target = Box::getContainingElement(box->getTargetNode());

    // mousedown, mousemove
    if (imp = new(std::nothrow) MouseEventImp) {
        event = imp;
        if (!up) {
            clickTarget = target;
            ++detail;
        }
        imp->initMouseEvent(up ? u"mouseup" : u"mousedown",
                            true, true, this, detail, x, y, x, y,
                            modifiers & 2, modifiers & 4, modifiers & 1, false, button, 0);
        imp->setButtons(buttons);
        target.dispatchEvent(event);
    }

    if (!up || detail == 0)
        return;
    Box* clickBox = view->boxFromPoint(x, y);
    if (box != clickBox)
        return;

    // click
    if (imp = new(std::nothrow) MouseEventImp) {
        event = imp;
        imp->initMouseEvent(u"click",
                            true, true, this, detail, x, y, x, y,
                            modifiers & 2, modifiers & 4, modifiers & 1, false, button, 0);
        imp->setButtons(buttons);
        target.dispatchEvent(event);
    }
}

void WindowImp::mouseMove(const EventTask& task)
{
    int x = task.x;
    int y = task.y;
    int modifiers = task.modifiers;

    if (!view)
        return;
    Box* box = view->boxFromPoint(x, y);
    if (!box)
        return;
    if (WindowImp* childWindow = box->getChildWindow()) {
        childWindow->mouseMove(x - box->getX() - box->getBlankLeft(),
                               y - box->getY() - box->getBlankTop(),
                               modifiers);
    }

    Element target = Box::getContainingElement(box->getTargetNode());
    view->setHovered(target);

    // mousemove
    events::MouseEvent event(0);
    MouseEventImp* imp = 0;
    if (imp = new(std::nothrow) MouseEventImp) {
        event = imp;
        if (target != clickTarget)
            detail = 0;
        imp->initMouseEvent(u"mousemove",
                            true, true, this, detail, x, y, x, y,
                            modifiers & 2, modifiers & 4, modifiers & 1, false, 0, 0);
        imp->setButtons(buttons);
        target.dispatchEvent(event);
    }
}

void WindowImp::keydown(const EventTask& task)
{
    unsigned charCode = task.charCode;
    unsigned keyCode = task.keyCode;
    int modifiers = task.modifiers;

    Document document = window->getDocument();
    if (!document)
        return;
    Element e = document.getActiveElement();
    if (!e)
        return;

    if (auto iframe = dynamic_cast<HTMLIFrameElementImp*>(e.self())) {
        if (auto child = dynamic_cast<WindowImp*>(iframe->getContentWindow().self()))
            child->keydown(charCode, keyCode, modifiers);
    }

    KeyboardEventImp* imp = new(std::nothrow) KeyboardEventImp(modifiers, charCode, keyCode, 0);
    events::KeyboardEvent event = imp;
    imp->initKeyboardEvent(u"keydown", true, true, this,
                           u"", u"", 0, u"", false, u"");
    e.dispatchEvent(event);

    if (!charCode)
        return;
    imp = new(std::nothrow) KeyboardEventImp(modifiers, charCode, keyCode, 0);
    event = imp;
    imp->initKeyboardEvent(u"keypress", true, true, this,
                           u"", u"", 0, u"", false, u"");
    e.dispatchEvent(event);
}

void WindowImp::keyup(const EventTask& task)
{
    unsigned charCode = task.charCode;
    unsigned keyCode = task.keyCode;
    int modifiers = task.modifiers;

    Document document = window->getDocument();
    if (!document)
        return;
    Element e = document.getActiveElement();
    if (!e)
        return;

    if (auto iframe = dynamic_cast<HTMLIFrameElementImp*>(e.self())) {
        if (auto child = dynamic_cast<WindowImp*>(iframe->getContentWindow().self()))
            child->keyup(charCode, keyCode, modifiers);
    }

    KeyboardEventImp* imp = new(std::nothrow) KeyboardEventImp(modifiers, charCode, keyCode, 0);
    events::KeyboardEvent event(imp);
    imp->initKeyboardEvent(u"keyup", true, true, this,
                           u"", u"", 0, u"", false, u"");
    e.dispatchEvent(event);
}

void WindowImp::setFavicon(IcoImage* ico, std::FILE* file)
{
    if (parent) {
        if (parent->getFaviconOverridable())
            parent->setFavicon(ico, file);
        return;
    }
    for (size_t i = 0; i < ico->getPlaneCount(); ++i) {
        const IconDirectoryEntry& ent(ico->getEntry(i));
        if (BoxImage* image = ico->open(file, i)) {
            uint32_t* pixels = reinterpret_cast<uint32_t*>(image->getPixels());
            setIcon(i, ent.getWidth(), ent.getHeight(), pixels);
            delete image;
        }
    }
}

void WindowImp::setFavicon(BoxImage* image)
{
    if (parent) {
        if (parent->getFaviconOverridable())
            parent->setFavicon(image);
        return;
    }
    uint32_t* pixels = reinterpret_cast<uint32_t*>(image->getPixels());
    setIcon(0, image->getNaturalWidth(), image->getNaturalHeight(), pixels);
}

void WindowImp::setFavicon()
{
    for (WindowImp* w = this; w; w = w->parent) {
        if (w->parent && !w->parent->getFaviconOverridable())
            return;
        if (!w->window)
            continue;
        DocumentImp* document = dynamic_cast<DocumentImp*>(w->window->getDocument().self());
        if (!document)
            continue;
        html::HTMLHeadElement head = document->getHead();
        if (!head)
            continue;
        for (auto i = head.getFirstElementChild(); i; i = i.getNextElementSibling()) {
            if (i.getTagName() == u"link") {
                if (auto link = dynamic_cast<HTMLLinkElementImp*>(i.self())) {
                    if (link->setFavicon(document))
                        return;
                }
            }
        }
    }
}

//
// CSSOM View support operations
//

Element WindowImp::elementFromPoint(float x, float y)
{
    if (!view)
        return 0;
    if (x < 0.0f || width < x || y < 0.0f || height < y)
        return 0;
    Box* box = view->boxFromPoint(x, y);
    if (!box)
        return 0;
    for (Node node = box->getTargetNode(); node; node = node.getParentNode()) {
        if (node.getNodeType() == Node::ELEMENT_NODE)
            return interface_cast<Element>(node);
    }
    return 0;
}

//
// html::Window - implemented
//

html::Window WindowImp::getWindow()
{
    return this;
}

html::Window WindowImp::getSelf()
{
    return this;
}

Document WindowImp::getDocument()
{
    return !window ? 0 : window->getDocument();
}

html::Location WindowImp::getLocation()
{
    return getDocument().getLocation();
}

void WindowImp::setLocation(const std::u16string& href)
{
    getLocation().setHref(href);
}

html::History WindowImp::getHistory()
{
    return &history;
}

Any WindowImp::getFrames()
{
    return this;
}

Any WindowImp::getLength()
{
    return childWindows.size();
}

html::Window WindowImp::getTop()
{
    WindowImp* top = this;
    while (top->parent)
        top = top->parent;
    return top;
}

html::Window WindowImp::getParent()
{
    return parent;
}

html::Window WindowImp::open(const std::u16string& url, const std::u16string& target, const std::u16string& features, bool replace)
{
    if (window) {
        if (DocumentImp* document = dynamic_cast<DocumentImp*>(window->getDocument().self())) {
            URL base(document->getDocumentURI());
            URL link(base, url);
            if (base.isSameExceptFragments(link)) {
                // cf. http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html#scroll-to-fragid
                // TODO: update history, etc.
                std::u16string hash = link.getHash();
                if (hash[0] == '#')
                    hash.erase(0, 1);
                if (Element element = document->getElementById(hash))
                    element.scrollIntoView(true);
                return this;
            }

            // Prompt to unload the Document object.
            if (html::BeforeUnloadEvent event = new(std::nothrow) BeforeUnloadEventImp) {
                window->dispatchEvent(event);
                if (!event.getReturnValue().empty() || event.getDefaultPrevented())
                    return this;
                if (parent && parent->getFaviconOverridable())
                    parent->setFavicon();
            }
        }
    }

    backgroundTask.restart();

    // TODO: add more details
    window = new(std::nothrow) DocumentWindow;

    request.abort();
    history.setReplace(replace);
    request.open(u"get", url.empty() ? u"about:blank" : url);
    request.send();
    return this;
}

html::Window WindowImp::getElement(unsigned int index)
{
    if (index < childWindows.size())
        return childWindows[index];
    return 0;
}

void WindowImp::alert(const std::u16string& message)
{
    std::cerr << message << '\n';
}

//
// html::Window - just generated
//

std::u16string WindowImp::getName()
{
    // TODO: implement me!
    return u"";
}

void WindowImp::setName(const std::u16string& name)
{
    // TODO: implement me!
}

html::UndoManager WindowImp::getUndoManager()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

Any WindowImp::getLocationbar()
{
    // TODO: implement me!
    return 0;
}

void WindowImp::setLocationbar(Any locationbar)
{
    // TODO: implement me!
}

Any WindowImp::getMenubar()
{
    // TODO: implement me!
    return 0;
}

void WindowImp::setMenubar(Any menubar)
{
    // TODO: implement me!
}

Any WindowImp::getPersonalbar()
{
    // TODO: implement me!
    return 0;
}

void WindowImp::setPersonalbar(Any personalbar)
{
    // TODO: implement me!
}

Any WindowImp::getScrollbars()
{
    // TODO: implement me!
    return 0;
}

void WindowImp::setScrollbars(Any scrollbars)
{
    // TODO: implement me!
}

Any WindowImp::getStatusbar()
{
    // TODO: implement me!
    return 0;
}

void WindowImp::setStatusbar(Any statusbar)
{
    // TODO: implement me!
}

Any WindowImp::getToolbar()
{
    // TODO: implement me!
    return 0;
}

void WindowImp::setToolbar(Any toolbar)
{
    // TODO: implement me!
}

std::u16string WindowImp::getStatus()
{
    // TODO: implement me!
    return u"";
}

void WindowImp::setStatus(const std::u16string& status)
{
    // TODO: implement me!
}

void WindowImp::close()
{
    // TODO: implement me!
}

void WindowImp::stop()
{
    // TODO: implement me!
}

void WindowImp::focus()
{
    // TODO: implement me!
}

void WindowImp::blur()
{
    // TODO: implement me!
}

void WindowImp::setFrames(Any frames)
{
    // TODO: implement me!
}

void WindowImp::setLength(Any length)
{
    // TODO: implement me!
}

html::Window WindowImp::getOpener()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOpener(html::Window opener)
{
    // TODO: implement me!
}

Element WindowImp::getFrameElement()
{

    // TODO: implement me!
    return static_cast<Object*>(0);
}

Any WindowImp::getElement(const std::u16string& name)
{
    // TODO: implement me!
    return 0;
}

void WindowImp::setElement(const std::u16string& name, Any value)
{
    // TODO: implement me!
}

html::Navigator WindowImp::getNavigator()
{
    return &navigator;
}

html::External WindowImp::getExternal()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

html::ApplicationCache WindowImp::getApplicationCache()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

bool WindowImp::confirm(const std::u16string& message)
{
    // TODO: implement me!
    return 0;
}

Nullable<std::u16string> WindowImp::prompt(const std::u16string& message)
{
    // TODO: implement me!
    return u"";
}

Nullable<std::u16string> WindowImp::prompt(const std::u16string& message, const std::u16string& _default)
{
    // TODO: implement me!
    return u"";
}

void WindowImp::print()
{
    // TODO: implement me!
}

Any WindowImp::showModalDialog(const std::u16string& url)
{
    // TODO: implement me!
    return 0;
}

Any WindowImp::showModalDialog(const std::u16string& url, Any argument)
{
    // TODO: implement me!
    return 0;
}

void WindowImp::postMessage(Any message, const std::u16string& targetOrigin)
{
    // TODO: implement me!
}

void WindowImp::postMessage(Any message, const std::u16string& targetOrigin, Sequence<html::Transferable> transfer)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnabort()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnabort(html::Function onabort)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnafterprint()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnafterprint(html::Function onafterprint)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnbeforeprint()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnbeforeprint(html::Function onbeforeprint)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnbeforeunload()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnbeforeunload(html::Function onbeforeunload)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnblur()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnblur(html::Function onblur)
{
    // TODO: implement me!
}

html::Function WindowImp::getOncanplay()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOncanplay(html::Function oncanplay)
{
    // TODO: implement me!
}

html::Function WindowImp::getOncanplaythrough()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOncanplaythrough(html::Function oncanplaythrough)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnchange()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnchange(html::Function onchange)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnclick()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnclick(html::Function onclick)
{
    // TODO: implement me!
}

html::Function WindowImp::getOncontextmenu()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOncontextmenu(html::Function oncontextmenu)
{
    // TODO: implement me!
}

html::Function WindowImp::getOncuechange()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOncuechange(html::Function oncuechange)
{
    // TODO: implement me!
}

html::Function WindowImp::getOndblclick()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOndblclick(html::Function ondblclick)
{
    // TODO: implement me!
}

html::Function WindowImp::getOndrag()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOndrag(html::Function ondrag)
{
    // TODO: implement me!
}

html::Function WindowImp::getOndragend()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOndragend(html::Function ondragend)
{
    // TODO: implement me!
}

html::Function WindowImp::getOndragenter()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOndragenter(html::Function ondragenter)
{
    // TODO: implement me!
}

html::Function WindowImp::getOndragleave()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOndragleave(html::Function ondragleave)
{
    // TODO: implement me!
}

html::Function WindowImp::getOndragover()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOndragover(html::Function ondragover)
{
    // TODO: implement me!
}

html::Function WindowImp::getOndragstart()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOndragstart(html::Function ondragstart)
{
    // TODO: implement me!
}

html::Function WindowImp::getOndrop()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOndrop(html::Function ondrop)
{
    // TODO: implement me!
}

html::Function WindowImp::getOndurationchange()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOndurationchange(html::Function ondurationchange)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnemptied()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnemptied(html::Function onemptied)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnended()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnended(html::Function onended)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnerror()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnerror(html::Function onerror)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnfocus()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnfocus(html::Function onfocus)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnhashchange()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnhashchange(html::Function onhashchange)
{
    // TODO: implement me!
}

html::Function WindowImp::getOninput()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOninput(html::Function oninput)
{
    // TODO: implement me!
}

html::Function WindowImp::getOninvalid()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOninvalid(html::Function oninvalid)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnkeydown()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnkeydown(html::Function onkeydown)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnkeypress()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnkeypress(html::Function onkeypress)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnkeyup()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnkeyup(html::Function onkeyup)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnload()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnload(html::Function onload)
{
    if (!window)
        return;
    window->addEventListener(u"load",
                             new(std::nothrow) EventListenerImp(boost::bind(&ECMAScriptContext::dispatchEvent, window->getContext(), onload, _1)));
}

html::Function WindowImp::getOnloadeddata()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnloadeddata(html::Function onloadeddata)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnloadedmetadata()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnloadedmetadata(html::Function onloadedmetadata)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnloadstart()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnloadstart(html::Function onloadstart)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnmessage()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnmessage(html::Function onmessage)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnmousedown()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnmousedown(html::Function onmousedown)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnmousemove()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnmousemove(html::Function onmousemove)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnmouseout()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnmouseout(html::Function onmouseout)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnmouseover()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnmouseover(html::Function onmouseover)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnmouseup()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnmouseup(html::Function onmouseup)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnmousewheel()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnmousewheel(html::Function onmousewheel)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnoffline()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnoffline(html::Function onoffline)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnonline()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnonline(html::Function ononline)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnpause()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnpause(html::Function onpause)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnplay()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnplay(html::Function onplay)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnplaying()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnplaying(html::Function onplaying)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnpagehide()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnpagehide(html::Function onpagehide)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnpageshow()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnpageshow(html::Function onpageshow)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnpopstate()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnpopstate(html::Function onpopstate)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnprogress()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnprogress(html::Function onprogress)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnratechange()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnratechange(html::Function onratechange)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnreadystatechange()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnreadystatechange(html::Function onreadystatechange)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnredo()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnredo(html::Function onredo)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnreset()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnreset(html::Function onreset)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnresize()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnresize(html::Function onresize)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnscroll()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnscroll(html::Function onscroll)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnseeked()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnseeked(html::Function onseeked)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnseeking()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnseeking(html::Function onseeking)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnselect()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnselect(html::Function onselect)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnshow()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnshow(html::Function onshow)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnstalled()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnstalled(html::Function onstalled)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnstorage()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnstorage(html::Function onstorage)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnsubmit()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnsubmit(html::Function onsubmit)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnsuspend()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnsuspend(html::Function onsuspend)
{
    // TODO: implement me!
}

html::Function WindowImp::getOntimeupdate()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOntimeupdate(html::Function ontimeupdate)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnundo()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnundo(html::Function onundo)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnunload()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnunload(html::Function onunload)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnvolumechange()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnvolumechange(html::Function onvolumechange)
{
    // TODO: implement me!
}

html::Function WindowImp::getOnwaiting()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void WindowImp::setOnwaiting(html::Function onwaiting)
{
    // TODO: implement me!
}

css::CSSStyleDeclaration WindowImp::getComputedStyle(Element elt)
{
    if (!view)
        return 0;
    return view->getStyle(elt);
}

css::CSSStyleDeclaration WindowImp::getComputedStyle(Element elt, const std::u16string& pseudoElt)
{
    if (!view)
        return 0;
    return view->getStyle(elt, pseudoElt);
}

html::MediaQueryList WindowImp::matchMedia(const std::u16string& media_query_list)
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

html::Screen WindowImp::getScreen()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

int WindowImp::getInnerWidth()
{
    return width;
}

int WindowImp::getInnerHeight()
{
    return height;
}

int WindowImp::getScrollX()
{
    return window->getScrollX();
}

int WindowImp::getPageXOffset()
{
    return getScrollX();
}

int WindowImp::getScrollY()
{
    return window->getScrollY();
}

int WindowImp::getPageYOffset()
{
    return getScrollY();
}

void WindowImp::scroll(int x, int y)
{
    if (!view)
        return;

    float overflow = getScrollWidth() - width;
    x = std::max(0, std::min(x, static_cast<int>(overflow)));

    overflow = getScrollHeight() - height;
    y = std::max(0, std::min(y, static_cast<int>(overflow)));

    window->scroll(x, y);
    view->setFlags(Box::NEED_REPAINT);
}

void WindowImp::scrollTo(int x, int y)
{
    window->scroll(x, y);
}

void WindowImp::scrollBy(int x, int y)
{
    scroll(getScrollX() + x, getScrollY() + y);
}

int WindowImp::getScreenX()
{
    // TODO: implement me!
    return 0;
}

int WindowImp::getScreenY()
{
    // TODO: implement me!
    return 0;
}

int WindowImp::getOuterWidth()
{
    // TODO: implement me!
    return 0;
}

int WindowImp::getOuterHeight()
{
    // TODO: implement me!
    return 0;
}

void WindowImp::addEventListener(const std::u16string& type, events::EventListener listener, bool capture)
{
    if (window)
        window->addEventListener(type, listener, capture);
}

void WindowImp::removeEventListener(const std::u16string& type, events::EventListener listener, bool capture)
{
    if (window)
        window->removeEventListener(type, listener, capture);
}

bool WindowImp::dispatchEvent(events::Event event)
{
    if (window)
        return window->dispatchEvent(event);
    return false;
}

std::u16string WindowImp::btoa(const std::u16string& btoa)
{
    // TODO: implement me!
    return u"";
}

std::u16string WindowImp::atob(const std::u16string& atob)
{
    // TODO: implement me!
    return u"";
}

int WindowImp::setTimeout(Any handler)
{
    // TODO: implement me!
    return 0;
}

int WindowImp::setTimeout(Any handler, Any timeout, Variadic<Any> args)
{
    // TODO: implement me!
    return 0;
}

void WindowImp::clearTimeout(int handle)
{
    // TODO: implement me!
}

int WindowImp::setInterval(Any handler)
{
    // TODO: implement me!
    return 0;
}

int WindowImp::setInterval(Any handler, Any timeout, Variadic<Any> args)
{
    // TODO: implement me!
    return 0;
}

void WindowImp::clearInterval(int handle)
{
    // TODO: implement me!
}

}}}}  // org::w3c::dom::bootstrap


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>JobStatusImplementation (xenon-2.3.0 2.5.0 API for Xenon developers)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

nl.esciencecenter.xenon.adaptors.schedulers

Class JobStatusImplementation

java.lang.Object

nl.esciencecenter.xenon.adaptors.schedulers.JobStatusImplementation

All Implemented Interfaces:

JobStatus

public class JobStatusImplementation
extends java.lang.Object
implements JobStatus

JobStatus contains status information for a specific job.

Since:

1.0

Field Summary

Fields

Modifier and Type
Field and Description

private boolean
done

private XenonException
exception

private java.lang.Integer
exitCode

private java.lang.String
jobIdentifier

private java.lang.String
name

private boolean
running

private java.util.Map<java.lang.String,java.lang.String>
schedulerSpecificInformation

private java.lang.String
state

Constructor Summary

Constructors

Constructor and Description

JobStatusImplementation(java.lang.String jobIdentifier,
                       java.lang.String name,
                       java.lang.String state,
                       java.lang.Integer exitCode,
                       XenonException exception,
                       boolean running,
                       boolean done,
                       java.util.Map<java.lang.String,java.lang.String> schedulerSpecificInformation)

Create a JobStatus.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

boolean
equals(java.lang.Object o)

XenonException
getException()

Get the exception produced by the Job or while retrieving the status.

java.lang.Integer
getExitCode()

Get the exit code for the Job.

java.lang.String
getJobIdentifier()

Get the job identifier of the Job for which this JobStatus was created.

java.lang.String
getName()

Get the name of the Job for which this JobStatus was created.

java.util.Map<java.lang.String,java.lang.String>
getSchedulerSpecificInformation()

Get scheduler specific information on the Job.

java.lang.String
getState()

Get the state of the Job.

boolean
hasException()

Has the Job or job retrieval produced a exception ?

int
hashCode()

boolean
isDone()

Is the Job done.

boolean
isRunning()

Is the Job running.

void
maybeThrowException()

Throws the exception produced by the Job or while retrieving the status, if it exists.

java.lang.String
toString()

Methods inherited from class java.lang.Object

clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Field Detail

jobIdentifier

private final java.lang.String jobIdentifier

name

private final java.lang.String name

state

private final java.lang.String state

exitCode

private final java.lang.Integer exitCode

exception

private final XenonException exception

running

private final boolean running

done

private final boolean done

schedulerSpecificInformation

private final java.util.Map<java.lang.String,java.lang.String> schedulerSpecificInformation

Constructor Detail

JobStatusImplementation

public JobStatusImplementation(java.lang.String jobIdentifier,
                               java.lang.String name,
                               java.lang.String state,
                               java.lang.Integer exitCode,
                               XenonException exception,
                               boolean running,
                               boolean done,
                               java.util.Map<java.lang.String,java.lang.String> schedulerSpecificInformation)

Create a JobStatus.

Parameters:

jobIdentifier - the identifier of the job for which this status was created.

name - the name of the job for which this status was created.

state - the state of the Job at the time this status was created.

exitCode - the exit code of the Job (if the jobs has finished).

exception - the exception produced when running Job (if the jobs has failed).

running - is the Job running ?

done - is the Job finished ?

schedulerSpecificInformation - a map of scheduler implementation specific information on the job.

Method Detail

getJobIdentifier

public java.lang.String getJobIdentifier()

Get the job identifier of the Job for which this JobStatus was created.

Specified by:

getJobIdentifier in interface JobStatus

Returns:

the Job.

getName

public java.lang.String getName()

Get the name of the Job for which this JobStatus was created.

Specified by:

getName in interface JobStatus

Returns:

the Job.

getState

public java.lang.String getState()

Get the state of the Job.

Specified by:

getState in interface JobStatus

Returns:

the state of the Job.

getExitCode

public java.lang.Integer getExitCode()

Get the exit code for the Job.

Specified by:

getExitCode in interface JobStatus

Returns:

the exit code for the Job.

getException

public XenonException getException()

Get the exception produced by the Job or while retrieving the status. If a job was canceled, will return a JobCanceledException.

Specified by:

getException in interface JobStatus

Returns:

the exception.

maybeThrowException

public void maybeThrowException()
                         throws XenonException

Description copied from interface: JobStatus

Throws the exception produced by the Job or while retrieving the status, if it exists. Otherwise continue.

Specified by:

maybeThrowException in interface JobStatus

Throws:

JobCanceledException - if the job was cancelled

NoSuchJobException - if the job of which the status was requested does not exist

XenonException - if an I/O error occurred.

isRunning

public boolean isRunning()

Is the Job running.

Specified by:

isRunning in interface JobStatus

Returns:

if the Job is running.

isDone

public boolean isDone()

Is the Job done.

Specified by:

isDone in interface JobStatus

Returns:

if the Job is done.

hasException

public boolean hasException()

Has the Job or job retrieval produced a exception ?

Specified by:

hasException in interface JobStatus

Returns:

if the Job has an exception.

getSchedulerSpecificInformation

public java.util.Map<java.lang.String,java.lang.String> getSchedulerSpecificInformation()

Get scheduler specific information on the Job.

Specified by:

getSchedulerSpecificInformation in interface JobStatus

Returns:

scheduler specific information on the Job.

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

equals

public boolean equals(java.lang.Object o)

Overrides:

equals in class java.lang.Object

hashCode

public int hashCode()

Overrides:

hashCode in class java.lang.Object

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method