<commit_before>#!/usr/bin/env node

/**
 * Module dependencies
 */

var _ = require('@sailshq/lodash');
var program = require('./private/patched-commander');
var sailsPackageJson = require('../package.json');
var NOOP = function() {};

program
  .version(sailsPackageJson.version, '-v, --version');

//
// Normalize version argument, i.e.
//
// $ sails -v
// $ sails -V
// $ sails --version
// $ sails version
//

// make `-v` option case-insensitive
process.argv = _.map(process.argv, function(arg) {
  return (arg === '-V') ? '-v' : arg;
});

// $ sails version (--version synonym)
program
  .command('version')
  .description('')
  .action(program.versionInformation);

program
  .option('--silent')
  .option('--verbose')
  .option('--silly')
  .unknownOption = NOOP;
program.usage('[command]');

// $ sails lift
var cmd;
cmd = program.command('lift');
cmd.option('--prod');
cmd.option('--port [port]');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.alias('l');
cmd.action(require('./sails-lift'));

// $ sails new <appname>
cmd = program.command('new [path_to_new_app]');
// cmd.option('--dry');
cmd.option('--viewEngine [viewEngine]');
cmd.option('--template [viewEngine]');
cmd.usage('[path_to_new_app]');
cmd.unknownOption = NOOP;
cmd.action(require('./sails-new'));

// $ sails generate <module>
cmd = program.command('generate');
// cmd.option('--dry');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.usage('[something]');
cmd.action(require('./sails-generate'));

// $ sails deploy
cmd = program.command('deploy');
// cmd.option('--dry');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.usage('');
cmd.action(require('./sails-deploy'));

// $ sails console
cmd = program.command('console');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.alias('c');
cmd.action(require('./sails-console'));

// $ sails www
// Compile `assets` directory into a standalone `www` folder.
cmd = program.command('www');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.action(require('./sails-www'));

// $ sails debug
cmd = program.command('debug');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.action(require('./sails-debug'));

//
// Normalize help argument, i.e.
//
// $ sails --help
// $ sails help
// $ sails
// $ sails <unrecognized_cmd>
//

// $ sails help (--help synonym)
cmd = program.command('help');
cmd.description('');
cmd.action(program.usageMinusWildcard);

// $ sails <unrecognized_cmd>
// Mask the '*' in `help`.
program
  .command('*')
  .action(program.usageMinusWildcard);

// Don't balk at unknown options
program.unknownOption = NOOP;

// $ sails
//
program.parse(process.argv);
var NO_COMMAND_SPECIFIED = program.args.length === 0;
if (NO_COMMAND_SPECIFIED) {
  program.usageMinusWildcard();
}
<commit_msg>Add a `.description()` to the `sails new` command to avoid the `undefined` in the output<commit_after>#!/usr/bin/env node

/**
 * Module dependencies
 */

var _ = require('@sailshq/lodash');
var program = require('./private/patched-commander');
var sailsPackageJson = require('../package.json');
var NOOP = function() {};

program
  .version(sailsPackageJson.version, '-v, --version');

//
// Normalize version argument, i.e.
//
// $ sails -v
// $ sails -V
// $ sails --version
// $ sails version
//

// make `-v` option case-insensitive
process.argv = _.map(process.argv, function(arg) {
  return (arg === '-V') ? '-v' : arg;
});

// $ sails version (--version synonym)
program
  .command('version')
  .description('')
  .action(program.versionInformation);

program
  .option('--silent')
  .option('--verbose')
  .option('--silly')
  .unknownOption = NOOP;
program.usage('[command]');

// $ sails lift
var cmd;
cmd = program.command('lift');
cmd.option('--prod');
cmd.option('--port [port]');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.alias('l');
cmd.action(require('./sails-lift'));

// $ sails new <appname>
cmd = program.command('new [path_to_new_app]');
// cmd.option('--dry');
cmd.option('--viewEngine [viewEngine]');
cmd.option('--template [viewEngine]');
cmd.usage('[path_to_new_app]');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.action(require('./sails-new'));

// $ sails generate <module>
cmd = program.command('generate');
// cmd.option('--dry');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.usage('[something]');
cmd.action(require('./sails-generate'));

// $ sails deploy
cmd = program.command('deploy');
// cmd.option('--dry');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.usage('');
cmd.action(require('./sails-deploy'));

// $ sails console
cmd = program.command('console');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.alias('c');
cmd.action(require('./sails-console'));

// $ sails www
// Compile `assets` directory into a standalone `www` folder.
cmd = program.command('www');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.action(require('./sails-www'));

// $ sails debug
cmd = program.command('debug');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.action(require('./sails-debug'));

//
// Normalize help argument, i.e.
//
// $ sails --help
// $ sails help
// $ sails
// $ sails <unrecognized_cmd>
//

// $ sails help (--help synonym)
cmd = program.command('help');
cmd.description('');
cmd.action(program.usageMinusWildcard);

// $ sails <unrecognized_cmd>
// Mask the '*' in `help`.
program
  .command('*')
  .action(program.usageMinusWildcard);

// Don't balk at unknown options
program.unknownOption = NOOP;

// $ sails
//
program.parse(process.argv);
var NO_COMMAND_SPECIFIED = program.args.length === 0;
if (NO_COMMAND_SPECIFIED) {
  program.usageMinusWildcard();
}
<|endoftext|>


<commit_before>// Copyright (c) Rice University 2012
// This software is subject to
// the provisions of the GNU Lesser General
// Public License Version 2.1 (LGPL).
// See LICENCE.txt for details.
//

    var REPOBASEURL = 'http://' + FROZONE.e2repoFQDN;
    var MODULEURL = 'http://' + FROZONE.e2repoFQDN + '/module/';
    var WORKSPACEURL = 'http://' + FROZONE.e2repoFQDN + '/workspace/';

    function logout(msg) {
        //log to a HTML area all messages
        var smsg = '';

        if (typeof(msg) == 'object') {
            for (var item in msg){
                smsg += item + "-" + msg[item];
                                 }
                                     }
        else                         {
            smsg = msg;
                                     }
        var txt = $('#logarea').html();
        $('#logarea').html(txt + '
 ' + smsg);
        console.log(smsg);
    }

    function get_username() {
        return $('#username').val();
    }

    function get_title() {
        var mname = $('#title').val();
        return mname;
    }

function save_validate() {
    var title = get_title();
    if (title = '') {
        jQuery.error('Must have a title');
    }
    return;
}

function get_textarea_html5() {
        //retrieve, as JSON, the contents of the edit-area
        var txtarea = $('#editarea-aloha').html();
        return txtarea;
    }

function load_textarea(mhashid) {
        //

        var request = $.ajax({
            url: MODULEURL + mhashid,

        xhrFields: {
            withCredentials: true
        },
            type: 'GET'
        });

        request.done(function(data) {
            //why not returned as json???
            var jdata = $.parseJSON(data);
            logout(jdata);
            //weird aloha feature - suffixed textareas.. ask phil..
            $('#editarea-aloha').val(jdata['content']);
            $('#aclrw').val(jdata['aclrw']);
            $('#contentrw').val(jdata['contentrw']);
            $('#title').val(jdata['title']);
            $('#uuid').val(jdata['uuid']);

        });

        request.fail(function(jqXHR, textStatus, err) {
            logout('Request failed: ' + textStatus + ':' + err + ':' + jqXHR.status);
        });

        request.always(function(jqXHR, textStatus) {
            logout(textStatus);
        });
    }

function getLoadHistoryVer(uuid) {
    // ajax request to retrieve module and parse json and load into textarea
    $.ajax({
        type: 'GET',
        dataType: 'json',
        url: MODULEURL + uuid,
        xhrFields: {
            withCredentials: true
        },  //http://stackoverflow.com/questions/2870371/why-jquery-ajax-not-sending-session-cookie

        success: function(nodedoc) {
            var title = nodedoc['title'];
            var txtarea = nodedoc['content'];

            var aclrw = nodedoc['aclrw'];
            var contentrw = nodedoc['contentrw'];

            $('#title').val(title);
            $('#aclrw').val(aclrw);
            $('#contentrw').val(contentrw);
            $('#uuid').val(uuid);

            $('#editarea-aloha').html(txtarea);
        },

        error: function(jqXHR, textStatus, err) {
            logout('Request failed: ' + textStatus + ':' + err + ':' + jqXHR.status);
        },

        complete: function(jqXHR, textStatus, err) {
            logout('Complete: Request failed: ' + textStatus + ':' + err + ':' + jqXHR.status);
        }

    });
}

function getwhoami() {
    // ajax request
    $.ajax({
        type: 'GET',
        dataType: 'json',
        url: REPOBASEURL + '/whoami/',
        xhrFields: {
            withCredentials: true
        },
        //display who I am
        success: function(jsondoc) {

//            for (var i in jsondoc){
//               alert(i);
//            };
            var user_email = jsondoc['email'];
            var user_name = jsondoc['name'];
            $('#usernamedisplay').html(user_name + '-' + user_email);
        },

        error: function(jqXHR, textStatus, err) {
            logout('Request failed: ' + textStatus + ':' + err + ':' + jqXHR.status);
        }

    });
}

function buildHistory() {

    var jsond = '[';
    var htmlfrag = '
';
    $.ajax({
        type: 'GET',
        dataType: 'json',
        url: WORKSPACEURL,
        xhrFields: {
            withCredentials: true
        },  //http://stackoverflow.com/questions/2870371/why-jquery-ajax-not-sending-session-cookie

        success: function(historyarr) {
            historyarr.sort();
            $.each(historyarr, function(i, elem) {
                var strelem = "'" + elem[0] + "'";
                htmlfrag += '
' + elem[1] + '' + '(Delete)';
                jsond += '{"data": "' + elem[1] + '", "attr": {"id": "' + elem[0] + '"}, "state": "closed"},';
            });

            x = jsond.length - 1;
            y = jsond.substring(0, x);
            jsond = y + ']';
            //jsond += ']"';
            logout(jsond);
            populate_tree(jsond);
            $('#workspaces').html(htmlfrag);
        }
    });
}

function delete_module(filename) {
    $.ajax({
        type: 'DELETE',
        dataType: 'json',
        url: REPOBASEURL + '/module/' + filename,
        xhrFields: {
            withCredentials: true
        },  //http://stackoverflow.com/questions/2870371/why-jquery-ajax-not-sending-session-cookie

        success: function() {
            logout('deleted ' + filename);
            buildHistory();
        },

        error: function(jqXHR, textStatus, err) {
            logout('Request failed: ' + textStatus + ':' + err + ':' + jqXHR.status);
        }

    });

}

function showres(i, elem) {

    logout(i + ': ' + elem);
}

function serialise_form() {
    // return form1 as object/hasharrary
    var payload = new Object;
    payload['content'] = get_textarea_html5();
    payload['uuid'] = $('#uuid').val();

    payload['aclrw'] = $('#aclrw').val().split(',');

    payload['contentrw'] = $('#contentrw').val().split(',');
    payload['title'] = $('#title').val();

//        var json_text = JSON.stringify(payload, null, 2);
//        return json_text;

    return payload;

}

function newText() {
    $('#aclrw').val(whoami['userID']);
    $('#contentrw').val(whoami['userID']);
    $('#title').val('Enter title here ...');
    $('#uuid').val('');
    $('#editarea-aloha').html('Enter your text here...');

}

function saveText() {
         //constants

         save_validate();

         var requestmethod = 'POST';
         var payload = serialise_form();
         if (payload['uuid'] != '') {
             requestmethod = 'PUT';
         }

         var foo = '';
         for (var i in payload) {
             foo = '/n' + i + ' : ' + payload[i];
         }
//         alert(requestmethod);
//         alert(foo);

         var json_text = JSON.stringify(payload, null, 2);

         var request = $.ajax({
             url: MODULEURL,
                xhrFields: {
                 withCredentials: true
                },

             type: requestmethod,
             data: json_text,
             contentType: 'application/json; charset=utf-8',
             dataType: 'json'
         });

         request.done(function(data) {
             //$("#responsearea").html(data);
             $.each(data, showres);
             buildHistory();
         });

         request.fail(function(jqXHR, textStatus, err) {
             logout('Request failed: ' + textStatus + ':' + err + ':' + jqXHR.status);
         });

         request.always(function(jqXHR, textStatus) {
             logout(textStatus);
         });

    }

function opendialog(dia) {

   $(dia).dialog('open');

}

function test() {

    //alert(whoami.identity_url + "/n" +
    //      whoami.name + "/n" +
    //      whoami.email);
    var s = '#dialog';
    $(s).dialog('open');

}

function start_aloha() {

    $('#editarea').aloha();
    logout('started aloha');
}

function node_load_event(node) {

   var moduleuuid = node.attr('id');
   getLoadHistoryVer(moduleuuid);
//   var s = "Calling load_textarea(" + moduleuuid + ")";
//   logout(s);
//   load_textarea(moduleuuid);

   }

function start_tree() {

var data = [
 {
 'data' : false,
 'attr': {'rel': 'directory'}
 }];

    $('#coltree').jstree({
            json_data: {data: data},
            plugins: ['themes', 'json_data', 'ui', 'crrm', 'hotkeys', 'contextmenu'],
            core: { },

            contextmenu: {'select_node': true,
                          'items': {'load': {'label': 'Edit module',
                                           'action': function(obj) {node_load_event(obj);}
                                          },
                                   'create': false,
                                   'rename': false,
                                   'delete': false,
                                   'edit': false,
                                   'remove':false,
                                   'ccp':false

                                 }
                        }

                         })
           .bind("delete.jstree", function(e, data) {alert("Delete TBD");
                                                    });

}

function populate_tree(jsonstr) {

    logout(jsonstr);
    x = $.parseJSON(jsonstr);

    var jsTreeSettings = $('#coltree').jstree('get_settings');
    jsTreeSettings.json_data.data = x; //$.parseJSON(jsonstr);
    $.jstree._reference('coltree')._set_settings(jsTreeSettings);

    // Refresh whole our tree (-1 means root of tree)
    $.jstree._reference('coltree').refresh(-1);
}

$(document).ready(function() {

    start_aloha();

    //mark dialog areas as dialog but not shown
    var dialogs = ['#dialog_files', '#dialog_metadata',
                   '#dialog_roles', '#dialog_links',
                   '#dialog_links', '#dialog_preview',
                   '#dialog_publish'];
    $.each(dialogs, function(i, v) {
//        alert(i + ":" + v);
        $(v).dialog({ autoOpen: false });
    });

    //bind various clicks
    $('#testclick').click(function(e) {test();
                                      e.preventDefault()});

    $('#clickLoadTextArea').click(function(e) {load_textarea();
                                              e.preventDefault()});

    logout('AJAX will fire at ' + MODULEURL);

    getwhoami();

    start_tree();
//    var d = '{"data": "title",' +
//            '"state": "closed"}';

//    populate_tree(d);

    buildHistory();

    //nolink are links that do some jquery function, but should not be links
    $('a.nolink').click(function(event) {
        logout('click-preventDefault');
        event.preventDefault();

    });

    $('#savemodule').click(function(event) {
                         saveText();
                         event.preventDefault();
                       }
                      );

    $('#newmodule').click(function(event) {
                         newText();
                         event.preventDefault();
                       }
                      );

});
<commit_msg>Draggable JStree<commit_after>// Copyright (c) Rice University 2012
// This software is subject to
// the provisions of the GNU Lesser General
// Public License Version 2.1 (LGPL).
// See LICENCE.txt for details.
//

    var REPOBASEURL = 'http://' + FROZONE.e2repoFQDN;
    var MODULEURL = 'http://' + FROZONE.e2repoFQDN + '/module/';
    var WORKSPACEURL = 'http://' + FROZONE.e2repoFQDN + '/workspace/';

    function logout(msg) {
        //log to a HTML area all messages
        var smsg = '';

        if (typeof(msg) == 'object') {
            for (var item in msg){
                smsg += item + "-" + msg[item];
                                 }
                                     }
        else                         {
            smsg = msg;
                                     }
        var txt = $('#logarea').html();
        $('#logarea').html(txt + '
 ' + smsg);
        console.log(smsg);
    }

    function get_username() {
        return $('#username').val();
    }

    function get_title() {
        var mname = $('#title').val();
        return mname;
    }

function save_validate() {
    var title = get_title();
    if (title = '') {
        jQuery.error('Must have a title');
    }
    return;
}

function get_textarea_html5() {
        //retrieve, as JSON, the contents of the edit-area
        var txtarea = $('#editarea-aloha').html();
        return txtarea;
    }

function load_textarea(mhashid) {
        //

        var request = $.ajax({
            url: MODULEURL + mhashid,

        xhrFields: {
            withCredentials: true
        },
            type: 'GET'
        });

        request.done(function(data) {
            //why not returned as json???
            var jdata = $.parseJSON(data);
            logout(jdata);
            //weird aloha feature - suffixed textareas.. ask phil..
            $('#editarea-aloha').val(jdata['content']);
            $('#aclrw').val(jdata['aclrw']);
            $('#contentrw').val(jdata['contentrw']);
            $('#title').val(jdata['title']);
            $('#uuid').val(jdata['uuid']);

        });

        request.fail(function(jqXHR, textStatus, err) {
            logout('Request failed: ' + textStatus + ':' + err + ':' + jqXHR.status);
        });

        request.always(function(jqXHR, textStatus) {
            logout(textStatus);
        });
    }

function getLoadHistoryVer(uuid) {
    // ajax request to retrieve module and parse json and load into textarea
    $.ajax({
        type: 'GET',
        dataType: 'json',
        url: MODULEURL + uuid,
        xhrFields: {
            withCredentials: true
        },  //http://stackoverflow.com/questions/2870371/why-jquery-ajax-not-sending-session-cookie

        success: function(nodedoc) {
            var title = nodedoc['title'];
            var txtarea = nodedoc['content'];

            var aclrw = nodedoc['aclrw'];
            var contentrw = nodedoc['contentrw'];

            $('#title').val(title);
            $('#aclrw').val(aclrw);
            $('#contentrw').val(contentrw);
            $('#uuid').val(uuid);

            $('#editarea-aloha').html(txtarea);
        },

        error: function(jqXHR, textStatus, err) {
            logout('Request failed: ' + textStatus + ':' + err + ':' + jqXHR.status);
        },

        complete: function(jqXHR, textStatus, err) {
            logout('Complete: Request failed: ' + textStatus + ':' + err + ':' + jqXHR.status);
        }

    });
}

function getwhoami() {
    // ajax request
    $.ajax({
        type: 'GET',
        dataType: 'json',
        url: REPOBASEURL + '/whoami/',
        xhrFields: {
            withCredentials: true
        },
        //display who I am
        success: function(jsondoc) {

//            for (var i in jsondoc){
//               alert(i);
//            };
            var user_email = jsondoc['email'];
            var user_name = jsondoc['name'];
            $('#usernamedisplay').html(user_name + '-' + user_email);
        },

        error: function(jqXHR, textStatus, err) {
            logout('Request failed: ' + textStatus + ':' + err + ':' + jqXHR.status);
        }

    });
}

function buildHistory() {

    var jsond = '[';
    var htmlfrag = '
';
    $.ajax({
        type: 'GET',
        dataType: 'json',
        url: WORKSPACEURL,
        xhrFields: {
            withCredentials: true
        },  //http://stackoverflow.com/questions/2870371/why-jquery-ajax-not-sending-session-cookie

        success: function(historyarr) {
            historyarr.sort();
            $.each(historyarr, function(i, elem) {
                var strelem = "'" + elem[0] + "'";
                htmlfrag += '
' + elem[1] + '' + '(Delete)';
                jsond += '{"data": "' + elem[1] + '", "attr": {"id": "' + elem[0] + '"}, "state": "closed"},';
            });

            x = jsond.length - 1;
            y = jsond.substring(0, x);
            jsond = y + ']';
            //jsond += ']"';
            logout(jsond);
            populate_tree(jsond);
            $('#workspaces').html(htmlfrag);
        }
    });
}

function delete_module(filename) {
    $.ajax({
        type: 'DELETE',
        dataType: 'json',
        url: REPOBASEURL + '/module/' + filename,
        xhrFields: {
            withCredentials: true
        },  //http://stackoverflow.com/questions/2870371/why-jquery-ajax-not-sending-session-cookie

        success: function() {
            logout('deleted ' + filename);
            buildHistory();
        },

        error: function(jqXHR, textStatus, err) {
            logout('Request failed: ' + textStatus + ':' + err + ':' + jqXHR.status);
        }

    });

}

function showres(i, elem) {

    logout(i + ': ' + elem);
}

function serialise_form() {
    // return form1 as object/hasharrary
    var payload = new Object;
    payload['content'] = get_textarea_html5();
    payload['uuid'] = $('#uuid').val();

    payload['aclrw'] = $('#aclrw').val().split(',');

    payload['contentrw'] = $('#contentrw').val().split(',');
    payload['title'] = $('#title').val();

//        var json_text = JSON.stringify(payload, null, 2);
//        return json_text;

    return payload;

}

function newText() {
    $('#aclrw').val(whoami['userID']);
    $('#contentrw').val(whoami['userID']);
    $('#title').val('Enter title here ...');
    $('#uuid').val('');
    $('#editarea-aloha').html('Enter your text here...');

}

function saveText() {
         //constants

         save_validate();

         var requestmethod = 'POST';
         var payload = serialise_form();
         if (payload['uuid'] != '') {
             requestmethod = 'PUT';
         }

         var foo = '';
         for (var i in payload) {
             foo = '/n' + i + ' : ' + payload[i];
         }
//         alert(requestmethod);
//         alert(foo);

         var json_text = JSON.stringify(payload, null, 2);

         var request = $.ajax({
             url: MODULEURL,
                xhrFields: {
                 withCredentials: true
                },

             type: requestmethod,
             data: json_text,
             contentType: 'application/json; charset=utf-8',
             dataType: 'json'
         });

         request.done(function(data) {
             //$("#responsearea").html(data);
             $.each(data, showres);
             buildHistory();
         });

         request.fail(function(jqXHR, textStatus, err) {
             logout('Request failed: ' + textStatus + ':' + err + ':' + jqXHR.status);
         });

         request.always(function(jqXHR, textStatus) {
             logout(textStatus);
         });

    }

function opendialog(dia) {

   $(dia).dialog('open');

}

function test() {

    //alert(whoami.identity_url + "/n" +
    //      whoami.name + "/n" +
    //      whoami.email);
    var s = '#dialog';
    $(s).dialog('open');

}

function start_aloha() {

    $('#editarea').aloha();
    logout('started aloha');
}

function node_load_event(node) {

   var moduleuuid = node.attr('id');
   getLoadHistoryVer(moduleuuid);
//   var s = "Calling load_textarea(" + moduleuuid + ")";
//   logout(s);
//   load_textarea(moduleuuid);

   }

function start_tree() {

var data = [
 {
 'data' : false,
 'attr': {'rel': 'directory'}
 }];

    $('#coltree').jstree({
            json_data: {data: data},
            plugins: ['themes', 'json_data', 'ui', 'crrm', 'hotkeys',
                      'contextmenu', 'dnd'],
            core: { },
            dnd: {
                 "drop_finish": function (data) {
                                                alert("some message");
                                                },

                 },

            contextmenu: {'select_node': true,
                          'items': {'load': {'label': 'Edit module',
                                           'action': function(obj) {node_load_event(obj);}
                                          },
                                   'create': false,
                                   'rename': false,
                                   'delete': false,
                                   'edit': false,
                                   'remove':false,
                                   'ccp':false

                                 }
                        }

                         })
           .bind("delete.jstree", function(e, data) {alert("Delete TBD");
                                                    });

}

function populate_tree(jsonstr) {

    logout(jsonstr);
    x = $.parseJSON(jsonstr);

    var jsTreeSettings = $('#coltree').jstree('get_settings');
    jsTreeSettings.json_data.data = x; //$.parseJSON(jsonstr);
    $.jstree._reference('coltree')._set_settings(jsTreeSettings);

    // Refresh whole our tree (-1 means root of tree)
    $.jstree._reference('coltree').refresh(-1);
}

$(document).ready(function() {

    start_aloha();

    //mark dialog areas as dialog but not shown
    var dialogs = ['#dialog_files', '#dialog_metadata',
                   '#dialog_roles', '#dialog_links',
                   '#dialog_links', '#dialog_preview',
                   '#dialog_publish'];
    $.each(dialogs, function(i, v) {
//        alert(i + ":" + v);
        $(v).dialog({ autoOpen: false });
    });

    //bind various clicks
    $('#testclick').click(function(e) {test();
                                      e.preventDefault()});

    $('#clickLoadTextArea').click(function(e) {load_textarea();
                                              e.preventDefault()});

    logout('AJAX will fire at ' + MODULEURL);

    getwhoami();

    start_tree();
//    var d = '{"data": "title",' +
//            '"state": "closed"}';

//    populate_tree(d);

    buildHistory();

    //nolink are links that do some jquery function, but should not be links
    $('a.nolink').click(function(event) {
        logout('click-preventDefault');
        event.preventDefault();

    });

    $('#savemodule').click(function(event) {
                         saveText();
                         event.preventDefault();
                       }
                      );

    $('#newmodule').click(function(event) {
                         newText();
                         event.preventDefault();
                       }
                      );

});
<|endoftext|>


<commit_before>/**
 * @module  notifications
 * @author  Flavio De Stefano <flavio.destefano@caffeinalab.com>
 */

/**
 * @property config
 * @property {Boolean} 	[config.autoReset=true] 	Check if auto-reset the badge when app is open.
 * @property {String} 	[config.driver="http"] 		The driver to use.
 * @type {Object}
 */
exports.config = _.extend({
	autoReset: true,
	driver: 'http',
}, Alloy.CFG.T ? Alloy.CFG.T.notifications : {});

var Event = require('T/event');
var Util = require('T/util');
var Router = require('T/router');
var Q = require('T/ext/q');

var cachedDeviceToken = null;

/**
 * @property onReceived
 * A callback called when a notification is received
 */
exports.onReceived = function(e) {
	Ti.API.info("Notifications: Received", e);
};

var interactiveCategories = [];
var interactiveCategoriesCallbacks = {};

var INTERACTIVE_NOTIFICATIONS_CAPABLE = (OS_IOS && _.isFunction(Ti.App.iOS.createUserNotificationAction));

function validateToken(token) {
	return token != null && token != "undefined" && token != "null" && token.length >= 32;
}

function onNotificationReceived(e) {
	if (OS_ANDROID) {
		_.each(['notification','data'], function(prop) {
			if (_.isString(e[prop])) {
				try {
					e[prop] = JSON.parse(e[prop]);
				} catch (ex) {
					e[prop] = {};
				}
			}
		});
	}

	// Auto-reset the badge
	if (exports.config.autoReset === true) {
		exports.resetBadge();
	}

	if (_.isFunction(exports.onReceived)) exports.onReceived(e);
	Event.trigger('notifications.received', e);
}

/**
 * Load a driver of current module
 */
exports.loadDriver = function(name) {
	return Alloy.Globals.Trimethyl.loadDriver('notifications', name, {
		subscribe: function(opt) {},
		unsubscribe: function(opt) {}
	});
};

/**
 * Attach events to current module
 */
exports.event = function(name, cb) {
	Event.on('notifications.' + name, cb);
};

/**
 * @param  {Function} callback Callback invoked when success occur
 */
exports.activate = function(callback) {
	var defer = Q.defer();

	if (cachedDeviceToken != null) {
		Ti.API.warn("Notifications: multiple call to activate, will return cached remote device UDID");
		defer.resolve(cachedDeviceToken);
		return defer.promise;
	}

	if (INTERACTIVE_NOTIFICATIONS_CAPABLE) {

		var userNotificationsCallback = function(settings) {
			Ti.App.iOS.removeEventListener('usernotificationsettings', userNotificationsCallback);

			if (_.isEmpty(settings.types)) {
				return defer.reject({
					disabled: true
				});
			}

			Ti.Network.registerForPushNotifications({
				callback: onNotificationReceived,
				success: function(e) {
					if ( ! validateToken(e.deviceToken)) {
						Ti.API.error('Notifications: Retrieve device token failed');
						return defer.reject({
							invalidToken: true
						});
					}

					// Set a flag to prevent that future calls to registerForPush will trigger multiple notifications
					cachedDeviceToken = e.deviceToken;

					defer.resolve(e.deviceToken);
					Event.trigger('notifications.activation.success');
				},
				error: function(err) {
					Ti.API.error('Notifications: Retrieve device token failed', err);

					defer.reject(err);
					Event.trigger('notifications.activation.error', err);
				}
			});
		};

		Ti.App.iOS.addEventListener('usernotificationsettings', userNotificationsCallback);
		Ti.App.iOS.registerUserNotificationSettings({
			types: [
				Ti.Network.NOTIFICATION_TYPE_BADGE,
				Ti.Network.NOTIFICATION_TYPE_ALERT,
				Ti.Network.NOTIFICATION_TYPE_SOUND
			],
			categories: interactiveCategories
		});

	} else {

		var Module = null;
		var moduleOpt = {};

		if (OS_IOS) {

			Module = Ti.Network;
			moduleOpt.types = [
				Ti.Network.NOTIFICATION_TYPE_BADGE,
				Ti.Network.NOTIFICATION_TYPE_ALERT,
				Ti.Network.NOTIFICATION_TYPE_SOUND
			];

		} else if (OS_ANDROID) {

			Module = require('ti.goosh');

		} else return;

		Module.registerForPushNotifications(_.extend(moduleOpt, {
			callback: onNotificationReceived,
			success: function(e) {
				if ( ! validateToken(e.deviceToken)) {
					Ti.API.error('Notifications: Retrieve device token failed');
					return defer.reject({
						invalidToken: true
					});
				}

				// Set a flag to prevent that future calls to registerForPush will trigger multiple notifications
				cachedDeviceToken = e.deviceToken;

				defer.resolve(e.deviceToken);
				Event.trigger('notifications.activation.success');
			},
			error: function(err) {
				Ti.API.error('Notifications: Retrieve device token failed', err);

				defer.reject(err);
				Event.trigger('notifications.activation.error', err);
			},
		}));
	}

	return defer.promise;
};

/**
 * Deactivate completely the notifications
 */
exports.deactivate = function() {
	if (OS_IOS) {
		Module = Ti.Network;
	} else if (OS_ANDROID) {
		Module = require("ti.goosh");
	} else return;

	Module.unregisterForPushNotifications();
};

/**
 * Subscribe for that channel
 * @param {String} channel 	Channel name
 * @param {Object} data 		Additional data
 * @param {Object} [opt={}] 	Additional options
 */
exports.subscribe = function(channel, data, opt) {
	var defer = Q.defer();

	if (!Ti.Network.online) {
		defer.reject({
			offline: true
		});
		return defer.promise;
	}

	exports.activate()
	.then(function(deviceToken) {

		exports.loadDriver(exports.config.driver).subscribe(_.extend({}, opt, {
			deviceToken: deviceToken,
			channel: channel,
			data: data,
			success: function(response) {
				Event.trigger('notifications.subscription.success', { channel: channel });
				Ti.API.debug('Notifications: Subscription to channel <' + (channel || 'default') + '> succeded', response);

				defer.resolve(response);
			},
			error: function(err) {
				Event.trigger('notifications.subscription.error', err);
				Ti.API.error('Notifications: Subscription failed to channel <' + (channel || 'default') + '>', err);

				defer.reject(err);
			}
		}));

	})
	.fail(defer.reject);

	return defer.promise;
};

/**
 * Unsubscribe for that channel
 * @param {String} channel 	Channel name
 * @param {Object} data 		Additional data
 */
exports.unsubscribe = function(channel, data) {
	var defer = Q.defer();

	if (!Ti.Network.online) {
		defer.reject({
			offline: true
		});
		return defer.promise;
	}

	exports.loadDriver(exports.config.driver).unsubscribe({
		deviceToken: exports.getRemoteDeviceUUID(),
		channel: channel,
		data: data,
		success: function(response) {
			Event.trigger('notifications.unsubscription.error', { channel: channel });
			Ti.API.debug('Notifications: Unsubscription to channel <' + (channel || 'default') + '> succeded', response);

			defer.resolve(response);
		},
		error: function(err) {
			Event.trigger('notifications.unsubscription.error', err);
			Ti.API.error('Notifications: Unsubscription failed to channel <' + (channel || 'default') + '>', err);

			defer.reject(err);
		}
	});

	return defer.promise;
};

/**
 * Set the App badge value
 * @param {Number} x
 */
exports.setBadge = function(x) {
	var Module = OS_IOS ? Ti.UI.iPhone : require('ti.goosh');
	Module.setAppBadge(Math.max(x,0));
};

/**
 * Get the App badge value
 * @return {Number}
 */
exports.getBadge = function() {
	var Module = OS_IOS ? Ti.UI.iPhone : require('ti.goosh');
	return Module.getAppBadge();
};

/**
 * Reset to 0 the badge
 */
exports.resetBadge = function() {
	exports.setBadge(0);
};

/**
 * Increment the badge app
 * @param  {Number} i The value to increment
 */
exports.incBadge = function(i) {
	exports.setBadge(exports.getBadge() + i);
};

/**
 * Get the stored device token.
 * Don't rely on this method to check if notifications are active, use {@link #isRemoteNotificationsEnabled} instead
 * @return {String}
 */
exports.getRemoteDeviceUUID = function() {
	var Module = OS_IOS ? Ti.Network : require('ti.goosh');
	return Module.remoteDeviceUUID;
};

/**
 * Check if the remote notifications has been registered once
 * Use this method at startup in conjunction with `activate()`
 * @return {Boolean} [description]
 */
exports.isRemoteNotificationsEnabled = function() {
	var Module = OS_IOS ? Ti.Network : require('ti.goosh');
	return Module.remoteNotificationsEnabled;
};

///////////////////////////////
// Interactive notifications //
///////////////////////////////

function createIntNotifAction(opt) {
	if (opt.id == null) throw new Error('Notifications: interactive notifications must have and ID');
	if (opt.title == null) throw new Error('Notifications: interactive notifications must have a title');

	return Ti.App.iOS.createUserNotificationAction({
		identifier: opt.id,
		title: opt.title,
		activationMode: Ti.App.iOS["USER_NOTIFICATION_ACTIVATION_MODE_" + (opt.openApplication == true ? "FOREGROUND" : "BACKGROUND")],
		destructive: !!opt.destructive,
		authenticationRequired: !!opt.authenticationRequired
	});
}

/**
 * @param {String}   id       	The ID of the category. It must be unique.
 * @param {Array}    dict     	An array of actions, with `id, title` (required) and `openApplication, destructive, authenticationRequired` (optional)
 * @param {Function} callback 	The callback to invoke
 */
exports.addInteractiveNotificationCategory = function(id, dict, callback) {
	if (!INTERACTIVE_NOTIFICATIONS_CAPABLE) return;

	var category = Ti.App.iOS.createUserNotificationCategory({
		identifier: id,
		actionsForDefaultContext: dict.map(createIntNotifAction)
	});

	// Add in the interactiveCategories array to register in the activate method
	interactiveCategories.push(category);
	interactiveCategoriesCallbacks[id] = callback;
};

//////////
// Init //
//////////

if (INTERACTIVE_NOTIFICATIONS_CAPABLE) {
	Ti.App.iOS.addEventListener('remotenotificationaction', function(e) {
		var func = interactiveCategoriesCallbacks[e.category];
		if (_.isFunction(func)) {
			func(e);
		} else {
			Ti.API.error('Notifications: remote notification with an unregistered category (' + e.category + ')');
		}
	});
}

if (exports.config.autoReset === true) {
	exports.resetBadge();
	Ti.App.addEventListener('resumed', exports.resetBadge);
}
<commit_msg>no support for notif<commit_after>/**
 * @module  notifications
 * @author  Flavio De Stefano <flavio.destefano@caffeinalab.com>
 */

/**
 * @property config
 * @property {Boolean} 	[config.autoReset=true] 	Check if auto-reset the badge when app is open.
 * @property {String} 	[config.driver="http"] 		The driver to use.
 * @type {Object}
 */
exports.config = _.extend({
	autoReset: true,
	driver: 'http',
}, Alloy.CFG.T ? Alloy.CFG.T.notifications : {});

var Event = require('T/event');
var Util = require('T/util');
var Router = require('T/router');
var Q = require('T/ext/q');

var cachedDeviceToken = null;

/**
 * @property onReceived
 * A callback called when a notification is received
 */
exports.onReceived = function(e) {
	Ti.API.info("Notifications: Received", e);
};

var interactiveCategories = [];
var interactiveCategoriesCallbacks = {};

var INTERACTIVE_NOTIFICATIONS_CAPABLE = (OS_IOS && _.isFunction(Ti.App.iOS.createUserNotificationAction));

function validateToken(token) {
	return token != null && token != "undefined" && token != "null" && token.length >= 32;
}

function onNotificationReceived(e) {
	if (OS_ANDROID) {
		if (_.isString(e.data)) {
			try {
				e.data = JSON.parse(e.data);
			} catch (ex) {
				e.data = {};
			}
		}
	}

	// Auto-reset the badge
	if (exports.config.autoReset === true) {
		exports.resetBadge();
	}

	if (_.isFunction(exports.onReceived)) exports.onReceived(e);
	Event.trigger('notifications.received', e);
}

/**
 * Load a driver of current module
 */
exports.loadDriver = function(name) {
	return Alloy.Globals.Trimethyl.loadDriver('notifications', name, {
		subscribe: function(opt) {},
		unsubscribe: function(opt) {}
	});
};

/**
 * Attach events to current module
 */
exports.event = function(name, cb) {
	Event.on('notifications.' + name, cb);
};

/**
 * @param  {Function} callback Callback invoked when success occur
 */
exports.activate = function(callback) {
	var defer = Q.defer();

	if (cachedDeviceToken != null) {
		Ti.API.warn("Notifications: multiple call to activate, will return cached remote device UDID");
		defer.resolve(cachedDeviceToken);
		return defer.promise;
	}

	if (INTERACTIVE_NOTIFICATIONS_CAPABLE) {

		var userNotificationsCallback = function(settings) {
			Ti.App.iOS.removeEventListener('usernotificationsettings', userNotificationsCallback);

			if (_.isEmpty(settings.types)) {
				return defer.reject({
					disabled: true
				});
			}

			Ti.Network.registerForPushNotifications({
				callback: onNotificationReceived,
				success: function(e) {
					if ( ! validateToken(e.deviceToken)) {
						Ti.API.error('Notifications: Retrieve device token failed');
						return defer.reject({
							invalidToken: true
						});
					}

					// Set a flag to prevent that future calls to registerForPush will trigger multiple notifications
					cachedDeviceToken = e.deviceToken;

					defer.resolve(e.deviceToken);
					Event.trigger('notifications.activation.success');
				},
				error: function(err) {
					Ti.API.error('Notifications: Retrieve device token failed', err);

					defer.reject(err);
					Event.trigger('notifications.activation.error', err);
				}
			});
		};

		Ti.App.iOS.addEventListener('usernotificationsettings', userNotificationsCallback);
		Ti.App.iOS.registerUserNotificationSettings({
			types: [
				Ti.Network.NOTIFICATION_TYPE_BADGE,
				Ti.Network.NOTIFICATION_TYPE_ALERT,
				Ti.Network.NOTIFICATION_TYPE_SOUND
			],
			categories: interactiveCategories
		});

	} else {

		var Module = null;
		var moduleOpt = {};

		if (OS_IOS) {

			Module = Ti.Network;
			moduleOpt.types = [
				Ti.Network.NOTIFICATION_TYPE_BADGE,
				Ti.Network.NOTIFICATION_TYPE_ALERT,
				Ti.Network.NOTIFICATION_TYPE_SOUND
			];

		} else if (OS_ANDROID) {

			Module = require('ti.goosh');

		} else return;

		Module.registerForPushNotifications(_.extend(moduleOpt, {
			callback: onNotificationReceived,
			success: function(e) {
				if ( ! validateToken(e.deviceToken)) {
					Ti.API.error('Notifications: Retrieve device token failed');
					return defer.reject({
						invalidToken: true
					});
				}

				// Set a flag to prevent that future calls to registerForPush will trigger multiple notifications
				cachedDeviceToken = e.deviceToken;

				defer.resolve(e.deviceToken);
				Event.trigger('notifications.activation.success');
			},
			error: function(err) {
				Ti.API.error('Notifications: Retrieve device token failed', err);

				defer.reject(err);
				Event.trigger('notifications.activation.error', err);
			},
		}));
	}

	return defer.promise;
};

/**
 * Deactivate completely the notifications
 */
exports.deactivate = function() {
	if (OS_IOS) {
		Module = Ti.Network;
	} else if (OS_ANDROID) {
		Module = require("ti.goosh");
	} else return;

	Module.unregisterForPushNotifications();
};

/**
 * Subscribe for that channel
 * @param {String} channel 	Channel name
 * @param {Object} data 		Additional data
 * @param {Object} [opt={}] 	Additional options
 */
exports.subscribe = function(channel, data, opt) {
	var defer = Q.defer();

	if (!Ti.Network.online) {
		defer.reject({
			offline: true
		});
		return defer.promise;
	}

	exports.activate()
	.then(function(deviceToken) {

		exports.loadDriver(exports.config.driver).subscribe(_.extend({}, opt, {
			deviceToken: deviceToken,
			channel: channel,
			data: data,
			success: function(response) {
				Event.trigger('notifications.subscription.success', { channel: channel });
				Ti.API.debug('Notifications: Subscription to channel <' + (channel || 'default') + '> succeded', response);

				defer.resolve(response);
			},
			error: function(err) {
				Event.trigger('notifications.subscription.error', err);
				Ti.API.error('Notifications: Subscription failed to channel <' + (channel || 'default') + '>', err);

				defer.reject(err);
			}
		}));

	})
	.fail(defer.reject);

	return defer.promise;
};

/**
 * Unsubscribe for that channel
 * @param {String} channel 	Channel name
 * @param {Object} data 		Additional data
 */
exports.unsubscribe = function(channel, data) {
	var defer = Q.defer();

	if (!Ti.Network.online) {
		defer.reject({
			offline: true
		});
		return defer.promise;
	}

	exports.loadDriver(exports.config.driver).unsubscribe({
		deviceToken: exports.getRemoteDeviceUUID(),
		channel: channel,
		data: data,
		success: function(response) {
			Event.trigger('notifications.unsubscription.error', { channel: channel });
			Ti.API.debug('Notifications: Unsubscription to channel <' + (channel || 'default') + '> succeded', response);

			defer.resolve(response);
		},
		error: function(err) {
			Event.trigger('notifications.unsubscription.error', err);
			Ti.API.error('Notifications: Unsubscription failed to channel <' + (channel || 'default') + '>', err);

			defer.reject(err);
		}
	});

	return defer.promise;
};

/**
 * Set the App badge value
 * @param {Number} x
 */
exports.setBadge = function(x) {
	var Module = OS_IOS ? Ti.UI.iPhone : require('ti.goosh');
	Module.setAppBadge(Math.max(x,0));
};

/**
 * Get the App badge value
 * @return {Number}
 */
exports.getBadge = function() {
	var Module = OS_IOS ? Ti.UI.iPhone : require('ti.goosh');
	return Module.getAppBadge();
};

/**
 * Reset to 0 the badge
 */
exports.resetBadge = function() {
	exports.setBadge(0);
};

/**
 * Increment the badge app
 * @param  {Number} i The value to increment
 */
exports.incBadge = function(i) {
	exports.setBadge(exports.getBadge() + i);
};

/**
 * Get the stored device token.
 * Don't rely on this method to check if notifications are active, use {@link #isRemoteNotificationsEnabled} instead
 * @return {String}
 */
exports.getRemoteDeviceUUID = function() {
	var Module = OS_IOS ? Ti.Network : require('ti.goosh');
	return Module.remoteDeviceUUID;
};

/**
 * Check if the remote notifications has been registered once
 * Use this method at startup in conjunction with `activate()`
 * @return {Boolean} [description]
 */
exports.isRemoteNotificationsEnabled = function() {
	var Module = OS_IOS ? Ti.Network : require('ti.goosh');
	return Module.remoteNotificationsEnabled;
};

///////////////////////////////
// Interactive notifications //
///////////////////////////////

function createIntNotifAction(opt) {
	if (opt.id == null) throw new Error('Notifications: interactive notifications must have and ID');
	if (opt.title == null) throw new Error('Notifications: interactive notifications must have a title');

	return Ti.App.iOS.createUserNotificationAction({
		identifier: opt.id,
		title: opt.title,
		activationMode: Ti.App.iOS["USER_NOTIFICATION_ACTIVATION_MODE_" + (opt.openApplication == true ? "FOREGROUND" : "BACKGROUND")],
		destructive: !!opt.destructive,
		authenticationRequired: !!opt.authenticationRequired
	});
}

/**
 * @param {String}   id       	The ID of the category. It must be unique.
 * @param {Array}    dict     	An array of actions, with `id, title` (required) and `openApplication, destructive, authenticationRequired` (optional)
 * @param {Function} callback 	The callback to invoke
 */
exports.addInteractiveNotificationCategory = function(id, dict, callback) {
	if (!INTERACTIVE_NOTIFICATIONS_CAPABLE) return;

	var category = Ti.App.iOS.createUserNotificationCategory({
		identifier: id,
		actionsForDefaultContext: dict.map(createIntNotifAction)
	});

	// Add in the interactiveCategories array to register in the activate method
	interactiveCategories.push(category);
	interactiveCategoriesCallbacks[id] = callback;
};

//////////
// Init //
//////////

if (INTERACTIVE_NOTIFICATIONS_CAPABLE) {
	Ti.App.iOS.addEventListener('remotenotificationaction', function(e) {
		var func = interactiveCategoriesCallbacks[e.category];
		if (_.isFunction(func)) {
			func(e);
		} else {
			Ti.API.error('Notifications: remote notification with an unregistered category (' + e.category + ')');
		}
	});
}

if (exports.config.autoReset === true) {
	exports.resetBadge();
	Ti.App.addEventListener('resumed', exports.resetBadge);
}
<|endoftext|>


<commit_before>var convert = require("../index");

var converter = convert();

var times = 10000;

console.time("cached");
converter.rgb(10, 2, 30);
for(var i = 0; i < times; i++) {
   converter.hsv();
   converter.hsl();
   converter.cmyk();
}
console.timeEnd("cached");

console.time("uncached");
for(var i = 0; i < times; i++) {
   convert.rgb2hsl(10, 2, 30);
   convert.rgb2hsv(10, 2, 30);
   convert.rgb2cmyk(10, 2, 30);
}
console.timeEnd("uncached");

<commit_msg>Delete speed.js<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.provide("frappe.customize_form");

frappe.ui.form.on("Customize Form", {
	onload: function(frm) {
		frm.set_query("doc_type", function() {
			return {
				translate_values: false,
				filters: [
					['DocType', 'issingle', '=', 0],
					['DocType', 'custom', '=', 0],
					['DocType', 'name', 'not in', frappe.model.core_doctypes_list],
					['DocType', 'restrict_to_domain', 'in', frappe.boot.active_domains]
				]
			};
		});

		frm.set_query("default_print_format", function() {
			return {
				filters: {
					'print_format_type': ['!=', 'JS']
				}
			}
		});

		$(frm.wrapper).on("grid-row-render", function(e, grid_row) {
			if(grid_row.doc && grid_row.doc.fieldtype=="Section Break") {
				$(grid_row.row).css({"font-weight": "bold"});
			}
		});

		$(frm.wrapper).on("grid-make-sortable", function(e, frm) {
			frm.trigger("setup_sortable");
		});

		$(frm.wrapper).on("grid-move-row", function(e, frm) {
			frm.trigger("setup_sortable");
		});

	},

	doc_type: function(frm) {
		if(frm.doc.doc_type) {
			return frm.call({
				method: "fetch_to_customize",
				doc: frm.doc,
				freeze: true,
				callback: function(r) {
					if(r) {
						if(r._server_messages && r._server_messages.length) {
							frm.set_value("doc_type", "");
						} else {
							frm.refresh();
							frm.trigger("setup_sortable");
						}
					}
				}
			});
		} else {
			frm.refresh();
		}
	},

	setup_sortable: function(frm) {
		frm.page.body.find('.highlight').removeClass('highlight');
		frm.doc.fields.forEach(function(f, i) {
			var data_row = frm.page.body.find('[data-fieldname="fields"] [data-idx="'+ f.idx +'"] .data-row');

			if(f.is_custom_field) {
				data_row.addClass("highlight");
			} else {
				f._sortable = false;
			}
		});
		frm.fields_dict.fields.grid.refresh();
	},

	refresh: function(frm) {
		frm.disable_save();
		frm.page.clear_icons();

		if(frm.doc.doc_type) {
			frappe.customize_form.set_primary_action(frm);

			frm.add_custom_button(__('Refresh Form'), function() {
				frm.script_manager.trigger("doc_type");
			}, "fa fa-refresh", "btn-default");

			frm.add_custom_button(__('Reset to defaults'), function() {
				frappe.customize_form.confirm(__('Remove all customizations?'), frm);
			}, "fa fa-eraser", "btn-default");

			frm.add_custom_button(__('Set Permissions'), function() {
				frappe.set_route('permission-manager', frm.doc.doc_type);
			}, "fa fa-lock", "btn-default");

			if(frappe.boot.developer_mode) {
				frm.add_custom_button(__('Export Customizations'), function() {
					frappe.prompt(
						[
							{fieldtype:'Link', fieldname:'module', options:'Module Def',
								label: __('Module to Export')},
							{fieldtype:'Check', fieldname:'sync_on_migrate',
								label: __('Sync on Migrate'), 'default': 1},
							{fieldtype:'Check', fieldname:'with_permissions',
								label: __('Export Custom Permissions'), 'default': 1},
						],
						function(data) {
							frappe.call({
								method: 'frappe.modules.utils.export_customizations',
								args: {
									doctype: frm.doc.doc_type,
									module: data.module,
									sync_on_migrate: data.sync_on_migrate,
									with_permissions: data.with_permissions
								}
							});
						},
						__("Select Module"));
				});
			}
		}

		// sort order select
		if(frm.doc.doc_type) {
			var fields = $.map(frm.doc.fields,
					function(df) { return frappe.model.is_value_type(df.fieldtype) ? df.fieldname : null; });
			fields = ["", "name", "modified"].concat(fields);
			frm.set_df_property("sort_field", "options", fields);
		}

		if(frappe.route_options && frappe.route_options.doc_type) {
			setTimeout(function() {
				frm.set_value("doc_type", frappe.route_options.doc_type);
				frappe.route_options = null;
			}, 1000);
		}

	},

});

frappe.ui.form.on("Customize Form Field", {
	before_fields_remove: function(frm, doctype, name) {
		var row = frappe.get_doc(doctype, name);
		if(!(row.is_custom_field || row.__islocal)) {
			frappe.msgprint(__("Cannot delete standard field. You can hide it if you want"));
			throw "cannot delete custom field";
		}
	},
	fields_add: function(frm, cdt, cdn) {
		var f = frappe.model.get_doc(cdt, cdn);
		f.is_custom_field = 1;
	}
});

frappe.customize_form.set_primary_action = function(frm) {
	frm.page.set_primary_action(__("Update"), function() {
		if(frm.doc.doc_type) {
			return frm.call({
				doc: frm.doc,
				freeze: true,
				btn: frm.page.btn_primary,
				method: "save_customization",
				callback: function(r) {
					if(!r.exc) {
						frappe.customize_form.clear_locals_and_refresh(frm);
						frm.script_manager.trigger("doc_type");
					}
				}
			});
		}
	});
};

frappe.customize_form.confirm = function(msg, frm) {
	if(!frm.doc.doc_type) return;

	var d = new frappe.ui.Dialog({
		title: 'Reset To Defaults',
		fields: [
			{fieldtype:"HTML", options:__("All customizations will be removed. Please confirm.")},
		],
		primary_action: function() {
			return frm.call({
				doc: frm.doc,
				method: "reset_to_defaults",
				callback: function(r) {
					if(r.exc) {
						frappe.msgprint(r.exc);
					} else {
						d.hide();
						frappe.show_alert({message:__('Customizations Reset'), indicator:'green'});
						frappe.customize_form.clear_locals_and_refresh(frm);
					}
				}
			});
		}
	});

	frappe.customize_form.confirm.dialog = d;
	d.show();
}

frappe.customize_form.clear_locals_and_refresh = function(frm) {
	// clear doctype from locals
	frappe.model.clear_doc("DocType", frm.doc.doc_type);
	delete frappe.meta.docfield_copy[frm.doc.doc_type];

	frm.refresh();
}

<commit_msg>fix: filter default print format in customize form by doctype<commit_after>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.provide("frappe.customize_form");

frappe.ui.form.on("Customize Form", {
	onload: function(frm) {
		frm.set_query("doc_type", function() {
			return {
				translate_values: false,
				filters: [
					['DocType', 'issingle', '=', 0],
					['DocType', 'custom', '=', 0],
					['DocType', 'name', 'not in', frappe.model.core_doctypes_list],
					['DocType', 'restrict_to_domain', 'in', frappe.boot.active_domains]
				]
			};
		});

		frm.set_query("default_print_format", function() {
			return {
				filters: {
					'print_format_type': ['!=', 'JS'],
					'doc_type': ['=', frm.doc.doc_type]
				}
			}
		});

		$(frm.wrapper).on("grid-row-render", function(e, grid_row) {
			if(grid_row.doc && grid_row.doc.fieldtype=="Section Break") {
				$(grid_row.row).css({"font-weight": "bold"});
			}
		});

		$(frm.wrapper).on("grid-make-sortable", function(e, frm) {
			frm.trigger("setup_sortable");
		});

		$(frm.wrapper).on("grid-move-row", function(e, frm) {
			frm.trigger("setup_sortable");
		});

	},

	doc_type: function(frm) {
		if(frm.doc.doc_type) {
			return frm.call({
				method: "fetch_to_customize",
				doc: frm.doc,
				freeze: true,
				callback: function(r) {
					if(r) {
						if(r._server_messages && r._server_messages.length) {
							frm.set_value("doc_type", "");
						} else {
							frm.refresh();
							frm.trigger("setup_sortable");
						}
					}
				}
			});
		} else {
			frm.refresh();
		}
	},

	setup_sortable: function(frm) {
		frm.page.body.find('.highlight').removeClass('highlight');
		frm.doc.fields.forEach(function(f, i) {
			var data_row = frm.page.body.find('[data-fieldname="fields"] [data-idx="'+ f.idx +'"] .data-row');

			if(f.is_custom_field) {
				data_row.addClass("highlight");
			} else {
				f._sortable = false;
			}
		});
		frm.fields_dict.fields.grid.refresh();
	},

	refresh: function(frm) {
		frm.disable_save();
		frm.page.clear_icons();

		if(frm.doc.doc_type) {
			frappe.customize_form.set_primary_action(frm);

			frm.add_custom_button(__('Refresh Form'), function() {
				frm.script_manager.trigger("doc_type");
			}, "fa fa-refresh", "btn-default");

			frm.add_custom_button(__('Reset to defaults'), function() {
				frappe.customize_form.confirm(__('Remove all customizations?'), frm);
			}, "fa fa-eraser", "btn-default");

			frm.add_custom_button(__('Set Permissions'), function() {
				frappe.set_route('permission-manager', frm.doc.doc_type);
			}, "fa fa-lock", "btn-default");

			if(frappe.boot.developer_mode) {
				frm.add_custom_button(__('Export Customizations'), function() {
					frappe.prompt(
						[
							{fieldtype:'Link', fieldname:'module', options:'Module Def',
								label: __('Module to Export')},
							{fieldtype:'Check', fieldname:'sync_on_migrate',
								label: __('Sync on Migrate'), 'default': 1},
							{fieldtype:'Check', fieldname:'with_permissions',
								label: __('Export Custom Permissions'), 'default': 1},
						],
						function(data) {
							frappe.call({
								method: 'frappe.modules.utils.export_customizations',
								args: {
									doctype: frm.doc.doc_type,
									module: data.module,
									sync_on_migrate: data.sync_on_migrate,
									with_permissions: data.with_permissions
								}
							});
						},
						__("Select Module"));
				});
			}
		}

		// sort order select
		if(frm.doc.doc_type) {
			var fields = $.map(frm.doc.fields,
					function(df) { return frappe.model.is_value_type(df.fieldtype) ? df.fieldname : null; });
			fields = ["", "name", "modified"].concat(fields);
			frm.set_df_property("sort_field", "options", fields);
		}

		if(frappe.route_options && frappe.route_options.doc_type) {
			setTimeout(function() {
				frm.set_value("doc_type", frappe.route_options.doc_type);
				frappe.route_options = null;
			}, 1000);
		}

	},

});

frappe.ui.form.on("Customize Form Field", {
	before_fields_remove: function(frm, doctype, name) {
		var row = frappe.get_doc(doctype, name);
		if(!(row.is_custom_field || row.__islocal)) {
			frappe.msgprint(__("Cannot delete standard field. You can hide it if you want"));
			throw "cannot delete custom field";
		}
	},
	fields_add: function(frm, cdt, cdn) {
		var f = frappe.model.get_doc(cdt, cdn);
		f.is_custom_field = 1;
	}
});

frappe.customize_form.set_primary_action = function(frm) {
	frm.page.set_primary_action(__("Update"), function() {
		if(frm.doc.doc_type) {
			return frm.call({
				doc: frm.doc,
				freeze: true,
				btn: frm.page.btn_primary,
				method: "save_customization",
				callback: function(r) {
					if(!r.exc) {
						frappe.customize_form.clear_locals_and_refresh(frm);
						frm.script_manager.trigger("doc_type");
					}
				}
			});
		}
	});
};

frappe.customize_form.confirm = function(msg, frm) {
	if(!frm.doc.doc_type) return;

	var d = new frappe.ui.Dialog({
		title: 'Reset To Defaults',
		fields: [
			{fieldtype:"HTML", options:__("All customizations will be removed. Please confirm.")},
		],
		primary_action: function() {
			return frm.call({
				doc: frm.doc,
				method: "reset_to_defaults",
				callback: function(r) {
					if(r.exc) {
						frappe.msgprint(r.exc);
					} else {
						d.hide();
						frappe.show_alert({message:__('Customizations Reset'), indicator:'green'});
						frappe.customize_form.clear_locals_and_refresh(frm);
					}
				}
			});
		}
	});

	frappe.customize_form.confirm.dialog = d;
	d.show();
}

frappe.customize_form.clear_locals_and_refresh = function(frm) {
	// clear doctype from locals
	frappe.model.clear_doc("DocType", frm.doc.doc_type);
	delete frappe.meta.docfield_copy[frm.doc.doc_type];

	frm.refresh();
}

<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

if (!Crossfire) var Crossfire = {};

// FirebugEventAdaptor
FBL.ns(function() { with(FBL) {

    /**
     * @name FirebugEventAdaptor
     * @constructor FirebugEventAdaptor
     * @description handles events on a per-context basis
     * @description and returns event arguments formatted as JSON objects.
     */
     function FirebugEventAdaptor( context) {
         this.context = context;
         this.contextId = context.Crossfire.crossfire_id;
         if (FBTrace.DBG_CROSSFIRE)
                FBTrace.sysout("CROSSFIRE Creating new FirebugEventAdaptor for context: " + this.contextId);
     }

     FirebugEventAdaptor.prototype =
         /**
          *  @lends FirebugEventAdaptor
          */
         {
             /**
              * @name FirebugEventAdaptor.onContextCreated
              * @function
              * @return context_id of the created context.
              */
             "onContextCreated": function() {
                 if (FBTrace.DBG_CROSSFIRE)
                     FBTrace.sysout("CROSSFIRE EventAdaptor onContextCreated");
                 var href;
                 try {
                     href = this.context.window.location.href;
                 } catch(e) {
                     href = "";
                 }
                 return { "context_id": this.contextId, "data": { "href": href } };
              },

              /**
                * @name FirebugEventAdaptor.onContextLoaded
                * @function
                * @return context_id of the loaded context.
                */
              "onContextLoaded": function() {
            	  if (FBTrace.DBG_CROSSFIRE)
                      FBTrace.sysout("CROSSFIRE EventAdaptor onContextLoaded");

                  var href;
                  try {
                      href = this.context.window.location.href;
                  } catch(e) {
                      href = "";
                  }
                  return { "context_id": this.contextId, "data": { "href": href } };
              },

              /**
               * @name FirebugEventAdaptor.onContextChanged
               * @function
               * @return old_context_id and new_context_id
               */
              "onContextChanged": function( newContext) {
            	  if (FBTrace.DBG_CROSSFIRE)
                      FBTrace.sysout("CROSSFIRE EventAdaptor onContextChanged");

                  var newContextId, newHref, href;

                  newContextId = newContext.Crossfire.crossfire_id;

                  try {
                      href = this.context.window.location.href;
                  } catch(e) {
                      href = "";
                  }

                  try {
                      newHref = newContext.window.location.href;
                  } catch(e) {
                      newHref = "";
                  }

                  return { "context_id": this.contextId, "new_context_id": newContextId, "data": { "href": href, "new_href": newHref } };

              },

              /**
               * @name FirebugEventAdaptor.onContextDestroyed
               * @function
               * @return context_id of the destroyed context.
               */
              "onContextDestroyed": function() {
                   if (FBTrace.DBG_CROSSFIRE)
                       FBTrace.sysout("CROSSFIRE EventAdaptor onContextDestroyed");
                   return { "context_id": this.contextId };
              },

             /**
              * @name FirebugEventAdaptor.onConsoleDebug
              * @function
              * @param data the data that was logged to the console with this console event.
              * @returns context_id, data
              */
            "onConsoleDebug": function( data) {
                 if (FBTrace.DBG_CROSSFIRE)
                     FBTrace.sysout("CROSSFIRE EventAdaptor onConsoleDebug");
                 return { "context_id": this.contextId, "data": data };
             },

             /**
              * @name FirebugEventAdaptor.onConsoleLog
              * @function
              * @param data the data that was logged to the console with this console event.
              * @returns context_id, data data associated with this console event.
              */
            "onConsoleLog": function( data) {
                 if (FBTrace.DBG_CROSSFIRE)
                     FBTrace.sysout("CROSSFIRE EventAdaptor onConsoleLog");
                 return { "context_id": this.contextId, "data": data };
             },

             /**
              * @name FirebugEventAdaptor.onConsoleInfo
              * @function
              * @param data the data that was logged to the console with this console event.
              * @returns context_id, data data associated with this console event.
              */
            "onConsoleInfo": function( data) {
                 if (FBTrace.DBG_CROSSFIRE)
                     FBTrace.sysout("CROSSFIRE EventAdaptor onConsoleInfo");
                 return { "context_id": this.contextId, "data": data };
             },

             /**
              * @name FirebugEventAdaptor.onConsoleWarn
              * @function
              * @param data the data that was logged to the console with this console event.
              * @returns context_id, data data associated with this console event.
              */
             "onConsoleWarn": function( data) {
                 if (FBTrace.DBG_CROSSFIRE)
                     FBTrace.sysout("CROSSFIRE EventAdaptor onConsoleWarn");
                 return { "context_id": this.contextId, "data": data };
             },

             /**
              * @name FirebugEventAdaptor.onConsoleError
              * @function
              * @param data the data that was logged to the console with this console event.
              * @returns context_id, data data associated with this console event.
              */
             "onConsoleError": function( data) {
                 if (FBTrace.DBG_CROSSFIRE)
                     FBTrace.sysout("CROSSFIRE EventAdaptor onConsoleError");
                 return { "context_id": this.contextId, "data": data };
             },

             /**
              * @name FirebugEventAdaptor.onScript
              * @function
              * @description Event that is generated when a new script is compiled
              * @param data
              * @returns context_id, data script that was created
              */
             "onScript": function( data) {
                  if (FBTrace.DBG_CROSSFIRE)
                      FBTrace.sysout("CROSSFIRE EventAdaptor onScript");
                  return {"context_id": this.contextId, "data": data };
             },

           /**
            * @name FirebugEventAdaptor.onBreak
            * @function
            * @description handles onBreak event.
            * @returns url, line and context_id
            */
           "onBreak": function() {
                if (FBTrace.DBG_CROSSFIRE)
                     FBTrace.sysout("CROSSFIRE EventAdaptor onBreak");
                var url, line;
                if ((typeof arguments[0]) == "number") {
                    line = arguments[0];
                    url = arguments[1];
                } else if ((typeof arguments[1]) == "number") {
                    line = arguments[1];
                    url = arguments[0];
                }
               return { "context_id": this.contextId, "data": { "url" : url, "line": line } };
            },

            /**
             * @name FirebugEventAdaptor.onResume
             * @function
             * @description handles onResume event.
             * @returns context_id
             */
            "onResume": function() {
                if (FBTrace.DBG_CROSSFIRE)
                     FBTrace.sysout("CROSSFIRE EventAdaptor onResume");
                return { "context_id": this.contextId };
            },

            /**
             * @name FirebugEventAdaptor.onToggleBreakpoint
             * @function
             * @description handles onToggleBreakpoint event.
             * @returns context_id
             */
            "onToggleBreakpoint": function() {
                if (FBTrace.DBG_CROSSFIRE)
                     FBTrace.sysout("CROSSFIRE EventAdaptor onToggleBreakpoint");
                return { "context_id": this.contextId };
            },

            /**
             * @name FirebugEventAdaptor.onInspectNode
             * @function
             * @param node the node that is being inspected.
             * @description handles onInspectNode event.
             * @description returns an xpath string that selects the inspected node.
             * @returns context_id, node
             */
            "onInspectNode": function( node) {
                if (FBTrace.DBG_CROSSFIRE)
                     FBTrace.sysout("CROSSFIRE EventAdaptor onInspectNode: ", node);

                if (FireDiff) { //FIXME: remove dependency on FireDiff
                    var nodePath = FireDiff.Path.getElementPath(node, true);
                }

                return { "context_id": this.contextId, "data": { "node": nodePath } };
            }
     };

     Crossfire.FirebugEventAdaptor = FirebugEventAdaptor;

// end FBL.ns
}});<commit_msg>Issue 3366: Crossfire's onInspectNode causes JS error if FireDiff not installed<commit_after>/* See license.txt for terms of usage */

if (!Crossfire) var Crossfire = {};

// FirebugEventAdaptor
FBL.ns(function() { with(FBL) {

    /**
     * @name FirebugEventAdaptor
     * @constructor FirebugEventAdaptor
     * @description handles events on a per-context basis
     * @description and returns event arguments formatted as JSON objects.
     */
     function FirebugEventAdaptor( context) {
         this.context = context;
         this.contextId = context.Crossfire.crossfire_id;
         if (FBTrace.DBG_CROSSFIRE)
                FBTrace.sysout("CROSSFIRE Creating new FirebugEventAdaptor for context: " + this.contextId);
     }

     FirebugEventAdaptor.prototype =
         /**
          *  @lends FirebugEventAdaptor
          */
         {
             /**
              * @name FirebugEventAdaptor.onContextCreated
              * @function
              * @return context_id of the created context.
              */
             "onContextCreated": function() {
                 if (FBTrace.DBG_CROSSFIRE)
                     FBTrace.sysout("CROSSFIRE EventAdaptor onContextCreated");
                 var href;
                 try {
                     href = this.context.window.location.href;
                 } catch(e) {
                     href = "";
                 }
                 return { "context_id": this.contextId, "data": { "href": href } };
              },

              /**
                * @name FirebugEventAdaptor.onContextLoaded
                * @function
                * @return context_id of the loaded context.
                */
              "onContextLoaded": function() {
            	  if (FBTrace.DBG_CROSSFIRE)
                      FBTrace.sysout("CROSSFIRE EventAdaptor onContextLoaded");

                  var href;
                  try {
                      href = this.context.window.location.href;
                  } catch(e) {
                      href = "";
                  }
                  return { "context_id": this.contextId, "data": { "href": href } };
              },

              /**
               * @name FirebugEventAdaptor.onContextChanged
               * @function
               * @return old_context_id and new_context_id
               */
              "onContextChanged": function( newContext) {
            	  if (FBTrace.DBG_CROSSFIRE)
                      FBTrace.sysout("CROSSFIRE EventAdaptor onContextChanged");

                  var newContextId, newHref, href;

                  newContextId = newContext.Crossfire.crossfire_id;

                  try {
                      href = this.context.window.location.href;
                  } catch(e) {
                      href = "";
                  }

                  try {
                      newHref = newContext.window.location.href;
                  } catch(e) {
                      newHref = "";
                  }

                  return { "context_id": this.contextId, "new_context_id": newContextId, "data": { "href": href, "new_href": newHref } };

              },

              /**
               * @name FirebugEventAdaptor.onContextDestroyed
               * @function
               * @return context_id of the destroyed context.
               */
              "onContextDestroyed": function() {
                   if (FBTrace.DBG_CROSSFIRE)
                       FBTrace.sysout("CROSSFIRE EventAdaptor onContextDestroyed");
                   return { "context_id": this.contextId };
              },

             /**
              * @name FirebugEventAdaptor.onConsoleDebug
              * @function
              * @param data the data that was logged to the console with this console event.
              * @returns context_id, data
              */
            "onConsoleDebug": function( data) {
                 if (FBTrace.DBG_CROSSFIRE)
                     FBTrace.sysout("CROSSFIRE EventAdaptor onConsoleDebug");
                 return { "context_id": this.contextId, "data": data };
             },

             /**
              * @name FirebugEventAdaptor.onConsoleLog
              * @function
              * @param data the data that was logged to the console with this console event.
              * @returns context_id, data data associated with this console event.
              */
            "onConsoleLog": function( data) {
                 if (FBTrace.DBG_CROSSFIRE)
                     FBTrace.sysout("CROSSFIRE EventAdaptor onConsoleLog");
                 return { "context_id": this.contextId, "data": data };
             },

             /**
              * @name FirebugEventAdaptor.onConsoleInfo
              * @function
              * @param data the data that was logged to the console with this console event.
              * @returns context_id, data data associated with this console event.
              */
            "onConsoleInfo": function( data) {
                 if (FBTrace.DBG_CROSSFIRE)
                     FBTrace.sysout("CROSSFIRE EventAdaptor onConsoleInfo");
                 return { "context_id": this.contextId, "data": data };
             },

             /**
              * @name FirebugEventAdaptor.onConsoleWarn
              * @function
              * @param data the data that was logged to the console with this console event.
              * @returns context_id, data data associated with this console event.
              */
             "onConsoleWarn": function( data) {
                 if (FBTrace.DBG_CROSSFIRE)
                     FBTrace.sysout("CROSSFIRE EventAdaptor onConsoleWarn");
                 return { "context_id": this.contextId, "data": data };
             },

             /**
              * @name FirebugEventAdaptor.onConsoleError
              * @function
              * @param data the data that was logged to the console with this console event.
              * @returns context_id, data data associated with this console event.
              */
             "onConsoleError": function( data) {
                 if (FBTrace.DBG_CROSSFIRE)
                     FBTrace.sysout("CROSSFIRE EventAdaptor onConsoleError");
                 return { "context_id": this.contextId, "data": data };
             },

             /**
              * @name FirebugEventAdaptor.onScript
              * @function
              * @description Event that is generated when a new script is compiled
              * @param data
              * @returns context_id, data script that was created
              */
             "onScript": function( data) {
                  if (FBTrace.DBG_CROSSFIRE)
                      FBTrace.sysout("CROSSFIRE EventAdaptor onScript");
                  return {"context_id": this.contextId, "data": data };
             },

           /**
            * @name FirebugEventAdaptor.onBreak
            * @function
            * @description handles onBreak event.
            * @returns url, line and context_id
            */
           "onBreak": function() {
                if (FBTrace.DBG_CROSSFIRE)
                     FBTrace.sysout("CROSSFIRE EventAdaptor onBreak");
                var url, line;
                if ((typeof arguments[0]) == "number") {
                    line = arguments[0];
                    url = arguments[1];
                } else if ((typeof arguments[1]) == "number") {
                    line = arguments[1];
                    url = arguments[0];
                }
               return { "context_id": this.contextId, "data": { "url" : url, "line": line } };
            },

            /**
             * @name FirebugEventAdaptor.onResume
             * @function
             * @description handles onResume event.
             * @returns context_id
             */
            "onResume": function() {
                if (FBTrace.DBG_CROSSFIRE)
                     FBTrace.sysout("CROSSFIRE EventAdaptor onResume");
                return { "context_id": this.contextId };
            },

            /**
             * @name FirebugEventAdaptor.onToggleBreakpoint
             * @function
             * @description handles onToggleBreakpoint event.
             * @returns context_id
             */
            "onToggleBreakpoint": function() {
                if (FBTrace.DBG_CROSSFIRE)
                     FBTrace.sysout("CROSSFIRE EventAdaptor onToggleBreakpoint");
                return { "context_id": this.contextId };
            },

            /**
             * @name FirebugEventAdaptor.onInspectNode
             * @function
             * @param node the node that is being inspected.
             * @description handles onInspectNode event.
             * @description returns an xpath string that selects the inspected node.
             * @returns context_id, node
             */
            "onInspectNode": function( node) {
                if (FBTrace.DBG_CROSSFIRE)
                     FBTrace.sysout("CROSSFIRE EventAdaptor onInspectNode: ", node);

                if (typeof FireDiff != 'undefined') { //FIXME: remove dependency on FireDiff
                    var nodePath = FireDiff.Path.getElementPath(node, true);
                }

                return { "context_id": this.contextId, "data": { "node": nodePath } };
            }
     };

     Crossfire.FirebugEventAdaptor = FirebugEventAdaptor;

// end FBL.ns
}});<|endoftext|>


<commit_before>const Promise = require('bluebird');
const common = require('../../../../lib/common');
const schema = require('../../../schema');

/*
 * [{
 *   tableName: 'posts',
 *   columns: ['custom_excerpt', 'description', 'etc...']
 * }]
 * */
const tablesToUpdate = Object.keys(schema.tables).reduce((tablesToUpdate, tableName) => {
    const table = schema.tables[tableName];
    const columns = Object.keys(table).filter((columnName) => {
        const column = table[columnName];
        return column.nullable && ['string', 'text'].includes(column.type);
    });
    if (!columns.length) {
        return tablesToUpdate;
    }
    return tablesToUpdate.concat({
        tableName,
        columns
    });
}, []);

const createReplace = (connection, from, to) => (tableName, columnName) => {
    return connection.schema.hasTable(tableName)
        .then((tableExists) => {
            if (!tableExists) {
                common.logging.warn(
                    `Table ${tableName} does not exist`
                );
                return;
            }
            return connection.schema.hasColumn(tableName, columnName)
                .then((columnExists) => {
                    if (!columnExists) {
                        common.logging.warn(
                            `Table '${tableName}' does not have column '${columnName}'`
                        );
                        return;
                    }

                    common.logging.info(
                        `Updating ${tableName}, setting '${from}' in ${columnName} to '${to}'`
                    );

                    return connection(tableName)
                        .where(columnName, from)
                        .update(columnName, to);
                });
        });
};

module.exports.up = ({transacting}) => {
    const replaceEmptyStringWithNull = createReplace(transacting, '', null);

    return Promise.all(
        tablesToUpdate.map(({tableName, columns}) => Promise.all(
            columns.map(
                columnName => replaceEmptyStringWithNull(tableName, columnName)
            )
        ))
    );
};

module.exports.down = ({connection}) => {
    const replaceNullWithEmptyString = createReplace(connection, null, '');

    return Promise.all(
        tablesToUpdate.map(({tableName, columns}) => Promise.all(
            columns.map(
                columnName => replaceNullWithEmptyString(tableName, columnName)
            )
        ))
    );
};

module.exports.config = {
    transaction: true
};
<commit_msg>Fixed error rolling back the "remove empty strings" migration<commit_after>const Promise = require('bluebird');
const common = require('../../../../lib/common');
const schema = require('../../../schema');

/*
 * [{
 *   tableName: 'posts',
 *   columns: ['custom_excerpt', 'description', 'etc...']
 * }]
 * */
const tablesToUpdate = Object.keys(schema.tables).reduce((tablesToUpdate, tableName) => {
    const table = schema.tables[tableName];
    const columns = Object.keys(table).filter((columnName) => {
        const column = table[columnName];
        return column.nullable && ['string', 'text'].includes(column.type);
    });
    if (!columns.length) {
        return tablesToUpdate;
    }
    return tablesToUpdate.concat({
        tableName,
        columns
    });
}, []);

const createReplace = (connection, from, to) => (tableName, columnName) => {
    return connection.schema.hasTable(tableName)
        .then((tableExists) => {
            if (!tableExists) {
                common.logging.warn(
                    `Table ${tableName} does not exist`
                );
                return;
            }
            return connection.schema.hasColumn(tableName, columnName)
                .then((columnExists) => {
                    if (!columnExists) {
                        common.logging.warn(
                            `Table '${tableName}' does not have column '${columnName}'`
                        );
                        return;
                    }

                    common.logging.info(
                        `Updating ${tableName}, setting '${from}' in ${columnName} to '${to}'`
                    );

                    return connection(tableName)
                        .where(columnName, from)
                        .update(columnName, to);
                });
        });
};

module.exports.up = ({transacting}) => {
    const replaceEmptyStringWithNull = createReplace(transacting, '', null);

    return Promise.all(
        tablesToUpdate.map(({tableName, columns}) => Promise.all(
            columns.map(
                columnName => replaceEmptyStringWithNull(tableName, columnName)
            )
        ))
    );
};

module.exports.down = ({transacting}) => {
    const replaceNullWithEmptyString = createReplace(transacting, null, '');

    return Promise.all(
        tablesToUpdate.map(({tableName, columns}) => Promise.all(
            columns.map(
                columnName => replaceNullWithEmptyString(tableName, columnName)
            )
        ))
    );
};

module.exports.config = {
    transaction: true
};
<|endoftext|>


<commit_before>/*
Copyright 2016 The Eyra 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.

File author/s:
    Matthias Petursson <oldschool01123@gmail.com>
*/

(function () {
'use strict';

angular.module('daApp')
.controller('MainController', MainController);

MainController.$inject = ['$location',
                          '$q',
                          '$rootScope',
                          '$scope',
                          '$window',
                          'androidRecordingService',
                          'locationService',
                          'logger',
                          'myLocalForageService',
                          'recordingService',
                          'routeService',
                          'tokenService',
                          'utilityService'];

function MainController($location,
                        $q,
                        $rootScope,
                        $scope,
                        $window,
                        androidRecordingService,
                        locationService,
                        logger,
                        myLocalForageService,
                        recordingService,
                        routeService,
                        tokenService,
                        utilityService) {
  var mainCtrl = this;
  var locService = locationService;
  var lfService = myLocalForageService;
  var recService = recordingService;
  var tokService = tokenService;
  var util = utilityService;
  $scope.info = util.getConstant('INFO');

  $scope.startText = util.getConstant('STARTTEXT');

  // because of a 8k filtering issue, detect if we are in an the Android webview app fix
  //   in which case use a different recorder from the web audio API
  var ANDROID;
  try {
    // AndroidRecorder is interface from WebView
    ANDROID = AndroidRecorder;
  } catch (e) {
    // we are not in a webview here, pass
  }
  if (ANDROID) {
    $rootScope.isWebView = true;
    recService = androidRecordingService;
  } else {
    $rootScope.isWebView = false;
  }

  mainCtrl.start = start;

  $rootScope.isLoaded = false;

  var recorderPromise, tokensPromise, initPromises;
  if (!$rootScope.appInitialized) {
    // promises for everything async that needs to be done for app to count as initialized
    recorderPromise = $q.defer();
    tokensPromise = $q.defer();
    initPromises = {  'recorder' : recorderPromise.promise,
                      'tokens'   : tokensPromise.promise};

    init();
  } else {
    $rootScope.isLoaded = true;
  }

  //////////

  function init() {
    // synchronous things
    // make sure user gets warning on navigate away from page if local db operations are going on still
    $window.addEventListener('beforeunload', function(e){
      if (lfService.inProgress()) {
        var msg =   'Are you sure you want to navigate away?\n\
                     There is still possibly important processing going on in the app.';

        // https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload
        // browsers still seem to ignore this message, at least some..
        //   at least they show a warning
        (e || $window.event).returnValue = msg;
        return msg;
      }
    });

    // async things
    locService.init(locServiceInitDoneCallback); // lets not require location
    recService.init(recServiceInitDoneCallback);
    getTokensIfNeeded();

    $q.all(initPromises).then(function(tasksComplete){
      $rootScope.appInitialized = true;
      logger.log('App initialized.');

      $rootScope.isLoaded = true;
    },
    // this means our app didn't initialize.. we should probably do something if that happens
    function error(data){
      $scope.msg = util.getConstant('APPINITIALIZATIONFAILMSG');
      logger.error(data);
    });
    $scope.info = 'stebbs'; //util.getConstant('INFO');
    $scope.startText = util.getConstant('STARTTEXT');
    console.log($scope.info);
  }

  function getTokensIfNeeded() {
    tokenService.countAvailableTokens().then(function(numTokens){
      if (numTokens < util.getConstant('tokenThreshold')) {
        $rootScope.loading_msg = util.getConstant('GETPROMPTSMSGTEXT');
        logger.log('Getting tokens..');
        tokenService.getTokens(util.getConstant('tokenGetCount')).then(function(tokens){
          tokensPromise.resolve(true);
          logger.log('Got tokens.');
          $rootScope.loading_msg = util.getConstant('WAITINGTEXT');
        },
        function error(data){
          tokensPromise.reject(data);
          logger.log('Failed getting tokens.');
          $rootScope.loading_msg = util.getConstant('FAILEDTOGETTOKENS');
          logger.error(data);
        });
      } else {
        // we are still okay, just didn't get any tokens, so resolve not reject here.
        tokensPromise.resolve(false);
      }
    }, function error(data){
      tokensPromise.reject(data);
      logger.error(data);
    });
  }

  function locServiceInitDoneCallback(result) {
    if (result) {
      logger.log('Location successfully set.');
    } else {
      logger.log('No location set.');
    }
  }

  function recServiceInitDoneCallback(result) {
    if (result)
      recorderPromise.resolve(true);
    else
      recorderPromise.reject('Recorder not initialized.');
  }

  // NAVIGATION //

  function start() {
    if (util.getConstant('RECAGREEMENT') && !$rootScope.agreementSigned) {
      $location.path('/recording-agreement');
    } else {
      $location.path('/start');
    }
  }
}
}());
<commit_msg>delete useless logging<commit_after>/*
Copyright 2016 The Eyra 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.

File author/s:
    Matthias Petursson <oldschool01123@gmail.com>
*/

(function () {
'use strict';

angular.module('daApp')
.controller('MainController', MainController);

MainController.$inject = ['$location',
                          '$q',
                          '$rootScope',
                          '$scope',
                          '$window',
                          'androidRecordingService',
                          'locationService',
                          'logger',
                          'myLocalForageService',
                          'recordingService',
                          'routeService',
                          'tokenService',
                          'utilityService'];

function MainController($location,
                        $q,
                        $rootScope,
                        $scope,
                        $window,
                        androidRecordingService,
                        locationService,
                        logger,
                        myLocalForageService,
                        recordingService,
                        routeService,
                        tokenService,
                        utilityService) {
  var mainCtrl = this;
  var locService = locationService;
  var lfService = myLocalForageService;
  var recService = recordingService;
  var tokService = tokenService;
  var util = utilityService;
  $scope.info = util.getConstant('INFO');

  $scope.startText = util.getConstant('STARTTEXT');

  // because of a 8k filtering issue, detect if we are in an the Android webview app fix
  //   in which case use a different recorder from the web audio API
  var ANDROID;
  try {
    // AndroidRecorder is interface from WebView
    ANDROID = AndroidRecorder;
  } catch (e) {
    // we are not in a webview here, pass
  }
  if (ANDROID) {
    $rootScope.isWebView = true;
    recService = androidRecordingService;
  } else {
    $rootScope.isWebView = false;
  }

  mainCtrl.start = start;

  $rootScope.isLoaded = false;

  var recorderPromise, tokensPromise, initPromises;
  if (!$rootScope.appInitialized) {
    // promises for everything async that needs to be done for app to count as initialized
    recorderPromise = $q.defer();
    tokensPromise = $q.defer();
    initPromises = {  'recorder' : recorderPromise.promise,
                      'tokens'   : tokensPromise.promise};

    init();
  } else {
    $rootScope.isLoaded = true;
  }

  //////////

  function init() {
    // synchronous things
    // make sure user gets warning on navigate away from page if local db operations are going on still
    $window.addEventListener('beforeunload', function(e){
      if (lfService.inProgress()) {
        var msg =   'Are you sure you want to navigate away?\n\
                     There is still possibly important processing going on in the app.';

        // https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload
        // browsers still seem to ignore this message, at least some..
        //   at least they show a warning
        (e || $window.event).returnValue = msg;
        return msg;
      }
    });

    // async things
    locService.init(locServiceInitDoneCallback); // lets not require location
    recService.init(recServiceInitDoneCallback);
    getTokensIfNeeded();

    $q.all(initPromises).then(function(tasksComplete){
      $rootScope.appInitialized = true;
      logger.log('App initialized.');

      $rootScope.isLoaded = true;
    },
    // this means our app didn't initialize.. we should probably do something if that happens
    function error(data){
      $scope.msg = util.getConstant('APPINITIALIZATIONFAILMSG');
      logger.error(data);
    });
    $scope.startText = util.getConstant('STARTTEXT');
  }

  function getTokensIfNeeded() {
    tokenService.countAvailableTokens().then(function(numTokens){
      if (numTokens < util.getConstant('tokenThreshold')) {
        $rootScope.loading_msg = util.getConstant('GETPROMPTSMSGTEXT');
        logger.log('Getting tokens..');
        tokenService.getTokens(util.getConstant('tokenGetCount')).then(function(tokens){
          tokensPromise.resolve(true);
          logger.log('Got tokens.');
          $rootScope.loading_msg = util.getConstant('WAITINGTEXT');
        },
        function error(data){
          tokensPromise.reject(data);
          logger.log('Failed getting tokens.');
          $rootScope.loading_msg = util.getConstant('FAILEDTOGETTOKENS');
          logger.error(data);
        });
      } else {
        // we are still okay, just didn't get any tokens, so resolve not reject here.
        tokensPromise.resolve(false);
      }
    }, function error(data){
      tokensPromise.reject(data);
      logger.error(data);
    });
  }

  function locServiceInitDoneCallback(result) {
    if (result) {
      logger.log('Location successfully set.');
    } else {
      logger.log('No location set.');
    }
  }

  function recServiceInitDoneCallback(result) {
    if (result)
      recorderPromise.resolve(true);
    else
      recorderPromise.reject('Recorder not initialized.');
  }

  // NAVIGATION //

  function start() {
    if (util.getConstant('RECAGREEMENT') && !$rootScope.agreementSigned) {
      $location.path('/recording-agreement');
    } else {
      $location.path('/start');
    }
  }
}
}());
<|endoftext|>


<commit_before>
import React from 'react';
import PureComponent from 'react-pure-render/component';
import ReactDOM from 'react-dom';

import Qustom from '../../src/index';

class App extends PureComponent {

    constructor(props) {
        super(props);
        this.receiveClientMessage = this.receiveClientMessage.bind(this);
        this.state = {
            clientData: ''
        };
    }

    componentDidMount() {
        // Create IE + others compatible event handler
        const eventMethod = window.addEventListener ? 'addEventListener' : 'attachEvent';
        const eventer = window[eventMethod];
        const messageEvent = eventMethod === 'attachEvent' ? 'onmessage' : 'message';
        eventer(messageEvent, (e) => this.receiveClientMessage(e), false);
    }

    render() {
        // TODO: get surveyID/accountID from Client
        return (

                <Qustom
                    accountid="context.authorizer.principalId"
                    surveyid="759e7930-3219-11e6-b8fc-ed3df7fb1eab"
                    localize_path="../../assets/L10N"
                    type="embedded"
                />

        );
    }

    receiveClientMessage(e) {
        // TODO: event origin detection
        // if (e.origin !== 'https://qustomURL') return;
        console.log('Message received from Client!:  ', e.data);
        this.setState({
            clientData: e.data
        });
    }
}

function initApp() {
    ReactDOM.render(
        <App />,
        document.getElementById('main')
    );
}

initApp();

if (module.hot) {
    module.hot.accept();
}
<commit_msg>Change recieve client postMessage timing.<commit_after>
import React from 'react';
import PureComponent from 'react-pure-render/component';
import ReactDOM from 'react-dom';

import Qustom from '../../src/index';

class App extends PureComponent {
    render() {
        // TODO: get surveyID/accountID from Client
        return (

                <Qustom {...this.props} />

        );
    }
}

function initApp(accountID, surveyID, type) {
    const props = {
        accountid: accountID || 'context.authorizer.principalId',
        surveyid: surveyID || '759e7930-3219-11e6-b8fc-ed3df7fb1eab',
        type: type || 'preview',
        localize_path: '../../assets/L10N'
    };

    if (accountID && surveyID) {
        ReactDOM.render(
            <App {...props} />,
            document.getElementById('main')
        );
    } else {
        console.log('Survey ID / Account ID required');
    }
}

// Create IE + others compatible event handler

function receiveClientMessage(e) {
    console.log(e.origin);
    console.log(e.data.source);
    if (e.origin !== e.data.source) return;
    console.log('Message received from Client!:  ', e.data);
    initApp(e.data.accountID, e.data.surveyID, 'embedded');
}

const eventMethod = window.addEventListener ? 'addEventListener' : 'attachEvent';
const eventer = window[eventMethod];
const messageEvent = eventMethod === 'attachEvent' ? 'onmessage' : 'message';
eventer(messageEvent, (e) => receiveClientMessage(e), false);

initApp();

if (module.hot) {
    module.hot.accept();
}
<|endoftext|>