Changeset - f4e158ed49b1
kallithea/public/js/base.js
Show inline comments
 
/**
 
Kallithea JS Files
 
**/
 
'use strict';
 

	
 
if (typeof console == "undefined" || typeof console.log == "undefined"){
 
    console = { log: function() {} }
 
}
 

	
 
/**
 
 * INJECT .html_escape function into String
 
 * Usage: "unsafe string".html_escape()
 
 *
 
 * This is the Javascript equivalent of kallithea.lib.helpers.html_escape(). It
 
 * will escape HTML characters to prevent XSS or other issues.  It should be
 
 * used in all cases where Javascript code is inserting potentially unsafe data
 
 * into the document.
 
 *
 
 * For example:
 
 *      <script>confirm("boo")</script>
 
 * is changed into:
 
 *      &lt;script&gt;confirm(&quot;boo&quot;)&lt;/script&gt;
 
 *
 
 */
 
String.prototype.html_escape = function() {
 
    return this
 
        .replace(/&/g,'&amp;')
 
        .replace(/</g,'&lt;')
 
        .replace(/>/g,'&gt;')
 
        .replace(/"/g, '&quot;')
 
        .replace(/'/g, '&#039;');
 
}
 

	
 
/**
 
 * INJECT .format function into String
 
 * Usage: "My name is {0} {1}".format("Johny","Bravo")
 
 * Return "My name is Johny Bravo"
 
 * Inspired by https://gist.github.com/1049426
 
 */
 
String.prototype.format = function() {
 
    function format() {
 
        var str = this;
 
        var len = arguments.length+1;
 
        var safe = undefined;
 
        var arg = undefined;
 

	
 
        // For each {0} {1} {n...} replace with the argument in that position.  If
 
        // the argument is an object or an array it will be stringified to JSON.
 
        for (var i=0; i < len; arg = arguments[i++]) {
 
            safe = typeof arg === 'object' ? JSON.stringify(arg) : arg;
 
            str = str.replace(RegExp('\\{'+(i-1)+'\\}', 'g'), safe);
 
        }
 
        return str;
 
    }
 

	
 
    // Save a reference of what may already exist under the property native.
 
    // Allows for doing something like: if("".format.native) { /* use native */ }
 
    format.native = String.prototype.format;
 

	
 
    // Replace the prototype property
 
    return format;
 

	
 
}();
 

	
 
String.prototype.strip = function(char) {
 
    if(char === undefined){
 
        char = '\\s';
 
    }
 
    return this.replace(new RegExp('^'+char+'+|'+char+'+$','g'), '');
 
}
 

	
 
String.prototype.lstrip = function(char) {
 
    if(char === undefined){
 
        char = '\\s';
 
    }
 
    return this.replace(new RegExp('^'+char+'+'),'');
 
}
 

	
 
String.prototype.rstrip = function(char) {
 
    if(char === undefined){
 
        char = '\\s';
 
    }
 
    return this.replace(new RegExp(''+char+'+$'),'');
 
}
 

	
 
/* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Polyfill
 
   under MIT license / public domain, see
 
   https://developer.mozilla.org/en-US/docs/MDN/About#Copyrights_and_licenses */
 
if(!Array.prototype.indexOf) {
 
    Array.prototype.indexOf = function (searchElement, fromIndex) {
 
        if ( this === undefined || this === null ) {
 
            throw new TypeError( '"this" is null or not defined' );
 
        }
 

	
 
        var length = this.length >>> 0; // Hack to convert object.length to a UInt32
 

	
 
        fromIndex = +fromIndex || 0;
 

	
 
        if (Math.abs(fromIndex) === Infinity) {
 
            fromIndex = 0;
 
        }
 

	
 
        if (fromIndex < 0) {
 
            fromIndex += length;
 
            if (fromIndex < 0) {
 
                fromIndex = 0;
 
            }
 
        }
 

	
 
        for (;fromIndex < length; fromIndex++) {
 
            if (this[fromIndex] === searchElement) {
 
                return fromIndex;
 
            }
 
        }
 

	
 
        return -1;
 
    };
 
}
 

	
 
/* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Compatibility
 
   under MIT license / public domain, see
 
   https://developer.mozilla.org/en-US/docs/MDN/About#Copyrights_and_licenses */
 
if (!Array.prototype.filter)
 
{
 
    Array.prototype.filter = function(fun /*, thisArg */)
 
    {
 
        if (this === void 0 || this === null)
 
            throw new TypeError();
 

	
 
        var t = Object(this);
 
        var len = t.length >>> 0;
 
        if (typeof fun !== "function")
 
            throw new TypeError();
 

	
 
        var res = [];
 
        var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
 
        for (var i = 0; i < len; i++)
 
        {
 
            if (i in t)
 
            {
 
                var val = t[i];
 

	
 
                // NOTE: Technically this should Object.defineProperty at
 
                //       the next index, as push can be affected by
 
                //       properties on Object.prototype and Array.prototype.
 
                //       But that method's new, and collisions should be
 
                //       rare, so use the more-compatible alternative.
 
                if (fun.call(thisArg, val, i, t))
 
                    res.push(val);
 
            }
 
        }
 

	
 
        return res;
 
    };
 
}
 

	
 
/**
 
 * A customized version of PyRoutes.JS from https://pypi.python.org/pypi/pyroutes.js/
 
 * which is copyright Stephane Klein and was made available under the BSD License.
 
 *
 
 * Usage pyroutes.url('mark_error_fixed',{"error_id":error_id}) // /mark_error_fixed/<error_id>
 
 */
 
var pyroutes = (function() {
 
    var matchlist = {};
 
    var sprintf = (function() {
 
        function get_type(variable) {
 
            return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
 
        }
 
        function str_repeat(input, multiplier) {
 
            for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
 
            return output.join('');
 
        }
 

	
 
        var str_format = function() {
 
        function str_format() {
 
            if (!str_format.cache.hasOwnProperty(arguments[0])) {
 
                str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
 
            }
 
            return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
 
        };
 
        }
 

	
 
        str_format.format = function(parse_tree, argv) {
 
            var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
 
            for (i = 0; i < tree_length; i++) {
 
                node_type = get_type(parse_tree[i]);
 
                if (node_type === 'string') {
 
                    output.push(parse_tree[i]);
 
                }
 
                else if (node_type === 'array') {
 
                    match = parse_tree[i]; // convenience purposes only
 
                    if (match[2]) { // keyword argument
 
                        arg = argv[cursor];
 
                        for (k = 0; k < match[2].length; k++) {
 
                            if (!arg.hasOwnProperty(match[2][k])) {
 
                                throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
 
                            }
 
                            arg = arg[match[2][k]];
 
                        }
 
                    }
 
                    else if (match[1]) { // positional argument (explicit)
 
                        arg = argv[match[1]];
 
                    }
 
                    else { // positional argument (implicit)
 
                        arg = argv[cursor++];
 
                    }
 

	
 
                    if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
 
                        throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
 
                    }
 
                    switch (match[8]) {
 
                        case 'b': arg = arg.toString(2); break;
 
                        case 'c': arg = String.fromCharCode(arg); break;
 
                        case 'd': arg = parseInt(arg, 10); break;
 
                        case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
 
                        case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
 
                        case 'o': arg = arg.toString(8); break;
 
                        case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
 
                        case 'u': arg = Math.abs(arg); break;
 
                        case 'x': arg = arg.toString(16); break;
 
                        case 'X': arg = arg.toString(16).toUpperCase(); break;
 
                    }
 
                    arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
 
                    pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
 
                    pad_length = match[6] - String(arg).length;
 
                    pad = match[6] ? str_repeat(pad_character, pad_length) : '';
 
                    output.push(match[5] ? arg + pad : pad + arg);
 
                }
 
            }
 
            return output.join('');
 
        };
 

	
 
        str_format.cache = {};
 

	
 
        str_format.parse = function(fmt) {
 
            var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
 
            while (_fmt) {
 
                if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
 
                    parse_tree.push(match[0]);
 
                }
 
                else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
 
                    parse_tree.push('%');
 
                }
 
                else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
 
                    if (match[2]) {
 
                        arg_names |= 1;
 
                        var field_list = [], replacement_field = match[2], field_match = [];
 
                        if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
 
                            field_list.push(field_match[1]);
 
                            while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
 
                                if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
 
                                    field_list.push(field_match[1]);
 
                                }
 
                                else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
 
                                    field_list.push(field_match[1]);
 
                                }
 
                                else {
 
                                    throw('[sprintf] huh?');
 
                                }
 
                            }
 
                        }
 
                        else {
 
                            throw('[sprintf] huh?');
 
                        }
 
                        match[2] = field_list;
 
                    }
 
                    else {
 
                        arg_names |= 2;
 
                    }
 
                    if (arg_names === 3) {
 
                        throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
 
                    }
 
                    parse_tree.push(match);
 
                }
 
                else {
 
                    throw('[sprintf] huh?');
 
                }
 
                _fmt = _fmt.substring(match[0].length);
 
            }
 
            return parse_tree;
 
        };
 

	
 
        return str_format;
 
    })();
 

	
 
    var vsprintf = function(fmt, argv) {
 
        argv.unshift(fmt);
 
        return sprintf.apply(null, argv);
 
    };
 
    return {
 
        'url': function(route_name, params) {
 
            var result = route_name;
 
            if (typeof(params) != 'object'){
 
                params = {};
 
            }
 
            if (matchlist.hasOwnProperty(route_name)) {
 
                var route = matchlist[route_name];
 
                // param substitution
 
                for(var i=0; i < route[1].length; i++) {
 
                   if (!params.hasOwnProperty(route[1][i]))
 
                        throw new Error(route[1][i] + ' missing in "' + route_name + '" route generation');
 
                }
 
                result = sprintf(route[0], params);
 

	
 
                var ret = [];
 
                //extra params => GET
 
                for(var param in params){
 
                    if (route[1].indexOf(param) == -1){
 
                        ret.push(encodeURIComponent(param) + "=" + encodeURIComponent(params[param]));
 
                    }
 
                }
 
                var _parts = ret.join("&");
 
                if(_parts){
 
                    result = result +'?'+ _parts
 
                }
 
            }
 

	
 
            return result;
 
        },
 
        'register': function(route_name, route_tmpl, req_params) {
 
            if (typeof(req_params) != 'object') {
 
                req_params = [];
 
            }
 
            var keys = [];
 
            for (var i=0; i < req_params.length; i++) {
 
                keys.push(req_params[i]);
 
            }
 
            matchlist[route_name] = [
 
                unescape(route_tmpl),
 
                keys
 
            ]
 
        },
 
        '_routes': function(){
 
            return matchlist;
 
        }
 
    }
 
})();
 

	
 

	
 
/* Invoke all functions in callbacks */
 
var _run_callbacks = function(callbacks){
 
    if (callbacks !== undefined){
 
        var _l = callbacks.length;
 
        for (var i=0;i<_l;i++){
 
            var func = callbacks[i];
 
            if(typeof(func)=='function'){
 
                try{
 
                    func();
 
                }catch (err){};
 
            }
 
        }
 
    }
 
}
 

	
 
/**
 
 * turns objects into GET query string
 
 */
 
function _toQueryString(o) {
 
    if(typeof o !== 'object') {
 
        return false;
 
    }
 
    var _p, _qs = [];
 
    for(_p in o) {
 
        _qs.push(encodeURIComponent(_p) + '=' + encodeURIComponent(o[_p]));
 
    }
 
    return _qs.join('&');
 
}
 

	
 
/**
 
 * Load HTML into DOM using Ajax
 
 *
 
 * @param $target: load html async and place it (or an error message) here
 
 * @param success: success callback function
 
 * @param args: query parameters to pass to url
 
 */
 
function asynchtml(url, $target, success, args){
 
    if(args===undefined){
 
        args=null;
 
    }
 
    $target.html(_TM['Loading ...']).css('opacity','0.3');
 

	
 
    return $.ajax({url: url, data: args, headers: {'X-PARTIAL-XHR': '1'}, cache: false, dataType: 'html'})
 
        .done(function(html) {
 
                $target.html(html);
 
                $target.css('opacity','1.0');
 
                //execute the given original callback
 
                if (success !== undefined && success) {
 
                    success();
 
                }
 
            })
 
        .fail(function(jqXHR, textStatus, errorThrown) {
 
                if (textStatus == "abort")
 
                    return;
 
                $target.html('<span class="bg-danger">ERROR: {0}</span>'.format(textStatus));
 
                $target.css('opacity','1.0');
 
            })
 
        ;
 
};
 

	
 
function ajaxGET(url, success, failure) {
 
    if(failure === undefined) {
 
        failure = function(jqXHR, textStatus, errorThrown) {
 
                if (textStatus != "abort")
 
                    alert("Ajax GET error: " + textStatus);
 
            };
 
    }
 
    return $.ajax({url: url, headers: {'X-PARTIAL-XHR': '1'}, cache: false})
 
        .done(success)
 
        .fail(failure);
 
}
 

	
 
function ajaxPOST(url, postData, success, failure) {
 
    postData['_session_csrf_secret_token'] = _session_csrf_secret_token;
 
    var postData = _toQueryString(postData);
 
    if(failure === undefined) {
 
        failure = function(jqXHR, textStatus, errorThrown) {
 
                if (textStatus != "abort")
 
                    alert("Error posting to server: " + textStatus);
 
            };
 
    }
 
    return $.ajax({url: url, data: postData, type: 'POST', headers: {'X-PARTIAL-XHR': '1'}, cache: false})
 
        .done(success)
 
        .fail(failure);
 
}
 

	
 

	
 
/**
 
 * activate .show_more links
 
 * the .show_more must have an id that is the the id of an element to hide prefixed with _
 
 * the parentnode will be displayed
 
 */
 
function show_more_event(){
 
    $('.show_more').click(function(e){
 
        var el = e.currentTarget;
 
        $('#' + el.id.substring(1)).hide();
 
        $(el.parentNode).show();
 
    });
 
}
 

	
 

	
 
function _onSuccessFollow(target){
 
    var $target = $(target);
 
    var $f_cnt = $('#current_followers_count');
 
    if ($target.hasClass('follow')) {
 
        $target.removeClass('follow').addClass('following');
 
        $target.prop('title', _TM['Stop following this repository']);
 
        if ($f_cnt.html()) {
 
            var cnt = Number($f_cnt.html())+1;
 
            $f_cnt.html(cnt);
 
        }
 
    } else {
 
        $target.removeClass('following').addClass('follow');
 
        $target.prop('title', _TM['Start following this repository']);
 
        if ($f_cnt.html()) {
 
            var cnt = Number($f_cnt.html())-1;
 
            $f_cnt.html(cnt);
 
        }
 
    }
 
}
 

	
 
function toggleFollowingRepo(target, follows_repository_id){
 
    var args = {
 
        'follows_repository_id': follows_repository_id,
 
        '_session_csrf_secret_token': _session_csrf_secret_token
 
    }
 
    $.post(TOGGLE_FOLLOW_URL, args, function(data){
 
            _onSuccessFollow(target);
 
        });
 
    return false;
 
}
 

	
 
function showRepoSize(target, repo_name){
 
    var args = '_session_csrf_secret_token=' + _session_csrf_secret_token;
 

	
 
    if(!$("#" + target).hasClass('loaded')){
 
        $("#" + target).html(_TM['Loading ...']);
 
        var url = pyroutes.url('repo_size', {"repo_name":repo_name});
 
        $.post(url, args, function(data) {
 
            $("#" + target).html(data);
 
            $("#" + target).addClass('loaded');
 
        });
 
    }
 
    return false;
 
}
 

	
 
/**
 
 * load tooltips dynamically based on data attributes, used for .lazy-cs changeset links
 
 */
 
function get_changeset_tooltip() {
 
    var $target = $(this);
 
    var tooltip = $target.data('tooltip');
 
    if (!tooltip) {
 
        var raw_id = $target.data('raw_id');
 
        var repo_name = $target.data('repo_name');
 
        var url = pyroutes.url('changeset_info', {"repo_name": repo_name, "revision": raw_id});
 

	
 
        $.ajax(url, {
 
            async: false,
 
            success: function(data) {
 
                tooltip = data["message"];
 
            }
 
        });
 
        $target.data('tooltip', tooltip);
 
    }
 
    return tooltip;
 
}
 

	
 
/**
 
 * activate tooltips and popups
 
 */
 
function tooltip_activate(){
 
    function placement(p, e){
 
        if(e.getBoundingClientRect().top > 2*$(window).height()/3){
 
            return 'top';
 
        }else{
 
            return 'bottom';
 
        }
 
    }
 
    $(document).ready(function(){
 
        $('[data-toggle="tooltip"]').tooltip({
 
            container: 'body',
 
            placement: placement
 
        });
 
        $('[data-toggle="popover"]').popover({
 
            html: true,
 
            container: 'body',
 
            placement: placement,
 
            trigger: 'hover',
 
            template: '<div class="popover cs-popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
 
        });
 
        $('.lazy-cs').tooltip({
 
            title: get_changeset_tooltip,
 
            placement: placement
 
        });
 
    });
 
}
 

	
 

	
 
/**
 
 * Quick filter widget
 
 *
 
 * @param target: filter input target
 
 * @param nodes: list of nodes in html we want to filter.
 
 * @param display_element function that takes current node from nodes and
 
 *    does hide or show based on the node
 
 */
 
var q_filter = (function() {
 
    var _namespace = {};
 
    var namespace = function (target) {
 
        if (!(target in _namespace)) {
 
            _namespace[target] = {};
 
        }
 
        return _namespace[target];
 
    };
 
    return function (target, $nodes, display_element) {
 
        var $nodes = $nodes;
 
        var $q_filter_field = $('#' + target);
 
        var F = namespace(target);
 

	
 
        $q_filter_field.keyup(function (e) {
 
            clearTimeout(F.filterTimeout);
 
            F.filterTimeout = setTimeout(F.updateFilter, 600);
 
        });
 

	
 
        F.filterTimeout = null;
 

	
 
        F.updateFilter = function () {
 
            // Reset timeout
 
            F.filterTimeout = null;
 

	
 
            var obsolete = [];
 

	
 
            var req = $q_filter_field.val().toLowerCase();
 

	
 
            var showing = 0;
 
            $nodes.each(function () {
 
                var n = this;
 
                var target_element = display_element(n);
 
                if (req && n.innerHTML.toLowerCase().indexOf(req) == -1) {
 
                    $(target_element).hide();
 
                }
 
                else {
 
                    $(target_element).show();
 
                    showing += 1;
 
                }
 
            });
 

	
 
            $('#repo_count').html(showing);
 
            /* FIXME: don't hardcode */
 
        }
 
    }
 
})();
 

	
 

	
 
/**
 
 * Comment handling
 
 */
 

	
 
// move comments to their right location, inside new trs
 
function move_comments($anchorcomments) {
 
    $anchorcomments.each(function(i, anchorcomment) {
 
        var $anchorcomment = $(anchorcomment);
 
        var target_id = $anchorcomment.data('target-id');
 
        var $comment_div = _get_add_comment_div(target_id);
 
        var f_path = $anchorcomment.data('f_path');
 
        var line_no = $anchorcomment.data('line_no');
 
        if ($comment_div[0]) {
 
            $comment_div.append($anchorcomment.children());
 
            if (f_path && line_no) {
 
                _comment_div_append_add($comment_div, f_path, line_no);
 
            } else {
 
                _comment_div_append_form($comment_div, f_path, line_no);
 
            }
 
        } else {
 
            $anchorcomment.before("<span class='bg-warning'>Comment to {0} line {1} which is outside the diff context:</span>".format(f_path || '?', line_no || '?'));
 
        }
 
    });
 
    linkInlineComments($('.firstlink'), $('.comment:first-child'));
 
}
 

	
 
// comment bubble was clicked - insert new tr and show form
 
function show_comment_form($bubble) {
 
    var children = $bubble.closest('tr.line').children('[id]');
 
    var line_td_id = children[children.length - 1].id;
 
    var $comment_div = _get_add_comment_div(line_td_id);
 
    var f_path = $bubble.closest('[data-f_path]').data('f_path');
 
    var parts = line_td_id.split('_');
 
    var line_no = parts[parts.length-1];
 
    comment_div_state($comment_div, f_path, line_no, true);
 
}
 

	
 
// return comment div for target_id - add it if it doesn't exist yet
 
function _get_add_comment_div(target_id) {
 
    var comments_box_id = 'comments-' + target_id;
 
    var $comments_box = $('#' + comments_box_id);
 
    if (!$comments_box.length) {
 
        var html = '<tr><td id="{0}" colspan="3" class="inline-comments"></td></tr>'.format(comments_box_id);
 
        $('#' + target_id).closest('tr').after(html);
 
        $comments_box = $('#' + comments_box_id);
 
    }
 
    return $comments_box;
 
}
 

	
 
// Set $comment_div state - showing or not showing form and Add button.
 
// An Add button is shown on non-empty forms when no form is shown.
 
// The form is controlled by show_form_opt - if undefined, form is only shown for general comments.
 
function comment_div_state($comment_div, f_path, line_no, show_form_opt) {
 
    var show_form = show_form_opt !== undefined ? show_form_opt : !f_path && !line_no;
 
    var $forms = $comment_div.children('.comment-inline-form');
 
    var $buttonrow = $comment_div.children('.add-button-row');
 
    var $comments = $comment_div.children('.comment:not(.submitting)');
 
    $forms.remove();
 
    $buttonrow.remove();
 
    if (show_form) {
 
        _comment_div_append_form($comment_div, f_path, line_no);
 
    } else if ($comments.length) {
 
        _comment_div_append_add($comment_div, f_path, line_no);
 
    } else {
 
        $comment_div.parent('tr').remove();
 
    }
 
}
 

	
 
// append an Add button to $comment_div and hook it up to show form
 
function _comment_div_append_add($comment_div, f_path, line_no) {
 
    var addlabel = TRANSLATION_MAP['Add Another Comment'];
 
    var $add = $('<div class="add-button-row"><span class="btn btn-default btn-xs add-button">{0}</span></div>'.format(addlabel));
 
    $comment_div.append($add);
 
    $add.children('.add-button').click(function(e) {
 
        comment_div_state($comment_div, f_path, line_no, true);
 
    });
 
}
 

	
 
// append a comment form to $comment_div
 
function _comment_div_append_form($comment_div, f_path, line_no) {
 
    var $form_div = $('#comment-inline-form-template').children()
 
        .clone()
 
        .addClass('comment-inline-form');
 
    $comment_div.append($form_div);
 
    var $preview = $comment_div.find("div.comment-preview");
 
    var $form = $comment_div.find("form");
 
    var $textarea = $form.find('textarea');
 

	
 
    $form.submit(function(e) {
 
        e.preventDefault();
 

	
 
        var text = $textarea.val();
 
        var review_status = $form.find('input:radio[name=changeset_status]:checked').val();
 
        var pr_close = $form.find('input:checkbox[name=save_close]:checked').length ? 'on' : '';
 
        var pr_delete = $form.find('input:checkbox[name=save_delete]:checked').length ? 'delete' : '';
 

	
 
        if (!text && !review_status && !pr_close && !pr_delete) {
 
            alert("Please provide a comment");
 
            return false;
 
        }
 

	
 
        if (pr_delete) {
 
            if (text || review_status || pr_close) {
 
                alert('Cannot delete pull request while making other changes');
 
                return false;
 
            }
 
            if (!confirm('Confirm to delete this pull request')) {
 
                return false;
 
            }
 
            var comments = $('.comment').length;
 
            if (comments > 0 &&
 
                !confirm('Confirm again to delete this pull request with {0} comments'.format(comments))) {
 
                return false;
 
            }
 
        }
 

	
 
        if (review_status) {
 
            var $review_status = $preview.find('.automatic-comment');
 
            var review_status_lbl = $("#comment-inline-form-template input.status_change_radio[value='" + review_status + "']").parent().text().strip();
 
            $review_status.find('.comment-status-label').text(review_status_lbl);
 
            $review_status.show();
 
        }
 
        $preview.find('.comment-text div').text(text);
 
        $preview.show();
 
        $textarea.val('');
 
        if (f_path && line_no) {
 
            $form.hide();
 
        }
 

	
 
        var postData = {
 
            'text': text,
 
            'f_path': f_path,
 
            'line': line_no,
 
            'changeset_status': review_status,
 
            'save_close': pr_close,
 
            'save_delete': pr_delete
 
        };
 
        var success = function(json_data) {
 
        function success(json_data) {
 
            if (pr_delete) {
 
                location = json_data['location'];
 
            } else {
 
                $comment_div.append(json_data['rendered_text']);
 
                comment_div_state($comment_div, f_path, line_no);
 
                linkInlineComments($('.firstlink'), $('.comment:first-child'));
 
                if ((review_status || pr_close) && !f_path && !line_no) {
 
                    // Page changed a lot - reload it after closing the submitted form
 
                    comment_div_state($comment_div, f_path, line_no, false);
 
                    location.reload(true);
 
                }
 
            }
 
        };
 
        var failure = function(x, s, e) {
 
        }
 
        function failure(x, s, e) {
 
            $preview.removeClass('submitting').addClass('failed');
 
            var $status = $preview.find('.comment-submission-status');
 
            $('<span>', {
 
                'title': e,
 
                text: _TM['Unable to post']
 
            }).replaceAll($status.contents());
 
            $('<div>', {
 
                'class': 'btn-group'
 
            }).append(
 
                $('<button>', {
 
                    'class': 'btn btn-default btn-xs',
 
                    text: _TM['Retry']
 
                }).click(function() {
 
                    $status.text(_TM['Submitting ...']);
 
                    $preview.addClass('submitting').removeClass('failed');
 
                    ajaxPOST(AJAX_COMMENT_URL, postData, success, failure);
 
                }),
 
                $('<button>', {
 
                    'class': 'btn btn-default btn-xs',
 
                    text: _TM['Cancel']
 
                }).click(function() {
 
                    comment_div_state($comment_div, f_path, line_no);
 
                })
 
            ).appendTo($status);
 
        };
 
        }
 
        ajaxPOST(AJAX_COMMENT_URL, postData, success, failure);
 
    });
 

	
 
    // add event handler for hide/cancel buttons
 
    $form.find('.hide-inline-form').click(function(e) {
 
        comment_div_state($comment_div, f_path, line_no);
 
    });
 

	
 
    tooltip_activate();
 
    if ($textarea.length > 0) {
 
        MentionsAutoComplete($textarea);
 
    }
 
    if (f_path) {
 
        $textarea.focus();
 
    }
 
}
 

	
 

	
 
function deleteComment(comment_id) {
 
    var url = AJAX_COMMENT_DELETE_URL.replace('__COMMENT_ID__', comment_id);
 
    var postData = {};
 
    var success = function(o) {
 
    function success(o) {
 
        $('#comment-'+comment_id).remove();
 
        // Ignore that this might leave a stray Add button (or have a pending form with another comment) ...
 
    }
 
    ajaxPOST(url, postData, success);
 
}
 

	
 

	
 
/**
 
 * Double link comments
 
 */
 
function linkInlineComments($firstlinks, $comments){
 
    if ($comments.length > 0) {
 
        $firstlinks.html('<a href="#{0}">First comment</a>'.format($comments.prop('id')));
 
    }
 
    if ($comments.length <= 1) {
 
        return;
 
    }
 

	
 
    $comments.each(function(i, e){
 
            var prev = '';
 
            if (i > 0){
 
                var prev_anchor = $($comments.get(i-1)).prop('id');
 
                prev = '<a href="#{0}">Previous comment</a>'.format(prev_anchor);
 
            }
 
            var next = '';
 
            if (i+1 < $comments.length){
 
                var next_anchor = $($comments.get(i+1)).prop('id');
 
                next = '<a href="#{0}">Next comment</a>'.format(next_anchor);
 
            }
 
            $(this).find('.comment-prev-next-links').html(
 
                '<div class="prev-comment">{0}</div>'.format(prev) +
 
                '<div class="next-comment">{0}</div>'.format(next));
 
        });
 
}
 

	
 
/* activate files.html stuff */
 
function fileBrowserListeners(node_list_url, url_base){
 
    var $node_filter = $('#node_filter');
 

	
 
    var filterTimeout = null;
 
    var nodes = null;
 

	
 
    var initFilter = function(){
 
    function initFilter(){
 
        $('#node_filter_box_loading').show();
 
        $('#search_activate_id').hide();
 
        $('#add_node_id').hide();
 
        $.ajax({url: node_list_url, headers: {'X-PARTIAL-XHR': '1'}, cache: false})
 
            .done(function(json) {
 
                    nodes = json.nodes;
 
                    $('#node_filter_box_loading').hide();
 
                    $('#node_filter_box').show();
 
                    $node_filter.focus();
 
                    if($node_filter.hasClass('init')){
 
                        $node_filter.val('');
 
                        $node_filter.removeClass('init');
 
                    }
 
                })
 
            .fail(function() {
 
                    console.log('fileBrowserListeners initFilter failed to load');
 
                })
 
        ;
 
    }
 

	
 
    var updateFilter = function(e) {
 
    function updateFilter(e) {
 
        return function(){
 
            // Reset timeout
 
            filterTimeout = null;
 
            var query = e.currentTarget.value.toLowerCase();
 
            var match = [];
 
            var matches = 0;
 
            var matches_max = 20;
 
            if (query != ""){
 
                for(var i=0;i<nodes.length;i++){
 
                    var pos = nodes[i].name.toLowerCase().indexOf(query);
 
                    if(query && pos != -1){
 
                        matches++
 
                        //show only certain amount to not kill browser
 
                        if (matches > matches_max){
 
                            break;
 
                        }
 

	
 
                        var n = nodes[i].name;
 
                        var t = nodes[i].type;
 
                        var n_hl = n.substring(0,pos)
 
                            + "<b>{0}</b>".format(n.substring(pos,pos+query.length))
 
                            + n.substring(pos+query.length);
 
                        var new_url = url_base.replace('__FPATH__',n);
 
                        match.push('<tr><td><a class="browser-{0}" href="{1}">{2}</a></td><td colspan="5"></td></tr>'.format(t,new_url,n_hl));
 
                    }
 
                    if(match.length >= matches_max){
 
                        match.push('<tr><td>{0}</td><td colspan="5"></td></tr>'.format(_TM['Search truncated']));
 
                        break;
 
                    }
 
                }
 
            }
 
            if(query != ""){
 
                $('#tbody').hide();
 
                $('#tbody_filtered').show();
 

	
 
                if (match.length==0){
 
                  match.push('<tr><td>{0}</td><td colspan="5"></td></tr>'.format(_TM['No matching files']));
 
                }
 

	
 
                $('#tbody_filtered').html(match.join(""));
 
            }
 
            else{
 
                $('#tbody').show();
 
                $('#tbody_filtered').hide();
 
            }
 
        }
 
    };
 
    }
 

	
 
    $('#filter_activate').click(function(){
 
            initFilter();
 
        });
 
    $node_filter.click(function(){
 
            if($node_filter.hasClass('init')){
 
                $node_filter.val('');
 
                $node_filter.removeClass('init');
 
            }
 
        });
 
    $node_filter.keyup(function(e){
 
            clearTimeout(filterTimeout);
 
            filterTimeout = setTimeout(updateFilter(e),600);
 
        });
 
}
 

	
 

	
 
function initCodeMirror(textarea_id, baseUrl, resetUrl){
 
    var myCodeMirror = CodeMirror.fromTextArea($('#' + textarea_id)[0], {
 
            mode: "null",
 
            lineNumbers: true,
 
            indentUnit: 4,
 
            autofocus: true
 
        });
 
    CodeMirror.modeURL = baseUrl + "/codemirror/mode/%N/%N.js";
 

	
 
    $('#reset').click(function(e){
 
            window.location=resetUrl;
 
        });
 

	
 
    $('#file_enable').click(function(){
 
            $('#upload_file_container').hide();
 
            $('#filename_container').show();
 
            $('#body').show();
 
        });
 

	
 
    $('#upload_file_enable').click(function(){
 
            $('#upload_file_container').show();
 
            $('#filename_container').hide();
 
            $('#body').hide();
 
        });
 

	
 
    return myCodeMirror
 
}
 

	
 
function setCodeMirrorMode(codeMirrorInstance, mode) {
 
    CodeMirror.autoLoadMode(codeMirrorInstance, mode);
 
}
 

	
 

	
 
function _getIdentNode(n){
 
    //iterate thrugh nodes until matching interesting node
 

	
 
    if (typeof n == 'undefined'){
 
        return -1
 
    }
 

	
 
    if(typeof n.id != "undefined" && n.id.match('L[0-9]+')){
 
        return n
 
    }
 
    else{
 
        return _getIdentNode(n.parentNode);
 
    }
 
}
 

	
 
/* generate links for multi line selects that can be shown by files.html page_highlights.
 
 * This is a mouseup handler for hlcode from CodeHtmlFormatter and pygmentize */
 
function getSelectionLink(e) {
 
    //get selection from start/to nodes
 
    if (typeof window.getSelection != "undefined") {
 
        var s = window.getSelection();
 

	
 
        var from = _getIdentNode(s.anchorNode);
 
        var till = _getIdentNode(s.focusNode);
 

	
 
        var f_int = parseInt(from.id.replace('L',''));
 
        var t_int = parseInt(till.id.replace('L',''));
 

	
 
        var yoffset = 35;
 
        var ranges = [parseInt(from.id.replace('L','')), parseInt(till.id.replace('L',''))];
 
        if (ranges[0] > ranges[1]){
 
            //highlight from bottom
 
            yoffset = -yoffset;
 
            ranges = [ranges[1], ranges[0]];
 
        }
 
        var $hl_div = $('div#linktt');
 
        // if we select more than 2 lines
 
        if (ranges[0] != ranges[1]){
 
            if ($hl_div.length) {
 
                $hl_div.html('');
 
            } else {
 
                $hl_div = $('<div id="linktt" class="hl-tip-box">');
 
                $('body').prepend($hl_div);
 
            }
 

	
 
            $hl_div.append($('<a>').html(_TM['Selection Link']).prop('href', location.href.substring(0, location.href.indexOf('#')) + '#L' + ranges[0] + '-'+ranges[1]));
 
            var xy = $(till).offset();
 
            $hl_div.css('top', (xy.top + yoffset) + 'px').css('left', xy.left + 'px');
 
            $hl_div.show();
 
        }
 
        else{
 
            $hl_div.hide();
 
        }
 
    }
 
}
 

	
 
/**
 
 * Autocomplete functionality
 
 */
 

	
 
// Custom search function for the DataSource of users
 
var autocompleteMatchUsers = function (sQuery, myUsers) {
 
    // Case insensitive matching
 
    var query = sQuery.toLowerCase();
 
    var i = 0;
 
    var l = myUsers.length;
 
    var matches = [];
 

	
 
    // Match against each name of each contact
 
    for (; i < l; i++) {
 
        var contact = myUsers[i];
 
        if (((contact.fname+"").toLowerCase().indexOf(query) > -1) ||
 
             ((contact.lname+"").toLowerCase().indexOf(query) > -1) ||
 
             ((contact.nname) && ((contact.nname).toLowerCase().indexOf(query) > -1))) {
 
            matches[matches.length] = contact;
 
        }
 
    }
 
    return matches;
 
};
 

	
 
// Custom search function for the DataSource of userGroups
 
var autocompleteMatchGroups = function (sQuery, myGroups) {
 
    // Case insensitive matching
 
    var query = sQuery.toLowerCase();
 
    var i = 0;
 
    var l = myGroups.length;
 
    var matches = [];
 

	
 
    // Match against each name of each group
 
    for (; i < l; i++) {
 
        var matched_group = myGroups[i];
 
        if (matched_group.grname.toLowerCase().indexOf(query) > -1) {
 
            matches[matches.length] = matched_group;
 
        }
 
    }
 
    return matches;
 
};
 

	
 
// Highlight the snippet if it is found in the full text, while escaping any existing markup.
 
// Snippet must be lowercased already.
 
function autocompleteHighlightMatch(full, snippet) {
 
    var matchindex = full.toLowerCase().indexOf(snippet);
 
    if (matchindex <0)
 
        return full.html_escape();
 
    return full.substring(0, matchindex).html_escape()
 
        + '<span class="select2-match">'
 
        + full.substr(matchindex, snippet.length).html_escape()
 
        + '</span>'
 
        + full.substring(matchindex + snippet.length).html_escape();
 
}
 

	
 
// Return html snippet for showing the provided gravatar url
 
function gravatar(gravatar_lnk, size, cssclass) {
 
    if (!gravatar_lnk) {
 
        return '';
 
    }
 
    if (gravatar_lnk == 'default') {
 
        return '<i class="icon-user {1}" style="font-size: {0}px;"></i>'.format(size, cssclass);
 
    }
 
    return ('<i class="icon-gravatar {2}"' +
 
            ' style="font-size: {0}px;background-image: url(\'{1}\'); background-size: {0}px"' +
 
            '></i>').format(size, gravatar_lnk, cssclass);
 
}
 

	
 
function autocompleteGravatar(res, gravatar_lnk, size, group) {
 
    var elem;
 
    if (group !== undefined) {
 
        elem = '<i class="perm-gravatar-ac icon-users"></i>';
 
    } else {
 
        elem = gravatar(gravatar_lnk, size, "perm-gravatar-ac");
 
    }
 
    return '<div class="ac-container-wrap">{0}{1}</div>'.format(elem, res);
 
}
 

	
 
// Custom formatter to highlight the matching letters and do HTML escaping
 
function autocompleteFormatter(oResultData, sQuery, sResultMatch) {
 
    var query;
 
    if (sQuery && sQuery.toLowerCase) // YAHOO AutoComplete
 
        query = sQuery.toLowerCase();
 
    else if (sResultMatch && sResultMatch.term) // select2 - parameter names doesn't match
 
        query = sResultMatch.term.toLowerCase();
 

	
 
    // group
 
    if (oResultData.type == "group") {
 
        return autocompleteGravatar(
 
            "{0}: {1}".format(
 
                _TM['Group'],
 
                autocompleteHighlightMatch(oResultData.grname, query)),
 
            null, null, true);
 
    }
 

	
 
    // users
 
    if (oResultData.nname) {
 
        var displayname = autocompleteHighlightMatch(oResultData.nname, query);
 
        if (oResultData.fname && oResultData.lname) {
 
            displayname = "{0} {1} ({2})".format(
 
                autocompleteHighlightMatch(oResultData.fname, query),
 
                autocompleteHighlightMatch(oResultData.lname, query),
 
                displayname);
 
        }
 

	
 
        return autocompleteGravatar(displayname, oResultData.gravatar_lnk, oResultData.gravatar_size);
 
    }
 

	
 
    return '';
 
}
 

	
 
function SimpleUserAutoComplete($inputElement) {
 
    $inputElement.select2({
 
        formatInputTooShort: $inputElement.attr('placeholder'),
 
        initSelection : function (element, callback) {
 
            $.ajax({
 
                url: pyroutes.url('users_and_groups_data'),
 
                dataType: 'json',
 
                data: {
 
                    key: element.val()
 
                },
 
                success: function(data){
 
                  callback(data.results[0]);
 
                }
 
            });
 
        },
 
        minimumInputLength: 1,
 
        ajax: {
 
            url: pyroutes.url('users_and_groups_data'),
 
            dataType: 'json',
 
            data: function(term, page){
 
              return {
 
                query: term
 
              };
 
            },
 
            results: function (data, page){
 
              return data;
 
            },
 
            cache: true
 
        },
 
        formatSelection: autocompleteFormatter,
 
        formatResult: autocompleteFormatter,
 
        id: function(item) { return item.nname; },
 
    });
 
}
 

	
 
function MembersAutoComplete($inputElement, $typeElement) {
 

	
 
    $inputElement.select2({
 
        placeholder: $inputElement.attr('placeholder'),
 
        minimumInputLength: 1,
 
        ajax: {
 
            url: pyroutes.url('users_and_groups_data'),
 
            dataType: 'json',
 
            data: function(term, page){
 
              return {
 
                query: term,
 
                types: 'users,groups'
 
              };
 
            },
 
            results: function (data, page){
 
              return data;
 
            },
 
            cache: true
 
        },
 
        formatSelection: autocompleteFormatter,
 
        formatResult: autocompleteFormatter,
 
        id: function(item) { return item.type == 'user' ? item.nname : item.grname },
 
    }).on("select2-selecting", function(e) {
 
        // e.choice.id is automatically used as selection value - just set the type of the selection
 
        $typeElement.val(e.choice.type);
 
    });
 
}
 

	
 
function MentionsAutoComplete($inputElement) {
 
  $inputElement.atwho({
 
    at: "@",
 
    callbacks: {
 
      remoteFilter: function(query, callback) {
 
        $.getJSON(
 
          pyroutes.url('users_and_groups_data'),
 
          {
 
            query: query,
 
            types: 'users'
 
          },
 
          function(data) {
 
            callback(data.results)
 
          }
 
        );
 
      },
 
      sorter: function(query, items, searchKey) {
 
        return items;
 
      }
 
    },
 
    displayTpl: function(item) {
 
        return "<li>" +
 
            autocompleteGravatar(
 
                "{0} {1} ({2})".format(item.fname, item.lname, item.nname).html_escape(),
 
                '${gravatar_lnk}', 16) +
 
            "</li>";
 
    },
 
    insertTpl: "${atwho-at}${nname}"
 
  });
 
}
 

	
 

	
 
// Set caret at the given position in the input element
 
function _setCaretPosition($inputElement, caretPos) {
 
    $inputElement.each(function(){
 
        if(this.createTextRange) { // IE
 
            var range = this.createTextRange();
 
            range.move('character', caretPos);
 
            range.select();
 
        }
 
        else if(this.selectionStart) { // other recent browsers
 
            this.focus();
 
            this.setSelectionRange(caretPos, caretPos);
 
        }
 
        else // last resort - very old browser
 
            this.focus();
 
    });
 
}
 

	
 

	
 
function addReviewMember(id,fname,lname,nname,gravatar_link,gravatar_size){
 
    var displayname = nname;
 
    if ((fname != "") && (lname != "")) {
 
        displayname = "{0} {1} ({2})".format(fname, lname, nname);
 
    }
 
    var gravatarelm = gravatar(gravatar_link, gravatar_size, "");
 
    // WARNING: the HTML below is duplicate with
 
    // kallithea/templates/pullrequests/pullrequest_show.html
 
    // If you change something here it should be reflected in the template too.
 
    var element = (
 
        '     <li id="reviewer_{2}">\n'+
 
        '       <span class="reviewers_member">\n'+
 
        '         <input type="hidden" value="{2}" name="review_members" />\n'+
 
        '         <span class="reviewer_status" data-toggle="tooltip" title="not_reviewed">\n'+
 
        '             <i class="icon-circle changeset-status-not_reviewed"></i>\n'+
 
        '         </span>\n'+
 
        (gravatarelm ?
 
        '         {0}\n' :
 
        '')+
 
        '         <span>{1}</span>\n'+
 
        '         <a href="#" class="reviewer_member_remove" onclick="removeReviewMember({2})">\n'+
 
        '             <i class="icon-minus-circled"></i>\n'+
 
        '         </a> (add not saved)\n'+
 
        '       </span>\n'+
 
        '     </li>\n'
 
        ).format(gravatarelm, displayname.html_escape(), id);
 
    // check if we don't have this ID already in
 
    var ids = [];
 
    $('#review_members').find('li').each(function() {
 
            ids.push(this.id);
 
        });
 
    if(ids.indexOf('reviewer_'+id) == -1){
 
        //only add if it's not there
 
        $('#review_members').append(element);
 
    }
 
}
 

	
 
function removeReviewMember(reviewer_id, repo_name, pull_request_id){
 
    var $li = $('#reviewer_{0}'.format(reviewer_id));
 
    $li.find('div div').css("text-decoration", "line-through");
 
    $li.find('input').prop('name', 'review_members_removed');
 
    $li.find('.reviewer_member_remove').replaceWith('&nbsp;(remove not saved)');
 
}
 

	
 
/* activate auto completion of users as PR reviewers */
 
function PullRequestAutoComplete($inputElement) {
 
    $inputElement.select2(
 
    {
 
        placeholder: $inputElement.attr('placeholder'),
 
        minimumInputLength: 1,
 
        ajax: {
 
            url: pyroutes.url('users_and_groups_data'),
 
            dataType: 'json',
 
            data: function(term, page){
 
              return {
 
                query: term
 
              };
 
            },
 
            results: function (data, page){
 
              return data;
 
            },
 
            cache: true
 
        },
 
        formatSelection: autocompleteFormatter,
 
        formatResult: autocompleteFormatter,
 
    }).on("select2-selecting", function(e) {
 
        addReviewMember(e.choice.id, e.choice.fname, e.choice.lname, e.choice.nname,
 
                        e.choice.gravatar_lnk, e.choice.gravatar_size);
 
        $inputElement.select2("close");
 
        e.preventDefault();
 
    });
 
}
 

	
 

	
 
function addPermAction(perm_type) {
 
    var template =
 
        '<td><input type="radio" value="{1}.none" name="perm_new_member_{0}" id="perm_new_member_{0}"></td>' +
 
        '<td><input type="radio" value="{1}.read" checked="checked" name="perm_new_member_{0}" id="perm_new_member_{0}"></td>' +
 
        '<td><input type="radio" value="{1}.write" name="perm_new_member_{0}" id="perm_new_member_{0}"></td>' +
 
        '<td><input type="radio" value="{1}.admin" name="perm_new_member_{0}" id="perm_new_member_{0}"></td>' +
 
        '<td>' +
 
                '<input class="form-control" id="perm_new_member_name_{0}" name="perm_new_member_name_{0}" value="" type="text" placeholder="{2}">' +
 
                '<input id="perm_new_member_type_{0}" name="perm_new_member_type_{0}" value="" type="hidden">' +
 
        '</td>' +
 
        '<td></td>';
 
    var $last_node = $('.last_new_member').last(); // empty tr between last and add
 
    var next_id = $('.new_members').length;
 
    $last_node.before($('<tr class="new_members">').append(template.format(next_id, perm_type, _TM['Type name of user or member to grant permission'])));
 
    MembersAutoComplete($("#perm_new_member_name_"+next_id), $("#perm_new_member_type_"+next_id));
 
}
 

	
 
function ajaxActionRevokePermission(url, obj_id, obj_type, field_id, extra_data) {
 
    var success = function (o) {
 
    function success(o) {
 
            $('#' + field_id).remove();
 
        };
 
    var failure = function (o) {
 
        }
 
    function failure(o) {
 
            alert(_TM['Failed to revoke permission'] + ": " + o.status);
 
        };
 
        }
 
    var query_params = {};
 
    // put extra data into POST
 
    if (extra_data !== undefined && (typeof extra_data === 'object')){
 
        for(var k in extra_data){
 
            query_params[k] = extra_data[k];
 
        }
 
    }
 

	
 
    if (obj_type=='user'){
 
        query_params['user_id'] = obj_id;
 
        query_params['obj_type'] = 'user';
 
    }
 
    else if (obj_type=='user_group'){
 
        query_params['user_group_id'] = obj_id;
 
        query_params['obj_type'] = 'user_group';
 
    }
 

	
 
    ajaxPOST(url, query_params, success, failure);
 
};
 

	
 
/* Multi selectors */
 

	
 
function MultiSelectWidget(selected_id, available_id, form_id){
 
    var $availableselect = $('#' + available_id);
 
    var $selectedselect = $('#' + selected_id);
 

	
 
    //fill available only with those not in selected
 
    var $selectedoptions = $selectedselect.children('option');
 
    $availableselect.children('option').filter(function(i, e){
 
            for(var j = 0, node; node = $selectedoptions[j]; j++){
 
                if(node.value == e.value){
 
                    return true;
 
                }
 
            }
 
            return false;
 
        }).remove();
 

	
 
    $('#add_element').click(function(e){
 
            $selectedselect.append($availableselect.children('option:selected'));
 
        });
 
    $('#remove_element').click(function(e){
 
            $availableselect.append($selectedselect.children('option:selected'));
 
        });
 

	
 
    $('#'+form_id).submit(function(){
 
            $selectedselect.children('option').each(function(i, e){
 
                e.selected = 'selected';
 
            });
 
        });
 
}
 

	
 

	
 
/**
 
 Branch Sorting callback for select2, modifying the filtered result so prefix
 
 matches come before matches in the line.
 
 **/
 
function branchSort(results, container, query) {
 
    if (query.term) {
 
        return results.sort(function (a, b) {
 
            // Put closed branches after open ones (a bit of a hack ...)
 
            var aClosed = a.text.indexOf("(closed)") > -1,
 
                bClosed = b.text.indexOf("(closed)") > -1;
 
            if (aClosed && !bClosed) {
 
                return 1;
 
            }
 
            if (bClosed && !aClosed) {
 
                return -1;
 
            }
 

	
 
            // Put early (especially prefix) matches before later matches
 
            var aPos = a.text.toLowerCase().indexOf(query.term.toLowerCase()),
 
                bPos = b.text.toLowerCase().indexOf(query.term.toLowerCase());
 
            if (aPos < bPos) {
 
                return -1;
 
            }
 
            if (bPos < aPos) {
 
                return 1;
 
            }
 

	
 
            // Default sorting
 
            if (a.text > b.text) {
 
                return 1;
 
            }
 
            if (a.text < b.text) {
 
                return -1;
 
            }
 
            return 0;
 
        });
 
    }
 
    return results;
 
}
 

	
 
function prefixFirstSort(results, container, query) {
 
    if (query.term) {
 
        return results.sort(function (a, b) {
 
            // if parent node, no sorting
 
            if (a.children != undefined || b.children != undefined) {
 
                return 0;
 
            }
 

	
 
            // Put prefix matches before matches in the line
 
            var aPos = a.text.toLowerCase().indexOf(query.term.toLowerCase()),
 
                bPos = b.text.toLowerCase().indexOf(query.term.toLowerCase());
 
            if (aPos === 0 && bPos !== 0) {
 
                return -1;
 
            }
 
            if (bPos === 0 && aPos !== 0) {
 
                return 1;
 
            }
 

	
 
            // Default sorting
 
            if (a.text > b.text) {
 
                return 1;
 
            }
 
            if (a.text < b.text) {
 
                return -1;
 
            }
 
            return 0;
 
        });
 
    }
 
    return results;
 
}
 

	
 
/* Helper for jQuery DataTables */
 

	
 
function updateRowCountCallback($elem, onlyDisplayed) {
 
    return function drawCallback() {
 
        var info = this.api().page.info(),
 
            count = onlyDisplayed === true ? info.recordsDisplay : info.recordsTotal;
 
        $elem.html(count);
 
    }
 
}
 

	
 

	
 
/**
 
 * activate changeset parent/child navigation links
 
 */
 
function activate_parent_child_links(){
 

	
 
    $('.parent-child-link').on('click', function(e){
 
        var $this = $(this);
 
        //fetch via ajax what is going to be the next link, if we have
 
        //>1 links show them to user to choose
 
        if(!$this.hasClass('disabled')){
 
            $.ajax({
 
                url: $this.data('ajax-url'),
 
                success: function(data) {
 
                    var repo_name = $this.data('reponame');
 
                    if(data.results.length === 0){
 
                        $this.addClass('disabled');
 
                        $this.text(_TM['No revisions']);
 
                    }
 
                    if(data.results.length === 1){
 
                        var commit = data.results[0];
 
                        window.location = pyroutes.url('changeset_home', {'repo_name': repo_name, 'revision': commit.raw_id});
 
                    }
 
                    else if(data.results.length > 1){
 
                        $this.addClass('disabled');
 
                        $this.addClass('double');
 
                        var template =
 
                            ($this.data('linktype') == 'parent' ? '<i class="icon-left-open"/> ' : '') +
 
                            '<a title="__title__" href="__url__">__rev__</a>' +
 
                            ($this.data('linktype') == 'child' ? ' <i class="icon-right-open"/>' : '');
 
                        var _html = [];
 
                        for(var i = 0; i < data.results.length; i++){
 
                            _html.push(template
 
                                .replace('__rev__', 'r{0}:{1}'.format(data.results[i].revision, data.results[i].raw_id.substr(0, 6)))
 
                                .replace('__title__', data.results[i].message.html_escape())
 
                                .replace('__url__', pyroutes.url('changeset_home', {
 
                                    'repo_name': repo_name,
 
                                    'revision': data.results[i].raw_id}))
 
                                );
 
                        }
 
                        $this.html(_html.join('<br/>'));
 
                    }
 
                }
 
            });
 
        e.preventDefault();
 
        }
 
    });
 
}
kallithea/public/js/mergely.js
Show inline comments
 
/**
 
 * Copyright (c) 2012-2015 by Jamie Peabody, http://www.mergely.com
 
 * All rights reserved.
 
 * Version: 3.3.9 2014-12-07
 
 *
 
 * NOTE by bkuhn@sfconservancy.org for Kallithea:
 
 * Mergely license appears at http://www.mergely.com/license.php and in LICENSE-MERGELY.html
 
 */
 

	
 
"use strict"; 
 

	
 
(function( window, document, jQuery, CodeMirror ){
 

	
 
var Mgly = {};
 

	
 
Mgly.Timer = function(){
 
	var self = this;
 
	self.start = function() { self.t0 = new Date().getTime(); };
 
	self.stop = function() {
 
		var t1 = new Date().getTime();
 
		var d = t1 - self.t0; 
 
		self.t0 = t1;
 
		return d;
 
	};
 
	self.start();
 
};
 

	
 
Mgly.ChangeExpression = new RegExp(/(^(?![><\-])*\d+(?:,\d+)?)([acd])(\d+(?:,\d+)?)/);
 

	
 
Mgly.DiffParser = function(diff) {
 
	var changes = [];
 
	var change_id = 0;
 
	// parse diff
 
	var diff_lines = diff.split(/\n/);
 
	for (var i = 0; i < diff_lines.length; ++i) {
 
		if (diff_lines[i].length == 0) continue;
 
		var change = {};
 
		var test = Mgly.ChangeExpression.exec(diff_lines[i]);
 
		if (test == null) continue;
 
		// lines are zero-based
 
		var fr = test[1].split(',');
 
		change['lhs-line-from'] = fr[0] - 1;
 
		if (fr.length == 1) change['lhs-line-to'] = fr[0] - 1;
 
		else change['lhs-line-to'] = fr[1] - 1;
 
		var to = test[3].split(',');
 
		change['rhs-line-from'] = to[0] - 1;
 
		if (to.length == 1) change['rhs-line-to'] = to[0] - 1;
 
		else change['rhs-line-to'] = to[1] - 1;
 
		change['op'] = test[2];
 
		changes[change_id++] = change;
 
	}
 
	return changes;
 
};
 

	
 
Mgly.sizeOf = function(obj) {
 
	var size = 0, key;
 
	for (key in obj) {
 
		if (obj.hasOwnProperty(key)) size++;
 
	}
 
	return size;
 
};
 

	
 
Mgly.LCS = function(x, y) {
 
	this.x = x.replace(/[ ]{1}/g, '\n');
 
	this.y = y.replace(/[ ]{1}/g, '\n');
 
};
 

	
 
jQuery.extend(Mgly.LCS.prototype, {
 
	clear: function() { this.ready = 0; },
 
	diff: function(added, removed) {
 
		var d = new Mgly.diff(this.x, this.y, {ignorews: false});
 
		var changes = Mgly.DiffParser(d.normal_form());
 
		var li = 0, lj = 0;
 
		for (var i = 0; i < changes.length; ++i) {
 
			var change = changes[i];
 
			if (change.op != 'a') {
 
				// find the starting index of the line
 
				li = d.getLines('lhs').slice(0, change['lhs-line-from']).join(' ').length;
 
				// get the index of the the span of the change
 
				lj = change['lhs-line-to'] + 1;
 
				// get the changed text
 
				var lchange = d.getLines('lhs').slice(change['lhs-line-from'], lj).join(' ');
 
				if (change.op == 'd') lchange += ' ';// include the leading space
 
				else if (li > 0 && change.op == 'c') li += 1; // ignore leading space if not first word
 
				// output the changed index and text
 
				removed(li, li + lchange.length);
 
			}
 
			if (change.op != 'd') {
 
				// find the starting index of the line
 
				li = d.getLines('rhs').slice(0, change['rhs-line-from']).join(' ').length;
 
				// get the index of the the span of the change
 
				lj = change['rhs-line-to'] + 1;
 
				// get the changed text
 
				var rchange = d.getLines('rhs').slice(change['rhs-line-from'], lj).join(' ');
 
				if (change.op == 'a') rchange += ' ';// include the leading space
 
				else if (li > 0 && change.op == 'c') li += 1; // ignore leading space if not first word
 
				// output the changed index and text
 
				added(li, li + rchange.length);
 
			}
 
		}
 
	}
 
});
 

	
 
Mgly.CodeifyText = function(settings) {
 
    this._max_code = 0;
 
    this._diff_codes = {};
 
	this.ctxs = {};
 
	this.options = {ignorews: false};
 
	jQuery.extend(this, settings);
 
	this.lhs = settings.lhs.split('\n');
 
	this.rhs = settings.rhs.split('\n');
 
};
 

	
 
jQuery.extend(Mgly.CodeifyText.prototype, {
 
	getCodes: function(side) {
 
		if (!this.ctxs.hasOwnProperty(side)) {
 
			var ctx = this._diff_ctx(this[side]);
 
			this.ctxs[side] = ctx;
 
			ctx.codes.length = Object.keys(ctx.codes).length;
 
		}
 
		return this.ctxs[side].codes;
 
	},
 
	getLines: function(side) {
 
		return this.ctxs[side].lines;
 
	},
 
	_diff_ctx: function(lines) {
 
		var ctx = {i: 0, codes: {}, lines: lines};
 
		this._codeify(lines, ctx);
 
		return ctx;
 
	},
 
	_codeify: function(lines, ctx) {
 
		var code = this._max_code;
 
		for (var i = 0; i < lines.length; ++i) {
 
			var line = lines[i];
 
			if (this.options.ignorews) {
 
				line = line.replace(/\s+/g, '');
 
			}
 
			var aCode = this._diff_codes[line];
 
			if (aCode != undefined) {
 
				ctx.codes[i] = aCode;
 
			}
 
			else {
 
				this._max_code++;
 
				this._diff_codes[line] = this._max_code;
 
				ctx.codes[i] = this._max_code;
 
			}
 
		}
 
	}
 
});
 

	
 
Mgly.diff = function(lhs, rhs, options) {
 
	var opts = jQuery.extend({ignorews: false}, options);
 
	this.codeify = new Mgly.CodeifyText({
 
		lhs: lhs,
 
		rhs: rhs,
 
		options: opts
 
	});
 
	var lhs_ctx = {
 
		codes: this.codeify.getCodes('lhs'),
 
		modified: {}
 
	};
 
	var rhs_ctx = {
 
		codes: this.codeify.getCodes('rhs'),
 
		modified: {}
 
	};
 
	var max = (lhs_ctx.codes.length + rhs_ctx.codes.length + 1);
 
	var vector_d = [];
 
	var vector_u = [];
 
	this._lcs(lhs_ctx, 0, lhs_ctx.codes.length, rhs_ctx, 0, rhs_ctx.codes.length, vector_u, vector_d);
 
	this._optimize(lhs_ctx);
 
	this._optimize(rhs_ctx);
 
	this.items = this._create_diffs(lhs_ctx, rhs_ctx);
 
};
 

	
 
jQuery.extend(Mgly.diff.prototype, {
 
	changes: function() { return this.items; },
 
	getLines: function(side) {
 
		return this.codeify.getLines(side);
 
	},
 
	normal_form: function() {
 
		var nf = '';
 
		for (var index = 0; index < this.items.length; ++index) {
 
			var item = this.items[index];
 
			var lhs_str = '';
 
			var rhs_str = '';
 
			var change = 'c';
 
			if (item.lhs_deleted_count == 0 && item.rhs_inserted_count > 0) change = 'a';
 
			else if (item.lhs_deleted_count > 0 && item.rhs_inserted_count == 0) change = 'd';
 
			
 
			if (item.lhs_deleted_count == 1) lhs_str = item.lhs_start + 1;
 
			else if (item.lhs_deleted_count == 0) lhs_str = item.lhs_start;
 
			else lhs_str = (item.lhs_start + 1) + ',' + (item.lhs_start + item.lhs_deleted_count);
 
			
 
			if (item.rhs_inserted_count == 1) rhs_str = item.rhs_start + 1;
 
			else if (item.rhs_inserted_count == 0) rhs_str = item.rhs_start;
 
			else rhs_str = (item.rhs_start + 1) + ',' + (item.rhs_start + item.rhs_inserted_count);
 
			nf += lhs_str + change + rhs_str + '\n';
 

	
 
			var lhs_lines = this.getLines('lhs');
 
			var rhs_lines = this.getLines('rhs');
 
			if (rhs_lines && lhs_lines) {
 
				var i;
 
				// if rhs/lhs lines have been retained, output contextual diff
 
				for (i = item.lhs_start; i < item.lhs_start + item.lhs_deleted_count; ++i) {
 
					nf += '< ' + lhs_lines[i] + '\n';
 
				}
 
				if (item.rhs_inserted_count && item.lhs_deleted_count) nf += '---\n';
 
				for (i = item.rhs_start; i < item.rhs_start + item.rhs_inserted_count; ++i) {
 
					nf += '> ' + rhs_lines[i] + '\n';
 
				}
 
			}
 
		}
 
		return nf;
 
	},
 
	_lcs: function(lhs_ctx, lhs_lower, lhs_upper, rhs_ctx, rhs_lower, rhs_upper, vector_u, vector_d) {
 
		while ( (lhs_lower < lhs_upper) && (rhs_lower < rhs_upper) && (lhs_ctx.codes[lhs_lower] == rhs_ctx.codes[rhs_lower]) ) {
 
			++lhs_lower;
 
			++rhs_lower;
 
		}
 
		while ( (lhs_lower < lhs_upper) && (rhs_lower < rhs_upper) && (lhs_ctx.codes[lhs_upper - 1] == rhs_ctx.codes[rhs_upper - 1]) ) {
 
			--lhs_upper;
 
			--rhs_upper;
 
		}
 
		if (lhs_lower == lhs_upper) {
 
			while (rhs_lower < rhs_upper) {
 
				rhs_ctx.modified[ rhs_lower++ ] = true;
 
			}
 
		}
 
		else if (rhs_lower == rhs_upper) {
 
			while (lhs_lower < lhs_upper) {
 
				lhs_ctx.modified[ lhs_lower++ ] = true;
 
			}
 
		}
 
		else {
 
			var sms = this._sms(lhs_ctx, lhs_lower, lhs_upper, rhs_ctx, rhs_lower, rhs_upper, vector_u, vector_d);
 
			this._lcs(lhs_ctx, lhs_lower, sms.x, rhs_ctx, rhs_lower, sms.y, vector_u, vector_d);
 
			this._lcs(lhs_ctx, sms.x, lhs_upper, rhs_ctx, sms.y, rhs_upper, vector_u, vector_d);
 
		}
 
	},
 
	_sms: function(lhs_ctx, lhs_lower, lhs_upper, rhs_ctx, rhs_lower, rhs_upper, vector_u, vector_d) {
 
		var max = lhs_ctx.codes.length + rhs_ctx.codes.length + 1;
 
		var kdown = lhs_lower - rhs_lower;
 
		var kup = lhs_upper - rhs_upper;
 
		var delta = (lhs_upper - lhs_lower) - (rhs_upper - rhs_lower);
 
		var odd = (delta & 1) != 0;
 
		var offset_down = max - kdown;
 
		var offset_up = max - kup;
 
		var maxd = ((lhs_upper - lhs_lower + rhs_upper - rhs_lower) / 2) + 1;
 
		vector_d[ offset_down + kdown + 1 ] = lhs_lower;
 
		vector_u[ offset_up + kup - 1 ] = lhs_upper;
 
		var ret = {x:0,y:0}, d, k, x, y;
 
		for (d = 0; d <= maxd; ++d) {
 
			for (k = kdown - d; k <= kdown + d; k += 2) {
 
				if (k == kdown - d) {
 
					x = vector_d[ offset_down + k + 1 ];//down
 
				}
 
				else {
 
					x = vector_d[ offset_down + k - 1 ] + 1;//right
 
					if ((k < (kdown + d)) && (vector_d[ offset_down + k + 1 ] >= x)) {
 
						x = vector_d[ offset_down + k + 1 ];//down
 
					}
 
				}
 
				y = x - k;
 
				// find the end of the furthest reaching forward D-path in diagonal k.
 
				while ((x < lhs_upper) && (y < rhs_upper) && (lhs_ctx.codes[x] == rhs_ctx.codes[y])) {
 
					x++; y++;
 
				}
 
				vector_d[ offset_down + k ] = x;
 
				// overlap ?
 
				if (odd && (kup - d < k) && (k < kup + d)) {
 
					if (vector_u[offset_up + k] <= vector_d[offset_down + k]) {
 
						ret.x = vector_d[offset_down + k];
 
						ret.y = vector_d[offset_down + k] - k;
 
						return (ret);
 
					}
 
				}
 
			}
 
			// Extend the reverse path.
 
			for (k = kup - d; k <= kup + d; k += 2) {
 
				// find the only or better starting point
 
				if (k == kup + d) {
 
					x = vector_u[offset_up + k - 1]; // up
 
				} else {
 
					x = vector_u[offset_up + k + 1] - 1; // left
 
					if ((k > kup - d) && (vector_u[offset_up + k - 1] < x))
 
						x = vector_u[offset_up + k - 1]; // up
 
				}
 
				y = x - k;
 
				while ((x > lhs_lower) && (y > rhs_lower) && (lhs_ctx.codes[x - 1] == rhs_ctx.codes[y - 1])) {
 
					// diagonal
 
					x--;
 
					y--;
 
				}
 
				vector_u[offset_up + k] = x;
 
				// overlap ?
 
				if (!odd && (kdown - d <= k) && (k <= kdown + d)) {
 
					if (vector_u[offset_up + k] <= vector_d[offset_down + k]) {
 
						ret.x = vector_d[offset_down + k];
 
						ret.y = vector_d[offset_down + k] - k;
 
						return (ret);
 
					}
 
				}
 
			}
 
		}
 
		throw "the algorithm should never come here.";
 
	},
 
	_optimize: function(ctx) {
 
		var start = 0, end = 0;
 
		while (start < ctx.length) {
 
			while ((start < ctx.length) && (ctx.modified[start] == undefined || ctx.modified[start] == false)) {
 
				start++;
 
			}
 
			end = start;
 
			while ((end < ctx.length) && (ctx.modified[end] == true)) {
 
				end++;
 
			}
 
			if ((end < ctx.length) && (ctx.ctx[start] == ctx.codes[end])) {
 
				ctx.modified[start] = false;
 
				ctx.modified[end] = true;
 
			}
 
			else {
 
				start = end;
 
			}
 
		}
 
	},
 
	_create_diffs: function(lhs_ctx, rhs_ctx) {
 
		var items = [];
 
		var lhs_start = 0, rhs_start = 0;
 
		var lhs_line = 0, rhs_line = 0;
 

	
 
		while (lhs_line < lhs_ctx.codes.length || rhs_line < rhs_ctx.codes.length) {
 
			if ((lhs_line < lhs_ctx.codes.length) && (!lhs_ctx.modified[lhs_line])
 
				&& (rhs_line < rhs_ctx.codes.length) && (!rhs_ctx.modified[rhs_line])) {
 
				// equal lines
 
				lhs_line++;
 
				rhs_line++;
 
			}
 
			else {
 
				// maybe deleted and/or inserted lines
 
				lhs_start = lhs_line;
 
				rhs_start = rhs_line;
 

	
 
				while (lhs_line < lhs_ctx.codes.length && (rhs_line >= rhs_ctx.codes.length || lhs_ctx.modified[lhs_line]))
 
					lhs_line++;
 

	
 
				while (rhs_line < rhs_ctx.codes.length && (lhs_line >= lhs_ctx.codes.length || rhs_ctx.modified[rhs_line]))
 
					rhs_line++;
 

	
 
				if ((lhs_start < lhs_line) || (rhs_start < rhs_line)) {
 
					// store a new difference-item
 
					items.push({
 
						lhs_start: lhs_start,
 
						rhs_start: rhs_start,
 
						lhs_deleted_count: lhs_line - lhs_start,
 
						rhs_inserted_count: rhs_line - rhs_start
 
					});
 
				}
 
			}
 
		}
 
		return items;
 
	}
 
});
 

	
 
Mgly.mergely = function(el, options) {
 
	if (el) {
 
		this.init(el, options);
 
	}
 
};
 

	
 
jQuery.extend(Mgly.mergely.prototype, {
 
	name: 'mergely',
 
	//http://jupiterjs.com/news/writing-the-perfect-jquery-plugin
 
	init: function(el, options) {
 
		this.diffView = new Mgly.CodeMirrorDiffView(el, options);
 
		this.bind(el);
 
	},
 
	bind: function(el) {
 
		this.diffView.bind(el);
 
	}
 
});
 

	
 
Mgly.CodeMirrorDiffView = function(el, options) {
 
	CodeMirror.defineExtension('centerOnCursor', function() {
 
		var coords = this.cursorCoords(null, 'local');
 
		this.scrollTo(null, 
 
			(coords.y + coords.yBot) / 2 - (this.getScrollerElement().clientHeight / 2));
 
	});
 
	this.init(el, options);
 
};
 

	
 
jQuery.extend(Mgly.CodeMirrorDiffView.prototype, {
 
	init: function(el, options) {
 
		this.settings = {
 
			autoupdate: true,
 
			autoresize: true,
 
			rhs_margin: 'right',
 
			lcs: true,
 
			sidebar: true,
 
			viewport: false,
 
			ignorews: false,
 
			fadein: 'fast',
 
			editor_width: '650px',
 
			editor_height: '400px',
 
			resize_timeout: 500,
 
			change_timeout: 150,
 
			fgcolor: {a:'#4ba3fa',c:'#a3a3a3',d:'#ff7f7f',  // color for differences (soft color)
 
				ca:'#4b73ff',cc:'#434343',cd:'#ff4f4f'},    // color for currently active difference (bright color)
 
			bgcolor: '#eee',
 
			vpcolor: 'rgba(0, 0, 200, 0.5)',
 
			lhs: function(setValue) { },
 
			rhs: function(setValue) { },
 
			loaded: function() { },
 
			_auto_width: function(w) { return w; },
 
			resize: function(init) {
 
				var scrollbar = init ? 16 : 0;
 
				var w = jQuery(el).parent().width() + scrollbar, h = 0;
 
				if (this.width == 'auto') {
 
					w = this._auto_width(w);
 
				}
 
				else {
 
					w = this.width;
 
					this.editor_width = w;
 
				}
 
				if (this.height == 'auto') {
 
					//h = this._auto_height(h);
 
					h = jQuery(el).parent().height();
 
				}
 
				else {
 
					h = this.height;
 
					this.editor_height = h;
 
				}
 
				var content_width = w / 2.0 - 2 * 8 - 8;
 
				var content_height = h;
 
				var self = jQuery(el);
 
				self.find('.mergely-column').css({ width: content_width + 'px' });
 
				self.find('.mergely-column, .mergely-canvas, .mergely-margin, .mergely-column textarea, .CodeMirror-scroll, .cm-s-default').css({ height: content_height + 'px' });
 
				self.find('.mergely-canvas').css({ height: content_height + 'px' });
 
				self.find('.mergely-column textarea').css({ width: content_width + 'px' });
 
				self.css({ width: w, height: h, clear: 'both' });
 
				if (self.css('display') == 'none') {
 
					if (this.fadein != false) self.fadeIn(this.fadein);
 
					else self.show();
 
					if (this.loaded) this.loaded();
 
				}
 
				if (this.resized) this.resized();
 
			},
 
			_debug: '', //scroll,draw,calc,diff,markup,change
 
			resized: function() { }
 
		};
 
		var cmsettings = {
 
			mode: 'text/plain',
 
			readOnly: false,
 
			lineWrapping: false,
 
			lineNumbers: true,
 
			gutters: ['merge', 'CodeMirror-linenumbers']
 
		};
 
		this.lhs_cmsettings = {};
 
		this.rhs_cmsettings = {};
 
		
 
		// save this element for faster queries
 
		this.element = jQuery(el);
 
		
 
		// save options if there are any
 
		if (options && options.cmsettings) jQuery.extend(this.lhs_cmsettings, cmsettings, options.cmsettings, options.lhs_cmsettings);
 
		if (options && options.cmsettings) jQuery.extend(this.rhs_cmsettings, cmsettings, options.cmsettings, options.rhs_cmsettings);
 
		//if (options) jQuery.extend(this.settings, options);
 
		
 
		// bind if the element is destroyed
 
		this.element.bind('destroyed', jQuery.proxy(this.teardown, this));
 

	
 
		// save this instance in jQuery data, binding this view to the node
 
		jQuery.data(el, 'mergely', this);
 

	
 
		this._setOptions(options);
 
	},
 
	unbind: function() {
 
		if (this.changed_timeout != null) clearTimeout(this.changed_timeout);
 
		this.editor[this.id + '-lhs'].toTextArea();
 
		this.editor[this.id + '-rhs'].toTextArea();
 
	},
 
	destroy: function() {
 
		this.element.unbind('destroyed', this.teardown);
 
		this.teardown();
 
	},
 
	teardown: function() {
 
		this.unbind();
 
	},
 
	lhs: function(text) {
 
		this.editor[this.id + '-lhs'].setValue(text);
 
	},
 
	rhs: function(text) {
 
		this.editor[this.id + '-rhs'].setValue(text);
 
	},
 
	update: function() {
 
		this._changing(this.id + '-lhs', this.id + '-rhs');
 
	},
 
	unmarkup: function() {
 
		this._clear();
 
	},
 
	scrollToDiff: function(direction) {
 
		if (!this.changes.length) return;
 
		if (direction == 'next') {
 
			this._current_diff = Math.min(++this._current_diff, this.changes.length - 1);
 
		}
 
		else {
 
			this._current_diff = Math.max(--this._current_diff, 0);
 
		}
 
		this._scroll_to_change(this.changes[this._current_diff]);
 
		this._changed(this.id + '-lhs', this.id + '-rhs');
 
	},
 
	mergeCurrentChange: function(side) {
 
		if (!this.changes.length) return;
 
		if (side == 'lhs' && !this.lhs_cmsettings.readOnly) {
 
			this._merge_change(this.changes[this._current_diff], 'rhs', 'lhs');
 
		}
 
		else if (side == 'rhs' && !this.rhs_cmsettings.readOnly) {
 
			this._merge_change(this.changes[this._current_diff], 'lhs', 'rhs');
 
		}
 
	},
 
	scrollTo: function(side, num) {
 
		var le = this.editor[this.id + '-lhs'];
 
		var re = this.editor[this.id + '-rhs'];
 
		if (side == 'lhs') {
 
			le.setCursor(num);
 
			le.centerOnCursor();
 
		}
 
		else {
 
			re.setCursor(num);
 
			re.centerOnCursor();
 
		}
 
	},
 
	_setOptions: function(opts) {
 
		jQuery.extend(this.settings, opts);
 
		if (this.settings.hasOwnProperty('rhs_margin')) {
 
			// dynamically swap the margin
 
			if (this.settings.rhs_margin == 'left') {
 
				this.element.find('.mergely-margin:last-child').insertAfter(
 
					this.element.find('.mergely-canvas'));
 
			}
 
			else {
 
				var target = this.element.find('.mergely-margin').last();
 
				target.appendTo(target.parent());
 
			}
 
		}
 
		if (this.settings.hasOwnProperty('sidebar')) {
 
			// dynamically enable sidebars
 
			if (this.settings.sidebar) {
 
				jQuery(this.element).find('.mergely-margin').css({display: 'block'});
 
			}
 
			else {
 
				jQuery(this.element).find('.mergely-margin').css({display: 'none'});
 
			}
 
		}
 
	},
 
	options: function(opts) {
 
		if (opts) {
 
			this._setOptions(opts);
 
			if (this.settings.autoresize) this.resize();
 
			if (this.settings.autoupdate) this.update();
 
		}
 
		else {
 
			return this.settings;
 
		}
 
	},
 
	swap: function() {
 
		if (this.lhs_cmsettings.readOnly || this.rhs_cmsettings.readOnly) return;
 
		var le = this.editor[this.id + '-lhs'];
 
		var re = this.editor[this.id + '-rhs'];
 
		var tmp = re.getValue();
 
		re.setValue(le.getValue());
 
		le.setValue(tmp);
 
	},
 
	merge: function(side) {
 
		var le = this.editor[this.id + '-lhs'];
 
		var re = this.editor[this.id + '-rhs'];
 
		if (side == 'lhs' && !this.lhs_cmsettings.readOnly) le.setValue(re.getValue());
 
		else if (!this.rhs_cmsettings.readOnly) re.setValue(le.getValue());
 
	},
 
	get: function(side) {
 
		var ed = this.editor[this.id + '-' + side];
 
		var t = ed.getValue();
 
		if (t == undefined) return '';
 
		return t;
 
	},
 
	clear: function(side) {
 
		if (side == 'lhs' && this.lhs_cmsettings.readOnly) return;
 
		if (side == 'rhs' && this.rhs_cmsettings.readOnly) return;
 
		var ed = this.editor[this.id + '-' + side];
 
		ed.setValue('');
 
	},
 
	cm: function(side) {
 
		return this.editor[this.id + '-' + side];
 
	},
 
	search: function(side, query, direction) {
 
		var le = this.editor[this.id + '-lhs'];
 
		var re = this.editor[this.id + '-rhs'];
 
		var editor;
 
		if (side == 'lhs') editor = le;
 
		else editor = re;
 
		direction = (direction == 'prev') ? 'findPrevious' : 'findNext';
 
		if ((editor.getSelection().length == 0) || (this.prev_query[side] != query)) {
 
			this.cursor[this.id] = editor.getSearchCursor(query, { line: 0, ch: 0 }, false);
 
			this.prev_query[side] = query;
 
		}
 
		var cursor = this.cursor[this.id];
 
		
 
		if (cursor[direction]()) {
 
			editor.setSelection(cursor.from(), cursor.to());
 
		}
 
		else {
 
			cursor = editor.getSearchCursor(query, { line: 0, ch: 0 }, false);
 
		}
 
	},
 
	resize: function() {
 
		this.settings.resize();
 
		this._changing(this.id + '-lhs', this.id + '-rhs');
 
		this._set_top_offset(this.id + '-lhs');
 
	},
 
	diff: function() {
 
		var lhs = this.editor[this.id + '-lhs'].getValue();
 
		var rhs = this.editor[this.id + '-rhs'].getValue();
 
		var d = new Mgly.diff(lhs, rhs, this.settings);
 
		return d.normal_form();
 
	},
 
	bind: function(el) {
 
		this.element.hide();//hide
 
		this.id = jQuery(el).attr('id');
 
		this.changed_timeout = null;
 
		this.chfns = {};
 
		this.chfns[this.id + '-lhs'] = [];
 
		this.chfns[this.id + '-rhs'] = [];
 
		this.prev_query = [];
 
		this.cursor = [];
 
		this._skipscroll = {};
 
		this.change_exp = new RegExp(/(\d+(?:,\d+)?)([acd])(\d+(?:,\d+)?)/);
 
		var merge_lhs_button;
 
		var merge_rhs_button;
 
		if (jQuery.button != undefined) {
 
			//jquery ui
 
			merge_lhs_button = '<button title="Merge left"></button>';
 
			merge_rhs_button = '<button title="Merge right"></button>';
 
		}
 
		else {
 
			// homebrew
 
			var style = 'opacity:0.4;width:10px;height:15px;background-color:#888;cursor:pointer;text-align:center;color:#eee;border:1px solid: #222;margin-right:5px;margin-top: -2px;';
 
			merge_lhs_button = '<div style="' + style + '" title="Merge left">&lt;</div>';
 
			merge_rhs_button = '<div style="' + style + '" title="Merge right">&gt;</div>';
 
		}
 
		this.merge_rhs_button = jQuery(merge_rhs_button);
 
		this.merge_lhs_button = jQuery(merge_lhs_button);
 
		
 
		// create the textarea and canvas elements
 
		var height = this.settings.editor_height;
 
		var width = this.settings.editor_width;
 
		this.element.append(jQuery('<div class="mergely-margin" style="height: ' + height + '"><canvas id="' + this.id + '-lhs-margin" width="8px" height="' + height + '"></canvas></div>'));
 
		this.element.append(jQuery('<div style="position:relative;width:' + width + '; height:' + height + '" id="' + this.id + '-editor-lhs" class="mergely-column"><textarea style="" id="' + this.id + '-lhs"></textarea></div>'));
 
		this.element.append(jQuery('<div class="mergely-canvas" style="height: ' + height + '"><canvas id="' + this.id + '-lhs-' + this.id + '-rhs-canvas" style="width:28px" width="28px" height="' + height + '"></canvas></div>'));
 
		var rmargin = jQuery('<div class="mergely-margin" style="height: ' + height + '"><canvas id="' + this.id + '-rhs-margin" width="8px" height="' + height + '"></canvas></div>');
 
		if (!this.settings.sidebar) {
 
			this.element.find('.mergely-margin').css({display: 'none'});
 
		}
 
		if (this.settings.rhs_margin == 'left') {
 
			this.element.append(rmargin);
 
		}
 
		this.element.append(jQuery('<div style="width:' + width + '; height:' + height + '" id="' + this.id + '-editor-rhs" class="mergely-column"><textarea style="" id="' + this.id + '-rhs"></textarea></div>'));
 
		if (this.settings.rhs_margin != 'left') {
 
			this.element.append(rmargin);
 
		}
 
		//codemirror
 
		var cmstyle = '#' + this.id + ' .CodeMirror-gutter-text { padding: 5px 0 0 0; }' +
 
			'#' + this.id + ' .CodeMirror-lines pre, ' + '#' + this.id + ' .CodeMirror-gutter-text pre { line-height: 18px; }' +
 
			'.CodeMirror-linewidget { overflow: hidden; };';
 
		if (this.settings.autoresize) {
 
			cmstyle += this.id + ' .CodeMirror-scroll { height: 100%; overflow: auto; }';
 
		}
 
		// adjust the margin line height
 
		cmstyle += '\n.CodeMirror { line-height: 18px; }';
 
		jQuery('<style type="text/css">' + cmstyle + '</style>').appendTo('head');
 

	
 
		//bind
 
		var rhstx = jQuery('#' + this.id + '-rhs').get(0);
 
		if (!rhstx) {
 
			console.error('rhs textarea not defined - Mergely not initialized properly');
 
			return;
 
		}
 
		var lhstx = jQuery('#' + this.id + '-lhs').get(0);
 
		if (!rhstx) {
 
			console.error('lhs textarea not defined - Mergely not initialized properly');
 
			return;
 
		}
 
		var self = this;
 
		this.editor = [];
 
		this.editor[this.id + '-lhs'] = CodeMirror.fromTextArea(lhstx, this.lhs_cmsettings);
 
		this.editor[this.id + '-rhs'] = CodeMirror.fromTextArea(rhstx, this.rhs_cmsettings);
 
		this.editor[this.id + '-lhs'].on('change', function(){ if (self.settings.autoupdate) self._changing(self.id + '-lhs', self.id + '-rhs'); });
 
		this.editor[this.id + '-lhs'].on('scroll', function(){ self._scrolling(self.id + '-lhs'); });
 
		this.editor[this.id + '-rhs'].on('change', function(){ if (self.settings.autoupdate) self._changing(self.id + '-lhs', self.id + '-rhs'); });
 
		this.editor[this.id + '-rhs'].on('scroll', function(){ self._scrolling(self.id + '-rhs'); });
 
		// resize
 
		if (this.settings.autoresize) {
 
			var sz_timeout1 = null;
 
			var sz = function(init) {
 
			function sz(init) {
 
				//self.em_height = null; //recalculate
 
				if (self.settings.resize) self.settings.resize(init);
 
				self.editor[self.id + '-lhs'].refresh();
 
				self.editor[self.id + '-rhs'].refresh();
 
				if (self.settings.autoupdate) {
 
					self._changing(self.id + '-lhs', self.id + '-rhs');
 
				}
 
			};
 
			jQuery(window).resize(
 
				function () {
 
					if (sz_timeout1) clearTimeout(sz_timeout1);
 
					sz_timeout1 = setTimeout(sz, self.settings.resize_timeout);
 
				}
 
			);
 
			sz(true);
 
		}
 
		//bind
 
		var setv;
 
		if (this.settings.lhs) {
 
			setv = this.editor[this.id + '-lhs'].getDoc().setValue;
 
			this.settings.lhs(setv.bind(this.editor[this.id + '-lhs'].getDoc()));
 
		}
 
		if (this.settings.rhs) {
 
			setv = this.editor[this.id + '-rhs'].getDoc().setValue;
 
			this.settings.rhs(setv.bind(this.editor[this.id + '-rhs'].getDoc()));
 
		}
 
	},
 

	
 
	_scroll_to_change : function(change) {
 
		if (!change) return;
 
		var self = this;
 
		var led = self.editor[self.id+'-lhs'];
 
		var red = self.editor[self.id+'-rhs'];
 

	
 
		var yref = led.getScrollerElement().offsetHeight * 0.5; // center between >0 and 1/2
 

	
 
		// set cursors
 
		led.setCursor(Math.max(change["lhs-line-from"],0), 0); // use led.getCursor().ch ?
 
		red.setCursor(Math.max(change["rhs-line-from"],0), 0);
 

	
 
		// using directly CodeMirror breaks canvas alignment
 
		// var ly = led.charCoords({line: Math.max(change["lhs-line-from"],0), ch: 0}, "local").top;
 

	
 
		// calculate scroll offset for current change. Warning: returns relative y position so we scroll to 0 first.
 
		led.scrollTo(null, 0);
 
		red.scrollTo(null, 0);
 
		self._calculate_offsets(self.id+'-lhs', self.id+'-rhs', [change]);
 
		led.scrollTo(null, Math.max(change["lhs-y-start"]-yref, 0));
 
		red.scrollTo(null, Math.max(change["rhs-y-start"]-yref, 0));
 
		// right pane should simply follows
 
	},
 

	
 
	_scrolling: function(editor_name) {
 
		if (this._skipscroll[editor_name] === true) {
 
			// scrolling one side causes the other to event - ignore it
 
			this._skipscroll[editor_name] = false;
 
			return;
 
		}
 
		var scroller = jQuery(this.editor[editor_name].getScrollerElement());
 
		if (this.midway == undefined) {
 
			this.midway = (scroller.height() / 2.0 + scroller.offset().top).toFixed(2);
 
		}
 
		// balance-line
 
		var midline = this.editor[editor_name].coordsChar({left:0, top:this.midway});
 
		var top_to = scroller.scrollTop();
 
		var left_to = scroller.scrollLeft();
 
		
 
		this.trace('scroll', 'side', editor_name);
 
		this.trace('scroll', 'midway', this.midway);
 
		this.trace('scroll', 'midline', midline);
 
		this.trace('scroll', 'top_to', top_to);
 
		this.trace('scroll', 'left_to', left_to);
 
		
 
		var editor_name1 = this.id + '-lhs';
 
		var editor_name2 = this.id + '-rhs';
 
		
 
		for (var name in this.editor) {
 
			if (!this.editor.hasOwnProperty(name)) continue;
 
			if (editor_name == name) continue; //same editor
 
			var this_side = editor_name.replace(this.id + '-', '');
 
			var other_side = name.replace(this.id + '-', '');
 
			var top_adjust = 0;
 
			
 
			// find the last change that is less than or within the midway point
 
			// do not move the rhs until the lhs end point is >= the rhs end point.
 
			var last_change = null;
 
			var force_scroll = false;
 
			for (var i = 0; i < this.changes.length; ++i) {
 
				var change = this.changes[i];
 
				if ((midline.line >= change[this_side+'-line-from'])) {
 
					last_change = change;
 
					if (midline.line >= last_change[this_side+'-line-to']) {
 
						if (!change.hasOwnProperty(this_side+'-y-start') ||
 
							!change.hasOwnProperty(this_side+'-y-end') ||
 
							!change.hasOwnProperty(other_side+'-y-start') ||
 
							!change.hasOwnProperty(other_side+'-y-end')){
 
							// change outside of viewport
 
							force_scroll = true;
 
						}
 
						else {
 
							top_adjust += 
 
								(change[this_side+'-y-end'] - change[this_side+'-y-start']) - 
 
								(change[other_side+'-y-end'] - change[other_side+'-y-start']);
 
						}
 
					}
 
				}
 
			}
 
			
 
			var vp = this.editor[name].getViewport();
 
			var scroll = true;
 
			if (last_change) {
 
				this.trace('scroll', 'last change before midline', last_change);
 
				if (midline.line >= vp.from && midline <= vp.to) {
 
					scroll = false;
 
				}
 
			}
 
			this.trace('scroll', 'scroll', scroll);
 
			if (scroll || force_scroll) {
 
				// scroll the other side
 
				this.trace('scroll', 'scrolling other side', top_to - top_adjust);
 
				this._skipscroll[name] = true;//disable next event
 
				this.editor[name].scrollTo(left_to, top_to - top_adjust);
 
			}
 
			else this.trace('scroll', 'not scrolling other side');
 
			
 
			if (this.settings.autoupdate) {
 
				var timer = new Mgly.Timer();
 
				this._calculate_offsets(editor_name1, editor_name2, this.changes);
 
				this.trace('change', 'offsets time', timer.stop());
 
				this._markup_changes(editor_name1, editor_name2, this.changes);
 
				this.trace('change', 'markup time', timer.stop());
 
				this._draw_diff(editor_name1, editor_name2, this.changes);
 
				this.trace('change', 'draw time', timer.stop());
 
			}
 
			this.trace('scroll', 'scrolled');
 
		}
 
	},
 
	_changing: function(editor_name1, editor_name2) {
 
		this.trace('change', 'changing-timeout', this.changed_timeout);
 
		var self = this;
 
		if (this.changed_timeout != null) clearTimeout(this.changed_timeout);
 
		this.changed_timeout = setTimeout(function(){
 
			var timer = new Mgly.Timer();
 
			self._changed(editor_name1, editor_name2);
 
			self.trace('change', 'total time', timer.stop());
 
		}, this.settings.change_timeout);
 
	},
 
	_changed: function(editor_name1, editor_name2) {
 
		this._clear();
 
		this._diff(editor_name1, editor_name2);
 
	},
 
	_clear: function() {
 
		var self = this, name, editor, fns, timer, i, change, l;
 

	
 
		var clear_changes = function() {
 
		function clear_changes() {
 
			timer = new Mgly.Timer();
 
			for (i = 0, l = editor.lineCount(); i < l; ++i) {
 
				editor.removeLineClass(i, 'background');
 
			}
 
			for (i = 0; i < fns.length; ++i) {
 
				//var edid = editor.getDoc().id;
 
				change = fns[i];
 
				//if (change.doc.id != edid) continue;
 
				if (change.lines.length) {
 
					self.trace('change', 'clear text', change.lines[0].text);
 
				}
 
				change.clear();
 
			}
 
			editor.clearGutter('merge');
 
			self.trace('change', 'clear time', timer.stop());
 
		};
 

	
 
		for (name in this.editor) {
 
			if (!this.editor.hasOwnProperty(name)) continue;
 
			editor = this.editor[name];
 
			fns = self.chfns[name];
 
			// clear editor changes
 
			editor.operation(clear_changes);
 
		}
 
		self.chfns[name] = [];
 
		
 
		var ex = this._draw_info(this.id + '-lhs', this.id + '-rhs');
 
		var ctx_lhs = ex.clhs.get(0).getContext('2d');
 
		var ctx_rhs = ex.crhs.get(0).getContext('2d');
 
		var ctx = ex.dcanvas.getContext('2d');
 
		
 
		ctx_lhs.beginPath();
 
		ctx_lhs.fillStyle = this.settings.bgcolor;
 
		ctx_lhs.strokeStyle = '#888';
 
		ctx_lhs.fillRect(0, 0, 6.5, ex.visible_page_height);
 
		ctx_lhs.strokeRect(0, 0, 6.5, ex.visible_page_height);
 

	
 
		ctx_rhs.beginPath();
 
		ctx_rhs.fillStyle = this.settings.bgcolor;
 
		ctx_rhs.strokeStyle = '#888';
 
		ctx_rhs.fillRect(0, 0, 6.5, ex.visible_page_height);
 
		ctx_rhs.strokeRect(0, 0, 6.5, ex.visible_page_height);
 
		
 
		ctx.beginPath();
 
		ctx.fillStyle = '#fff';
 
		ctx.fillRect(0, 0, this.draw_mid_width, ex.visible_page_height);
 
	},
 
	_diff: function(editor_name1, editor_name2) {
 
		var lhs = this.editor[editor_name1].getValue();
 
		var rhs = this.editor[editor_name2].getValue();
 
		var timer = new Mgly.Timer();
 
		var d = new Mgly.diff(lhs, rhs, this.settings);
 
		this.trace('change', 'diff time', timer.stop());
 
		this.changes = Mgly.DiffParser(d.normal_form());
 
		this.trace('change', 'parse time', timer.stop());
 
		if (this._current_diff === undefined) {
 
			// go to first difference on start-up
 
			this._current_diff = 0;
 
			this._scroll_to_change(this.changes[0]);
 
		}
 
		this.trace('change', 'scroll_to_change time', timer.stop());
 
		this._calculate_offsets(editor_name1, editor_name2, this.changes);
 
		this.trace('change', 'offsets time', timer.stop());
 
		this._markup_changes(editor_name1, editor_name2, this.changes);
 
		this.trace('change', 'markup time', timer.stop());
 
		this._draw_diff(editor_name1, editor_name2, this.changes);
 
		this.trace('change', 'draw time', timer.stop());
 
	},
 
	_parse_diff: function (editor_name1, editor_name2, diff) {
 
		this.trace('diff', 'diff results:\n', diff);
 
		var changes = [];
 
		var change_id = 0;
 
		// parse diff
 
		var diff_lines = diff.split(/\n/);
 
		for (var i = 0; i < diff_lines.length; ++i) {
 
			if (diff_lines[i].length == 0) continue;
 
			var change = {};
 
			var test = this.change_exp.exec(diff_lines[i]);
 
			if (test == null) continue;
 
			// lines are zero-based
 
			var fr = test[1].split(',');
 
			change['lhs-line-from'] = fr[0] - 1;
 
			if (fr.length == 1) change['lhs-line-to'] = fr[0] - 1;
 
			else change['lhs-line-to'] = fr[1] - 1;
 
			var to = test[3].split(',');
 
			change['rhs-line-from'] = to[0] - 1;
 
			if (to.length == 1) change['rhs-line-to'] = to[0] - 1;
 
			else change['rhs-line-to'] = to[1] - 1;
 
			// TODO: optimize for changes that are adds/removes
 
			if (change['lhs-line-from'] < 0) change['lhs-line-from'] = 0;
 
			if (change['lhs-line-to'] < 0) change['lhs-line-to'] = 0;
 
			if (change['rhs-line-from'] < 0) change['rhs-line-from'] = 0;
 
			if (change['rhs-line-to'] < 0) change['rhs-line-to'] = 0;
 
			change['op'] = test[2];
 
			changes[change_id++] = change;
 
			this.trace('diff', 'change', change);
 
		}
 
		return changes;
 
	},
 
	_get_viewport: function(editor_name1, editor_name2) {
 
		var lhsvp = this.editor[editor_name1].getViewport();
 
		var rhsvp = this.editor[editor_name2].getViewport();
 
		return {from: Math.min(lhsvp.from, rhsvp.from), to: Math.max(lhsvp.to, rhsvp.to)};
 
	},
 
	_is_change_in_view: function(vp, change) {
 
		if (!this.settings.viewport) return true;
 
		if ((change['lhs-line-from'] < vp.from && change['lhs-line-to'] < vp.to) ||
 
			(change['lhs-line-from'] > vp.from && change['lhs-line-to'] > vp.to) ||
 
			(change['rhs-line-from'] < vp.from && change['rhs-line-to'] < vp.to) ||
 
			(change['rhs-line-from'] > vp.from && change['rhs-line-to'] > vp.to)) {
 
			// if the change is outside the viewport, skip
 
			return false;
 
		}
 
		return true;
 
	},
 
	_set_top_offset: function (editor_name1) {
 
		// save the current scroll position of the editor
 
		var saveY = this.editor[editor_name1].getScrollInfo().top;
 
		// temporarily scroll to top
 
		this.editor[editor_name1].scrollTo(null, 0);
 
		
 
		// this is the distance from the top of the screen to the top of the 
 
		// content of the first codemirror editor
 
		var topnode = jQuery('#' + this.id + ' .CodeMirror-measure').first();
 
		var top_offset = topnode.offset().top - 4;
 
		if(!top_offset) return false;
 
		
 
		// restore editor's scroll position
 
		this.editor[editor_name1].scrollTo(null, saveY);
 
		
 
		this.draw_top_offset = 0.5 - top_offset;
 
		return true;
 
	},
 
	_calculate_offsets: function (editor_name1, editor_name2, changes) {
 
		if (this.em_height == null) {
 
			if(!this._set_top_offset(editor_name1)) return; //try again
 
			this.em_height = this.editor[editor_name1].defaultTextHeight();
 
			if (!this.em_height) {
 
				console.warn('Failed to calculate offsets, using 18 by default');
 
				this.em_height = 18;
 
			}
 
			this.draw_lhs_min = 0.5;
 
			var c = jQuery('#' + editor_name1 + '-' + editor_name2 + '-canvas');
 
			if (!c.length) {
 
				console.error('failed to find canvas', '#' + editor_name1 + '-' + editor_name2 + '-canvas');
 
			}
 
			if (!c.width()) {
 
				console.error('canvas width is 0');
 
				return;
 
			}
 
			this.draw_mid_width = jQuery('#' + editor_name1 + '-' + editor_name2 + '-canvas').width();
 
			this.draw_rhs_max = this.draw_mid_width - 0.5; //24.5;
 
			this.draw_lhs_width = 5;
 
			this.draw_rhs_width = 5;
 
			this.trace('calc', 'change offsets calculated', {top_offset: this.draw_top_offset, lhs_min: this.draw_lhs_min, rhs_max: this.draw_rhs_max, lhs_width: this.draw_lhs_width, rhs_width: this.draw_rhs_width});
 
		}
 
		var lhschc = this.editor[editor_name1].charCoords({line: 0});
 
		var rhschc = this.editor[editor_name2].charCoords({line: 0});
 
		var vp = this._get_viewport(editor_name1, editor_name2);
 
		
 
		for (var i = 0; i < changes.length; ++i) {
 
			var change = changes[i];
 
			
 
			if (!this.settings.sidebar && !this._is_change_in_view(vp, change)) {
 
				// if the change is outside the viewport, skip
 
				delete change['lhs-y-start'];
 
				delete change['lhs-y-end'];
 
				delete change['rhs-y-start'];
 
				delete change['rhs-y-end'];
 
				continue;
 
			}
 
			var llf = change['lhs-line-from'] >= 0 ? change['lhs-line-from'] : 0;
 
			var llt = change['lhs-line-to'] >= 0 ? change['lhs-line-to'] : 0;
 
			var rlf = change['rhs-line-from'] >= 0 ? change['rhs-line-from'] : 0;
 
			var rlt = change['rhs-line-to'] >= 0 ? change['rhs-line-to'] : 0;
 
			
 
			var ls, le, rs, re, tls, tle, lhseh, lhssh, rhssh, rhseh;
 
			if (this.editor[editor_name1].getOption('lineWrapping') || this.editor[editor_name2].getOption('lineWrapping')) {
 
				// If using line-wrapping, we must get the height of the line
 
				tls = this.editor[editor_name1].cursorCoords({line: llf, ch: 0}, 'page');
 
				lhssh = this.editor[editor_name1].getLineHandle(llf);
 
				ls = { top: tls.top, bottom: tls.top + lhssh.height };
 

	
 
				tle = this.editor[editor_name1].cursorCoords({line: llt, ch: 0}, 'page');
 
				lhseh = this.editor[editor_name1].getLineHandle(llt);
 
				le = { top: tle.top, bottom: tle.top + lhseh.height };
 
				
 
				tls = this.editor[editor_name2].cursorCoords({line: rlf, ch: 0}, 'page');
 
				rhssh = this.editor[editor_name2].getLineHandle(rlf);
 
				rs = { top: tls.top, bottom: tls.top + rhssh.height };
 

	
 
				tle = this.editor[editor_name2].cursorCoords({line: rlt, ch: 0}, 'page');
 
				rhseh = this.editor[editor_name2].getLineHandle(rlt);
 
				re = { top: tle.top, bottom: tle.top + rhseh.height };
 
			}
 
			else {
 
				// If not using line-wrapping, we can calculate the line position
 
				ls = { 
 
					top: lhschc.top + llf * this.em_height, 
 
					bottom: lhschc.bottom + llf * this.em_height + 2
 
				};
 
				le = {
 
					top: lhschc.top + llt * this.em_height, 
 
					bottom: lhschc.bottom + llt * this.em_height + 2
 
				};
 
				rs = {
 
					top: rhschc.top + rlf * this.em_height, 
 
					bottom: rhschc.bottom + rlf * this.em_height + 2
 
				};
 
				re = {
 
					top: rhschc.top + rlt * this.em_height, 
 
					bottom: rhschc.bottom + rlt * this.em_height + 2
 
				};
 
			}
 
			
 
			if (change['op'] == 'a') {
 
				// adds (right), normally start from the end of the lhs,
 
				// except for the case when the start of the rhs is 0
 
				if (rlf > 0) {
 
					ls.top = ls.bottom;
 
					ls.bottom += this.em_height;
 
					le = ls;
 
				}
 
			}
 
			else if (change['op'] == 'd') {
 
				// deletes (left) normally finish from the end of the rhs,
 
				// except for the case when the start of the lhs is 0
 
				if (llf > 0) {
 
					rs.top = rs.bottom;
 
					rs.bottom += this.em_height;
 
					re = rs;
 
				}
 
			}
 
			change['lhs-y-start'] = this.draw_top_offset + ls.top;
 
			if (change['op'] == 'c' || change['op'] == 'd') {
 
				change['lhs-y-end'] = this.draw_top_offset + le.bottom;
 
			}
 
			else {
 
				change['lhs-y-end'] = this.draw_top_offset + le.top;
 
			}
 
			change['rhs-y-start'] = this.draw_top_offset + rs.top;
 
			if (change['op'] == 'c' || change['op'] == 'a') {
 
				change['rhs-y-end'] = this.draw_top_offset + re.bottom;
 
			}
 
			else {
 
				change['rhs-y-end'] = this.draw_top_offset + re.top;
 
			}
 
			this.trace('calc', 'change calculated', i, change);
 
		}
 
		return changes;
 
	},
 
	_markup_changes: function (editor_name1, editor_name2, changes) {
 
		jQuery('.merge-button').remove(); // clear
 
		
 
		var self = this;
 
		var led = this.editor[editor_name1];
 
		var red = this.editor[editor_name2];
 

	
 
		var timer = new Mgly.Timer();
 
		led.operation(function() {
 
			for (var i = 0; i < changes.length; ++i) {
 
				var change = changes[i];
 
				var llf = change['lhs-line-from'] >= 0 ? change['lhs-line-from'] : 0;
 
				var llt = change['lhs-line-to'] >= 0 ? change['lhs-line-to'] : 0;
 
				var rlf = change['rhs-line-from'] >= 0 ? change['rhs-line-from'] : 0;
 
				var rlt = change['rhs-line-to'] >= 0 ? change['rhs-line-to'] : 0;
 
				
 
				var clazz = ['mergely', 'lhs', change['op'], 'cid-' + i];
 
				led.addLineClass(llf, 'background', 'start');
 
				led.addLineClass(llt, 'background', 'end');
 
				
 
				if (llf == 0 && llt == 0 && rlf == 0) {
 
					led.addLineClass(llf, 'background', clazz.join(' '));
 
					led.addLineClass(llf, 'background', 'first');
 
				}
 
				else {
 
					// apply change for each line in-between the changed lines
 
					for (var j = llf; j <= llt; ++j) {
 
						led.addLineClass(j, 'background', clazz.join(' '));
 
						led.addLineClass(j, 'background', clazz.join(' '));
 
					}
 
				}
 
				
 
				if (!red.getOption('readOnly')) {
 
					// add widgets to lhs, if rhs is not read only
 
					var rhs_button = self.merge_rhs_button.clone();
 
					if (rhs_button.button) {
 
						//jquery-ui support
 
						rhs_button.button({icons: {primary: 'ui-icon-triangle-1-e'}, text: false});
 
					}
 
					rhs_button.addClass('merge-button');
 
					rhs_button.attr('id', 'merge-rhs-' + i);
 
					led.setGutterMarker(llf, 'merge', rhs_button.get(0));
 
				}
 
			}
 
		});
 

	
 
		var vp = this._get_viewport(editor_name1, editor_name2);
 
		
 
		this.trace('change', 'markup lhs-editor time', timer.stop());
 
		red.operation(function() {
 
			for (var i = 0; i < changes.length; ++i) {
 
				var change = changes[i];
 
				var llf = change['lhs-line-from'] >= 0 ? change['lhs-line-from'] : 0;
 
				var llt = change['lhs-line-to'] >= 0 ? change['lhs-line-to'] : 0;
 
				var rlf = change['rhs-line-from'] >= 0 ? change['rhs-line-from'] : 0;
 
				var rlt = change['rhs-line-to'] >= 0 ? change['rhs-line-to'] : 0;
 
				
 
				if (!self._is_change_in_view(vp, change)) {
 
					// if the change is outside the viewport, skip
 
					continue;
 
				}
 
				
 
				var clazz = ['mergely', 'rhs', change['op'], 'cid-' + i];
 
				red.addLineClass(rlf, 'background', 'start');
 
				red.addLineClass(rlt, 'background', 'end');
 
				
 
				if (rlf == 0 && rlt == 0 && llf == 0) {
 
					red.addLineClass(rlf, 'background', clazz.join(' '));
 
					red.addLineClass(rlf, 'background', 'first');
 
				}
 
				else {
 
					// apply change for each line in-between the changed lines
 
					for (var j = rlf; j <= rlt; ++j) {
 
						red.addLineClass(j, 'background', clazz.join(' '));
 
						red.addLineClass(j, 'background', clazz.join(' '));
 
					}
 
				}
 

	
 
				if (!led.getOption('readOnly')) {
 
					// add widgets to rhs, if lhs is not read only
 
					var lhs_button = self.merge_lhs_button.clone();
 
					if (lhs_button.button) {
 
						//jquery-ui support
 
						lhs_button.button({icons: {primary: 'ui-icon-triangle-1-w'}, text: false});
 
					}
 
					lhs_button.addClass('merge-button');
 
					lhs_button.attr('id', 'merge-lhs-' + i);
 
					red.setGutterMarker(rlf, 'merge', lhs_button.get(0));
 
				}
 
			}
 
		});
 
		this.trace('change', 'markup rhs-editor time', timer.stop());
 
		
 
		// mark text deleted, LCS changes
 
		var marktext = [], i, j, k, p;
 
		for (i = 0; this.settings.lcs && i < changes.length; ++i) {
 
			var change = changes[i];
 
			var llf = change['lhs-line-from'] >= 0 ? change['lhs-line-from'] : 0;
 
			var llt = change['lhs-line-to'] >= 0 ? change['lhs-line-to'] : 0;
 
			var rlf = change['rhs-line-from'] >= 0 ? change['rhs-line-from'] : 0;
 
			var rlt = change['rhs-line-to'] >= 0 ? change['rhs-line-to'] : 0;
 
			
 
			if (!this._is_change_in_view(vp, change)) {
 
				// if the change is outside the viewport, skip
 
				continue;
 
			}
 
			if (change['op'] == 'd') {
 
				// apply delete to cross-out (left-hand side only)
 
				var from = llf;
 
				var to = llt;
 
				var to_ln = led.lineInfo(to);
 
				if (to_ln) {
 
					marktext.push([led, {line:from, ch:0}, {line:to, ch:to_ln.text.length}, {className: 'mergely ch d lhs'}]);
 
				}
 
			}
 
			else if (change['op'] == 'c') {
 
				// apply LCS changes to each line
 
				for (j = llf, k = rlf, p = 0; 
 
					 ((j >= 0) && (j <= llt)) || ((k >= 0) && (k <= rlt));
 
					 ++j, ++k) {
 
					var lhs_line, rhs_line;
 
					if (k + p > rlt) {
 
						// lhs continues past rhs, mark lhs as deleted
 
						lhs_line = led.getLine( j );
 
						marktext.push([led, {line:j, ch:0}, {line:j, ch:lhs_line.length}, {className: 'mergely ch d lhs'}]);
 
						continue;
 
					}
 
					if (j + p > llt) {
 
						// rhs continues past lhs, mark rhs as added
 
						rhs_line = red.getLine( k );
 
						marktext.push([red, {line:k, ch:0}, {line:k, ch:rhs_line.length}, {className: 'mergely ch a rhs'}]);
 
						continue;
 
					}
 
					lhs_line = led.getLine( j );
 
					rhs_line = red.getLine( k );
 
					var lcs = new Mgly.LCS(lhs_line, rhs_line);
 
					lcs.diff(
 
						function added (from, to) {
 
							marktext.push([red, {line:k, ch:from}, {line:k, ch:to}, {className: 'mergely ch a rhs'}]);
 
						},
 
						function removed (from, to) {
 
							marktext.push([led, {line:j, ch:from}, {line:j, ch:to}, {className: 'mergely ch d lhs'}]);
 
						}
 
					);
 
				}
 
			}
 
		}
 
		this.trace('change', 'LCS marktext time', timer.stop());
 
		
 
		// mark changes outside closure
 
		led.operation(function() {
 
			// apply lhs markup
 
			for (var i = 0; i < marktext.length; ++i) {
 
				var m = marktext[i];
 
				if (m[0].doc.id != led.getDoc().id) continue;
 
				self.chfns[self.id + '-lhs'].push(m[0].markText(m[1], m[2], m[3]));
 
			}
 
		});
 
		red.operation(function() {
 
			// apply lhs markup
 
			for (var i = 0; i < marktext.length; ++i) {
 
				var m = marktext[i];
 
				if (m[0].doc.id != red.getDoc().id) continue;
 
				self.chfns[self.id + '-rhs'].push(m[0].markText(m[1], m[2], m[3]));
 
			}
 
		});
 
		this.trace('change', 'LCS markup time', timer.stop());
 
		
 
		// merge buttons
 
		var ed = {lhs:led, rhs:red};
 
		jQuery('.merge-button').on('click', function(ev){
 
			// side of mouseenter
 
			var side = 'rhs';
 
			var oside = 'lhs';
 
			var parent = jQuery(this).parents('#' + self.id + '-editor-lhs');
 
			if (parent.length) {
 
				side = 'lhs';
 
				oside = 'rhs';
 
			}
 
			var pos = ed[side].coordsChar({left:ev.pageX, top:ev.pageY});
 

	
 
			// get the change id
 
			var cid = null;
 
			var info = ed[side].lineInfo(pos.line);
 
			jQuery.each(info.bgClass.split(' '), function(i, clazz) {
 
				if (clazz.indexOf('cid-') == 0) {
 
					cid = parseInt(clazz.split('-')[1], 10);
 
					return false;
 
				}
 
			});
 
			var change = self.changes[cid];
 
			self._merge_change(change, side, oside);
 
			return false;
 
		});
 
		this.trace('change', 'markup buttons time', timer.stop());
 
	},
 
	_merge_change :	function(change, side, oside) {
 
		if (!change) return;
 
		var led = this.editor[this.id+'-lhs'];
 
		var red = this.editor[this.id+'-rhs'];
 
		var ed = {lhs:led, rhs:red};
 
		var i, from, to;
 

	
 
		var text = ed[side].getRange(
 
			CodeMirror.Pos(change[side + '-line-from'], 0),
 
			CodeMirror.Pos(change[side + '-line-to'] + 1, 0));
 
		
 
		if (change['op'] == 'c') {
 
			ed[oside].replaceRange(text,
 
				CodeMirror.Pos(change[oside + '-line-from'], 0),
 
				CodeMirror.Pos(change[oside + '-line-to'] + 1, 0));
 
		}
 
		else if (side == 'rhs') {
 
			if (change['op'] == 'a') {
 
				ed[oside].replaceRange(text,
 
					CodeMirror.Pos(change[oside + '-line-from'] + 1, 0),
 
					CodeMirror.Pos(change[oside + '-line-to'] + 1, 0));
 
			}
 
			else {// 'd'
 
				from = parseInt(change[oside + '-line-from'], 10);
 
				to = parseInt(change[oside + '-line-to'], 10);
 
				for (i = to; i >= from; --i) {
 
					ed[oside].setCursor({line: i, ch: -1});
 
					ed[oside].execCommand('deleteLine');
 
				}
 
			}
 
		}
 
		else if (side == 'lhs') {
 
			if (change['op'] == 'a') {
 
				from = parseInt(change[oside + '-line-from'], 10);
 
				to = parseInt(change[oside + '-line-to'], 10);
 
				for (i = to; i >= from; --i) {
 
					//ed[oside].removeLine(i);
 
					ed[oside].setCursor({line: i, ch: -1});
 
					ed[oside].execCommand('deleteLine');
 
				}
 
			}
 
			else {// 'd'
 
				ed[oside].replaceRange( text,
 
					CodeMirror.Pos(change[oside + '-line-from'] + 1, 0));
 
			}
 
		}
 
		//reset
 
		ed['lhs'].setValue(ed['lhs'].getValue());
 
		ed['rhs'].setValue(ed['rhs'].getValue());
 

	
 
		this._scroll_to_change(change);
 
	},
 
	_draw_info: function(editor_name1, editor_name2) {
 
		var visible_page_height = jQuery(this.editor[editor_name1].getScrollerElement()).height();
 
		var gutter_height = jQuery(this.editor[editor_name1].getScrollerElement()).children(':first-child').height();
 
		var dcanvas = document.getElementById(editor_name1 + '-' + editor_name2 + '-canvas');
 
		if (dcanvas == undefined) throw 'Failed to find: ' + editor_name1 + '-' + editor_name2 + '-canvas';
 
		var clhs = jQuery('#' + this.id + '-lhs-margin');
 
		var crhs = jQuery('#' + this.id + '-rhs-margin');
 
		return {
 
			visible_page_height: visible_page_height,
 
			gutter_height: gutter_height,
 
			visible_page_ratio: (visible_page_height / gutter_height),
 
			margin_ratio: (visible_page_height / gutter_height),
 
			lhs_scroller: jQuery(this.editor[editor_name1].getScrollerElement()),
 
			rhs_scroller: jQuery(this.editor[editor_name2].getScrollerElement()),
 
			lhs_lines: this.editor[editor_name1].lineCount(),
 
			rhs_lines: this.editor[editor_name2].lineCount(),
 
			dcanvas: dcanvas,
 
			clhs: clhs,
 
			crhs: crhs,
 
			lhs_xyoffset: jQuery(clhs).offset(),
 
			rhs_xyoffset: jQuery(crhs).offset()
 
		};
 
	},
 
	_draw_diff: function(editor_name1, editor_name2, changes) {
 
		var ex = this._draw_info(editor_name1, editor_name2);
 
		var mcanvas_lhs = ex.clhs.get(0);
 
		var mcanvas_rhs = ex.crhs.get(0);
 
		var ctx = ex.dcanvas.getContext('2d');
 
		var ctx_lhs = mcanvas_lhs.getContext('2d');
 
		var ctx_rhs = mcanvas_rhs.getContext('2d');
 

	
 
		this.trace('draw', 'visible_page_height', ex.visible_page_height);
 
		this.trace('draw', 'gutter_height', ex.gutter_height);
 
		this.trace('draw', 'visible_page_ratio', ex.visible_page_ratio);
 
		this.trace('draw', 'lhs-scroller-top', ex.lhs_scroller.scrollTop());
 
		this.trace('draw', 'rhs-scroller-top', ex.rhs_scroller.scrollTop());
 
		
 
		jQuery.each(jQuery.find('#' + this.id + ' canvas'), function () {
 
			jQuery(this).get(0).height = ex.visible_page_height;
 
		});
 
		
 
		ex.clhs.unbind('click');
 
		ex.crhs.unbind('click');
 
		
 
		ctx_lhs.beginPath();
 
		ctx_lhs.fillStyle = this.settings.bgcolor;
 
		ctx_lhs.strokeStyle = '#888';
 
		ctx_lhs.fillRect(0, 0, 6.5, ex.visible_page_height);
 
		ctx_lhs.strokeRect(0, 0, 6.5, ex.visible_page_height);
 

	
 
		ctx_rhs.beginPath();
 
		ctx_rhs.fillStyle = this.settings.bgcolor;
 
		ctx_rhs.strokeStyle = '#888';
 
		ctx_rhs.fillRect(0, 0, 6.5, ex.visible_page_height);
 
		ctx_rhs.strokeRect(0, 0, 6.5, ex.visible_page_height);
 

	
 
		var vp = this._get_viewport(editor_name1, editor_name2);
 
		for (var i = 0; i < changes.length; ++i) {
 
			var change = changes[i];
 

	
 
			this.trace('draw', change);
 
			// margin indicators
 
			var lhs_y_start = ((change['lhs-y-start'] + ex.lhs_scroller.scrollTop()) * ex.visible_page_ratio);
 
			var lhs_y_end = ((change['lhs-y-end'] + ex.lhs_scroller.scrollTop()) * ex.visible_page_ratio) + 1;
 
			var rhs_y_start = ((change['rhs-y-start'] + ex.rhs_scroller.scrollTop()) * ex.visible_page_ratio);
 
			var rhs_y_end = ((change['rhs-y-end'] + ex.rhs_scroller.scrollTop()) * ex.visible_page_ratio) + 1;
 
			this.trace('draw', 'marker calculated', lhs_y_start, lhs_y_end, rhs_y_start, rhs_y_end);
 

	
 
			ctx_lhs.beginPath();
 
			ctx_lhs.fillStyle = this.settings.fgcolor[(this._current_diff==i?'c':'')+change['op']];
 
			ctx_lhs.strokeStyle = '#000';
 
			ctx_lhs.lineWidth = 0.5;
 
			ctx_lhs.fillRect(1.5, lhs_y_start, 4.5, Math.max(lhs_y_end - lhs_y_start, 5));
 
			ctx_lhs.strokeRect(1.5, lhs_y_start, 4.5, Math.max(lhs_y_end - lhs_y_start, 5));
 

	
 
			ctx_rhs.beginPath();
 
			ctx_rhs.fillStyle = this.settings.fgcolor[(this._current_diff==i?'c':'')+change['op']];
 
			ctx_rhs.strokeStyle = '#000';
 
			ctx_rhs.lineWidth = 0.5;
 
			ctx_rhs.fillRect(1.5, rhs_y_start, 4.5, Math.max(rhs_y_end - rhs_y_start, 5));
 
			ctx_rhs.strokeRect(1.5, rhs_y_start, 4.5, Math.max(rhs_y_end - rhs_y_start, 5));
 
			
 
			if (!this._is_change_in_view(vp, change)) {
 
				continue;
 
			}
 
			
 
			lhs_y_start = change['lhs-y-start'];
 
			lhs_y_end = change['lhs-y-end'];
 
			rhs_y_start = change['rhs-y-start'];
 
			rhs_y_end = change['rhs-y-end'];
 
			
 
			var radius = 3;
 
			
 
			// draw left box
 
			ctx.beginPath();
 
			ctx.strokeStyle = this.settings.fgcolor[(this._current_diff==i?'c':'')+change['op']];
 
			ctx.lineWidth = (this._current_diff==i) ? 1.5 : 1;
 
			
 
			var rectWidth = this.draw_lhs_width;
 
			var rectHeight = lhs_y_end - lhs_y_start - 1;
 
			var rectX = this.draw_lhs_min;
 
			var rectY = lhs_y_start;
 
			// top and top top-right corner
 
			
 
			// draw left box
 
			ctx.moveTo(rectX, rectY);
 
			if (navigator.appName == 'Microsoft Internet Explorer') {
 
				// IE arcs look awful
 
				ctx.lineTo(this.draw_lhs_min + this.draw_lhs_width, lhs_y_start);
 
				ctx.lineTo(this.draw_lhs_min + this.draw_lhs_width, lhs_y_end + 1);
 
				ctx.lineTo(this.draw_lhs_min, lhs_y_end + 1);
 
			}
 
			else {
 
				if (rectHeight <= 0) {
 
					ctx.lineTo(rectX + rectWidth, rectY);
 
				}
 
				else {
 
					ctx.arcTo(rectX + rectWidth, rectY, rectX + rectWidth, rectY + radius, radius);
 
					ctx.arcTo(rectX + rectWidth, rectY + rectHeight, rectX + rectWidth - radius, rectY + rectHeight, radius);
 
				}
 
				// bottom line
 
				ctx.lineTo(rectX, rectY + rectHeight);
 
			}
 
			ctx.stroke();
 
			
 
			rectWidth = this.draw_rhs_width;
 
			rectHeight = rhs_y_end - rhs_y_start - 1;
 
			rectX = this.draw_rhs_max;
 
			rectY = rhs_y_start;
 

	
 
			// draw right box
 
			ctx.moveTo(rectX, rectY);
 
			if (navigator.appName == 'Microsoft Internet Explorer') {
 
				ctx.lineTo(this.draw_rhs_max - this.draw_rhs_width, rhs_y_start);
 
				ctx.lineTo(this.draw_rhs_max - this.draw_rhs_width, rhs_y_end + 1);
 
				ctx.lineTo(this.draw_rhs_max, rhs_y_end + 1);
 
			}
 
			else {
 
				if (rectHeight <= 0) {
 
					ctx.lineTo(rectX - rectWidth, rectY);
 
				}
 
				else {
 
					ctx.arcTo(rectX - rectWidth, rectY, rectX - rectWidth, rectY + radius, radius);
 
					ctx.arcTo(rectX - rectWidth, rectY + rectHeight, rectX - radius, rectY + rectHeight, radius);
 
				}
 
				ctx.lineTo(rectX, rectY + rectHeight);
 
			}
 
			ctx.stroke();
 
			
 
			// connect boxes
 
			var cx = this.draw_lhs_min + this.draw_lhs_width;
 
			var cy = lhs_y_start + (lhs_y_end + 1 - lhs_y_start) / 2.0;
 
			var dx = this.draw_rhs_max - this.draw_rhs_width;
 
			var dy = rhs_y_start + (rhs_y_end + 1 - rhs_y_start) / 2.0;
 
			ctx.moveTo(cx, cy);
 
			if (cy == dy) {
 
				ctx.lineTo(dx, dy);
 
			}
 
			else {
 
				// fancy!
 
				ctx.bezierCurveTo(
 
					cx + 12, cy - 3, // control-1 X,Y
 
					dx - 12, dy - 3, // control-2 X,Y
 
					dx, dy);
 
			}
 
			ctx.stroke();
 
		}
 

	
 
		// visible window feedback
 
		ctx_lhs.fillStyle = this.settings.vpcolor;
 
		ctx_rhs.fillStyle = this.settings.vpcolor;
 
		
 
		var lto = ex.clhs.height() * ex.visible_page_ratio;
 
		var lfrom = (ex.lhs_scroller.scrollTop() / ex.gutter_height) * ex.clhs.height();
 
		var rto = ex.crhs.height() * ex.visible_page_ratio;
 
		var rfrom = (ex.rhs_scroller.scrollTop() / ex.gutter_height) * ex.crhs.height();
 
		this.trace('draw', 'cls.height', ex.clhs.height());
 
		this.trace('draw', 'lhs_scroller.scrollTop()', ex.lhs_scroller.scrollTop());
 
		this.trace('draw', 'gutter_height', ex.gutter_height);
 
		this.trace('draw', 'visible_page_ratio', ex.visible_page_ratio);
 
		this.trace('draw', 'lhs from', lfrom, 'lhs to', lto);
 
		this.trace('draw', 'rhs from', rfrom, 'rhs to', rto);
 
		
 
		ctx_lhs.fillRect(1.5, lfrom, 4.5, lto);
 
		ctx_rhs.fillRect(1.5, rfrom, 4.5, rto);
 
		
 
		ex.clhs.click(function (ev) {
 
			var y = ev.pageY - ex.lhs_xyoffset.top - (lto / 2);
 
			var sto = Math.max(0, (y / mcanvas_lhs.height) * ex.lhs_scroller.get(0).scrollHeight);
 
			ex.lhs_scroller.scrollTop(sto);
 
		});
 
		ex.crhs.click(function (ev) {
 
			var y = ev.pageY - ex.rhs_xyoffset.top - (rto / 2);
 
			var sto = Math.max(0, (y / mcanvas_rhs.height) * ex.rhs_scroller.get(0).scrollHeight);			
 
			ex.rhs_scroller.scrollTop(sto);
 
		});
 
	},
 
	trace: function(name) {
 
		if(this.settings._debug.indexOf(name) >= 0) {
 
			arguments[0] = name + ':';
 
			console.log([].slice.apply(arguments));
 
		} 
 
	}
 
});
 

	
 
jQuery.pluginMaker = function(plugin) {
 
	// add the plugin function as a jQuery plugin
 
	jQuery.fn[plugin.prototype.name] = function(options) {
 
		// get the arguments 
 
		var args = jQuery.makeArray(arguments),
 
		after = args.slice(1);
 
		var rc;
 
		this.each(function() {
 
			// see if we have an instance
 
			var instance = jQuery.data(this, plugin.prototype.name);
 
			if (instance) {
 
				// call a method on the instance
 
				if (typeof options == "string") {
 
					rc = instance[options].apply(instance, after);
 
				} else if (instance.update) {
 
					// call update on the instance
 
					return instance.update.apply(instance, args);
 
				}
 
			} else {
 
				// create the plugin
 
				var _plugin = new plugin(this, options);
 
			}
 
		});
 
		if (rc != undefined) return rc;
 
	};
 
};
 

	
 
// make the mergely widget
 
jQuery.pluginMaker(Mgly.mergely);
 

	
 
})( window, document, jQuery, CodeMirror );
kallithea/templates/admin/admin.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
<%inherit file="/base/base.html"/>
 

	
 
<%block name="title">
 
    ${_('Admin Journal')}
 
</%block>
 

	
 
<%def name="breadcrumbs_links()">
 
    <form id="filter_form" class="pull-left form-inline input-group-sm">
 
        <input class="form-control q_filter_box ${'' if c.search_term else 'initial'}" id="j_filter" size="15" type="text" name="filter" value="${c.search_term or _('journal filter...')}"/>
 
        <span data-toggle="popover" data-content="${h.journal_filter_help()}">?</span>
 
        <input type='submit' value="${_('Filter')}" class="btn btn-default btn-xs"/>
 
        ${_('Admin Journal')} - ${ungettext('%s Entry', '%s Entries', c.users_log.item_count) % (c.users_log.item_count)}
 
    </form>
 
</%def>
 

	
 
<%block name="header_menu">
 
    ${self.menu('admin')}
 
</%block>
 
<%def name="main()">
 
<div class="panel panel-primary">
 
    <div class="panel-heading clearfix">
 
        ${self.breadcrumbs()}
 
    </div>
 
    <div id="user_log" class="panel-body">
 
            <%include file='admin_log.html'/>
 
    </div>
 
</div>
 

	
 
<script>'use strict';
 
$(document).ready(function() {
 
  $('#j_filter').click(function(){
 
    var $jfilter = $('#j_filter');
 
    if($jfilter.hasClass('initial')){
 
        $jfilter.val('');
 
    }
 
  });
 
  var fix_j_filter_width = function(len){
 
  function fix_j_filter_width(len){
 
      $('#j_filter').css('width', Math.max(80, len*6.50)+'px');
 
  };
 
  }
 
  $('#j_filter').keyup(function () {
 
    fix_j_filter_width($('#j_filter').val().length);
 
  });
 
  $('#filter_form').submit(function (e) {
 
      e.preventDefault();
 
      var val = $('#j_filter').val();
 
      window.location = ${h.js(url.current(filter='__FILTER__'))}.replace('__FILTER__',val);
 
  });
 
  fix_j_filter_width($('#j_filter').val().length);
 
});
 
</script>
 
</%def>
kallithea/templates/admin/auth/auth_settings.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
<%inherit file="/base/base.html"/>
 

	
 
<%block name="title">
 
    ${_('Authentication Settings')}
 
</%block>
 

	
 
<%def name="breadcrumbs_links()">
 
    ${h.link_to(_('Admin'),h.url('admin_home'))}
 
    &raquo;
 
    ${_('Authentication')}
 
</%def>
 

	
 
<%block name="header_menu">
 
    ${self.menu('admin')}
 
</%block>
 

	
 
<%def name="main()">
 
<div class="panel panel-primary">
 
    <div class="panel-heading clearfix">
 
        ${self.breadcrumbs()}
 
    </div>
 
    <div class="form panel-body settings">
 
    ${h.form(url('auth_settings'))}
 

	
 
    ## enabled auth plugins
 
    <h1>${_('Authentication Plugins')}</h1>
 
        <div class="form-group">
 
            <label class="control-label" for="auth_plugins">${_("Enabled Plugins")}</label>
 
            <div>
 
                ${h.text("auth_plugins", class_='form-control')}
 
                <span class="help-block">${_('Comma-separated list of plugins; Kallithea will try user authentication in plugin order')}</span>
 
            </div>
 
        </div>
 
        <div class="form-group">
 
            <label class="control-label">${_('Available built-in plugins')}</label>
 
            <div>
 
                <ul class="list-group">
 
                %for plugin_path in c.available_plugins:
 
                    <li class="list-group-item">
 
                        <button type="button" data-plugin_id="${plugin_path}" class="toggle-plugin btn btn-default btn-xs ${'active' if plugin_path in c.enabled_plugin_names else ''}">
 
                            ${_('Enabled') if plugin_path in c.enabled_plugin_names else _('Disabled')}
 
                        </button>
 
                        ${plugin_path}
 
                    </li>
 
                %endfor
 
                </ul>
 
            </div>
 
        </div>
 

	
 
    %for cnt, module in enumerate(c.enabled_plugin_names):
 
        <% pluginName = c.plugin_shortnames[module] %>
 
        <h1>${_('Plugin')}: ${pluginName}</h1>
 
        ## autoform generation, based on plugin definition from it's settings
 
        %for setting in c.plugin_settings[module]:
 
            <% fullsetting = "auth_%s_%s" % (pluginName, setting["name"]) %>
 
            <% displayname = (setting["formname"] if ("formname" in setting) else setting["name"]) %>
 
            %if setting["type"] == "password":
 
            <div class="form-group">
 
                <label class="control-label" for="${fullsetting}">${_(displayname)}</label>
 
                <div>
 
                    ${h.password(fullsetting,class_='form-control')}
 
                    <span class="help-block">${setting["description"]}</span>
 
                </div>
 
            </div>
 
            %elif setting["type"] in ["string", "int"]:
 
            <div class="form-group">
 
                <label class="control-label" for="${fullsetting}">${_(displayname)}</label>
 
                <div>
 
                    ${h.text(fullsetting,class_='form-control')}
 
                    <span class="help-block">${setting["description"]}</span>
 
                </div>
 
            </div>
 
            %elif setting["type"] == "bool":
 
            <div class="form-group">
 
                <label class="control-label" for="${fullsetting}">${_(displayname)}</label>
 
                <div>
 
                    ${h.checkbox(fullsetting,True)}
 
                    <span class="help-block">${setting["description"]}</span>
 
                </div>
 
            </div>
 
            %elif setting["type"] == "select":
 
            <div class="form-group">
 
                <label class="control-label" for="${fullsetting}">${_(displayname)}</label>
 
                <div>
 
                    ${h.select(fullsetting,setting['values'][0],setting['values'],class_='form-control')}
 
                    <span class="help-block">${setting["description"]}</span>
 
                </div>
 
            </div>
 
            %else:
 
            <div class="form-group">
 
                <label class="control-label" for="${fullsetting}">${_(displayname)}</label>
 
                <div>This field is of type ${setting['type']}, which cannot be displayed. Must be one of [string|int|bool|select].</div>
 
                <span class="help-block">${setting["description"]}</span>
 
            </div>
 
            %endif
 
        %endfor
 
    %endfor
 
            <div class="form-group">
 
                <div class="buttons">
 
                    ${h.submit('save',_('Save'),class_="btn btn-default")}
 
                </div>
 
            </div>
 
    ${h.end_form()}
 
    </div>
 
</div>
 

	
 
<script>'use strict';
 
    $('.toggle-plugin').click(function(e){
 
        var $auth_plugins_input = $('#auth_plugins');
 
        var notEmpty = function(element, index, array) {
 
        function notEmpty(element, index, array) {
 
            return (element != "");
 
        }
 
        var elems = $auth_plugins_input.val().split(',').filter(notEmpty);
 
        var $cur_button = $(e.currentTarget);
 
        var plugin_id = $cur_button.data('plugin_id');
 

	
 
        if($cur_button.hasClass('active')){
 
            elems.splice(elems.indexOf(plugin_id), 1);
 
            $auth_plugins_input.val(elems.join(','));
 
            $cur_button.removeClass('active');
 
            $cur_button.html(_TM['Disabled']);
 
        }
 
        else{
 
            if(elems.indexOf(plugin_id) == -1){
 
                elems.push(plugin_id);
 
            }
 
            $auth_plugins_input.val(elems.join(','));
 
            $cur_button.addClass('active');
 
            $cur_button.html(_TM['Enabled']);
 
        }
 
    });
 
</script>
 
</%def>
kallithea/templates/admin/repo_groups/repo_group_add.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
<%inherit file="/base/base.html"/>
 

	
 
<%block name="title">
 
    ${_('Add Repository Group')}
 
</%block>
 

	
 
<%def name="breadcrumbs_links()">
 
    ${h.link_to(_('Admin'),h.url('admin_home'))}
 
    &raquo;
 
    ${h.link_to(_('Repository Groups'),h.url('repos_groups'))}
 
    &raquo;
 
    ${_('Add Repository Group')}
 
</%def>
 

	
 
<%block name="header_menu">
 
    ${self.menu('admin')}
 
</%block>
 

	
 
<%def name="main()">
 
<div class="panel panel-primary">
 
    <div class="panel-heading clearfix">
 
        ${self.breadcrumbs()}
 
    </div>
 
    ${h.form(url('repos_groups'))}
 
    <div class="form panel-body settings">
 
            <div class="form-group">
 
                <label class="control-label" for="group_name">${_('Group name')}:</label>
 
                <div>
 
                    ${h.text('group_name',class_='form-control')}
 
                </div>
 
            </div>
 

	
 
            <div class="form-group">
 
                <label class="control-label" for="group_description">${_('Description')}:</label>
 
                <div>
 
                    ${h.textarea('group_description',cols=23,rows=5,class_='form-control')}
 
                </div>
 
            </div>
 

	
 
            <div class="form-group">
 
                <label class="control-label" for="parent_group_id">${_('Group parent')}:</label>
 
                <div>
 
                    ${h.select('parent_group_id',request.GET.get('parent_group'),c.repo_groups,class_='form-control')}
 
                </div>
 
            </div>
 

	
 
            <div id="copy_perms" class="form-group">
 
                <label class="control-label" for="group_copy_permissions">${_('Copy parent group permissions')}:</label>
 
                <div>
 
                    ${h.checkbox('group_copy_permissions',value="True")}
 
                    <span class="help-block">${_('Copy permission set from parent repository group.')}</span>
 
                </div>
 
            </div>
 

	
 
            <div class="form-group">
 
                <div class="buttons">
 
                    ${h.submit('save',_('Save'),class_="btn btn-default")}
 
                </div>
 
            </div>
 
    </div>
 
    ${h.end_form()}
 
</div>
 
<script>'use strict';
 
    $(document).ready(function(){
 
        var setCopyPermsOption = function(group_val){
 
        function setCopyPermsOption(group_val){
 
            if(group_val != "-1"){
 
                $('#copy_perms').show();
 
            }
 
            else{
 
                $('#copy_perms').hide();
 
            }
 
        }
 
        $("#parent_group_id").select2({
 
            'dropdownAutoWidth': true
 
        });
 
        setCopyPermsOption($('#parent_group_id').val());
 
        $("#parent_group_id").on("change", function(e) {
 
            setCopyPermsOption(e.val);
 
        });
 
        $('#group_name').focus();
 
    });
 
</script>
 
</%def>
kallithea/templates/admin/repos/repo_add_base.html
Show inline comments
 
## -*- coding: utf-8 -*-
 

	
 
${h.form(url('repos'))}
 
<div class="form">
 
        <div class="form-group">
 
            <label class="control-label" for="repo_name">${_('Name')}:</label>
 
            <div>
 
                ${h.text('repo_name',class_='form-control')}
 
            </div>
 
         </div>
 
        <div id="remote_clone" class="form-group">
 
            <label class="control-label" for="clone_uri">${_('Clone remote repository')}:</label>
 
            <div>
 
                ${h.text('clone_uri',class_='form-control')}
 
                <span class="help-block">
 
                    ${_('Optional: URL of a remote repository. If set, the repository will be created as a clone from this URL.')}
 
                </span>
 
            </div>
 
        </div>
 
        <div class="form-group">
 
            <label class="control-label" for="repo_description">${_('Description')}:</label>
 
            <div>
 
                ${h.textarea('repo_description',class_='form-control')}
 
                <span class="help-block">${_('Keep it short and to the point. Use a README file for longer descriptions.')}</span>
 
            </div>
 
        </div>
 
        <div class="form-group">
 
            <label class="control-label" for="repo_group">${_('Repository group')}:</label>
 
            <div>
 
                ${h.select('repo_group',request.GET.get('parent_group'),c.repo_groups,class_='form-control')}
 
                <span class="help-block">${_('Optionally select a group to put this repository into.')}</span>
 
            </div>
 
        </div>
 
        <div id="copy_perms" class="form-group">
 
            <label class="control-label" for="repo_copy_permissions">${_('Copy parent group permissions')}:</label>
 
            <div>
 
                ${h.checkbox('repo_copy_permissions',value="True")}
 
                <span class="help-block">${_('Copy permission set from parent repository group.')}</span>
 
            </div>
 
        </div>
 
        <div class="form-group">
 
            <label class="control-label" for="repo_type">${_('Type')}:</label>
 
            <div>
 
                ${h.select('repo_type','hg',c.backends,class_='form-control')}
 
                <span class="help-block">${_('Type of repository to create.')}</span>
 
            </div>
 
        </div>
 
        <div class="form-group">
 
            <label class="control-label" for="repo_landing_rev">${_('Landing revision')}:</label>
 
            <div>
 
                ${h.select('repo_landing_rev','',c.landing_revs,class_='form-control')}
 
                <span class="help-block">${_('Default revision for files page, downloads, full text search index and readme generation')}</span>
 
            </div>
 
        </div>
 
        <div class="form-group">
 
            <label class="control-label" for="repo_private">${_('Private repository')}:</label>
 
            <div>
 
                ${h.checkbox('repo_private',value="True")}
 
                <span class="help-block">${_('Private repositories are only visible to people explicitly added as collaborators.')}</span>
 
            </div>
 
        </div>
 
        <div class="form-group">
 
            <div class="buttons">
 
                ${h.submit('add',_('Add'),class_="btn btn-default")}
 
            </div>
 
        </div>
 
</div>
 
<script>'use strict';
 
    $(document).ready(function(){
 
        var setCopyPermsOption = function(group_val){
 
        function setCopyPermsOption(group_val){
 
            if(group_val != "-1"){
 
                $('#copy_perms').show();
 
            }
 
            else{
 
                $('#copy_perms').hide();
 
            }
 
        }
 

	
 
        $("#repo_group").select2({
 
            'dropdownAutoWidth': true
 
        });
 

	
 
        setCopyPermsOption($('#repo_group').val());
 
        $("#repo_group").on("change", function(e) {
 
            setCopyPermsOption(e.val);
 
        });
 

	
 
        $("#repo_type").select2({
 
            'minimumResultsForSearch': -1
 
        });
 
        $("#repo_landing_rev").select2({
 
            'minimumResultsForSearch': -1
 
        });
 
        $('#repo_name').focus();
 
    });
 
</script>
 
${h.end_form()}
kallithea/templates/admin/settings/settings_hooks.html
Show inline comments
 
<div class="form">
 
      <div class="form-group">
 
      <h4>${_('Built-in Mercurial Hooks (Read-Only)')}</h4>
 
      % for hook in c.hooks:
 
        <% input_id = hook.ui_key.replace('.', '_') %>
 
            <label class="control-label" for="${input_id}" title="${hook.ui_key}">${hook.ui_key}</label>
 
            <div>
 
              ${h.text(hook.ui_key,hook.ui_value,id=input_id,size=60,readonly="readonly",class_='form-control')}
 
            </div>
 
      % endfor
 
      </div>
 
</div>
 

	
 
% if c.visual.allow_custom_hooks_settings:
 
${h.form(url('admin_settings_hooks'), method='post')}
 
<div class="form">
 
        <h4>${_('Custom Hooks')}</h4>
 
        <span class="help-block">${_('Hooks can be used to trigger actions on certain events such as push / pull. They can trigger Python functions or external applications.')}</span>
 
        %for hook in c.custom_hooks:
 
            <div class="form-group form-inline" id="${'id%s' % hook.ui_id }">
 
                <% input_id = hook.ui_key.replace('.', '_') %>
 
                    <label class="control-label" for="${input_id}" title="${hook.ui_key}">${hook.ui_key}</label>
 
                    <div>
 
                        ${h.hidden('hook_ui_key',hook.ui_key,id='hook_ui_key_'+input_id)}
 
                        ${h.hidden('hook_ui_value',hook.ui_value,id='hook_ui_value_'+input_id)}
 
                        ${h.text('hook_ui_value_new',hook.ui_value,id=input_id,size=50,class_='form-control')}
 
                        <button type="button" class="btn btn-default btn-xs"
 
                            onclick="delete_hook(${hook.ui_id},'${'id%s' % hook.ui_id }')">
 
                            <i class="icon-trashcan"></i>
 
                            ${_('Delete')}
 
                        </button>
 
                    </div>
 
            </div>
 
        %endfor
 

	
 
        <div class="form-group form-inline">
 
            <label>
 
                ${h.text('new_hook_ui_key',size=15,class_='form-control')}
 
            </label>
 
            <div>
 
                ${h.text('new_hook_ui_value',size=50,class_='form-control')}
 
            </div>
 
        </div>
 
        <div class="form-group">
 
            <div class="buttons">
 
                ${h.submit('save',_('Save'),class_="btn btn-default")}
 
            </div>
 
        </div>
 
</div>
 
${h.end_form()}
 
% endif
 

	
 
<script>'use strict';
 
function delete_hook(hook_id, field_id) {
 
    var sUrl = ${h.js(h.url('admin_settings_hooks_delete'))};
 
    var success = function (o) {
 
    function success(o) {
 
            $('#' + field_id).remove();
 
        };
 
    var failure = function (o) {
 
        }
 
    function failure(o) {
 
            alert(${h.js(_('Failed to remove hook'))});
 
        };
 
        }
 
    var postData = {'hook_id': hook_id};
 
    ajaxPOST(sUrl, postData, success, failure);
 
};
 
</script>
kallithea/templates/base/base.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
<%inherit file="root.html"/>
 

	
 
<!-- CONTENT -->
 
<div id="content" class="container-fluid">
 
    ${self.flash_msg()}
 
    <div id="main">
 
        ${next.main()}
 
    </div>
 
</div>
 
<!-- END CONTENT -->
 

	
 
<!-- FOOTER -->
 
<div class="footer navbar navbar-inverse">
 
    <span class="navbar-text pull-left">
 
        ${_('Server instance: %s') % c.instance_id if c.instance_id else ''}
 
    </span>
 
    <span class="navbar-text pull-right">
 
        This site is powered by
 
        %if c.visual.show_version:
 
            <a class="navbar-link" href="${h.url('kallithea_project_url')}" target="_blank">Kallithea</a> ${c.kallithea_version},
 
        %else:
 
            <a class="navbar-link" href="${h.url('kallithea_project_url')}" target="_blank">Kallithea</a>,
 
        %endif
 
        which is
 
        <a class="navbar-link" href="${h.canonical_url('about')}#copyright">&copy; 2010&ndash;2020 by various authors &amp; licensed under GPLv3</a>.
 
        %if c.issues_url:
 
            &ndash; <a class="navbar-link" href="${c.issues_url}" target="_blank">${_('Support')}</a>
 
        %endif
 
    </span>
 
</div>
 

	
 
<!-- END FOOTER -->
 

	
 
### MAKO DEFS ###
 

	
 
<%block name="branding_title">
 
    %if c.site_name:
 
    &middot; ${c.site_name}
 
    %endif
 
</%block>
 

	
 
<%def name="flash_msg()">
 
    <%include file="/base/flash_msg.html"/>
 
</%def>
 

	
 
<%def name="breadcrumbs()">
 
    <div class="panel-title">
 
    ${self.breadcrumbs_links()}
 
    </div>
 
</%def>
 

	
 
<%def name="admin_menu()">
 
  <ul class="dropdown-menu" role="menu">
 
      <li><a href="${h.url('admin_home')}"><i class="icon-book"></i>${_('Admin Journal')}</a></li>
 
      <li><a href="${h.url('repos')}"><i class="icon-database"></i>${_('Repositories')}</a></li>
 
      <li><a href="${h.url('repos_groups')}"><i class="icon-folder"></i>${_('Repository Groups')}</a></li>
 
      <li><a href="${h.url('users')}"><i class="icon-user"></i>${_('Users')}</a></li>
 
      <li><a href="${h.url('users_groups')}"><i class="icon-users"></i>${_('User Groups')}</a></li>
 
      <li><a href="${h.url('admin_permissions')}"><i class="icon-block"></i>${_('Default Permissions')}</a></li>
 
      <li><a href="${h.url('auth_home')}"><i class="icon-key"></i>${_('Authentication')}</a></li>
 
      <li><a href="${h.url('defaults')}"><i class="icon-wrench"></i>${_('Repository Defaults')}</a></li>
 
      <li class="last"><a href="${h.url('admin_settings')}"><i class="icon-gear"></i>${_('Settings')}</a></li>
 
  </ul>
 

	
 
</%def>
 

	
 

	
 
## admin menu used for people that have some admin resources
 
<%def name="admin_menu_simple(repositories=None, repository_groups=None, user_groups=None)">
 
  <ul class="dropdown-menu" role="menu">
 
   %if repositories:
 
      <li><a href="${h.url('repos')}"><i class="icon-database"></i>${_('Repositories')}</a></li>
 
   %endif
 
   %if repository_groups:
 
      <li><a href="${h.url('repos_groups')}"><i class="icon-folder"></i>${_('Repository Groups')}</a></li>
 
   %endif
 
   %if user_groups:
 
      <li><a href="${h.url('users_groups')}"><i class="icon-users"></i>${_('User Groups')}</a></li>
 
   %endif
 
  </ul>
 
</%def>
 

	
 
<%def name="repolabel(repo)">
 
  %if h.is_hg(repo):
 
    <span class="label label-repo" title="${_('Mercurial repository')}">hg</span>
 
  %endif
 
  %if h.is_git(repo):
 
    <span class="label label-repo" title="${_('Git repository')}">git</span>
 
  %endif
 
</%def>
 

	
 
<%def name="repo_context_bar(current=None, rev=None)">
 
  <% rev = None if rev == 'tip' else rev %>
 
  <!--- CONTEXT BAR -->
 
  <nav id="context-bar" class="navbar navbar-inverse">
 
    <div class="container-fluid">
 
    <div class="navbar-header">
 
      <div class="navbar-brand">
 
        ${repolabel(c.db_repo)}
 

	
 
        ## public/private
 
        %if c.db_repo.private:
 
          <i class="icon-lock"></i>
 
        %else:
 
          <i class="icon-globe"></i>
 
        %endif
 
        %for group in c.db_repo.groups_with_parents:
 
          ${h.link_to(group.name, url('repos_group_home', group_name=group.group_name), class_='navbar-link')}
 
          &raquo;
 
        %endfor
 
        ${h.link_to(c.db_repo.just_name, url('summary_home', repo_name=c.db_repo.repo_name), class_='navbar-link')}
 

	
 
        %if current == 'createfork':
 
         - ${_('Create Fork')}
 
        %endif
 
      </div>
 
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#context-pages" aria-expanded="false">
 
        <span class="sr-only">Toggle navigation</span>
 
        <span class="icon-bar"></span>
 
        <span class="icon-bar"></span>
 
        <span class="icon-bar"></span>
 
      </button>
 
    </div>
 
    <div id="context-pages" class="navbar-collapse collapse">
 
    <ul class="nav navbar-nav navbar-right">
 
        <li class="${'active' if current == 'summary' else ''}" data-context="summary"><a href="${h.url('summary_home', repo_name=c.repo_name)}"><i class="icon-doc-text"></i>${_('Summary')}</a></li>
 
        %if rev:
 
        <li class="${'active' if current == 'changelog' else ''}" data-context="changelog"><a href="${h.url('changelog_file_home', repo_name=c.repo_name, revision=rev, f_path='')}"><i class="icon-clock"></i>${_('Changelog')}</a></li>
 
        %else:
 
        <li class="${'active' if current == 'changelog' else ''}" data-context="changelog"><a href="${h.url('changelog_home', repo_name=c.repo_name)}"><i class="icon-clock"></i>${_('Changelog')}</a></li>
 
        %endif
 
        <li class="${'active' if current == 'files' else ''}" data-context="files"><a href="${h.url('files_home', repo_name=c.repo_name, revision=rev or 'tip')}"><i class="icon-doc-inv"></i>${_('Files')}</a></li>
 
        <li class="${'active' if current == 'showpullrequest' else ''}" data-context="showpullrequest">
 
          <a href="${h.url('pullrequest_show_all',repo_name=c.repo_name)}" title="${_('Show Pull Requests for %s') % c.repo_name}"> <i class="icon-git-pull-request"></i>${_('Pull Requests')}
 
            %if c.repository_pull_requests:
 
              <span class="badge">${c.repository_pull_requests}</span>
 
            %endif
 
          </a>
 
        </li>
 
        <li class="${'active' if current == 'switch-to' else ''}" data-context="switch-to">
 
          <input id="branch_switcher" name="branch_switcher" type="hidden">
 
        </li>
 
        <li class="${'active' if current == 'options' else ''} dropdown" data-context="options">
 
             %if h.HasRepoPermissionLevel('admin')(c.repo_name):
 
               <a href="${h.url('edit_repo',repo_name=c.repo_name)}" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false" aria-haspopup="true"><i class="icon-wrench"></i>${_('Options')} <i class="caret"></i></a>
 
             %else:
 
               <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false" aria-haspopup="true"><i class="icon-wrench"></i>${_('Options')} <i class="caret"></i></a>
 
             %endif
 
          <ul class="dropdown-menu" role="menu" aria-hidden="true">
 
             %if h.HasRepoPermissionLevel('admin')(c.repo_name):
 
                   <li><a href="${h.url('edit_repo',repo_name=c.repo_name)}"><i class="icon-gear"></i>${_('Settings')}</a></li>
 
             %endif
 
              %if c.db_repo.fork:
 
               <li><a href="${h.url('compare_url',repo_name=c.db_repo.fork.repo_name,org_ref_type=c.db_repo.landing_rev[0],org_ref_name=c.db_repo.landing_rev[1], other_repo=c.repo_name,other_ref_type='branch' if request.GET.get('branch') else c.db_repo.landing_rev[0],other_ref_name=request.GET.get('branch') or c.db_repo.landing_rev[1], merge=1)}">
 
                   <i class="icon-git-compare"></i>${_('Compare Fork')}</a></li>
 
              %endif
 
              <li><a href="${h.url('compare_home',repo_name=c.repo_name)}"><i class="icon-git-compare"></i>${_('Compare')}</a></li>
 

	
 
              <li><a href="${h.url('search_repo',repo_name=c.repo_name)}"><i class="icon-search"></i>${_('Search')}</a></li>
 

	
 
              ## TODO: this check feels wrong, it would be better to have a check for permissions
 
              ## also it feels like a job for the controller
 
              %if request.authuser.username != 'default':
 
                  <li>
 
                   <a href="#" class="${'following' if c.repository_following else 'follow'}" onclick="return toggleFollowingRepo(this, ${c.db_repo.repo_id});">
 
                    <span class="show-follow"><i class="icon-heart-empty"></i>${_('Follow')}</span>
 
                    <span class="show-following"><i class="icon-heart"></i>${_('Unfollow')}</span>
 
                   </a>
 
                  </li>
 
                  <li><a href="${h.url('repo_fork_home',repo_name=c.repo_name)}"><i class="icon-fork"></i>${_('Fork')}</a></li>
 
                  <li><a href="${h.url('pullrequest_home',repo_name=c.repo_name)}"><i class="icon-git-pull-request"></i>${_('Create Pull Request')}</a></li>
 
              %endif
 
             </ul>
 
        </li>
 
    </ul>
 
    </div>
 
    </div>
 
  </nav>
 
  <script>'use strict';
 
    $(document).ready(function() {
 
      var bcache = {};
 

	
 
      var branch_switcher_placeholder = '<i class="icon-exchange"></i>' + ${h.jshtml(_('Switch To'))} + ' <span class="caret"></span>';
 
      $("#branch_switcher").select2({
 
          placeholder: branch_switcher_placeholder,
 
          dropdownAutoWidth: true,
 
          sortResults: prefixFirstSort,
 
          formatResult: function(obj) {
 
              return obj.text.html_escape();
 
          },
 
          formatSelection: function(obj) {
 
              return obj.text.html_escape();
 
          },
 
          formatNoMatches: function(term) {
 
              return ${h.jshtml(_('No matches found'))};
 
          },
 
          escapeMarkup: function(m) {
 
              if (m == branch_switcher_placeholder)
 
                  return branch_switcher_placeholder;
 
              return Select2.util.escapeMarkup(m);
 
          },
 
          containerCssClass: "branch-switcher",
 
          dropdownCssClass: "repo-switcher-dropdown",
 
          query: function(query) {
 
              var key = 'cache';
 
              var cached = bcache[key];
 
              if (cached) {
 
                  var data = {
 
                      results: []
 
                  };
 
                  // filter results
 
                  $.each(cached.results, function() {
 
                      var section = this.text;
 
                      var children = [];
 
                      $.each(this.children, function() {
 
                          if (query.term.length === 0 || this.text.toUpperCase().indexOf(query.term.toUpperCase()) >= 0) {
 
                              children.push({
 
                                  'id': this.id,
 
                                  'text': this.text,
 
                                  'type': this.type,
 
                                  'obj': this.obj
 
                              });
 
                          }
 
                      });
 
                      if (children.length !== 0) {
 
                          data.results.push({
 
                              'text': section,
 
                              'children': children
 
                          });
 
                      }
 

	
 
                  });
 
                  query.callback(data);
 
              } else {
 
                  $.ajax({
 
                      url: pyroutes.url('repo_refs_data', {
 
                          'repo_name': ${h.js(c.repo_name)}
 
                      }),
 
                      data: {},
 
                      dataType: 'json',
 
                      type: 'GET',
 
                      success: function(data) {
 
                          bcache[key] = data;
 
                          query.callback(data);
 
                      }
 
                  });
 
              }
 
          }
 
      });
 

	
 
      $("#branch_switcher").on('select2-selecting', function(e) {
 
          e.preventDefault();
 
          var context = $('#context-bar .active').data('context');
 
          if (context == 'files') {
 
              window.location = pyroutes.url('files_home', {
 
                  'repo_name': REPO_NAME,
 
                  'revision': e.choice.id,
 
                  'f_path': '',
 
                  'at': e.choice.text
 
              });
 
          } else if (context == 'changelog') {
 
              if (e.choice.type == 'tag' || e.choice.type == 'book') {
 
                  $("#branch_filter").append($('<'+'option/>').val(e.choice.text));
 
              }
 
              $("#branch_filter").val(e.choice.text).change();
 
          } else {
 
              window.location = pyroutes.url('changelog_home', {
 
                  'repo_name': ${h.js(c.repo_name)},
 
                  'branch': e.choice.text
 
              });
 
          }
 
      });
 
    });
 
  </script>
 
  <!--- END CONTEXT BAR -->
 
</%def>
 

	
 
<%def name="menu(current=None)">
 
  <ul id="quick" class="nav navbar-nav navbar-right">
 
    <!-- repo switcher -->
 
    <li class="${'active' if current == 'repositories' else ''}">
 
      <input id="repo_switcher" name="repo_switcher" type="hidden">
 
    </li>
 

	
 
    ##ROOT MENU
 
    %if request.authuser.username != 'default':
 
      <li class="${'active' if current == 'journal' else ''}">
 
        <a class="menu_link" title="${_('Show recent activity')}"  href="${h.url('journal')}">
 
          <i class="icon-book"></i>${_('Journal')}
 
        </a>
 
      </li>
 
    %else:
 
      <li class="${'active' if current == 'journal' else ''}">
 
        <a class="menu_link" title="${_('Public journal')}"  href="${h.url('public_journal')}">
 
          <i class="icon-book"></i>${_('Public journal')}
 
        </a>
 
      </li>
 
    %endif
 
      <li class="${'active' if current == 'gists' else ''} dropdown">
 
        <a class="menu_link dropdown-toggle" data-toggle="dropdown" role="button" title="${_('Show public gists')}"  href="${h.url('gists')}">
 
          <i class="icon-clippy"></i>${_('Gists')} <span class="caret"></span>
 
        </a>
 
          <ul class="dropdown-menu" role="menu">
 
            <li><a href="${h.url('new_gist', public=1)}"><i class="icon-paste"></i>${_('Create New Gist')}</a></li>
 
            <li><a href="${h.url('gists')}"><i class="icon-globe"></i>${_('All Public Gists')}</a></li>
 
            %if request.authuser.username != 'default':
 
              <li><a href="${h.url('gists', public=1)}"><i class="icon-user"></i>${_('My Public Gists')}</a></li>
 
              <li><a href="${h.url('gists', private=1)}"><i class="icon-lock"></i>${_('My Private Gists')}</a></li>
 
            %endif
 
          </ul>
 
      </li>
 
    <li class="${'active' if current == 'search' else ''}">
 
        <a class="menu_link" title="${_('Search in repositories')}"  href="${h.url('search')}">
 
          <i class="icon-search"></i>${_('Search')}
 
        </a>
 
    </li>
 
    % if h.HasPermissionAny('hg.admin')('access admin main page'):
 
      <li class="${'active' if current == 'admin' else ''} dropdown">
 
        <a class="menu_link dropdown-toggle" data-toggle="dropdown" role="button" title="${_('Admin')}" href="${h.url('admin_home')}">
 
          <i class="icon-gear"></i>${_('Admin')} <span class="caret"></span>
 
        </a>
 
        ${admin_menu()}
 
      </li>
 
    % elif request.authuser.repositories_admin or request.authuser.repository_groups_admin or request.authuser.user_groups_admin:
 
    <li class="${'active' if current == 'admin' else ''} dropdown">
 
        <a class="menu_link dropdown-toggle" data-toggle="dropdown" role="button" title="${_('Admin')}" href="">
 
          <i class="icon-gear"></i>${_('Admin')}
 
        </a>
 
        ${admin_menu_simple(request.authuser.repositories_admin,
 
                            request.authuser.repository_groups_admin,
 
                            request.authuser.user_groups_admin or h.HasPermissionAny('hg.usergroup.create.true')())}
 
    </li>
 
    % endif
 

	
 
    <li class="${'active' if current == 'my_pullrequests' else ''}">
 
      <a class="menu_link" title="${_('My Pull Requests')}" href="${h.url('my_pullrequests')}">
 
        <i class="icon-git-pull-request"></i>${_('My Pull Requests')}
 
        %if c.my_pr_count != 0:
 
          <span class="badge">${c.my_pr_count}</span>
 
        %endif
 
      </a>
 
    </li>
 

	
 
    ## USER MENU
 
    <li class="dropdown">
 
      <a class="menu_link dropdown-toggle" data-toggle="dropdown" role="button" id="quick_login_link"
 
        aria-expanded="false" aria-controls="quick_login" href="#">
 
          ${h.gravatar_div(request.authuser.email, size=20, div_class="icon")}
 
          %if request.authuser.username != 'default':
 
            <span class="menu_link_user">${request.authuser.username}</span>
 
          %else:
 
              <span>${_('Not Logged In')}</span>
 
          %endif
 
          <i class="caret"></i>
 
      </a>
 

	
 
      <div class="dropdown-menu user-menu" role="menu">
 
        <div id="quick_login" role="form" aria-describedby="quick_login_h" aria-hidden="true" class="container-fluid">
 
          %if request.authuser.username == 'default' or request.authuser.user_id is None:
 
            ${h.form(h.url('login_home', came_from=request.path_qs), class_='form clearfix')}
 
                <h4 id="quick_login_h">${_('Login to Your Account')}</h4>
 
                <label>
 
                    ${_('Username')}:
 
                    ${h.text('username',class_='form-control')}
 
                </label>
 
                <label>
 
                    ${_('Password')}:
 
                    ${h.password('password',class_='form-control')}
 
                </label>
 
                <div class="password_forgotten">
 
                    ${h.link_to(_('Forgot password?'),h.url('reset_password'))}
 
                </div>
 
                <div class="register">
 
                    %if h.HasPermissionAny('hg.admin', 'hg.register.auto_activate', 'hg.register.manual_activate')():
 
                        ${h.link_to(_("Don't have an account?"),h.url('register'))}
 
                    %endif
 
                </div>
 
                <div class="submit">
 
                    ${h.submit('sign_in',_('Log In'),class_="btn btn-default btn-xs")}
 
                </div>
 
            ${h.end_form()}
 
          %else:
 
            <div class="pull-left">
 
                ${h.gravatar_div(request.authuser.email, size=48, div_class="big_gravatar")}
 
                <b class="full_name">${request.authuser.full_name_or_username}</b>
 
                <div class="email">${request.authuser.email}</div>
 
            </div>
 
            <div id="quick_login_h" class="pull-right list-group text-right">
 
              ${h.link_to(_('My Account'),h.url('my_account'),class_='list-group-item')}
 
              %if not request.authuser.is_external_auth:
 
                ## Cannot log out if using external (container) authentication.
 
                ${h.link_to(_('Log Out'), h.url('logout_home'),class_='list-group-item')}
 
              %endif
 
            </div>
 
          %endif
 
        </div>
 
      </div>
 
    </li>
 
  </ul>
 

	
 
    <script>'use strict';
 
        $(document).ready(function(){
 
            var visual_show_public_icon = ${h.js(c.visual.show_public_icon)};
 
            var cache = {}
 
            /*format the look of items in the list*/
 
            var format = function(state){
 
            function format(state){
 
                if (!state.id){
 
                  return state.text.html_escape(); // optgroup
 
                }
 
                var obj_dict = state.obj;
 
                var tmpl = '';
 

	
 
                if(obj_dict && state.type == 'repo'){
 
                    tmpl += '<span class="repo-icons">';
 
                    if(obj_dict['repo_type'] === 'hg'){
 
                        tmpl += '<span class="label label-repo" title="${_('Mercurial repository')}">hg</span> ';
 
                    }
 
                    else if(obj_dict['repo_type'] === 'git'){
 
                        tmpl += '<span class="label label-repo" title="${_('Git repository')}">git</span> ';
 
                    }
 
                    if(obj_dict['private']){
 
                        tmpl += '<i class="icon-lock"></i>';
 
                    }
 
                    else if(visual_show_public_icon){
 
                        tmpl += '<i class="icon-globe"></i>';
 
                    }
 
                    tmpl += '</span>';
 
                }
 
                if(obj_dict && state.type == 'group'){
 
                        tmpl += '<i class="icon-folder"></i>';
 
                }
 
                tmpl += state.text.html_escape();
 
                return tmpl;
 
            }
 

	
 
            var repo_switcher_placeholder = '<i class="icon-database"></i>' + ${h.jshtml(_('Repositories'))} + ' <span class="caret"></span>';
 
            $("#repo_switcher").select2({
 
                placeholder: repo_switcher_placeholder,
 
                dropdownAutoWidth: true,
 
                sortResults: prefixFirstSort,
 
                formatResult: format,
 
                formatSelection: format,
 
                formatNoMatches: function(term){
 
                    return ${h.jshtml(_('No matches found'))};
 
                },
 
                containerCssClass: "repo-switcher",
 
                dropdownCssClass: "repo-switcher-dropdown",
 
                escapeMarkup: function(m){
 
                    if (m == repo_switcher_placeholder)
 
                        return repo_switcher_placeholder;
 
                    return Select2.util.escapeMarkup(m);
 
                },
 
                query: function(query){
 
                  var key = 'cache';
 
                  var cached = cache[key] ;
 
                  if(cached) {
 
                    var data = {results: []};
 
                    //filter results
 
                    $.each(cached.results, function(){
 
                        var section = this.text;
 
                        var children = [];
 
                        $.each(this.children, function(){
 
                            if(query.term.length == 0 || this.text.toUpperCase().indexOf(query.term.toUpperCase()) >= 0 ){
 
                                children.push({'id': this.id, 'text': this.text, 'type': this.type, 'obj': this.obj});
 
                            }
 
                        });
 
                        if(children.length !== 0){
 
                            data.results.push({'text': section, 'children': children});
 
                        }
 

	
 
                    });
 
                    query.callback(data);
 
                  }else{
 
                      $.ajax({
 
                        url: ${h.js(h.url('repo_switcher_data'))},
 
                        data: {},
 
                        dataType: 'json',
 
                        type: 'GET',
 
                        success: function(data) {
 
                          cache[key] = data;
 
                          query.callback({results: data.results});
 
                        }
 
                      });
 
                  }
 
                }
 
            });
 

	
 
            $("#repo_switcher").on('select2-selecting', function(e){
 
                e.preventDefault();
 
                window.location = pyroutes.url('summary_home', {'repo_name': e.val});
 
            });
 

	
 
            $(document).on('shown.bs.dropdown', function(event) {
 
                var dropdown = $(event.target);
 

	
 
                dropdown.attr('aria-expanded', true);
 
                dropdown.find('.dropdown-menu').attr('aria-hidden', false);
 
            });
 

	
 
            $(document).on('hidden.bs.dropdown', function(event) {
 
                var dropdown = $(event.target);
 

	
 
                dropdown.attr('aria-expanded', false);
 
                dropdown.find('.dropdown-menu').attr('aria-hidden', true);
 
            });
 
        });
 
    </script>
 
</%def>
 

	
 
<%def name="parent_child_navigation()">
 
    <div class="pull-left">
 
        <div class="parent-child-link"
 
             data-ajax-url="${h.url('changeset_parents',repo_name=c.repo_name, revision=c.changeset.raw_id)}"
 
             data-linktype="parent"
 
             data-reponame="${c.repo_name}">
 
            <i class="icon-left-open"></i><a href="#">${_('Parent rev.')}</a>
 
        </div>
 
    </div>
 

	
 
    <div class="pull-right">
 
        <div class="parent-child-link"
 
             data-ajax-url="${h.url('changeset_children',repo_name=c.repo_name, revision=c.changeset.raw_id)}"
 
             data-linktype="child"
 
             data-reponame="${c.repo_name}">
 
            <a href="#">${_('Child rev.')}</a><i class="icon-right-open"></i>
 
        </div>
 
    </div>
 

	
 
    <script>'use strict';
 
      $(document).ready(function(){
 
          activate_parent_child_links();
 
      });
 
    </script>
 
</%def>
kallithea/templates/base/perms_summary.html
Show inline comments
 
## snippet for displaying permissions overview for users
 
## usage:
 
##    <%namespace name="p" file="/base/perms_summary.html"/>
 
##    ${p.perms_summary(c.perm_user.permissions)}
 

	
 
<%def name="perms_summary(permissions, show_all=False, actions=True)">
 
<div id="perms">
 
     %for section in sorted(permissions):
 
        <div class="perms_section_head">
 
            <h4>${section.replace("_"," ").capitalize()}</h4>
 
            %if section != 'global':
 
              <div class="pull-right checkbox">
 
                ${_('Show')}:
 
                <label>${h.checkbox('perms_filter_none_%s' % section, 'none', 'checked', class_='perm_filter filter_%s' % section, **{'data-section':section, 'data-perm_type':'none'})}<span class="label label-none">${_('None')}</span></label>
 
                <label>${h.checkbox('perms_filter_read_%s' % section, 'read', 'checked', class_='perm_filter filter_%s' % section, **{'data-section':section, 'data-perm_type':'read'})}<span class="label label-read">${_('Read')}</span></label>
 
                <label>${h.checkbox('perms_filter_write_%s' % section, 'write', 'checked', class_='perm_filter filter_%s' % section, **{'data-section':section, 'data-perm_type':'write'})}<span class="label label-write">${_('Write')}</span></label>
 
                <label>${h.checkbox('perms_filter_admin_%s' % section, 'admin', 'checked', class_='perm_filter filter_%s' % section, **{'data-section':section, 'data-perm_type':'admin'})}<span class="label label-admin">${_('Admin')}</span></label>
 
              </div>
 
            %endif
 
        </div>
 
        %if not permissions[section]:
 
            <span class="text-muted">${_('No permissions defined yet')}</span>
 
        %else:
 
        <div id='tbl_list_wrap_${section}'>
 
         <table id="tbl_list_${section}" class="table">
 
          ## global permission box
 
          %if section == 'global':
 
              <thead>
 
                <tr>
 
                  <th class="left col-xs-9">${_('Permission')}</th>
 
                  %if actions:
 
                  <th class="left col-xs-3">${_('Edit Permission')}</th>
 
                  %endif
 
                </tr>
 
              </thead>
 
              <tbody>
 
              %for k in permissions[section]:
 
                  <tr>
 
                      <td>
 
                          ${h.get_permission_name(k)}
 
                      </td>
 
                      %if actions:
 
                      <td>
 
                           <a href="${h.url('admin_permissions')}">${_('Edit')}</a>
 
                      </td>
 
                      %endif
 
                  </tr>
 
              %endfor
 
              </tbody>
 
          %else:
 
             ## none/read/write/admin permissions on groups/repos etc
 
              <thead>
 
                <tr>
 
                  <th class="left col-xs-7">${_('Name')}</th>
 
                  <th class="left col-xs-2">${_('Permission')}</th>
 
                  %if actions:
 
                  <th class="left col-xs-3">${_('Edit Permission')}</th>
 
                  %endif
 
                </tr>
 
              </thead>
 
              <tbody class="section_${section}">
 
              %for k, section_perm in sorted(permissions[section].items(), key=lambda s: {'none':0, 'read':1,'write':2,'admin':3}.get(s[1].split('.')[-1])):
 
                  %if section_perm.split('.')[-1] != 'none' or show_all:
 
                  <tr class="perm_row ${'%s_%s' % (section, section_perm.split('.')[-1])}">
 
                      <td>
 
                          %if section == 'repositories':
 
                              <a href="${h.url('summary_home',repo_name=k)}">${k}</a>
 
                          %elif section == 'repositories_groups':
 
                              <a href="${h.url('repos_group_home',group_name=k)}">${k}</a>
 
                          %elif section == 'user_groups':
 
                              ##<a href="${h.url('edit_users_group',id=k)}">${k}</a>
 
                              ${k}
 
                          %endif
 
                      </td>
 
                      <td>
 
                           <span class="label label-${section_perm.split('.')[-1]}">${section_perm}</span>
 
                      </td>
 
                      %if actions:
 
                      <td>
 
                          %if section == 'repositories':
 
                              <a href="${h.url('edit_repo_perms',repo_name=k,anchor='permissions_manage')}">${_('Edit')}</a>
 
                          %elif section == 'repositories_groups':
 
                              <a href="${h.url('edit_repo_group_perms',group_name=k,anchor='permissions_manage')}">${_('Edit')}</a>
 
                          %elif section == 'user_groups':
 
                              ##<a href="${h.url('edit_users_group',id=k)}">${_('Edit')}</a>
 
                          %endif
 
                      </td>
 
                      %endif
 
                  </tr>
 
                  %endif
 
              %endfor
 
              <tr id="empty_${section}" style="display: none"><td colspan="${3 if actions else 2}">${_('No permission defined')}</td></tr>
 
              </tbody>
 
          %endif
 
         </table>
 
        </div>
 
        %endif
 
     %endfor
 
</div>
 
<script>'use strict';
 
    $(document).ready(function(){
 
        var show_empty = function(section){
 
        function show_empty(section){
 
            var visible = $('.section_{0} tr.perm_row:visible'.format(section)).length;
 
            if(visible == 0){
 
                $('#empty_{0}'.format(section)).show();
 
            }
 
            else{
 
                $('#empty_{0}'.format(section)).hide();
 
            }
 
        }
 
        var update_show = function($checkbox){
 
        function update_show($checkbox){
 
            var section = $checkbox.data('section');
 

	
 
            var elems = $('.filter_' + section).each(function(el){
 
                var perm_type = $checkbox.data('perm_type');
 
                var checked = $checkbox.prop('checked');
 
                if(checked){
 
                    $('.'+section+'_'+perm_type).show();
 
                }
 
                else{
 
                    $('.'+section+'_'+perm_type).hide();
 
                }
 
            });
 
            show_empty(section);
 
        }
 
        $('.perm_filter').on('change', function(){update_show($(this));});
 
        $('.perm_filter[value=none]').each(function(){this.checked = false; update_show($(this));});
 
    });
 
</script>
 
</%def>
kallithea/templates/changelog/changelog.html
Show inline comments
 
## -*- coding: utf-8 -*-
 

	
 
<%inherit file="/base/base.html"/>
 

	
 
<%namespace name="changelog_table" file="changelog_table.html"/>
 

	
 
<%block name="title">
 
    ${_('%s Changelog') % c.repo_name}
 
    %if c.changelog_for_path:
 
      /${c.changelog_for_path}
 
    %endif
 
</%block>
 

	
 
<%def name="breadcrumbs_links()">
 
    <% size = c.size if c.size <= c.total_cs else c.total_cs %>
 
    ${_('Changelog')}
 
    %if c.changelog_for_path:
 
     - /${c.changelog_for_path}
 
    %endif
 
    %if c.revision:
 
    @ ${h.short_id(c.first_revision.raw_id)}
 
    %endif
 
    - ${ungettext('showing %d out of %d revision', 'showing %d out of %d revisions', size) % (size, c.total_cs)}
 
</%def>
 

	
 
<%block name="header_menu">
 
    ${self.menu('repositories')}
 
</%block>
 

	
 
<%def name="main()">
 
${self.repo_context_bar('changelog', c.first_revision.raw_id if c.first_revision else None)}
 
<div class="panel panel-primary">
 
    <div class="panel-heading clearfix">
 
        ${self.breadcrumbs()}
 
    </div>
 
    <div class="panel-body changelog-panel">
 
        %if c.cs_pagination:
 
                <div class="changelog-heading clearfix" style="${'display:none' if c.changelog_for_path else ''}">
 
                    <div class="pull-left">
 
                        ${h.form(h.url.current(),method='get',class_="form-inline")}
 
                            ${h.submit(None,_('Show'),id='set_size_submit',class_="btn btn-default btn-sm")}
 
                            ${h.text('size',size=3,value=c.size,class_='form-control')}
 
                            ${_('revisions')}
 
                            %if c.branch_name:
 
                                ${h.hidden('branch', c.branch_name)}
 
                            %endif
 
                            <a href="#" class="btn btn-default btn-sm" id="rev_range_clear" style="display:none">${_('Clear selection')}</a>
 
                        ${h.end_form()}
 
                    </div>
 
                    <div class="pull-right">
 
                        <a href="#" class="btn btn-default btn-sm" id="rev_range_container" style="display:none"></a>
 
                        %if c.revision:
 
                            <a class="btn btn-default btn-sm" href="${h.url('changelog_home', repo_name=c.repo_name)}">
 
                                ${_('Go to tip of repository')}
 
                            </a>
 
                        %endif
 
                        %if c.db_repo.fork:
 
                            <a id="compare_fork"
 
                               title="${_('Compare fork with %s' % c.db_repo.fork.repo_name)}"
 
                               href="${h.url('compare_url',repo_name=c.db_repo.fork.repo_name,org_ref_type=c.db_repo.landing_rev[0],org_ref_name=c.db_repo.landing_rev[1],other_repo=c.repo_name,other_ref_type='branch' if request.GET.get('branch') else c.db_repo.landing_rev[0],other_ref_name=request.GET.get('branch') or c.db_repo.landing_rev[1], merge=1)}"
 
                               class="btn btn-default btn-sm"><i class="icon-git-compare"></i>${_('Compare fork with parent repository (%s)' % c.db_repo.fork.repo_name)}</a>
 
                        %endif
 
                        ## text and href of open_new_pr is controlled from javascript
 
                        <a id="open_new_pr" class="btn btn-default btn-sm"></a>
 
                        ${_("Branch filter:")} ${h.select('branch_filter',c.branch_name,c.branch_filters)}
 
                    </div>
 
                </div>
 

	
 
                <div id="graph_nodes">
 
                    <canvas id="graph_canvas" style="width:0"></canvas>
 
                </div>
 

	
 
                <div id="graph_content" style="${'margin: 0px' if c.changelog_for_path else ''}">
 
                  ${changelog_table.changelog(c.repo_name, c.cs_pagination, c.cs_statuses, c.cs_comments,
 
                                              show_checkbox=not c.changelog_for_path,
 
                                              show_branch=not c.branch_name,
 
                                              resize_js='graph.render(jsdata)')}
 
                  <input type="checkbox" id="singlerange" style="display:none"/>
 
                </div>
 

	
 
                ${c.cs_pagination.pager()}
 

	
 
        <script src="${h.url('/js/graph.js', ver=c.kallithea_version)}"></script>
 
        <script>'use strict';
 
            var jsdata = ${h.js(c.jsdata)};
 
            var graph = new BranchRenderer('graph_canvas', 'graph_content', 'chg_');
 

	
 
            $(document).ready(function(){
 
                var $checkboxes = $('.changeset_range');
 

	
 
                pyroutes.register('changeset_home', ${h.js(h.url('changeset_home', repo_name='%(repo_name)s', revision='%(revision)s'))}, ['repo_name', 'revision']);
 

	
 
                var checkbox_checker = function(e) {
 
                function checkbox_checker(e) {
 
                    var $checked_checkboxes = $checkboxes.filter(':checked');
 
                    var $singlerange = $('#singlerange');
 

	
 
                    $('#rev_range_container').hide();
 
                    $checkboxes.show();
 
                    $singlerange.show();
 

	
 
                    if ($checked_checkboxes.length > 0) {
 
                        $checked_checkboxes.first().parent('td').append($singlerange);
 
                        var singlerange = $singlerange.prop('checked');
 
                        var rev_end = $checked_checkboxes.first().prop('name');
 
                        if ($checked_checkboxes.length > 1 || singlerange) {
 
                            var rev_start = $checked_checkboxes.last().prop('name');
 
                            $('#rev_range_container').prop('href',
 
                                pyroutes.url('changeset_home', {'repo_name': ${h.js(c.repo_name)},
 
                                                                'revision': rev_start + '...' + rev_end}));
 
                            $('#rev_range_container').html(
 
                                 _TM['Show Selected Changesets {0} &rarr; {1}'].format(rev_start.substr(0, 12), rev_end.substr(0, 12)));
 
                            $('#rev_range_container').show();
 
                            $('#open_new_pr').prop('href', pyroutes.url('pullrequest_home',
 
                                                                        {'repo_name': ${h.js(c.repo_name)},
 
                                                                         'rev_start': rev_start,
 
                                                                         'rev_end': rev_end}));
 
                            $('#open_new_pr').html(_TM['Open New Pull Request for {0} &rarr; {1}'].format(rev_start.substr(0, 12), rev_end.substr(0, 12)));
 
                        } else {
 
                            $('#open_new_pr').prop('href', pyroutes.url('pullrequest_home',
 
                                                                        {'repo_name': ${h.js(c.repo_name)},
 
                                                                         'rev_end': rev_end}));
 
                            $('#open_new_pr').html(_TM['Open New Pull Request from {0}'].format(rev_end.substr(0, 12)));
 
                        }
 
                        $('#rev_range_clear').show();
 
                        $('#compare_fork').hide();
 

	
 
                        var disabled = true;
 
                        $checkboxes.each(function(){
 
                            var $this = $(this);
 
                            if (disabled) {
 
                                if ($this.prop('checked')) {
 
                                    $this.closest('tr').removeClass('out-of-range');
 
                                    disabled = singlerange;
 
                                } else {
 
                                    $this.closest('tr').addClass('out-of-range');
 
                                }
 
                            } else {
 
                                $this.closest('tr').removeClass('out-of-range');
 
                                disabled = $this.prop('checked');
 
                            }
 
                        });
 

	
 
                        if ($checked_checkboxes.length + (singlerange ? 1 : 0) >= 2) {
 
                            $checkboxes.hide();
 
                            $checked_checkboxes.show();
 
                            if (!singlerange)
 
                                $singlerange.hide();
 
                        }
 
                    } else {
 
                        $('#singlerange').hide().prop('checked', false);
 
                        $('#rev_range_clear').hide();
 
                        %if c.revision:
 
                            $('#open_new_pr').prop('href', pyroutes.url('pullrequest_home',
 
                                                                        {'repo_name': ${h.js(c.repo_name)},
 
                                                                         'rev_end':${h.js(c.first_revision.raw_id)}}));
 
                            $('#open_new_pr').html(_TM['Open New Pull Request from {0}'].format(${h.jshtml(c.revision)}));
 
                        %else:
 
                            $('#open_new_pr').prop('href', pyroutes.url('pullrequest_home',
 
                                                                        {'repo_name': ${h.js(c.repo_name)},
 
                                                                        'branch':${h.js(c.first_revision.branch)}}));
 
                            $('#open_new_pr').html(_TM['Open New Pull Request from {0}'].format(${h.jshtml(c.first_revision.branch)}));
 
                        %endif
 
                        $('#compare_fork').show();
 
                        $checkboxes.closest('tr').removeClass('out-of-range');
 
                    }
 
                };
 
                }
 
                checkbox_checker();
 
                $checkboxes.click(function() {
 
                    checkbox_checker();
 
                    graph.render(jsdata);
 
                });
 
                $('#singlerange').click(checkbox_checker);
 

	
 
                $('#rev_range_clear').click(function(e){
 
                    $checkboxes.prop('checked', false);
 
                    checkbox_checker();
 
                    graph.render(jsdata);
 
                });
 

	
 
                var $msgs = $('.message');
 
                // get first element height
 
                var el = $('#graph_content tr')[0];
 
                var row_h = el.clientHeight;
 
                $msgs.each(function() {
 
                    var m = this;
 

	
 
                    var h = m.clientHeight;
 
                    if(h > row_h){
 
                        var offset = row_h - (h+12);
 
                        $(m.nextElementSibling).css('display', 'block');
 
                        $(m.nextElementSibling).css('margin-top', offset+'px');
 
                    }
 
                });
 

	
 
                // change branch filter
 
                $("#branch_filter").select2({
 
                    dropdownAutoWidth: true,
 
                    maxResults: 50,
 
                    sortResults: branchSort
 
                    });
 

	
 
                $("#branch_filter").change(function(e){
 
                    var selected_branch = e.currentTarget.options[e.currentTarget.selectedIndex].value;
 
                    if(selected_branch != ''){
 
                        window.location = pyroutes.url('changelog_home', {'repo_name': ${h.js(c.repo_name)},
 
                                                                          'branch': selected_branch});
 
                    }else{
 
                        window.location = pyroutes.url('changelog_home', {'repo_name': ${h.js(c.repo_name)}});
 
                    }
 
                    $("#changelog").hide();
 
                });
 

	
 
                graph.render(jsdata);
 
            });
 

	
 
            $(window).resize(function(){
 
                graph.render(jsdata);
 
            });
 
        </script>
 
        %else:
 
            ${_('There are no changes yet')}
 
        %endif
 
    </div>
 
</div>
 
</%def>
kallithea/templates/changeset/diff_block.html
Show inline comments
 
## -*- coding: utf-8 -*-
 

	
 
<%def name="diff_block(a_repo_name, a_ref_type, a_ref_name, a_rev,
 
                       cs_repo_name, cs_ref_name, cs_ref_type, cs_rev,
 
                       file_diff_data)">
 
<div class="diff-collapse">
 
    <button data-target="${'diff-container-%s' % (id(file_diff_data))}" class="diff-collapse-button btn btn-link btn-sm">&uarr; ${_('Collapse Diff')} &uarr;</button>
 
</div>
 
%for id_fid, url_fid, op, a_filename, cs_filename, diff, stats in file_diff_data:
 
    ${diff_block_diffblock(id_fid, url_fid, op, diff,
 
        a_repo_name, a_rev, a_ref_type, a_ref_name, a_filename,
 
        cs_repo_name, cs_rev, cs_ref_type, cs_ref_name, cs_filename,
 
        'diff-container-%s' % id(file_diff_data))}
 
%endfor
 
</%def>
 

	
 
<%def name="diff_block_diffblock(id_fid, url_fid, op, diff,
 
    a_repo_name, a_rev, a_ref_type, a_ref_name, a_filename,
 
    cs_repo_name, cs_rev, cs_ref_type, cs_ref_name, cs_filename, cls)"
 
>
 
    <div id="${id_fid}_target"></div>
 
    <div id="${id_fid}" class="panel panel-default ${cls}">
 
        <div class="panel-heading clearfix">
 
                <div class="pull-left">
 
                    ${cs_filename}
 
                </div>
 
                <div class="pull-left diff-actions">
 
                  <span>
 
                    %if op == 'A':
 
                      <span class="no-file" data-toggle="tooltip" title="${_('No file before')}">
 
                        <i class="icon-minus-circled"></i></span>
 
                    %else:
 
                      <a href="${h.url('files_home', repo_name=a_repo_name, f_path=a_filename, revision=a_rev)}" data-toggle="tooltip" title="${_('File before')}">
 
                        <i class="icon-doc"></i></a>
 
                    %endif
 

	
 
                    %if op == 'A':
 
                      <span class="arrow" data-toggle="tooltip" title="${_('Added')}">&#10142;</span>
 
                    %elif op == 'M':
 
                      <span class="arrow" data-toggle="tooltip" title="${_('Modified')}">&#10142;</span>
 
                    %elif op == 'D':
 
                      <span class="arrow" data-toggle="tooltip" title="${_('Deleted')}">&#10142;</span>
 
                    %elif op == 'R':
 
                      <span class="arrow" data-toggle="tooltip" title="${_('Renamed')}">&#10142;</span>
 
                    %elif op is None:
 
                      <span class="arrow" data-toggle="tooltip" title="${_('No change')}">&#10142;</span>
 
                    %else:
 
                      <span class="arrow" data-toggle="tooltip" title="${_('Unknown operation: %r') % op}">&#10142;</span>
 
                    %endif
 

	
 
                    %if op == 'D':
 
                      <span class="no-file" data-toggle="tooltip" title="${_('No file after')}">
 
                        <i class="icon-minus-circled"></i></span>
 
                    %else:
 
                      <a href="${h.url('files_home', repo_name=cs_repo_name, f_path=cs_filename, revision=cs_rev)}" data-toggle="tooltip" title="${_('File after')}">
 
                        <i class="icon-doc"></i></a>
 
                    %endif
 
                  </span>
 

	
 
                  <a href="${h.url('files_diff_home',repo_name=cs_repo_name,f_path=cs_filename,diff2=cs_rev,diff1=a_rev,diff='diff',fulldiff=1)}" data-toggle="tooltip" title="${_('Show full diff for this file')}">
 
                      <i class="icon-file-code"></i></a>
 
                  <a href="${h.url('files_diff_2way_home',repo_name=cs_repo_name,f_path=cs_filename,diff2=cs_rev,diff1=a_rev,diff='diff',fulldiff=1)}" data-toggle="tooltip" title="${_('Show full side-by-side diff for this file')}">
 
                      <i class="icon-docs"></i></a>
 
                  <a href="${h.url('files_diff_home',repo_name=cs_repo_name,f_path=cs_filename,diff2=cs_rev,diff1=a_rev,diff='raw')}" data-toggle="tooltip" title="${_('Raw diff')}">
 
                      <i class="icon-diff"></i></a>
 
                  <a href="${h.url('files_diff_home',repo_name=cs_repo_name,f_path=cs_filename,diff2=cs_rev,diff1=a_rev,diff='download')}" data-toggle="tooltip" title="${_('Download diff')}">
 
                      <i class="icon-floppy"></i></a>
 
                  ${c.ignorews_url(request.GET, url_fid)}
 
                  ${c.context_url(request.GET, url_fid)}
 
                </div>
 
                <div class="pull-right">
 
                    ${_('Show inline comments')}
 
                    ${h.checkbox('checkbox-show-inline-' + id_fid, checked="checked",class_="show-inline-comments",**{'data-id_for':id_fid})}
 
                </div>
 
        </div>
 
        <div class="no-padding panel-body" data-f_path="${cs_filename}">
 
            ${diff|n}
 
            %if op and cs_filename.rsplit('.')[-1] in ['png', 'gif', 'jpg', 'bmp']:
 
              <div class="btn btn-image-diff-show">Show images</div>
 
              %if op == 'M':
 
                <div id="${id_fid}_image-diff" class="btn btn-image-diff-swap" style="display:none">Press to swap images</div>
 
              %endif
 
              <div>
 
                %if op in 'DM':
 
                  <img id="${id_fid}_image-diff-img-a" class="img-diff img-diff-swapable" style="display:none"
 
                      realsrc="${h.url('files_raw_home',repo_name=a_repo_name,revision=a_rev,f_path=a_filename)}" />
 
                %endif
 
                %if op in 'AM':
 
                  <img id="${id_fid}_image-diff-img-b" class="img-diff img-diff-swapable" style="display:none"
 
                      realsrc="${h.url('files_raw_home',repo_name=cs_repo_name,revision=cs_rev,f_path=cs_filename)}" />
 
                %endif
 
              </div>
 
            %endif
 
        </div>
 
    </div>
 
</%def>
 

	
 
<%def name="diff_block_js()">
 
<script>'use strict';
 
$(document).ready(function(){
 
    $('.btn-image-diff-show').click(function(e){
 
        $('.btn-image-diff-show').hide();
 
        $('.btn-image-diff-swap').show();
 
        $('.img-diff-swapable')
 
            .each(function(i,e){
 
                    $(e).prop('src', $(e).attr('realsrc'));
 
                })
 
            .show();
 
        });
 

	
 
    $('.btn-image-diff-swap').mousedown(function(e){
 
        $('#'+e.currentTarget.id+'-img-a.img-diff-swapable')
 
          .before($('#'+e.currentTarget.id+'-img-b.img-diff-swapable'));
 
    });
 
    var reset = function(e){
 
    function reset(e){
 
        $('#'+e.currentTarget.id+'-img-a.img-diff-swapable')
 
          .after($('#'+e.currentTarget.id+'-img-b.img-diff-swapable'));
 
    };
 
    }
 
    $('.btn-image-diff-swap').mouseup(reset);
 
    $('.btn-image-diff-swap').mouseleave(reset);
 

	
 
    $('.diff-collapse-button').click(function(e) {
 
        $('.diff_block').toggleClass('hidden');
 
        var $button = $(e.currentTarget);
 
        var $target = $('.' + $button.data('target'));
 
        if($target.hasClass('hidden')){
 
            $target.removeClass('hidden');
 
            $button.html("&uarr; {0} &uarr;".format(_TM['Collapse Diff']));
 
        }
 
        else if(!$target.hasClass('hidden')){
 
            $target.addClass('hidden');
 
            $button.html("&darr; {0} &darr;".format(_TM['Expand Diff']));
 
        }
 
    });
 
    $('.show-inline-comments').change(function(e){
 
        var target = e.currentTarget;
 
        if(target == null){
 
            target = this;
 
        }
 
        var boxid = $(target).data('id_for');
 
        if(target.checked){
 
            $('#{0} .inline-comments'.format(boxid)).show();
 
        }else{
 
            $('#{0} .inline-comments'.format(boxid)).hide();
 
        }
 
    });
 
});
 
</script>
 
</%def>
kallithea/templates/compare/compare_diff.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
<%inherit file="/base/base.html"/>
 

	
 
<%block name="title">
 
    %if c.compare_home:
 
        ${_('%s Compare') % c.repo_name}
 
    %else:
 
        ${_('%s Compare') % c.repo_name} - ${'%s@%s' % (c.a_repo.repo_name, c.a_ref_name)} &gt; ${'%s@%s' % (c.cs_repo.repo_name, c.cs_ref_name)}
 
    %endif
 
</%block>
 

	
 
<%def name="breadcrumbs_links()">
 
  ${_('Compare Revisions')}
 
</%def>
 

	
 
<%block name="header_menu">
 
    ${self.menu('repositories')}
 
</%block>
 

	
 
<%def name="main()">
 
${self.repo_context_bar('changelog')}
 
<div class="panel panel-primary">
 
    <div class="panel-heading clearfix">
 
        ${self.breadcrumbs()}
 
    </div>
 
    <div class="panel-body">
 
      <div class="panel panel-default">
 
        <div id="body" class="panel-heading">
 
            <div class="compare-revision-selector">
 
                ## divs are "inline-block" and cannot have whitespace between them.
 
                <span>
 
                    ${h.hidden('compare_org')}
 
                </span><span>
 
                    <i class="icon-right"></i>
 
                </span><span>
 
                    ${h.hidden('compare_other')}
 
                </span><span>
 
                    %if not c.compare_home:
 
                        <a class="btn btn-default btn-sm" href="${c.swap_url}"><i class="icon-arrows-cw"></i>${_('Swap')}</a>
 
                    %endif
 
                    <button type="button" id="compare_revs" class="btn btn-default btn-sm"><i class="icon-git-compare"></i>${_('Compare Revisions')}</button>
 
                </span>
 
            </div>
 
        </div>
 

	
 
    %if c.compare_home:
 
        <div id="changeset_compare_view_content" class="panel-body">
 
         <h4 class="text-muted">${_('Compare revisions, branches, bookmarks, or tags.')}</h4>
 
        </div>
 
    %else:
 
        <div id="changeset_compare_view_content" class="panel-body">
 
                ##CS
 
                <h5>${ungettext('Showing %s commit','Showing %s commits', len(c.cs_ranges)) % len(c.cs_ranges)}</h5>
 
                <%include file="compare_cs.html" />
 

	
 
                ## FILES
 
                <h5>
 
                % if c.limited_diff:
 
                    ${ungettext('%s file changed', '%s files changed', len(c.file_diff_data)) % len(c.file_diff_data)}:
 
                % else:
 
                    ${ungettext('%s file changed with %s insertions and %s deletions','%s files changed with %s insertions and %s deletions', len(c.file_diff_data)) % (len(c.file_diff_data),c.lines_added,c.lines_deleted)}:
 
                %endif
 

	
 
                ${c.ignorews_url(request.GET)}
 
                ${c.context_url(request.GET)}
 
                </h5>
 
                <div class="cs_files">
 
                  %if not c.file_diff_data:
 
                     <span class="text-muted">${_('No files')}</span>
 
                  %endif
 
                  %for fid, url_fid, op, a_path, path, diff, stats in c.file_diff_data:
 
                    <div class="cs_${op} clearfix">
 
                      <span class="node">
 
                          <i class="icon-diff-${op}"></i>
 
                          ${h.link_to(path, '#%s' % fid)}
 
                      </span>
 
                      <div class="changes">${h.fancy_file_stats(stats)}</div>
 
                    </div>
 
                  %endfor
 
                  %if c.limited_diff:
 
                    <h5>${_('Changeset was too big and was cut off...')} <a href="${h.url.current(fulldiff=1, **request.GET.mixed())}">${_('Show full diff anyway')}</a></h5>
 
                  %endif
 
                </div>
 
        </div>
 
      </div>
 
    %endif
 

	
 
    %if not c.compare_home:
 
        ## diff block
 
        <%namespace name="diff_block" file="/changeset/diff_block.html"/>
 
        ${diff_block.diff_block_js()}
 
        ${diff_block.diff_block(c.a_repo.repo_name, c.a_ref_type, c.a_ref_name, c.a_rev,
 
                                c.cs_repo.repo_name, c.cs_ref_type, c.cs_ref_name, c.cs_rev, c.file_diff_data)}
 
        % if c.limited_diff:
 
          <h4>${_('Changeset was too big and was cut off...')} <a href="${h.url.current(fulldiff=1, **request.GET.mixed())}">${_('Show full diff')}</a></h4>
 
        % endif
 
    %endif
 
    </div>
 

	
 
</div>
 
    <script>'use strict';
 

	
 
   $(document).ready(function(){
 
    var cache = {};
 

	
 
    function make_revision_dropdown(css_selector, repo_name, ref_name, cache_key) {
 
      $(css_selector).select2({
 
        placeholder: '{0}@{1}'.format(repo_name, ref_name || ${h.jshtml(_('Select changeset'))}),
 
        formatSelection: function(obj){
 
            return '{0}@{1}'.format(repo_name, obj.text).html_escape();
 
        },
 
        dropdownAutoWidth: true,
 
        maxResults: 50,
 
        query: function(query){
 
          var key = cache_key;
 
          var cached = cache[key] ;
 
          if(cached) {
 
            var data = {results: []};
 
            var queryLower = query.term.toLowerCase();
 
            //filter results
 
            $.each(cached.results, function(){
 
                var section = this.text;
 
                var children = [];
 
                $.each(this.children, function(){
 
                    if(children.length < 50 ?
 
                       ((queryLower.length == 0) || (this.text.toLowerCase().indexOf(queryLower) >= 0)) :
 
                       ((queryLower.length != 0) && (this.text.toLowerCase().indexOf(queryLower) == 0))) {
 
                        children.push(this);
 
                    }
 
                });
 
                children = branchSort(children, undefined, query)
 
                data.results.push({'text': section, 'children': children});
 
            });
 
            //push the typed in changeset
 
            data.results.push({'text':_TM['Specify changeset'],
 
                               'children': [{'id': query.term, 'text': query.term, 'type': 'rev'}]});
 
            query.callback(data);
 
          }else{
 
              $.ajax({
 
                url: pyroutes.url('repo_refs_data', {'repo_name': repo_name}),
 
                data: {},
 
                dataType: 'json',
 
                type: 'GET',
 
                success: function(data) {
 
                  cache[key] = data;
 
                  query.callback(data);
 
                }
 
              });
 
          }
 
        }
 
    });
 
    }
 

	
 
    make_revision_dropdown("#compare_org",   ${h.js(c.a_repo.repo_name)},  ${h.js(c.a_ref_name)},  'cache');
 
    make_revision_dropdown("#compare_other", ${h.js(c.cs_repo.repo_name)}, ${h.js(c.cs_ref_name)}, 'cache2');
 

	
 
    var values_changed = function() {
 
    function values_changed() {
 
        var values = $('#compare_org').select2('data') && $('#compare_other').select2('data');
 
        if (values) {
 
             $('#compare_revs').removeClass("disabled");
 
             // TODO: the swap button ... if any
 
        } else {
 
             $('#compare_revs').addClass("disabled");
 
             // TODO: the swap button ... if any
 
        }
 
    }
 
    values_changed();
 
    $('#compare_org').change(values_changed);
 
    $('#compare_other').change(values_changed);
 
    $('#compare_revs').on('click', function(e){
 
        var org = $('#compare_org').select2('data');
 
        var other = $('#compare_other').select2('data');
 
        if (!org || !other) {
 
            return;
 
        }
 

	
 
        var compare_url = ${h.js(h.url('compare_url',repo_name=c.repo_name,org_ref_type='__other_ref_type__',org_ref_name='__org__',other_ref_type='__org_ref_type__',other_ref_name='__other__', other_repo=c.cs_repo.repo_name))};
 
        var u = compare_url.replace('__other_ref_type__',org.type)
 
                           .replace('__org__',org.text)
 
                           .replace('__org_ref_type__',other.type)
 
                           .replace('__other__',other.text);
 
        window.location = u;
 
    });
 
   });
 
    </script>
 
</%def>
kallithea/templates/journal/journal.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
<%inherit file="/base/base.html"/>
 

	
 
<%block name="title">
 
    ${_('Journal')}
 
</%block>
 

	
 
<%def name="breadcrumbs_links()">
 
    <form id="filter_form" class="pull-left form-inline input-group-sm">
 
        <input class="form-control q_filter_box ${'' if c.search_term else 'initial'}" id="j_filter" size="15" type="text" name="filter" value="${c.search_term or _('journal filter...')}"/>
 
        <span data-toggle="popover" data-content="${h.journal_filter_help()}">?</span>
 
        <input type='submit' value="${_('Filter')}" class="btn btn-default btn-xs"/>
 
        ${_('Journal')} - ${ungettext('%s Entry', '%s Entries', c.journal_pager.item_count) % (c.journal_pager.item_count)}
 
    </form>
 
</%def>
 

	
 
<%block name="header_menu">
 
    ${self.menu('journal')}
 
</%block>
 

	
 
<%block name="head_extra">
 
  <link href="${h.url('journal_atom', api_key=request.authuser.api_key)}" rel="alternate" title="${_('ATOM journal feed')}" type="application/atom+xml" />
 
  <link href="${h.url('journal_rss', api_key=request.authuser.api_key)}" rel="alternate" title="${_('RSS journal feed')}" type="application/rss+xml" />
 
</%block>
 

	
 
<%def name="main()">
 
    <div class="panel panel-primary">
 
        <div class="panel-heading clearfix">
 
            <div class="pull-left">
 
                ${self.breadcrumbs()}
 
            </div>
 
            <div class="pull-right panel-title">
 
                <a href="${h.url('my_account_watched')}"><i class="icon-eye"></i>${_('Watched Repositories')}</a>
 
                <a href="${h.url('my_account_repos')}"><i class="icon-database"></i>${_('My Repositories')}</a>
 
                <a id="refresh" href="${h.url('journal')}"><i class="icon-arrows-cw"></i></a>
 
                <a href="${h.url('journal_atom', api_key=request.authuser.api_key)}"><i class="icon-rss-squared"></i></a>
 
            </div>
 
        </div>
 
        <div id="journal" class="panel-body">
 
            <%include file='journal_data.html'/>
 
        </div>
 
    </div>
 

	
 
<script>'use strict';
 

	
 
    $('#j_filter').click(function(){
 
        var $jfilter = $('#j_filter');
 
        if($jfilter.hasClass('initial')){
 
            $jfilter.val('');
 
        }
 
    });
 
    var fix_j_filter_width = function(len){
 
    function fix_j_filter_width(len){
 
        $('#j_filter').css('width', Math.max(80, len*6.50)+'px');
 
    };
 
    }
 
    $('#j_filter').keyup(function(){
 
        fix_j_filter_width($('#j_filter').val().length);
 
    });
 
    $('#filter_form').submit(function(e){
 
        e.preventDefault();
 
        var val = $('#j_filter').val();
 
        window.location = ${h.js(url.current(filter='__FILTER__'))}.replace('__FILTER__',val);
 
    });
 
    fix_j_filter_width($('#j_filter').val().length);
 

	
 
    $('#refresh').click(function(e){
 
        asynchtml(${h.js(h.url.current(filter=c.search_term))}, $("#journal"), function(){
 
            show_more_event();
 
            tooltip_activate();
 
            });
 
        e.preventDefault();
 
    });
 

	
 
</script>
 

	
 
<script>'use strict';
 
    $(document).ready(function(){
 
        var $journal = $('#journal');
 
        $journal.on('click','.pager_link',function(e){
 
            asynchtml(e.target.href, $journal, function(){
 
                show_more_event();
 
                tooltip_activate();
 
            });
 
            e.preventDefault();
 
        });
 
        $('#journal').on('click','.show_more',function(e){
 
            var el = e.target;
 
            $('#'+el.id.substring(1)).show();
 
            $(el.parentNode).hide();
 
        });
 
    });
 
</script>
 
</%def>
kallithea/templates/pullrequests/pullrequest.html
Show inline comments
 
<%inherit file="/base/base.html"/>
 

	
 
<%block name="title">
 
    ${c.repo_name} ${_('New Pull Request')}
 
</%block>
 

	
 
<%def name="breadcrumbs_links()">
 
    ${_('New Pull Request')}
 
</%def>
 

	
 
<%block name="header_menu">
 
    ${self.menu('repositories')}
 
</%block>
 

	
 
<%def name="main()">
 
${self.repo_context_bar('showpullrequest')}
 
<div class="panel panel-primary">
 
    <div class="panel-heading clearfix">
 
        ${self.breadcrumbs()}
 
    </div>
 

	
 
    ${h.form(url('pullrequest', repo_name=c.repo_name), method='post', id='pull_request_form')}
 
    <div class="form panel-body">
 
        <div class="settings clearfix">
 
            <div class="form-group">
 
                <label class="control-label" for="pullrequest_title">${_('Title')}:</label>
 
                <div>
 
                    ${h.text('pullrequest_title',class_='form-control',placeholder=_('Summarize the changes - or leave empty'))}
 
                </div>
 
            </div>
 

	
 
            <div class="form-group">
 
                <label class="control-label" for="pullrequest_desc">${_('Description')}:</label>
 
                <div>
 
                    ${h.textarea('pullrequest_desc',class_='form-control',placeholder=_('Write a short description on this pull request'))}
 
                </div>
 
            </div>
 

	
 
            <div class="form-group">
 
                <label class="control-label">${_('Changeset flow')}:</label>
 
                <div class="clearfix">
 
                    ##ORG
 
                    <div>
 
                        <div>
 
                            <div>
 
                            <b>${_('Origin repository')}:</b> <span id="org_repo_desc">${c.db_repo.description.split('\n')[0]}</span>
 
                            </div>
 
                            <div>
 
                            ${h.select('org_repo','',c.cs_repos,class_='refs')}:${h.select('org_ref',c.default_cs_ref,c.cs_refs,class_='refs')}
 
                            </div>
 
                            <div>
 
                            <b>${_('Revision')}:</b> <span id="org_rev_span">-</span>
 
                            </div>
 
                        </div>
 
                    </div>
 

	
 
                    ##OTHER, most Probably the PARENT OF THIS FORK
 
                    <div>
 
                        <div>
 
                            ## filled with JS
 
                            <div>
 
                            <b>${_('Destination repository')}:</b> <span id="other_repo_desc">${c.a_repo.description.split('\n')[0]}</span>
 
                            </div>
 
                            <div>
 
                            ${h.select('other_repo',c.a_repo.repo_name,c.a_repos,class_='refs')}:${h.select('other_ref',c.default_a_ref,c.a_refs,class_='refs')}
 
                            </div>
 
                            <div>
 
                            <b>${_('Revision')}:</b> <span id="other_rev_span">-</span>
 
                            </div>
 
                        </div>
 
                    </div>
 
                </div>
 
            </div>
 

	
 
            <div class="form-group">
 
                <div class="buttons">
 
                    ${h.submit('save',_('Create Pull Request'),class_="btn btn-default")}
 
                    ${h.reset('reset',_('Reset'),class_="btn btn-default")}
 
                </div>
 
            </div>
 
        </div>
 

	
 
        <div>
 
           <h4>${_('Changesets')}</h4>
 
           ## overview pulled by ajax
 
           <div id="pull_request_overview"></div>
 
        </div>
 
    </div>
 

	
 
    ${h.end_form()}
 

	
 
</div>
 

	
 
<script src="${h.url('/js/graph.js', ver=c.kallithea_version)}"></script>
 
<script>'use strict';
 
  pyroutes.register('pullrequest_repo_info', ${h.js(url('pullrequest_repo_info',repo_name='%(repo_name)s'))}, ['repo_name']);
 

	
 
  var pendingajax = undefined;
 
  var otherrepoChanged = function(){
 
  function otherrepoChanged(){
 
      var $other_ref = $('#other_ref');
 
      $other_ref.prop('disabled', true);
 
      var repo_name = $('#other_repo').val();
 
      if (pendingajax) {
 
          pendingajax.abort();
 
          pendingajax = undefined;
 
      }
 
      pendingajax = ajaxGET(pyroutes.url('pullrequest_repo_info', {"repo_name": repo_name}),
 
          function(data){
 
              pendingajax = undefined;
 
              $('#other_repo_desc').html(data.description);
 

	
 
              // replace options of other_ref with the ones for the current other_repo
 
              $other_ref.empty();
 
              for(var i = 0; i < data.refs.length; i++)
 
              {
 
                var $optgroup = $('<optgroup/>').prop('label', data.refs[i][1]);
 
                var options = data.refs[i][0];
 
                var length = options.length;
 
                for(var j = 0; j < length; j++)
 
                {
 
                  $optgroup.append($('<'+'option/>').text(options[j][1]).val(options[j][0]));
 
                }
 
                $other_ref.append($optgroup);
 
              }
 
              $other_ref.val(data.selected_ref);
 

	
 
              // re-populate the select2 thingy
 
              $("#other_ref").select2({
 
                  dropdownAutoWidth: true
 
              });
 

	
 
              $other_ref.prop('disabled', false);
 
              loadPreview();
 
          });
 
  };
 
  }
 

	
 
  var loadPreview = function(){
 
  function loadPreview(){
 
      //url template
 
      var url = ${h.js(h.url('compare_url',
 
                         repo_name='__other_repo__',
 
                         org_ref_type='rev',
 
                         org_ref_name='__other_ref_name__',
 
                         other_repo='__org_repo__',
 
                         other_ref_type='rev',
 
                         other_ref_name='__org_ref_name__',
 
                         is_ajax_preview=True,
 
                         merge=True,
 
                         ))};
 
      var org_repo = $('#pull_request_form #org_repo').val();
 
      var org_ref = $('#pull_request_form #org_ref').val().split(':');
 
      ## TODO: make nice link like link_to_ref() do
 
      $('#org_rev_span').html(org_ref[2].substr(0,12));
 

	
 
      var other_repo = $('#pull_request_form #other_repo').val();
 
      var other_ref = $('#pull_request_form #other_ref').val().split(':');
 
      $('#other_rev_span').html(other_ref[2].substr(0,12));
 

	
 
      var rev_data = {
 
          '__org_repo__': org_repo,
 
          '__org_ref_name__': org_ref[2],
 
          '__other_repo__': other_repo,
 
          '__other_ref_name__': other_ref[2]
 
      }; // gather the org/other ref and repo here
 

	
 
      for (let k in rev_data){
 
          url = url.replace(k,rev_data[k]);
 
      }
 

	
 
      if (pendingajax) {
 
          pendingajax.abort();
 
          pendingajax = undefined;
 
      }
 
      pendingajax = asynchtml(url, $('#pull_request_overview'), function(o){
 
          pendingajax = undefined;
 
      });
 
  }
 

	
 
  $(document).ready(function(){
 
      $("#org_repo").select2({
 
          dropdownAutoWidth: true
 
      });
 
      ## (org_repo can't change)
 

	
 
      $("#org_ref").select2({
 
          dropdownAutoWidth: true,
 
          maxResults: 50,
 
          sortResults: branchSort
 
      });
 
      $("#org_ref").on("change", function(e){
 
          loadPreview();
 
      });
 

	
 
      $("#other_repo").select2({
 
          dropdownAutoWidth: true
 
      });
 
      $("#other_repo").on("change", function(e){
 
          otherrepoChanged();
 
      });
 

	
 
      $("#other_ref").select2({
 
          dropdownAutoWidth: true,
 
          maxResults: 50,
 
          sortResults: branchSort
 
      });
 
      $("#other_ref").on("change", function(e){
 
          loadPreview();
 
      });
 

	
 
      //lazy load overview after 0.5s
 
      setTimeout(loadPreview, 500);
 
  });
 

	
 
</script>
 

	
 
</%def>
0 comments (0 inline, 0 general)