<commit_before>/*
 * Copyright 2019 The CodeWorld Authors. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

window.openProjectName = '';
window.lastXML = '';

// This will get bound in Haskell to a function that runs the program
window.runFunc = null;

// Helper functions /////////////////////////////////////////////////

function loadSample(code) {
    if (isEditorClean()) sweetAlert.close();
    warnIfUnsaved(() => {
        loadWorkspace(code);
    }, false);
}

function loadWorkspace(text) {
    const workspace = Blockly.mainWorkspace;
    workspace.clear();
    const xmldom = Blockly.Xml.textToDom(text);
    Blockly.Xml.domToWorkspace(xmldom, workspace);
    window.lastXML = text;
}

function loadXmlHash(hash, autostart) {
    sendHttp('GET', `loadXML?hash=${hash}&mode=blocklyXML`, null, request => {
        if (request.status === 200) {
            loadWorkspace(request.responseText);
            if (autostart) {
                if (runFunc) runFunc();
            }
        }
    });
}

function init() {
    Alert.init().then(Auth.init).then(() => {
        window.nestedDirs = [''];
        window.allProjectNames = [
            []
        ];
        window.allFolderNames = [
            []
        ];
        window.lastXML = null;
        window.showingResult = false;
        window.buildMode = 'codeworld';

        let hash = location.hash.slice(1);
        if (hash.length > 0) {
            if (hash.slice(-2) === '==') {
                hash = hash.slice(0, -2);
            }
            if (hash[0] === 'F') {
                sweetAlert({
                    title: Alert.title('Save As', 'mdi-cloud-upload'),
                    html: 'Enter a name for the shared folder:',
                    input: 'text',
                    confirmButtonText: 'Save',
                    showCancelButton: false,
                    closeOnConfirm: false
                }).then(result => {
                    if (!result) {
                        return;
                    }

                    const data = new FormData();
                    data.append('mode', 'blocklyXML');
                    data.append('shash', hash);
                    data.append('name', result.value);

                    sendHttp('POST', 'shareContent', data,
                        request => {
                            window.location.hash = '';
                            if (request.status === 200) {
                                sweetAlert('Success!',
                                    'The shared folder is moved into your root directory.',
                                    'success');
                            } else {
                                sweetAlert('Oops!',
                                    'Could not load the shared directory. Please try again.',
                                    'error');
                            }
                            initCodeworld();
                            discoverProjects('', 0);
                            updateUI();
                        });
                });
            } else {
                initCodeworld();
                loadXmlHash(hash, true);
            }
        } else {
            initCodeworld();
        }
    });
}

function initCodeworld() {
    window.codeworldKeywords = {};
    registerStandardHints(() => {});

    window.onbeforeunload = event => {
        if (containsUnsavedChanges()) {
            const msg = 'There are unsaved changes to your project. ' +
                'If you continue, they will be lost!';
            if (event) event.returnValue = msg;
            return msg;
        }
    };
}

function getCurrentProject() {
    return {
        'name': window.openProjectName || 'Untitled',
        'source': getWorkspaceXMLText(),
        'history': ''
    };
}

// Sets the generated code
function updateEditor(code) {
    const editor = document.getElementById('genCode');
    CodeMirror.runMode(code, {
        name: 'codeworld',
        overrideKeywords: codeworldKeywords
    }, editor);
}

function run(xmlHash, codeHash, msg, error, dhash) {
    const hash = codeHash;

    if (hash) {
        window.location.hash = `#${xmlHash}`;
        document.getElementById('shareButton').style.display = '';
        document.getElementById('shareFolderButton').style.display = 'none';
    } else {
        window.location.hash = '';
        document.getElementById('shareButton').style.display = 'none';
        document.getElementById('shareFolderButton').style.display = '';
    }

    window.showingResult = hash || msg;

    if (window.showingResult) {
        window.showingDoc = false;
    }

    const runner = document.getElementById('runner');
    if (hash && !error) {
        const loc = `run.html?hash=${hash}&mode=${window.buildMode}`;
        runner.contentWindow.location.replace(loc);
        document.getElementById('runner').style.display = '';
        document.getElementById('runner').contentWindow.focus();
        document.getElementById('message').style.display = 'none';
        window.programRunning = true;
    } else {
        document.getElementById('message').style.display = '';
        runner.contentWindow.location.replace('about:blank');
        document.getElementById('runner').style.display = 'none';
        window.programRunning = false;
    }
    if (!hash && !error && !msg) { // We stopped, don't show message window
        document.getElementById('message').style.display = 'none';
    }

    if (msg) {
        const message = document.getElementById('message');
        let type = "error";
        message.innerHTML = '';
        if (error) {
            type = "error";
        } else {
            type = "log";
        }
        printMessage(type, msg);
    }

    document.getElementById('editButton').setAttribute('href', `/#${codeHash}`);
    window.deployHash = dhash;
    cancelMove();
    updateUI();
}

function removeErrors() {
    $('.blocklyDraggable').removeClass('blocklyErrorSelected');
    const blocks = Blockly.getMainWorkspace().getAllBlocks();

    blocks.forEach(block => {
        block.removeErrorSelect();
    });
}

function getWorkspaceXMLText() {
    const workspace = Blockly.getMainWorkspace();
    const xml = Blockly.Xml.workspaceToDom(workspace);
    const xml_text = Blockly.Xml.domToText(xml);
    return xml_text;
}

function containsUnsavedChanges() {
    const blank = '<xml xmlns="http://www.w3.org/1999/xhtml"></xml>';<commit_msg>Shorten some code in funblocks, and eliminate a warning about extraneous initialization.<commit_after>/*
 * Copyright 2019 The CodeWorld Authors. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

window.openProjectName = '';
window.lastXML = '';

// This will get bound in Haskell to a function that runs the program
window.runFunc = null;

// Helper functions /////////////////////////////////////////////////

function loadSample(code) {
    if (isEditorClean()) sweetAlert.close();
    warnIfUnsaved(() => {
        loadWorkspace(code);
    }, false);
}

function loadWorkspace(text) {
    const workspace = Blockly.mainWorkspace;
    workspace.clear();
    const xmldom = Blockly.Xml.textToDom(text);
    Blockly.Xml.domToWorkspace(xmldom, workspace);
    window.lastXML = text;
}

function loadXmlHash(hash, autostart) {
    sendHttp('GET', `loadXML?hash=${hash}&mode=blocklyXML`, null, request => {
        if (request.status === 200) {
            loadWorkspace(request.responseText);
            if (autostart) {
                if (runFunc) runFunc();
            }
        }
    });
}

function init() {
    Alert.init().then(Auth.init).then(() => {
        window.nestedDirs = [''];
        window.allProjectNames = [
            []
        ];
        window.allFolderNames = [
            []
        ];
        window.lastXML = null;
        window.showingResult = false;
        window.buildMode = 'codeworld';

        let hash = location.hash.slice(1);
        if (hash.length > 0) {
            if (hash.slice(-2) === '==') {
                hash = hash.slice(0, -2);
            }
            if (hash[0] === 'F') {
                sweetAlert({
                    title: Alert.title('Save As', 'mdi-cloud-upload'),
                    html: 'Enter a name for the shared folder:',
                    input: 'text',
                    confirmButtonText: 'Save',
                    showCancelButton: false,
                    closeOnConfirm: false
                }).then(result => {
                    if (!result) {
                        return;
                    }

                    const data = new FormData();
                    data.append('mode', 'blocklyXML');
                    data.append('shash', hash);
                    data.append('name', result.value);

                    sendHttp('POST', 'shareContent', data,
                        request => {
                            window.location.hash = '';
                            if (request.status === 200) {
                                sweetAlert('Success!',
                                    'The shared folder is moved into your root directory.',
                                    'success');
                            } else {
                                sweetAlert('Oops!',
                                    'Could not load the shared directory. Please try again.',
                                    'error');
                            }
                            initCodeworld();
                            discoverProjects('', 0);
                            updateUI();
                        });
                });
            } else {
                initCodeworld();
                loadXmlHash(hash, true);
            }
        } else {
            initCodeworld();
        }
    });
}

function initCodeworld() {
    window.codeworldKeywords = {};
    registerStandardHints(() => {});

    window.onbeforeunload = event => {
        if (containsUnsavedChanges()) {
            const msg = 'There are unsaved changes to your project. ' +
                'If you continue, they will be lost!';
            if (event) event.returnValue = msg;
            return msg;
        }
    };
}

function getCurrentProject() {
    return {
        'name': window.openProjectName || 'Untitled',
        'source': getWorkspaceXMLText(),
        'history': ''
    };
}

// Sets the generated code
function updateEditor(code) {
    const editor = document.getElementById('genCode');
    CodeMirror.runMode(code, {
        name: 'codeworld',
        overrideKeywords: codeworldKeywords
    }, editor);
}

function run(xmlHash, codeHash, msg, error, dhash) {
    const hash = codeHash;

    if (hash) {
        window.location.hash = `#${xmlHash}`;
        document.getElementById('shareButton').style.display = '';
        document.getElementById('shareFolderButton').style.display = 'none';
    } else {
        window.location.hash = '';
        document.getElementById('shareButton').style.display = 'none';
        document.getElementById('shareFolderButton').style.display = '';
    }

    window.showingResult = hash || msg;

    if (window.showingResult) {
        window.showingDoc = false;
    }

    const runner = document.getElementById('runner');
    if (hash && !error) {
        const loc = `run.html?hash=${hash}&mode=${window.buildMode}`;
        runner.contentWindow.location.replace(loc);
        document.getElementById('runner').style.display = '';
        document.getElementById('runner').contentWindow.focus();
        document.getElementById('message').style.display = 'none';
        window.programRunning = true;
    } else {
        document.getElementById('message').style.display = '';
        runner.contentWindow.location.replace('about:blank');
        document.getElementById('runner').style.display = 'none';
        window.programRunning = false;
    }
    if (!hash && !error && !msg) { // We stopped, don't show message window
        document.getElementById('message').style.display = 'none';
    }

    if (msg) {
        const message = document.getElementById('message');
        message.innerHTML = '';

        printMessage(error ? 'error' : 'log', msg);
    }

    document.getElementById('editButton').setAttribute('href', `/#${codeHash}`);
    window.deployHash = dhash;
    cancelMove();
    updateUI();
}

function removeErrors() {
    $('.blocklyDraggable').removeClass('blocklyErrorSelected');
    const blocks = Blockly.getMainWorkspace().getAllBlocks();

    blocks.forEach(block => {
        block.removeErrorSelect();
    });
}

function getWorkspaceXMLText() {
    const workspace = Blockly.getMainWorkspace();
    const xml = Blockly.Xml.workspaceToDom(workspace);
    const xml_text = Blockly.Xml.domToText(xml);
    return xml_text;
}

function containsUnsavedChanges() {
    const blank = '<xml xmlns="http://www.w3.org/1999/xhtml"></xml>';
{'fraction_non_alphanumeric': 0.1332188595549832, 'fraction_numerical': 0.0037203977963797667, 'mean_word_length': 1.853235354153909, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 22}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1959183', 'n_tokens_mistral': 3625, 'n_tokens_neox': 3539, 'n_words': 832}