code
stringlengths
1
2.08M
language
stringclasses
1 value
/* SelectFilter2 - Turns a multiple-select box into a filter interface. Different than SelectFilter because this is coupled to the admin framework. Requires core.js, SelectBox.js and addevent.js. */ function findForm(node) { // returns the node of the form containing the given node if (node.tagName.toLowerCase() != 'form') { return findForm(node.parentNode); } return node; } var SelectFilter = { init: function(field_id, field_name, is_stacked, admin_media_prefix) { if (field_id.match(/__prefix__/)){ // Don't intialize on empty forms. return; } var from_box = document.getElementById(field_id); from_box.id += '_from'; // change its ID from_box.className = 'filtered'; var ps = from_box.parentNode.getElementsByTagName('p'); for (var i=0; i<ps.length; i++) { if (ps[i].className.indexOf("info") != -1) { // Remove <p class="info">, because it just gets in the way. from_box.parentNode.removeChild(ps[i]); } else if (ps[i].className.indexOf("help") != -1) { // Move help text up to the top so it isn't below the select // boxes or wrapped off on the side to the right of the add // button: from_box.parentNode.insertBefore(ps[i], from_box.parentNode.firstChild); } } // <div class="selector"> or <div class="selector stacked"> var selector_div = quickElement('div', from_box.parentNode); selector_div.className = is_stacked ? 'selector stacked' : 'selector'; // <div class="selector-available"> var selector_available = quickElement('div', selector_div, ''); selector_available.className = 'selector-available'; quickElement('h2', selector_available, interpolate(gettext('Available %s'), [field_name])); var filter_p = quickElement('p', selector_available, ''); filter_p.className = 'selector-filter'; var search_filter_label = quickElement('label', filter_p, '', 'for', field_id + "_input", 'style', 'width:16px;padding:2px'); var search_selector_img = quickElement('img', search_filter_label, '', 'src', admin_media_prefix + 'img/admin/selector-search.gif'); search_selector_img.alt = gettext("Filter"); filter_p.appendChild(document.createTextNode(' ')); var filter_input = quickElement('input', filter_p, '', 'type', 'text'); filter_input.id = field_id + '_input'; selector_available.appendChild(from_box); var choose_all = quickElement('a', selector_available, gettext('Choose all'), 'href', 'javascript: (function(){ SelectBox.move_all("' + field_id + '_from", "' + field_id + '_to"); })()'); choose_all.className = 'selector-chooseall'; // <ul class="selector-chooser"> var selector_chooser = quickElement('ul', selector_div, ''); selector_chooser.className = 'selector-chooser'; var add_link = quickElement('a', quickElement('li', selector_chooser, ''), gettext('Add'), 'href', 'javascript: (function(){ SelectBox.move("' + field_id + '_from","' + field_id + '_to");})()'); add_link.className = 'selector-add'; var remove_link = quickElement('a', quickElement('li', selector_chooser, ''), gettext('Remove'), 'href', 'javascript: (function(){ SelectBox.move("' + field_id + '_to","' + field_id + '_from");})()'); remove_link.className = 'selector-remove'; // <div class="selector-chosen"> var selector_chosen = quickElement('div', selector_div, ''); selector_chosen.className = 'selector-chosen'; quickElement('h2', selector_chosen, interpolate(gettext('Chosen %s'), [field_name])); var selector_filter = quickElement('p', selector_chosen, gettext('Select your choice(s) and click ')); selector_filter.className = 'selector-filter'; quickElement('img', selector_filter, '', 'src', admin_media_prefix + (is_stacked ? 'img/admin/selector_stacked-add.gif':'img/admin/selector-add.gif'), 'alt', 'Add'); var to_box = quickElement('select', selector_chosen, '', 'id', field_id + '_to', 'multiple', 'multiple', 'size', from_box.size, 'name', from_box.getAttribute('name')); to_box.className = 'filtered'; var clear_all = quickElement('a', selector_chosen, gettext('Clear all'), 'href', 'javascript: (function() { SelectBox.move_all("' + field_id + '_to", "' + field_id + '_from");})()'); clear_all.className = 'selector-clearall'; from_box.setAttribute('name', from_box.getAttribute('name') + '_old'); // Set up the JavaScript event handlers for the select box filter interface addEvent(filter_input, 'keyup', function(e) { SelectFilter.filter_key_up(e, field_id); }); addEvent(filter_input, 'keydown', function(e) { SelectFilter.filter_key_down(e, field_id); }); addEvent(from_box, 'dblclick', function() { SelectBox.move(field_id + '_from', field_id + '_to'); }); addEvent(to_box, 'dblclick', function() { SelectBox.move(field_id + '_to', field_id + '_from'); }); addEvent(findForm(from_box), 'submit', function() { SelectBox.select_all(field_id + '_to'); }); SelectBox.init(field_id + '_from'); SelectBox.init(field_id + '_to'); // Move selected from_box options to to_box SelectBox.move(field_id + '_from', field_id + '_to'); }, filter_key_up: function(event, field_id) { from = document.getElementById(field_id + '_from'); // don't submit form if user pressed Enter if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) { from.selectedIndex = 0; SelectBox.move(field_id + '_from', field_id + '_to'); from.selectedIndex = 0; return false; } var temp = from.selectedIndex; SelectBox.filter(field_id + '_from', document.getElementById(field_id + '_input').value); from.selectedIndex = temp; return true; }, filter_key_down: function(event, field_id) { from = document.getElementById(field_id + '_from'); // right arrow -- move across if ((event.which && event.which == 39) || (event.keyCode && event.keyCode == 39)) { var old_index = from.selectedIndex; SelectBox.move(field_id + '_from', field_id + '_to'); from.selectedIndex = (old_index == from.length) ? from.length - 1 : old_index; return false; } // down arrow -- wrap around if ((event.which && event.which == 40) || (event.keyCode && event.keyCode == 40)) { from.selectedIndex = (from.length == from.selectedIndex + 1) ? 0 : from.selectedIndex + 1; } // up arrow -- wrap around if ((event.which && event.which == 38) || (event.keyCode && event.keyCode == 38)) { from.selectedIndex = (from.selectedIndex == 0) ? from.length - 1 : from.selectedIndex - 1; } return true; } }
JavaScript
/** * Django admin inlines * * Based on jQuery Formset 1.1 * @author Stanislaus Madueke (stan DOT madueke AT gmail DOT com) * @requires jQuery 1.2.6 or later * * Copyright (c) 2009, Stanislaus Madueke * All rights reserved. * * Spiced up with Code from Zain Memon's GSoC project 2009 * and modified for Django by Jannis Leidel * * Licensed under the New BSD License * See: http://www.opensource.org/licenses/bsd-license.php */ (function($) { $.fn.formset = function(opts) { var options = $.extend({}, $.fn.formset.defaults, opts); var updateElementIndex = function(el, prefix, ndx) { var id_regex = new RegExp("(" + prefix + "-(\\d+|__prefix__))"); var replacement = prefix + "-" + ndx; if ($(el).attr("for")) { $(el).attr("for", $(el).attr("for").replace(id_regex, replacement)); } if (el.id) { el.id = el.id.replace(id_regex, replacement); } if (el.name) { el.name = el.name.replace(id_regex, replacement); } }; var totalForms = $("#id_" + options.prefix + "-TOTAL_FORMS").attr("autocomplete", "off"); var nextIndex = parseInt(totalForms.val()); var maxForms = $("#id_" + options.prefix + "-MAX_NUM_FORMS").attr("autocomplete", "off"); // only show the add button if we are allowed to add more items, // note that max_num = None translates to a blank string. var showAddButton = maxForms.val() == '' || (maxForms.val()-totalForms.val()) > 0; $(this).each(function(i) { $(this).not("." + options.emptyCssClass).addClass(options.formCssClass); }); if ($(this).length && showAddButton) { var addButton; if ($(this).attr("tagName") == "TR") { // If forms are laid out as table rows, insert the // "add" button in a new table row: var numCols = this.eq(0).children().length; $(this).parent().append('<tr class="' + options.addCssClass + '"><td colspan="' + numCols + '"><a href="javascript:void(0)">' + options.addText + "</a></tr>"); addButton = $(this).parent().find("tr:last a"); } else { // Otherwise, insert it immediately after the last form: $(this).filter(":last").after('<div class="' + options.addCssClass + '"><a href="javascript:void(0)">' + options.addText + "</a></div>"); addButton = $(this).filter(":last").next().find("a"); } addButton.click(function() { var totalForms = $("#id_" + options.prefix + "-TOTAL_FORMS"); var template = $("#" + options.prefix + "-empty"); var row = template.clone(true); row.removeClass(options.emptyCssClass) .addClass(options.formCssClass) .attr("id", options.prefix + "-" + nextIndex); if (row.is("tr")) { // If the forms are laid out in table rows, insert // the remove button into the last table cell: row.children(":last").append('<div><a class="' + options.deleteCssClass +'" href="javascript:void(0)">' + options.deleteText + "</a></div>"); } else if (row.is("ul") || row.is("ol")) { // If they're laid out as an ordered/unordered list, // insert an <li> after the last list item: row.append('<li><a class="' + options.deleteCssClass +'" href="javascript:void(0)">' + options.deleteText + "</a></li>"); } else { // Otherwise, just insert the remove button as the // last child element of the form's container: row.children(":first").append('<span><a class="' + options.deleteCssClass + '" href="javascript:void(0)">' + options.deleteText + "</a></span>"); } row.find("*").each(function() { updateElementIndex(this, options.prefix, totalForms.val()); }); // Insert the new form when it has been fully edited row.insertBefore($(template)); // Update number of total forms $(totalForms).val(parseInt(totalForms.val()) + 1); nextIndex += 1; // Hide add button in case we've hit the max, except we want to add infinitely if ((maxForms.val() != '') && (maxForms.val()-totalForms.val()) <= 0) { addButton.parent().hide(); } // The delete button of each row triggers a bunch of other things row.find("a." + options.deleteCssClass).click(function() { // Remove the parent form containing this button: var row = $(this).parents("." + options.formCssClass); row.remove(); nextIndex -= 1; // If a post-delete callback was provided, call it with the deleted form: if (options.removed) { options.removed(row); } // Update the TOTAL_FORMS form count. var forms = $("." + options.formCssClass); $("#id_" + options.prefix + "-TOTAL_FORMS").val(forms.length); // Show add button again once we drop below max if ((maxForms.val() == '') || (maxForms.val()-forms.length) > 0) { addButton.parent().show(); } // Also, update names and ids for all remaining form controls // so they remain in sequence: for (var i=0, formCount=forms.length; i<formCount; i++) { updateElementIndex($(forms).get(i), options.prefix, i); $(forms.get(i)).find("*").each(function() { updateElementIndex(this, options.prefix, i); }); } return false; }); // If a post-add callback was supplied, call it with the added form: if (options.added) { options.added(row); } return false; }); } return this; } /* Setup plugin defaults */ $.fn.formset.defaults = { prefix: "form", // The form prefix for your django formset addText: "add another", // Text for the add link deleteText: "remove", // Text for the delete link addCssClass: "add-row", // CSS class applied to the add link deleteCssClass: "delete-row", // CSS class applied to the delete link emptyCssClass: "empty-row", // CSS class applied to the empty row formCssClass: "dynamic-form", // CSS class applied to each form in a formset added: null, // Function called each time a new form is added removed: null // Function called each time a form is deleted } })(django.jQuery);
JavaScript
/* calendar.js - Calendar functions by Adrian Holovaty */ function removeChildren(a) { // "a" is reference to an object while (a.hasChildNodes()) a.removeChild(a.lastChild); } // quickElement(tagType, parentReference, textInChildNode, [, attribute, attributeValue ...]); function quickElement() { var obj = document.createElement(arguments[0]); if (arguments[2] != '' && arguments[2] != null) { var textNode = document.createTextNode(arguments[2]); obj.appendChild(textNode); } var len = arguments.length; for (var i = 3; i < len; i += 2) { obj.setAttribute(arguments[i], arguments[i+1]); } arguments[1].appendChild(obj); return obj; } // CalendarNamespace -- Provides a collection of HTML calendar-related helper functions var CalendarNamespace = { monthsOfYear: gettext('January February March April May June July August September October November December').split(' '), daysOfWeek: gettext('S M T W T F S').split(' '), firstDayOfWeek: parseInt(get_format('FIRST_DAY_OF_WEEK')), isLeapYear: function(year) { return (((year % 4)==0) && ((year % 100)!=0) || ((year % 400)==0)); }, getDaysInMonth: function(month,year) { var days; if (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12) { days = 31; } else if (month==4 || month==6 || month==9 || month==11) { days = 30; } else if (month==2 && CalendarNamespace.isLeapYear(year)) { days = 29; } else { days = 28; } return days; }, draw: function(month, year, div_id, callback) { // month = 1-12, year = 1-9999 var today = new Date(); var todayDay = today.getDate(); var todayMonth = today.getMonth()+1; var todayYear = today.getFullYear(); var todayClass = ''; month = parseInt(month); year = parseInt(year); var calDiv = document.getElementById(div_id); removeChildren(calDiv); var calTable = document.createElement('table'); quickElement('caption', calTable, CalendarNamespace.monthsOfYear[month-1] + ' ' + year); var tableBody = quickElement('tbody', calTable); // Draw days-of-week header var tableRow = quickElement('tr', tableBody); for (var i = 0; i < 7; i++) { quickElement('th', tableRow, CalendarNamespace.daysOfWeek[(i + CalendarNamespace.firstDayOfWeek) % 7]); } var startingPos = new Date(year, month-1, 1 - CalendarNamespace.firstDayOfWeek).getDay(); var days = CalendarNamespace.getDaysInMonth(month, year); // Draw blanks before first of month tableRow = quickElement('tr', tableBody); for (var i = 0; i < startingPos; i++) { var _cell = quickElement('td', tableRow, ' '); _cell.style.backgroundColor = '#f3f3f3'; } // Draw days of month var currentDay = 1; for (var i = startingPos; currentDay <= days; i++) { if (i%7 == 0 && currentDay != 1) { tableRow = quickElement('tr', tableBody); } if ((currentDay==todayDay) && (month==todayMonth) && (year==todayYear)) { todayClass='today'; } else { todayClass=''; } var cell = quickElement('td', tableRow, '', 'class', todayClass); quickElement('a', cell, currentDay, 'href', 'javascript:void(' + callback + '('+year+','+month+','+currentDay+'));'); currentDay++; } // Draw blanks after end of month (optional, but makes for valid code) while (tableRow.childNodes.length < 7) { var _cell = quickElement('td', tableRow, ' '); _cell.style.backgroundColor = '#f3f3f3'; } calDiv.appendChild(calTable); } } // Calendar -- A calendar instance function Calendar(div_id, callback) { // div_id (string) is the ID of the element in which the calendar will // be displayed // callback (string) is the name of a JavaScript function that will be // called with the parameters (year, month, day) when a day in the // calendar is clicked this.div_id = div_id; this.callback = callback; this.today = new Date(); this.currentMonth = this.today.getMonth() + 1; this.currentYear = this.today.getFullYear(); } Calendar.prototype = { drawCurrent: function() { CalendarNamespace.draw(this.currentMonth, this.currentYear, this.div_id, this.callback); }, drawDate: function(month, year) { this.currentMonth = month; this.currentYear = year; this.drawCurrent(); }, drawPreviousMonth: function() { if (this.currentMonth == 1) { this.currentMonth = 12; this.currentYear--; } else { this.currentMonth--; } this.drawCurrent(); }, drawNextMonth: function() { if (this.currentMonth == 12) { this.currentMonth = 1; this.currentYear++; } else { this.currentMonth++; } this.drawCurrent(); }, drawPreviousYear: function() { this.currentYear--; this.drawCurrent(); }, drawNextYear: function() { this.currentYear++; this.drawCurrent(); } }
JavaScript
// Puts the included jQuery into our own namespace var django = { "jQuery": jQuery.noConflict(true) };
JavaScript
// Core javascript helper functions // basic browser identification & version var isOpera = (navigator.userAgent.indexOf("Opera")>=0) && parseFloat(navigator.appVersion); var isIE = ((document.all) && (!isOpera)) && parseFloat(navigator.appVersion.split("MSIE ")[1].split(";")[0]); // Cross-browser event handlers. function addEvent(obj, evType, fn) { if (obj.addEventListener) { obj.addEventListener(evType, fn, false); return true; } else if (obj.attachEvent) { var r = obj.attachEvent("on" + evType, fn); return r; } else { return false; } } function removeEvent(obj, evType, fn) { if (obj.removeEventListener) { obj.removeEventListener(evType, fn, false); return true; } else if (obj.detachEvent) { obj.detachEvent("on" + evType, fn); return true; } else { return false; } } // quickElement(tagType, parentReference, textInChildNode, [, attribute, attributeValue ...]); function quickElement() { var obj = document.createElement(arguments[0]); if (arguments[2] != '' && arguments[2] != null) { var textNode = document.createTextNode(arguments[2]); obj.appendChild(textNode); } var len = arguments.length; for (var i = 3; i < len; i += 2) { obj.setAttribute(arguments[i], arguments[i+1]); } arguments[1].appendChild(obj); return obj; } // ---------------------------------------------------------------------------- // Cross-browser xmlhttp object // from http://jibbering.com/2002/4/httprequest.html // ---------------------------------------------------------------------------- var xmlhttp; /*@cc_on @*/ /*@if (@_jscript_version >= 5) try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { xmlhttp = false; } } @else xmlhttp = false; @end @*/ if (!xmlhttp && typeof XMLHttpRequest != 'undefined') { xmlhttp = new XMLHttpRequest(); } // ---------------------------------------------------------------------------- // Find-position functions by PPK // See http://www.quirksmode.org/js/findpos.html // ---------------------------------------------------------------------------- function findPosX(obj) { var curleft = 0; if (obj.offsetParent) { while (obj.offsetParent) { curleft += obj.offsetLeft - ((isOpera) ? 0 : obj.scrollLeft); obj = obj.offsetParent; } // IE offsetParent does not include the top-level if (isIE && obj.parentElement){ curleft += obj.offsetLeft - obj.scrollLeft; } } else if (obj.x) { curleft += obj.x; } return curleft; } function findPosY(obj) { var curtop = 0; if (obj.offsetParent) { while (obj.offsetParent) { curtop += obj.offsetTop - ((isOpera) ? 0 : obj.scrollTop); obj = obj.offsetParent; } // IE offsetParent does not include the top-level if (isIE && obj.parentElement){ curtop += obj.offsetTop - obj.scrollTop; } } else if (obj.y) { curtop += obj.y; } return curtop; } //----------------------------------------------------------------------------- // Date object extensions // ---------------------------------------------------------------------------- Date.prototype.getCorrectYear = function() { // Date.getYear() is unreliable -- // see http://www.quirksmode.org/js/introdate.html#year var y = this.getYear() % 100; return (y < 38) ? y + 2000 : y + 1900; } Date.prototype.getTwelveHours = function() { hours = this.getHours(); if (hours == 0) { return 12; } else { return hours <= 12 ? hours : hours-12 } } Date.prototype.getTwoDigitMonth = function() { return (this.getMonth() < 9) ? '0' + (this.getMonth()+1) : (this.getMonth()+1); } Date.prototype.getTwoDigitDate = function() { return (this.getDate() < 10) ? '0' + this.getDate() : this.getDate(); } Date.prototype.getTwoDigitTwelveHour = function() { return (this.getTwelveHours() < 10) ? '0' + this.getTwelveHours() : this.getTwelveHours(); } Date.prototype.getTwoDigitHour = function() { return (this.getHours() < 10) ? '0' + this.getHours() : this.getHours(); } Date.prototype.getTwoDigitMinute = function() { return (this.getMinutes() < 10) ? '0' + this.getMinutes() : this.getMinutes(); } Date.prototype.getTwoDigitSecond = function() { return (this.getSeconds() < 10) ? '0' + this.getSeconds() : this.getSeconds(); } Date.prototype.getISODate = function() { return this.getCorrectYear() + '-' + this.getTwoDigitMonth() + '-' + this.getTwoDigitDate(); } Date.prototype.getHourMinute = function() { return this.getTwoDigitHour() + ':' + this.getTwoDigitMinute(); } Date.prototype.getHourMinuteSecond = function() { return this.getTwoDigitHour() + ':' + this.getTwoDigitMinute() + ':' + this.getTwoDigitSecond(); } Date.prototype.strftime = function(format) { var fields = { c: this.toString(), d: this.getTwoDigitDate(), H: this.getTwoDigitHour(), I: this.getTwoDigitTwelveHour(), m: this.getTwoDigitMonth(), M: this.getTwoDigitMinute(), p: (this.getHours() >= 12) ? 'PM' : 'AM', S: this.getTwoDigitSecond(), w: '0' + this.getDay(), x: this.toLocaleDateString(), X: this.toLocaleTimeString(), y: ('' + this.getFullYear()).substr(2, 4), Y: '' + this.getFullYear(), '%' : '%' }; var result = '', i = 0; while (i < format.length) { if (format.charAt(i) === '%') { result = result + fields[format.charAt(i + 1)]; ++i; } else { result = result + format.charAt(i); } ++i; } return result; } // ---------------------------------------------------------------------------- // String object extensions // ---------------------------------------------------------------------------- String.prototype.pad_left = function(pad_length, pad_string) { var new_string = this; for (var i = 0; new_string.length < pad_length; i++) { new_string = pad_string + new_string; } return new_string; } // ---------------------------------------------------------------------------- // Get the computed style for and element // ---------------------------------------------------------------------------- function getStyle(oElm, strCssRule){ var strValue = ""; if(document.defaultView && document.defaultView.getComputedStyle){ strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule); } else if(oElm.currentStyle){ strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){ return p1.toUpperCase(); }); strValue = oElm.currentStyle[strCssRule]; } return strValue; }
JavaScript
addEvent(window, 'load', reorder_init); var lis; var top = 0; var left = 0; var height = 30; function reorder_init() { lis = document.getElementsBySelector('ul#orderthese li'); var input = document.getElementsBySelector('input[name=order_]')[0]; setOrder(input.value.split(',')); input.disabled = true; draw(); // Now initialise the dragging behaviour var limit = (lis.length - 1) * height; for (var i = 0; i < lis.length; i++) { var li = lis[i]; var img = document.getElementById('handle'+li.id); li.style.zIndex = 1; Drag.init(img, li, left + 10, left + 10, top + 10, top + 10 + limit); li.onDragStart = startDrag; li.onDragEnd = endDrag; img.style.cursor = 'move'; } } function submitOrderForm() { var inputOrder = document.getElementsBySelector('input[name=order_]')[0]; inputOrder.value = getOrder(); inputOrder.disabled=false; } function startDrag() { this.style.zIndex = '10'; this.className = 'dragging'; } function endDrag(x, y) { this.style.zIndex = '1'; this.className = ''; // Work out how far along it has been dropped, using x co-ordinate var oldIndex = this.index; var newIndex = Math.round((y - 10 - top) / height); // 'Snap' to the correct position this.style.top = (10 + top + newIndex * height) + 'px'; this.index = newIndex; moveItem(oldIndex, newIndex); } function moveItem(oldIndex, newIndex) { // Swaps two items, adjusts the index and left co-ord for all others if (oldIndex == newIndex) { return; // Nothing to swap; } var direction, lo, hi; if (newIndex > oldIndex) { lo = oldIndex; hi = newIndex; direction = -1; } else { direction = 1; hi = oldIndex; lo = newIndex; } var lis2 = new Array(); // We will build the new order in this array for (var i = 0; i < lis.length; i++) { if (i < lo || i > hi) { // Position of items not between the indexes is unaffected lis2[i] = lis[i]; continue; } else if (i == newIndex) { lis2[i] = lis[oldIndex]; continue; } else { // Item is between the two indexes - move it along 1 lis2[i] = lis[i - direction]; } } // Re-index everything reIndex(lis2); lis = lis2; draw(); // document.getElementById('hiddenOrder').value = getOrder(); document.getElementsBySelector('input[name=order_]')[0].value = getOrder(); } function reIndex(lis) { for (var i = 0; i < lis.length; i++) { lis[i].index = i; } } function draw() { for (var i = 0; i < lis.length; i++) { var li = lis[i]; li.index = i; li.style.position = 'absolute'; li.style.left = (10 + left) + 'px'; li.style.top = (10 + top + (i * height)) + 'px'; } } function getOrder() { var order = new Array(lis.length); for (var i = 0; i < lis.length; i++) { order[i] = lis[i].id.substring(1, 100); } return order.join(','); } function setOrder(id_list) { /* Set the current order to match the lsit of IDs */ var temp_lis = new Array(); for (var i = 0; i < id_list.length; i++) { var id = 'p' + id_list[i]; temp_lis[temp_lis.length] = document.getElementById(id); } reIndex(temp_lis); lis = temp_lis; draw(); } function addEvent(elm, evType, fn, useCapture) // addEvent and removeEvent // cross-browser event handling for IE5+, NS6 and Mozilla // By Scott Andrew { if (elm.addEventListener){ elm.addEventListener(evType, fn, useCapture); return true; } else if (elm.attachEvent){ var r = elm.attachEvent("on"+evType, fn); return r; } else { elm['on'+evType] = fn; } }
JavaScript
// Handles related-objects functionality: lookup link for raw_id_fields // and Add Another links. function html_unescape(text) { // Unescape a string that was escaped using django.utils.html.escape. text = text.replace(/&lt;/g, '<'); text = text.replace(/&gt;/g, '>'); text = text.replace(/&quot;/g, '"'); text = text.replace(/&#39;/g, "'"); text = text.replace(/&amp;/g, '&'); return text; } // IE doesn't accept periods or dashes in the window name, but the element IDs // we use to generate popup window names may contain them, therefore we map them // to allowed characters in a reversible way so that we can locate the correct // element when the popup window is dismissed. function id_to_windowname(text) { text = text.replace(/\./g, '__dot__'); text = text.replace(/\-/g, '__dash__'); return text; } function windowname_to_id(text) { text = text.replace(/__dot__/g, '.'); text = text.replace(/__dash__/g, '-'); return text; } function showRelatedObjectLookupPopup(triggeringLink) { var name = triggeringLink.id.replace(/^lookup_/, ''); name = id_to_windowname(name); var href; if (triggeringLink.href.search(/\?/) >= 0) { href = triggeringLink.href + '&pop=1'; } else { href = triggeringLink.href + '?pop=1'; } var win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes'); win.focus(); return false; } function dismissRelatedLookupPopup(win, chosenId) { var name = windowname_to_id(win.name); var elem = document.getElementById(name); if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) { elem.value += ',' + chosenId; } else { document.getElementById(name).value = chosenId; } win.close(); } function showAddAnotherPopup(triggeringLink) { var name = triggeringLink.id.replace(/^add_/, ''); name = id_to_windowname(name); href = triggeringLink.href if (href.indexOf('?') == -1) { href += '?_popup=1'; } else { href += '&_popup=1'; } var win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes'); win.focus(); return false; } function dismissAddAnotherPopup(win, newId, newRepr) { // newId and newRepr are expected to have previously been escaped by // django.utils.html.escape. newId = html_unescape(newId); newRepr = html_unescape(newRepr); var name = windowname_to_id(win.name); var elem = document.getElementById(name); if (elem) { if (elem.nodeName == 'SELECT') { var o = new Option(newRepr, newId); elem.options[elem.options.length] = o; o.selected = true; } else if (elem.nodeName == 'INPUT') { if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) { elem.value += ',' + newId; } else { elem.value = newId; } } } else { var toId = name + "_to"; elem = document.getElementById(toId); var o = new Option(newRepr, newId); SelectBox.add_to_cache(toId, o); SelectBox.redisplay(toId); } win.close(); }
JavaScript
// Inserts shortcut buttons after all of the following: // <input type="text" class="vDateField"> // <input type="text" class="vTimeField"> var DateTimeShortcuts = { calendars: [], calendarInputs: [], clockInputs: [], calendarDivName1: 'calendarbox', // name of calendar <div> that gets toggled calendarDivName2: 'calendarin', // name of <div> that contains calendar calendarLinkName: 'calendarlink',// name of the link that is used to toggle clockDivName: 'clockbox', // name of clock <div> that gets toggled clockLinkName: 'clocklink', // name of the link that is used to toggle shortCutsClass: 'datetimeshortcuts', // class of the clock and cal shortcuts admin_media_prefix: '', init: function() { // Get admin_media_prefix by grabbing it off the window object. It's // set in the admin/base.html template, so if it's not there, someone's // overridden the template. In that case, we'll set a clearly-invalid // value in the hopes that someone will examine HTTP requests and see it. if (window.__admin_media_prefix__ != undefined) { DateTimeShortcuts.admin_media_prefix = window.__admin_media_prefix__; } else { DateTimeShortcuts.admin_media_prefix = '/missing-admin-media-prefix/'; } var inputs = document.getElementsByTagName('input'); for (i=0; i<inputs.length; i++) { var inp = inputs[i]; if (inp.getAttribute('type') == 'text' && inp.className.match(/vTimeField/)) { DateTimeShortcuts.addClock(inp); } else if (inp.getAttribute('type') == 'text' && inp.className.match(/vDateField/)) { DateTimeShortcuts.addCalendar(inp); } } }, // Add clock widget to a given field addClock: function(inp) { var num = DateTimeShortcuts.clockInputs.length; DateTimeShortcuts.clockInputs[num] = inp; // Shortcut links (clock icon and "Now" link) var shortcuts_span = document.createElement('span'); shortcuts_span.className = DateTimeShortcuts.shortCutsClass; inp.parentNode.insertBefore(shortcuts_span, inp.nextSibling); var now_link = document.createElement('a'); now_link.setAttribute('href', "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date().strftime('" + get_format('TIME_INPUT_FORMATS')[0] + "'));"); now_link.appendChild(document.createTextNode(gettext('Now'))); var clock_link = document.createElement('a'); clock_link.setAttribute('href', 'javascript:DateTimeShortcuts.openClock(' + num + ');'); clock_link.id = DateTimeShortcuts.clockLinkName + num; quickElement('img', clock_link, '', 'src', DateTimeShortcuts.admin_media_prefix + 'img/admin/icon_clock.gif', 'alt', gettext('Clock')); shortcuts_span.appendChild(document.createTextNode('\240')); shortcuts_span.appendChild(now_link); shortcuts_span.appendChild(document.createTextNode('\240|\240')); shortcuts_span.appendChild(clock_link); // Create clock link div // // Markup looks like: // <div id="clockbox1" class="clockbox module"> // <h2>Choose a time</h2> // <ul class="timelist"> // <li><a href="#">Now</a></li> // <li><a href="#">Midnight</a></li> // <li><a href="#">6 a.m.</a></li> // <li><a href="#">Noon</a></li> // </ul> // <p class="calendar-cancel"><a href="#">Cancel</a></p> // </div> var clock_box = document.createElement('div'); clock_box.style.display = 'none'; clock_box.style.position = 'absolute'; clock_box.className = 'clockbox module'; clock_box.setAttribute('id', DateTimeShortcuts.clockDivName + num); document.body.appendChild(clock_box); addEvent(clock_box, 'click', DateTimeShortcuts.cancelEventPropagation); quickElement('h2', clock_box, gettext('Choose a time')); time_list = quickElement('ul', clock_box, ''); time_list.className = 'timelist'; time_format = get_format('TIME_INPUT_FORMATS')[0]; quickElement("a", quickElement("li", time_list, ""), gettext("Now"), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date().strftime('" + time_format + "'));"); quickElement("a", quickElement("li", time_list, ""), gettext("Midnight"), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date(1970,1,1,0,0,0,0).strftime('" + time_format + "'));"); quickElement("a", quickElement("li", time_list, ""), gettext("6 a.m."), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date(1970,1,1,6,0,0,0).strftime('" + time_format + "'));"); quickElement("a", quickElement("li", time_list, ""), gettext("Noon"), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date(1970,1,1,12,0,0,0).strftime('" + time_format + "'));"); cancel_p = quickElement('p', clock_box, ''); cancel_p.className = 'calendar-cancel'; quickElement('a', cancel_p, gettext('Cancel'), 'href', 'javascript:DateTimeShortcuts.dismissClock(' + num + ');'); }, openClock: function(num) { var clock_box = document.getElementById(DateTimeShortcuts.clockDivName+num) var clock_link = document.getElementById(DateTimeShortcuts.clockLinkName+num) // Recalculate the clockbox position // is it left-to-right or right-to-left layout ? if (getStyle(document.body,'direction')!='rtl') { clock_box.style.left = findPosX(clock_link) + 17 + 'px'; } else { // since style's width is in em, it'd be tough to calculate // px value of it. let's use an estimated px for now // TODO: IE returns wrong value for findPosX when in rtl mode // (it returns as it was left aligned), needs to be fixed. clock_box.style.left = findPosX(clock_link) - 110 + 'px'; } clock_box.style.top = Math.max(0, findPosY(clock_link) - 30) + 'px'; // Show the clock box clock_box.style.display = 'block'; addEvent(window.document, 'click', function() { DateTimeShortcuts.dismissClock(num); return true; }); }, dismissClock: function(num) { document.getElementById(DateTimeShortcuts.clockDivName + num).style.display = 'none'; window.document.onclick = null; }, handleClockQuicklink: function(num, val) { DateTimeShortcuts.clockInputs[num].value = val; DateTimeShortcuts.clockInputs[num].focus(); DateTimeShortcuts.dismissClock(num); }, // Add calendar widget to a given field. addCalendar: function(inp) { var num = DateTimeShortcuts.calendars.length; DateTimeShortcuts.calendarInputs[num] = inp; // Shortcut links (calendar icon and "Today" link) var shortcuts_span = document.createElement('span'); shortcuts_span.className = DateTimeShortcuts.shortCutsClass; inp.parentNode.insertBefore(shortcuts_span, inp.nextSibling); var today_link = document.createElement('a'); today_link.setAttribute('href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', 0);'); today_link.appendChild(document.createTextNode(gettext('Today'))); var cal_link = document.createElement('a'); cal_link.setAttribute('href', 'javascript:DateTimeShortcuts.openCalendar(' + num + ');'); cal_link.id = DateTimeShortcuts.calendarLinkName + num; quickElement('img', cal_link, '', 'src', DateTimeShortcuts.admin_media_prefix + 'img/admin/icon_calendar.gif', 'alt', gettext('Calendar')); shortcuts_span.appendChild(document.createTextNode('\240')); shortcuts_span.appendChild(today_link); shortcuts_span.appendChild(document.createTextNode('\240|\240')); shortcuts_span.appendChild(cal_link); // Create calendarbox div. // // Markup looks like: // // <div id="calendarbox3" class="calendarbox module"> // <h2> // <a href="#" class="link-previous">&lsaquo;</a> // <a href="#" class="link-next">&rsaquo;</a> February 2003 // </h2> // <div class="calendar" id="calendarin3"> // <!-- (cal) --> // </div> // <div class="calendar-shortcuts"> // <a href="#">Yesterday</a> | <a href="#">Today</a> | <a href="#">Tomorrow</a> // </div> // <p class="calendar-cancel"><a href="#">Cancel</a></p> // </div> var cal_box = document.createElement('div'); cal_box.style.display = 'none'; cal_box.style.position = 'absolute'; cal_box.className = 'calendarbox module'; cal_box.setAttribute('id', DateTimeShortcuts.calendarDivName1 + num); document.body.appendChild(cal_box); addEvent(cal_box, 'click', DateTimeShortcuts.cancelEventPropagation); // next-prev links var cal_nav = quickElement('div', cal_box, ''); var cal_nav_prev = quickElement('a', cal_nav, '<', 'href', 'javascript:DateTimeShortcuts.drawPrev('+num+');'); cal_nav_prev.className = 'calendarnav-previous'; var cal_nav_next = quickElement('a', cal_nav, '>', 'href', 'javascript:DateTimeShortcuts.drawNext('+num+');'); cal_nav_next.className = 'calendarnav-next'; // main box var cal_main = quickElement('div', cal_box, '', 'id', DateTimeShortcuts.calendarDivName2 + num); cal_main.className = 'calendar'; DateTimeShortcuts.calendars[num] = new Calendar(DateTimeShortcuts.calendarDivName2 + num, DateTimeShortcuts.handleCalendarCallback(num)); DateTimeShortcuts.calendars[num].drawCurrent(); // calendar shortcuts var shortcuts = quickElement('div', cal_box, ''); shortcuts.className = 'calendar-shortcuts'; quickElement('a', shortcuts, gettext('Yesterday'), 'href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', -1);'); shortcuts.appendChild(document.createTextNode('\240|\240')); quickElement('a', shortcuts, gettext('Today'), 'href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', 0);'); shortcuts.appendChild(document.createTextNode('\240|\240')); quickElement('a', shortcuts, gettext('Tomorrow'), 'href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', +1);'); // cancel bar var cancel_p = quickElement('p', cal_box, ''); cancel_p.className = 'calendar-cancel'; quickElement('a', cancel_p, gettext('Cancel'), 'href', 'javascript:DateTimeShortcuts.dismissCalendar(' + num + ');'); }, openCalendar: function(num) { var cal_box = document.getElementById(DateTimeShortcuts.calendarDivName1+num) var cal_link = document.getElementById(DateTimeShortcuts.calendarLinkName+num) var inp = DateTimeShortcuts.calendarInputs[num]; // Determine if the current value in the input has a valid date. // If so, draw the calendar with that date's year and month. if (inp.value) { var date_parts = inp.value.split('-'); var year = date_parts[0]; var month = parseFloat(date_parts[1]); if (year.match(/\d\d\d\d/) && month >= 1 && month <= 12) { DateTimeShortcuts.calendars[num].drawDate(month, year); } } // Recalculate the clockbox position // is it left-to-right or right-to-left layout ? if (getStyle(document.body,'direction')!='rtl') { cal_box.style.left = findPosX(cal_link) + 17 + 'px'; } else { // since style's width is in em, it'd be tough to calculate // px value of it. let's use an estimated px for now // TODO: IE returns wrong value for findPosX when in rtl mode // (it returns as it was left aligned), needs to be fixed. cal_box.style.left = findPosX(cal_link) - 180 + 'px'; } cal_box.style.top = Math.max(0, findPosY(cal_link) - 75) + 'px'; cal_box.style.display = 'block'; addEvent(window.document, 'click', function() { DateTimeShortcuts.dismissCalendar(num); return true; }); }, dismissCalendar: function(num) { document.getElementById(DateTimeShortcuts.calendarDivName1+num).style.display = 'none'; window.document.onclick = null; }, drawPrev: function(num) { DateTimeShortcuts.calendars[num].drawPreviousMonth(); }, drawNext: function(num) { DateTimeShortcuts.calendars[num].drawNextMonth(); }, handleCalendarCallback: function(num) { format = get_format('DATE_INPUT_FORMATS')[0]; // the format needs to be escaped a little format = format.replace('\\', '\\\\'); format = format.replace('\r', '\\r'); format = format.replace('\n', '\\n'); format = format.replace('\t', '\\t'); format = format.replace("'", "\\'"); return ["function(y, m, d) { DateTimeShortcuts.calendarInputs[", num, "].value = new Date(y, m-1, d).strftime('", format, "');DateTimeShortcuts.calendarInputs[", num, "].focus();document.getElementById(DateTimeShortcuts.calendarDivName1+", num, ").style.display='none';}"].join(''); }, handleCalendarQuickLink: function(num, offset) { var d = new Date(); d.setDate(d.getDate() + offset) DateTimeShortcuts.calendarInputs[num].value = d.strftime(get_format('DATE_INPUT_FORMATS')[0]); DateTimeShortcuts.calendarInputs[num].focus(); DateTimeShortcuts.dismissCalendar(num); }, cancelEventPropagation: function(e) { if (!e) e = window.event; e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation(); } } addEvent(window, 'load', DateTimeShortcuts.init);
JavaScript
(function($) { $.fn.actions = function(opts) { var options = $.extend({}, $.fn.actions.defaults, opts); var actionCheckboxes = $(this); var list_editable_changed = false; checker = function(checked) { if (checked) { showQuestion(); } else { reset(); } $(actionCheckboxes).attr("checked", checked) .parent().parent().toggleClass(options.selectedClass, checked); } updateCounter = function() { var sel = $(actionCheckboxes).filter(":checked").length; $(options.counterContainer).html(interpolate( ngettext('%(sel)s of %(cnt)s selected', '%(sel)s of %(cnt)s selected', sel), { sel: sel, cnt: _actions_icnt }, true)); $(options.allToggle).attr("checked", function() { if (sel == actionCheckboxes.length) { value = true; showQuestion(); } else { value = false; clearAcross(); } return value; }); } showQuestion = function() { $(options.acrossClears).hide(); $(options.acrossQuestions).show(); $(options.allContainer).hide(); } showClear = function() { $(options.acrossClears).show(); $(options.acrossQuestions).hide(); $(options.actionContainer).toggleClass(options.selectedClass); $(options.allContainer).show(); $(options.counterContainer).hide(); } reset = function() { $(options.acrossClears).hide(); $(options.acrossQuestions).hide(); $(options.allContainer).hide(); $(options.counterContainer).show(); } clearAcross = function() { reset(); $(options.acrossInput).val(0); $(options.actionContainer).removeClass(options.selectedClass); } // Show counter by default $(options.counterContainer).show(); // Check state of checkboxes and reinit state if needed $(this).filter(":checked").each(function(i) { $(this).parent().parent().toggleClass(options.selectedClass); updateCounter(); if ($(options.acrossInput).val() == 1) { showClear(); } }); $(options.allToggle).show().click(function() { checker($(this).attr("checked")); updateCounter(); }); $("div.actions span.question a").click(function(event) { event.preventDefault(); $(options.acrossInput).val(1); showClear(); }); $("div.actions span.clear a").click(function(event) { event.preventDefault(); $(options.allToggle).attr("checked", false); clearAcross(); checker(0); updateCounter(); }); lastChecked = null; $(actionCheckboxes).click(function(event) { if (!event) { var event = window.event; } var target = event.target ? event.target : event.srcElement; if (lastChecked && $.data(lastChecked) != $.data(target) && event.shiftKey == true) { var inrange = false; $(lastChecked).attr("checked", target.checked) .parent().parent().toggleClass(options.selectedClass, target.checked); $(actionCheckboxes).each(function() { if ($.data(this) == $.data(lastChecked) || $.data(this) == $.data(target)) { inrange = (inrange) ? false : true; } if (inrange) { $(this).attr("checked", target.checked) .parent().parent().toggleClass(options.selectedClass, target.checked); } }); } $(target).parent().parent().toggleClass(options.selectedClass, target.checked); lastChecked = target; updateCounter(); }); $('form#changelist-form table#result_list tr').find('td:gt(0) :input').change(function() { list_editable_changed = true; }); $('form#changelist-form button[name="index"]').click(function(event) { if (list_editable_changed) { return confirm(gettext("You have unsaved changes on individual editable fields. If you run an action, your unsaved changes will be lost.")); } }); $('form#changelist-form input[name="_save"]').click(function(event) { var action_changed = false; $('div.actions select option:selected').each(function() { if ($(this).val()) { action_changed = true; } }); if (action_changed) { if (list_editable_changed) { return confirm(gettext("You have selected an action, but you haven't saved your changes to individual fields yet. Please click OK to save. You'll need to re-run the action.")); } else { return confirm(gettext("You have selected an action, and you haven't made any changes on individual fields. You're probably looking for the Go button rather than the Save button.")); } } }); } /* Setup plugin defaults */ $.fn.actions.defaults = { actionContainer: "div.actions", counterContainer: "span.action-counter", allContainer: "div.actions span.all", acrossInput: "div.actions input.select-across", acrossQuestions: "div.actions span.question", acrossClears: "div.actions span.clear", allToggle: "#action-toggle", selectedClass: "selected" } })(django.jQuery);
JavaScript
var timeParsePatterns = [ // 9 { re: /^\d{1,2}$/i, handler: function(bits) { if (bits[0].length == 1) { return '0' + bits[0] + ':00'; } else { return bits[0] + ':00'; } } }, // 13:00 { re: /^\d{2}[:.]\d{2}$/i, handler: function(bits) { return bits[0].replace('.', ':'); } }, // 9:00 { re: /^\d[:.]\d{2}$/i, handler: function(bits) { return '0' + bits[0].replace('.', ':'); } }, // 3 am / 3 a.m. / 3am { re: /^(\d+)\s*([ap])(?:.?m.?)?$/i, handler: function(bits) { var hour = parseInt(bits[1]); if (hour == 12) { hour = 0; } if (bits[2].toLowerCase() == 'p') { if (hour == 12) { hour = 0; } return (hour + 12) + ':00'; } else { if (hour < 10) { return '0' + hour + ':00'; } else { return hour + ':00'; } } } }, // 3.30 am / 3:15 a.m. / 3.00am { re: /^(\d+)[.:](\d{2})\s*([ap]).?m.?$/i, handler: function(bits) { var hour = parseInt(bits[1]); var mins = parseInt(bits[2]); if (mins < 10) { mins = '0' + mins; } if (hour == 12) { hour = 0; } if (bits[3].toLowerCase() == 'p') { if (hour == 12) { hour = 0; } return (hour + 12) + ':' + mins; } else { if (hour < 10) { return '0' + hour + ':' + mins; } else { return hour + ':' + mins; } } } }, // noon { re: /^no/i, handler: function(bits) { return '12:00'; } }, // midnight { re: /^mid/i, handler: function(bits) { return '00:00'; } } ]; function parseTimeString(s) { for (var i = 0; i < timeParsePatterns.length; i++) { var re = timeParsePatterns[i].re; var handler = timeParsePatterns[i].handler; var bits = re.exec(s); if (bits) { return handler(bits); } } return s; }
JavaScript
(function($) { $(document).ready(function() { // Add anchor tag for Show/Hide link $("fieldset.collapse").each(function(i, elem) { // Don't hide if fields in this fieldset have errors if ( $(elem).find("div.errors").length == 0 ) { $(elem).addClass("collapsed"); $(elem).find("h2").first().append(' (<a id="fieldsetcollapser' + i +'" class="collapse-toggle" href="#">' + gettext("Show") + '</a>)'); } }); // Add toggle to anchor tag $("fieldset.collapse a.collapse-toggle").toggle( function() { // Show $(this).text(gettext("Hide")); $(this).closest("fieldset").removeClass("collapsed"); return false; }, function() { // Hide $(this).text(gettext("Show")); $(this).closest("fieldset").addClass("collapsed"); return false; } ); }); })(django.jQuery);
JavaScript
/* 'Magic' date parsing, by Simon Willison (6th October 2003) http://simon.incutio.com/archive/2003/10/06/betterDateInput Adapted for 6newslawrence.com, 28th January 2004 */ /* Finds the index of the first occurence of item in the array, or -1 if not found */ if (typeof Array.prototype.indexOf == 'undefined') { Array.prototype.indexOf = function(item) { var len = this.length; for (var i = 0; i < len; i++) { if (this[i] == item) { return i; } } return -1; }; } /* Returns an array of items judged 'true' by the passed in test function */ if (typeof Array.prototype.filter == 'undefined') { Array.prototype.filter = function(test) { var matches = []; var len = this.length; for (var i = 0; i < len; i++) { if (test(this[i])) { matches[matches.length] = this[i]; } } return matches; }; } var monthNames = gettext("January February March April May June July August September October November December").split(" "); var weekdayNames = gettext("Sunday Monday Tuesday Wednesday Thursday Friday Saturday").split(" "); /* Takes a string, returns the index of the month matching that string, throws an error if 0 or more than 1 matches */ function parseMonth(month) { var matches = monthNames.filter(function(item) { return new RegExp("^" + month, "i").test(item); }); if (matches.length == 0) { throw new Error("Invalid month string"); } if (matches.length > 1) { throw new Error("Ambiguous month"); } return monthNames.indexOf(matches[0]); } /* Same as parseMonth but for days of the week */ function parseWeekday(weekday) { var matches = weekdayNames.filter(function(item) { return new RegExp("^" + weekday, "i").test(item); }); if (matches.length == 0) { throw new Error("Invalid day string"); } if (matches.length > 1) { throw new Error("Ambiguous weekday"); } return weekdayNames.indexOf(matches[0]); } /* Array of objects, each has 're', a regular expression and 'handler', a function for creating a date from something that matches the regular expression. Handlers may throw errors if string is unparseable. */ var dateParsePatterns = [ // Today { re: /^tod/i, handler: function() { return new Date(); } }, // Tomorrow { re: /^tom/i, handler: function() { var d = new Date(); d.setDate(d.getDate() + 1); return d; } }, // Yesterday { re: /^yes/i, handler: function() { var d = new Date(); d.setDate(d.getDate() - 1); return d; } }, // 4th { re: /^(\d{1,2})(st|nd|rd|th)?$/i, handler: function(bits) { var d = new Date(); d.setDate(parseInt(bits[1], 10)); return d; } }, // 4th Jan { re: /^(\d{1,2})(?:st|nd|rd|th)? (\w+)$/i, handler: function(bits) { var d = new Date(); d.setDate(1); d.setMonth(parseMonth(bits[2])); d.setDate(parseInt(bits[1], 10)); return d; } }, // 4th Jan 2003 { re: /^(\d{1,2})(?:st|nd|rd|th)? (\w+),? (\d{4})$/i, handler: function(bits) { var d = new Date(); d.setDate(1); d.setYear(bits[3]); d.setMonth(parseMonth(bits[2])); d.setDate(parseInt(bits[1], 10)); return d; } }, // Jan 4th { re: /^(\w+) (\d{1,2})(?:st|nd|rd|th)?$/i, handler: function(bits) { var d = new Date(); d.setDate(1); d.setMonth(parseMonth(bits[1])); d.setDate(parseInt(bits[2], 10)); return d; } }, // Jan 4th 2003 { re: /^(\w+) (\d{1,2})(?:st|nd|rd|th)?,? (\d{4})$/i, handler: function(bits) { var d = new Date(); d.setDate(1); d.setYear(bits[3]); d.setMonth(parseMonth(bits[1])); d.setDate(parseInt(bits[2], 10)); return d; } }, // next Tuesday - this is suspect due to weird meaning of "next" { re: /^next (\w+)$/i, handler: function(bits) { var d = new Date(); var day = d.getDay(); var newDay = parseWeekday(bits[1]); var addDays = newDay - day; if (newDay <= day) { addDays += 7; } d.setDate(d.getDate() + addDays); return d; } }, // last Tuesday { re: /^last (\w+)$/i, handler: function(bits) { throw new Error("Not yet implemented"); } }, // mm/dd/yyyy (American style) { re: /(\d{1,2})\/(\d{1,2})\/(\d{4})/, handler: function(bits) { var d = new Date(); d.setDate(1); d.setYear(bits[3]); d.setMonth(parseInt(bits[1], 10) - 1); // Because months indexed from 0 d.setDate(parseInt(bits[2], 10)); return d; } }, // yyyy-mm-dd (ISO style) { re: /(\d{4})-(\d{1,2})-(\d{1,2})/, handler: function(bits) { var d = new Date(); d.setDate(1); d.setYear(parseInt(bits[1])); d.setMonth(parseInt(bits[2], 10) - 1); d.setDate(parseInt(bits[3], 10)); return d; } }, ]; function parseDateString(s) { for (var i = 0; i < dateParsePatterns.length; i++) { var re = dateParsePatterns[i].re; var handler = dateParsePatterns[i].handler; var bits = re.exec(s); if (bits) { return handler(bits); } } throw new Error("Invalid date string"); } function fmt00(x) { // fmt00: Tags leading zero onto numbers 0 - 9. // Particularly useful for displaying results from Date methods. // if (Math.abs(parseInt(x)) < 10){ x = "0"+ Math.abs(x); } return x; } function parseDateStringISO(s) { try { var d = parseDateString(s); return d.getFullYear() + '-' + (fmt00(d.getMonth() + 1)) + '-' + fmt00(d.getDate()) } catch (e) { return s; } } function magicDate(input) { var messagespan = input.id + 'Msg'; try { var d = parseDateString(input.value); input.value = d.getFullYear() + '-' + (fmt00(d.getMonth() + 1)) + '-' + fmt00(d.getDate()); input.className = ''; // Human readable date if (document.getElementById(messagespan)) { document.getElementById(messagespan).firstChild.nodeValue = d.toDateString(); document.getElementById(messagespan).className = 'normal'; } } catch (e) { input.className = 'error'; var message = e.message; // Fix for IE6 bug if (message.indexOf('is null or not an object') > -1) { message = 'Invalid date string'; } if (document.getElementById(messagespan)) { document.getElementById(messagespan).firstChild.nodeValue = message; document.getElementById(messagespan).className = 'error'; } } }
JavaScript
/* document.getElementsBySelector(selector) - returns an array of element objects from the current document matching the CSS selector. Selectors can contain element names, class names and ids and can be nested. For example: elements = document.getElementsBySelect('div#main p a.external') Will return an array of all 'a' elements with 'external' in their class attribute that are contained inside 'p' elements that are contained inside the 'div' element which has id="main" New in version 0.4: Support for CSS2 and CSS3 attribute selectors: See http://www.w3.org/TR/css3-selectors/#attribute-selectors Version 0.4 - Simon Willison, March 25th 2003 -- Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows -- Opera 7 fails */ function getAllChildren(e) { // Returns all children of element. Workaround required for IE5/Windows. Ugh. return e.all ? e.all : e.getElementsByTagName('*'); } document.getElementsBySelector = function(selector) { // Attempt to fail gracefully in lesser browsers if (!document.getElementsByTagName) { return new Array(); } // Split selector in to tokens var tokens = selector.split(' '); var currentContext = new Array(document); for (var i = 0; i < tokens.length; i++) { token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');; if (token.indexOf('#') > -1) { // Token is an ID selector var bits = token.split('#'); var tagName = bits[0]; var id = bits[1]; var element = document.getElementById(id); if (!element || (tagName && element.nodeName.toLowerCase() != tagName)) { // ID not found or tag with that ID not found, return false. return new Array(); } // Set currentContext to contain just this element currentContext = new Array(element); continue; // Skip to next token } if (token.indexOf('.') > -1) { // Token contains a class selector var bits = token.split('.'); var tagName = bits[0]; var className = bits[1]; if (!tagName) { tagName = '*'; } // Get elements matching tag, filter them for class selector var found = new Array; var foundCount = 0; for (var h = 0; h < currentContext.length; h++) { var elements; if (tagName == '*') { elements = getAllChildren(currentContext[h]); } else { try { elements = currentContext[h].getElementsByTagName(tagName); } catch(e) { elements = []; } } for (var j = 0; j < elements.length; j++) { found[foundCount++] = elements[j]; } } currentContext = new Array; var currentContextIndex = 0; for (var k = 0; k < found.length; k++) { if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) { currentContext[currentContextIndex++] = found[k]; } } continue; // Skip to next token } // Code to deal with attribute selectors if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) { var tagName = RegExp.$1; var attrName = RegExp.$2; var attrOperator = RegExp.$3; var attrValue = RegExp.$4; if (!tagName) { tagName = '*'; } // Grab all of the tagName elements within current context var found = new Array; var foundCount = 0; for (var h = 0; h < currentContext.length; h++) { var elements; if (tagName == '*') { elements = getAllChildren(currentContext[h]); } else { elements = currentContext[h].getElementsByTagName(tagName); } for (var j = 0; j < elements.length; j++) { found[foundCount++] = elements[j]; } } currentContext = new Array; var currentContextIndex = 0; var checkFunction; // This function will be used to filter the elements switch (attrOperator) { case '=': // Equality checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); }; break; case '~': // Match one of space seperated words checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); }; break; case '|': // Match start with value followed by optional hyphen checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); }; break; case '^': // Match starts with value checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); }; break; case '$': // Match ends with value - fails with "Warning" in Opera 7 checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); }; break; case '*': // Match ends with value checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); }; break; default : // Just test for existence of attribute checkFunction = function(e) { return e.getAttribute(attrName); }; } currentContext = new Array; var currentContextIndex = 0; for (var k = 0; k < found.length; k++) { if (checkFunction(found[k])) { currentContext[currentContextIndex++] = found[k]; } } // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue); continue; // Skip to next token } // If we get here, token is JUST an element (not a class or ID selector) tagName = token; var found = new Array; var foundCount = 0; for (var h = 0; h < currentContext.length; h++) { var elements = currentContext[h].getElementsByTagName(tagName); for (var j = 0; j < elements.length; j++) { found[foundCount++] = elements[j]; } } currentContext = found; } return currentContext; } /* That revolting regular expression explained /^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/ \---/ \---/\-------------/ \-------/ | | | | | | | The value | | ~,|,^,$,* or = | Attribute Tag */
JavaScript
(function($) { $.fn.prepopulate = function(dependencies, maxLength) { /* Depends on urlify.js Populates a selected field with the values of the dependent fields, URLifies and shortens the string. dependencies - array of dependent fields id's maxLength - maximum length of the URLify'd string */ return this.each(function() { var field = $(this); field.data('_changed', false); field.change(function() { field.data('_changed', true); }); var populate = function () { // Bail if the fields value has changed if (field.data('_changed') == true) return; var values = []; $.each(dependencies, function(i, field) { if ($(field).val().length > 0) { values.push($(field).val()); } }) field.val(URLify(values.join(' '), maxLength)); }; $(dependencies.join(',')).keyup(populate).change(populate).focus(populate); }); }; })(django.jQuery);
JavaScript
var SelectBox = { cache: new Object(), init: function(id) { var box = document.getElementById(id); var node; SelectBox.cache[id] = new Array(); var cache = SelectBox.cache[id]; for (var i = 0; (node = box.options[i]); i++) { cache.push({value: node.value, text: node.text, displayed: 1}); } }, redisplay: function(id) { // Repopulate HTML select box from cache var box = document.getElementById(id); box.options.length = 0; // clear all options for (var i = 0, j = SelectBox.cache[id].length; i < j; i++) { var node = SelectBox.cache[id][i]; if (node.displayed) { box.options[box.options.length] = new Option(node.text, node.value, false, false); } } }, filter: function(id, text) { // Redisplay the HTML select box, displaying only the choices containing ALL // the words in text. (It's an AND search.) var tokens = text.toLowerCase().split(/\s+/); var node, token; for (var i = 0; (node = SelectBox.cache[id][i]); i++) { node.displayed = 1; for (var j = 0; (token = tokens[j]); j++) { if (node.text.toLowerCase().indexOf(token) == -1) { node.displayed = 0; } } } SelectBox.redisplay(id); }, delete_from_cache: function(id, value) { var node, delete_index = null; for (var i = 0; (node = SelectBox.cache[id][i]); i++) { if (node.value == value) { delete_index = i; break; } } var j = SelectBox.cache[id].length - 1; for (var i = delete_index; i < j; i++) { SelectBox.cache[id][i] = SelectBox.cache[id][i+1]; } SelectBox.cache[id].length--; }, add_to_cache: function(id, option) { SelectBox.cache[id].push({value: option.value, text: option.text, displayed: 1}); }, cache_contains: function(id, value) { // Check if an item is contained in the cache var node; for (var i = 0; (node = SelectBox.cache[id][i]); i++) { if (node.value == value) { return true; } } return false; }, move: function(from, to) { var from_box = document.getElementById(from); var to_box = document.getElementById(to); var option; for (var i = 0; (option = from_box.options[i]); i++) { if (option.selected && SelectBox.cache_contains(from, option.value)) { SelectBox.add_to_cache(to, {value: option.value, text: option.text, displayed: 1}); SelectBox.delete_from_cache(from, option.value); } } SelectBox.redisplay(from); SelectBox.redisplay(to); }, move_all: function(from, to) { var from_box = document.getElementById(from); var to_box = document.getElementById(to); var option; for (var i = 0; (option = from_box.options[i]); i++) { if (SelectBox.cache_contains(from, option.value)) { SelectBox.add_to_cache(to, {value: option.value, text: option.text, displayed: 1}); SelectBox.delete_from_cache(from, option.value); } } SelectBox.redisplay(from); SelectBox.redisplay(to); }, sort: function(id) { SelectBox.cache[id].sort( function(a, b) { a = a.text.toLowerCase(); b = b.text.toLowerCase(); try { if (a > b) return 1; if (a < b) return -1; } catch (e) { // silently fail on IE 'unknown' exception } return 0; } ); }, select_all: function(id) { var box = document.getElementById(id); for (var i = 0; i < box.options.length; i++) { box.options[i].selected = 'selected'; } } }
JavaScript
var LATIN_MAP = { 'À': 'A', 'Á': 'A', 'Â': 'A', 'Ã': 'A', 'Ä': 'A', 'Å': 'A', 'Æ': 'AE', 'Ç': 'C', 'È': 'E', 'É': 'E', 'Ê': 'E', 'Ë': 'E', 'Ì': 'I', 'Í': 'I', 'Î': 'I', 'Ï': 'I', 'Ð': 'D', 'Ñ': 'N', 'Ò': 'O', 'Ó': 'O', 'Ô': 'O', 'Õ': 'O', 'Ö': 'O', 'Ő': 'O', 'Ø': 'O', 'Ù': 'U', 'Ú': 'U', 'Û': 'U', 'Ü': 'U', 'Ű': 'U', 'Ý': 'Y', 'Þ': 'TH', 'ß': 'ss', 'à':'a', 'á':'a', 'â': 'a', 'ã': 'a', 'ä': 'a', 'å': 'a', 'æ': 'ae', 'ç': 'c', 'è': 'e', 'é': 'e', 'ê': 'e', 'ë': 'e', 'ì': 'i', 'í': 'i', 'î': 'i', 'ï': 'i', 'ð': 'd', 'ñ': 'n', 'ò': 'o', 'ó': 'o', 'ô': 'o', 'õ': 'o', 'ö': 'o', 'ő': 'o', 'ø': 'o', 'ù': 'u', 'ú': 'u', 'û': 'u', 'ü': 'u', 'ű': 'u', 'ý': 'y', 'þ': 'th', 'ÿ': 'y' } var LATIN_SYMBOLS_MAP = { '©':'(c)' } var GREEK_MAP = { 'α':'a', 'β':'b', 'γ':'g', 'δ':'d', 'ε':'e', 'ζ':'z', 'η':'h', 'θ':'8', 'ι':'i', 'κ':'k', 'λ':'l', 'μ':'m', 'ν':'n', 'ξ':'3', 'ο':'o', 'π':'p', 'ρ':'r', 'σ':'s', 'τ':'t', 'υ':'y', 'φ':'f', 'χ':'x', 'ψ':'ps', 'ω':'w', 'ά':'a', 'έ':'e', 'ί':'i', 'ό':'o', 'ύ':'y', 'ή':'h', 'ώ':'w', 'ς':'s', 'ϊ':'i', 'ΰ':'y', 'ϋ':'y', 'ΐ':'i', 'Α':'A', 'Β':'B', 'Γ':'G', 'Δ':'D', 'Ε':'E', 'Ζ':'Z', 'Η':'H', 'Θ':'8', 'Ι':'I', 'Κ':'K', 'Λ':'L', 'Μ':'M', 'Ν':'N', 'Ξ':'3', 'Ο':'O', 'Π':'P', 'Ρ':'R', 'Σ':'S', 'Τ':'T', 'Υ':'Y', 'Φ':'F', 'Χ':'X', 'Ψ':'PS', 'Ω':'W', 'Ά':'A', 'Έ':'E', 'Ί':'I', 'Ό':'O', 'Ύ':'Y', 'Ή':'H', 'Ώ':'W', 'Ϊ':'I', 'Ϋ':'Y' } var TURKISH_MAP = { 'ş':'s', 'Ş':'S', 'ı':'i', 'İ':'I', 'ç':'c', 'Ç':'C', 'ü':'u', 'Ü':'U', 'ö':'o', 'Ö':'O', 'ğ':'g', 'Ğ':'G' } var RUSSIAN_MAP = { 'а':'a', 'б':'b', 'в':'v', 'г':'g', 'д':'d', 'е':'e', 'ё':'yo', 'ж':'zh', 'з':'z', 'и':'i', 'й':'j', 'к':'k', 'л':'l', 'м':'m', 'н':'n', 'о':'o', 'п':'p', 'р':'r', 'с':'s', 'т':'t', 'у':'u', 'ф':'f', 'х':'h', 'ц':'c', 'ч':'ch', 'ш':'sh', 'щ':'sh', 'ъ':'', 'ы':'y', 'ь':'', 'э':'e', 'ю':'yu', 'я':'ya', 'А':'A', 'Б':'B', 'В':'V', 'Г':'G', 'Д':'D', 'Е':'E', 'Ё':'Yo', 'Ж':'Zh', 'З':'Z', 'И':'I', 'Й':'J', 'К':'K', 'Л':'L', 'М':'M', 'Н':'N', 'О':'O', 'П':'P', 'Р':'R', 'С':'S', 'Т':'T', 'У':'U', 'Ф':'F', 'Х':'H', 'Ц':'C', 'Ч':'Ch', 'Ш':'Sh', 'Щ':'Sh', 'Ъ':'', 'Ы':'Y', 'Ь':'', 'Э':'E', 'Ю':'Yu', 'Я':'Ya' } var UKRAINIAN_MAP = { 'Є':'Ye', 'І':'I', 'Ї':'Yi', 'Ґ':'G', 'є':'ye', 'і':'i', 'ї':'yi', 'ґ':'g' } var CZECH_MAP = { 'č':'c', 'ď':'d', 'ě':'e', 'ň': 'n', 'ř':'r', 'š':'s', 'ť':'t', 'ů':'u', 'ž':'z', 'Č':'C', 'Ď':'D', 'Ě':'E', 'Ň': 'N', 'Ř':'R', 'Š':'S', 'Ť':'T', 'Ů':'U', 'Ž':'Z' } var POLISH_MAP = { 'ą':'a', 'ć':'c', 'ę':'e', 'ł':'l', 'ń':'n', 'ó':'o', 'ś':'s', 'ź':'z', 'ż':'z', 'Ą':'A', 'Ć':'C', 'Ę':'e', 'Ł':'L', 'Ń':'N', 'Ó':'o', 'Ś':'S', 'Ź':'Z', 'Ż':'Z' } var LATVIAN_MAP = { 'ā':'a', 'č':'c', 'ē':'e', 'ģ':'g', 'ī':'i', 'ķ':'k', 'ļ':'l', 'ņ':'n', 'š':'s', 'ū':'u', 'ž':'z', 'Ā':'A', 'Č':'C', 'Ē':'E', 'Ģ':'G', 'Ī':'i', 'Ķ':'k', 'Ļ':'L', 'Ņ':'N', 'Š':'S', 'Ū':'u', 'Ž':'Z' } var ALL_DOWNCODE_MAPS=new Array() ALL_DOWNCODE_MAPS[0]=LATIN_MAP ALL_DOWNCODE_MAPS[1]=LATIN_SYMBOLS_MAP ALL_DOWNCODE_MAPS[2]=GREEK_MAP ALL_DOWNCODE_MAPS[3]=TURKISH_MAP ALL_DOWNCODE_MAPS[4]=RUSSIAN_MAP ALL_DOWNCODE_MAPS[5]=UKRAINIAN_MAP ALL_DOWNCODE_MAPS[6]=CZECH_MAP ALL_DOWNCODE_MAPS[7]=POLISH_MAP ALL_DOWNCODE_MAPS[8]=LATVIAN_MAP var Downcoder = new Object(); Downcoder.Initialize = function() { if (Downcoder.map) // already made return ; Downcoder.map ={} Downcoder.chars = '' ; for(var i in ALL_DOWNCODE_MAPS) { var lookup = ALL_DOWNCODE_MAPS[i] for (var c in lookup) { Downcoder.map[c] = lookup[c] ; Downcoder.chars += c ; } } Downcoder.regex = new RegExp('[' + Downcoder.chars + ']|[^' + Downcoder.chars + ']+','g') ; } downcode= function( slug ) { Downcoder.Initialize() ; var downcoded ="" var pieces = slug.match(Downcoder.regex); if(pieces) { for (var i = 0 ; i < pieces.length ; i++) { if (pieces[i].length == 1) { var mapped = Downcoder.map[pieces[i]] ; if (mapped != null) { downcoded+=mapped; continue ; } } downcoded+=pieces[i]; } } else { downcoded = slug; } return downcoded; } function URLify(s, num_chars) { // changes, e.g., "Petty theft" to "petty_theft" // remove all these words from the string before urlifying s = downcode(s); removelist = ["a", "an", "as", "at", "before", "but", "by", "for", "from", "is", "in", "into", "like", "of", "off", "on", "onto", "per", "since", "than", "the", "this", "that", "to", "up", "via", "with"]; r = new RegExp('\\b(' + removelist.join('|') + ')\\b', 'gi'); s = s.replace(r, ''); // if downcode doesn't hit, the char will be stripped here s = s.replace(/[^-\w\s]/g, ''); // remove unneeded chars s = s.replace(/^\s+|\s+$/g, ''); // trim leading/trailing spaces s = s.replace(/[-\s]+/g, '-'); // convert spaces to hyphens s = s.toLowerCase(); // convert to lowercase return s.substring(0, num_chars);// trim to first num_chars chars }
JavaScript
/* SelectFilter2 - Turns a multiple-select box into a filter interface. Different than SelectFilter because this is coupled to the admin framework. Requires core.js, SelectBox.js and addevent.js. */ function findForm(node) { // returns the node of the form containing the given node if (node.tagName.toLowerCase() != 'form') { return findForm(node.parentNode); } return node; } var SelectFilter = { init: function(field_id, field_name, is_stacked, admin_media_prefix) { var from_box = document.getElementById(field_id); from_box.id += '_from'; // change its ID from_box.className = 'filtered'; // Remove <p class="info">, because it just gets in the way. var ps = from_box.parentNode.getElementsByTagName('p'); for (var i=0; i<ps.length; i++) { from_box.parentNode.removeChild(ps[i]); } // <div class="selector"> or <div class="selector stacked"> var selector_div = quickElement('div', from_box.parentNode); selector_div.className = is_stacked ? 'selector stacked' : 'selector'; // <div class="selector-available"> var selector_available = quickElement('div', selector_div, ''); selector_available.className = 'selector-available'; quickElement('h2', selector_available, interpolate(gettext('Available %s'), [field_name])); var filter_p = quickElement('p', selector_available, ''); filter_p.className = 'selector-filter'; quickElement('img', filter_p, '', 'src', admin_media_prefix + 'img/admin/selector-search.gif'); filter_p.appendChild(document.createTextNode(' ')); var filter_input = quickElement('input', filter_p, '', 'type', 'text'); filter_input.id = field_id + '_input'; selector_available.appendChild(from_box); var choose_all = quickElement('a', selector_available, gettext('Choose all'), 'href', 'javascript: (function(){ SelectBox.move_all("' + field_id + '_from", "' + field_id + '_to"); })()'); choose_all.className = 'selector-chooseall'; // <ul class="selector-chooser"> var selector_chooser = quickElement('ul', selector_div, ''); selector_chooser.className = 'selector-chooser'; var add_link = quickElement('a', quickElement('li', selector_chooser, ''), gettext('Add'), 'href', 'javascript: (function(){ SelectBox.move("' + field_id + '_from","' + field_id + '_to");})()'); add_link.className = 'selector-add'; var remove_link = quickElement('a', quickElement('li', selector_chooser, ''), gettext('Remove'), 'href', 'javascript: (function(){ SelectBox.move("' + field_id + '_to","' + field_id + '_from");})()'); remove_link.className = 'selector-remove'; // <div class="selector-chosen"> var selector_chosen = quickElement('div', selector_div, ''); selector_chosen.className = 'selector-chosen'; quickElement('h2', selector_chosen, interpolate(gettext('Chosen %s'), [field_name])); var selector_filter = quickElement('p', selector_chosen, gettext('Select your choice(s) and click ')); selector_filter.className = 'selector-filter'; quickElement('img', selector_filter, '', 'src', admin_media_prefix + (is_stacked ? 'img/admin/selector_stacked-add.gif':'img/admin/selector-add.gif'), 'alt', 'Add'); var to_box = quickElement('select', selector_chosen, '', 'id', field_id + '_to', 'multiple', 'multiple', 'size', from_box.size, 'name', from_box.getAttribute('name')); to_box.className = 'filtered'; var clear_all = quickElement('a', selector_chosen, gettext('Clear all'), 'href', 'javascript: (function() { SelectBox.move_all("' + field_id + '_to", "' + field_id + '_from");})()'); clear_all.className = 'selector-clearall'; from_box.setAttribute('name', from_box.getAttribute('name') + '_old'); // Set up the JavaScript event handlers for the select box filter interface addEvent(filter_input, 'keyup', function(e) { SelectFilter.filter_key_up(e, field_id); }); addEvent(filter_input, 'keydown', function(e) { SelectFilter.filter_key_down(e, field_id); }); addEvent(from_box, 'dblclick', function() { SelectBox.move(field_id + '_from', field_id + '_to'); }); addEvent(to_box, 'dblclick', function() { SelectBox.move(field_id + '_to', field_id + '_from'); }); addEvent(findForm(from_box), 'submit', function() { SelectBox.select_all(field_id + '_to'); }); SelectBox.init(field_id + '_from'); SelectBox.init(field_id + '_to'); // Move selected from_box options to to_box SelectBox.move(field_id + '_from', field_id + '_to'); }, filter_key_up: function(event, field_id) { from = document.getElementById(field_id + '_from'); // don't submit form if user pressed Enter if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) { from.selectedIndex = 0; SelectBox.move(field_id + '_from', field_id + '_to'); from.selectedIndex = 0; return false; } var temp = from.selectedIndex; SelectBox.filter(field_id + '_from', document.getElementById(field_id + '_input').value); from.selectedIndex = temp; return true; }, filter_key_down: function(event, field_id) { from = document.getElementById(field_id + '_from'); // right arrow -- move across if ((event.which && event.which == 39) || (event.keyCode && event.keyCode == 39)) { var old_index = from.selectedIndex; SelectBox.move(field_id + '_from', field_id + '_to'); from.selectedIndex = (old_index == from.length) ? from.length - 1 : old_index; return false; } // down arrow -- wrap around if ((event.which && event.which == 40) || (event.keyCode && event.keyCode == 40)) { from.selectedIndex = (from.length == from.selectedIndex + 1) ? 0 : from.selectedIndex + 1; } // up arrow -- wrap around if ((event.which && event.which == 38) || (event.keyCode && event.keyCode == 38)) { from.selectedIndex = (from.selectedIndex == 0) ? from.length - 1 : from.selectedIndex - 1; } return true; } }
JavaScript
/* calendar.js - Calendar functions by Adrian Holovaty */ function removeChildren(a) { // "a" is reference to an object while (a.hasChildNodes()) a.removeChild(a.lastChild); } // quickElement(tagType, parentReference, textInChildNode, [, attribute, attributeValue ...]); function quickElement() { var obj = document.createElement(arguments[0]); if (arguments[2] != '' && arguments[2] != null) { var textNode = document.createTextNode(arguments[2]); obj.appendChild(textNode); } var len = arguments.length; for (var i = 3; i < len; i += 2) { obj.setAttribute(arguments[i], arguments[i+1]); } arguments[1].appendChild(obj); return obj; } // CalendarNamespace -- Provides a collection of HTML calendar-related helper functions var CalendarNamespace = { monthsOfYear: gettext('January February March April May June July August September October November December').split(' '), daysOfWeek: gettext('S M T W T F S').split(' '), isLeapYear: function(year) { return (((year % 4)==0) && ((year % 100)!=0) || ((year % 400)==0)); }, getDaysInMonth: function(month,year) { var days; if (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12) { days = 31; } else if (month==4 || month==6 || month==9 || month==11) { days = 30; } else if (month==2 && CalendarNamespace.isLeapYear(year)) { days = 29; } else { days = 28; } return days; }, draw: function(month, year, div_id, callback) { // month = 1-12, year = 1-9999 month = parseInt(month); year = parseInt(year); var calDiv = document.getElementById(div_id); removeChildren(calDiv); var calTable = document.createElement('table'); quickElement('caption', calTable, CalendarNamespace.monthsOfYear[month-1] + ' ' + year); var tableBody = quickElement('tbody', calTable); // Draw days-of-week header var tableRow = quickElement('tr', tableBody); for (var i = 0; i < 7; i++) { quickElement('th', tableRow, CalendarNamespace.daysOfWeek[i]); } var startingPos = new Date(year, month-1, 1).getDay(); var days = CalendarNamespace.getDaysInMonth(month, year); // Draw blanks before first of month tableRow = quickElement('tr', tableBody); for (var i = 0; i < startingPos; i++) { var _cell = quickElement('td', tableRow, ' '); _cell.style.backgroundColor = '#f3f3f3'; } // Draw days of month var currentDay = 1; for (var i = startingPos; currentDay <= days; i++) { if (i%7 == 0 && currentDay != 1) { tableRow = quickElement('tr', tableBody); } var cell = quickElement('td', tableRow, ''); quickElement('a', cell, currentDay, 'href', 'javascript:void(' + callback + '('+year+','+month+','+currentDay+'));'); currentDay++; } // Draw blanks after end of month (optional, but makes for valid code) while (tableRow.childNodes.length < 7) { var _cell = quickElement('td', tableRow, ' '); _cell.style.backgroundColor = '#f3f3f3'; } calDiv.appendChild(calTable); } } // Calendar -- A calendar instance function Calendar(div_id, callback) { // div_id (string) is the ID of the element in which the calendar will // be displayed // callback (string) is the name of a JavaScript function that will be // called with the parameters (year, month, day) when a day in the // calendar is clicked this.div_id = div_id; this.callback = callback; this.today = new Date(); this.currentMonth = this.today.getMonth() + 1; this.currentYear = this.today.getFullYear(); } Calendar.prototype = { drawCurrent: function() { CalendarNamespace.draw(this.currentMonth, this.currentYear, this.div_id, this.callback); }, drawDate: function(month, year) { this.currentMonth = month; this.currentYear = year; this.drawCurrent(); }, drawPreviousMonth: function() { if (this.currentMonth == 1) { this.currentMonth = 12; this.currentYear--; } else { this.currentMonth--; } this.drawCurrent(); }, drawNextMonth: function() { if (this.currentMonth == 12) { this.currentMonth = 1; this.currentYear++; } else { this.currentMonth++; } this.drawCurrent(); }, drawPreviousYear: function() { this.currentYear--; this.drawCurrent(); }, drawNextYear: function() { this.currentYear++; this.drawCurrent(); } }
JavaScript
// Core javascript helper functions // basic browser identification & version var isOpera = (navigator.userAgent.indexOf("Opera")>=0) && parseFloat(navigator.appVersion); var isIE = ((document.all) && (!isOpera)) && parseFloat(navigator.appVersion.split("MSIE ")[1].split(";")[0]); // Cross-browser event handlers. function addEvent(obj, evType, fn) { if (obj.addEventListener) { obj.addEventListener(evType, fn, false); return true; } else if (obj.attachEvent) { var r = obj.attachEvent("on" + evType, fn); return r; } else { return false; } } function removeEvent(obj, evType, fn) { if (obj.removeEventListener) { obj.removeEventListener(evType, fn, false); return true; } else if (obj.detachEvent) { obj.detachEvent("on" + evType, fn); return true; } else { return false; } } // quickElement(tagType, parentReference, textInChildNode, [, attribute, attributeValue ...]); function quickElement() { var obj = document.createElement(arguments[0]); if (arguments[2] != '' && arguments[2] != null) { var textNode = document.createTextNode(arguments[2]); obj.appendChild(textNode); } var len = arguments.length; for (var i = 3; i < len; i += 2) { obj.setAttribute(arguments[i], arguments[i+1]); } arguments[1].appendChild(obj); return obj; } // ---------------------------------------------------------------------------- // Cross-browser xmlhttp object // from http://jibbering.com/2002/4/httprequest.html // ---------------------------------------------------------------------------- var xmlhttp; /*@cc_on @*/ /*@if (@_jscript_version >= 5) try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { xmlhttp = false; } } @else xmlhttp = false; @end @*/ if (!xmlhttp && typeof XMLHttpRequest != 'undefined') { xmlhttp = new XMLHttpRequest(); } // ---------------------------------------------------------------------------- // Find-position functions by PPK // See http://www.quirksmode.org/js/findpos.html // ---------------------------------------------------------------------------- function findPosX(obj) { var curleft = 0; if (obj.offsetParent) { while (obj.offsetParent) { curleft += obj.offsetLeft - ((isOpera) ? 0 : obj.scrollLeft); obj = obj.offsetParent; } // IE offsetParent does not include the top-level if (isIE && obj.parentElement){ curleft += obj.offsetLeft - obj.scrollLeft; } } else if (obj.x) { curleft += obj.x; } return curleft; } function findPosY(obj) { var curtop = 0; if (obj.offsetParent) { while (obj.offsetParent) { curtop += obj.offsetTop - ((isOpera) ? 0 : obj.scrollTop); obj = obj.offsetParent; } // IE offsetParent does not include the top-level if (isIE && obj.parentElement){ curtop += obj.offsetTop - obj.scrollTop; } } else if (obj.y) { curtop += obj.y; } return curtop; } //----------------------------------------------------------------------------- // Date object extensions // ---------------------------------------------------------------------------- Date.prototype.getCorrectYear = function() { // Date.getYear() is unreliable -- // see http://www.quirksmode.org/js/introdate.html#year var y = this.getYear() % 100; return (y < 38) ? y + 2000 : y + 1900; } Date.prototype.getTwoDigitMonth = function() { return (this.getMonth() < 9) ? '0' + (this.getMonth()+1) : (this.getMonth()+1); } Date.prototype.getTwoDigitDate = function() { return (this.getDate() < 10) ? '0' + this.getDate() : this.getDate(); } Date.prototype.getTwoDigitHour = function() { return (this.getHours() < 10) ? '0' + this.getHours() : this.getHours(); } Date.prototype.getTwoDigitMinute = function() { return (this.getMinutes() < 10) ? '0' + this.getMinutes() : this.getMinutes(); } Date.prototype.getTwoDigitSecond = function() { return (this.getSeconds() < 10) ? '0' + this.getSeconds() : this.getSeconds(); } Date.prototype.getISODate = function() { return this.getCorrectYear() + '-' + this.getTwoDigitMonth() + '-' + this.getTwoDigitDate(); } Date.prototype.getHourMinute = function() { return this.getTwoDigitHour() + ':' + this.getTwoDigitMinute(); } Date.prototype.getHourMinuteSecond = function() { return this.getTwoDigitHour() + ':' + this.getTwoDigitMinute() + ':' + this.getTwoDigitSecond(); } // ---------------------------------------------------------------------------- // String object extensions // ---------------------------------------------------------------------------- String.prototype.pad_left = function(pad_length, pad_string) { var new_string = this; for (var i = 0; new_string.length < pad_length; i++) { new_string = pad_string + new_string; } return new_string; } // ---------------------------------------------------------------------------- // Get the computed style for and element // ---------------------------------------------------------------------------- function getStyle(oElm, strCssRule){ var strValue = ""; if(document.defaultView && document.defaultView.getComputedStyle){ strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule); } else if(oElm.currentStyle){ strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){ return p1.toUpperCase(); }); strValue = oElm.currentStyle[strCssRule]; } return strValue; }
JavaScript
addEvent(window, 'load', reorder_init); var lis; var top = 0; var left = 0; var height = 30; function reorder_init() { lis = document.getElementsBySelector('ul#orderthese li'); var input = document.getElementsBySelector('input[name=order_]')[0]; setOrder(input.value.split(',')); input.disabled = true; draw(); // Now initialise the dragging behaviour var limit = (lis.length - 1) * height; for (var i = 0; i < lis.length; i++) { var li = lis[i]; var img = document.getElementById('handle'+li.id); li.style.zIndex = 1; Drag.init(img, li, left + 10, left + 10, top + 10, top + 10 + limit); li.onDragStart = startDrag; li.onDragEnd = endDrag; img.style.cursor = 'move'; } } function submitOrderForm() { var inputOrder = document.getElementsBySelector('input[name=order_]')[0]; inputOrder.value = getOrder(); inputOrder.disabled=false; } function startDrag() { this.style.zIndex = '10'; this.className = 'dragging'; } function endDrag(x, y) { this.style.zIndex = '1'; this.className = ''; // Work out how far along it has been dropped, using x co-ordinate var oldIndex = this.index; var newIndex = Math.round((y - 10 - top) / height); // 'Snap' to the correct position this.style.top = (10 + top + newIndex * height) + 'px'; this.index = newIndex; moveItem(oldIndex, newIndex); } function moveItem(oldIndex, newIndex) { // Swaps two items, adjusts the index and left co-ord for all others if (oldIndex == newIndex) { return; // Nothing to swap; } var direction, lo, hi; if (newIndex > oldIndex) { lo = oldIndex; hi = newIndex; direction = -1; } else { direction = 1; hi = oldIndex; lo = newIndex; } var lis2 = new Array(); // We will build the new order in this array for (var i = 0; i < lis.length; i++) { if (i < lo || i > hi) { // Position of items not between the indexes is unaffected lis2[i] = lis[i]; continue; } else if (i == newIndex) { lis2[i] = lis[oldIndex]; continue; } else { // Item is between the two indexes - move it along 1 lis2[i] = lis[i - direction]; } } // Re-index everything reIndex(lis2); lis = lis2; draw(); // document.getElementById('hiddenOrder').value = getOrder(); document.getElementsBySelector('input[name=order_]')[0].value = getOrder(); } function reIndex(lis) { for (var i = 0; i < lis.length; i++) { lis[i].index = i; } } function draw() { for (var i = 0; i < lis.length; i++) { var li = lis[i]; li.index = i; li.style.position = 'absolute'; li.style.left = (10 + left) + 'px'; li.style.top = (10 + top + (i * height)) + 'px'; } } function getOrder() { var order = new Array(lis.length); for (var i = 0; i < lis.length; i++) { order[i] = lis[i].id.substring(1, 100); } return order.join(','); } function setOrder(id_list) { /* Set the current order to match the lsit of IDs */ var temp_lis = new Array(); for (var i = 0; i < id_list.length; i++) { var id = 'p' + id_list[i]; temp_lis[temp_lis.length] = document.getElementById(id); } reIndex(temp_lis); lis = temp_lis; draw(); } function addEvent(elm, evType, fn, useCapture) // addEvent and removeEvent // cross-browser event handling for IE5+, NS6 and Mozilla // By Scott Andrew { if (elm.addEventListener){ elm.addEventListener(evType, fn, useCapture); return true; } else if (elm.attachEvent){ var r = elm.attachEvent("on"+evType, fn); return r; } else { elm['on'+evType] = fn; } }
JavaScript
// Handles related-objects functionality: lookup link for raw_id_fields // and Add Another links. function html_unescape(text) { // Unescape a string that was escaped using django.utils.html.escape. text = text.replace(/&lt;/g, '<'); text = text.replace(/&gt;/g, '>'); text = text.replace(/&quot;/g, '"'); text = text.replace(/&#39;/g, "'"); text = text.replace(/&amp;/g, '&'); return text; } // IE doesn't accept periods or dashes in the window name, but the element IDs // we use to generate popup window names may contain them, therefore we map them // to allowed characters in a reversible way so that we can locate the correct // element when the popup window is dismissed. function id_to_windowname(text) { text = text.replace(/\./g, '__dot__'); text = text.replace(/\-/g, '__dash__'); return text; } function windowname_to_id(text) { text = text.replace(/__dot__/g, '.'); text = text.replace(/__dash__/g, '-'); return text; } function showRelatedObjectLookupPopup(triggeringLink) { var name = triggeringLink.id.replace(/^lookup_/, ''); name = id_to_windowname(name); var href; if (triggeringLink.href.search(/\?/) >= 0) { href = triggeringLink.href + '&pop=1'; } else { href = triggeringLink.href + '?pop=1'; } var win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes'); win.focus(); return false; } function dismissRelatedLookupPopup(win, chosenId) { var name = windowname_to_id(win.name); var elem = document.getElementById(name); if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) { elem.value += ',' + chosenId; } else { document.getElementById(name).value = chosenId; } win.close(); } function showAddAnotherPopup(triggeringLink) { var name = triggeringLink.id.replace(/^add_/, ''); name = id_to_windowname(name); href = triggeringLink.href if (href.indexOf('?') == -1) { href += '?_popup=1'; } else { href += '&_popup=1'; } var win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes'); win.focus(); return false; } function dismissAddAnotherPopup(win, newId, newRepr) { // newId and newRepr are expected to have previously been escaped by // django.utils.html.escape. newId = html_unescape(newId); newRepr = html_unescape(newRepr); var name = windowname_to_id(win.name); var elem = document.getElementById(name); if (elem) { if (elem.nodeName == 'SELECT') { var o = new Option(newRepr, newId); elem.options[elem.options.length] = o; o.selected = true; } else if (elem.nodeName == 'INPUT') { if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) { elem.value += ',' + newId; } else { elem.value = newId; } } } else { var toId = name + "_to"; elem = document.getElementById(toId); var o = new Option(newRepr, newId); SelectBox.add_to_cache(toId, o); SelectBox.redisplay(toId); } win.close(); }
JavaScript
// Finds all fieldsets with class="collapse", collapses them, and gives each // one a "Show" link that uncollapses it. The "Show" link becomes a "Hide" // link when the fieldset is visible. function findForm(node) { // returns the node of the form containing the given node if (node.tagName.toLowerCase() != 'form') { return findForm(node.parentNode); } return node; } var CollapsedFieldsets = { collapse_re: /\bcollapse\b/, // Class of fieldsets that should be dealt with. collapsed_re: /\bcollapsed\b/, // Class that fieldsets get when they're hidden. collapsed_class: 'collapsed', init: function() { var fieldsets = document.getElementsByTagName('fieldset'); var collapsed_seen = false; for (var i = 0, fs; fs = fieldsets[i]; i++) { // Collapse this fieldset if it has the correct class, and if it // doesn't have any errors. (Collapsing shouldn't apply in the case // of error messages.) if (fs.className.match(CollapsedFieldsets.collapse_re) && !CollapsedFieldsets.fieldset_has_errors(fs)) { collapsed_seen = true; // Give it an additional class, used by CSS to hide it. fs.className += ' ' + CollapsedFieldsets.collapsed_class; // (<a id="fieldsetcollapser3" class="collapse-toggle" href="#">Show</a>) var collapse_link = document.createElement('a'); collapse_link.className = 'collapse-toggle'; collapse_link.id = 'fieldsetcollapser' + i; collapse_link.onclick = new Function('CollapsedFieldsets.show('+i+'); return false;'); collapse_link.href = '#'; collapse_link.innerHTML = gettext('Show'); var h2 = fs.getElementsByTagName('h2')[0]; h2.appendChild(document.createTextNode(' (')); h2.appendChild(collapse_link); h2.appendChild(document.createTextNode(')')); } } if (collapsed_seen) { // Expand all collapsed fieldsets when form is submitted. addEvent(findForm(document.getElementsByTagName('fieldset')[0]), 'submit', function() { CollapsedFieldsets.uncollapse_all(); }); } }, fieldset_has_errors: function(fs) { // Returns true if any fields in the fieldset have validation errors. var divs = fs.getElementsByTagName('div'); for (var i=0; i<divs.length; i++) { if (divs[i].className.match(/\berrors\b/)) { return true; } } return false; }, show: function(fieldset_index) { var fs = document.getElementsByTagName('fieldset')[fieldset_index]; // Remove the class name that causes the "display: none". fs.className = fs.className.replace(CollapsedFieldsets.collapsed_re, ''); // Toggle the "Show" link to a "Hide" link var collapse_link = document.getElementById('fieldsetcollapser' + fieldset_index); collapse_link.onclick = new Function('CollapsedFieldsets.hide('+fieldset_index+'); return false;'); collapse_link.innerHTML = gettext('Hide'); }, hide: function(fieldset_index) { var fs = document.getElementsByTagName('fieldset')[fieldset_index]; // Add the class name that causes the "display: none". fs.className += ' ' + CollapsedFieldsets.collapsed_class; // Toggle the "Hide" link to a "Show" link var collapse_link = document.getElementById('fieldsetcollapser' + fieldset_index); collapse_link.onclick = new Function('CollapsedFieldsets.show('+fieldset_index+'); return false;'); collapse_link.innerHTML = gettext('Show'); }, uncollapse_all: function() { var fieldsets = document.getElementsByTagName('fieldset'); for (var i=0; i<fieldsets.length; i++) { if (fieldsets[i].className.match(CollapsedFieldsets.collapsed_re)) { CollapsedFieldsets.show(i); } } } } addEvent(window, 'load', CollapsedFieldsets.init);
JavaScript
// Inserts shortcut buttons after all of the following: // <input type="text" class="vDateField"> // <input type="text" class="vTimeField"> var DateTimeShortcuts = { calendars: [], calendarInputs: [], clockInputs: [], calendarDivName1: 'calendarbox', // name of calendar <div> that gets toggled calendarDivName2: 'calendarin', // name of <div> that contains calendar calendarLinkName: 'calendarlink',// name of the link that is used to toggle clockDivName: 'clockbox', // name of clock <div> that gets toggled clockLinkName: 'clocklink', // name of the link that is used to toggle admin_media_prefix: '', init: function() { // Deduce admin_media_prefix by looking at the <script>s in the // current document and finding the URL of *this* module. var scripts = document.getElementsByTagName('script'); for (var i=0; i<scripts.length; i++) { if (scripts[i].src.match(/DateTimeShortcuts/)) { var idx = scripts[i].src.indexOf('js/admin/DateTimeShortcuts'); DateTimeShortcuts.admin_media_prefix = scripts[i].src.substring(0, idx); break; } } var inputs = document.getElementsByTagName('input'); for (i=0; i<inputs.length; i++) { var inp = inputs[i]; if (inp.getAttribute('type') == 'text' && inp.className.match(/vTimeField/)) { DateTimeShortcuts.addClock(inp); } else if (inp.getAttribute('type') == 'text' && inp.className.match(/vDateField/)) { DateTimeShortcuts.addCalendar(inp); } } }, // Add clock widget to a given field addClock: function(inp) { var num = DateTimeShortcuts.clockInputs.length; DateTimeShortcuts.clockInputs[num] = inp; // Shortcut links (clock icon and "Now" link) var shortcuts_span = document.createElement('span'); inp.parentNode.insertBefore(shortcuts_span, inp.nextSibling); var now_link = document.createElement('a'); now_link.setAttribute('href', "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date().getHourMinuteSecond());"); now_link.appendChild(document.createTextNode(gettext('Now'))); var clock_link = document.createElement('a'); clock_link.setAttribute('href', 'javascript:DateTimeShortcuts.openClock(' + num + ');'); clock_link.id = DateTimeShortcuts.clockLinkName + num; quickElement('img', clock_link, '', 'src', DateTimeShortcuts.admin_media_prefix + 'img/admin/icon_clock.gif', 'alt', gettext('Clock')); shortcuts_span.appendChild(document.createTextNode('\240')); shortcuts_span.appendChild(now_link); shortcuts_span.appendChild(document.createTextNode('\240|\240')); shortcuts_span.appendChild(clock_link); // Create clock link div // // Markup looks like: // <div id="clockbox1" class="clockbox module"> // <h2>Choose a time</h2> // <ul class="timelist"> // <li><a href="#">Now</a></li> // <li><a href="#">Midnight</a></li> // <li><a href="#">6 a.m.</a></li> // <li><a href="#">Noon</a></li> // </ul> // <p class="calendar-cancel"><a href="#">Cancel</a></p> // </div> var clock_box = document.createElement('div'); clock_box.style.display = 'none'; clock_box.style.position = 'absolute'; clock_box.className = 'clockbox module'; clock_box.setAttribute('id', DateTimeShortcuts.clockDivName + num); document.body.appendChild(clock_box); addEvent(clock_box, 'click', DateTimeShortcuts.cancelEventPropagation); quickElement('h2', clock_box, gettext('Choose a time')); time_list = quickElement('ul', clock_box, ''); time_list.className = 'timelist'; quickElement("a", quickElement("li", time_list, ""), gettext("Now"), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date().getHourMinuteSecond());") quickElement("a", quickElement("li", time_list, ""), gettext("Midnight"), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", '00:00:00');") quickElement("a", quickElement("li", time_list, ""), gettext("6 a.m."), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", '06:00:00');") quickElement("a", quickElement("li", time_list, ""), gettext("Noon"), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", '12:00:00');") cancel_p = quickElement('p', clock_box, ''); cancel_p.className = 'calendar-cancel'; quickElement('a', cancel_p, gettext('Cancel'), 'href', 'javascript:DateTimeShortcuts.dismissClock(' + num + ');'); }, openClock: function(num) { var clock_box = document.getElementById(DateTimeShortcuts.clockDivName+num) var clock_link = document.getElementById(DateTimeShortcuts.clockLinkName+num) // Recalculate the clockbox position // is it left-to-right or right-to-left layout ? if (getStyle(document.body,'direction')!='rtl') { clock_box.style.left = findPosX(clock_link) + 17 + 'px'; } else { // since style's width is in em, it'd be tough to calculate // px value of it. let's use an estimated px for now // TODO: IE returns wrong value for findPosX when in rtl mode // (it returns as it was left aligned), needs to be fixed. clock_box.style.left = findPosX(clock_link) - 110 + 'px'; } clock_box.style.top = findPosY(clock_link) - 30 + 'px'; // Show the clock box clock_box.style.display = 'block'; addEvent(window.document, 'click', function() { DateTimeShortcuts.dismissClock(num); return true; }); }, dismissClock: function(num) { document.getElementById(DateTimeShortcuts.clockDivName + num).style.display = 'none'; window.document.onclick = null; }, handleClockQuicklink: function(num, val) { DateTimeShortcuts.clockInputs[num].value = val; DateTimeShortcuts.dismissClock(num); }, // Add calendar widget to a given field. addCalendar: function(inp) { var num = DateTimeShortcuts.calendars.length; DateTimeShortcuts.calendarInputs[num] = inp; // Shortcut links (calendar icon and "Today" link) var shortcuts_span = document.createElement('span'); inp.parentNode.insertBefore(shortcuts_span, inp.nextSibling); var today_link = document.createElement('a'); today_link.setAttribute('href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', 0);'); today_link.appendChild(document.createTextNode(gettext('Today'))); var cal_link = document.createElement('a'); cal_link.setAttribute('href', 'javascript:DateTimeShortcuts.openCalendar(' + num + ');'); cal_link.id = DateTimeShortcuts.calendarLinkName + num; quickElement('img', cal_link, '', 'src', DateTimeShortcuts.admin_media_prefix + 'img/admin/icon_calendar.gif', 'alt', gettext('Calendar')); shortcuts_span.appendChild(document.createTextNode('\240')); shortcuts_span.appendChild(today_link); shortcuts_span.appendChild(document.createTextNode('\240|\240')); shortcuts_span.appendChild(cal_link); // Create calendarbox div. // // Markup looks like: // // <div id="calendarbox3" class="calendarbox module"> // <h2> // <a href="#" class="link-previous">&lsaquo;</a> // <a href="#" class="link-next">&rsaquo;</a> February 2003 // </h2> // <div class="calendar" id="calendarin3"> // <!-- (cal) --> // </div> // <div class="calendar-shortcuts"> // <a href="#">Yesterday</a> | <a href="#">Today</a> | <a href="#">Tomorrow</a> // </div> // <p class="calendar-cancel"><a href="#">Cancel</a></p> // </div> var cal_box = document.createElement('div'); cal_box.style.display = 'none'; cal_box.style.position = 'absolute'; cal_box.className = 'calendarbox module'; cal_box.setAttribute('id', DateTimeShortcuts.calendarDivName1 + num); document.body.appendChild(cal_box); addEvent(cal_box, 'click', DateTimeShortcuts.cancelEventPropagation); // next-prev links var cal_nav = quickElement('div', cal_box, ''); var cal_nav_prev = quickElement('a', cal_nav, '<', 'href', 'javascript:DateTimeShortcuts.drawPrev('+num+');'); cal_nav_prev.className = 'calendarnav-previous'; var cal_nav_next = quickElement('a', cal_nav, '>', 'href', 'javascript:DateTimeShortcuts.drawNext('+num+');'); cal_nav_next.className = 'calendarnav-next'; // main box var cal_main = quickElement('div', cal_box, '', 'id', DateTimeShortcuts.calendarDivName2 + num); cal_main.className = 'calendar'; DateTimeShortcuts.calendars[num] = new Calendar(DateTimeShortcuts.calendarDivName2 + num, DateTimeShortcuts.handleCalendarCallback(num)); DateTimeShortcuts.calendars[num].drawCurrent(); // calendar shortcuts var shortcuts = quickElement('div', cal_box, ''); shortcuts.className = 'calendar-shortcuts'; quickElement('a', shortcuts, gettext('Yesterday'), 'href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', -1);'); shortcuts.appendChild(document.createTextNode('\240|\240')); quickElement('a', shortcuts, gettext('Today'), 'href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', 0);'); shortcuts.appendChild(document.createTextNode('\240|\240')); quickElement('a', shortcuts, gettext('Tomorrow'), 'href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', +1);'); // cancel bar var cancel_p = quickElement('p', cal_box, ''); cancel_p.className = 'calendar-cancel'; quickElement('a', cancel_p, gettext('Cancel'), 'href', 'javascript:DateTimeShortcuts.dismissCalendar(' + num + ');'); }, openCalendar: function(num) { var cal_box = document.getElementById(DateTimeShortcuts.calendarDivName1+num) var cal_link = document.getElementById(DateTimeShortcuts.calendarLinkName+num) var inp = DateTimeShortcuts.calendarInputs[num]; // Determine if the current value in the input has a valid date. // If so, draw the calendar with that date's year and month. if (inp.value) { var date_parts = inp.value.split('-'); var year = date_parts[0]; var month = parseFloat(date_parts[1]); if (year.match(/\d\d\d\d/) && month >= 1 && month <= 12) { DateTimeShortcuts.calendars[num].drawDate(month, year); } } // Recalculate the clockbox position // is it left-to-right or right-to-left layout ? if (getStyle(document.body,'direction')!='rtl') { cal_box.style.left = findPosX(cal_link) + 17 + 'px'; } else { // since style's width is in em, it'd be tough to calculate // px value of it. let's use an estimated px for now // TODO: IE returns wrong value for findPosX when in rtl mode // (it returns as it was left aligned), needs to be fixed. cal_box.style.left = findPosX(cal_link) - 180 + 'px'; } cal_box.style.top = findPosY(cal_link) - 75 + 'px'; cal_box.style.display = 'block'; addEvent(window.document, 'click', function() { DateTimeShortcuts.dismissCalendar(num); return true; }); }, dismissCalendar: function(num) { document.getElementById(DateTimeShortcuts.calendarDivName1+num).style.display = 'none'; window.document.onclick = null; }, drawPrev: function(num) { DateTimeShortcuts.calendars[num].drawPreviousMonth(); }, drawNext: function(num) { DateTimeShortcuts.calendars[num].drawNextMonth(); }, handleCalendarCallback: function(num) { return "function(y, m, d) { DateTimeShortcuts.calendarInputs["+num+"].value = y+'-'+(m<10?'0':'')+m+'-'+(d<10?'0':'')+d; document.getElementById(DateTimeShortcuts.calendarDivName1+"+num+").style.display='none';}"; }, handleCalendarQuickLink: function(num, offset) { var d = new Date(); d.setDate(d.getDate() + offset) DateTimeShortcuts.calendarInputs[num].value = d.getISODate(); DateTimeShortcuts.dismissCalendar(num); }, cancelEventPropagation: function(e) { if (!e) e = window.event; e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation(); } } addEvent(window, 'load', DateTimeShortcuts.init);
JavaScript
var Actions = { init: function() { var selectAll = document.getElementById('action-toggle'); if (selectAll) { selectAll.style.display = 'inline'; addEvent(selectAll, 'click', function() { Actions.checker(selectAll.checked); }); } var changelistTable = document.getElementsBySelector('#changelist table')[0]; if (changelistTable) { addEvent(changelistTable, 'click', function(e) { if (!e) { var e = window.event; } var target = e.target ? e.target : e.srcElement; if (target.nodeType == 3) { target = target.parentNode; } if (target.className == 'action-select') { var tr = target.parentNode.parentNode; Actions.toggleRow(tr, target.checked); } }); } }, toggleRow: function(tr, checked) { if (checked && tr.className.indexOf('selected') == -1) { tr.className += ' selected'; } else if (!checked) { tr.className = tr.className.replace(' selected', ''); } }, checker: function(checked) { var actionCheckboxes = document.getElementsBySelector('tr input.action-select'); for(var i = 0; i < actionCheckboxes.length; i++) { actionCheckboxes[i].checked = checked; Actions.toggleRow(actionCheckboxes[i].parentNode.parentNode, checked); } } }; addEvent(window, 'load', Actions.init);
JavaScript
var timeParsePatterns = [ // 9 { re: /^\d{1,2}$/i, handler: function(bits) { if (bits[0].length == 1) { return '0' + bits[0] + ':00'; } else { return bits[0] + ':00'; } } }, // 13:00 { re: /^\d{2}[:.]\d{2}$/i, handler: function(bits) { return bits[0].replace('.', ':'); } }, // 9:00 { re: /^\d[:.]\d{2}$/i, handler: function(bits) { return '0' + bits[0].replace('.', ':'); } }, // 3 am / 3 a.m. / 3am { re: /^(\d+)\s*([ap])(?:.?m.?)?$/i, handler: function(bits) { var hour = parseInt(bits[1]); if (hour == 12) { hour = 0; } if (bits[2].toLowerCase() == 'p') { if (hour == 12) { hour = 0; } return (hour + 12) + ':00'; } else { if (hour < 10) { return '0' + hour + ':00'; } else { return hour + ':00'; } } } }, // 3.30 am / 3:15 a.m. / 3.00am { re: /^(\d+)[.:](\d{2})\s*([ap]).?m.?$/i, handler: function(bits) { var hour = parseInt(bits[1]); var mins = parseInt(bits[2]); if (mins < 10) { mins = '0' + mins; } if (hour == 12) { hour = 0; } if (bits[3].toLowerCase() == 'p') { if (hour == 12) { hour = 0; } return (hour + 12) + ':' + mins; } else { if (hour < 10) { return '0' + hour + ':' + mins; } else { return hour + ':' + mins; } } } }, // noon { re: /^no/i, handler: function(bits) { return '12:00'; } }, // midnight { re: /^mid/i, handler: function(bits) { return '00:00'; } } ]; function parseTimeString(s) { for (var i = 0; i < timeParsePatterns.length; i++) { var re = timeParsePatterns[i].re; var handler = timeParsePatterns[i].handler; var bits = re.exec(s); if (bits) { return handler(bits); } } return s; }
JavaScript
/* 'Magic' date parsing, by Simon Willison (6th October 2003) http://simon.incutio.com/archive/2003/10/06/betterDateInput Adapted for 6newslawrence.com, 28th January 2004 */ /* Finds the index of the first occurence of item in the array, or -1 if not found */ if (typeof Array.prototype.indexOf == 'undefined') { Array.prototype.indexOf = function(item) { var len = this.length; for (var i = 0; i < len; i++) { if (this[i] == item) { return i; } } return -1; }; } /* Returns an array of items judged 'true' by the passed in test function */ if (typeof Array.prototype.filter == 'undefined') { Array.prototype.filter = function(test) { var matches = []; var len = this.length; for (var i = 0; i < len; i++) { if (test(this[i])) { matches[matches.length] = this[i]; } } return matches; }; } var monthNames = gettext("January February March April May June July August September October November December").split(" "); var weekdayNames = gettext("Sunday Monday Tuesday Wednesday Thursday Friday Saturday").split(" "); /* Takes a string, returns the index of the month matching that string, throws an error if 0 or more than 1 matches */ function parseMonth(month) { var matches = monthNames.filter(function(item) { return new RegExp("^" + month, "i").test(item); }); if (matches.length == 0) { throw new Error("Invalid month string"); } if (matches.length > 1) { throw new Error("Ambiguous month"); } return monthNames.indexOf(matches[0]); } /* Same as parseMonth but for days of the week */ function parseWeekday(weekday) { var matches = weekdayNames.filter(function(item) { return new RegExp("^" + weekday, "i").test(item); }); if (matches.length == 0) { throw new Error("Invalid day string"); } if (matches.length > 1) { throw new Error("Ambiguous weekday"); } return weekdayNames.indexOf(matches[0]); } /* Array of objects, each has 're', a regular expression and 'handler', a function for creating a date from something that matches the regular expression. Handlers may throw errors if string is unparseable. */ var dateParsePatterns = [ // Today { re: /^tod/i, handler: function() { return new Date(); } }, // Tomorrow { re: /^tom/i, handler: function() { var d = new Date(); d.setDate(d.getDate() + 1); return d; } }, // Yesterday { re: /^yes/i, handler: function() { var d = new Date(); d.setDate(d.getDate() - 1); return d; } }, // 4th { re: /^(\d{1,2})(st|nd|rd|th)?$/i, handler: function(bits) { var d = new Date(); d.setDate(parseInt(bits[1], 10)); return d; } }, // 4th Jan { re: /^(\d{1,2})(?:st|nd|rd|th)? (\w+)$/i, handler: function(bits) { var d = new Date(); d.setDate(parseInt(bits[1], 10)); d.setMonth(parseMonth(bits[2])); return d; } }, // 4th Jan 2003 { re: /^(\d{1,2})(?:st|nd|rd|th)? (\w+),? (\d{4})$/i, handler: function(bits) { var d = new Date(); d.setDate(parseInt(bits[1], 10)); d.setMonth(parseMonth(bits[2])); d.setYear(bits[3]); return d; } }, // Jan 4th { re: /^(\w+) (\d{1,2})(?:st|nd|rd|th)?$/i, handler: function(bits) { var d = new Date(); d.setDate(parseInt(bits[2], 10)); d.setMonth(parseMonth(bits[1])); return d; } }, // Jan 4th 2003 { re: /^(\w+) (\d{1,2})(?:st|nd|rd|th)?,? (\d{4})$/i, handler: function(bits) { var d = new Date(); d.setDate(parseInt(bits[2], 10)); d.setMonth(parseMonth(bits[1])); d.setYear(bits[3]); return d; } }, // next Tuesday - this is suspect due to weird meaning of "next" { re: /^next (\w+)$/i, handler: function(bits) { var d = new Date(); var day = d.getDay(); var newDay = parseWeekday(bits[1]); var addDays = newDay - day; if (newDay <= day) { addDays += 7; } d.setDate(d.getDate() + addDays); return d; } }, // last Tuesday { re: /^last (\w+)$/i, handler: function(bits) { throw new Error("Not yet implemented"); } }, // mm/dd/yyyy (American style) { re: /(\d{1,2})\/(\d{1,2})\/(\d{4})/, handler: function(bits) { var d = new Date(); d.setYear(bits[3]); d.setDate(parseInt(bits[2], 10)); d.setMonth(parseInt(bits[1], 10) - 1); // Because months indexed from 0 return d; } }, // yyyy-mm-dd (ISO style) { re: /(\d{4})-(\d{1,2})-(\d{1,2})/, handler: function(bits) { var d = new Date(); d.setYear(parseInt(bits[1])); d.setMonth(parseInt(bits[2], 10) - 1); d.setDate(parseInt(bits[3], 10)); return d; } }, ]; function parseDateString(s) { for (var i = 0; i < dateParsePatterns.length; i++) { var re = dateParsePatterns[i].re; var handler = dateParsePatterns[i].handler; var bits = re.exec(s); if (bits) { return handler(bits); } } throw new Error("Invalid date string"); } function fmt00(x) { // fmt00: Tags leading zero onto numbers 0 - 9. // Particularly useful for displaying results from Date methods. // if (Math.abs(parseInt(x)) < 10){ x = "0"+ Math.abs(x); } return x; } function parseDateStringISO(s) { try { var d = parseDateString(s); return d.getFullYear() + '-' + (fmt00(d.getMonth() + 1)) + '-' + fmt00(d.getDate()) } catch (e) { return s; } } function magicDate(input) { var messagespan = input.id + 'Msg'; try { var d = parseDateString(input.value); input.value = d.getFullYear() + '-' + (fmt00(d.getMonth() + 1)) + '-' + fmt00(d.getDate()); input.className = ''; // Human readable date if (document.getElementById(messagespan)) { document.getElementById(messagespan).firstChild.nodeValue = d.toDateString(); document.getElementById(messagespan).className = 'normal'; } } catch (e) { input.className = 'error'; var message = e.message; // Fix for IE6 bug if (message.indexOf('is null or not an object') > -1) { message = 'Invalid date string'; } if (document.getElementById(messagespan)) { document.getElementById(messagespan).firstChild.nodeValue = message; document.getElementById(messagespan).className = 'error'; } } }
JavaScript
/* document.getElementsBySelector(selector) - returns an array of element objects from the current document matching the CSS selector. Selectors can contain element names, class names and ids and can be nested. For example: elements = document.getElementsBySelect('div#main p a.external') Will return an array of all 'a' elements with 'external' in their class attribute that are contained inside 'p' elements that are contained inside the 'div' element which has id="main" New in version 0.4: Support for CSS2 and CSS3 attribute selectors: See http://www.w3.org/TR/css3-selectors/#attribute-selectors Version 0.4 - Simon Willison, March 25th 2003 -- Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows -- Opera 7 fails */ function getAllChildren(e) { // Returns all children of element. Workaround required for IE5/Windows. Ugh. return e.all ? e.all : e.getElementsByTagName('*'); } document.getElementsBySelector = function(selector) { // Attempt to fail gracefully in lesser browsers if (!document.getElementsByTagName) { return new Array(); } // Split selector in to tokens var tokens = selector.split(' '); var currentContext = new Array(document); for (var i = 0; i < tokens.length; i++) { token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');; if (token.indexOf('#') > -1) { // Token is an ID selector var bits = token.split('#'); var tagName = bits[0]; var id = bits[1]; var element = document.getElementById(id); if (!element || (tagName && element.nodeName.toLowerCase() != tagName)) { // ID not found or tag with that ID not found, return false. return new Array(); } // Set currentContext to contain just this element currentContext = new Array(element); continue; // Skip to next token } if (token.indexOf('.') > -1) { // Token contains a class selector var bits = token.split('.'); var tagName = bits[0]; var className = bits[1]; if (!tagName) { tagName = '*'; } // Get elements matching tag, filter them for class selector var found = new Array; var foundCount = 0; for (var h = 0; h < currentContext.length; h++) { var elements; if (tagName == '*') { elements = getAllChildren(currentContext[h]); } else { try { elements = currentContext[h].getElementsByTagName(tagName); } catch(e) { elements = []; } } for (var j = 0; j < elements.length; j++) { found[foundCount++] = elements[j]; } } currentContext = new Array; var currentContextIndex = 0; for (var k = 0; k < found.length; k++) { if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) { currentContext[currentContextIndex++] = found[k]; } } continue; // Skip to next token } // Code to deal with attribute selectors if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) { var tagName = RegExp.$1; var attrName = RegExp.$2; var attrOperator = RegExp.$3; var attrValue = RegExp.$4; if (!tagName) { tagName = '*'; } // Grab all of the tagName elements within current context var found = new Array; var foundCount = 0; for (var h = 0; h < currentContext.length; h++) { var elements; if (tagName == '*') { elements = getAllChildren(currentContext[h]); } else { elements = currentContext[h].getElementsByTagName(tagName); } for (var j = 0; j < elements.length; j++) { found[foundCount++] = elements[j]; } } currentContext = new Array; var currentContextIndex = 0; var checkFunction; // This function will be used to filter the elements switch (attrOperator) { case '=': // Equality checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); }; break; case '~': // Match one of space seperated words checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); }; break; case '|': // Match start with value followed by optional hyphen checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); }; break; case '^': // Match starts with value checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); }; break; case '$': // Match ends with value - fails with "Warning" in Opera 7 checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); }; break; case '*': // Match ends with value checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); }; break; default : // Just test for existence of attribute checkFunction = function(e) { return e.getAttribute(attrName); }; } currentContext = new Array; var currentContextIndex = 0; for (var k = 0; k < found.length; k++) { if (checkFunction(found[k])) { currentContext[currentContextIndex++] = found[k]; } } // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue); continue; // Skip to next token } // If we get here, token is JUST an element (not a class or ID selector) tagName = token; var found = new Array; var foundCount = 0; for (var h = 0; h < currentContext.length; h++) { var elements = currentContext[h].getElementsByTagName(tagName); for (var j = 0; j < elements.length; j++) { found[foundCount++] = elements[j]; } } currentContext = found; } return currentContext; } /* That revolting regular expression explained /^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/ \---/ \---/\-------------/ \-------/ | | | | | | | The value | | ~,|,^,$,* or = | Attribute Tag */
JavaScript
var SelectBox = { cache: new Object(), init: function(id) { var box = document.getElementById(id); var node; SelectBox.cache[id] = new Array(); var cache = SelectBox.cache[id]; for (var i = 0; (node = box.options[i]); i++) { cache.push({value: node.value, text: node.text, displayed: 1}); } }, redisplay: function(id) { // Repopulate HTML select box from cache var box = document.getElementById(id); box.options.length = 0; // clear all options for (var i = 0, j = SelectBox.cache[id].length; i < j; i++) { var node = SelectBox.cache[id][i]; if (node.displayed) { box.options[box.options.length] = new Option(node.text, node.value, false, false); } } }, filter: function(id, text) { // Redisplay the HTML select box, displaying only the choices containing ALL // the words in text. (It's an AND search.) var tokens = text.toLowerCase().split(/\s+/); var node, token; for (var i = 0; (node = SelectBox.cache[id][i]); i++) { node.displayed = 1; for (var j = 0; (token = tokens[j]); j++) { if (node.text.toLowerCase().indexOf(token) == -1) { node.displayed = 0; } } } SelectBox.redisplay(id); }, delete_from_cache: function(id, value) { var node, delete_index = null; for (var i = 0; (node = SelectBox.cache[id][i]); i++) { if (node.value == value) { delete_index = i; break; } } var j = SelectBox.cache[id].length - 1; for (var i = delete_index; i < j; i++) { SelectBox.cache[id][i] = SelectBox.cache[id][i+1]; } SelectBox.cache[id].length--; }, add_to_cache: function(id, option) { SelectBox.cache[id].push({value: option.value, text: option.text, displayed: 1}); }, cache_contains: function(id, value) { // Check if an item is contained in the cache var node; for (var i = 0; (node = SelectBox.cache[id][i]); i++) { if (node.value == value) { return true; } } return false; }, move: function(from, to) { var from_box = document.getElementById(from); var to_box = document.getElementById(to); var option; for (var i = 0; (option = from_box.options[i]); i++) { if (option.selected && SelectBox.cache_contains(from, option.value)) { SelectBox.add_to_cache(to, {value: option.value, text: option.text, displayed: 1}); SelectBox.delete_from_cache(from, option.value); } } SelectBox.redisplay(from); SelectBox.redisplay(to); }, move_all: function(from, to) { var from_box = document.getElementById(from); var to_box = document.getElementById(to); var option; for (var i = 0; (option = from_box.options[i]); i++) { if (SelectBox.cache_contains(from, option.value)) { SelectBox.add_to_cache(to, {value: option.value, text: option.text, displayed: 1}); SelectBox.delete_from_cache(from, option.value); } } SelectBox.redisplay(from); SelectBox.redisplay(to); }, sort: function(id) { SelectBox.cache[id].sort( function(a, b) { a = a.text.toLowerCase(); b = b.text.toLowerCase(); try { if (a > b) return 1; if (a < b) return -1; } catch (e) { // silently fail on IE 'unknown' exception } return 0; } ); }, select_all: function(id) { var box = document.getElementById(id); for (var i = 0; i < box.options.length; i++) { box.options[i].selected = 'selected'; } } }
JavaScript
var LATIN_MAP = { 'À': 'A', 'Á': 'A', 'Â': 'A', 'Ã': 'A', 'Ä': 'A', 'Å': 'A', 'Æ': 'AE', 'Ç': 'C', 'È': 'E', 'É': 'E', 'Ê': 'E', 'Ë': 'E', 'Ì': 'I', 'Í': 'I', 'Î': 'I', 'Ï': 'I', 'Ð': 'D', 'Ñ': 'N', 'Ò': 'O', 'Ó': 'O', 'Ô': 'O', 'Õ': 'O', 'Ö': 'O', 'Ő': 'O', 'Ø': 'O', 'Ù': 'U', 'Ú': 'U', 'Û': 'U', 'Ü': 'U', 'Ű': 'U', 'Ý': 'Y', 'Þ': 'TH', 'ß': 'ss', 'à':'a', 'á':'a', 'â': 'a', 'ã': 'a', 'ä': 'a', 'å': 'a', 'æ': 'ae', 'ç': 'c', 'è': 'e', 'é': 'e', 'ê': 'e', 'ë': 'e', 'ì': 'i', 'í': 'i', 'î': 'i', 'ï': 'i', 'ð': 'd', 'ñ': 'n', 'ò': 'o', 'ó': 'o', 'ô': 'o', 'õ': 'o', 'ö': 'o', 'ő': 'o', 'ø': 'o', 'ù': 'u', 'ú': 'u', 'û': 'u', 'ü': 'u', 'ű': 'u', 'ý': 'y', 'þ': 'th', 'ÿ': 'y' } var LATIN_SYMBOLS_MAP = { '©':'(c)' } var GREEK_MAP = { 'α':'a', 'β':'b', 'γ':'g', 'δ':'d', 'ε':'e', 'ζ':'z', 'η':'h', 'θ':'8', 'ι':'i', 'κ':'k', 'λ':'l', 'μ':'m', 'ν':'n', 'ξ':'3', 'ο':'o', 'π':'p', 'ρ':'r', 'σ':'s', 'τ':'t', 'υ':'y', 'φ':'f', 'χ':'x', 'ψ':'ps', 'ω':'w', 'ά':'a', 'έ':'e', 'ί':'i', 'ό':'o', 'ύ':'y', 'ή':'h', 'ώ':'w', 'ς':'s', 'ϊ':'i', 'ΰ':'y', 'ϋ':'y', 'ΐ':'i', 'Α':'A', 'Β':'B', 'Γ':'G', 'Δ':'D', 'Ε':'E', 'Ζ':'Z', 'Η':'H', 'Θ':'8', 'Ι':'I', 'Κ':'K', 'Λ':'L', 'Μ':'M', 'Ν':'N', 'Ξ':'3', 'Ο':'O', 'Π':'P', 'Ρ':'R', 'Σ':'S', 'Τ':'T', 'Υ':'Y', 'Φ':'F', 'Χ':'X', 'Ψ':'PS', 'Ω':'W', 'Ά':'A', 'Έ':'E', 'Ί':'I', 'Ό':'O', 'Ύ':'Y', 'Ή':'H', 'Ώ':'W', 'Ϊ':'I', 'Ϋ':'Y' } var TURKISH_MAP = { 'ş':'s', 'Ş':'S', 'ı':'i', 'İ':'I', 'ç':'c', 'Ç':'C', 'ü':'u', 'Ü':'U', 'ö':'o', 'Ö':'O', 'ğ':'g', 'Ğ':'G' } var RUSSIAN_MAP = { 'а':'a', 'б':'b', 'в':'v', 'г':'g', 'д':'d', 'е':'e', 'ё':'yo', 'ж':'zh', 'з':'z', 'и':'i', 'й':'j', 'к':'k', 'л':'l', 'м':'m', 'н':'n', 'о':'o', 'п':'p', 'р':'r', 'с':'s', 'т':'t', 'у':'u', 'ф':'f', 'х':'h', 'ц':'c', 'ч':'ch', 'ш':'sh', 'щ':'sh', 'ъ':'', 'ы':'y', 'ь':'', 'э':'e', 'ю':'yu', 'я':'ya', 'А':'A', 'Б':'B', 'В':'V', 'Г':'G', 'Д':'D', 'Е':'E', 'Ё':'Yo', 'Ж':'Zh', 'З':'Z', 'И':'I', 'Й':'J', 'К':'K', 'Л':'L', 'М':'M', 'Н':'N', 'О':'O', 'П':'P', 'Р':'R', 'С':'S', 'Т':'T', 'У':'U', 'Ф':'F', 'Х':'H', 'Ц':'C', 'Ч':'Ch', 'Ш':'Sh', 'Щ':'Sh', 'Ъ':'', 'Ы':'Y', 'Ь':'', 'Э':'E', 'Ю':'Yu', 'Я':'Ya' } var UKRAINIAN_MAP = { 'Є':'Ye', 'І':'I', 'Ї':'Yi', 'Ґ':'G', 'є':'ye', 'і':'i', 'ї':'yi', 'ґ':'g' } var CZECH_MAP = { 'č':'c', 'ď':'d', 'ě':'e', 'ň': 'n', 'ř':'r', 'š':'s', 'ť':'t', 'ů':'u', 'ž':'z', 'Č':'C', 'Ď':'D', 'Ě':'E', 'Ň': 'N', 'Ř':'R', 'Š':'S', 'Ť':'T', 'Ů':'U', 'Ž':'Z' } var POLISH_MAP = { 'ą':'a', 'ć':'c', 'ę':'e', 'ł':'l', 'ń':'n', 'ó':'o', 'ś':'s', 'ź':'z', 'ż':'z', 'Ą':'A', 'Ć':'C', 'Ę':'e', 'Ł':'L', 'Ń':'N', 'Ó':'o', 'Ś':'S', 'Ź':'Z', 'Ż':'Z' } var LATVIAN_MAP = { 'ā':'a', 'č':'c', 'ē':'e', 'ģ':'g', 'ī':'i', 'ķ':'k', 'ļ':'l', 'ņ':'n', 'š':'s', 'ū':'u', 'ž':'z', 'Ā':'A', 'Č':'C', 'Ē':'E', 'Ģ':'G', 'Ī':'i', 'Ķ':'k', 'Ļ':'L', 'Ņ':'N', 'Š':'S', 'Ū':'u', 'Ž':'Z' } var ALL_DOWNCODE_MAPS=new Array() ALL_DOWNCODE_MAPS[0]=LATIN_MAP ALL_DOWNCODE_MAPS[1]=LATIN_SYMBOLS_MAP ALL_DOWNCODE_MAPS[2]=GREEK_MAP ALL_DOWNCODE_MAPS[3]=TURKISH_MAP ALL_DOWNCODE_MAPS[4]=RUSSIAN_MAP ALL_DOWNCODE_MAPS[5]=UKRAINIAN_MAP ALL_DOWNCODE_MAPS[6]=CZECH_MAP ALL_DOWNCODE_MAPS[7]=POLISH_MAP ALL_DOWNCODE_MAPS[8]=LATVIAN_MAP var Downcoder = new Object(); Downcoder.Initialize = function() { if (Downcoder.map) // already made return ; Downcoder.map ={} Downcoder.chars = '' ; for(var i in ALL_DOWNCODE_MAPS) { var lookup = ALL_DOWNCODE_MAPS[i] for (var c in lookup) { Downcoder.map[c] = lookup[c] ; Downcoder.chars += c ; } } Downcoder.regex = new RegExp('[' + Downcoder.chars + ']|[^' + Downcoder.chars + ']+','g') ; } downcode= function( slug ) { Downcoder.Initialize() ; var downcoded ="" var pieces = slug.match(Downcoder.regex); if(pieces) { for (var i = 0 ; i < pieces.length ; i++) { if (pieces[i].length == 1) { var mapped = Downcoder.map[pieces[i]] ; if (mapped != null) { downcoded+=mapped; continue ; } } downcoded+=pieces[i]; } } else { downcoded = slug; } return downcoded; } function URLify(s, num_chars) { // changes, e.g., "Petty theft" to "petty_theft" // remove all these words from the string before urlifying s = downcode(s); removelist = ["a", "an", "as", "at", "before", "but", "by", "for", "from", "is", "in", "into", "like", "of", "off", "on", "onto", "per", "since", "than", "the", "this", "that", "to", "up", "via", "with"]; r = new RegExp('\\b(' + removelist.join('|') + ')\\b', 'gi'); s = s.replace(r, ''); // if downcode doesn't hit, the char will be stripped here s = s.replace(/[^-\w\s]/g, ''); // remove unneeded chars s = s.replace(/^\s+|\s+$/g, ''); // trim leading/trailing spaces s = s.replace(/[-\s]+/g, '-'); // convert spaces to hyphens s = s.toLowerCase(); // convert to lowercase return s.substring(0, num_chars);// trim to first num_chars chars }
JavaScript
/* SelectFilter2 - Turns a multiple-select box into a filter interface. Different than SelectFilter because this is coupled to the admin framework. Requires core.js, SelectBox.js and addevent.js. */ function findForm(node) { // returns the node of the form containing the given node if (node.tagName.toLowerCase() != 'form') { return findForm(node.parentNode); } return node; } var SelectFilter = { init: function(field_id, field_name, is_stacked, admin_media_prefix) { if (field_id.match(/__prefix__/)){ // Don't intialize on empty forms. return; } var from_box = document.getElementById(field_id); from_box.id += '_from'; // change its ID from_box.className = 'filtered'; var ps = from_box.parentNode.getElementsByTagName('p'); for (var i=0; i<ps.length; i++) { if (ps[i].className.indexOf("info") != -1) { // Remove <p class="info">, because it just gets in the way. from_box.parentNode.removeChild(ps[i]); } else if (ps[i].className.indexOf("help") != -1) { // Move help text up to the top so it isn't below the select // boxes or wrapped off on the side to the right of the add // button: from_box.parentNode.insertBefore(ps[i], from_box.parentNode.firstChild); } } // <div class="selector"> or <div class="selector stacked"> var selector_div = quickElement('div', from_box.parentNode); selector_div.className = is_stacked ? 'selector stacked' : 'selector'; // <div class="selector-available"> var selector_available = quickElement('div', selector_div, ''); selector_available.className = 'selector-available'; quickElement('h2', selector_available, interpolate(gettext('Available %s'), [field_name])); var filter_p = quickElement('p', selector_available, ''); filter_p.className = 'selector-filter'; var search_filter_label = quickElement('label', filter_p, '', 'for', field_id + "_input", 'style', 'width:16px;padding:2px'); var search_selector_img = quickElement('img', search_filter_label, '', 'src', admin_media_prefix + 'img/admin/selector-search.gif'); search_selector_img.alt = gettext("Filter"); filter_p.appendChild(document.createTextNode(' ')); var filter_input = quickElement('input', filter_p, '', 'type', 'text'); filter_input.id = field_id + '_input'; selector_available.appendChild(from_box); var choose_all = quickElement('a', selector_available, gettext('Choose all'), 'href', 'javascript: (function(){ SelectBox.move_all("' + field_id + '_from", "' + field_id + '_to"); })()'); choose_all.className = 'selector-chooseall'; // <ul class="selector-chooser"> var selector_chooser = quickElement('ul', selector_div, ''); selector_chooser.className = 'selector-chooser'; var add_link = quickElement('a', quickElement('li', selector_chooser, ''), gettext('Add'), 'href', 'javascript: (function(){ SelectBox.move("' + field_id + '_from","' + field_id + '_to");})()'); add_link.className = 'selector-add'; var remove_link = quickElement('a', quickElement('li', selector_chooser, ''), gettext('Remove'), 'href', 'javascript: (function(){ SelectBox.move("' + field_id + '_to","' + field_id + '_from");})()'); remove_link.className = 'selector-remove'; // <div class="selector-chosen"> var selector_chosen = quickElement('div', selector_div, ''); selector_chosen.className = 'selector-chosen'; quickElement('h2', selector_chosen, interpolate(gettext('Chosen %s'), [field_name])); var selector_filter = quickElement('p', selector_chosen, gettext('Select your choice(s) and click ')); selector_filter.className = 'selector-filter'; quickElement('img', selector_filter, '', 'src', admin_media_prefix + (is_stacked ? 'img/admin/selector_stacked-add.gif':'img/admin/selector-add.gif'), 'alt', 'Add'); var to_box = quickElement('select', selector_chosen, '', 'id', field_id + '_to', 'multiple', 'multiple', 'size', from_box.size, 'name', from_box.getAttribute('name')); to_box.className = 'filtered'; var clear_all = quickElement('a', selector_chosen, gettext('Clear all'), 'href', 'javascript: (function() { SelectBox.move_all("' + field_id + '_to", "' + field_id + '_from");})()'); clear_all.className = 'selector-clearall'; from_box.setAttribute('name', from_box.getAttribute('name') + '_old'); // Set up the JavaScript event handlers for the select box filter interface addEvent(filter_input, 'keyup', function(e) { SelectFilter.filter_key_up(e, field_id); }); addEvent(filter_input, 'keydown', function(e) { SelectFilter.filter_key_down(e, field_id); }); addEvent(from_box, 'dblclick', function() { SelectBox.move(field_id + '_from', field_id + '_to'); }); addEvent(to_box, 'dblclick', function() { SelectBox.move(field_id + '_to', field_id + '_from'); }); addEvent(findForm(from_box), 'submit', function() { SelectBox.select_all(field_id + '_to'); }); SelectBox.init(field_id + '_from'); SelectBox.init(field_id + '_to'); // Move selected from_box options to to_box SelectBox.move(field_id + '_from', field_id + '_to'); }, filter_key_up: function(event, field_id) { from = document.getElementById(field_id + '_from'); // don't submit form if user pressed Enter if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) { from.selectedIndex = 0; SelectBox.move(field_id + '_from', field_id + '_to'); from.selectedIndex = 0; return false; } var temp = from.selectedIndex; SelectBox.filter(field_id + '_from', document.getElementById(field_id + '_input').value); from.selectedIndex = temp; return true; }, filter_key_down: function(event, field_id) { from = document.getElementById(field_id + '_from'); // right arrow -- move across if ((event.which && event.which == 39) || (event.keyCode && event.keyCode == 39)) { var old_index = from.selectedIndex; SelectBox.move(field_id + '_from', field_id + '_to'); from.selectedIndex = (old_index == from.length) ? from.length - 1 : old_index; return false; } // down arrow -- wrap around if ((event.which && event.which == 40) || (event.keyCode && event.keyCode == 40)) { from.selectedIndex = (from.length == from.selectedIndex + 1) ? 0 : from.selectedIndex + 1; } // up arrow -- wrap around if ((event.which && event.which == 38) || (event.keyCode && event.keyCode == 38)) { from.selectedIndex = (from.selectedIndex == 0) ? from.length - 1 : from.selectedIndex - 1; } return true; } }
JavaScript
/** * Django admin inlines * * Based on jQuery Formset 1.1 * @author Stanislaus Madueke (stan DOT madueke AT gmail DOT com) * @requires jQuery 1.2.6 or later * * Copyright (c) 2009, Stanislaus Madueke * All rights reserved. * * Spiced up with Code from Zain Memon's GSoC project 2009 * and modified for Django by Jannis Leidel * * Licensed under the New BSD License * See: http://www.opensource.org/licenses/bsd-license.php */ (function($) { $.fn.formset = function(opts) { var options = $.extend({}, $.fn.formset.defaults, opts); var updateElementIndex = function(el, prefix, ndx) { var id_regex = new RegExp("(" + prefix + "-(\\d+|__prefix__))"); var replacement = prefix + "-" + ndx; if ($(el).attr("for")) { $(el).attr("for", $(el).attr("for").replace(id_regex, replacement)); } if (el.id) { el.id = el.id.replace(id_regex, replacement); } if (el.name) { el.name = el.name.replace(id_regex, replacement); } }; var totalForms = $("#id_" + options.prefix + "-TOTAL_FORMS").attr("autocomplete", "off"); var nextIndex = parseInt(totalForms.val()); var maxForms = $("#id_" + options.prefix + "-MAX_NUM_FORMS").attr("autocomplete", "off"); // only show the add button if we are allowed to add more items, // note that max_num = None translates to a blank string. var showAddButton = maxForms.val() == '' || (maxForms.val()-totalForms.val()) > 0; $(this).each(function(i) { $(this).not("." + options.emptyCssClass).addClass(options.formCssClass); }); if ($(this).length && showAddButton) { var addButton; if ($(this).attr("tagName") == "TR") { // If forms are laid out as table rows, insert the // "add" button in a new table row: var numCols = this.eq(0).children().length; $(this).parent().append('<tr class="' + options.addCssClass + '"><td colspan="' + numCols + '"><a href="javascript:void(0)">' + options.addText + "</a></tr>"); addButton = $(this).parent().find("tr:last a"); } else { // Otherwise, insert it immediately after the last form: $(this).filter(":last").after('<div class="' + options.addCssClass + '"><a href="javascript:void(0)">' + options.addText + "</a></div>"); addButton = $(this).filter(":last").next().find("a"); } addButton.click(function() { var totalForms = $("#id_" + options.prefix + "-TOTAL_FORMS"); var template = $("#" + options.prefix + "-empty"); var row = template.clone(true); row.removeClass(options.emptyCssClass) .addClass(options.formCssClass) .attr("id", options.prefix + "-" + nextIndex); if (row.is("tr")) { // If the forms are laid out in table rows, insert // the remove button into the last table cell: row.children(":last").append('<div><a class="' + options.deleteCssClass +'" href="javascript:void(0)">' + options.deleteText + "</a></div>"); } else if (row.is("ul") || row.is("ol")) { // If they're laid out as an ordered/unordered list, // insert an <li> after the last list item: row.append('<li><a class="' + options.deleteCssClass +'" href="javascript:void(0)">' + options.deleteText + "</a></li>"); } else { // Otherwise, just insert the remove button as the // last child element of the form's container: row.children(":first").append('<span><a class="' + options.deleteCssClass + '" href="javascript:void(0)">' + options.deleteText + "</a></span>"); } row.find("*").each(function() { updateElementIndex(this, options.prefix, totalForms.val()); }); // Insert the new form when it has been fully edited row.insertBefore($(template)); // Update number of total forms $(totalForms).val(parseInt(totalForms.val()) + 1); nextIndex += 1; // Hide add button in case we've hit the max, except we want to add infinitely if ((maxForms.val() != '') && (maxForms.val()-totalForms.val()) <= 0) { addButton.parent().hide(); } // The delete button of each row triggers a bunch of other things row.find("a." + options.deleteCssClass).click(function() { // Remove the parent form containing this button: var row = $(this).parents("." + options.formCssClass); row.remove(); nextIndex -= 1; // If a post-delete callback was provided, call it with the deleted form: if (options.removed) { options.removed(row); } // Update the TOTAL_FORMS form count. var forms = $("." + options.formCssClass); $("#id_" + options.prefix + "-TOTAL_FORMS").val(forms.length); // Show add button again once we drop below max if ((maxForms.val() == '') || (maxForms.val()-forms.length) > 0) { addButton.parent().show(); } // Also, update names and ids for all remaining form controls // so they remain in sequence: for (var i=0, formCount=forms.length; i<formCount; i++) { updateElementIndex($(forms).get(i), options.prefix, i); $(forms.get(i)).find("*").each(function() { updateElementIndex(this, options.prefix, i); }); } return false; }); // If a post-add callback was supplied, call it with the added form: if (options.added) { options.added(row); } return false; }); } return this; } /* Setup plugin defaults */ $.fn.formset.defaults = { prefix: "form", // The form prefix for your django formset addText: "add another", // Text for the add link deleteText: "remove", // Text for the delete link addCssClass: "add-row", // CSS class applied to the add link deleteCssClass: "delete-row", // CSS class applied to the delete link emptyCssClass: "empty-row", // CSS class applied to the empty row formCssClass: "dynamic-form", // CSS class applied to each form in a formset added: null, // Function called each time a new form is added removed: null // Function called each time a form is deleted } })(django.jQuery);
JavaScript
/* calendar.js - Calendar functions by Adrian Holovaty */ function removeChildren(a) { // "a" is reference to an object while (a.hasChildNodes()) a.removeChild(a.lastChild); } // quickElement(tagType, parentReference, textInChildNode, [, attribute, attributeValue ...]); function quickElement() { var obj = document.createElement(arguments[0]); if (arguments[2] != '' && arguments[2] != null) { var textNode = document.createTextNode(arguments[2]); obj.appendChild(textNode); } var len = arguments.length; for (var i = 3; i < len; i += 2) { obj.setAttribute(arguments[i], arguments[i+1]); } arguments[1].appendChild(obj); return obj; } // CalendarNamespace -- Provides a collection of HTML calendar-related helper functions var CalendarNamespace = { monthsOfYear: gettext('January February March April May June July August September October November December').split(' '), daysOfWeek: gettext('S M T W T F S').split(' '), firstDayOfWeek: parseInt(get_format('FIRST_DAY_OF_WEEK')), isLeapYear: function(year) { return (((year % 4)==0) && ((year % 100)!=0) || ((year % 400)==0)); }, getDaysInMonth: function(month,year) { var days; if (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12) { days = 31; } else if (month==4 || month==6 || month==9 || month==11) { days = 30; } else if (month==2 && CalendarNamespace.isLeapYear(year)) { days = 29; } else { days = 28; } return days; }, draw: function(month, year, div_id, callback) { // month = 1-12, year = 1-9999 var today = new Date(); var todayDay = today.getDate(); var todayMonth = today.getMonth()+1; var todayYear = today.getFullYear(); var todayClass = ''; month = parseInt(month); year = parseInt(year); var calDiv = document.getElementById(div_id); removeChildren(calDiv); var calTable = document.createElement('table'); quickElement('caption', calTable, CalendarNamespace.monthsOfYear[month-1] + ' ' + year); var tableBody = quickElement('tbody', calTable); // Draw days-of-week header var tableRow = quickElement('tr', tableBody); for (var i = 0; i < 7; i++) { quickElement('th', tableRow, CalendarNamespace.daysOfWeek[(i + CalendarNamespace.firstDayOfWeek) % 7]); } var startingPos = new Date(year, month-1, 1 - CalendarNamespace.firstDayOfWeek).getDay(); var days = CalendarNamespace.getDaysInMonth(month, year); // Draw blanks before first of month tableRow = quickElement('tr', tableBody); for (var i = 0; i < startingPos; i++) { var _cell = quickElement('td', tableRow, ' '); _cell.style.backgroundColor = '#f3f3f3'; } // Draw days of month var currentDay = 1; for (var i = startingPos; currentDay <= days; i++) { if (i%7 == 0 && currentDay != 1) { tableRow = quickElement('tr', tableBody); } if ((currentDay==todayDay) && (month==todayMonth) && (year==todayYear)) { todayClass='today'; } else { todayClass=''; } var cell = quickElement('td', tableRow, '', 'class', todayClass); quickElement('a', cell, currentDay, 'href', 'javascript:void(' + callback + '('+year+','+month+','+currentDay+'));'); currentDay++; } // Draw blanks after end of month (optional, but makes for valid code) while (tableRow.childNodes.length < 7) { var _cell = quickElement('td', tableRow, ' '); _cell.style.backgroundColor = '#f3f3f3'; } calDiv.appendChild(calTable); } } // Calendar -- A calendar instance function Calendar(div_id, callback) { // div_id (string) is the ID of the element in which the calendar will // be displayed // callback (string) is the name of a JavaScript function that will be // called with the parameters (year, month, day) when a day in the // calendar is clicked this.div_id = div_id; this.callback = callback; this.today = new Date(); this.currentMonth = this.today.getMonth() + 1; this.currentYear = this.today.getFullYear(); } Calendar.prototype = { drawCurrent: function() { CalendarNamespace.draw(this.currentMonth, this.currentYear, this.div_id, this.callback); }, drawDate: function(month, year) { this.currentMonth = month; this.currentYear = year; this.drawCurrent(); }, drawPreviousMonth: function() { if (this.currentMonth == 1) { this.currentMonth = 12; this.currentYear--; } else { this.currentMonth--; } this.drawCurrent(); }, drawNextMonth: function() { if (this.currentMonth == 12) { this.currentMonth = 1; this.currentYear++; } else { this.currentMonth++; } this.drawCurrent(); }, drawPreviousYear: function() { this.currentYear--; this.drawCurrent(); }, drawNextYear: function() { this.currentYear++; this.drawCurrent(); } }
JavaScript
// Puts the included jQuery into our own namespace var django = { "jQuery": jQuery.noConflict(true) };
JavaScript
// Core javascript helper functions // basic browser identification & version var isOpera = (navigator.userAgent.indexOf("Opera")>=0) && parseFloat(navigator.appVersion); var isIE = ((document.all) && (!isOpera)) && parseFloat(navigator.appVersion.split("MSIE ")[1].split(";")[0]); // Cross-browser event handlers. function addEvent(obj, evType, fn) { if (obj.addEventListener) { obj.addEventListener(evType, fn, false); return true; } else if (obj.attachEvent) { var r = obj.attachEvent("on" + evType, fn); return r; } else { return false; } } function removeEvent(obj, evType, fn) { if (obj.removeEventListener) { obj.removeEventListener(evType, fn, false); return true; } else if (obj.detachEvent) { obj.detachEvent("on" + evType, fn); return true; } else { return false; } } // quickElement(tagType, parentReference, textInChildNode, [, attribute, attributeValue ...]); function quickElement() { var obj = document.createElement(arguments[0]); if (arguments[2] != '' && arguments[2] != null) { var textNode = document.createTextNode(arguments[2]); obj.appendChild(textNode); } var len = arguments.length; for (var i = 3; i < len; i += 2) { obj.setAttribute(arguments[i], arguments[i+1]); } arguments[1].appendChild(obj); return obj; } // ---------------------------------------------------------------------------- // Cross-browser xmlhttp object // from http://jibbering.com/2002/4/httprequest.html // ---------------------------------------------------------------------------- var xmlhttp; /*@cc_on @*/ /*@if (@_jscript_version >= 5) try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { xmlhttp = false; } } @else xmlhttp = false; @end @*/ if (!xmlhttp && typeof XMLHttpRequest != 'undefined') { xmlhttp = new XMLHttpRequest(); } // ---------------------------------------------------------------------------- // Find-position functions by PPK // See http://www.quirksmode.org/js/findpos.html // ---------------------------------------------------------------------------- function findPosX(obj) { var curleft = 0; if (obj.offsetParent) { while (obj.offsetParent) { curleft += obj.offsetLeft - ((isOpera) ? 0 : obj.scrollLeft); obj = obj.offsetParent; } // IE offsetParent does not include the top-level if (isIE && obj.parentElement){ curleft += obj.offsetLeft - obj.scrollLeft; } } else if (obj.x) { curleft += obj.x; } return curleft; } function findPosY(obj) { var curtop = 0; if (obj.offsetParent) { while (obj.offsetParent) { curtop += obj.offsetTop - ((isOpera) ? 0 : obj.scrollTop); obj = obj.offsetParent; } // IE offsetParent does not include the top-level if (isIE && obj.parentElement){ curtop += obj.offsetTop - obj.scrollTop; } } else if (obj.y) { curtop += obj.y; } return curtop; } //----------------------------------------------------------------------------- // Date object extensions // ---------------------------------------------------------------------------- Date.prototype.getCorrectYear = function() { // Date.getYear() is unreliable -- // see http://www.quirksmode.org/js/introdate.html#year var y = this.getYear() % 100; return (y < 38) ? y + 2000 : y + 1900; } Date.prototype.getTwelveHours = function() { hours = this.getHours(); if (hours == 0) { return 12; } else { return hours <= 12 ? hours : hours-12 } } Date.prototype.getTwoDigitMonth = function() { return (this.getMonth() < 9) ? '0' + (this.getMonth()+1) : (this.getMonth()+1); } Date.prototype.getTwoDigitDate = function() { return (this.getDate() < 10) ? '0' + this.getDate() : this.getDate(); } Date.prototype.getTwoDigitTwelveHour = function() { return (this.getTwelveHours() < 10) ? '0' + this.getTwelveHours() : this.getTwelveHours(); } Date.prototype.getTwoDigitHour = function() { return (this.getHours() < 10) ? '0' + this.getHours() : this.getHours(); } Date.prototype.getTwoDigitMinute = function() { return (this.getMinutes() < 10) ? '0' + this.getMinutes() : this.getMinutes(); } Date.prototype.getTwoDigitSecond = function() { return (this.getSeconds() < 10) ? '0' + this.getSeconds() : this.getSeconds(); } Date.prototype.getISODate = function() { return this.getCorrectYear() + '-' + this.getTwoDigitMonth() + '-' + this.getTwoDigitDate(); } Date.prototype.getHourMinute = function() { return this.getTwoDigitHour() + ':' + this.getTwoDigitMinute(); } Date.prototype.getHourMinuteSecond = function() { return this.getTwoDigitHour() + ':' + this.getTwoDigitMinute() + ':' + this.getTwoDigitSecond(); } Date.prototype.strftime = function(format) { var fields = { c: this.toString(), d: this.getTwoDigitDate(), H: this.getTwoDigitHour(), I: this.getTwoDigitTwelveHour(), m: this.getTwoDigitMonth(), M: this.getTwoDigitMinute(), p: (this.getHours() >= 12) ? 'PM' : 'AM', S: this.getTwoDigitSecond(), w: '0' + this.getDay(), x: this.toLocaleDateString(), X: this.toLocaleTimeString(), y: ('' + this.getFullYear()).substr(2, 4), Y: '' + this.getFullYear(), '%' : '%' }; var result = '', i = 0; while (i < format.length) { if (format.charAt(i) === '%') { result = result + fields[format.charAt(i + 1)]; ++i; } else { result = result + format.charAt(i); } ++i; } return result; } // ---------------------------------------------------------------------------- // String object extensions // ---------------------------------------------------------------------------- String.prototype.pad_left = function(pad_length, pad_string) { var new_string = this; for (var i = 0; new_string.length < pad_length; i++) { new_string = pad_string + new_string; } return new_string; } // ---------------------------------------------------------------------------- // Get the computed style for and element // ---------------------------------------------------------------------------- function getStyle(oElm, strCssRule){ var strValue = ""; if(document.defaultView && document.defaultView.getComputedStyle){ strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule); } else if(oElm.currentStyle){ strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){ return p1.toUpperCase(); }); strValue = oElm.currentStyle[strCssRule]; } return strValue; }
JavaScript
addEvent(window, 'load', reorder_init); var lis; var top = 0; var left = 0; var height = 30; function reorder_init() { lis = document.getElementsBySelector('ul#orderthese li'); var input = document.getElementsBySelector('input[name=order_]')[0]; setOrder(input.value.split(',')); input.disabled = true; draw(); // Now initialise the dragging behaviour var limit = (lis.length - 1) * height; for (var i = 0; i < lis.length; i++) { var li = lis[i]; var img = document.getElementById('handle'+li.id); li.style.zIndex = 1; Drag.init(img, li, left + 10, left + 10, top + 10, top + 10 + limit); li.onDragStart = startDrag; li.onDragEnd = endDrag; img.style.cursor = 'move'; } } function submitOrderForm() { var inputOrder = document.getElementsBySelector('input[name=order_]')[0]; inputOrder.value = getOrder(); inputOrder.disabled=false; } function startDrag() { this.style.zIndex = '10'; this.className = 'dragging'; } function endDrag(x, y) { this.style.zIndex = '1'; this.className = ''; // Work out how far along it has been dropped, using x co-ordinate var oldIndex = this.index; var newIndex = Math.round((y - 10 - top) / height); // 'Snap' to the correct position this.style.top = (10 + top + newIndex * height) + 'px'; this.index = newIndex; moveItem(oldIndex, newIndex); } function moveItem(oldIndex, newIndex) { // Swaps two items, adjusts the index and left co-ord for all others if (oldIndex == newIndex) { return; // Nothing to swap; } var direction, lo, hi; if (newIndex > oldIndex) { lo = oldIndex; hi = newIndex; direction = -1; } else { direction = 1; hi = oldIndex; lo = newIndex; } var lis2 = new Array(); // We will build the new order in this array for (var i = 0; i < lis.length; i++) { if (i < lo || i > hi) { // Position of items not between the indexes is unaffected lis2[i] = lis[i]; continue; } else if (i == newIndex) { lis2[i] = lis[oldIndex]; continue; } else { // Item is between the two indexes - move it along 1 lis2[i] = lis[i - direction]; } } // Re-index everything reIndex(lis2); lis = lis2; draw(); // document.getElementById('hiddenOrder').value = getOrder(); document.getElementsBySelector('input[name=order_]')[0].value = getOrder(); } function reIndex(lis) { for (var i = 0; i < lis.length; i++) { lis[i].index = i; } } function draw() { for (var i = 0; i < lis.length; i++) { var li = lis[i]; li.index = i; li.style.position = 'absolute'; li.style.left = (10 + left) + 'px'; li.style.top = (10 + top + (i * height)) + 'px'; } } function getOrder() { var order = new Array(lis.length); for (var i = 0; i < lis.length; i++) { order[i] = lis[i].id.substring(1, 100); } return order.join(','); } function setOrder(id_list) { /* Set the current order to match the lsit of IDs */ var temp_lis = new Array(); for (var i = 0; i < id_list.length; i++) { var id = 'p' + id_list[i]; temp_lis[temp_lis.length] = document.getElementById(id); } reIndex(temp_lis); lis = temp_lis; draw(); } function addEvent(elm, evType, fn, useCapture) // addEvent and removeEvent // cross-browser event handling for IE5+, NS6 and Mozilla // By Scott Andrew { if (elm.addEventListener){ elm.addEventListener(evType, fn, useCapture); return true; } else if (elm.attachEvent){ var r = elm.attachEvent("on"+evType, fn); return r; } else { elm['on'+evType] = fn; } }
JavaScript
// Handles related-objects functionality: lookup link for raw_id_fields // and Add Another links. function html_unescape(text) { // Unescape a string that was escaped using django.utils.html.escape. text = text.replace(/&lt;/g, '<'); text = text.replace(/&gt;/g, '>'); text = text.replace(/&quot;/g, '"'); text = text.replace(/&#39;/g, "'"); text = text.replace(/&amp;/g, '&'); return text; } // IE doesn't accept periods or dashes in the window name, but the element IDs // we use to generate popup window names may contain them, therefore we map them // to allowed characters in a reversible way so that we can locate the correct // element when the popup window is dismissed. function id_to_windowname(text) { text = text.replace(/\./g, '__dot__'); text = text.replace(/\-/g, '__dash__'); return text; } function windowname_to_id(text) { text = text.replace(/__dot__/g, '.'); text = text.replace(/__dash__/g, '-'); return text; } function showRelatedObjectLookupPopup(triggeringLink) { var name = triggeringLink.id.replace(/^lookup_/, ''); name = id_to_windowname(name); var href; if (triggeringLink.href.search(/\?/) >= 0) { href = triggeringLink.href + '&pop=1'; } else { href = triggeringLink.href + '?pop=1'; } var win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes'); win.focus(); return false; } function dismissRelatedLookupPopup(win, chosenId) { var name = windowname_to_id(win.name); var elem = document.getElementById(name); if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) { elem.value += ',' + chosenId; } else { document.getElementById(name).value = chosenId; } win.close(); } function showAddAnotherPopup(triggeringLink) { var name = triggeringLink.id.replace(/^add_/, ''); name = id_to_windowname(name); href = triggeringLink.href if (href.indexOf('?') == -1) { href += '?_popup=1'; } else { href += '&_popup=1'; } var win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes'); win.focus(); return false; } function dismissAddAnotherPopup(win, newId, newRepr) { // newId and newRepr are expected to have previously been escaped by // django.utils.html.escape. newId = html_unescape(newId); newRepr = html_unescape(newRepr); var name = windowname_to_id(win.name); var elem = document.getElementById(name); if (elem) { if (elem.nodeName == 'SELECT') { var o = new Option(newRepr, newId); elem.options[elem.options.length] = o; o.selected = true; } else if (elem.nodeName == 'INPUT') { if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) { elem.value += ',' + newId; } else { elem.value = newId; } } } else { var toId = name + "_to"; elem = document.getElementById(toId); var o = new Option(newRepr, newId); SelectBox.add_to_cache(toId, o); SelectBox.redisplay(toId); } win.close(); }
JavaScript
// Inserts shortcut buttons after all of the following: // <input type="text" class="vDateField"> // <input type="text" class="vTimeField"> var DateTimeShortcuts = { calendars: [], calendarInputs: [], clockInputs: [], calendarDivName1: 'calendarbox', // name of calendar <div> that gets toggled calendarDivName2: 'calendarin', // name of <div> that contains calendar calendarLinkName: 'calendarlink',// name of the link that is used to toggle clockDivName: 'clockbox', // name of clock <div> that gets toggled clockLinkName: 'clocklink', // name of the link that is used to toggle shortCutsClass: 'datetimeshortcuts', // class of the clock and cal shortcuts admin_media_prefix: '', init: function() { // Get admin_media_prefix by grabbing it off the window object. It's // set in the admin/base.html template, so if it's not there, someone's // overridden the template. In that case, we'll set a clearly-invalid // value in the hopes that someone will examine HTTP requests and see it. if (window.__admin_media_prefix__ != undefined) { DateTimeShortcuts.admin_media_prefix = window.__admin_media_prefix__; } else { DateTimeShortcuts.admin_media_prefix = '/missing-admin-media-prefix/'; } var inputs = document.getElementsByTagName('input'); for (i=0; i<inputs.length; i++) { var inp = inputs[i]; if (inp.getAttribute('type') == 'text' && inp.className.match(/vTimeField/)) { DateTimeShortcuts.addClock(inp); } else if (inp.getAttribute('type') == 'text' && inp.className.match(/vDateField/)) { DateTimeShortcuts.addCalendar(inp); } } }, // Add clock widget to a given field addClock: function(inp) { var num = DateTimeShortcuts.clockInputs.length; DateTimeShortcuts.clockInputs[num] = inp; // Shortcut links (clock icon and "Now" link) var shortcuts_span = document.createElement('span'); shortcuts_span.className = DateTimeShortcuts.shortCutsClass; inp.parentNode.insertBefore(shortcuts_span, inp.nextSibling); var now_link = document.createElement('a'); now_link.setAttribute('href', "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date().strftime('" + get_format('TIME_INPUT_FORMATS')[0] + "'));"); now_link.appendChild(document.createTextNode(gettext('Now'))); var clock_link = document.createElement('a'); clock_link.setAttribute('href', 'javascript:DateTimeShortcuts.openClock(' + num + ');'); clock_link.id = DateTimeShortcuts.clockLinkName + num; quickElement('img', clock_link, '', 'src', DateTimeShortcuts.admin_media_prefix + 'img/admin/icon_clock.gif', 'alt', gettext('Clock')); shortcuts_span.appendChild(document.createTextNode('\240')); shortcuts_span.appendChild(now_link); shortcuts_span.appendChild(document.createTextNode('\240|\240')); shortcuts_span.appendChild(clock_link); // Create clock link div // // Markup looks like: // <div id="clockbox1" class="clockbox module"> // <h2>Choose a time</h2> // <ul class="timelist"> // <li><a href="#">Now</a></li> // <li><a href="#">Midnight</a></li> // <li><a href="#">6 a.m.</a></li> // <li><a href="#">Noon</a></li> // </ul> // <p class="calendar-cancel"><a href="#">Cancel</a></p> // </div> var clock_box = document.createElement('div'); clock_box.style.display = 'none'; clock_box.style.position = 'absolute'; clock_box.className = 'clockbox module'; clock_box.setAttribute('id', DateTimeShortcuts.clockDivName + num); document.body.appendChild(clock_box); addEvent(clock_box, 'click', DateTimeShortcuts.cancelEventPropagation); quickElement('h2', clock_box, gettext('Choose a time')); time_list = quickElement('ul', clock_box, ''); time_list.className = 'timelist'; time_format = get_format('TIME_INPUT_FORMATS')[0]; quickElement("a", quickElement("li", time_list, ""), gettext("Now"), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date().strftime('" + time_format + "'));"); quickElement("a", quickElement("li", time_list, ""), gettext("Midnight"), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date(1970,1,1,0,0,0,0).strftime('" + time_format + "'));"); quickElement("a", quickElement("li", time_list, ""), gettext("6 a.m."), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date(1970,1,1,6,0,0,0).strftime('" + time_format + "'));"); quickElement("a", quickElement("li", time_list, ""), gettext("Noon"), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date(1970,1,1,12,0,0,0).strftime('" + time_format + "'));"); cancel_p = quickElement('p', clock_box, ''); cancel_p.className = 'calendar-cancel'; quickElement('a', cancel_p, gettext('Cancel'), 'href', 'javascript:DateTimeShortcuts.dismissClock(' + num + ');'); }, openClock: function(num) { var clock_box = document.getElementById(DateTimeShortcuts.clockDivName+num) var clock_link = document.getElementById(DateTimeShortcuts.clockLinkName+num) // Recalculate the clockbox position // is it left-to-right or right-to-left layout ? if (getStyle(document.body,'direction')!='rtl') { clock_box.style.left = findPosX(clock_link) + 17 + 'px'; } else { // since style's width is in em, it'd be tough to calculate // px value of it. let's use an estimated px for now // TODO: IE returns wrong value for findPosX when in rtl mode // (it returns as it was left aligned), needs to be fixed. clock_box.style.left = findPosX(clock_link) - 110 + 'px'; } clock_box.style.top = Math.max(0, findPosY(clock_link) - 30) + 'px'; // Show the clock box clock_box.style.display = 'block'; addEvent(window.document, 'click', function() { DateTimeShortcuts.dismissClock(num); return true; }); }, dismissClock: function(num) { document.getElementById(DateTimeShortcuts.clockDivName + num).style.display = 'none'; window.document.onclick = null; }, handleClockQuicklink: function(num, val) { DateTimeShortcuts.clockInputs[num].value = val; DateTimeShortcuts.clockInputs[num].focus(); DateTimeShortcuts.dismissClock(num); }, // Add calendar widget to a given field. addCalendar: function(inp) { var num = DateTimeShortcuts.calendars.length; DateTimeShortcuts.calendarInputs[num] = inp; // Shortcut links (calendar icon and "Today" link) var shortcuts_span = document.createElement('span'); shortcuts_span.className = DateTimeShortcuts.shortCutsClass; inp.parentNode.insertBefore(shortcuts_span, inp.nextSibling); var today_link = document.createElement('a'); today_link.setAttribute('href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', 0);'); today_link.appendChild(document.createTextNode(gettext('Today'))); var cal_link = document.createElement('a'); cal_link.setAttribute('href', 'javascript:DateTimeShortcuts.openCalendar(' + num + ');'); cal_link.id = DateTimeShortcuts.calendarLinkName + num; quickElement('img', cal_link, '', 'src', DateTimeShortcuts.admin_media_prefix + 'img/admin/icon_calendar.gif', 'alt', gettext('Calendar')); shortcuts_span.appendChild(document.createTextNode('\240')); shortcuts_span.appendChild(today_link); shortcuts_span.appendChild(document.createTextNode('\240|\240')); shortcuts_span.appendChild(cal_link); // Create calendarbox div. // // Markup looks like: // // <div id="calendarbox3" class="calendarbox module"> // <h2> // <a href="#" class="link-previous">&lsaquo;</a> // <a href="#" class="link-next">&rsaquo;</a> February 2003 // </h2> // <div class="calendar" id="calendarin3"> // <!-- (cal) --> // </div> // <div class="calendar-shortcuts"> // <a href="#">Yesterday</a> | <a href="#">Today</a> | <a href="#">Tomorrow</a> // </div> // <p class="calendar-cancel"><a href="#">Cancel</a></p> // </div> var cal_box = document.createElement('div'); cal_box.style.display = 'none'; cal_box.style.position = 'absolute'; cal_box.className = 'calendarbox module'; cal_box.setAttribute('id', DateTimeShortcuts.calendarDivName1 + num); document.body.appendChild(cal_box); addEvent(cal_box, 'click', DateTimeShortcuts.cancelEventPropagation); // next-prev links var cal_nav = quickElement('div', cal_box, ''); var cal_nav_prev = quickElement('a', cal_nav, '<', 'href', 'javascript:DateTimeShortcuts.drawPrev('+num+');'); cal_nav_prev.className = 'calendarnav-previous'; var cal_nav_next = quickElement('a', cal_nav, '>', 'href', 'javascript:DateTimeShortcuts.drawNext('+num+');'); cal_nav_next.className = 'calendarnav-next'; // main box var cal_main = quickElement('div', cal_box, '', 'id', DateTimeShortcuts.calendarDivName2 + num); cal_main.className = 'calendar'; DateTimeShortcuts.calendars[num] = new Calendar(DateTimeShortcuts.calendarDivName2 + num, DateTimeShortcuts.handleCalendarCallback(num)); DateTimeShortcuts.calendars[num].drawCurrent(); // calendar shortcuts var shortcuts = quickElement('div', cal_box, ''); shortcuts.className = 'calendar-shortcuts'; quickElement('a', shortcuts, gettext('Yesterday'), 'href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', -1);'); shortcuts.appendChild(document.createTextNode('\240|\240')); quickElement('a', shortcuts, gettext('Today'), 'href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', 0);'); shortcuts.appendChild(document.createTextNode('\240|\240')); quickElement('a', shortcuts, gettext('Tomorrow'), 'href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', +1);'); // cancel bar var cancel_p = quickElement('p', cal_box, ''); cancel_p.className = 'calendar-cancel'; quickElement('a', cancel_p, gettext('Cancel'), 'href', 'javascript:DateTimeShortcuts.dismissCalendar(' + num + ');'); }, openCalendar: function(num) { var cal_box = document.getElementById(DateTimeShortcuts.calendarDivName1+num) var cal_link = document.getElementById(DateTimeShortcuts.calendarLinkName+num) var inp = DateTimeShortcuts.calendarInputs[num]; // Determine if the current value in the input has a valid date. // If so, draw the calendar with that date's year and month. if (inp.value) { var date_parts = inp.value.split('-'); var year = date_parts[0]; var month = parseFloat(date_parts[1]); if (year.match(/\d\d\d\d/) && month >= 1 && month <= 12) { DateTimeShortcuts.calendars[num].drawDate(month, year); } } // Recalculate the clockbox position // is it left-to-right or right-to-left layout ? if (getStyle(document.body,'direction')!='rtl') { cal_box.style.left = findPosX(cal_link) + 17 + 'px'; } else { // since style's width is in em, it'd be tough to calculate // px value of it. let's use an estimated px for now // TODO: IE returns wrong value for findPosX when in rtl mode // (it returns as it was left aligned), needs to be fixed. cal_box.style.left = findPosX(cal_link) - 180 + 'px'; } cal_box.style.top = Math.max(0, findPosY(cal_link) - 75) + 'px'; cal_box.style.display = 'block'; addEvent(window.document, 'click', function() { DateTimeShortcuts.dismissCalendar(num); return true; }); }, dismissCalendar: function(num) { document.getElementById(DateTimeShortcuts.calendarDivName1+num).style.display = 'none'; window.document.onclick = null; }, drawPrev: function(num) { DateTimeShortcuts.calendars[num].drawPreviousMonth(); }, drawNext: function(num) { DateTimeShortcuts.calendars[num].drawNextMonth(); }, handleCalendarCallback: function(num) { format = get_format('DATE_INPUT_FORMATS')[0]; // the format needs to be escaped a little format = format.replace('\\', '\\\\'); format = format.replace('\r', '\\r'); format = format.replace('\n', '\\n'); format = format.replace('\t', '\\t'); format = format.replace("'", "\\'"); return ["function(y, m, d) { DateTimeShortcuts.calendarInputs[", num, "].value = new Date(y, m-1, d).strftime('", format, "');DateTimeShortcuts.calendarInputs[", num, "].focus();document.getElementById(DateTimeShortcuts.calendarDivName1+", num, ").style.display='none';}"].join(''); }, handleCalendarQuickLink: function(num, offset) { var d = new Date(); d.setDate(d.getDate() + offset) DateTimeShortcuts.calendarInputs[num].value = d.strftime(get_format('DATE_INPUT_FORMATS')[0]); DateTimeShortcuts.calendarInputs[num].focus(); DateTimeShortcuts.dismissCalendar(num); }, cancelEventPropagation: function(e) { if (!e) e = window.event; e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation(); } } addEvent(window, 'load', DateTimeShortcuts.init);
JavaScript
(function($) { $.fn.actions = function(opts) { var options = $.extend({}, $.fn.actions.defaults, opts); var actionCheckboxes = $(this); var list_editable_changed = false; checker = function(checked) { if (checked) { showQuestion(); } else { reset(); } $(actionCheckboxes).attr("checked", checked) .parent().parent().toggleClass(options.selectedClass, checked); } updateCounter = function() { var sel = $(actionCheckboxes).filter(":checked").length; $(options.counterContainer).html(interpolate( ngettext('%(sel)s of %(cnt)s selected', '%(sel)s of %(cnt)s selected', sel), { sel: sel, cnt: _actions_icnt }, true)); $(options.allToggle).attr("checked", function() { if (sel == actionCheckboxes.length) { value = true; showQuestion(); } else { value = false; clearAcross(); } return value; }); } showQuestion = function() { $(options.acrossClears).hide(); $(options.acrossQuestions).show(); $(options.allContainer).hide(); } showClear = function() { $(options.acrossClears).show(); $(options.acrossQuestions).hide(); $(options.actionContainer).toggleClass(options.selectedClass); $(options.allContainer).show(); $(options.counterContainer).hide(); } reset = function() { $(options.acrossClears).hide(); $(options.acrossQuestions).hide(); $(options.allContainer).hide(); $(options.counterContainer).show(); } clearAcross = function() { reset(); $(options.acrossInput).val(0); $(options.actionContainer).removeClass(options.selectedClass); } // Show counter by default $(options.counterContainer).show(); // Check state of checkboxes and reinit state if needed $(this).filter(":checked").each(function(i) { $(this).parent().parent().toggleClass(options.selectedClass); updateCounter(); if ($(options.acrossInput).val() == 1) { showClear(); } }); $(options.allToggle).show().click(function() { checker($(this).attr("checked")); updateCounter(); }); $("div.actions span.question a").click(function(event) { event.preventDefault(); $(options.acrossInput).val(1); showClear(); }); $("div.actions span.clear a").click(function(event) { event.preventDefault(); $(options.allToggle).attr("checked", false); clearAcross(); checker(0); updateCounter(); }); lastChecked = null; $(actionCheckboxes).click(function(event) { if (!event) { var event = window.event; } var target = event.target ? event.target : event.srcElement; if (lastChecked && $.data(lastChecked) != $.data(target) && event.shiftKey == true) { var inrange = false; $(lastChecked).attr("checked", target.checked) .parent().parent().toggleClass(options.selectedClass, target.checked); $(actionCheckboxes).each(function() { if ($.data(this) == $.data(lastChecked) || $.data(this) == $.data(target)) { inrange = (inrange) ? false : true; } if (inrange) { $(this).attr("checked", target.checked) .parent().parent().toggleClass(options.selectedClass, target.checked); } }); } $(target).parent().parent().toggleClass(options.selectedClass, target.checked); lastChecked = target; updateCounter(); }); $('form#changelist-form table#result_list tr').find('td:gt(0) :input').change(function() { list_editable_changed = true; }); $('form#changelist-form button[name="index"]').click(function(event) { if (list_editable_changed) { return confirm(gettext("You have unsaved changes on individual editable fields. If you run an action, your unsaved changes will be lost.")); } }); $('form#changelist-form input[name="_save"]').click(function(event) { var action_changed = false; $('div.actions select option:selected').each(function() { if ($(this).val()) { action_changed = true; } }); if (action_changed) { if (list_editable_changed) { return confirm(gettext("You have selected an action, but you haven't saved your changes to individual fields yet. Please click OK to save. You'll need to re-run the action.")); } else { return confirm(gettext("You have selected an action, and you haven't made any changes on individual fields. You're probably looking for the Go button rather than the Save button.")); } } }); } /* Setup plugin defaults */ $.fn.actions.defaults = { actionContainer: "div.actions", counterContainer: "span.action-counter", allContainer: "div.actions span.all", acrossInput: "div.actions input.select-across", acrossQuestions: "div.actions span.question", acrossClears: "div.actions span.clear", allToggle: "#action-toggle", selectedClass: "selected" } })(django.jQuery);
JavaScript
var timeParsePatterns = [ // 9 { re: /^\d{1,2}$/i, handler: function(bits) { if (bits[0].length == 1) { return '0' + bits[0] + ':00'; } else { return bits[0] + ':00'; } } }, // 13:00 { re: /^\d{2}[:.]\d{2}$/i, handler: function(bits) { return bits[0].replace('.', ':'); } }, // 9:00 { re: /^\d[:.]\d{2}$/i, handler: function(bits) { return '0' + bits[0].replace('.', ':'); } }, // 3 am / 3 a.m. / 3am { re: /^(\d+)\s*([ap])(?:.?m.?)?$/i, handler: function(bits) { var hour = parseInt(bits[1]); if (hour == 12) { hour = 0; } if (bits[2].toLowerCase() == 'p') { if (hour == 12) { hour = 0; } return (hour + 12) + ':00'; } else { if (hour < 10) { return '0' + hour + ':00'; } else { return hour + ':00'; } } } }, // 3.30 am / 3:15 a.m. / 3.00am { re: /^(\d+)[.:](\d{2})\s*([ap]).?m.?$/i, handler: function(bits) { var hour = parseInt(bits[1]); var mins = parseInt(bits[2]); if (mins < 10) { mins = '0' + mins; } if (hour == 12) { hour = 0; } if (bits[3].toLowerCase() == 'p') { if (hour == 12) { hour = 0; } return (hour + 12) + ':' + mins; } else { if (hour < 10) { return '0' + hour + ':' + mins; } else { return hour + ':' + mins; } } } }, // noon { re: /^no/i, handler: function(bits) { return '12:00'; } }, // midnight { re: /^mid/i, handler: function(bits) { return '00:00'; } } ]; function parseTimeString(s) { for (var i = 0; i < timeParsePatterns.length; i++) { var re = timeParsePatterns[i].re; var handler = timeParsePatterns[i].handler; var bits = re.exec(s); if (bits) { return handler(bits); } } return s; }
JavaScript
(function($) { $(document).ready(function() { // Add anchor tag for Show/Hide link $("fieldset.collapse").each(function(i, elem) { // Don't hide if fields in this fieldset have errors if ( $(elem).find("div.errors").length == 0 ) { $(elem).addClass("collapsed"); $(elem).find("h2").first().append(' (<a id="fieldsetcollapser' + i +'" class="collapse-toggle" href="#">' + gettext("Show") + '</a>)'); } }); // Add toggle to anchor tag $("fieldset.collapse a.collapse-toggle").toggle( function() { // Show $(this).text(gettext("Hide")); $(this).closest("fieldset").removeClass("collapsed"); return false; }, function() { // Hide $(this).text(gettext("Show")); $(this).closest("fieldset").addClass("collapsed"); return false; } ); }); })(django.jQuery);
JavaScript
/* 'Magic' date parsing, by Simon Willison (6th October 2003) http://simon.incutio.com/archive/2003/10/06/betterDateInput Adapted for 6newslawrence.com, 28th January 2004 */ /* Finds the index of the first occurence of item in the array, or -1 if not found */ if (typeof Array.prototype.indexOf == 'undefined') { Array.prototype.indexOf = function(item) { var len = this.length; for (var i = 0; i < len; i++) { if (this[i] == item) { return i; } } return -1; }; } /* Returns an array of items judged 'true' by the passed in test function */ if (typeof Array.prototype.filter == 'undefined') { Array.prototype.filter = function(test) { var matches = []; var len = this.length; for (var i = 0; i < len; i++) { if (test(this[i])) { matches[matches.length] = this[i]; } } return matches; }; } var monthNames = gettext("January February March April May June July August September October November December").split(" "); var weekdayNames = gettext("Sunday Monday Tuesday Wednesday Thursday Friday Saturday").split(" "); /* Takes a string, returns the index of the month matching that string, throws an error if 0 or more than 1 matches */ function parseMonth(month) { var matches = monthNames.filter(function(item) { return new RegExp("^" + month, "i").test(item); }); if (matches.length == 0) { throw new Error("Invalid month string"); } if (matches.length > 1) { throw new Error("Ambiguous month"); } return monthNames.indexOf(matches[0]); } /* Same as parseMonth but for days of the week */ function parseWeekday(weekday) { var matches = weekdayNames.filter(function(item) { return new RegExp("^" + weekday, "i").test(item); }); if (matches.length == 0) { throw new Error("Invalid day string"); } if (matches.length > 1) { throw new Error("Ambiguous weekday"); } return weekdayNames.indexOf(matches[0]); } /* Array of objects, each has 're', a regular expression and 'handler', a function for creating a date from something that matches the regular expression. Handlers may throw errors if string is unparseable. */ var dateParsePatterns = [ // Today { re: /^tod/i, handler: function() { return new Date(); } }, // Tomorrow { re: /^tom/i, handler: function() { var d = new Date(); d.setDate(d.getDate() + 1); return d; } }, // Yesterday { re: /^yes/i, handler: function() { var d = new Date(); d.setDate(d.getDate() - 1); return d; } }, // 4th { re: /^(\d{1,2})(st|nd|rd|th)?$/i, handler: function(bits) { var d = new Date(); d.setDate(parseInt(bits[1], 10)); return d; } }, // 4th Jan { re: /^(\d{1,2})(?:st|nd|rd|th)? (\w+)$/i, handler: function(bits) { var d = new Date(); d.setDate(1); d.setMonth(parseMonth(bits[2])); d.setDate(parseInt(bits[1], 10)); return d; } }, // 4th Jan 2003 { re: /^(\d{1,2})(?:st|nd|rd|th)? (\w+),? (\d{4})$/i, handler: function(bits) { var d = new Date(); d.setDate(1); d.setYear(bits[3]); d.setMonth(parseMonth(bits[2])); d.setDate(parseInt(bits[1], 10)); return d; } }, // Jan 4th { re: /^(\w+) (\d{1,2})(?:st|nd|rd|th)?$/i, handler: function(bits) { var d = new Date(); d.setDate(1); d.setMonth(parseMonth(bits[1])); d.setDate(parseInt(bits[2], 10)); return d; } }, // Jan 4th 2003 { re: /^(\w+) (\d{1,2})(?:st|nd|rd|th)?,? (\d{4})$/i, handler: function(bits) { var d = new Date(); d.setDate(1); d.setYear(bits[3]); d.setMonth(parseMonth(bits[1])); d.setDate(parseInt(bits[2], 10)); return d; } }, // next Tuesday - this is suspect due to weird meaning of "next" { re: /^next (\w+)$/i, handler: function(bits) { var d = new Date(); var day = d.getDay(); var newDay = parseWeekday(bits[1]); var addDays = newDay - day; if (newDay <= day) { addDays += 7; } d.setDate(d.getDate() + addDays); return d; } }, // last Tuesday { re: /^last (\w+)$/i, handler: function(bits) { throw new Error("Not yet implemented"); } }, // mm/dd/yyyy (American style) { re: /(\d{1,2})\/(\d{1,2})\/(\d{4})/, handler: function(bits) { var d = new Date(); d.setDate(1); d.setYear(bits[3]); d.setMonth(parseInt(bits[1], 10) - 1); // Because months indexed from 0 d.setDate(parseInt(bits[2], 10)); return d; } }, // yyyy-mm-dd (ISO style) { re: /(\d{4})-(\d{1,2})-(\d{1,2})/, handler: function(bits) { var d = new Date(); d.setDate(1); d.setYear(parseInt(bits[1])); d.setMonth(parseInt(bits[2], 10) - 1); d.setDate(parseInt(bits[3], 10)); return d; } }, ]; function parseDateString(s) { for (var i = 0; i < dateParsePatterns.length; i++) { var re = dateParsePatterns[i].re; var handler = dateParsePatterns[i].handler; var bits = re.exec(s); if (bits) { return handler(bits); } } throw new Error("Invalid date string"); } function fmt00(x) { // fmt00: Tags leading zero onto numbers 0 - 9. // Particularly useful for displaying results from Date methods. // if (Math.abs(parseInt(x)) < 10){ x = "0"+ Math.abs(x); } return x; } function parseDateStringISO(s) { try { var d = parseDateString(s); return d.getFullYear() + '-' + (fmt00(d.getMonth() + 1)) + '-' + fmt00(d.getDate()) } catch (e) { return s; } } function magicDate(input) { var messagespan = input.id + 'Msg'; try { var d = parseDateString(input.value); input.value = d.getFullYear() + '-' + (fmt00(d.getMonth() + 1)) + '-' + fmt00(d.getDate()); input.className = ''; // Human readable date if (document.getElementById(messagespan)) { document.getElementById(messagespan).firstChild.nodeValue = d.toDateString(); document.getElementById(messagespan).className = 'normal'; } } catch (e) { input.className = 'error'; var message = e.message; // Fix for IE6 bug if (message.indexOf('is null or not an object') > -1) { message = 'Invalid date string'; } if (document.getElementById(messagespan)) { document.getElementById(messagespan).firstChild.nodeValue = message; document.getElementById(messagespan).className = 'error'; } } }
JavaScript
/* document.getElementsBySelector(selector) - returns an array of element objects from the current document matching the CSS selector. Selectors can contain element names, class names and ids and can be nested. For example: elements = document.getElementsBySelect('div#main p a.external') Will return an array of all 'a' elements with 'external' in their class attribute that are contained inside 'p' elements that are contained inside the 'div' element which has id="main" New in version 0.4: Support for CSS2 and CSS3 attribute selectors: See http://www.w3.org/TR/css3-selectors/#attribute-selectors Version 0.4 - Simon Willison, March 25th 2003 -- Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows -- Opera 7 fails */ function getAllChildren(e) { // Returns all children of element. Workaround required for IE5/Windows. Ugh. return e.all ? e.all : e.getElementsByTagName('*'); } document.getElementsBySelector = function(selector) { // Attempt to fail gracefully in lesser browsers if (!document.getElementsByTagName) { return new Array(); } // Split selector in to tokens var tokens = selector.split(' '); var currentContext = new Array(document); for (var i = 0; i < tokens.length; i++) { token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');; if (token.indexOf('#') > -1) { // Token is an ID selector var bits = token.split('#'); var tagName = bits[0]; var id = bits[1]; var element = document.getElementById(id); if (!element || (tagName && element.nodeName.toLowerCase() != tagName)) { // ID not found or tag with that ID not found, return false. return new Array(); } // Set currentContext to contain just this element currentContext = new Array(element); continue; // Skip to next token } if (token.indexOf('.') > -1) { // Token contains a class selector var bits = token.split('.'); var tagName = bits[0]; var className = bits[1]; if (!tagName) { tagName = '*'; } // Get elements matching tag, filter them for class selector var found = new Array; var foundCount = 0; for (var h = 0; h < currentContext.length; h++) { var elements; if (tagName == '*') { elements = getAllChildren(currentContext[h]); } else { try { elements = currentContext[h].getElementsByTagName(tagName); } catch(e) { elements = []; } } for (var j = 0; j < elements.length; j++) { found[foundCount++] = elements[j]; } } currentContext = new Array; var currentContextIndex = 0; for (var k = 0; k < found.length; k++) { if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) { currentContext[currentContextIndex++] = found[k]; } } continue; // Skip to next token } // Code to deal with attribute selectors if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) { var tagName = RegExp.$1; var attrName = RegExp.$2; var attrOperator = RegExp.$3; var attrValue = RegExp.$4; if (!tagName) { tagName = '*'; } // Grab all of the tagName elements within current context var found = new Array; var foundCount = 0; for (var h = 0; h < currentContext.length; h++) { var elements; if (tagName == '*') { elements = getAllChildren(currentContext[h]); } else { elements = currentContext[h].getElementsByTagName(tagName); } for (var j = 0; j < elements.length; j++) { found[foundCount++] = elements[j]; } } currentContext = new Array; var currentContextIndex = 0; var checkFunction; // This function will be used to filter the elements switch (attrOperator) { case '=': // Equality checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); }; break; case '~': // Match one of space seperated words checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); }; break; case '|': // Match start with value followed by optional hyphen checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); }; break; case '^': // Match starts with value checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); }; break; case '$': // Match ends with value - fails with "Warning" in Opera 7 checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); }; break; case '*': // Match ends with value checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); }; break; default : // Just test for existence of attribute checkFunction = function(e) { return e.getAttribute(attrName); }; } currentContext = new Array; var currentContextIndex = 0; for (var k = 0; k < found.length; k++) { if (checkFunction(found[k])) { currentContext[currentContextIndex++] = found[k]; } } // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue); continue; // Skip to next token } // If we get here, token is JUST an element (not a class or ID selector) tagName = token; var found = new Array; var foundCount = 0; for (var h = 0; h < currentContext.length; h++) { var elements = currentContext[h].getElementsByTagName(tagName); for (var j = 0; j < elements.length; j++) { found[foundCount++] = elements[j]; } } currentContext = found; } return currentContext; } /* That revolting regular expression explained /^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/ \---/ \---/\-------------/ \-------/ | | | | | | | The value | | ~,|,^,$,* or = | Attribute Tag */
JavaScript
(function($) { $.fn.prepopulate = function(dependencies, maxLength) { /* Depends on urlify.js Populates a selected field with the values of the dependent fields, URLifies and shortens the string. dependencies - array of dependent fields id's maxLength - maximum length of the URLify'd string */ return this.each(function() { var field = $(this); field.data('_changed', false); field.change(function() { field.data('_changed', true); }); var populate = function () { // Bail if the fields value has changed if (field.data('_changed') == true) return; var values = []; $.each(dependencies, function(i, field) { if ($(field).val().length > 0) { values.push($(field).val()); } }) field.val(URLify(values.join(' '), maxLength)); }; $(dependencies.join(',')).keyup(populate).change(populate).focus(populate); }); }; })(django.jQuery);
JavaScript
var SelectBox = { cache: new Object(), init: function(id) { var box = document.getElementById(id); var node; SelectBox.cache[id] = new Array(); var cache = SelectBox.cache[id]; for (var i = 0; (node = box.options[i]); i++) { cache.push({value: node.value, text: node.text, displayed: 1}); } }, redisplay: function(id) { // Repopulate HTML select box from cache var box = document.getElementById(id); box.options.length = 0; // clear all options for (var i = 0, j = SelectBox.cache[id].length; i < j; i++) { var node = SelectBox.cache[id][i]; if (node.displayed) { box.options[box.options.length] = new Option(node.text, node.value, false, false); } } }, filter: function(id, text) { // Redisplay the HTML select box, displaying only the choices containing ALL // the words in text. (It's an AND search.) var tokens = text.toLowerCase().split(/\s+/); var node, token; for (var i = 0; (node = SelectBox.cache[id][i]); i++) { node.displayed = 1; for (var j = 0; (token = tokens[j]); j++) { if (node.text.toLowerCase().indexOf(token) == -1) { node.displayed = 0; } } } SelectBox.redisplay(id); }, delete_from_cache: function(id, value) { var node, delete_index = null; for (var i = 0; (node = SelectBox.cache[id][i]); i++) { if (node.value == value) { delete_index = i; break; } } var j = SelectBox.cache[id].length - 1; for (var i = delete_index; i < j; i++) { SelectBox.cache[id][i] = SelectBox.cache[id][i+1]; } SelectBox.cache[id].length--; }, add_to_cache: function(id, option) { SelectBox.cache[id].push({value: option.value, text: option.text, displayed: 1}); }, cache_contains: function(id, value) { // Check if an item is contained in the cache var node; for (var i = 0; (node = SelectBox.cache[id][i]); i++) { if (node.value == value) { return true; } } return false; }, move: function(from, to) { var from_box = document.getElementById(from); var to_box = document.getElementById(to); var option; for (var i = 0; (option = from_box.options[i]); i++) { if (option.selected && SelectBox.cache_contains(from, option.value)) { SelectBox.add_to_cache(to, {value: option.value, text: option.text, displayed: 1}); SelectBox.delete_from_cache(from, option.value); } } SelectBox.redisplay(from); SelectBox.redisplay(to); }, move_all: function(from, to) { var from_box = document.getElementById(from); var to_box = document.getElementById(to); var option; for (var i = 0; (option = from_box.options[i]); i++) { if (SelectBox.cache_contains(from, option.value)) { SelectBox.add_to_cache(to, {value: option.value, text: option.text, displayed: 1}); SelectBox.delete_from_cache(from, option.value); } } SelectBox.redisplay(from); SelectBox.redisplay(to); }, sort: function(id) { SelectBox.cache[id].sort( function(a, b) { a = a.text.toLowerCase(); b = b.text.toLowerCase(); try { if (a > b) return 1; if (a < b) return -1; } catch (e) { // silently fail on IE 'unknown' exception } return 0; } ); }, select_all: function(id) { var box = document.getElementById(id); for (var i = 0; i < box.options.length; i++) { box.options[i].selected = 'selected'; } } }
JavaScript
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @fileoverview Bookmark bubble library. This is meant to be included in the * main JavaScript binary of a mobile web application. * * Supported browsers: iPhone / iPod / iPad Safari 3.0+ */ var google = google || {}; google.bookmarkbubble = google.bookmarkbubble || {}; /** * Binds a context object to the function. * @param {Function} fn The function to bind to. * @param {Object} context The "this" object to use when the function is run. * @return {Function} A partially-applied form of fn. */ google.bind = function(fn, context) { return function() { return fn.apply(context, arguments); }; }; /** * Function used to define an abstract method in a base class. If a subclass * fails to override the abstract method, then an error will be thrown whenever * that method is invoked. */ google.abstractMethod = function() { throw Error('Unimplemented abstract method.'); }; /** * The bubble constructor. Instantiating an object does not cause anything to * be rendered yet, so if necessary you can set instance properties before * showing the bubble. * @constructor */ google.bookmarkbubble.Bubble = function() { /** * Handler for the scroll event. Keep a reference to it here, so it can be * unregistered when the bubble is destroyed. * @type {function()} * @private */ this.boundScrollHandler_ = google.bind(this.setPosition, this); /** * The bubble element. * @type {Element} * @private */ this.element_ = null; /** * Whether the bubble has been destroyed. * @type {boolean} * @private */ this.hasBeenDestroyed_ = false; }; /** * Shows the bubble if allowed. It is not allowed if: * - The browser is not Mobile Safari, or * - The user has dismissed it too often already, or * - The hash parameter is present in the location hash, or * - The application is in fullscreen mode, which means it was already loaded * from a homescreen bookmark. * @return {boolean} True if the bubble is being shown, false if it is not * allowed to show for one of the aforementioned reasons. */ google.bookmarkbubble.Bubble.prototype.showIfAllowed = function() { if (!this.isAllowedToShow_()) { return false; } this.show_(); return true; }; /** * Shows the bubble if allowed after loading the icon image. This method creates * an image element to load the image into the browser's cache before showing * the bubble to ensure that the image isn't blank. Use this instead of * showIfAllowed if the image url is http and cacheable. * This hack is necessary because Mobile Safari does not properly render * image elements with border-radius CSS. * @param {function()} opt_callback Closure to be called if and when the bubble * actually shows. * @return {boolean} True if the bubble is allowed to show. */ google.bookmarkbubble.Bubble.prototype.showIfAllowedWhenLoaded = function(opt_callback) { if (!this.isAllowedToShow_()) { return false; } var self = this; // Attach to self to avoid garbage collection. var img = self.loadImg_ = document.createElement('img'); img.src = self.getIconUrl_(); img.onload = function() { if (img.complete) { delete self.loadImg_; img.onload = null; // Break the circular reference. self.show_(); opt_callback && opt_callback(); } }; img.onload(); return true; }; /** * Sets the parameter in the location hash. As it is * unpredictable what hash scheme is to be used, this method must be * implemented by the host application. * * This gets called automatically when the bubble is shown. The idea is that if * the user then creates a bookmark, we can later recognize on application * startup whether it was from a bookmark suggested with this bubble. * * NOTE: Using a hash parameter to track whether the bubble has been shown * conflicts with the navigation system in jQuery Mobile. If you are using that * library, you should implement this function to track the bubble's status in * a different way, e.g. using window.localStorage in HTML5. */ google.bookmarkbubble.Bubble.prototype.setHashParameter = google.abstractMethod; /** * Whether the parameter is present in the location hash. As it is * unpredictable what hash scheme is to be used, this method must be * implemented by the host application. * * Call this method during application startup if you want to log whether the * application was loaded from a bookmark with the bookmark bubble promotion * parameter in it. * * @return {boolean} Whether the bookmark bubble parameter is present in the * location hash. */ google.bookmarkbubble.Bubble.prototype.hasHashParameter = google.abstractMethod; /** * The number of times the user must dismiss the bubble before we stop showing * it. This is a public property and can be changed by the host application if * necessary. * @type {number} */ google.bookmarkbubble.Bubble.prototype.NUMBER_OF_TIMES_TO_DISMISS = 2; /** * Time in milliseconds. If the user does not dismiss the bubble, it will auto * destruct after this amount of time. * @type {number} */ google.bookmarkbubble.Bubble.prototype.TIME_UNTIL_AUTO_DESTRUCT = 15000; /** * The prefix for keys in local storage. This is a public property and can be * changed by the host application if necessary. * @type {string} */ google.bookmarkbubble.Bubble.prototype.LOCAL_STORAGE_PREFIX = 'BOOKMARK_'; /** * The key name for the dismissed state. * @type {string} * @private */ google.bookmarkbubble.Bubble.prototype.DISMISSED_ = 'DISMISSED_COUNT'; /** * The arrow image in base64 data url format. * @type {string} * @private */ google.bookmarkbubble.Bubble.prototype.IMAGE_ARROW_DATA_URL_ = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAATCAMAAABSrFY3AAABKVBMVEUAAAD///8AAAAAAAAAAAAAAAAAAADf398AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD09PQAAAAAAAAAAAC9vb0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD19fUAAAAAAAAAAAAAAADq6uoAAAAAAAAAAAC8vLzU1NTT09MAAADg4OAAAADs7OwAAAAAAAAAAAD///+cueenwerA0vC1y+3a5fb5+/3t8vr4+v3w9PuwyOy3zO3h6vfh6vjq8Pqkv+mat+fE1fHB0/Cduuifu+iuxuuivemrxOvC1PDz9vzJ2fKpwuqmwOrb5vapw+q/0vDf6ffK2vLN3PPprJISAAAAQHRSTlMAAAEGExES7FM+JhUoQSxIRwMbNfkJUgXXBE4kDQIMHSA0Tw4xIToeTSc4Chz4OyIjPfI3QD/X5OZR6zzwLSUPrm1y3gAAAQZJREFUeF5lzsVyw0AURNE3IMsgmZmZgszQZoeZOf//EYlG5Yrhbs+im4Dj7slM5wBJ4OJ+undAUr68gK/Hyb6Bcp5yBR/w8jreNeAr5Eg2XE7g6e2/0z6cGw1JQhpmHP3u5aiPPnTTkIK48Hj9Op7bD3btAXTfgUdwYjwSDCVXMbizO0O4uDY/x4kYC5SWFnfC6N1a9RCO7i2XEmQJj2mHK1Hgp9Vq3QBRl9shuBLGhcNtHexcdQCnDUoUGetxDD+H2DQNG2xh6uAWgG2/17o1EmLqYH0Xej0UjHAaFxZIV6rJ/WK1kg7QZH8HU02zmdJinKZJaDV3TVMjM5Q9yiqYpUwiMwa/1apDXTNESjsAAAAASUVORK5CYII='; /** * The close image in base64 data url format. * @type {string} * @private */ google.bookmarkbubble.Bubble.prototype.IMAGE_CLOSE_DATA_URL_ = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAALVBMVEXM3fm+1Pfb5/rF2fjw9f23z/aavPOhwfTp8PyTt/L3+v7T4vqMs/K7zP////+qRWzhAAAAXElEQVQIW2O4CwUM996BwVskxtOqd++2rwMyPI+ve31GD8h4Madqz2mwms5jZ/aBGS/mHIDoen3m+DowY8/hOVUgxusz+zqPg7SvPA1UxQfSvu/du0YUK2AMmDMA5H1qhVX33T8AAAAASUVORK5CYII='; /** * The link used to locate the application's home screen icon to display inside * the bubble. The default link used here is for an iPhone home screen icon * without gloss. If your application uses a glossy icon, change this to * 'apple-touch-icon'. * @type {string} * @private */ google.bookmarkbubble.Bubble.prototype.REL_ICON_ = 'apple-touch-icon-precomposed'; /** * Regular expression for detecting an iPhone or iPod or iPad. * @type {!RegExp} * @private */ google.bookmarkbubble.Bubble.prototype.MOBILE_SAFARI_USERAGENT_REGEX_ = /iPhone|iPod|iPad/; /** * Regular expression for detecting an iPad. * @type {!RegExp} * @private */ google.bookmarkbubble.Bubble.prototype.IPAD_USERAGENT_REGEX_ = /iPad/; /** * Regular expression for extracting the iOS version. Only matches 2.0 and up. * @type {!RegExp} * @private */ google.bookmarkbubble.Bubble.prototype.IOS_VERSION_USERAGENT_REGEX_ = /OS (\d)_(\d)(?:_(\d))?/; /** * Determines whether the bubble should be shown or not. * @return {boolean} Whether the bubble should be shown or not. * @private */ google.bookmarkbubble.Bubble.prototype.isAllowedToShow_ = function() { return this.isMobileSafari_() && !this.hasBeenDismissedTooManyTimes_() && !this.isFullscreen_() && !this.hasHashParameter(); }; /** * Builds and shows the bubble. * @private */ google.bookmarkbubble.Bubble.prototype.show_ = function() { this.element_ = this.build_(); document.body.appendChild(this.element_); this.element_.style.WebkitTransform = 'translate3d(0,' + this.getHiddenYPosition_() + 'px,0)'; this.setHashParameter(); window.setTimeout(this.boundScrollHandler_, 1); window.addEventListener('scroll', this.boundScrollHandler_, false); // If the user does not dismiss the bubble, slide out and destroy it after // some time. window.setTimeout(google.bind(this.autoDestruct_, this), this.TIME_UNTIL_AUTO_DESTRUCT); }; /** * Destroys the bubble by removing its DOM nodes from the document. */ google.bookmarkbubble.Bubble.prototype.destroy = function() { if (this.hasBeenDestroyed_) { return; } window.removeEventListener('scroll', this.boundScrollHandler_, false); if (this.element_ && this.element_.parentNode == document.body) { document.body.removeChild(this.element_); this.element_ = null; } this.hasBeenDestroyed_ = true; }; /** * Remember that the user has dismissed the bubble once more. * @private */ google.bookmarkbubble.Bubble.prototype.rememberDismissal_ = function() { if (window.localStorage) { try { var key = this.LOCAL_STORAGE_PREFIX + this.DISMISSED_; var value = Number(window.localStorage[key]) || 0; window.localStorage[key] = String(value + 1); } catch (ex) { // Looks like we've hit the storage size limit. Currently we have no // fallback for this scenario, but we could use cookie storage instead. // This would increase the code bloat though. } } }; /** * Whether the user has dismissed the bubble often enough that we will not * show it again. * @return {boolean} Whether the user has dismissed the bubble often enough * that we will not show it again. * @private */ google.bookmarkbubble.Bubble.prototype.hasBeenDismissedTooManyTimes_ = function() { if (!window.localStorage) { // If we can not use localStorage to remember how many times the user has // dismissed the bubble, assume he has dismissed it. Otherwise we might end // up showing it every time the host application loads, into eternity. return true; } try { var key = this.LOCAL_STORAGE_PREFIX + this.DISMISSED_; // If the key has never been set, localStorage yields undefined, which // Number() turns into NaN. In that case we'll fall back to zero for // clarity's sake. var value = Number(window.localStorage[key]) || 0; return value >= this.NUMBER_OF_TIMES_TO_DISMISS; } catch (ex) { // If we got here, something is wrong with the localStorage. Make the same // assumption as when it does not exist at all. Exceptions should only // occur when setting a value (due to storage limitations) but let's be // extra careful. return true; } }; /** * Whether the application is running in fullscreen mode. * @return {boolean} Whether the application is running in fullscreen mode. * @private */ google.bookmarkbubble.Bubble.prototype.isFullscreen_ = function() { return !!window.navigator.standalone; }; /** * Whether the application is running inside Mobile Safari. * @return {boolean} True if the current user agent looks like Mobile Safari. * @private */ google.bookmarkbubble.Bubble.prototype.isMobileSafari_ = function() { return this.MOBILE_SAFARI_USERAGENT_REGEX_.test(window.navigator.userAgent); }; /** * Whether the application is running on an iPad. * @return {boolean} True if the current user agent looks like an iPad. * @private */ google.bookmarkbubble.Bubble.prototype.isIpad_ = function() { return this.IPAD_USERAGENT_REGEX_.test(window.navigator.userAgent); }; /** * Creates a version number from 4 integer pieces between 0 and 127 (inclusive). * @param {*=} opt_a The major version. * @param {*=} opt_b The minor version. * @param {*=} opt_c The revision number. * @param {*=} opt_d The build number. * @return {number} A representation of the version. * @private */ google.bookmarkbubble.Bubble.prototype.getVersion_ = function(opt_a, opt_b, opt_c, opt_d) { // We want to allow implicit conversion of any type to number while avoiding // compiler warnings about the type. return /** @type {number} */ (opt_a) << 21 | /** @type {number} */ (opt_b) << 14 | /** @type {number} */ (opt_c) << 7 | /** @type {number} */ (opt_d); }; /** * Gets the iOS version of the device. Only works for 2.0+. * @return {number} The iOS version. * @private */ google.bookmarkbubble.Bubble.prototype.getIosVersion_ = function() { var groups = this.IOS_VERSION_USERAGENT_REGEX_.exec( window.navigator.userAgent) || []; groups.shift(); return this.getVersion_.apply(this, groups); }; /** * Positions the bubble at the bottom of the viewport using an animated * transition. */ google.bookmarkbubble.Bubble.prototype.setPosition = function() { this.element_.style.WebkitTransition = '-webkit-transform 0.7s ease-out'; this.element_.style.WebkitTransform = 'translate3d(0,' + this.getVisibleYPosition_() + 'px,0)'; }; /** * Destroys the bubble by removing its DOM nodes from the document, and * remembers that it was dismissed. * @private */ google.bookmarkbubble.Bubble.prototype.closeClickHandler_ = function() { this.destroy(); this.rememberDismissal_(); }; /** * Gets called after a while if the user ignores the bubble. * @private */ google.bookmarkbubble.Bubble.prototype.autoDestruct_ = function() { if (this.hasBeenDestroyed_) { return; } this.element_.style.WebkitTransition = '-webkit-transform 0.7s ease-in'; this.element_.style.WebkitTransform = 'translate3d(0,' + this.getHiddenYPosition_() + 'px,0)'; window.setTimeout(google.bind(this.destroy, this), 700); }; /** * Gets the y offset used to show the bubble (i.e., position it on-screen). * @return {number} The y offset. * @private */ google.bookmarkbubble.Bubble.prototype.getVisibleYPosition_ = function() { return this.isIpad_() ? window.pageYOffset + 17 : window.pageYOffset - this.element_.offsetHeight + window.innerHeight - 17; }; /** * Gets the y offset used to hide the bubble (i.e., position it off-screen). * @return {number} The y offset. * @private */ google.bookmarkbubble.Bubble.prototype.getHiddenYPosition_ = function() { return this.isIpad_() ? window.pageYOffset - this.element_.offsetHeight : window.pageYOffset + window.innerHeight; }; /** * The url of the app's bookmark icon. * @type {string|undefined} * @private */ google.bookmarkbubble.Bubble.prototype.iconUrl_; /** * Scrapes the document for a link element that specifies an Apple favicon and * returns the icon url. Returns an empty data url if nothing can be found. * @return {string} A url string. * @private */ google.bookmarkbubble.Bubble.prototype.getIconUrl_ = function() { if (!this.iconUrl_) { var link = this.getLink(this.REL_ICON_); if (!link || !(this.iconUrl_ = link.href)) { this.iconUrl_ = 'data:image/png;base64,'; } } return this.iconUrl_; }; /** * Gets the requested link tag if it exists. * @param {string} rel The rel attribute of the link tag to get. * @return {Element} The requested link tag or null. */ google.bookmarkbubble.Bubble.prototype.getLink = function(rel) { rel = rel.toLowerCase(); var links = document.getElementsByTagName('link'); for (var i = 0; i < links.length; ++i) { var currLink = /** @type {Element} */ (links[i]); if (currLink.getAttribute('rel').toLowerCase() == rel) { return currLink; } } return null; }; /** * Creates the bubble and appends it to the document. * @return {Element} The bubble element. * @private */ google.bookmarkbubble.Bubble.prototype.build_ = function() { var bubble = document.createElement('div'); var isIpad = this.isIpad_(); bubble.style.position = 'absolute'; bubble.style.zIndex = 1000; bubble.style.width = '100%'; bubble.style.left = '0'; bubble.style.top = '0'; var bubbleInner = document.createElement('div'); bubbleInner.style.position = 'relative'; bubbleInner.style.width = '214px'; bubbleInner.style.margin = isIpad ? '0 0 0 82px' : '0 auto'; bubbleInner.style.border = '2px solid #fff'; bubbleInner.style.padding = '20px 20px 20px 10px'; bubbleInner.style.WebkitBorderRadius = '8px'; bubbleInner.style.WebkitBoxShadow = '0 0 8px rgba(0, 0, 0, 0.7)'; bubbleInner.style.WebkitBackgroundSize = '100% 8px'; bubbleInner.style.backgroundColor = '#b0c8ec'; bubbleInner.style.background = '#cddcf3 -webkit-gradient(linear, ' + 'left bottom, left top, ' + isIpad ? 'from(#cddcf3), to(#b3caed)) no-repeat top' : 'from(#b3caed), to(#cddcf3)) no-repeat bottom'; bubbleInner.style.font = '13px/17px sans-serif'; bubble.appendChild(bubbleInner); // The "Add to Home Screen" text is intended to be the exact same text // that is displayed in the menu of Mobile Safari. if (this.getIosVersion_() >= this.getVersion_(4, 2)) { bubbleInner.innerHTML = 'Install this web app on your phone: ' + 'tap on the arrow and then <b>\'Add to Home Screen\'</b>'; } else { bubbleInner.innerHTML = 'Install this web app on your phone: ' + 'tap <b style="font-size:15px">+</b> and then ' + '<b>\'Add to Home Screen\'</b>'; } var icon = document.createElement('div'); icon.style['float'] = 'left'; icon.style.width = '55px'; icon.style.height = '55px'; icon.style.margin = '-2px 7px 3px 5px'; icon.style.background = '#fff url(' + this.getIconUrl_() + ') no-repeat -1px -1px'; icon.style.WebkitBackgroundSize = '57px'; icon.style.WebkitBorderRadius = '10px'; icon.style.WebkitBoxShadow = '0 2px 5px rgba(0, 0, 0, 0.4)'; bubbleInner.insertBefore(icon, bubbleInner.firstChild); var arrow = document.createElement('div'); arrow.style.backgroundImage = 'url(' + this.IMAGE_ARROW_DATA_URL_ + ')'; arrow.style.width = '25px'; arrow.style.height = '19px'; arrow.style.position = 'absolute'; arrow.style.left = '111px'; if (isIpad) { arrow.style.WebkitTransform = 'rotate(180deg)'; arrow.style.top = '-19px'; } else { arrow.style.bottom = '-19px'; } bubbleInner.appendChild(arrow); var close = document.createElement('a'); close.onclick = google.bind(this.closeClickHandler_, this); close.style.position = 'absolute'; close.style.display = 'block'; close.style.top = '-3px'; close.style.right = '-3px'; close.style.width = '16px'; close.style.height = '16px'; close.style.border = '10px solid transparent'; close.style.background = 'url(' + this.IMAGE_CLOSE_DATA_URL_ + ') no-repeat'; bubbleInner.appendChild(close); return bubble; };
JavaScript
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** @fileoverview Example of how to use the bookmark bubble. */ window.addEventListener('load', function() { window.setTimeout(function() { var bubble = new google.bookmarkbubble.Bubble(); var parameter = 'bmb=1'; bubble.hasHashParameter = function() { return window.location.hash.indexOf(parameter) != -1; }; bubble.setHashParameter = function() { if (!this.hasHashParameter()) { window.location.hash += parameter; } }; bubble.getViewportHeight = function() { window.console.log('Example of how to override getViewportHeight.'); return window.innerHeight; }; bubble.getViewportScrollY = function() { window.console.log('Example of how to override getViewportScrollY.'); return window.pageYOffset; }; bubble.registerScrollHandler = function(handler) { window.console.log('Example of how to override registerScrollHandler.'); window.addEventListener('scroll', handler, false); }; bubble.deregisterScrollHandler = function(handler) { window.console.log('Example of how to override deregisterScrollHandler.'); window.removeEventListener('scroll', handler, false); }; bubble.showIfAllowed(); }, 1000); }, false);
JavaScript
/* * Copyright (C) 2008, 2009, 2010 Mihai Şucan * * This file is part of PaintWeb. * * PaintWeb is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PaintWeb is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PaintWeb. If not, see <http://www.gnu.org/licenses/>. * * $URL: http://code.google.com/p/paintweb $ * $Date: 2010-06-26 21:47:30 +0300 $ */ /** * @author <a lang="ro" href="http://www.robodesign.ro/mihai">Mihai Şucan</a> * @fileOverview The default PaintWeb interface code. */ /** * @class The default PaintWeb interface. * * @param {PaintWeb} app Reference to the main paint application object. */ pwlib.gui = function (app) { var _self = this, config = app.config, doc = app.doc, lang = app.lang, MathRound = Math.round, pwlib = window.pwlib, appEvent = pwlib.appEvent, win = app.win; this.app = app; this.idPrefix = 'paintweb' + app.UID + '_', this.classPrefix = 'paintweb_'; /** * Holds references to DOM elements. * @type Object */ this.elems = {}; /** * Holds references to input elements associated to the PaintWeb configuration * properties. * @type Object */ this.inputs = {}; /** * Holds references to DOM elements associated to configuration values. * @type Object */ this.inputValues = {}; /** * Holds references to DOM elements associated to color configuration * properties. * * @type Object * @see pwlib.guiColorInput */ this.colorInputs = {}; /** * Holds references to DOM elements associated to each tool registered in the * current PaintWeb application instance. * * @private * @type Object */ this.tools = {}; /** * Holds references to DOM elements associated to PaintWeb commands. * * @private * @type Object */ this.commands = {}; /** * Holds references to floating panels GUI components. * * @type Object * @see pwlib.guiFloatingPanel */ this.floatingPanels = {zIndex_: 0}; /** * Holds references to tab panel GUI components. * * @type Object * @see pwlib.guiTabPanel */ this.tabPanels = {}; /** * Holds an instance of the guiResizer object attached to the Canvas. * * @private * @type pwlib.guiResizer */ this.canvasResizer = null; /** * Holds an instance of the guiResizer object attached to the viewport * element. * * @private * @type pwlib.guiResizer */ this.viewportResizer = null; /** * Holds tab configuration information for most drawing tools. * * @private * @type Object */ this.toolTabConfig = { bcurve: { lineTab: true, shapeType: true, lineWidth: true, lineWidthLabel: lang.inputs.borderWidth, lineCap: true }, ellipse: { lineTab: true, shapeType: true, lineWidth: true, lineWidthLabel: lang.inputs.borderWidth }, rectangle: { lineTab: true, shapeType: true, lineWidth: true, lineWidthLabel: lang.inputs.borderWidth, lineJoin: true }, polygon: { lineTab: true, shapeType: true, lineWidth: true, lineWidthLabel: lang.inputs.borderWidth, lineJoin: true, lineCap: true, miterLimit: true }, eraser: { lineTab: true, lineWidth: true, lineWidthLabel: lang.inputs.eraserSize, lineJoin: true, lineCap: true, miterLimit: true }, pencil: { lineTab: true, lineWidth: true, lineWidthLabel: lang.inputs.pencilSize, lineJoin: true, lineCap: true, miterLimit: true }, line: { lineTab: true, lineWidth: true, lineWidthLabel: lang.inputs.line.lineWidth, lineJoin: true, lineCap: true, miterLimit: true }, text: { lineTab: true, lineTabLabel: lang.tabs.main.textBorder, shapeType: true, lineWidth: true, lineWidthLabel: lang.inputs.borderWidth } }; /** * Initialize the PaintWeb interface. * * @param {Document|String} markup The interface markup loaded and parsed as * DOM Document object. Optionally, the value can be a string holding the * interface markup (this is used when PaintWeb is packaged). * * @returns {Boolean} True if the initialization was successful, or false if * not. */ this.init = function (markup) { // Make sure the user nicely waits for PaintWeb to load, without seeing // much. var placeholder = config.guiPlaceholder, placeholderStyle = placeholder.style; placeholderStyle.display = 'none'; placeholderStyle.height = '1px'; placeholderStyle.overflow = 'hidden'; placeholderStyle.position = 'absolute'; placeholderStyle.visibility = 'hidden'; placeholder.className += ' ' + this.classPrefix + 'placeholder'; if (!placeholder.tabIndex || placeholder.tabIndex == -1) { placeholder.tabIndex = 1; } if (!this.initImportDoc(markup)) { app.initError(lang.guiMarkupImportFailed); return false; } markup = null; if (!this.initParseMarkup()) { app.initError(lang.guiMarkupParseFailed); return false; } if (!this.initCanvas() || !this.initImageZoom() || !this.initSelectionTool() || !this.initTextTool() || !this.initKeyboardShortcuts()) { return false; } // Setup the main tabbed panel. var panel = this.tabPanels.main; if (!panel) { app.initError(lang.noMainTabPanel); return false; } // Hide the "Shadow" tab if the drawing of shadows is not supported. if (!app.shadowSupported && 'shadow' in panel.tabs) { panel.tabHide('shadow'); } if (!('viewport' in this.elems)) { app.initError(lang.missingViewport); return false; } // Setup the GUI dimensions . this.elems.viewport.style.height = config.viewportHeight; placeholderStyle.width = config.viewportWidth; // Setup the Canvas resizer. var resizeHandle = this.elems.canvasResizer; if (!resizeHandle) { app.initError(lang.missingCanvasResizer); return false; } resizeHandle.title = lang.guiCanvasResizer; resizeHandle.replaceChild(doc.createTextNode(resizeHandle.title), resizeHandle.firstChild); resizeHandle.addEventListener('mouseover', this.item_mouseover, false); resizeHandle.addEventListener('mouseout', this.item_mouseout, false); this.canvasResizer = new pwlib.guiResizer(this, resizeHandle, this.elems.canvasContainer); this.canvasResizer.events.add('guiResizeStart', this.canvasResizeStart); this.canvasResizer.events.add('guiResizeEnd', this.canvasResizeEnd); // Setup the viewport resizer. var resizeHandle = this.elems.viewportResizer; if (!resizeHandle) { app.initError(lang.missingViewportResizer); return false; } resizeHandle.title = lang.guiViewportResizer; resizeHandle.replaceChild(doc.createTextNode(resizeHandle.title), resizeHandle.firstChild); resizeHandle.addEventListener('mouseover', this.item_mouseover, false); resizeHandle.addEventListener('mouseout', this.item_mouseout, false); this.viewportResizer = new pwlib.guiResizer(this, resizeHandle, this.elems.viewport); this.viewportResizer.dispatchMouseMove = true; this.viewportResizer.events.add('guiResizeMouseMove', this.viewportResizeMouseMove); this.viewportResizer.events.add('guiResizeEnd', this.viewportResizeEnd); if ('statusMessage' in this.elems) { this.elems.statusMessage._prevText = false; } // Update the version string in Help. if ('version' in this.elems) { this.elems.version.appendChild(doc.createTextNode(app.toString())); } // Update the image dimensions in the GUI. var imageSize = this.elems.imageSize; if (imageSize) { imageSize.replaceChild(doc.createTextNode(app.image.width + 'x' + app.image.height), imageSize.firstChild); } // Add application-wide event listeners. app.events.add('canvasSizeChange', this.canvasSizeChange); app.events.add('commandRegister', this.commandRegister); app.events.add('commandUnregister', this.commandUnregister); app.events.add('configChange', this.configChangeHandler); app.events.add('imageSizeChange', this.imageSizeChange); app.events.add('imageZoom', this.imageZoom); app.events.add('appInit', this.appInit); app.events.add('shadowAllow', this.shadowAllow); app.events.add('toolActivate', this.toolActivate); app.events.add('toolRegister', this.toolRegister); app.events.add('toolUnregister', this.toolUnregister); // Make sure the historyUndo and historyRedo command elements are // synchronized with the application history state. if ('historyUndo' in this.commands && 'historyRedo' in this.commands) { app.events.add('historyUpdate', this.historyUpdate); } app.commandRegister('about', this.commandAbout); return true; }; /** * Initialize the Canvas elements. * * @private * @returns {Boolean} True if the initialization was successful, or false if * not. */ this.initCanvas = function () { var canvasContainer = this.elems.canvasContainer, layerCanvas = app.layer.canvas, layerContext = app.layer.context, layerStyle = layerCanvas.style, bufferCanvas = app.buffer.canvas; if (!canvasContainer) { app.initError(lang.missingCanvasContainer); return false; } var containerStyle = canvasContainer.style; canvasContainer.className = this.classPrefix + 'canvasContainer'; layerCanvas.className = this.classPrefix + 'layerCanvas'; bufferCanvas.className = this.classPrefix + 'bufferCanvas'; containerStyle.width = layerStyle.width; containerStyle.height = layerStyle.height; if (!config.checkersBackground || pwlib.browser.olpcxo) { containerStyle.backgroundImage = 'none'; } canvasContainer.appendChild(layerCanvas); canvasContainer.appendChild(bufferCanvas); // Make sure the selection transparency input checkbox is disabled if the // putImageData and getImageData methods are unsupported. if ('selection_transparent' in this.inputs && (!layerContext.putImageData || !layerContext.getImageData)) { this.inputs.selection_transparent.disabled = true; this.inputs.selection_transparent.checked = true; } return true; }; /** * Import the DOM nodes from the interface DOM document. All the nodes are * inserted into the {@link PaintWeb.config.guiPlaceholder} element. * * <p>Elements which have the ID attribute will have the attribute renamed to * <code>data-pwId</code>. * * <p>Input elements which have the ID attribute will have their attribute * updated to be unique for the current PaintWeb instance. * * @private * * @param {Document|String} markup The source DOM document to import the nodes * from. Optionally, this parameter can be a string which holds the interface * markup. * * @returns {Boolean} True if the initialization was successful, or false if * not. */ this.initImportDoc = function (markup) { // I could use some XPath here, but for the sake of compatibility I don't. var destElem = config.guiPlaceholder, elType = app.ELEMENT_NODE, elem, root, nodes, n, tag, isInput; if (typeof markup === 'string') { elem = doc.createElement('div'); elem.innerHTML = markup; root = elem.firstChild; } else { root = markup.documentElement; } markup = null; nodes = root.getElementsByTagName('*'); n = nodes.length; // Change all the id attributes to be data-pwId attributes. // Input elements have their ID updated to be unique for the current // PaintWeb instance. for (var i = 0; i < n; i++) { elem = nodes[i]; if (elem.nodeType !== elType || !elem.tagName) { continue; } tag = elem.tagName.toLowerCase(); isInput = tag === 'input' || tag === 'select' || tag === 'textarea'; if (elem.id) { elem.setAttribute('data-pwId', elem.id); if (isInput) { elem.id = this.idPrefix + elem.id; } else { elem.removeAttribute('id'); } } // label elements have their "for" attribute updated as well. if (tag === 'label' && elem.htmlFor) { elem.htmlFor = this.idPrefix + elem.htmlFor; } } // Import all the nodes. n = root.childNodes.length; for (var i = 0; i < n; i++) { destElem.appendChild(doc.importNode(root.childNodes[i], true)); } return true; }; /** * Parse the interface markup. The layout file can have custom * PaintWeb-specific attributes. * * <p>Elements with the <code>data-pwId</code> attribute are added to the * {@link pwlib.gui#elems} object. * * <p>Elements having the <code>data-pwCommand</code> attribute are added to * the {@link pwlib.gui#commands} object. * * <p>Elements having the <code>data-pwTool</code> attribute are added to the * {@link pwlib.gui#tools} object. * * <p>Elements having the <code>data-pwTabPanel</code> attribute are added to * the {@link pwlib.gui#tabPanels} object. These become interactive GUI * components (see {@link pwlib.guiTabPanel}). * * <p>Elements having the <code>data-pwFloatingPanel</code> attribute are * added to the {@link pwlib.gui#floatingPanels} object. These become * interactive GUI components (see {@link pwlib.guiFloatingPanel}). * * <p>Elements having the <code>data-pwConfig</code> attribute are added to * the {@link pwlib.gui#inputs} object. These become interactive GUI * components which allow users to change configuration options. * * <p>Elements having the <code>data-pwConfigValue</code> attribute are added * to the {@link pwlib.gui#inputValues} object. These can only be child nodes * of elements which have the <code>data-pwConfig</code> attribute. Each such * element is considered an icon. Anchor elements are appended to ensure * keyboard accessibility. * * <p>Elements having the <code>data-pwConfigToggle</code> attribute are added * to the {@link pwlib.gui#inputs} object. These become interactive GUI * components which toggle the boolean value of the configuration property * they are associated to. * * <p>Elements having the <code>data-pwColorInput</code> attribute are added * to the {@link pwlib.gui#colorInputs} object. These become color picker * inputs which are associated to the configuration property given as the * attribute value. (see {@link pwlib.guiColorInput}) * * @returns {Boolean} True if the parsing was successful, or false if not. */ this.initParseMarkup = function () { var nodes = config.guiPlaceholder.getElementsByTagName('*'), elType = app.ELEMENT_NODE, elem, tag, isInput, tool, tabPanel, floatingPanel, cmd, id, cfgAttr, colorInput; // Store references to important elements and parse PaintWeb-specific // attributes. for (var i = 0; i < nodes.length; i++) { elem = nodes[i]; if (elem.nodeType !== elType) { continue; } tag = elem.tagName.toLowerCase(); isInput = tag === 'input' || tag === 'select' || tag === 'textarea'; // Store references to commands. cmd = elem.getAttribute('data-pwCommand'); if (cmd && !(cmd in this.commands)) { elem.className += ' ' + this.classPrefix + 'command'; this.commands[cmd] = elem; } // Store references to tools. tool = elem.getAttribute('data-pwTool'); if (tool && !(tool in this.tools)) { elem.className += ' ' + this.classPrefix + 'tool'; this.tools[tool] = elem; } // Create tab panels. tabPanel = elem.getAttribute('data-pwTabPanel'); if (tabPanel) { this.tabPanels[tabPanel] = new pwlib.guiTabPanel(this, elem); } // Create floating panels. floatingPanel = elem.getAttribute('data-pwFloatingPanel'); if (floatingPanel) { this.floatingPanels[floatingPanel] = new pwlib.guiFloatingPanel(this, elem); } cfgAttr = elem.getAttribute('data-pwConfig'); if (cfgAttr) { if (isInput) { this.initConfigInput(elem, cfgAttr); } else { this.initConfigIcons(elem, cfgAttr); } } cfgAttr = elem.getAttribute('data-pwConfigToggle'); if (cfgAttr) { this.initConfigToggle(elem, cfgAttr); } // elem.hasAttribute() fails in webkit (tested with chrome and safari 4) if (elem.getAttribute('data-pwColorInput')) { colorInput = new pwlib.guiColorInput(this, elem); this.colorInputs[colorInput.id] = colorInput; } id = elem.getAttribute('data-pwId'); if (id) { elem.className += ' ' + this.classPrefix + id; // Store a reference to the element. if (isInput && !cfgAttr) { this.inputs[id] = elem; } else if (!isInput) { this.elems[id] = elem; } } } return true; }; /** * Initialize an input element associated to a configuration property. * * @private * * @param {Element} elem The DOM element which is associated to the * configuration property. * * @param {String} cfgAttr The configuration attribute. This tells the * configuration group and property to which the DOM element is attached to. */ this.initConfigInput = function (input, cfgAttr) { var cfgNoDots = cfgAttr.replace('.', '_'), cfgArray = cfgAttr.split('.'), cfgProp = cfgArray.pop(), cfgGroup = cfgArray.join('.'), cfgGroupRef = config, langGroup = lang.inputs, labelElem = input.parentNode; for (var i = 0, n = cfgArray.length; i < n; i++) { cfgGroupRef = cfgGroupRef[cfgArray[i]]; langGroup = langGroup[cfgArray[i]]; } input._pwConfigProperty = cfgProp; input._pwConfigGroup = cfgGroup; input._pwConfigGroupRef = cfgGroupRef; input.title = langGroup[cfgProp + 'Title'] || langGroup[cfgProp]; input.className += ' ' + this.classPrefix + 'cfg_' + cfgNoDots; this.inputs[cfgNoDots] = input; if (labelElem.tagName.toLowerCase() !== 'label') { labelElem = labelElem.getElementsByTagName('label')[0]; } if (input.type === 'checkbox' || labelElem.htmlFor) { labelElem.replaceChild(doc.createTextNode(langGroup[cfgProp]), labelElem.lastChild); } else { labelElem.replaceChild(doc.createTextNode(langGroup[cfgProp]), labelElem.firstChild); } if (input.type === 'checkbox') { input.checked = cfgGroupRef[cfgProp]; } else { input.value = cfgGroupRef[cfgProp]; } input.addEventListener('input', this.configInputChange, false); input.addEventListener('change', this.configInputChange, false); }; /** * Initialize an HTML element associated to a configuration property, and all * of its own sub-elements associated to configuration values. Each element * that has the <var>data-pwConfigValue</var> attribute is considered an icon. * * @private * * @param {Element} elem The DOM element which is associated to the * configuration property. * * @param {String} cfgAttr The configuration attribute. This tells the * configuration group and property to which the DOM element is attached to. */ this.initConfigIcons = function (input, cfgAttr) { var cfgNoDots = cfgAttr.replace('.', '_'), cfgArray = cfgAttr.split('.'), cfgProp = cfgArray.pop(), cfgGroup = cfgArray.join('.'), cfgGroupRef = config, langGroup = lang.inputs; for (var i = 0, n = cfgArray.length; i < n; i++) { cfgGroupRef = cfgGroupRef[cfgArray[i]]; langGroup = langGroup[cfgArray[i]]; } input._pwConfigProperty = cfgProp; input._pwConfigGroup = cfgGroup; input._pwConfigGroupRef = cfgGroupRef; input.title = langGroup[cfgProp + 'Title'] || langGroup[cfgProp]; input.className += ' ' + this.classPrefix + 'cfg_' + cfgNoDots; this.inputs[cfgNoDots] = input; var labelElem = input.getElementsByTagName('p')[0]; labelElem.replaceChild(doc.createTextNode(langGroup[cfgProp]), labelElem.firstChild); var elem, anchor, val, className = ' ' + this.classPrefix + 'configActive'; nodes = input.getElementsByTagName('*'), elType = app.ELEMENT_NODE; for (var i = 0; i < nodes.length; i++) { elem = nodes[i]; if (elem.nodeType !== elType) { continue; } val = elem.getAttribute('data-pwConfigValue'); if (!val) { continue; } anchor = doc.createElement('a'); anchor.href = '#'; anchor.title = langGroup[cfgProp + '_' + val]; anchor.appendChild(doc.createTextNode(anchor.title)); elem.className += ' ' + this.classPrefix + cfgProp + '_' + val + ' ' + this.classPrefix + 'icon'; elem._pwConfigParent = input; if (cfgGroupRef[cfgProp] == val) { elem.className += className; } anchor.addEventListener('click', this.configValueClick, false); anchor.addEventListener('mouseover', this.item_mouseover, false); anchor.addEventListener('mouseout', this.item_mouseout, false); elem.replaceChild(anchor, elem.firstChild); this.inputValues[cfgGroup + '_' + cfgProp + '_' + val] = elem; } }; /** * Initialize an HTML element associated to a boolean configuration property. * * @private * * @param {Element} elem The DOM element which is associated to the * configuration property. * * @param {String} cfgAttr The configuration attribute. This tells the * configuration group and property to which the DOM element is attached to. */ this.initConfigToggle = function (input, cfgAttr) { var cfgNoDots = cfgAttr.replace('.', '_'), cfgArray = cfgAttr.split('.'), cfgProp = cfgArray.pop(), cfgGroup = cfgArray.join('.'), cfgGroupRef = config, langGroup = lang.inputs; for (var i = 0, n = cfgArray.length; i < n; i++) { cfgGroupRef = cfgGroupRef[cfgArray[i]]; langGroup = langGroup[cfgArray[i]]; } input._pwConfigProperty = cfgProp; input._pwConfigGroup = cfgGroup; input._pwConfigGroupRef = cfgGroupRef; input.className += ' ' + this.classPrefix + 'cfg_' + cfgNoDots + ' ' + this.classPrefix + 'icon'; if (cfgGroupRef[cfgProp]) { input.className += ' ' + this.classPrefix + 'configActive'; } var anchor = doc.createElement('a'); anchor.href = '#'; anchor.title = langGroup[cfgProp + 'Title'] || langGroup[cfgProp]; anchor.appendChild(doc.createTextNode(langGroup[cfgProp])); anchor.addEventListener('click', this.configToggleClick, false); anchor.addEventListener('mouseover', this.item_mouseover, false); anchor.addEventListener('mouseout', this.item_mouseout, false); input.replaceChild(anchor, input.firstChild); this.inputs[cfgNoDots] = input; }; /** * Initialize the image zoom input. * * @private * @returns {Boolean} True if the initialization was successful, or false if * not. */ this.initImageZoom = function () { var input = this.inputs.imageZoom; if (!input) { return true; // allow layouts without the zoom input } input.value = 100; input._old_value = 100; // Override the attributes, based on the settings. input.setAttribute('step', config.imageZoomStep * 100); input.setAttribute('max', config.imageZoomMax * 100); input.setAttribute('min', config.imageZoomMin * 100); var changeFn = function () { app.imageZoomTo(parseInt(this.value) / 100); }; input.addEventListener('change', changeFn, false); input.addEventListener('input', changeFn, false); // Update some language strings var label = input.parentNode; if (label.tagName.toLowerCase() === 'label') { label.replaceChild(doc.createTextNode(lang.imageZoomLabel), label.firstChild); } var elem = this.elems.statusZoom; if (!elem) { return true; } elem.title = lang.imageZoomTitle; return true; }; /** * Initialize GUI elements associated to selection tool options and commands. * * @private * @returns {Boolean} True if the initialization was successful, or false if * not. */ this.initSelectionTool = function () { var classDisabled = ' ' + this.classPrefix + 'disabled', cut = this.commands.selectionCut, copy = this.commands.selectionCopy, paste = this.commands.clipboardPaste; if (paste) { app.events.add('clipboardUpdate', this.clipboardUpdate); paste.className += classDisabled; } if (cut && copy) { app.events.add('selectionChange', this.selectionChange); cut.className += classDisabled; copy.className += classDisabled; } var selTab_cmds = ['selectionCut', 'selectionCopy', 'clipboardPaste'], anchor, elem, cmd; for (var i = 0, n = selTab_cmds.length; i < n; i++) { cmd = selTab_cmds[i]; elem = this.elems['selTab_' + cmd]; if (!elem) { continue; } anchor = doc.createElement('a'); anchor.title = lang.commands[cmd]; anchor.href = '#'; anchor.appendChild(doc.createTextNode(anchor.title)); anchor.addEventListener('click', this.commandClick, false); elem.className += classDisabled + ' ' + this.classPrefix + 'command' + ' ' + this.classPrefix + 'cmd_' + cmd; elem.setAttribute('data-pwCommand', cmd); elem.replaceChild(anchor, elem.firstChild); } var selCrop = this.commands.selectionCrop, selFill = this.commands.selectionFill, selDelete = this.commands.selectionDelete; selCrop.className += classDisabled; selFill.className += classDisabled; selDelete.className += classDisabled; return true; }; /** * Initialize GUI elements associated to text tool options. * * @private * @returns {Boolean} True if the initialization was successful, or false if * not. */ this.initTextTool = function () { if ('textString' in this.inputs) { this.inputs.textString.value = lang.inputs.text.textString_value; } if (!('text_fontFamily' in this.inputs) || !('text' in config) || !('fontFamilies' in config.text)) { return true; } var option, input = this.inputs.text_fontFamily; for (var i = 0, n = config.text.fontFamilies.length; i < n; i++) { option = doc.createElement('option'); option.value = config.text.fontFamilies[i]; option.appendChild(doc.createTextNode(option.value)); input.appendChild(option); if (option.value === config.text.fontFamily) { input.selectedIndex = i; input.value = option.value; } } option = doc.createElement('option'); option.value = '+'; option.appendChild(doc.createTextNode(lang.inputs.text.fontFamily_add)); input.appendChild(option); return true; }; /** * Initialize the keyboard shortcuts. Basically, this updates various strings * to ensure the user interface is informational. * * @private * @returns {Boolean} True if the initialization was successful, or false if * not. */ this.initKeyboardShortcuts = function () { var kid = null, kobj = null; for (kid in config.keys) { kobj = config.keys[kid]; if ('toolActivate' in kobj && kobj.toolActivate in lang.tools) { lang.tools[kobj.toolActivate] += ' [ ' + kid + ' ]'; } if ('command' in kobj && kobj.command in lang.commands) { lang.commands[kobj.command] += ' [ ' + kid + ' ]'; } } return true; }; /** * The <code>appInit</code> event handler. This method is invoked once * PaintWeb completes all the loading. * * <p>This method dispatches the {@link pwlib.appEvent.guiShow} application * event. * * @private * @param {pwlib.appEvent.appInit} ev The application event object. */ this.appInit = function (ev) { // Initialization was not successful ... if (ev.state !== PaintWeb.INIT_DONE) { return; } // Make sure the Hand tool is enabled/disabled as needed. if ('hand' in _self.tools) { app.events.add('canvasSizeChange', _self.toolHandStateChange); app.events.add('viewportSizeChange', _self.toolHandStateChange); _self.toolHandStateChange(ev); } // Make PaintWeb visible. var placeholder = config.guiPlaceholder, placeholderStyle = placeholder.style; // We do not reset the display property. We leave this for the stylesheet. placeholderStyle.height = ''; placeholderStyle.overflow = ''; placeholderStyle.position = ''; placeholderStyle.visibility = ''; var cs = win.getComputedStyle(placeholder, null); // Do not allow the static positioning for the PaintWeb placeholder. // Usually, the GUI requires absolute/relative positioning. if (cs.position === 'static') { placeholderStyle.position = 'relative'; } try { placeholder.focus(); } catch (err) { } app.events.dispatch(new appEvent.guiShow()); }; /** * The <code>guiResizeStart</code> event handler for the Canvas resize * operation. * @private */ this.canvasResizeStart = function () { this.resizeHandle.style.visibility = 'hidden'; // ugly... this.timeout_ = setTimeout(function () { _self.statusShow('guiCanvasResizerActive', true); clearTimeout(_self.canvasResizer.timeout_); delete _self.canvasResizer.timeout_; }, 400); }; /** * The <code>guiResizeEnd</code> event handler for the Canvas resize * operation. * * @private * @param {pwlib.appEvent.guiResizeEnd} ev The application event object. */ this.canvasResizeEnd = function (ev) { this.resizeHandle.style.visibility = ''; app.imageCrop(0, 0, MathRound(ev.width / app.image.canvasScale), MathRound(ev.height / app.image.canvasScale)); if (this.timeout_) { clearTimeout(this.timeout_); delete this.timeout_; } else { _self.statusShow(-1); } }; /** * The <code>guiResizeMouseMove</code> event handler for the viewport resize * operation. * * @private * @param {pwlib.appEvent.guiResizeMouseMove} ev The application event object. */ this.viewportResizeMouseMove = function (ev) { config.guiPlaceholder.style.width = ev.width + 'px'; }; /** * The <code>guiResizeEnd</code> event handler for the viewport resize * operation. * * @private * @param {pwlib.appEvent.guiResizeEnd} ev The application event object. */ this.viewportResizeEnd = function (ev) { _self.elems.viewport.style.width = ''; _self.resizeTo(ev.width + 'px', ev.height + 'px'); try { config.guiPlaceholder.focus(); } catch (err) { } }; /** * The <code>mouseover</code> event handler for all tools, commands and icons. * This simply shows the title / text content of the element in the GUI status * bar. * * @see pwlib.gui#statusShow The method used for displaying the message in the * GUI status bar. */ this.item_mouseover = function () { if (this.title || this.textConent) { _self.statusShow(this.title || this.textContent, true); } }; /** * The <code>mouseout</code> event handler for all tools, commands and icons. * This method simply resets the GUI status bar to the previous message it was * displaying before the user hovered the current element. * * @see pwlib.gui#statusShow The method used for displaying the message in the * GUI status bar. */ this.item_mouseout = function () { _self.statusShow(-1); }; /** * Show a message in the status bar. * * @param {String|Number} msg The message ID you want to display. The ID * should be available in the {@link PaintWeb.lang.status} object. If the * value is -1 then the previous non-temporary message will be displayed. If * the ID is not available in the language file, then the string is shown * as-is. * * @param {Boolean} [temporary=false] Tells if the message is temporary or * not. */ this.statusShow = function (msg, temporary) { var elem = this.elems.statusMessage; if (msg === -1 && elem._prevText === false) { return false; } if (msg === -1) { msg = elem._prevText; } if (msg in lang.status) { msg = lang.status[msg]; } if (!temporary) { elem._prevText = msg; } if (elem.firstChild) { elem.removeChild(elem.firstChild); } win.status = msg; if (msg) { elem.appendChild(doc.createTextNode(msg)); } }; /** * The "About" command. This method displays the "About" panel. */ this.commandAbout = function () { _self.floatingPanels.about.toggle(); }; /** * The <code>click</code> event handler for the tool DOM elements. * * @private * * @param {Event} ev The DOM Event object. * * @see PaintWeb#toolActivate to activate a drawing tool. */ this.toolClick = function (ev) { app.toolActivate(this.parentNode.getAttribute('data-pwTool'), ev); ev.preventDefault(); }; /** * The <code>toolActivate</code> application event handler. This method * provides visual feedback for the activation of a new drawing tool. * * @private * * @param {pwlib.appEvent.toolActivate} ev The application event object. * * @see PaintWeb#toolActivate the method which allows you to activate * a drawing tool. */ this.toolActivate = function (ev) { var tabAnchor, tabActive = _self.tools[ev.id], tabConfig = _self.toolTabConfig[ev.id] || {}, tabPanel = _self.tabPanels.main, lineTab = tabPanel.tabs.line, shapeType = _self.inputs.shapeType, lineWidth = _self.inputs.line_lineWidth, lineCap = _self.inputs.line_lineCap, lineJoin = _self.inputs.line_lineJoin, miterLimit = _self.inputs.line_miterLimit, lineWidthLabel = null; tabActive.className += ' ' + _self.classPrefix + 'toolActive'; try { tabActive.firstChild.focus(); } catch (err) { } if ((ev.id + 'Active') in lang.status) { _self.statusShow(ev.id + 'Active'); } // show/hide the shapeType input config. if (shapeType) { if (tabConfig.shapeType) { shapeType.style.display = ''; } else { shapeType.style.display = 'none'; } } if (ev.prevId) { var prevTab = _self.tools[ev.prevId], prevTabConfig = _self.toolTabConfig[ev.prevId] || {}; prevTab.className = prevTab.className. replace(' ' + _self.classPrefix + 'toolActive', ''); // hide the line tab if (prevTabConfig.lineTab && lineTab) { tabPanel.tabHide('line'); lineTab.container.className = lineTab.container.className. replace(' ' + _self.classPrefix + 'main_line_' + ev.prevId, ' ' + _self.classPrefix + 'main_line'); } // hide the tab for the current tool. if (ev.prevId in tabPanel.tabs) { tabPanel.tabHide(ev.prevId); } } // Change the label of the lineWidth input element. if (tabConfig.lineWidthLabel) { lineWidthLabel = lineWidth.parentNode; lineWidthLabel.replaceChild(doc.createTextNode(tabConfig.lineWidthLabel), lineWidthLabel.firstChild); } if (lineJoin) { if (tabConfig.lineJoin) { lineJoin.style.display = ''; } else { lineJoin.style.display = 'none'; } } if (lineCap) { if (tabConfig.lineCap) { lineCap.style.display = ''; } else { lineCap.style.display = 'none'; } } if (miterLimit) { if (tabConfig.miterLimit) { miterLimit.parentNode.parentNode.style.display = ''; } else { miterLimit.parentNode.parentNode.style.display = 'none'; } } if (lineWidth) { if (tabConfig.lineWidth) { lineWidth.parentNode.parentNode.style.display = ''; } else { lineWidth.parentNode.parentNode.style.display = 'none'; } } // show the line tab, if configured if (tabConfig.lineTab && 'line' in tabPanel.tabs) { tabAnchor = lineTab.button.firstChild; tabAnchor.title = tabConfig.lineTabLabel || lang.tabs.main[ev.id]; tabAnchor.replaceChild(doc.createTextNode(tabAnchor.title), tabAnchor.firstChild); if (ev.id !== 'line') { lineTab.container.className = lineTab.container.className. replace(' ' + _self.classPrefix + 'main_line', ' ' + _self.classPrefix + 'main_line_' + ev.id); } tabPanel.tabShow('line'); } // show the tab for the current tool, if there's one. if (ev.id in tabPanel.tabs) { tabPanel.tabShow(ev.id); } }; /** * The <code>toolRegister</code> application event handler. This method adds * the new tool into the GUI. * * @private * * @param {pwlib.appEvent.toolRegister} ev The application event object. * * @see PaintWeb#toolRegister the method which allows you to register new * tools. */ this.toolRegister = function (ev) { var attr = null, elem = null, anchor = null; if (ev.id in _self.tools) { elem = _self.tools[ev.id]; attr = elem.getAttribute('data-pwTool'); if (attr && attr !== ev.id) { attr = null; elem = null; delete _self.tools[ev.id]; } } // Create a new element if there's none already associated to the tool ID. if (!elem) { elem = doc.createElement('li'); } if (!attr) { elem.setAttribute('data-pwTool', ev.id); } elem.className += ' ' + _self.classPrefix + 'tool_' + ev.id; // Append an anchor element which holds the locale string. anchor = doc.createElement('a'); anchor.title = lang.tools[ev.id]; anchor.href = '#'; anchor.appendChild(doc.createTextNode(anchor.title)); if (elem.firstChild) { elem.replaceChild(anchor, elem.firstChild); } else { elem.appendChild(anchor); } anchor.addEventListener('click', _self.toolClick, false); anchor.addEventListener('mouseover', _self.item_mouseover, false); anchor.addEventListener('mouseout', _self.item_mouseout, false); if (!(ev.id in _self.tools)) { _self.tools[ev.id] = elem; _self.elems.tools.appendChild(elem); } // Disable the text tool icon if the Canvas Text API is not supported. if (ev.id === 'text' && !app.layer.context.fillText && !app.layer.context.mozPathText && elem) { elem.className += ' ' + _self.classPrefix + 'disabled'; anchor.title = lang.tools.textUnsupported; anchor.removeEventListener('click', _self.toolClick, false); anchor.addEventListener('click', function (ev) { ev.preventDefault(); }, false); } }; /** * The <code>toolUnregister</code> application event handler. This method the * tool element from the GUI. * * @param {pwlib.appEvent.toolUnregister} ev The application event object. * * @see PaintWeb#toolUnregister the method which allows you to unregister * tools. */ this.toolUnregister = function (ev) { if (ev.id in _self.tools) { _self.elems.tools.removeChild(_self.tools[ev.id]); delete _self.tools[ev.id]; } else { return; } }; /** * The <code>click</code> event handler for the command DOM elements. * * @private * * @param {Event} ev The DOM Event object. * * @see PaintWeb#commandRegister to register a new command. */ this.commandClick = function (ev) { var cmd = this.parentNode.getAttribute('data-pwCommand'); if (cmd && cmd in app.commands) { app.commands[cmd].call(this, ev); } ev.preventDefault(); try { this.focus(); } catch (err) { } }; /** * The <code>commandRegister</code> application event handler. GUI elements * associated to commands are updated to ensure proper user interaction. * * @private * * @param {pwlib.appEvent.commandRegister} ev The application event object. * * @see PaintWeb#commandRegister the method which allows you to register new * commands. */ this.commandRegister = function (ev) { var elem = _self.commands[ev.id], anchor = null; if (!elem) { return; } elem.className += ' ' + _self.classPrefix + 'cmd_' + ev.id; anchor = doc.createElement('a'); anchor.title = lang.commands[ev.id]; anchor.href = '#'; anchor.appendChild(doc.createTextNode(anchor.title)); // Remove the text content and append the locale string associated to // current command inside an anchor element (for better keyboard // accessibility). if (elem.firstChild) { elem.removeChild(elem.firstChild); } elem.appendChild(anchor); anchor.addEventListener('click', _self.commandClick, false); anchor.addEventListener('mouseover', _self.item_mouseover, false); anchor.addEventListener('mouseout', _self.item_mouseout, false); }; /** * The <code>commandUnregister</code> application event handler. This method * simply removes all the user interactivity from the GUI element associated * to the command being unregistered. * * @private * * @param {pwlib.appEvent.commandUnregister} ev The application event object. * * @see PaintWeb#commandUnregister the method which allows you to unregister * commands. */ this.commandUnregister = function (ev) { var elem = _self.commands[ev.id], anchor = null; if (!elem) { return; } elem.className = elem.className.replace(' ' + _self.classPrefix + 'cmd_' + ev.id, ''); anchor = elem.firstChild; anchor.removeEventListener('click', this.commands[ev.id], false); anchor.removeEventListener('mouseover', _self.item_mouseover, false); anchor.removeEventListener('mouseout', _self.item_mouseout, false); elem.removeChild(anchor); }; /** * The <code>historyUpdate</code> application event handler. GUI elements * associated to the <code>historyUndo</code> and to the * <code>historyRedo</code> commands are updated such that they are either * enabled or disabled, depending on the current history position. * * @private * * @param {pwlib.appEvent.historyUpdate} ev The application event object. * * @see PaintWeb#historyGoto the method which allows you to go to different * history states. */ this.historyUpdate = function (ev) { var undoElem = _self.commands.historyUndo, undoState = false, redoElem = _self.commands.historyRedo, redoState = false, className = ' ' + _self.classPrefix + 'disabled', undoElemState = undoElem.className.indexOf(className) === -1, redoElemState = redoElem.className.indexOf(className) === -1; if (ev.currentPos > 1) { undoState = true; } if (ev.currentPos < ev.states) { redoState = true; } if (undoElemState !== undoState) { if (undoState) { undoElem.className = undoElem.className.replace(className, ''); } else { undoElem.className += className; } } if (redoElemState !== redoState) { if (redoState) { redoElem.className = redoElem.className.replace(className, ''); } else { redoElem.className += className; } } }; /** * The <code>imageSizeChange</code> application event handler. The GUI element * which displays the image dimensions is updated to display the new image * size. * * <p>Image size refers strictly to the dimensions of the image being edited * by the user, that's width and height. * * @private * @param {pwlib.appEvent.imageSizeChange} ev The application event object. */ this.imageSizeChange = function (ev) { var imageSize = _self.elems.imageSize; if (imageSize) { imageSize.replaceChild(doc.createTextNode(ev.width + 'x' + ev.height), imageSize.firstChild); } }; /** * The <code>canvasSizeChange</code> application event handler. The Canvas * container element dimensions are updated to the new values, and the image * resize handle is positioned accordingly. * * <p>Canvas size refers strictly to the dimensions of the Canvas elements in * the browser, changed with CSS style properties, width and height. Scaling * of the Canvas elements is applied when the user zooms the image or when the * browser changes the render DPI / zoom. * * @private * @param {pwlib.appEvent.canvasSizeChange} ev The application event object. */ this.canvasSizeChange = function (ev) { var canvasContainer = _self.elems.canvasContainer, canvasResizer = _self.canvasResizer, className = ' ' + _self.classPrefix + 'disabled', resizeHandle = canvasResizer.resizeHandle; // Update the Canvas container to be the same size as the Canvas elements. canvasContainer.style.width = ev.width + 'px'; canvasContainer.style.height = ev.height + 'px'; resizeHandle.style.top = ev.height + 'px'; resizeHandle.style.left = ev.width + 'px'; }; /** * The <code>imageZoom</code> application event handler. The GUI input element * which displays the image zoom level is updated to display the new value. * * @private * @param {pwlib.appEvent.imageZoom} ev The application event object. */ this.imageZoom = function (ev) { var elem = _self.inputs.imageZoom, val = MathRound(ev.zoom * 100); if (elem && elem.value != val) { elem.value = val; } }; /** * The <code>configChange</code> application event handler. This method * ensures the GUI input elements stay up-to-date when some PaintWeb * configuration is modified. * * @private * @param {pwlib.appEvent.configChange} ev The application event object. */ this.configChangeHandler = function (ev) { var cfg = '', input; if (ev.group) { cfg = ev.group.replace('.', '_') + '_'; } cfg += ev.config; input = _self.inputs[cfg]; // Handle changes for color inputs. if (!input && (input = _self.colorInputs[cfg])) { var color = ev.value.replace(/\s+/g, ''). replace(/^rgba\(/, '').replace(/\)$/, ''); color = color.split(','); input.updateColor({ red: color[0] / 255, green: color[1] / 255, blue: color[2] / 255, alpha: color[3] }); return; } if (!input) { return; } var tag = input.tagName.toLowerCase(), isInput = tag === 'select' || tag === 'input' || tag === 'textarea'; if (isInput) { if (input.type === 'checkbox' && input.checked !== ev.value) { input.checked = ev.value; } if (input.type !== 'checkbox' && input.value !== ev.value) { input.value = ev.value; } return; } var classActive = ' ' + _self.className + 'configActive'; if (input.hasAttribute('data-pwConfigToggle')) { var inputActive = input.className.indexOf(classActive) !== -1; if (ev.value && !inputActive) { input.className += classActive; } else if (!ev.value && inputActive) { input.className = input.className.replace(classActive, ''); } } var classActive = ' ' + _self.className + 'configActive', prevValElem = _self.inputValues[cfg + '_' + ev.previousValue], valElem = _self.inputValues[cfg + '_' + ev.value]; if (prevValElem && prevValElem.className.indexOf(classActive) !== -1) { prevValElem.className = prevValElem.className.replace(classActive, ''); } if (valElem && valElem.className.indexOf(classActive) === -1) { valElem.className += classActive; } }; /** * The <code>click</code> event handler for DOM elements associated to * PaintWeb configuration values. These elements rely on parent elements which * are associated to configuration properties. * * <p>This method dispatches the {@link pwlib.appEvent.configChange} event. * * @private * @param {Event} ev The DOM Event object. */ this.configValueClick = function (ev) { var pNode = this.parentNode, input = pNode._pwConfigParent, val = pNode.getAttribute('data-pwConfigValue'); if (!input || !input._pwConfigProperty) { return; } ev.preventDefault(); var className = ' ' + _self.classPrefix + 'configActive', groupRef = input._pwConfigGroupRef, group = input._pwConfigGroup, prop = input._pwConfigProperty, prevVal = groupRef[prop], prevValElem = _self.inputValues[group.replace('.', '_') + '_' + prop + '_' + prevVal]; if (prevVal == val) { return; } if (prevValElem && prevValElem.className.indexOf(className) !== -1) { prevValElem.className = prevValElem.className.replace(className, ''); } groupRef[prop] = val; if (pNode.className.indexOf(className) === -1) { pNode.className += className; } app.events.dispatch(new appEvent.configChange(val, prevVal, prop, group, groupRef)); }; /** * The <code>change</code> event handler for input elements associated to * PaintWeb configuration properties. * * <p>This method dispatches the {@link pwlib.appEvent.configChange} event. * * @private */ this.configInputChange = function () { if (!this._pwConfigProperty) { return; } var val = this.type === 'checkbox' ? this.checked : this.value, groupRef = this._pwConfigGroupRef, group = this._pwConfigGroup, prop = this._pwConfigProperty, prevVal = groupRef[prop]; if (this.getAttribute('type') === 'number') { val = parseInt(val); if (val != this.value) { this.value = val; } } if (val == prevVal) { return; } groupRef[prop] = val; app.events.dispatch(new appEvent.configChange(val, prevVal, prop, group, groupRef)); }; /** * The <code>click</code> event handler for DOM elements associated to boolean * configuration properties. These elements only toggle the true/false value * of the configuration property. * * <p>This method dispatches the {@link pwlib.appEvent.configChange} event. * * @private * @param {Event} ev The DOM Event object. */ this.configToggleClick = function (ev) { var className = ' ' + _self.classPrefix + 'configActive', pNode = this.parentNode, groupRef = pNode._pwConfigGroupRef, group = pNode._pwConfigGroup, prop = pNode._pwConfigProperty, elemActive = pNode.className.indexOf(className) !== -1; ev.preventDefault(); groupRef[prop] = !groupRef[prop]; if (groupRef[prop] && !elemActive) { pNode.className += className; } else if (!groupRef[prop] && elemActive) { pNode.className = pNode.className.replace(className, ''); } app.events.dispatch(new appEvent.configChange(groupRef[prop], !groupRef[prop], prop, group, groupRef)); }; /** * The <code>shadowAllow</code> application event handler. This method * shows/hide the shadow tab when shadows are allowed/disallowed. * * @private * @param {pwlib.appEvent.shadowAllow} ev The application event object. */ this.shadowAllow = function (ev) { if ('shadow' in _self.tabPanels.main.tabs) { if (ev.allowed) { _self.tabPanels.main.tabShow('shadow'); } else { _self.tabPanels.main.tabHide('shadow'); } } }; /** * The <code>clipboardUpdate</code> application event handler. The GUI element * associated to the <code>clipboardPaste</code> command is updated to be * disabled/enabled depending on the event. * * @private * @param {pwlib.appEvent.clipboardUpdate} ev The application event object. */ this.clipboardUpdate = function (ev) { var classDisabled = ' ' + _self.classPrefix + 'disabled', elem, elemEnabled, elems = [_self.commands.clipboardPaste, _self.elems.selTab_clipboardPaste]; for (var i = 0, n = elems.length; i < n; i++) { elem = elems[i]; if (!elem) { continue; } elemEnabled = elem.className.indexOf(classDisabled) === -1; if (!ev.data && elemEnabled) { elem.className += classDisabled; } else if (ev.data && !elemEnabled) { elem.className = elem.className.replace(classDisabled, ''); } } }; /** * The <code>selectionChange</code> application event handler. The GUI * elements associated to the <code>selectionCut</code> and * <code>selectionCopy</code> commands are updated to be disabled/enabled * depending on the event. * * @private * @param {pwlib.appEvent.selectionChange} ev The application event object. */ this.selectionChange = function (ev) { var classDisabled = ' ' + _self.classPrefix + 'disabled', elem, elemEnabled, elems = [_self.commands.selectionCut, _self.commands.selectionCopy, _self.elems.selTab_selectionCut, _self.elems.selTab_selectionCopy, _self.commands.selectionDelete, _self.commands.selectionFill, _self.commands.selectionCrop]; for (var i = 0, n = elems.length; i < n; i++) { elem = elems[i]; if (!elem) { continue; } elemEnabled = elem.className.indexOf(classDisabled) === -1; if (ev.state === ev.STATE_NONE && elemEnabled) { elem.className += classDisabled; } else if (ev.state === ev.STATE_SELECTED && !elemEnabled) { elem.className = elem.className.replace(classDisabled, ''); } } }; /** * Show the graphical user interface. * * <p>This method dispatches the {@link pwlib.appEvent.guiShow} application * event. */ this.show = function () { var placeholder = config.guiPlaceholder, className = this.classPrefix + 'placeholder', re = new RegExp('\\b' + className); if (!re.test(placeholder.className)) { placeholder.className += ' ' + className; } try { placeholder.focus(); } catch (err) { } app.events.dispatch(new appEvent.guiShow()); }; /** * Hide the graphical user interface. * * <p>This method dispatches the {@link pwlib.appEvent.guiHide} application * event. */ this.hide = function () { var placeholder = config.guiPlaceholder, re = new RegExp('\\b' + this.classPrefix + 'placeholder', 'g'); placeholder.className = placeholder.className.replace(re, ''); app.events.dispatch(new appEvent.guiHide()); }; /** * The application destroy event handler. This method is invoked by the main * PaintWeb application when the instance is destroyed, for the purpose of * cleaning-up the GUI-related things from the document add by the current * instance. * * @private */ this.destroy = function () { var placeholder = config.guiPlaceholder; while(placeholder.hasChildNodes()) { placeholder.removeChild(placeholder.firstChild); } }; /** * Resize the PaintWeb graphical user interface. * * <p>This method dispatches the {@link pwlib.appEvent.configChange} event for * the "viewportWidth" and "viewportHeight" configuration properties. Both * properties are updated to hold the new values you give. * * <p>Once the GUI is resized, the {@link pwlib.appEvent.viewportSizeChange} * event is also dispatched. * * @param {String} width The new width you want. Make sure the value is a CSS * length, like "50%", "450px" or "30em". * * @param {String} height The new height you want. */ this.resizeTo = function (width, height) { if (!width || !height) { return; } var width_old = config.viewportWidth, height_old = config.viewportHeight; config.viewportWidth = width; config.viewportHeight = height; app.events.dispatch(new appEvent.configChange(width, width_old, 'viewportWidth', '', config)); app.events.dispatch(new appEvent.configChange(height, height_old, 'viewportHeight', '', config)); config.guiPlaceholder.style.width = config.viewportWidth; this.elems.viewport.style.height = config.viewportHeight; app.events.dispatch(new appEvent.viewportSizeChange(width, height)); }; /** * The state change event handler for the Hand tool. This function * enables/disables the Hand tool by checking if the current image fits into * the viewport or not. * * <p>This function is invoked when one of the following application events is * dispatched: <code>viewportSizeChange</code>, <code>canvasSizeChange</code> * or <code>appInit</code. * * @private * @param * {pwlib.appEvent.viewportSizeChange|pwlib.appEvent.canvasSizeChange|pwlib.appEvent.appInit} * [ev] The application event object. */ this.toolHandStateChange = function (ev) { var cwidth = 0, cheight = 0, className = ' ' + _self.classPrefix + 'disabled', hand = _self.tools.hand, viewport = _self.elems.viewport; if (!hand) { return; } if (ev.type === 'canvasSizeChange') { cwidth = ev.width; cheight = ev.height; } else { var containerStyle = _self.elems.canvasContainer.style; cwidth = parseInt(containerStyle.width); cheight = parseInt(containerStyle.height); } // FIXME: it should be noted that when PaintWeb loads, the entire GUI is // hidden, and win.getComputedStyle() style tells that the viewport // width/height is 0. cs = win.getComputedStyle(viewport, null); var vwidth = parseInt(cs.width), vheight = parseInt(cs.height), enableHand = false, handState = hand.className.indexOf(className) === -1; if (vheight < cheight || vwidth < cwidth) { enableHand = true; } if (enableHand && !handState) { hand.className = hand.className.replace(className, ''); } else if (!enableHand && handState) { hand.className += className; } if (!enableHand && app.tool && app.tool._id === 'hand' && 'prevTool' in app.tool) { app.toolActivate(app.tool.prevTool, ev); } }; }; /** * @class A floating panel GUI element. * * @private * * @param {pwlib.gui} gui Reference to the PaintWeb GUI object. * * @param {Element} container Reference to the DOM element you want to transform * into a floating panel. */ pwlib.guiFloatingPanel = function (gui, container) { var _self = this, appEvent = pwlib.appEvent, cStyle = container.style, doc = gui.app.doc, guiPlaceholder = gui.app.config.guiPlaceholder, lang = gui.app.lang, panels = gui.floatingPanels, win = gui.app.win, zIndex_step = 200; // These hold the mouse starting location during the drag operation. var mx, my; // These hold the panel starting location during the drag operation. var ptop, pleft; /** * Panel state: hidden. * @constant */ this.STATE_HIDDEN = 0; /** * Panel state: visible. * @constant */ this.STATE_VISIBLE = 1; /** * Panel state: minimized. * @constant */ this.STATE_MINIMIZED = 3; /** * Panel state: the user is dragging the floating panel. * @constant */ this.STATE_DRAGGING = 4; /** * Tells the state of the floating panel: hidden/minimized/visible or if it's * being dragged. * @type Number */ this.state = -1; /** * Floating panel ID. This is the ID used in the * <var>data-pwFloatingPanel</var> element attribute. * @type String */ this.id = null; /** * Reference to the floating panel element. * @type Element */ this.container = container; /** * The viewport element. This element is the first parent element which has * the style.overflow set to "auto" or "scroll". * @type Element */ this.viewport = null; /** * Custom application events interface. * @type pwlib.appEvents */ this.events = null; /** * The panel content element. * @type Element */ this.content = null; // The initial viewport scroll position. var vScrollLeft = 0, vScrollTop = 0, btn_close = null, btn_minimize = null; /** * Initialize the floating panel. * @private */ function init () { _self.events = new pwlib.appEvents(_self); _self.id = _self.container.getAttribute('data-pwFloatingPanel'); var ttl = _self.container.getElementsByTagName('h1')[0], content = _self.container.getElementsByTagName('div')[0], cs = win.getComputedStyle(_self.container, null), zIndex = parseInt(cs.zIndex); cStyle.zIndex = cs.zIndex; if (zIndex > panels.zIndex_) { panels.zIndex_ = zIndex; } _self.container.className += ' ' + gui.classPrefix + 'floatingPanel ' + gui.classPrefix + 'floatingPanel_' + _self.id; // the content content.className += ' ' + gui.classPrefix + 'floatingPanel_content'; _self.content = content; // setup the title element ttl.className += ' ' + gui.classPrefix + 'floatingPanel_title'; ttl.replaceChild(doc.createTextNode(lang.floatingPanels[_self.id]), ttl.firstChild); ttl.addEventListener('mousedown', ev_mousedown, false); // allow auto-hide for the panel if (_self.container.getAttribute('data-pwPanelHide') === 'true') { _self.hide(); } else { _self.state = _self.STATE_VISIBLE; } // Find the viewport parent element. var pNode = _self.container.parentNode, found = null; while (!found && pNode) { if (pNode.nodeName.toLowerCase() === 'html') { found = pNode; break; } cs = win.getComputedStyle(pNode, null); if (cs && (cs.overflow === 'scroll' || cs.overflow === 'auto')) { found = pNode; } else { pNode = pNode.parentNode; } } _self.viewport = found; // add the panel minimize button. btn_minimize = doc.createElement('a'); btn_minimize.href = '#'; btn_minimize.title = lang.floatingPanelMinimize; btn_minimize.className = gui.classPrefix + 'floatingPanel_minimize'; btn_minimize.addEventListener('click', ev_minimize, false); btn_minimize.appendChild(doc.createTextNode(btn_minimize.title)); _self.container.insertBefore(btn_minimize, content); // add the panel close button. btn_close = doc.createElement('a'); btn_close.href = '#'; btn_close.title = lang.floatingPanelClose; btn_close.className = gui.classPrefix + 'floatingPanel_close'; btn_close.addEventListener('click', ev_close, false); btn_close.appendChild(doc.createTextNode(btn_close.title)); _self.container.insertBefore(btn_close, content); // setup the panel resize handle. if (_self.container.getAttribute('data-pwPanelResizable') === 'true') { var resizeHandle = doc.createElement('div'); resizeHandle.className = gui.classPrefix + 'floatingPanel_resizer'; _self.container.appendChild(resizeHandle); _self.resizer = new pwlib.guiResizer(gui, resizeHandle, _self.container); } }; /** * The <code>click</code> event handler for the panel Minimize button element. * * <p>This method dispatches the {@link * pwlib.appEvent.guiFloatingPanelStateChange} application event. * * @private * @param {Event} ev The DOM Event object. */ function ev_minimize (ev) { ev.preventDefault(); try { this.focus(); } catch (err) { } var classMinimized = ' ' + gui.classPrefix + 'floatingPanel_minimized'; if (_self.state === _self.STATE_MINIMIZED) { _self.state = _self.STATE_VISIBLE; this.title = lang.floatingPanelMinimize; this.className = gui.classPrefix + 'floatingPanel_minimize'; this.replaceChild(doc.createTextNode(this.title), this.firstChild); if (_self.container.className.indexOf(classMinimized) !== -1) { _self.container.className = _self.container.className.replace(classMinimized, ''); } } else if (_self.state === _self.STATE_VISIBLE) { _self.state = _self.STATE_MINIMIZED; this.title = lang.floatingPanelRestore; this.className = gui.classPrefix + 'floatingPanel_restore'; this.replaceChild(doc.createTextNode(this.title), this.firstChild); if (_self.container.className.indexOf(classMinimized) === -1) { _self.container.className += classMinimized; } } _self.events.dispatch(new appEvent.guiFloatingPanelStateChange(_self.state)); _self.bringOnTop(); }; /** * The <code>click</code> event handler for the panel Close button element. * This hides the floating panel. * * <p>This method dispatches the {@link * pwlib.appEvent.guiFloatingPanelStateChange} application event. * * @private * @param {Event} ev The DOM Event object. */ function ev_close (ev) { ev.preventDefault(); _self.hide(); try { guiPlaceholder.focus(); } catch (err) { } }; /** * The <code>mousedown</code> event handler. This is invoked when you start * dragging the floating panel. * * <p>This method dispatches the {@link * pwlib.appEvent.guiFloatingPanelStateChange} application event. * * @private * @param {Event} ev The DOM Event object. */ function ev_mousedown (ev) { _self.state = _self.STATE_DRAGGING; mx = ev.clientX; my = ev.clientY; var cs = win.getComputedStyle(_self.container, null); ptop = parseInt(cs.top); pleft = parseInt(cs.left); if (_self.viewport) { vScrollLeft = _self.viewport.scrollLeft; vScrollTop = _self.viewport.scrollTop; } _self.bringOnTop(); doc.addEventListener('mousemove', ev_mousemove, false); doc.addEventListener('mouseup', ev_mouseup, false); _self.events.dispatch(new appEvent.guiFloatingPanelStateChange(_self.state)); if (ev.preventDefault) { ev.preventDefault(); } }; /** * The <code>mousemove</code> event handler. This performs the actual move of * the floating panel. * * @private * @param {Event} ev The DOM Event object. */ function ev_mousemove (ev) { var x = pleft + ev.clientX - mx, y = ptop + ev.clientY - my; if (_self.viewport) { if (_self.viewport.scrollLeft !== vScrollLeft) { x += _self.viewport.scrollLeft - vScrollLeft; } if (_self.viewport.scrollTop !== vScrollTop) { y += _self.viewport.scrollTop - vScrollTop; } } cStyle.left = x + 'px'; cStyle.top = y + 'px'; }; /** * The <code>mouseup</code> event handler. This ends the panel drag operation. * * <p>This method dispatches the {@link * pwlib.appEvent.guiFloatingPanelStateChange} application event. * * @private * @param {Event} ev The DOM Event object. */ function ev_mouseup (ev) { if (_self.container.className.indexOf(' ' + gui.classPrefix + 'floatingPanel_minimized') !== -1) { _self.state = _self.STATE_MINIMIZED; } else { _self.state = _self.STATE_VISIBLE; } doc.removeEventListener('mousemove', ev_mousemove, false); doc.removeEventListener('mouseup', ev_mouseup, false); try { guiPlaceholder.focus(); } catch (err) { } _self.events.dispatch(new appEvent.guiFloatingPanelStateChange(_self.state)); }; /** * Bring the panel to the top. This method makes sure the current floating * panel is visible. */ this.bringOnTop = function () { panels.zIndex_ += zIndex_step; cStyle.zIndex = panels.zIndex_; }; /** * Hide the panel. * * <p>This method dispatches the {@link * pwlib.appEvent.guiFloatingPanelStateChange} application event. */ this.hide = function () { cStyle.display = 'none'; _self.state = _self.STATE_HIDDEN; _self.events.dispatch(new appEvent.guiFloatingPanelStateChange(_self.state)); }; /** * Show the panel. * * <p>This method dispatches the {@link * pwlib.appEvent.guiFloatingPanelStateChange} application event. */ this.show = function () { if (_self.state === _self.STATE_VISIBLE) { return; } cStyle.display = 'block'; _self.state = _self.STATE_VISIBLE; var classMinimized = ' ' + gui.classPrefix + 'floatingPanel_minimized'; if (_self.container.className.indexOf(classMinimized) !== -1) { _self.container.className = _self.container.className.replace(classMinimized, ''); btn_minimize.className = gui.classPrefix + 'floatingPanel_minimize'; btn_minimize.title = lang.floatingPanelMinimize; btn_minimize.replaceChild(doc.createTextNode(btn_minimize.title), btn_minimize.firstChild); } _self.events.dispatch(new appEvent.guiFloatingPanelStateChange(_self.state)); _self.bringOnTop(); }; /** * Toggle the panel visibility. * * <p>This method dispatches the {@link * pwlib.appEvent.guiFloatingPanelStateChange} application event. */ this.toggle = function () { if (_self.state === _self.STATE_VISIBLE || _self.state === _self.STATE_MINIMIZED) { _self.hide(); } else { _self.show(); } }; init(); }; /** * @class The state change event for the floating panel. This event is fired * when the floating panel changes its state. This event is not cancelable. * * @augments pwlib.appEvent * * @param {Number} state The floating panel state. */ pwlib.appEvent.guiFloatingPanelStateChange = function (state) { /** * Panel state: hidden. * @constant */ this.STATE_HIDDEN = 0; /** * Panel state: visible. * @constant */ this.STATE_VISIBLE = 1; /** * Panel state: minimized. * @constant */ this.STATE_MINIMIZED = 3; /** * Panel state: the user is dragging the floating panel. * @constant */ this.STATE_DRAGGING = 4; /** * The current floating panel state. * @type Number */ this.state = state; pwlib.appEvent.call(this, 'guiFloatingPanelStateChange'); }; /** * @class Resize handler. * * @private * * @param {pwlib.gui} gui Reference to the PaintWeb GUI object. * * @param {Element} resizeHandle Reference to the resize handle DOM element. * This is the element users will be able to drag to achieve the resize effect * on the <var>container</var> element. * * @param {Element} container Reference to the container DOM element. This is * the element users will be able to resize using the <var>resizeHandle</var> * element. */ pwlib.guiResizer = function (gui, resizeHandle, container) { var _self = this, cStyle = container.style, doc = gui.app.doc, guiResizeEnd = pwlib.appEvent.guiResizeEnd, guiResizeMouseMove = pwlib.appEvent.guiResizeMouseMove, guiResizeStart = pwlib.appEvent.guiResizeStart, win = gui.app.win; /** * Custom application events interface. * @type pwlib.appEvents */ this.events = null; /** * The resize handle DOM element. * @type Element */ this.resizeHandle = resizeHandle; /** * The container DOM element. This is the element that's resized by the user * when he/she drags the resize handle. * @type Element */ this.container = container; /** * The viewport element. This element is the first parent element which has * the style.overflow set to "auto" or "scroll". * @type Element */ this.viewport = null; /** * Tells if the GUI resizer should dispatch the {@link * pwlib.appEvent.guiResizeMouseMove} application event when the user moves * the mouse during the resize operation. * * @type Boolean * @default false */ this.dispatchMouseMove = false; /** * Tells if the user resizing the container now. * * @type Boolean * @default false */ this.resizing = false; // The initial position of the mouse. var mx = 0, my = 0; // The initial container dimensions. var cWidth = 0, cHeight = 0; // The initial viewport scroll position. var vScrollLeft = 0, vScrollTop = 0; /** * Initialize the resize functionality. * @private */ function init () { _self.events = new pwlib.appEvents(_self); resizeHandle.addEventListener('mousedown', ev_mousedown, false); // Find the viewport parent element. var cs, pNode = _self.container.parentNode, found = null; while (!found && pNode) { if (pNode.nodeName.toLowerCase() === 'html') { found = pNode; break; } cs = win.getComputedStyle(pNode, null); if (cs && (cs.overflow === 'scroll' || cs.overflow === 'auto')) { found = pNode; } else { pNode = pNode.parentNode; } } _self.viewport = found; }; /** * The <code>mousedown</code> event handler. This starts the resize operation. * * <p>This function dispatches the {@link pwlib.appEvent.guiResizeStart} * event. * * @private * @param {Event} ev The DOM Event object. */ function ev_mousedown (ev) { mx = ev.clientX; my = ev.clientY; var cs = win.getComputedStyle(_self.container, null); cWidth = parseInt(cs.width); cHeight = parseInt(cs.height); var cancel = _self.events.dispatch(new guiResizeStart(mx, my, cWidth, cHeight)); if (cancel) { return; } if (_self.viewport) { vScrollLeft = _self.viewport.scrollLeft; vScrollTop = _self.viewport.scrollTop; } _self.resizing = true; doc.addEventListener('mousemove', ev_mousemove, false); doc.addEventListener('mouseup', ev_mouseup, false); if (ev.preventDefault) { ev.preventDefault(); } if (ev.stopPropagation) { ev.stopPropagation(); } }; /** * The <code>mousemove</code> event handler. This performs the actual resizing * of the <var>container</var> element. * * @private * @param {Event} ev The DOM Event object. */ function ev_mousemove (ev) { var w = cWidth + ev.clientX - mx, h = cHeight + ev.clientY - my; if (_self.viewport) { if (_self.viewport.scrollLeft !== vScrollLeft) { w += _self.viewport.scrollLeft - vScrollLeft; } if (_self.viewport.scrollTop !== vScrollTop) { h += _self.viewport.scrollTop - vScrollTop; } } cStyle.width = w + 'px'; cStyle.height = h + 'px'; if (_self.dispatchMouseMove) { _self.events.dispatch(new guiResizeMouseMove(ev.clientX, ev.clientY, w, h)); } }; /** * The <code>mouseup</code> event handler. This ends the resize operation. * * <p>This function dispatches the {@link pwlib.appEvent.guiResizeEnd} event. * * @private * @param {Event} ev The DOM Event object. */ function ev_mouseup (ev) { var cancel = _self.events.dispatch(new guiResizeEnd(ev.clientX, ev.clientY, parseInt(cStyle.width), parseInt(cStyle.height))); if (cancel) { return; } _self.resizing = false; doc.removeEventListener('mousemove', ev_mousemove, false); doc.removeEventListener('mouseup', ev_mouseup, false); }; init(); }; /** * @class The GUI element resize start event. This event is cancelable. * * @augments pwlib.appEvent * * @param {Number} x The mouse location on the x-axis. * @param {Number} y The mouse location on the y-axis. * @param {Number} width The element width. * @param {Number} height The element height. */ pwlib.appEvent.guiResizeStart = function (x, y, width, height) { /** * The mouse location on the x-axis. * @type Number */ this.x = x; /** * The mouse location on the y-axis. * @type Number */ this.y = y; /** * The element width. * @type Number */ this.width = width; /** * The element height. * @type Number */ this.height = height; pwlib.appEvent.call(this, 'guiResizeStart', true); }; /** * @class The GUI element resize end event. This event is cancelable. * * @augments pwlib.appEvent * * @param {Number} x The mouse location on the x-axis. * @param {Number} y The mouse location on the y-axis. * @param {Number} width The element width. * @param {Number} height The element height. */ pwlib.appEvent.guiResizeEnd = function (x, y, width, height) { /** * The mouse location on the x-axis. * @type Number */ this.x = x; /** * The mouse location on the y-axis. * @type Number */ this.y = y; /** * The element width. * @type Number */ this.width = width; /** * The element height. * @type Number */ this.height = height; pwlib.appEvent.call(this, 'guiResizeEnd', true); }; /** * @class The GUI element resize mouse move event. This event is not cancelable. * * @augments pwlib.appEvent * * @param {Number} x The mouse location on the x-axis. * @param {Number} y The mouse location on the y-axis. * @param {Number} width The element width. * @param {Number} height The element height. */ pwlib.appEvent.guiResizeMouseMove = function (x, y, width, height) { /** * The mouse location on the x-axis. * @type Number */ this.x = x; /** * The mouse location on the y-axis. * @type Number */ this.y = y; /** * The element width. * @type Number */ this.width = width; /** * The element height. * @type Number */ this.height = height; pwlib.appEvent.call(this, 'guiResizeMouseMove'); }; /** * @class The tabbed panel GUI component. * * @private * * @param {pwlib.gui} gui Reference to the PaintWeb GUI object. * * @param {Element} panel Reference to the panel DOM element. */ pwlib.guiTabPanel = function (gui, panel) { var _self = this, appEvent = pwlib.appEvent, doc = gui.app.doc, lang = gui.app.lang; /** * Custom application events interface. * @type pwlib.appEvents */ this.events = null; /** * Panel ID. The ID is the same as the data-pwTabPanel attribute value of the * panel DOM element . * * @type String. */ this.id = null; /** * Holds references to the DOM element of each tab and tab button. * @type Object */ this.tabs = {}; /** * Reference to the tab buttons DOM element. * @type Element */ this.tabButtons = null; /** * The panel container DOM element. * @type Element */ this.container = panel; /** * Holds the ID of the currently active tab. * @type String */ this.tabId = null; /** * Holds the ID of the previously active tab. * * @private * @type String */ var prevTabId_ = null; /** * Initialize the toolbar functionality. * @private */ function init () { _self.events = new pwlib.appEvents(_self); _self.id = _self.container.getAttribute('data-pwTabPanel'); // Add two class names, the generic .paintweb_tabPanel and another class // name specific to the current tab panel: .paintweb_tabPanel_id. _self.container.className += ' ' + gui.classPrefix + 'tabPanel' + ' ' + gui.classPrefix + 'tabPanel_' + _self.id; var tabButtons = doc.createElement('ul'), tabButton = null, tabDefault = _self.container.getAttribute('data-pwTabDefault') || null, childNodes = _self.container.childNodes, type = gui.app.ELEMENT_NODE, elem = null, tabId = null, anchor = null; tabButtons.className = gui.classPrefix + 'tabsList'; // Find all the tabs in the current panel container element. for (var i = 0; elem = childNodes[i]; i++) { if (elem.nodeType !== type) { continue; } // A tab is any element with a given data-pwTab attribute. tabId = elem.getAttribute('data-pwTab'); if (!tabId) { continue; } // two class names, the generic .paintweb_tab and the tab-specific class // name .paintweb_tabPanelId_tabId. elem.className += ' ' + gui.classPrefix + 'tab ' + gui.classPrefix + _self.id + '_' + tabId; tabButton = doc.createElement('li'); tabButton._pwTab = tabId; anchor = doc.createElement('a'); anchor.href = '#'; anchor.addEventListener('click', ev_tabClick, false); if (_self.id in lang.tabs) { anchor.title = lang.tabs[_self.id][tabId + 'Title'] || lang.tabs[_self.id][tabId]; anchor.appendChild(doc.createTextNode(lang.tabs[_self.id][tabId])); } if ((tabDefault && tabId === tabDefault) || (!tabDefault && !_self.tabId)) { _self.tabId = tabId; tabButton.className = gui.classPrefix + 'tabActive'; } else { prevTabId_ = tabId; elem.style.display = 'none'; } // automatically hide the tab if (elem.getAttribute('data-pwTabHide') === 'true') { tabButton.style.display = 'none'; } _self.tabs[tabId] = {container: elem, button: tabButton}; tabButton.appendChild(anchor); tabButtons.appendChild(tabButton); } _self.tabButtons = tabButtons; _self.container.appendChild(tabButtons); }; /** * The <code>click</code> event handler for tab buttons. This function simply * activates the tab the user clicked. * * @private * @param {Event} ev The DOM Event object. */ function ev_tabClick (ev) { ev.preventDefault(); _self.tabActivate(this.parentNode._pwTab); }; /** * Activate a tab by ID. * * <p>This method dispatches the {@link pwlib.appEvent.guiTabActivate} event. * * @param {String} tabId The ID of the tab you want to activate. * @returns {Boolean} True if the tab has been activated successfully, or * false if not. */ this.tabActivate = function (tabId) { if (!tabId || !(tabId in this.tabs)) { return false; } else if (tabId === this.tabId) { return true; } var ev = new appEvent.guiTabActivate(tabId, this.tabId), cancel = this.events.dispatch(ev), elem = null, tabButton = null; if (cancel) { return false; } // Deactivate the currently active tab. if (this.tabId in this.tabs) { elem = this.tabs[this.tabId].container; elem.style.display = 'none'; tabButton = this.tabs[this.tabId].button; tabButton.className = ''; prevTabId_ = this.tabId; } // Activate the new tab. elem = this.tabs[tabId].container; elem.style.display = ''; tabButton = this.tabs[tabId].button; tabButton.className = gui.classPrefix + 'tabActive'; tabButton.style.display = ''; // make sure the tab is not hidden this.tabId = tabId; try { tabButton.firstChild.focus(); } catch (err) { } return true; }; /** * Hide a tab by ID. * * @param {String} tabId The ID of the tab you want to hide. * @returns {Boolean} True if the tab has been hidden successfully, or false * if not. */ this.tabHide = function (tabId) { if (!(tabId in this.tabs)) { return false; } if (this.tabId === tabId) { this.tabActivate(prevTabId_); } this.tabs[tabId].button.style.display = 'none'; return true; }; /** * Show a tab by ID. * * @param {String} tabId The ID of the tab you want to show. * @returns {Boolean} True if the tab has been displayed successfully, or * false if not. */ this.tabShow = function (tabId) { if (!(tabId in this.tabs)) { return false; } this.tabs[tabId].button.style.display = ''; return true; }; init(); }; /** * @class The GUI tab activation event. This event is cancelable. * * @augments pwlib.appEvent * * @param {String} tabId The ID of the tab being activated. * @param {String} prevTabId The ID of the previously active tab. */ pwlib.appEvent.guiTabActivate = function (tabId, prevTabId) { /** * The ID of the tab being activated. * @type String */ this.tabId = tabId; /** * The ID of the previously active tab. * @type String */ this.prevTabId = prevTabId; pwlib.appEvent.call(this, 'guiTabActivate', true); }; /** * @class The color input GUI component. * * @private * * @param {pwlib.gui} gui Reference to the PaintWeb GUI object. * * @param {Element} input Reference to the DOM input element. This can be * a span, a div, or any other tag. */ pwlib.guiColorInput = function (gui, input) { var _self = this, colormixer = null, config = gui.app.config, doc = gui.app.doc, MathRound = Math.round, lang = gui.app.lang; /** * Color input ID. The ID is the same as the data-pwColorInput attribute value * of the DOM input element . * * @type String. */ this.id = null; /** * The color input element DOM reference. * * @type Element */ this.input = input; /** * The configuration property to which this color input is attached to. * @type String */ this.configProperty = null; /** * The configuration group to which this color input is attached to. * @type String */ this.configGroup = null; /** * Reference to the configuration object which holds the color input value. * @type String */ this.configGroupRef = null; /** * Holds the current color displayed by the input. * * @type Object */ this.color = {red: 0, green: 0, blue: 0, alpha: 0}; /** * Initialize the color input functionality. * @private */ function init () { var cfgAttr = _self.input.getAttribute('data-pwColorInput'), cfgNoDots = cfgAttr.replace('.', '_'), cfgArray = cfgAttr.split('.'), cfgProp = cfgArray.pop(), cfgGroup = cfgArray.join('.'), cfgGroupRef = config, langGroup = lang.inputs, labelElem = _self.input.parentNode, anchor = doc.createElement('a'), color; for (var i = 0, n = cfgArray.length; i < n; i++) { cfgGroupRef = cfgGroupRef[cfgArray[i]]; langGroup = langGroup[cfgArray[i]]; } _self.configProperty = cfgProp; _self.configGroup = cfgGroup; _self.configGroupRef = cfgGroupRef; _self.id = cfgNoDots; _self.input.className += ' ' + gui.classPrefix + 'colorInput' + ' ' + gui.classPrefix + _self.id; labelElem.replaceChild(doc.createTextNode(langGroup[cfgProp]), labelElem.firstChild); color = _self.configGroupRef[_self.configProperty]; color = color.replace(/\s+/g, '').replace(/^rgba\(/, '').replace(/\)$/, ''); color = color.split(','); _self.color.red = color[0] / 255; _self.color.green = color[1] / 255; _self.color.blue = color[2] / 255; _self.color.alpha = color[3]; anchor.style.backgroundColor = 'rgb(' + color[0] + ',' + color[1] + ',' + color[2] + ')'; anchor.style.opacity = color[3]; anchor.href = '#'; anchor.title = langGroup[cfgProp + 'Title'] || langGroup[cfgProp]; anchor.appendChild(doc.createTextNode(lang.inputs.colorInputAnchorContent)); anchor.addEventListener('click', ev_input_click, false); _self.input.replaceChild(anchor, _self.input.firstChild); }; /** * The <code>click</code> event handler for the color input element. This * function shows/hides the Color Mixer panel. * * @private * @param {Event} ev The DOM Event object. */ function ev_input_click (ev) { ev.preventDefault(); if (!colormixer) { colormixer = gui.app.extensions.colormixer; } if (!colormixer.targetInput || colormixer.targetInput.id !== _self.id) { colormixer.show({ id: _self.id, configProperty: _self.configProperty, configGroup: _self.configGroup, configGroupRef: _self.configGroupRef, show: colormixer_show, hide: colormixer_hide }, _self.color); } else { colormixer.hide(); } }; /** * The color mixer <code>show</code> event handler. This function is invoked * when the color mixer is shown. * @private */ function colormixer_show () { var classActive = ' ' + gui.classPrefix + 'colorInputActive', elemActive = _self.input.className.indexOf(classActive) !== -1; if (!elemActive) { _self.input.className += classActive; } }; /** * The color mixer <code>hide</code> event handler. This function is invoked * when the color mixer is hidden. * @private */ function colormixer_hide () { var classActive = ' ' + gui.classPrefix + 'colorInputActive', elemActive = _self.input.className.indexOf(classActive) !== -1; if (elemActive) { _self.input.className = _self.input.className.replace(classActive, ''); } }; /** * Update color. This method allows the change of the color values associated * to the current color input. * * <p>This method is used by the color picker tool and by the global GUI * <code>configChange</code> application event handler. * * @param {Object} color The new color values. The object must have four * properties: <var>red</var>, <var>green</var>, <var>blue</var> and * <var>alpha</var>. All values must be between 0 and 1. */ this.updateColor = function (color) { var anchor = _self.input.firstChild.style; anchor.opacity = color.alpha; anchor.backgroundColor = 'rgb(' + MathRound(color.red * 255) + ',' + MathRound(color.green * 255) + ',' + MathRound(color.blue * 255) + ')'; _self.color.red = color.red; _self.color.green = color.green; _self.color.blue = color.blue; _self.color.alpha = color.alpha; }; init(); }; // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * Copyright (C) 2008, 2009 Mihai Şucan * * This file is part of PaintWeb. * * PaintWeb is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PaintWeb is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PaintWeb. If not, see <http://www.gnu.org/licenses/>. * * $URL: http://code.google.com/p/paintweb $ * $Date: 2009-07-06 16:20:38 +0300 $ */ /** * @author <a lang="ro" href="http://www.robodesign.ro/mihai">Mihai Şucan</a> * @fileOverview Holds the "Insert image" tool implementation. */ // TODO: allow inserting images from a different host, using server-side magic. /** * @class The "Insert image" tool. * * @param {PaintWeb} app Reference to the main paint application object. */ pwlib.tools.insertimg = function (app) { var _self = this, canvasImage = app.image, clearInterval = app.win.clearInterval, config = app.config, context = app.buffer.context, gui = app.gui, lang = app.lang, MathAbs = Math.abs, MathMin = Math.min, MathRound = Math.round, mouse = app.mouse, setInterval = app.win.setInterval; /** * Holds the previous tool ID. * * @private * @type String */ var prevTool = app.tool ? app.tool._id : null; /** * The interval ID used for invoking the drawing operation every few * milliseconds. * * @private * @see PaintWeb.config.toolDrawDelay */ var timer = null; /** * Tells if the <kbd>Shift</kbd> key is down or not. This is used by the * drawing function. * * @private * @type Boolean * @default false */ var shiftKey = false; /** * Tells if the drawing canvas needs to be updated or not. * * @private * @type Boolean * @default false */ var needsRedraw = false; /** * Holds the starting point on the <var>x</var> axis of the image, for the * current drawing operation. * * @private * @type Number */ var x0 = 0; /** * Holds the starting point on the <var>y</var> axis of the image, for the * current drawing operation. * * @private * @type Number */ var y0 = 0; /** * Tells if the image element loaded or not. * * @private * @type Boolean */ var imageLoaded = false; /** * Holds the image aspect ratio, used by the resize method. * * @private * @type Number */ var imageRatio = 1; /** * Holds the DOM image element. * * @private * @type Element */ var imageElement = null; /** * Holds the image address. * @type String */ if (!this.url) { this.url = 'http://'; } /** * The tool preactivation code. This function asks the user to provide an URL * to the image which is desired to be inserted into the canvas. * * @returns {Boolean} True if the URL provided is correct. False is returned * if the URL is not provided or if it's incorrect. When false is returned the * tool activation is cancelled. */ this.preActivate = function () { if (!gui.elems.viewport) { return false; } _self.url = prompt(lang.promptInsertimg, _self.url); if (!_self.url || _self.url.toLowerCase() === 'http://') { return false; } // Remember the URL. pwlib.extend(true, _self.constructor.prototype, {url: _self.url}); if (!pwlib.isSameHost(_self.url, app.win.location.host)) { alert(lang.errorInsertimgHost); return false; } return true; }; /** * The tool activation event handler. This function is called once the * previous tool has been deactivated. */ this.activate = function () { imageElement = new Image(); imageElement.addEventListener('load', ev_imageLoaded, false); imageElement.src = _self.url; return true; }; /** * The tool deactivation event handler. */ this.deactivate = function () { if (imageElement) { imageElement = null; } if (timer) { clearInterval(timer); timer = null; } needsRedraw = false; context.clearRect(0, 0, canvasImage.width, canvasImage.height); return true; }; /** * The <code>load</code> event handler for the image element. This method * makes sure the image dimensions are synchronized with the zoom level, and * draws the image on the canvas. * * @private */ function ev_imageLoaded () { // Did the image already load? if (imageLoaded) { return; } // The default position for the inserted image is the top left corner of the visible area, taking into consideration the zoom level. var x = MathRound(gui.elems.viewport.scrollLeft / canvasImage.canvasScale), y = MathRound(gui.elems.viewport.scrollTop / canvasImage.canvasScale); context.clearRect(0, 0, canvasImage.width, canvasImage.height); try { context.drawImage(imageElement, x, y); } catch (err) { alert(lang.errorInsertimg); return; } imageLoaded = true; needsRedraw = false; if (!timer) { timer = setInterval(_self.draw, config.toolDrawDelay); } gui.statusShow('insertimgLoaded'); }; /** * The <code>mousedown</code> event handler. This method stores the current * mouse location and the image aspect ratio for later reuse by the * <code>draw()</code> method. * * @param {Event} ev The DOM Event object. */ this.mousedown = function (ev) { if (!imageLoaded) { alert(lang.errorInsertimgNotLoaded); return false; } x0 = mouse.x; y0 = mouse.y; // The image aspect ratio - used by the draw() method when the user holds // the Shift key down. imageRatio = imageElement.width / imageElement.height; shiftKey = ev.shiftKey; gui.statusShow('insertimgResize'); if (ev.stopPropagation) { ev.stopPropagation(); } }; /** * The <code>mousemove</code> event handler. * * @param {Event} ev The DOM Event object. */ this.mousemove = function (ev) { shiftKey = ev.shiftKey; needsRedraw = true; }; /** * Perform the drawing operation. When the mouse button is not down, the user * is allowed to pick where he/she wants to insert the image element, inside * the canvas. Once the <code>mousedown</code> event is fired, this method * allows the user to resize the image inside the canvas. * * @see PaintWeb.config.toolDrawDelay */ this.draw = function () { if (!imageLoaded || !needsRedraw) { return; } context.clearRect(0, 0, canvasImage.width, canvasImage.height); // If the user is holding down the mouse button, then allow him/her to // resize the image. if (mouse.buttonDown) { var w = MathAbs(mouse.x - x0), h = MathAbs(mouse.y - y0), x = MathMin(mouse.x, x0), y = MathMin(mouse.y, y0); if (!w || !h) { needsRedraw = false; return; } // If the Shift key is down, constrain the image to have the same aspect // ratio as the original image element. if (shiftKey) { if (w > h) { if (y == mouse.y) { y -= w-h; } h = MathRound(w/imageRatio); } else { if (x == mouse.x) { x -= h-w; } w = MathRound(h*imageRatio); } } context.drawImage(imageElement, x, y, w, h); } else { // If the mouse button is not down, simply allow the user to pick where // he/she wants to insert the image element. context.drawImage(imageElement, mouse.x, mouse.y); } needsRedraw = false; }; /** * The <code>mouseup</code> event handler. This method completes the drawing * operation by inserting the image in the layer canvas, and by activating the * previous tool. * * @param {Event} ev The DOM Event object. */ this.mouseup = function (ev) { if (!imageLoaded) { return false; } if (timer) { clearInterval(timer); timer = null; } app.layerUpdate(); if (prevTool) { app.toolActivate(prevTool, ev); } if (ev.stopPropagation) { ev.stopPropagation(); } }; /** * The <code>keydown</code> event handler allows users to press the * <kbd>Escape</kbd> key to cancel the drawing operation and return to the * previous tool. * * @param {Event} ev The DOM Event object. * @returns {Boolean} True if the key was recognized, or false if not. */ this.keydown = function (ev) { if (!prevTool || ev.kid_ != 'Escape') { return false; } if (timer) { clearInterval(timer); timer = null; } mouse.buttonDown = false; app.toolActivate(prevTool, ev); return true; }; }; // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * Copyright (C) 2008, 2009 Mihai Şucan * * This file is part of PaintWeb. * * PaintWeb is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PaintWeb is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PaintWeb. If not, see <http://www.gnu.org/licenses/>. * * $URL: http://code.google.com/p/paintweb $ * $Date: 2009-07-29 20:34:06 +0300 $ */ /** * @author <a lang="ro" href="http://www.robodesign.ro/mihai">Mihai Şucan</a> * @fileOverview Holds the eraser tool implementation. */ /** * @class The eraser tool. * * @param {PaintWeb} app Reference to the main paint application object. */ pwlib.tools.eraser = function (app) { var _self = this, bufferContext = app.buffer.context, clearInterval = app.win.clearInterval, config = app.config, history = app.history.pos, image = app.image, layerContext = app.layer.context, mouse = app.mouse, setInterval = app.win.setInterval; /** * The interval ID used for running the erasing operation every few * milliseconds. * * @private * @see PaintWeb.config.toolDrawDelay */ var timer = null; /** * Holds the points needed to be drawn. Each point is added by the * <code>mousemove</code> event handler. * * @private * @type Array */ var points = []; /** * Holds the starting point on the <var>x</var> axis of the image, for the * current drawing operation. * * @private * @type Number */ var x0 = 0; /** * Holds the starting point on the <var>y</var> axis of the image, for the * current drawing operation. * * @private * @type Number */ var y0 = 0; var globalOp_ = null, lineWidth_ = null; /** * The tool deactivation event handler. This function clears timers, clears * the canvas and allows shadows to be rendered again. */ this.deactivate = function () { if (timer) { clearInterval(timer); timer = null; } if (mouse.buttonDown) { if (globalOp_) { layerContext.globalCompositeOperation = globalOp_; } if (lineWidth_) { layerContext.lineWidth = lineWidth_; } app.historyGoto(history.pos); } points = []; // Allow Canvas shadows. app.shadowAllow(); }; /** * The tool activation event handler. This is run after the tool construction * and after the deactivation of the previous tool. This function simply * disallows the rendering of shadows. */ this.activate = function () { // Do not allow Canvas shadows. app.shadowDisallow(); }; /** * Initialize the drawing operation. */ this.mousedown = function () { globalOp_ = layerContext.globalCompositeOperation; lineWidth_ = layerContext.lineWidth; layerContext.globalCompositeOperation = 'destination-out'; layerContext.lineWidth = bufferContext.lineWidth; x0 = mouse.x; y0 = mouse.y; points = []; if (!timer) { timer = setInterval(_self.draw, config.toolDrawDelay); } return true; }; /** * Save the mouse coordinates in the array. */ this.mousemove = function () { if (mouse.buttonDown) { points.push(mouse.x, mouse.y); } }; /** * Draw the points in the stack. This function is called every few * milliseconds. * * @see PaintWeb.config.toolDrawDelay */ this.draw = function () { var i = 0, n = points.length; if (!n) { return; } layerContext.beginPath(); layerContext.moveTo(x0, y0); while (i < n) { x0 = points[i++]; y0 = points[i++]; layerContext.lineTo(x0, y0); } layerContext.stroke(); layerContext.closePath(); points = []; }; /** * End the drawing operation, once the user releases the mouse button. */ this.mouseup = function () { if (mouse.x == x0 && mouse.y == y0) { points.push(x0+1, y0+1); } if (timer) { clearInterval(timer); timer = null; } _self.draw(); layerContext.globalCompositeOperation = globalOp_; layerContext.lineWidth = lineWidth_; app.historyAdd(); return true; }; /** * Allows the user to press <kbd>Escape</kbd> to cancel the drawing operation. * * @param {Event} ev The DOM Event object. * * @returns {Boolean} True if the drawing operation was cancelled, or false if * not. */ this.keydown = function (ev) { if (!mouse.buttonDown || ev.kid_ != 'Escape') { return false; } if (timer) { clearInterval(timer); timer = null; } layerContext.globalCompositeOperation = globalOp_; layerContext.lineWidth = lineWidth_; mouse.buttonDown = false; points = []; app.historyGoto(history.pos); return true; }; }; // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * Copyright (C) 2008, 2009 Mihai Şucan * * This file is part of PaintWeb. * * PaintWeb is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PaintWeb is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PaintWeb. If not, see <http://www.gnu.org/licenses/>. * * $URL: http://code.google.com/p/paintweb $ * $Date: 2009-07-02 15:37:38 +0300 $ */ /** * @author <a lang="ro" href="http://www.robodesign.ro/mihai">Mihai Şucan</a> * @fileOverview Holds the color picker implementation. */ /** * @class The color picker tool. * * @param {PaintWeb} app Reference to the main paint application object. */ pwlib.tools.cpicker = function (app) { var _self = this, colormixer = app.extensions.colormixer, context = app.layer.context, gui = app.gui, lang = app.lang, MathRound = Math.round, mouse = app.mouse; /** * Holds the ID of the previously active tool. Once the user completes the * color picking operation, the previous tool is activated. * * @private * @type String */ var prevTool = null; /** * Holds a reference to the target color input. This is a GUI color input * component. * * @private * @type pwlib.guiColorInput */ var targetInput = null; /** * Holds the previous color values - before the user started picking * a different color. * * @private * @type Object */ var prevColor = null; /** * Tells if the color mixer is active for the current target input. * * @private * @type Boolean */ var colormixerActive = false; /** * Tells if the current color values are accepted by the user. This value is * used by the tool deactivation code. * * @private * @type Boolean */ var colorAccepted = false; /** * The <code>preActivate</code> event handler. This method checks if the * browser implements the <code>getImageData()</code> context method. If not, * the color picker tool cannot be used. */ this.preActivate = function () { // The latest versions of all browsers which implement Canvas, also // implement the getImageData() method. This was only a problem with some // old versions (eg. Opera 9.2). if (!context.getImageData) { alert(lang.errorCpickerUnsupported); return false; } if (app.tool && app.tool._id) { prevTool = app.tool._id; } return true; }; /** * The <code>activate</code> event handler. This method determines the current * target input in the Color Mixer, if any. Canvas shadow rendering is * disallowed. */ this.activate = function () { // When the color mixer panel is active, the color picker uses the same // target input. if (colormixer && colormixer.targetInput) { targetInput = gui.colorInputs[colormixer.targetInput.id]; } if (targetInput) { gui.statusShow('cpicker_' + targetInput.id); } else { gui.statusShow('cpickerNormal'); } app.shadowDisallow(); }; /** * The <code>deactivate</code> event handler. This method allows shadow * rendering again, and resets the color input values if the user did not * accept the new color. */ this.deactivate = function () { if (!colorAccepted && targetInput && prevColor) { updateColor(null, true); } app.shadowAllow(); }; /** * The <code>mousedown</code> event handler. This method starts the color * picking operation. * * @param {Event} ev The DOM Event object. */ this.mousedown = function (ev) { // We check again, because the user might have opened/closed the color // mixer. if (colormixer && colormixer.targetInput) { targetInput = gui.colorInputs[colormixer.targetInput.id]; } if (targetInput) { colormixerActive = true; gui.statusShow('cpicker_' + targetInput.id); } else { colormixerActive = false; gui.statusShow('cpickerNormal'); // The context menu (right-click). This is unsupported by Opera. // Also allow Shift+Click for changing the stroke color (making it easier for Opera users). if (ev.button === 2 || ev.shiftKey) { targetInput = gui.colorInputs.strokeStyle; } else { targetInput = gui.colorInputs.fillStyle; } } updatePrevColor(); _self.mousemove = updateColor; updateColor(ev); return true; }; /** * Perform color update. This function updates the target input or the Color * Mixer to hold the color value under the mouse - it actually performs the * color picking operation. * * <p>This function is also the <code>mousemove</code> event handler for this * tool. * * @param {Event} ev The DOM Event object. * @param {Boolean} [usePrevColor=false] Tells the function to use the * previous color values we have stored. This is used when the user cancels * the color picking operation. */ function updateColor (ev, usePrevColor) { if (!targetInput) { return; } var p = usePrevColor ? prevColor : context.getImageData(mouse.x, mouse.y, 1, 1), color = { red: p.data[0] / 255, green: p.data[1] / 255, blue: p.data[2] / 255, alpha: (p.data[3] / 255).toFixed(3) }; if (colormixerActive) { colormixer.color.red = color.red; colormixer.color.green = color.green; colormixer.color.blue = color.blue; colormixer.color.alpha = color.alpha; colormixer.update_color('rgb'); } else { targetInput.updateColor(color); } }; /** * The <code>mouseup</code> event handler. This method completes the color * picking operation, and activates the previous tool. * * <p>The {@link pwlib.appEvent.configChange} application event is also * dispatched for the configuration property associated to the target input. * * @param {Event} ev The DOM Event object. */ this.mouseup = function (ev) { if (!targetInput) { return false; } delete _self.mousemove; updateColor(ev); colorAccepted = true; if (!colormixerActive) { var color = targetInput.color, configProperty = targetInput.configProperty, configGroup = targetInput.configGroup, configGroupRef = targetInput.configGroupRef, prevVal = configGroupRef[configProperty], newVal = 'rgba(' + MathRound(color.red * 255) + ',' + MathRound(color.green * 255) + ',' + MathRound(color.blue * 255) + ',' + color.alpha + ')'; if (prevVal !== newVal) { configGroupRef[configProperty] = newVal; app.events.dispatch(new pwlib.appEvent.configChange(newVal, prevVal, configProperty, configGroup, configGroupRef)); } } if (prevTool) { app.toolActivate(prevTool, ev); } return true; }; /** * The <code>keydown</code> event handler. This method allows the user to * press the <kbd>Escape</kbd> key to cancel the color picking operation. By * doing so, the original color values are restored. * * @param {Event} ev The DOM Event object. * @returns {Boolean} True if the keyboard shortcut was recognized, or false * if not. */ this.keydown = function (ev) { if (!prevTool || ev.kid_ !== 'Escape') { return false; } mouse.buttonDown = false; app.toolActivate(prevTool, ev); return true; }; /** * The <code>contextmenu</code> event handler. This method only cancels the * context menu. */ // Unfortunately, the contextmenu event is unsupported by Opera. this.contextmenu = function () { return true; }; /** * Store the color values from the target color input, before this tool * changes the colors. The previous color values are used when the user * decides to cancel the color picking operation. * @private */ function updatePrevColor () { // If the color mixer panel is visible, then we store the color values from // the color mixer, instead of those from the color input object. var color = colormixerActive ? colormixer.color : targetInput.color; prevColor = { width: 1, height: 1, data: [ MathRound(color.red * 255), MathRound(color.green * 255), MathRound(color.blue * 255), color.alpha * 255 ] }; }; }; // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * Copyright (C) 2008, 2009 Mihai Şucan * * This file is part of PaintWeb. * * PaintWeb is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PaintWeb is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PaintWeb. If not, see <http://www.gnu.org/licenses/>. * * $URL: http://code.google.com/p/paintweb $ * $Date: 2009-06-15 15:25:29 +0300 $ */ /** * @author <a lang="ro" href="http://www.robodesign.ro/mihai">Mihai Şucan</a> * @fileOverview Holds the pencil tool implementation. */ /** * @class The drawing pencil. * * @param {PaintWeb} app Reference to the main paint application object. */ pwlib.tools.pencil = function (app) { var _self = this, clearInterval = app.win.clearInterval, context = app.buffer.context, image = app.image, mouse = app.mouse, setInterval = app.win.setInterval; /** * The interval ID used for running the pencil drawing operation every few * milliseconds. * * @private * @see PaintWeb.config.toolDrawDelay */ var timer = null; /** * Holds the points needed to be drawn. Each point is added by the * <code>mousemove</code> event handler. * * @private * @type Array */ var points = []; /** * Holds the last point on the <var>x</var> axis of the image, for the current * drawing operation. * * @private * @type Number */ var x0 = 0; /** * Holds the last point on the <var>y</var> axis of the image, for the current * drawing operation. * * @private * @type Number */ var y0 = 0; /** * Tool deactivation event handler. */ this.deactivate = function () { if (timer) { clearInterval(timer); timer = null; } if (mouse.buttonDown) { context.clearRect(0, 0, image.width, image.height); } points = []; }; /** * Initialize the drawing operation. */ this.mousedown = function () { x0 = mouse.x; y0 = mouse.y; points = []; if (!timer) { timer = setInterval(_self.draw, app.config.toolDrawDelay); } return true; }; /** * Save the mouse coordinates in the array. */ this.mousemove = function () { if (mouse.buttonDown) { points.push(mouse.x, mouse.y); } }; /** * Draw the points in the stack. This function is called every few * milliseconds. * * @see PaintWeb.config.toolDrawDelay */ this.draw = function () { var i = 0, n = points.length; if (!n) { return; } context.beginPath(); context.moveTo(x0, y0); while (i < n) { x0 = points[i++]; y0 = points[i++]; context.lineTo(x0, y0); } context.stroke(); context.closePath(); points = []; }; /** * End the drawing operation, once the user releases the mouse button. */ this.mouseup = function () { if (mouse.x == x0 && mouse.y == y0) { points.push(x0+1, y0+1); } if (timer) { clearInterval(timer); timer = null; } _self.draw(); app.layerUpdate(); return true; }; /** * Allows the user to press <kbd>Escape</kbd> to cancel the drawing operation. * * @param {Event} ev The DOM Event object. * * @returns {Boolean} True if the drawing operation was cancelled, or false if * not. */ this.keydown = function (ev) { if (!mouse.buttonDown || ev.kid_ != 'Escape') { return false; } if (timer) { clearInterval(timer); timer = null; } context.clearRect(0, 0, image.width, image.height); mouse.buttonDown = false; points = []; return true; }; }; // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * Copyright (C) 2008, 2009 Mihai Şucan * * This file is part of PaintWeb. * * PaintWeb is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PaintWeb is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PaintWeb. If not, see <http://www.gnu.org/licenses/>. * * $URL: http://code.google.com/p/paintweb $ * $Date: 2009-08-24 13:18:05 +0300 $ */ /** * @author <a lang="ro" href="http://www.robodesign.ro/mihai">Mihai Şucan</a> * @fileOverview Holds the Bézier curve tool implementation. */ /** * @class The Bézier curve tool. * * @param {PaintWeb} app Reference to the main paint application object. */ pwlib.tools.bcurve = function (app) { var _self = this, clearInterval = app.win.clearInterval, config = app.config, context = app.buffer.context, gui = app.gui, image = app.image, mouse = app.mouse, setInterval = app.win.setInterval, snapXY = app.toolSnapXY; /** * Holds the points in the Bézier curve being drawn. * * @private * @type Array */ var points = []; /** * The interval ID used for invoking the drawing operation every few * milliseconds. * * @private * @see PaintWeb.config.toolDrawDelay */ var timer = null; /** * Tells if the <kbd>Shift</kbd> key is down or not. This is used by the * drawing function. * * @private * @type Boolean * @default false */ var shiftKey = false; /** * Tells if the drawing canvas needs to be updated or not. * * @private * @type Boolean * @default false */ var needsRedraw = false; /** * The tool deactivation method, used for clearing the buffer. */ this.deactivate = function () { if (timer) { clearInterval(timer); timer = null; } if (points.length > 0) { context.clearRect(0, 0, image.width, image.height); } needsRedraw = false; points = []; return true; }; /** * The <code>mousedown</code> event handler. * * @param {Event} ev The DOM Event object. */ this.mousedown = function (ev) { if (points.length === 0) { gui.statusShow('bcurveSnapping'); points.push([mouse.x, mouse.y]); } if (!timer) { timer = setInterval(_self.draw, config.toolDrawDelay); } shiftKey = ev.shiftKey; needsRedraw = false; return true; }; /** * Store the <kbd>Shift</kbd> key state which is used by the drawing function. * * @param {Event} ev The DOM Event object. */ this.mousemove = function (ev) { shiftKey = ev.shiftKey; needsRedraw = true; }; /** * Draw the Bézier curve, using the available points. * * @see PaintWeb.config.toolDrawDelay */ this.draw = function () { if (!needsRedraw) { return; } var n = points.length; // Add the temporary point while the mouse button is down. if (mouse.buttonDown) { if (shiftKey && n === 1) { snapXY(points[0][0], points[0][1]); } points.push([mouse.x, mouse.y]); n++; } var p0 = points[0], p1 = points[1], p2 = points[2], p3 = points[3] || points[2]; if (mouse.buttonDown) { points.pop(); } context.clearRect(0, 0, image.width, image.height); if (!n) { needsRedraw = false; return; } // Draw the main line if (n === 2) { context.beginPath(); context.moveTo(p0[0], p0[1]+2); context.lineTo(p1[0], p1[1]+2); if (config.shapeType === 'fill') { var lineWidth = context.lineWidth, strokeStyle = context.strokeStyle; context.lineWidth = 1; context.strokeStyle = context.fillStyle; } context.stroke(); context.closePath(); if (config.shapeType === 'fill') { context.lineWidth = lineWidth; context.strokeStyle = strokeStyle; } needsRedraw = false; return; } // Draw the Bézier curve context.beginPath(); context.moveTo(p0[0], p0[1]); context.bezierCurveTo( p2[0], p2[1], p3[0], p3[1], p1[0], p1[1]); if (config.shapeType !== 'stroke') { context.fill(); } if (config.shapeType !== 'fill') { context.stroke(); } context.closePath(); needsRedraw = false; }; /** * The <code>mouseup</code> event handler. This method stores the current * mouse coordinates as a point to be used for drawing the Bézier curve. * * @param {Event} ev The DOM Event object. */ this.mouseup = function (ev) { var n = points.length; // Allow click+mousemove+click, not only mousedown+mousemove+mouseup. // Do this only for the start point. if (n === 1 && mouse.x === points[0][0] && mouse.y === points[0][1]) { mouse.buttonDown = true; return true; } if (timer) { clearInterval(timer); timer = null; } if (n === 1 && ev.shiftKey) { snapXY(points[0][0], points[0][1]); } // We need 4 points to draw the Bézier curve: start, end, and two control // points. if (n < 4) { points.push([mouse.x, mouse.y]); needsRedraw = true; n++; } // Make sure the canvas is up-to-date. shiftKey = ev.shiftKey; _self.draw(); if (n === 2 || n === 3) { gui.statusShow('bcurveControlPoint' + (n-1)); } else if (n === 4) { gui.statusShow('bcurveActive'); app.layerUpdate(); points = []; } return true; }; /** * The <code>keydown</code> event handler. This method allows the user to * press the <kbd>Escape</kbd> key to cancel the current drawing operation. * * @param {Event} ev The DOM Event object. * * @returns {Boolean} True if the keyboard shortcut was recognized, or false * if not. */ this.keydown = function (ev) { if (!points.length || ev.kid_ !== 'Escape') { return false; } if (timer) { clearInterval(timer); timer = null; } context.clearRect(0, 0, image.width, image.height); points = []; needsRedraw = false; mouse.buttonDown = false; gui.statusShow('bcurveActive'); return true; }; }; // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * Copyright (C) 2008, 2009 Mihai Şucan * * This file is part of PaintWeb. * * PaintWeb is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PaintWeb is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PaintWeb. If not, see <http://www.gnu.org/licenses/>. * * $URL: http://code.google.com/p/paintweb $ * $Date: 2009-08-27 20:30:01 +0300 $ */ /** * @author <a lang="ro" href="http://www.robodesign.ro/mihai">Mihai Şucan</a> * @fileOverview Holds the text tool implementation. */ // TODO: make this tool nicer to use. /** * @class The text tool. * * @param {PaintWeb} app Reference to the main paint application object. */ pwlib.tools.text = function (app) { var _self = this, clearInterval = app.win.clearInterval, config = app.config.text, context = app.buffer.context, doc = app.doc, gui = app.gui, image = app.image, lang = app.lang, MathRound = Math.round, mouse = app.mouse, setInterval = app.win.setInterval; /** * The interval ID used for invoking the drawing operation every few * milliseconds. * * @private * @see PaintWeb.config.toolDrawDelay */ var timer = null; /** * Holds the previous tool ID. * * @private * @type String */ var prevTool = app.tool ? app.tool._id : null; /** * Tells if the drawing canvas needs to be updated or not. * * @private * @type Boolean * @default false */ var needsRedraw = false; var inputString = null, input_fontFamily = null, ev_configChangeId = null, ns_svg = "http://www.w3.org/2000/svg", svgDoc = null, svgText = null, textWidth = 0, textHeight = 0; /** * Tool preactivation code. This method check if the browser has support for * rendering text in Canvas. * * @returns {Boolean} True if the tool can be activated successfully, or false * if not. */ this.preActivate = function () { if (!gui.inputs.textString || !gui.inputs.text_fontFamily || !gui.elems.viewport) { return false; } // Canvas 2D Text API if (context.fillText && context.strokeText) { return true; } // Opera can only render text via SVG Text. // Note: support for Opera has been disabled. // There are severe SVG redraw issues when updating the SVG text element. // Besides, there are important memory leaks. // Ultimately, there's a deal breaker: security violation. The SVG document // which is rendered inside Canvas is considered "external" // - get/putImageData() and toDataURL() stop working after drawImage(svg) is // invoked. Eh. /*if (pwlib.browser.opera) { return true; }*/ // Gecko 1.9.0 had its own proprietary Canvas 2D Text API. if (context.mozPathText) { return true; } alert(lang.errorTextUnsupported); return false; }; /** * The tool activation code. This sets up a few variables, starts the drawing * timer and adds event listeners as needed. */ this.activate = function () { // Reset the mouse coordinates to the scroll top/left corner such that the // text is rendered there. mouse.x = Math.round(gui.elems.viewport.scrollLeft / image.canvasScale), mouse.y = Math.round(gui.elems.viewport.scrollTop / image.canvasScale), input_fontFamily = gui.inputs.text_fontFamily; inputString = gui.inputs.textString; if (!context.fillText && pwlib.browser.opera) { ev_configChangeId = app.events.add('configChange', ev_configChange_opera); inputString.addEventListener('input', ev_configChange_opera, false); inputString.addEventListener('change', ev_configChange_opera, false); } else { ev_configChangeId = app.events.add('configChange', ev_configChange); inputString.addEventListener('input', ev_configChange, false); inputString.addEventListener('change', ev_configChange, false); } // Render text using the Canvas 2D context text API defined by HTML 5. if (context.fillText && context.strokeText) { _self.draw = _self.draw_spec; } else if (pwlib.browser.opera) { // Render text using a SVG Text element which is copied into Canvas using // drawImage(). _self.draw = _self.draw_opera; initOpera(); } else if (context.mozPathText) { // Render text using proprietary API available in Gecko 1.9.0. _self.draw = _self.draw_moz; textWidth = context.mozMeasureText(inputString.value); } if (!timer) { timer = setInterval(_self.draw, app.config.toolDrawDelay); } needsRedraw = true; }; /** * The tool deactivation simply consists of removing the event listeners added * when the tool was constructed, and clearing the buffer canvas. */ this.deactivate = function () { if (timer) { clearInterval(timer); timer = null; } needsRedraw = false; if (ev_configChangeId) { app.events.remove('configChange', ev_configChangeId); } if (!context.fillText && pwlib.browser.opera) { inputString.removeEventListener('input', ev_configChange_opera, false); inputString.removeEventListener('change', ev_configChange_opera, false); } else { inputString.removeEventListener('input', ev_configChange, false); inputString.removeEventListener('change', ev_configChange, false); } svgText = null; svgDoc = null; context.clearRect(0, 0, image.width, image.height); return true; }; /** * Initialize the SVG document for Opera. This is used for rendering the text. * @private */ function initOpera () { svgDoc = doc.createElementNS(ns_svg, 'svg'); svgDoc.setAttributeNS(ns_svg, 'version', '1.1'); svgText = doc.createElementNS(ns_svg, 'text'); svgText.appendChild(doc.createTextNode(inputString.value)); svgDoc.appendChild(svgText); svgText.style.font = context.font; if (app.config.shapeType !== 'stroke') { svgText.style.fill = context.fillStyle; } else { svgText.style.fill = 'none'; } if (app.config.shapeType !== 'fill') { svgText.style.stroke = context.strokeStyle; svgText.style.strokeWidth = context.lineWidth; } else { svgText.style.stroke = 'none'; svgText.style.strokeWidth = context.lineWidth; } textWidth = svgText.getComputedTextLength(); textHeight = svgText.getBBox().height; svgDoc.setAttributeNS(ns_svg, 'width', textWidth); svgDoc.setAttributeNS(ns_svg, 'height', textHeight + 10); svgText.setAttributeNS(ns_svg, 'x', 0); svgText.setAttributeNS(ns_svg, 'y', textHeight); }; /** * The <code>configChange</code> application event handler. This is also the * <code>input</code> and <code>change</code> event handler for the text * string input element. This method updates the Canvas text-related * properties as needed, and re-renders the text. * * <p>This function is not used on Opera. * * @param {Event|pwlib.appEvent.configChange} ev The application/DOM event * object. */ function ev_configChange (ev) { if (ev.type === 'input' || ev.type === 'change' || (!ev.group && ev.config === 'shapeType') || (ev.group === 'line' && ev.config === 'lineWidth')) { needsRedraw = true; // Update the text width. if (!context.fillText && context.mozMeasureText) { textWidth = context.mozMeasureText(inputString.value); } return; } if (ev.type !== 'configChange' && ev.group !== 'text') { return; } var font = ''; switch (ev.config) { case 'fontFamily': if (ev.value === '+') { fontFamilyAdd(ev); } case 'bold': case 'italic': case 'fontSize': if (config.bold) { font += 'bold '; } if (config.italic) { font += 'italic '; } font += config.fontSize + 'px ' + config.fontFamily; context.font = font; if ('mozTextStyle' in context) { context.mozTextStyle = font; } case 'textAlign': case 'textBaseline': needsRedraw = true; } // Update the text width. if (ev.config !== 'textAlign' && ev.config !== 'textBaseline' && !context.fillText && context.mozMeasureText) { textWidth = context.mozMeasureText(inputString.value); } }; /** * The <code>configChange</code> application event handler. This is also the * <code>input</code> and <code>change</code> event handler for the text * string input element. This method updates the Canvas text-related * properties as needed, and re-renders the text. * * <p>This is function is specific to Opera. * * @param {Event|pwlib.appEvent.configChange} ev The application/DOM event * object. */ function ev_configChange_opera (ev) { if (ev.type === 'input' || ev.type === 'change') { svgText.replaceChild(doc.createTextNode(this.value), svgText.firstChild); needsRedraw = true; } if (!ev.group && ev.config === 'shapeType') { if (ev.value !== 'stroke') { svgText.style.fill = context.fillStyle; } else { svgText.style.fill = 'none'; } if (ev.value !== 'fill') { svgText.style.stroke = context.strokeStyle; svgText.style.strokeWidth = context.lineWidth; } else { svgText.style.stroke = 'none'; svgText.style.strokeWidth = context.lineWidth; } needsRedraw = true; } if (!ev.group && ev.config === 'fillStyle') { if (app.config.shapeType !== 'stroke') { svgText.style.fill = ev.value; needsRedraw = true; } } if ((!ev.group && ev.config === 'strokeStyle') || (ev.group === 'line' && ev.config === 'lineWidth')) { if (app.config.shapeType !== 'fill') { svgText.style.stroke = context.strokeStyle; svgText.style.strokeWidth = context.lineWidth; needsRedraw = true; } } if (ev.type === 'configChange' && ev.group === 'text') { var font = ''; switch (ev.config) { case 'fontFamily': if (ev.value === '+') { fontFamilyAdd(ev); } case 'bold': case 'italic': case 'fontSize': if (config.bold) { font += 'bold '; } if (config.italic) { font += 'italic '; } font += config.fontSize + 'px ' + config.fontFamily; context.font = font; svgText.style.font = font; case 'textAlign': case 'textBaseline': needsRedraw = true; } } textWidth = svgText.getComputedTextLength(); textHeight = svgText.getBBox().height; svgDoc.setAttributeNS(ns_svg, 'width', textWidth); svgDoc.setAttributeNS(ns_svg, 'height', textHeight + 10); svgText.setAttributeNS(ns_svg, 'x', 0); svgText.setAttributeNS(ns_svg, 'y', textHeight); }; /** * Add a new font family into the font family drop down. This function is * invoked by the <code>ev_configChange()</code> function when the user * attempts to add a new font family. * * @private * * @param {pwlib.appEvent.configChange} ev The application event object. */ function fontFamilyAdd (ev) { var new_font = prompt(lang.promptTextFont) || ''; new_font = new_font.replace(/^\s+/, '').replace(/\s+$/, '') || ev.previousValue; // Check if the font name is already in the list. var opt, new_font2 = new_font.toLowerCase(), n = input_fontFamily.options.length; for (var i = 0; i < n; i++) { opt = input_fontFamily.options[i]; if (opt.value.toLowerCase() == new_font2) { config.fontFamily = opt.value; input_fontFamily.selectedIndex = i; input_fontFamily.value = config.fontFamily; ev.value = config.fontFamily; return; } } // Add the new font. opt = doc.createElement('option'); opt.value = new_font; opt.appendChild(doc.createTextNode(new_font)); input_fontFamily.insertBefore(opt, input_fontFamily.options[n-1]); input_fontFamily.selectedIndex = n-1; input_fontFamily.value = new_font; ev.value = new_font; config.fontFamily = new_font; }; /** * The <code>mousemove</code> event handler. */ this.mousemove = function () { needsRedraw = true; }; /** * Perform the drawing operation using standard 2D context methods. * * @see PaintWeb.config.toolDrawDelay */ this.draw_spec = function () { if (!needsRedraw) { return; } context.clearRect(0, 0, image.width, image.height); if (app.config.shapeType != 'stroke') { context.fillText(inputString.value, mouse.x, mouse.y); } if (app.config.shapeType != 'fill') { context.beginPath(); context.strokeText(inputString.value, mouse.x, mouse.y); context.closePath(); } needsRedraw = false; }; /** * Perform the drawing operation in Gecko 1.9.0. */ this.draw_moz = function () { if (!needsRedraw) { return; } context.clearRect(0, 0, image.width, image.height); var x = mouse.x, y = mouse.y; if (config.textAlign === 'center') { x -= MathRound(textWidth / 2); } else if (config.textAlign === 'right') { x -= textWidth; } if (config.textBaseline === 'top') { y += config.fontSize; } else if (config.textBaseline === 'middle') { y += MathRound(config.fontSize / 2); } context.setTransform(1, 0, 0, 1, x, y); context.beginPath(); context.mozPathText(inputString.value); if (app.config.shapeType != 'stroke') { context.fill(); } if (app.config.shapeType != 'fill') { context.stroke(); } context.closePath(); context.setTransform(1, 0, 0, 1, 0, 0); needsRedraw = false; }; /** * Perform the drawing operation in Opera using SVG. */ this.draw_opera = function () { if (!needsRedraw) { return; } context.clearRect(0, 0, image.width, image.height); var x = mouse.x, y = mouse.y; if (config.textAlign === 'center') { x -= MathRound(textWidth / 2); } else if (config.textAlign === 'right') { x -= textWidth; } if (config.textBaseline === 'bottom') { y -= textHeight; } else if (config.textBaseline === 'middle') { y -= MathRound(textHeight / 2); } context.drawImage(svgDoc, x, y); needsRedraw = false; }; /** * The <code>click</code> event handler. This method completes the drawing * operation by inserting the text into the layer canvas. */ this.click = function () { _self.draw(); app.layerUpdate(); }; /** * The <code>keydown</code> event handler allows users to press the * <kbd>Escape</kbd> key to cancel the drawing operation and return to the * previous tool. * * @param {Event} ev The DOM Event object. * @returns {Boolean} True if the key was recognized, or false if not. */ this.keydown = function (ev) { if (!prevTool || ev.kid_ != 'Escape') { return false; } mouse.buttonDown = false; app.toolActivate(prevTool, ev); return true; }; }; // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * Copyright (C) 2008, 2009 Mihai Şucan * * This file is part of PaintWeb. * * PaintWeb is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PaintWeb is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PaintWeb. If not, see <http://www.gnu.org/licenses/>. * * $URL: http://code.google.com/p/paintweb $ * $Date: 2009-06-11 20:21:13 +0300 $ */ /** * @author <a lang="ro" href="http://www.robodesign.ro/mihai">Mihai Şucan</a> * @fileOverview Holds the rectangle tool implementation. */ /** * @class The rectangle tool. * * @param {PaintWeb} app Reference to the main paint application object. */ pwlib.tools.rectangle = function (app) { var _self = this, clearInterval = app.win.clearInterval, config = app.config, context = app.buffer.context, gui = app.gui, image = app.image, MathAbs = Math.abs, MathMin = Math.min, mouse = app.mouse, setInterval = app.win.setInterval; /** * The interval ID used for invoking the drawing operation every few * milliseconds. * * @private * @see PaintWeb.config.toolDrawDelay */ var timer = null; /** * Tells if the <kbd>Shift</kbd> key is down or not. This is used by the * drawing function. * * @private * @type Boolean * @default false */ var shiftKey = false; /** * Tells if the drawing canvas needs to be updated or not. * * @private * @type Boolean * @default false */ var needsRedraw = false; /** * Holds the starting point on the <var>x</var> axis of the image, for the * current drawing operation. * * @private * @type Number */ var x0 = 0; /** * Holds the starting point on the <var>y</var> axis of the image, for the * current drawing operation. * * @private * @type Number */ var y0 = 0; /** * Tool deactivation event handler. */ this.deactivate = function () { if (timer) { clearInterval(timer); timer = null; } if (mouse.buttonDown) { context.clearRect(0, 0, image.width, image.height); } needsRedraw = false; }; /** * Initialize the drawing operation. * * @param {Event} ev The DOM Event object. */ this.mousedown = function (ev) { x0 = mouse.x; y0 = mouse.y; if (!timer) { timer = setInterval(_self.draw, config.toolDrawDelay); } shiftKey = ev.shiftKey; needsRedraw = false; gui.statusShow('rectangleMousedown'); return true; }; /** * Store the <kbd>Shift</kbd> key state which is used by the drawing function. * * @param {Event} ev The DOM Event object. */ this.mousemove = function (ev) { shiftKey = ev.shiftKey; needsRedraw = true; }; /** * Perform the drawing operation. This function is called every few * milliseconds. * * <p>Hold down the <kbd>Shift</kbd> key to draw a square. * <p>Press <kbd>Escape</kbd> to cancel the drawing operation. * * @see PaintWeb.config.toolDrawDelay */ this.draw = function () { if (!needsRedraw) { return; } context.clearRect(0, 0, image.width, image.height); var x = MathMin(mouse.x, x0), y = MathMin(mouse.y, y0), w = MathAbs(mouse.x - x0), h = MathAbs(mouse.y - y0); if (!w || !h) { needsRedraw = false; return; } // Constrain the shape to a square if (shiftKey) { if (w > h) { if (y == mouse.y) { y -= w-h; } h = w; } else { if (x == mouse.x) { x -= h-w; } w = h; } } if (config.shapeType != 'stroke') { context.fillRect(x, y, w, h); } if (config.shapeType != 'fill') { context.strokeRect(x, y, w, h); } needsRedraw = false; }; /** * End the drawing operation, once the user releases the mouse button. * * @param {Event} ev The DOM Event object. */ this.mouseup = function (ev) { // Allow click+mousemove, not only mousedown+move+up if (mouse.x == x0 && mouse.y == y0) { mouse.buttonDown = true; return true; } if (timer) { clearInterval(timer); timer = null; } shiftKey = ev.shiftKey; _self.draw(); app.layerUpdate(); gui.statusShow('rectangleActive'); return true; }; /** * Allows the user to press <kbd>Escape</kbd> to cancel the drawing operation. * * @param {Event} ev The DOM Event object. * * @returns {Boolean} True if the drawing operation was cancelled, or false if * not. */ this.keydown = function (ev) { if (!mouse.buttonDown || ev.kid_ != 'Escape') { return false; } if (timer) { clearInterval(timer); timer = null; } context.clearRect(0, 0, image.width, image.height); mouse.buttonDown = false; needsRedraw = false; gui.statusShow('rectangleActive'); return true; }; }; // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * Copyright (C) 2008, 2009 Mihai Şucan * * This file is part of PaintWeb. * * PaintWeb is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PaintWeb is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PaintWeb. If not, see <http://www.gnu.org/licenses/>. * * $URL: http://code.google.com/p/paintweb $ * $Date: 2009-07-02 16:07:14 +0300 $ */ /** * @author <a lang="ro" href="http://www.robodesign.ro/mihai">Mihai Şucan</a> * @fileOverview Holds the selection tool implementation. */ /** * @class The selection tool. * * @param {PaintWeb} app Reference to the main paint application object. */ pwlib.tools.selection = function (app) { var _self = this, appEvent = pwlib.appEvent, bufferContext = app.buffer.context, clearInterval = app.win.clearInterval, config = app.config.selection, gui = app.gui, image = app.image, lang = app.lang, layerCanvas = app.layer.canvas, layerContext = app.layer.context, marqueeStyle = null, MathAbs = Math.abs, MathMin = Math.min, MathRound = Math.round, mouse = app.mouse, setInterval = app.win.setInterval, snapXY = app.toolSnapXY; /** * The interval ID used for invoking the drawing operation every few * milliseconds. * * @private * @see PaintWeb.config.toolDrawDelay */ var timer = null; /** * Tells if the drawing canvas needs to be updated or not. * * @private * @type Boolean * @default false */ var needsRedraw = false; /** * The selection has been dropped, and the mouse button is down. The user has * two choices: he releases the mouse button, thus the selection is dropped * and the tool switches to STATE_NONE, or he moves the mouse in order to * start a new selection (STATE_DRAWING). * @constant */ this.STATE_PENDING = -1; /** * No selection is available. * @constant */ this.STATE_NONE = 0; /** * The user is drawing a selection. * @constant */ this.STATE_DRAWING = 1; /** * The selection rectangle is available. * @constant */ this.STATE_SELECTED = 2; /** * The user is dragging/moving the selection rectangle. * @constant */ this.STATE_DRAGGING = 3; /** * The user is resizing the selection rectangle. * @constant */ this.STATE_RESIZING = 4; /** * Selection state. Known states: * * <ul> * <li>{@link pwlib.tools.selection#STATE_PENDING} - Selection dropped after * the <code>mousedown</code> event is fired. The script can switch to * STATE_DRAWING if the mouse moves, or to STATE_NONE if it does not * (allowing the user to drop the selection). * * <li>{@link pwlib.tools.selection#STATE_NONE} - No selection is available. * * <li>{@link pwlib.tools.selection#STATE_DRAWING} - The user is drawing the * selection rectangle. * * <li>{@link pwlib.tools.selection#STATE_SELECTED} - The selection * rectangle is available. * * <li>{@link pwlib.tools.selection#STATE_DRAGGING} - The user is * dragging/moving the current selection. * * <li>{@link pwlib.tools.selection#STATE_RESIZING} - The user is resizing * the current selection. * </ul> * * @type Number * @default STATE_NONE */ this.state = this.STATE_NONE; /** * Holds the starting point on the <var>x</var> axis of the image, for any * ongoing operation. * * @private * @type Number */ var x0 = 0; /** * Holds the starting point on the <var>y</var> axis of the image, for the any * ongoing operation. * * @private * @type Number */ var y0 = 0; /** * Holds selection information and image. * @type Object */ this.selection = { /** * Selection start point, on the <var>x</var> axis. * @type Number */ x: 0, /** * Selection start point, on the <var>y</var> axis. * @type Number */ y: 0, /** * Selection width. * @type Number */ width: 0, /** * Selection height. * @type Number */ height: 0, /** * Selection original width. The user can make a selection rectangle of * a given width and height, but after that he/she can resize the selection. * @type Number */ widthOriginal: 0, /** * Selection original height. The user can make a selection rectangle of * a given width and height, but after that he/she can resize the selection. * @type Number */ heightOriginal: 0, /** * Tells if the selected ImageData has been cut out or not from the * layerContext. * * @type Boolean * @default false */ layerCleared: false, /** * Selection marquee/border element. * @type HTMLElement */ marquee: null, /** * Selection buffer context which holds the selected pixels. * @type CanvasRenderingContext2D */ context: null, /** * Selection buffer canvas which holds the selected pixels. * @type HTMLCanvasElement */ canvas: null }; /** * The area type under the current mouse location. * * <p>When the selection is available the mouse location can be on top/inside * the selection rectangle, on the border of the selection, or outside the * selection. * * <p>Possible values: 'in', 'out', 'border'. * * @private * @type String * @default 'out' */ var mouseArea = 'out'; /** * The resize type. If the mouse is on top of the selection border, then the * selection can be resized. The direction of the resize operation is * determined by the location of the mouse. * * <p>While the user resizes the selection this variable can hold the * following values: 'n' (North), 'ne' (North-East), 'e' (East), 'se' * (South-East), 's' (South), 'sw' (South-West), 'w' (West), 'nw' * (North-West). * * @private * @type String * @default null */ var mouseResize = null; // shorthands / private variables var sel = this.selection, borderDouble = config.borderWidth * 2, ev_canvasSizeChangeId = null, ev_configChangeId = null, ctrlKey = false, shiftKey = false; /** * The last selection rectangle that was drawn. This is used by the selection * drawing functions. * * @private * @type Object */ // We avoid retrieving the mouse coordinates during the mouseup event, due to // the Opera bug DSK-232264. var lastSel = null; /** * The tool preactivation code. This function prepares the selection canvas * element. * * @returns {Boolean} True if the activation did not fail, or false otherwise. * If false is returned, the selection tool cannot be activated. */ this.preActivate = function () { if (!('canvasContainer' in gui.elems)) { alert(lang.errorToolActivate); return false; } // The selection image buffer. sel.canvas = app.doc.createElement('canvas'); if (!sel.canvas) { alert(lang.errorToolActivate); return false; } sel.canvas.width = 5; sel.canvas.height = 5; sel.context = sel.canvas.getContext('2d'); if (!sel.context) { alert(lang.errorToolActivate); return false; } sel.marquee = app.doc.createElement('div'); if (!sel.marquee) { alert(lang.errorToolActivate); return false; } sel.marquee.className = gui.classPrefix + 'selectionMarquee'; marqueeStyle = sel.marquee.style; return true; }; /** * The tool activation code. This method sets-up multiple event listeners for * several target objects. */ this.activate = function () { // Older browsers do not support get/putImageData, thus non-transparent // selections cannot be used. if (!layerContext.putImageData || !layerContext.getImageData) { config.transparent = true; } marqueeHide(); marqueeStyle.borderWidth = config.borderWidth + 'px'; sel.marquee.addEventListener('mousedown', marqueeMousedown, false); sel.marquee.addEventListener('mousemove', marqueeMousemove, false); sel.marquee.addEventListener('mouseup', marqueeMouseup, false); gui.elems.canvasContainer.appendChild(sel.marquee); // Disable the Canvas shadow. app.shadowDisallow(); // Application event listeners. ev_canvasSizeChangeId = app.events.add('canvasSizeChange', ev_canvasSizeChange); ev_configChangeId = app.events.add('configChange', ev_configChange); // Register selection-related commands app.commandRegister('selectionCrop', _self.selectionCrop); app.commandRegister('selectionDelete', _self.selectionDelete); app.commandRegister('selectionFill', _self.selectionFill); if (!timer) { timer = setInterval(timerFn, app.config.toolDrawDelay); } return true; }; /** * The tool deactivation code. This removes all event listeners and cleans up * the document. */ this.deactivate = function () { if (timer) { clearInterval(timer); timer = null; } _self.selectionMerge(); sel.marquee.removeEventListener('mousedown', marqueeMousedown, false); sel.marquee.removeEventListener('mousemove', marqueeMousemove, false); sel.marquee.removeEventListener('mouseup', marqueeMouseup, false); marqueeStyle = null; gui.elems.canvasContainer.removeChild(sel.marquee); delete sel.context, sel.canvas, sel.marquee; // Re-enable canvas shadow. app.shadowAllow(); // Remove the application event listeners. if (ev_canvasSizeChangeId) { app.events.remove('canvasSizeChange', ev_canvasSizeChangeId); } if (ev_configChangeId) { app.events.remove('configChange', ev_configChangeId); } // Unregister selection-related commands app.commandUnregister('selectionCrop'); app.commandUnregister('selectionDelete'); app.commandUnregister('selectionFill'); return true; }; /** * The <code>mousedown</code> event handler. Depending on the mouse location, * this method does initiate different selection operations: drawing, * dropping, dragging or resizing. * * <p>Hold the <kbd>Control</kbd> key down to temporarily toggle the * transformation mode. * * @param {Event} ev The DOM Event object. */ this.mousedown = function (ev) { if (_self.state !== _self.STATE_NONE && _self.state !== _self.STATE_SELECTED) { return false; } // Update the current mouse position, this is used as the start position for most of the operations. x0 = mouse.x; y0 = mouse.y; shiftKey = ev.shiftKey; ctrlKey = ev.ctrlKey; lastSel = null; // No selection is available, then start drawing a selection. if (_self.state === _self.STATE_NONE) { _self.state = _self.STATE_DRAWING; marqueeStyle.display = ''; gui.statusShow('selectionDraw'); return true; } // STATE_SELECTED: selection available. mouseAreaUpdate(); /* * Check if the user clicked outside the selection: drop the selection, * switch to STATE_PENDING, clear the image buffer and put the current * selection buffer in the image layer. * * If the user moves the mouse without taking the finger off the mouse * button, then a new selection rectangle will start to be drawn: the script * will switch to STATE_DRAWING. * * If the user simply takes the finger off the mouse button (mouseup), then * the script will switch to STATE_NONE (no selection available). */ switch (mouseArea) { case 'out': _self.state = _self.STATE_PENDING; marqueeHide(); gui.statusShow('selectionActive'); selectionMergeStrict(); return true; case 'in': // The mouse area: 'in' for drag. _self.state = _self.STATE_DRAGGING; gui.statusShow('selectionDrag'); break; case 'border': // 'border' for resize (the user is clicking on the borders). _self.state = _self.STATE_RESIZING; gui.statusShow('selectionResize'); } // Temporarily toggle the transformation mode if the user holds the Control // key down. if (ev.ctrlKey) { config.transform = !config.transform; } // If there's any ImageData currently in memory, which was "cut" out from // the current layer, then put it back on the layer. This needs to be done // only when the selection.transform mode is not active - that's when the // drag/resize operation only changes the selection, not the pixels // themselves. if (sel.layerCleared && !config.transform) { selectionMergeStrict(); } else if (!sel.layerCleared && config.transform) { // When the user starts dragging/resizing the ImageData we must cut out // the current selection from the image layer. selectionBufferInit(); } return true; }; /** * The <code>mousemove</code> event handler. * * @param {Event} ev The DOM Event object. */ this.mousemove = function (ev) { shiftKey = ev.shiftKey; needsRedraw = true; }; /** * The timer function. When the mouse button is down, this method performs the * dragging/resizing operation. When the mouse button is not down, this method * simply tracks the mouse location for the purpose of determining the area * being pointed at: the selection, the borders, or if the mouse is outside * the selection. * @private */ function timerFn () { if (!needsRedraw) { return; } switch (_self.state) { case _self.STATE_PENDING: // selection dropped, switch to draw selection _self.state = _self.STATE_DRAWING; marqueeStyle.display = ''; gui.statusShow('selectionDraw'); case _self.STATE_DRAWING: selectionDraw(); break; case _self.STATE_SELECTED: mouseAreaUpdate(); break; case _self.STATE_DRAGGING: selectionDrag(); break; case _self.STATE_RESIZING: selectionResize(); } needsRedraw = false; }; /** * The <code>mouseup</code> event handler. This method ends any selection * operation. * * <p>This method dispatches the {@link pwlib.appEvent.selectionChange} * application event when the selection state is changed or when the selection * size/location is updated. * * @param {Event} ev The DOM Event object. */ this.mouseup = function (ev) { // Allow click+mousemove+click, not only mousedown+move+up if (_self.state !== _self.STATE_PENDING && mouse.x === x0 && mouse.y === y0) { return true; } needsRedraw = false; shiftKey = ev.shiftKey; if (ctrlKey) { config.transform = !config.transform; } if (_self.state === _self.STATE_PENDING) { // Selection dropped? If yes, switch to the no selection state. _self.state = _self.STATE_NONE; app.events.dispatch(new appEvent.selectionChange(_self.state)); return true; } else if (!lastSel) { _self.state = _self.STATE_NONE; marqueeHide(); gui.statusShow('selectionActive'); app.events.dispatch(new appEvent.selectionChange(_self.state)); return true; } sel.x = lastSel.x; sel.y = lastSel.y; if ('width' in lastSel) { sel.width = lastSel.width; sel.height = lastSel.height; } _self.state = _self.STATE_SELECTED; app.events.dispatch(new appEvent.selectionChange(_self.state, sel.x, sel.y, sel.width, sel.height)); gui.statusShow('selectionAvailable'); return true; }; /** * The <code>mousedown</code> event handler for the selection marquee element. * * @private * @param {Event} ev The DOM Event object. */ function marqueeMousedown (ev) { if (mouse.buttonDown) { return; } mouse.buttonDown = true; ev.preventDefault(); _self.mousedown(ev); }; /** * The <code>mousemove</code> event handler for the selection marquee element. * * @private * @param {Event} ev The DOM Event object. */ function marqueeMousemove (ev) { if ('layerX' in ev) { mouse.x = MathRound((this.offsetLeft + ev.layerX) / image.canvasScale); mouse.y = MathRound((this.offsetTop + ev.layerY) / image.canvasScale); } else if ('offsetX' in ev) { mouse.x = MathRound((this.offsetLeft + ev.offsetX) / image.canvasScale); mouse.y = MathRound((this.offsetTop + ev.offsetY) / image.canvasScale); } shiftKey = ev.shiftKey; needsRedraw = true; }; /** * The <code>mouseup</code> event handler for the selection marquee element. * * @private * @param {Event} ev The DOM Event object. */ function marqueeMouseup (ev) { if (!mouse.buttonDown) { return; } mouse.buttonDown = false; ev.preventDefault(); _self.mouseup(ev); }; /** * Hide the selection marquee element. * @private */ function marqueeHide () { marqueeStyle.display = 'none'; marqueeStyle.top = '-' + (borderDouble + 50) + 'px'; marqueeStyle.left = '-' + (borderDouble + 50) + 'px'; marqueeStyle.width = '1px'; marqueeStyle.height = '1px'; marqueeStyle.cursor = ''; }; /** * Perform the selection rectangle drawing operation. * * @private */ function selectionDraw () { var x = MathMin(mouse.x, x0), y = MathMin(mouse.y, y0), w = MathAbs(mouse.x - x0), h = MathAbs(mouse.y - y0); // Constrain the shape to a square. if (shiftKey) { if (w > h) { if (y === mouse.y) { y -= w-h; } h = w; } else { if (x === mouse.x) { x -= h-w; } w = h; } } var mw = w * image.canvasScale - borderDouble, mh = h * image.canvasScale - borderDouble; if (mw < 1 || mh < 1) { lastSel = null; return; } marqueeStyle.top = (y * image.canvasScale) + 'px'; marqueeStyle.left = (x * image.canvasScale) + 'px'; marqueeStyle.width = mw + 'px'; marqueeStyle.height = mh + 'px'; lastSel = {'x': x, 'y': y, 'width': w, 'height': h}; }; /** * Perform the selection drag operation. * * @private * * @returns {false|Array} False is returned if the selection is too small, * otherwise an array of two elements is returned. The array holds the * selection coordinates, x and y. */ function selectionDrag () { // Snapping on the X/Y axis if (shiftKey) { snapXY(x0, y0); } var x = sel.x + mouse.x - x0, y = sel.y + mouse.y - y0; // Dragging the ImageData if (config.transform) { bufferContext.clearRect(0, 0, image.width, image.height); if (!config.transparent) { bufferContext.fillRect(x, y, sel.width, sel.height); } // Parameters: // source image, dest x, dest y, dest width, dest height bufferContext.drawImage(sel.canvas, x, y, sel.width, sel.height); } marqueeStyle.top = (y * image.canvasScale) + 'px'; marqueeStyle.left = (x * image.canvasScale) + 'px'; lastSel = {'x': x, 'y': y}; }; /** * Perform the selection resize operation. * * @private * * @returns {false|Array} False is returned if the selection is too small, * otherwise an array of four elements is returned. The array holds the * selection information: x, y, width and height. */ function selectionResize () { var diffx = mouse.x - x0, diffy = mouse.y - y0, x = sel.x, y = sel.y, w = sel.width, h = sel.height; switch (mouseResize) { case 'nw': x += diffx; y += diffy; w -= diffx; h -= diffy; break; case 'n': y += diffy; h -= diffy; break; case 'ne': y += diffy; w += diffx; h -= diffy; break; case 'e': w += diffx; break; case 'se': w += diffx; h += diffy; break; case 's': h += diffy; break; case 'sw': x += diffx; w -= diffx; h += diffy; break; case 'w': x += diffx; w -= diffx; break; default: lastSel = null; return; } if (!w || !h) { lastSel = null; return; } // Constrain the rectangle to have the same aspect ratio as the initial // rectangle. if (shiftKey) { var p = sel.width / sel.height, w2 = w, h2 = h; switch (mouseResize.charAt(0)) { case 'n': case 's': w2 = MathRound(h*p); break; default: h2 = MathRound(w/p); } switch (mouseResize) { case 'nw': case 'sw': x -= w2 - w; y -= h2 - h; } w = w2; h = h2; } if (w < 0) { x += w; w *= -1; } if (h < 0) { y += h; h *= -1; } var mw = w * image.canvasScale - borderDouble, mh = h * image.canvasScale - borderDouble; if (mw < 1 || mh < 1) { lastSel = null; return; } // Resizing the ImageData if (config.transform) { bufferContext.clearRect(0, 0, image.width, image.height); if (!config.transparent) { bufferContext.fillRect(x, y, w, h); } // Parameters: // source image, dest x, dest y, dest width, dest height bufferContext.drawImage(sel.canvas, x, y, w, h); } marqueeStyle.top = (y * image.canvasScale) + 'px'; marqueeStyle.left = (x * image.canvasScale) + 'px'; marqueeStyle.width = mw + 'px'; marqueeStyle.height = mh + 'px'; lastSel = {'x': x, 'y': y, 'width': w, 'height': h}; }; /** * Determine the are where the mouse is located: if it is inside or outside of * the selection rectangle, or on the selection border. * @private */ function mouseAreaUpdate () { var border = config.borderWidth / image.canvasScale, cursor = '', x1_out = sel.x + sel.width, y1_out = sel.y + sel.height, x1_in = x1_out - border, y1_in = y1_out - border, x0_out = sel.x, y0_out = sel.y, x0_in = sel.x + border, y0_in = sel.y + border; mouseArea = 'out'; // Inside the rectangle if (mouse.x < x1_in && mouse.y < y1_in && mouse.x > x0_in && mouse.y > y0_in) { cursor = 'move'; mouseArea = 'in'; } else { // On one of the borders (north/south) if (mouse.x >= x0_out && mouse.x <= x1_out && mouse.y >= y0_out && mouse.y <= y0_in) { cursor = 'n'; } else if (mouse.x >= x0_out && mouse.x <= x1_out && mouse.y >= y1_in && mouse.y <= y1_out) { cursor = 's'; } // West/east if (mouse.y >= y0_out && mouse.y <= y1_out && mouse.x >= x0_out && mouse.x <= x0_in) { cursor += 'w'; } else if (mouse.y >= y0_out && mouse.y <= y1_out && mouse.x >= x1_in && mouse.x <= x1_out) { cursor += 'e'; } if (cursor !== '') { mouseResize = cursor; cursor += '-resize'; mouseArea = 'border'; } } // Due to bug 126457 Opera will not automatically update the cursor, // therefore they will not see any visual feedback. if (cursor !== marqueeStyle.cursor) { marqueeStyle.cursor = cursor; } }; /** * The <code>canvasSizeChange</code> application event handler. This method * makes sure the selection size stays in sync. * * @private * @param {pwlib.appEvent.canvasSizeChange} ev The application event object. */ function ev_canvasSizeChange (ev) { if (_self.state !== _self.STATE_SELECTED) { return; } marqueeStyle.top = (sel.y * ev.scale) + 'px'; marqueeStyle.left = (sel.x * ev.scale) + 'px'; marqueeStyle.width = (sel.width * ev.scale - borderDouble) + 'px'; marqueeStyle.height = (sel.height * ev.scale - borderDouble) + 'px'; }; /** * The <code>configChange</code> application event handler. This method makes * sure that changes to the selection transparency configuration option are * applied. * * @private * @param {pwlib.appEvent.configChange} ev The application event object. */ function ev_configChange (ev) { // Continue only if the selection rectangle is available. if (ev.group !== 'selection' || ev.config !== 'transparent' || !config.transform || _self.state !== _self.STATE_SELECTED) { return; } if (!sel.layerCleared) { selectionBufferInit(); } bufferContext.clearRect(sel.x, sel.y, sel.width, sel.height); if (!ev.value) { bufferContext.fillRect(sel.x, sel.y, sel.width, sel.height); } // Draw the updated selection bufferContext.drawImage(sel.canvas, sel.x, sel.y, sel.width, sel.height); }; /** * Initialize the selection buffer, when the user starts dragging or resizing * the selected pixels. * * @private */ function selectionBufferInit () { var x = sel.x, y = sel.y, w = sel.width, h = sel.height, sumX = sel.x + sel.width, sumY = sel.y + sel.height, dx = 0, dy = 0; sel.widthOriginal = w; sel.heightOriginal = h; if (x < 0) { w += x; dx -= x; x = 0; } if (y < 0) { h += y; dy -= y; y = 0; } if (sumX > image.width) { w = image.width - sel.x; } if (sumY > image.height) { h = image.height - sel.y; } if (!config.transparent) { bufferContext.fillRect(x, y, w, h); } // Parameters: // source image, src x, src y, src w, src h, dest x, dest y, dest w, dest h bufferContext.drawImage(layerCanvas, x, y, w, h, x, y, w, h); sel.canvas.width = sel.widthOriginal; sel.canvas.height = sel.heightOriginal; // Also put the selected pixels into the selection buffer. sel.context.drawImage(layerCanvas, x, y, w, h, dx, dy, w, h); // Clear the selected pixels from the image layerContext.clearRect(x, y, w, h); sel.layerCleared = true; app.historyAdd(); }; /** * Perform the selection buffer merge onto the current image layer. * @private */ function selectionMergeStrict () { if (!sel.layerCleared) { return; } if (!config.transparent) { layerContext.fillRect(sel.x, sel.y, sel.width, sel.height); } layerContext.drawImage(sel.canvas, sel.x, sel.y, sel.width, sel.height); bufferContext.clearRect(sel.x, sel.y, sel.width, sel.height); sel.layerCleared = false; sel.canvas.width = 5; sel.canvas.height = 5; app.historyAdd(); }; /** * Merge the selection buffer onto the current image layer. * * <p>This method dispatches the {@link pwlib.appEvent.selectionChange} * application event. * * @returns {Boolean} True if the operation was successful, or false if not. */ this.selectionMerge = function () { if (_self.state !== _self.STATE_SELECTED) { return false; } selectionMergeStrict(); _self.state = _self.STATE_NONE; marqueeHide(); gui.statusShow('selectionActive'); app.events.dispatch(new appEvent.selectionChange(_self.state)); return true; }; /** * Select all the entire image. * * <p>This method dispatches the {@link pwlib.appEvent.selectionChange} * application event. * * @returns {Boolean} True if the operation was successful, or false if not. */ this.selectAll = function () { if (_self.state !== _self.STATE_NONE && _self.state !== _self.STATE_SELECTED) { return false; } if (_self.state === _self.STATE_SELECTED) { selectionMergeStrict(); } else { _self.state = _self.STATE_SELECTED; marqueeStyle.display = ''; } sel.x = 0; sel.y = 0; sel.width = image.width; sel.height = image.height; marqueeStyle.top = '0px'; marqueeStyle.left = '0px'; marqueeStyle.width = (sel.width*image.canvasScale - borderDouble) + 'px'; marqueeStyle.height = (sel.height*image.canvasScale - borderDouble) + 'px'; mouseAreaUpdate(); app.events.dispatch(new appEvent.selectionChange(_self.state, sel.x, sel.y, sel.width, sel.height)); return true; }; /** * Cut the selected pixels. The associated ImageData is stored in {@link * PaintWeb#clipboard}. * * <p>This method dispatches two application events: {@link * pwlib.appEvent.clipboardUpdate} and {@link pwlib.appEvent.selectionChange}. * * @returns {Boolean} True if the operation was successful, or false if not. */ this.selectionCut = function () { if (!_self.selectionCopy()) { return false; } if (sel.layerCleared) { bufferContext.clearRect(sel.x, sel.y, sel.width, sel.height); sel.canvas.width = 5; sel.canvas.height = 5; sel.layerCleared = false; } else { layerContext.clearRect(sel.x, sel.y, sel.width, sel.height); app.historyAdd(); } _self.state = _self.STATE_NONE; marqueeHide(); app.events.dispatch(new appEvent.selectionChange(_self.state)); gui.statusShow('selectionActive'); return true; }; /** * Copy the selected pixels. The associated ImageData is stored in {@link * PaintWeb#clipboard}. * * <p>This method dispatches the {@link pwlib.appEvent.clipboardUpdate} * application event. * * @returns {Boolean} True if the operation was successful, or false if not. */ this.selectionCopy = function () { if (_self.state !== _self.STATE_SELECTED) { return false; } if (!layerContext.getImageData || !layerContext.putImageData) { alert(lang.errorClipboardUnsupported); return false; } if (!sel.layerCleared) { var w = sel.width, h = sel.height, sumX = sel.width + sel.x; sumY = sel.height + sel.y; if (sumX > image.width) { w = image.width - sel.x; } if (sumY > image.height) { h = image.height - sel.y; } try { app.clipboard = layerContext.getImageData(sel.x, sel.y, w, h); } catch (err) { alert(lang.failedSelectionCopy); return false; } } else { try { app.clipboard = sel.context.getImageData(0, 0, sel.widthOriginal, sel.heightOriginal); } catch (err) { alert(lang.failedSelectionCopy); return false; } } app.events.dispatch(new appEvent.clipboardUpdate(app.clipboard)); return true; }; /** * Paste an image from the "clipboard". The {@link PaintWeb#clipboard} object * must be an ImageData. This method will generate a new selection which will * hold the pasted image. * * <p>The {@link pwlib.appEvent.selectionChange} application event is * dispatched. * * <p>If the {@link PaintWeb.config.selection.transform} value is false, then * it becomes true. The {@link pwlib.appEvent.configChange} application is * then dispatched. * * @returns {Boolean} True if the operation was successful, or false if not. */ this.clipboardPaste = function () { if (!app.clipboard || _self.state !== _self.STATE_NONE && _self.state !== _self.STATE_SELECTED) { return false; } if (!layerContext.getImageData || !layerContext.putImageData) { alert(lang.errorClipboardUnsupported); return false; } // The default position for the pasted image is the top left corner of the // visible area, taking into consideration the zoom level. var x = MathRound(gui.elems.viewport.scrollLeft / image.canvasScale), y = MathRound(gui.elems.viewport.scrollTop / image.canvasScale), w = app.clipboard.width, h = app.clipboard.height; sel.canvas.width = w; sel.canvas.height = h; sel.context.putImageData(app.clipboard, 0, 0); if (_self.state === _self.STATE_SELECTED) { bufferContext.clearRect(sel.x, sel.y, sel.width, sel.height); } else { _self.state = _self.STATE_SELECTED; } if (!config.transparent) { bufferContext.fillRect(x, y, w, h); } bufferContext.drawImage(sel.canvas, x, y, w, h); sel.widthOriginal = sel.width = w; sel.heightOriginal = sel.height = h; sel.x = x; sel.y = y; sel.layerCleared = true; marqueeStyle.top = (y * image.canvasScale) + 'px'; marqueeStyle.left = (x * image.canvasScale) + 'px'; marqueeStyle.width = (w * image.canvasScale - borderDouble) + 'px'; marqueeStyle.height = (h * image.canvasScale - borderDouble) + 'px'; marqueeStyle.display = ''; if (!config.transform) { config.transform = true; app.events.dispatch(new appEvent.configChange(true, false, 'transform', 'selection', config)); } mouseAreaUpdate(); app.events.dispatch(new appEvent.selectionChange(_self.state, sel.x, sel.y, sel.width, sel.height)); gui.statusShow('selectionAvailable'); return true; }; /** * Perform selection delete. * * <p>This method changes the {@link PaintWeb.config.selection.transform} * value to false if the current selection has pixels that are currently being * manipulated. In such cases, the {@link pwlib.appEvent.configChange} * application event is also dispatched. * * @returns {Boolean} True if the operation was successful, or false if not. */ this.selectionDelete = function () { // Delete the pixels from the image if they are not deleted already. if (_self.state !== _self.STATE_SELECTED) { return false; } if (!sel.layerCleared) { layerContext.clearRect(sel.x, sel.y, sel.width, sel.height); app.historyAdd(); } else { bufferContext.clearRect(sel.x, sel.y, sel.width, sel.height); sel.layerCleared = false; sel.canvas.width = 5; sel.canvas.height = 5; if (config.transform) { config.transform = false; app.events.dispatch(new appEvent.configChange(false, true, 'transform', 'selection', config)); } } return true; }; /** * Drop the current selection. * * <p>This method dispatches the {@link pwlib.appEvent.selectionChange} * application event. * * @returns {Boolean} True if the operation was successful, or false if not. */ this.selectionDrop = function () { if (_self.state !== _self.STATE_SELECTED) { return false; } if (sel.layerCleared) { bufferContext.clearRect(sel.x, sel.y, sel.width, sel.height); sel.canvas.width = 5; sel.canvas.height = 5; sel.layerCleared = false; } _self.state = _self.STATE_NONE; marqueeHide(); gui.statusShow('selectionActive'); app.events.dispatch(new appEvent.selectionChange(_self.state)); return true; }; /** * Fill the available selection with the current * <var>bufferContext.fillStyle</var>. * * @returns {Boolean} True if the operation was successful, or false if not. */ this.selectionFill = function () { if (_self.state !== _self.STATE_SELECTED) { return false; } if (sel.layerCleared) { sel.context.fillStyle = bufferContext.fillStyle; sel.context.fillRect(0, 0, sel.widthOriginal, sel.heightOriginal); bufferContext.fillRect(sel.x, sel.y, sel.width, sel.height); } else { layerContext.fillStyle = bufferContext.fillStyle; layerContext.fillRect(sel.x, sel.y, sel.width, sel.height); app.historyAdd(); } return true; }; /** * Crop the image to selection width and height. The selected pixels become * the image itself. * * <p>This method invokes the {@link this#selectionMerge} and {@link * PaintWeb#imageCrop} methods. * * @returns {Boolean} True if the operation was successful, or false if not. */ this.selectionCrop = function () { if (_self.state !== _self.STATE_SELECTED) { return false; } _self.selectionMerge(); var w = sel.width, h = sel.height, sumX = sel.x + w, sumY = sel.y + h; if (sumX > image.width) { w -= sumX - image.width; } if (sumY > image.height) { h -= sumY - image.height; } app.imageCrop(sel.x, sel.y, w, h); return true; }; /** * The <code>keydown</code> event handler. This method calls selection-related * commands associated to keyboard shortcuts. * * @param {Event} ev The DOM Event object. * * @returns {Boolean} True if the keyboard shortcut was recognized, or false * if not. * * @see PaintWeb.config.selection.keys holds the keyboard shortcuts * configuration. */ this.keydown = function (ev) { switch (ev.kid_) { case config.keys.transformToggle: // Toggle the selection transformation mode. config.transform = !config.transform; app.events.dispatch(new appEvent.configChange(config.transform, !config.transform, 'transform', 'selection', config)); break; case config.keys.selectionCrop: return _self.selectionCrop(ev); case config.keys.selectionDelete: return _self.selectionDelete(ev); case config.keys.selectionDrop: return _self.selectionDrop(ev); case config.keys.selectionFill: return _self.selectionFill(ev); default: return false; } return true; }; }; /** * @class Selection change event. This event is not cancelable. * * @augments pwlib.appEvent * * @param {Number} state Tells the new state of the selection. * @param {Number} [x] Selection start position on the x-axis of the image. * @param {Number} [y] Selection start position on the y-axis of the image. * @param {Number} [width] Selection width. * @param {Number} [height] Selection height. */ pwlib.appEvent.selectionChange = function (state, x, y, width, height) { /** * No selection is available. * @constant */ this.STATE_NONE = 0; /** * Selection available. * @constant */ this.STATE_SELECTED = 2; /** * Selection state. * @type Number */ this.state = state; /** * Selection location on the x-axis of the image. * @type Number */ this.x = x; /** * Selection location on the y-axis of the image. * @type Number */ this.y = y; /** * Selection width. * @type Number */ this.width = width; /** * Selection height. * @type Number */ this.height = height; pwlib.appEvent.call(this, 'selectionChange'); }; // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * Copyright (C) 2008, 2009 Mihai Şucan * * This file is part of PaintWeb. * * PaintWeb is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PaintWeb is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PaintWeb. If not, see <http://www.gnu.org/licenses/>. * * $URL: http://code.google.com/p/paintweb $ * $Date: 2009-07-01 18:44:56 +0300 $ */ /** * @author <a lang="ro" href="http://www.robodesign.ro/mihai">Mihai Şucan</a> * @fileOverview Holds the ellipse tool implementation. */ /** * @class The ellipse tool. * * @param {PaintWeb} app Reference to the main paint application object. */ pwlib.tools.ellipse = function (app) { var _self = this, clearInterval = app.win.clearInterval, config = app.config, context = app.buffer.context, gui = app.gui, image = app.image, MathMax = Math.max, MathMin = Math.min, mouse = app.mouse, setInterval = app.win.setInterval; /** * The interval ID used for invoking the drawing operation every few * milliseconds. * * @private * @see PaintWeb.config.toolDrawDelay */ var timer = null; /** * Tells if the <kbd>Shift</kbd> key is down or not. This is used by the * drawing function. * * @private * @type Boolean * @default false */ var shiftKey = false; /** * Tells if the drawing canvas needs to be updated or not. * * @private * @type Boolean * @default false */ var needsRedraw = false; var K = 4*((Math.SQRT2-1)/3); /** * Holds the starting point on the <var>x</var> axis of the image, for the * current drawing operation. * * @private * @type Number */ var x0 = 0; /** * Holds the starting point on the <var>y</var> axis of the image, for the * current drawing operation. * * @private * @type Number */ var y0 = 0; /** * Tool deactivation event handler. */ this.deactivate = function () { if (timer) { clearInterval(timer); timer = null; } if (mouse.buttonDown) { context.clearRect(0, 0, image.width, image.height); } needsRedraw = false; return true; }; /** * Initialize the drawing operation. * * @param {Event} ev The DOM Event object. */ this.mousedown = function (ev) { // The mouse start position x0 = mouse.x; y0 = mouse.y; if (!timer) { timer = setInterval(_self.draw, config.toolDrawDelay); } shiftKey = ev.shiftKey; needsRedraw = false; gui.statusShow('ellipseMousedown'); return true; }; /** * Store the <kbd>Shift</kbd> key state which is used by the drawing function. * * @param {Event} ev The DOM Event object. */ this.mousemove = function (ev) { shiftKey = ev.shiftKey; needsRedraw = true; }; /** * Perform the drawing operation. This function is called every few * milliseconds. * * <p>Hold down the <kbd>Shift</kbd> key to draw a circle. * <p>Press <kbd>Escape</kbd> to cancel the drawing operation. * * @see PaintWeb.config.toolDrawDelay */ this.draw = function () { if (!needsRedraw) { return; } context.clearRect(0, 0, image.width, image.height); var rectx0 = MathMin(mouse.x, x0), rectx1 = MathMax(mouse.x, x0), recty0 = MathMin(mouse.y, y0), recty1 = MathMax(mouse.y, y0); /* ABCD - rectangle A(rectx0, recty0), B(rectx1, recty0), C(rectx1, recty1), D(rectx0, recty1) */ var w = rectx1-rectx0, h = recty1-recty0; if (!w || !h) { needsRedraw = false; return; } // Constrain the ellipse to be a circle if (shiftKey) { if (w > h) { recty1 = recty0+w; if (recty0 == mouse.y) { recty0 -= w-h; recty1 -= w-h; } h = w; } else { rectx1 = rectx0+h; if (rectx0 == mouse.x) { rectx0 -= h-w; rectx1 -= h-w; } w = h; } } // Ellipse radius var rx = w/2, ry = h/2; // Ellipse center var cx = rectx0+rx, cy = recty0+ry; // Ellipse radius*Kappa, for the Bézier curve control points rx *= K; ry *= K; context.beginPath(); // startX, startY context.moveTo(cx, recty0); // Control points: cp1x, cp1y, cp2x, cp2y, destx, desty // go clockwise: top-middle, right-middle, bottom-middle, then left-middle context.bezierCurveTo(cx + rx, recty0, rectx1, cy - ry, rectx1, cy); context.bezierCurveTo(rectx1, cy + ry, cx + rx, recty1, cx, recty1); context.bezierCurveTo(cx - rx, recty1, rectx0, cy + ry, rectx0, cy); context.bezierCurveTo(rectx0, cy - ry, cx - rx, recty0, cx, recty0); if (config.shapeType != 'stroke') { context.fill(); } if (config.shapeType != 'fill') { context.stroke(); } context.closePath(); needsRedraw = false; }; /** * End the drawing operation, once the user releases the mouse button. * * @param {Event} ev The DOM Event object. */ this.mouseup = function (ev) { // Allow click+mousemove, not only mousedown+move+up if (mouse.x == x0 && mouse.y == y0) { mouse.buttonDown = true; return true; } if (timer) { clearInterval(timer); timer = null; } shiftKey = ev.shiftKey; _self.draw(); app.layerUpdate(); gui.statusShow('ellipseActive'); return true; }; /** * Allows the user to press <kbd>Escape</kbd> to cancel the drawing operation. * * @param {Event} ev The DOM Event object. * * @returns {Boolean} True if the drawing operation was cancelled, or false if * not. */ this.keydown = function (ev) { if (!mouse.buttonDown || ev.kid_ != 'Escape') { return false; } if (timer) { clearInterval(timer); timer = null; } context.clearRect(0, 0, image.width, image.height); mouse.buttonDown = false; needsRedraw = false; gui.statusShow('ellipseActive'); return true; }; }; // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * Copyright (C) 2008, 2009 Mihai Şucan * * This file is part of PaintWeb. * * PaintWeb is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PaintWeb is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PaintWeb. If not, see <http://www.gnu.org/licenses/>. * * $URL: http://code.google.com/p/paintweb $ * $Date: 2009-06-11 20:23:04 +0300 $ */ /** * @author <a lang="ro" href="http://www.robodesign.ro/mihai">Mihai Şucan</a> * @fileOverview Holds the line tool implementation. */ /** * @class The line tool. * * @param {PaintWeb} app Reference to the main paint application object. */ pwlib.tools.line = function (app) { var _self = this, clearInterval = app.win.clearInterval, config = app.config, context = app.buffer.context, gui = app.gui, image = app.image, mouse = app.mouse, setInterval = app.win.setInterval, snapXY = app.toolSnapXY; /** * The interval ID used for invoking the drawing operation every few * milliseconds. * * @private * @see PaintWeb.config.toolDrawDelay */ var timer = null; /** * Tells if the <kbd>Shift</kbd> key is down or not. This is used by the * drawing function. * * @private * @type Boolean * @default false */ var shiftKey = false; /** * Tells if the drawing canvas needs to be updated or not. * * @private * @type Boolean * @default false */ var needsRedraw = false; /** * Holds the starting point on the <var>x</var> axis of the image, for the * current drawing operation. * * @private * @type Number */ var x0 = 0; /** * Holds the starting point on the <var>y</var> axis of the image, for the * current drawing operation. * * @private * @type Number */ var y0 = 0; /** * Tool deactivation event handler. */ this.deactivate = function () { if (timer) { clearInterval(timer); timer = null; } if (mouse.buttonDown) { context.clearRect(0, 0, image.width, image.height); } needsRedraw = false; return true; }; /** * Initialize the drawing operation, by storing the location of the pointer, * the start position. * * @param {Event} ev The DOM Event object. */ this.mousedown = function (ev) { x0 = mouse.x; y0 = mouse.y; if (!timer) { timer = setInterval(_self.draw, config.toolDrawDelay); } shiftKey = ev.shiftKey; needsRedraw = false; gui.statusShow('lineMousedown'); return true; }; /** * Store the <kbd>Shift</kbd> key state which is used by the drawing function. * * @param {Event} ev The DOM Event object. */ this.mousemove = function (ev) { shiftKey = ev.shiftKey; needsRedraw = true; }; /** * Perform the drawing operation. This function is called every few * milliseconds. * * <p>Hold down the <kbd>Shift</kbd> key to draw a straight * horizontal/vertical line. * <p>Press <kbd>Escape</kbd> to cancel the drawing operation. * * @see PaintWeb.config.toolDrawDelay */ this.draw = function () { if (!needsRedraw) { return; } context.clearRect(0, 0, image.width, image.height); // Snapping on the X/Y axis. if (shiftKey) { snapXY(x0, y0); } context.beginPath(); context.moveTo(x0, y0); context.lineTo(mouse.x, mouse.y); context.stroke(); context.closePath(); needsRedraw = false; }; /** * End the drawing operation, once the user releases the mouse button. * * @param {Event} ev The DOM Event object. */ this.mouseup = function (ev) { // Allow users to click then drag, not only mousedown+drag+mouseup. if (mouse.x == x0 && mouse.y == y0) { mouse.buttonDown = true; return true; } if (timer) { clearInterval(timer); timer = null; } shiftKey = ev.shiftKey; _self.draw(); gui.statusShow('lineActive'); app.layerUpdate(); return true; }; /** * Allows the user to press <kbd>Escape</kbd> to cancel the drawing operation. * * @param {Event} ev The DOM Event object. * * @returns {Boolean} True if the drawing operation was cancelled, or false if * not. */ this.keydown = function (ev) { if (!mouse.buttonDown || ev.kid_ != 'Escape') { return false; } if (timer) { clearInterval(timer); timer = null; } context.clearRect(0, 0, image.width, image.height); mouse.buttonDown = false; needsRedraw = false; gui.statusShow('lineActive'); return true; }; }; // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * Copyright (C) 2008, 2009 Mihai Şucan * * This file is part of PaintWeb. * * PaintWeb is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PaintWeb is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PaintWeb. If not, see <http://www.gnu.org/licenses/>. * * $URL: http://code.google.com/p/paintweb $ * $Date: 2009-06-15 20:27:08 +0300 $ */ /** * @author <a lang="ro" href="http://www.robodesign.ro/mihai">Mihai Şucan</a> * @fileOverview Holds the hand tool implementation. */ /** * @class The hand tool. This tool allows the user to drag the image canvas * inside the viewport. * * @param {PaintWeb} app Reference to the main paint application object. */ pwlib.tools.hand = function (app) { var _self = this, bufferCanvas = app.buffer.canvas, bufferStyle = bufferCanvas.style, config = app.config; clearInterval = app.win.clearInterval, image = app.image, MathRound = Math.round, mouse = app.mouse, viewport = app.gui.elems.viewport, vheight = 0, vwidth = 0, setInterval = app.win.setInterval; /** * The interval ID used for invoking the viewport drag operation every few * milliseconds. * * @private * @see PaintWeb.config.toolDrawDelay */ var timer = null; /** * Tells if the viewport needs to be scrolled. * * @private * @type Boolean * @default false */ var needsScroll = false; /** * Holds the previous tool ID. * * @private * @type String */ this.prevTool = null; var x0 = 0, y0 = 0, x1 = 0, y1 = 0, l0 = 0, t0 = 0; /** * Tool preactivation event handler. * * @returns {Boolean} True if the tool can become active, or false if not. */ this.preActivate = function () { if (!viewport) { return false; } _self.prevTool = app.tool._id; // Check if the image canvas can be scrolled within the viewport. var cs = app.win.getComputedStyle(viewport, null), bwidth = parseInt(bufferStyle.width), bheight = parseInt(bufferStyle.height); vwidth = parseInt(cs.width), vheight = parseInt(cs.height); if (vheight < bheight || vwidth < bwidth) { return true; } else { return false; } }; /** * Tool activation event handler. */ this.activate = function () { bufferStyle.cursor = 'move'; app.shadowDisallow(); }; /** * Tool deactivation event handler. */ this.deactivate = function (ev) { if (timer) { clearInterval(timer); timer = null; app.doc.removeEventListener('mousemove', ev_mousemove, false); app.doc.removeEventListener('mouseup', ev_mouseup, false); } bufferStyle.cursor = ''; app.shadowAllow(); }; /** * Initialize the canvas drag. * * @param {Event} ev The DOM event object. */ this.mousedown = function (ev) { x0 = ev.clientX; y0 = ev.clientY; l0 = viewport.scrollLeft; t0 = viewport.scrollTop; needsScroll = false; app.doc.addEventListener('mousemove', ev_mousemove, false); app.doc.addEventListener('mouseup', ev_mouseup, false); if (!timer) { timer = setInterval(viewportScroll, config.toolDrawDelay); } return true; }; /** * The <code>mousemove</code> event handler. This simply stores the current * mouse location. * * @param {Event} ev The DOM Event object. */ function ev_mousemove (ev) { x1 = ev.clientX; y1 = ev.clientY; needsScroll = true; }; /** * Perform the canvas drag operation. This function is called every few * milliseconds. * * <p>Press <kbd>Escape</kbd> to stop dragging and to get back to the previous * tool. */ function viewportScroll () { if (needsScroll) { viewport.scrollTop = t0 - y1 + y0; viewport.scrollLeft = l0 - x1 + x0; needsScroll = false; } }; /** * The <code>mouseup</code> event handler. */ function ev_mouseup (ev) { if (timer) { clearInterval(timer); timer = null; } ev_mousemove(ev); viewportScroll(); app.doc.removeEventListener('mousemove', ev_mousemove, false); app.doc.removeEventListener('mouseup', ev_mouseup, false); mouse.buttonDown = false; }; /** * Allows the user to press <kbd>Escape</kbd> to stop dragging the canvas, and * to return to the previous tool. * * @param {Event} ev The DOM Event object. * * @returns {Boolean} True if the key was recognized, or false if not. */ this.keydown = function (ev) { if (!_self.prevTool || ev.kid_ != 'Escape') { return false; } app.toolActivate(_self.prevTool, ev); return true; }; }; // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * Copyright (C) 2009 Mihai Şucan * * This file is part of PaintWeb. * * PaintWeb is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PaintWeb is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PaintWeb. If not, see <http://www.gnu.org/licenses/>. * * $URL: http://code.google.com/p/paintweb $ * $Date: 2009-11-10 20:12:34 +0200 $ */ /** * @author <a lang="ro" href="http://www.robodesign.ro/mihai">Mihai Şucan</a> * @fileOverview Holds the color bucket tool implementation, also known as the * flood fill tool. */ /** * @class The color bucket tool. * * The implementation here is based on the seed fill algorithm of Paul S. * Heckbert (1990). * * @param {PaintWeb} app Reference to the main paint application object. */ pwlib.tools.cbucket = function (app) { var _self = this, config = app.config, layer = app.layer.context, buffer = app.buffer.context, iwidth = app.image.width, iheight = app.image.height, mouse = app.mouse; var stackMax = 10000; // maximum depth of stack var lines = []; // stack of lines var pixelNew, layerpix; /** * The <code>preActivate</code> event handler. This method checks if the * browser implements the <code>getImageData()</code> and * <code>putImageData()</code> context methods. If not, the color bucket tool * cannot be used. * * @returns {Boolean} True if the drawing tool can be activated, or false * otherwise. */ this.preActivate = function () { // The latest versions of all browsers which implement Canvas, also // implement the getImageData() method. This was only a problem with some // old versions (eg. Opera 9.2). if (!layer.getImageData || !layer.putImageData) { alert(app.lang.errorCbucketUnsupported); return false; } else { return true; } }; /** * The <code>activate</code> event handler. Canvas shadow rendering is * disabled. */ this.activate = function () { app.shadowDisallow(); }; /** * The <code>deactivate</code> event handler. Canvas shadow rendering is * allowed once again. */ this.deactivate = function () { app.shadowAllow(); }; /** * The <code>click</code> and <code>contextmenu</code> event handler. This * method performs the flood fill operation. * * @param {Event} ev The DOM Event object. * * @returns {Boolean} True if the image was modified, or false otherwise. */ this.click = function (ev) { // Allow the user to right-click or hold down the Shift key to use the // border color for filling the image. if (ev.type === 'contextmenu' || ev.button === 2 || ev.shiftKey) { var fillStyle = buffer.fillStyle; buffer.fillStyle = buffer.strokeStyle; buffer.fillRect(0, 0, 1, 1); buffer.fillStyle = fillStyle; } else { buffer.fillRect(0, 0, 1, 1); } // Instead of parsing the fillStyle ... pixelNew = buffer.getImageData(0, 0, 1, 1); pixelNew = [pixelNew.data[0], pixelNew.data[1], pixelNew.data[2], pixelNew.data[3]]; buffer.clearRect(0, 0, 1, 1); var pixelOld = layer.getImageData(mouse.x, mouse.y, 1, 1).data; pixelOld = pixelOld[0] + ';' + pixelOld[1] + ';' + pixelOld[2] + ';' + pixelOld[3]; if (pixelOld === pixelNew.join(';')) { return false; } fill(mouse.x, mouse.y, pixelOld); app.historyAdd(); return true; }; this.contextmenu = this.click; /** * Fill the image with the current fill color, starting from the <var>x</var> * and <var>y</var> coordinates. * * @private * * @param {Number} x The x coordinate for the starting point. * @param {Number} y The y coordinate for the starting point. * @param {String} pixelOld The old pixel value. */ var fill = function (x, y, pixelOld) { var start, x1, x2, dy, tmp, idata; pushLine(y, x, x, 1); // needed in some cases pushLine(y + 1, x, x, -1); // seed segment (popped 1st) while (lines.length > 0) { // pop segment off stack and fill a neighboring scan line tmp = lines.pop(); dy = tmp[3]; y = tmp[0] + dy; x1 = tmp[1]; x2 = tmp[2]; layerpix = null; idata = layer.getImageData(0, y, iwidth, 1); layerpix = idata.data; // segment of scan line y-dy for x1 <= x <= x2 was previously filled, now // explore adjacent pixels in scan line y for (x = x1; x >= 0 && pixelRead(x) === pixelOld; x--) { pixelWrite(x); } if (x >= x1) { for (x++; x <= x2 && pixelRead(x) !== pixelOld; x++); start = x; if (x > x2) { layer.putImageData(idata, 0, y); continue; } } else { start = x + 1; if (start < x1) { pushLine(y, start, x1 - 1, -dy); // leak on left? } x = x1 + 1; } do { for (; x < iwidth && pixelRead(x) === pixelOld; x++) { pixelWrite(x); } pushLine(y, start, x - 1, dy); if (x > (x2 + 1)) { pushLine(y, x2 + 1, x - 1, -dy); // leak on right? } for (x++; x <= x2 && pixelRead(x) !== pixelOld; x++); start = x; } while (x <= x2); layer.putImageData(idata, 0, y); } layerpix = null; idata = null; }; var pushLine = function (y, xl, xr, dy) { if (lines.length < stackMax && (y+dy) >= 0 && (y+dy) < iheight) { lines.push([y, xl, xr, dy]); } }; var pixelRead = function (x) { var r = 4 * x; return layerpix[r] + ';' + layerpix[r+1] + ';' + layerpix[r+2] + ';' + layerpix[r+3]; }; var pixelWrite = function (x) { var r = 4 * x; layerpix[r] = pixelNew[0]; layerpix[r+1] = pixelNew[1]; layerpix[r+2] = pixelNew[2]; layerpix[r+3] = pixelNew[3]; }; }; // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * Copyright (C) 2008, 2009 Mihai Şucan * * This file is part of PaintWeb. * * PaintWeb is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PaintWeb is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PaintWeb. If not, see <http://www.gnu.org/licenses/>. * * $URL: http://code.google.com/p/paintweb $ * $Date: 2009-06-11 20:28:07 +0300 $ */ /** * @author <a lang="ro" href="http://www.robodesign.ro/mihai">Mihai Şucan</a> * @fileOverview Holds the polygon tool implementation. */ /** * @class The polygon tool. * * @param {PaintWeb} app Reference to the main paint application object. */ pwlib.tools.polygon = function (app) { var _self = this, clearInterval = app.win.clearInterval, config = app.config, context = app.buffer.context, gui = app.gui, image = app.image, MathAbs = Math.abs, mouse = app.mouse, setInterval = app.win.setInterval, snapXY = app.toolSnapXY; /** * Holds the points in the polygon being drawn. * * @private * @type Array */ var points = []; /** * The interval ID used for invoking the drawing operation every few * milliseconds. * * @private * @see PaintWeb.config.toolDrawDelay */ var timer = null; /** * Tells if the <kbd>Shift</kbd> key is down or not. This is used by the * drawing function. * * @private * @type Boolean * @default false */ var shiftKey = false; /** * Tells if the drawing canvas needs to be updated or not. * * @private * @type Boolean * @default false */ var needsRedraw = false; /** * The tool deactivation method, used for clearing the buffer. */ this.deactivate = function () { if (timer) { clearInterval(timer); timer = null; } if (points.length) { context.clearRect(0, 0, image.width, image.height); } needsRedraw = false; points = []; return true; }; /** * The <code>mousedown</code> event handler. * * @param {Event} ev The DOM Event object. * @returns {Boolean} True if the event handler executed, or false if not. */ this.mousedown = function (ev) { if (points.length == 0) { points.push([mouse.x, mouse.y]); } if (!timer) { timer = setInterval(_self.draw, config.toolDrawDelay); } shiftKey = ev.shiftKey; needsRedraw = false; gui.statusShow('polygonMousedown'); return true; }; /** * Store the <kbd>Shift</kbd> key state which is used by the drawing function. * * @param {Event} ev The DOM Event object. */ this.mousemove = function (ev) { shiftKey = ev.shiftKey; needsRedraw = true; }; /** * Draw the polygon. * * @see PaintWeb.config.toolDrawDelay */ this.draw = function (ev) { if (!needsRedraw) { return; } var n = points.length; if (!n || (n == 1 && !mouse.buttonDown)) { needsRedraw = false; return; } // Snapping on the X/Y axis for the current point (if available). if (mouse.buttonDown && shiftKey) { snapXY(points[n-1][0], points[n-1][1]); } context.clearRect(0, 0, image.width, image.height); context.beginPath(); context.moveTo(points[0][0], points[0][1]); // Draw the path of the polygon for (var i = 0; i < n; i++) { context.lineTo(points[i][0], points[i][1]); } if (mouse.buttonDown) { context.lineTo(mouse.x, mouse.y); } if (config.shapeType != 'stroke') { context.fill(); } // In the case where we only have a straight line, draw a stroke even if no // stroke should be drawn, such that the user has better visual feedback. if (config.shapeType != 'fill' || n == 1) { context.stroke(); } context.closePath(); needsRedraw = false; }; /** * The <code>mouseup</code> event handler. * * @param {Event} ev The DOM Event object. * @returns {Boolean} True if the event handler executed, or false if not. */ this.mouseup = function (ev) { var n = points.length; // Allow click+mousemove+click, not only mousedown+mousemove+mouseup. // Do this only for the first point in the polygon. if (n == 1 && mouse.x == points[n-1][0] && mouse.y == points[n-1][1]) { mouse.buttonDown = true; return true; } if (timer) { clearInterval(timer); timer = null; } shiftKey = ev.shiftKey; needsRedraw = true; if (ev.shiftKey) { snapXY(points[n-1][0], points[n-1][1]); } var diffx1 = MathAbs(mouse.x - points[0][0]), diffy1 = MathAbs(mouse.y - points[0][1]), diffx2 = MathAbs(mouse.x - points[n-1][0]), diffy2 = MathAbs(mouse.y - points[n-1][1]); // End the polygon if the new point is close enough to the first/last point. if ((diffx1 < 5 && diffy1 < 5) || (diffx2 < 5 && diffy2 < 5)) { // Add the start point to complete the polygon shape. points.push(points[0]); _self.draw(); points = []; gui.statusShow('polygonActive'); app.layerUpdate(); return true; } if (n > 3) { gui.statusShow('polygonEnd'); } else { gui.statusShow('polygonAddPoint'); } points.push([mouse.x, mouse.y]); _self.draw(); return true; }; /** * The <code>keydown</code> event handler. This method allows the user to * cancel drawing the current polygon, using the <kbd>Escape</kbd> key. The * <kbd>Enter</kbd> key can be used to accept the current polygon shape, and * end the drawing operation. * * @param {Event} ev The DOM Event object. * * @returns {Boolean} True if the keyboard shortcut was recognized, or false * if not. */ this.keydown = function (ev) { var n = points.length; if (!n || (ev.kid_ != 'Escape' && ev.kid_ != 'Enter')) { return false; } if (timer) { clearInterval(timer); timer = null; } mouse.buttonDown = false; if (ev.kid_ == 'Escape') { context.clearRect(0, 0, image.width, image.height); needsRedraw = false; } else if (ev.kid_ == 'Enter') { // Add the point of the last mousemove event, and the start point, to // complete the polygon. points.push([mouse.x, mouse.y]); points.push(points[0]); needsRedraw = true; _self.draw(); app.layerUpdate(); } points = []; gui.statusShow('polygonActive'); return true; }; }; // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * Copyright (C) 2008, 2009 Mihai Şucan * * This file is part of PaintWeb. * * PaintWeb is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PaintWeb is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PaintWeb. If not, see <http://www.gnu.org/licenses/>. * * $URL: http://code.google.com/p/paintweb $ * $Date: 2009-07-09 14:26:21 +0300 $ */ /** * @author <a lang="ro" href="http://www.robodesign.ro/mihai">Mihai Şucan</a> * @fileOverview Holds the implementation of the Color Mixer dialog. */ // For the implementation of this extension I used the following references: // - Wikipedia articles on each subject. // - the great brucelindbloom.com Web site - lots of information. /** * @class The Color Mixer extension. * * @param {PaintWeb} app Reference to the main paint application object. */ pwlib.extensions.colormixer = function (app) { var _self = this, config = app.config.colormixer, doc = app.doc, gui = app.gui, lang = app.lang.colormixer, MathFloor = Math.floor, MathMax = Math.max, MathMin = Math.min, MathPow = Math.pow, MathRound = Math.round, resScale = app.resolution.scale; /** * Holds references to various DOM elements. * * @private * @type Object */ this.elems = { /** * Reference to the element which holds Canvas controls (the dot on the * Canvas, and the slider). * @type Element */ 'controls': null, /** * Reference to the dot element that is rendered on top of the color space * visualisation. * @type Element */ 'chartDot': null, /** * Reference to the slider element. * @type Element */ 'slider': null, /** * Reference to the input element that allows the user to pick the color * palette to be displayed. * @type Element */ 'cpaletteInput': null, /** * The container element which holds the colors of the currently selected * palette. * @type Element */ 'cpaletteOutput': null, /** * Reference to the element which displays the current color. * @type Element */ "colorActive": null, /** * Reference to the element which displays the old color. * @type Element */ "colorOld": null }; /** * Reference to the Color Mixer floating panel GUI component object. * * @private * @type pwlib.guiFloatingPanel */ this.panel = null; /** * Reference to the Color Mixer tab panel GUI component object which holds the * inputs. * * @private * @type pwlib.guiTabPanel */ this.panelInputs = null; /** * Reference to the Color Mixer tab panel GUI component object which holds the * Canvas used for color space visualisation and the color palettes selector. * * @private * @type pwlib.guiTabPanel */ this.panelSelector = null; /** * Holds a reference to the 2D context of the color mixer Canvas element. This * is where the color chart and the slider are both drawn. * * @private * @type CanvasRenderingContext2D */ this.context2d = false; /** * Target input hooks. This object must hold two methods: * * <ul> * <li><code>show()</code> which is invoked by this extension when the Color * Mixer panel shows up on screen. * * <li><code>hide()</code> which is invoked when the Color Mixer panel is * hidden from the screen. * </ul> * * <p>The object must also hold information about the associated configuration * property: <var>configProperty</var>, <var>configGroup</var> and * <var>configGroupRef</var>. * * @type Object */ this.targetInput = null; /** * Holds the current color in several formats: RGB, HEX, HSV, CIE Lab, and * CMYK. Except for 'hex', all the values should be from 0 to 1. * * @type Object */ this.color = { // RGB red : 0, green: 0, blue : 0, alpha : 0, hex : 0, // HSV hue : 0, sat : 0, val : 0, // CMYK cyan : 0, magenta : 0, yellow : 0, black : 0, // CIE Lab cie_l : 0, cie_a : 0, cie_b : 0 }; /** * Holds references to all the DOM input fields, for each color channel. * * @private * @type Object */ this.inputs = { red : null, green : null, blue : null, alpha : null, hex : null, hue : null, sat : null, val : null, cyan : null, magenta : null, yellow : null, black : null, cie_l : null, cie_a : null, cie_b : null }; /** * The "absolute maximum" value is determined based on the min/max values. * For min -100 and max 100, the abs_max is 200. * @private * */ this.abs_max = {}; // The hue spectrum used by the HSV charts. var hueSpectrum = [ [255, 0, 0], // 0, Red, 0° [255, 255, 0], // 1, Yellow, 60° [ 0, 255, 0], // 2, Green, 120° [ 0, 255, 255], // 3, Cyan, 180° [ 0, 0, 255], // 4, Blue, 240° [255, 0, 255], // 5, Magenta, 300° [255, 0, 0] // 6, Red, 360° ]; // The active color key (input) determines how the color chart works. this.ckey_active = 'red'; // Given a group of the inputs: red, green and blue, when one of them is active, the ckey_adjoint is set to an array of the other two input IDs. this.ckey_adjoint = false; this.ckey_active_group = false; this.ckey_grouping = { 'red' : 'rgb', 'green' : 'rgb', 'blue' : 'rgb', 'hue' : 'hsv', 'sat' : 'hsv', 'val' : 'hsv', 'cyan' : 'cmyk', 'magenta' : 'cmyk', 'yellow' : 'cmyk', 'black' : 'cmyk', 'cie_l' : 'lab', 'cie_a' : 'lab', 'cie_b' : 'lab' }; // These values are automatically calculated when the color mixer is // initialized. this.sliderX = 0; this.sliderWidth = 0; this.sliderHeight = 0; this.sliderSpacing = 0; this.chartWidth = 0; this.chartHeight = 0; /** * Register the Color Mixer extension. * * @returns {Boolean} True if the extension can be registered properly, or * false if not. */ this.extensionRegister = function (ev) { if (!gui.elems || !gui.elems.colormixer_canvas || !gui.floatingPanels || !gui.floatingPanels.colormixer || !gui.tabPanels || !gui.tabPanels.colormixer_inputs || !gui.tabPanels.colormixer_selector || !_self.init_lab()) { return false; } _self.panel = gui.floatingPanels.colormixer; _self.panelSelector = gui.tabPanels.colormixer_selector; _self.panelInputs = gui.tabPanels.colormixer_inputs; // Initialize the color mixer Canvas element. _self.context2d = gui.elems.colormixer_canvas.getContext('2d'); if (!_self.context2d) { return false; } // Setup the color mixer inputs. var elem, label, labelElem, inputValues = config.inputValues, form = _self.panelInputs.container; if (!form) { return false; } for (var i in _self.inputs) { elem = form.elements.namedItem('ckey_' + i) || gui.inputs['ckey_' + i]; if (!elem) { return false; } if (i === 'hex' || i === 'alpha') { label = lang.inputs[i]; } else { label = lang.inputs[_self.ckey_grouping[i] + '_' + i]; } labelElem = elem.parentNode; labelElem.replaceChild(doc.createTextNode(label), labelElem.firstChild); elem.addEventListener('input', _self.ev_input_change, false); elem.addEventListener('change', _self.ev_input_change, false); if (i !== 'hex') { elem.setAttribute('step', inputValues[i][2]); elem.setAttribute('max', MathRound(inputValues[i][1])); elem.setAttribute('min', MathRound(inputValues[i][0])); _self.abs_max[i] = inputValues[i][1] - inputValues[i][0]; } // Store the color key, which is used by the event handler. elem._ckey = i; _self.inputs[i] = elem; } // Setup the ckey inputs of type=radio. var ckey = form.ckey; if (!ckey) { return false; } for (var i = 0, n = ckey.length; i < n; i++) { elem = ckey[i]; if (_self.ckey_grouping[elem.value] === 'lab' && !_self.context2d.putImageData) { elem.disabled = true; continue; } elem.addEventListener('change', _self.ev_change_ckey_active, false); if (elem.value === _self.ckey_active) { elem.checked = true; _self.update_ckey_active(_self.ckey_active, true); } } // Prepare the color preview elements. _self.elems.colorActive = gui.elems.colormixer_colorActive.firstChild; _self.elems.colorOld = gui.elems.colormixer_colorOld.firstChild; _self.elems.colorOld.addEventListener('click', _self.ev_click_color, false); // Make sure the buttons work properly. var anchor, btn, buttons = ['accept', 'cancel', 'saveColor', 'pickColor']; for (var i = 0, n = buttons.length; i < n; i++) { btn = gui.elems['colormixer_btn_' + buttons[i]]; if (!btn) { continue; } anchor = doc.createElement('a'); anchor.href = '#'; anchor.appendChild(doc.createTextNode(lang.buttons[buttons[i]])); anchor.addEventListener('click', _self['ev_click_' + buttons[i]], false); btn.replaceChild(anchor, btn.firstChild); } // Prepare the canvas "controls" (the chart "dot" and the slider). var id, elems = ['controls', 'chartDot', 'slider']; for (var i = 0, n = elems.length; i < n; i++) { id = elems[i]; elem = gui.elems['colormixer_' + id]; if (!elem) { return false; } elem.addEventListener('mousedown', _self.ev_canvas, false); elem.addEventListener('mousemove', _self.ev_canvas, false); elem.addEventListener('mouseup', _self.ev_canvas, false); _self.elems[id] = elem; } // The color palette <select>. _self.elems.cpaletteInput = gui.inputs.colormixer_cpaletteInput; _self.elems.cpaletteInput.addEventListener('change', _self.ev_change_cpalette, false); // Add the list of color palettes into the <select>. var palette; for (var i in config.colorPalettes) { palette = config.colorPalettes[i]; elem = doc.createElement('option'); elem.value = i; if (i === config.paletteDefault) { elem.selected = true; } elem.appendChild( doc.createTextNode(lang.colorPalettes[i]) ); _self.elems.cpaletteInput.appendChild(elem); } // This is the ordered list where we add each color (list item). _self.elems.cpaletteOutput = gui.elems.colormixer_cpaletteOutput; _self.elems.cpaletteOutput.addEventListener('click', _self.ev_click_color, false); _self.cpalette_load(config.paletteDefault); // Make sure the Canvas element scale is in sync with the application. app.events.add('canvasSizeChange', _self.update_dimensions); _self.panelSelector.events.add('guiTabActivate', _self.ev_tabActivate); // Make sure the Color Mixer is properly closed when the floating panel is // closed. _self.panel.events.add('guiFloatingPanelStateChange', _self.ev_panel_stateChange); return true; }; /** * This function calculates lots of values used by the other CIE Lab-related * functions. * * @private * @returns {Boolean} True if the initialization was successful, or false if * not. */ this.init_lab = function () { var cfg = config.lab; if (!cfg) { return false; } // Chromaticity coordinates for the RGB primaries. var x0_r = cfg.x_r, y0_r = cfg.y_r, x0_g = cfg.x_g, y0_g = cfg.y_g, x0_b = cfg.x_b, y0_b = cfg.y_b, // The reference white point (xyY to XYZ). w_x = cfg.ref_x / cfg.ref_y, w_y = 1, w_z = (1 - cfg.ref_x - cfg.ref_y) / cfg.ref_y; cfg.w_x = w_x; cfg.w_y = w_y; cfg.w_z = w_z; // Again, xyY to XYZ for each RGB primary. Y=1. var x_r = x0_r / y0_r, y_r = 1, z_r = (1 - x0_r - y0_r) / y0_r, x_g = x0_g / y0_g, y_g = 1, z_g = (1 - x0_g - y0_g) / y0_g, x_b = x0_b / y0_b, y_b = 1, z_b = (1 - x0_b - y0_b) / y0_b, m = [x_r, y_r, z_r, x_g, y_g, z_g, x_b, y_b, z_b], m_i = _self.calc_m3inv(m), s = _self.calc_m1x3([w_x, w_y, w_z], m_i); // The 3x3 matrix used by rgb2xyz(). m = [s[0] * m[0], s[0] * m[1], s[0] * m[2], s[1] * m[3], s[1] * m[4], s[1] * m[5], s[2] * m[6], s[2] * m[7], s[2] * m[8]]; // The matrix inverse, used by xyz2rgb(); cfg.m_i = _self.calc_m3inv(m); cfg.m = m; // Now determine the min/max values for a and b. var xyz = _self.rgb2xyz([0, 1, 0]), // green gives the minimum value for a lab = _self.xyz2lab(xyz), values = config.inputValues; values.cie_a[0] = lab[1]; xyz = _self.rgb2xyz([1, 0, 1]); // magenta gives the maximum value for a lab = _self.xyz2lab(xyz); values.cie_a[1] = lab[1]; xyz = _self.rgb2xyz([0, 0, 1]); // blue gives the minimum value for b lab = _self.xyz2lab(xyz); values.cie_b[0] = lab[2]; xyz = _self.rgb2xyz([1, 1, 0]); // yellow gives the maximum value for b lab = _self.xyz2lab(xyz); values.cie_b[1] = lab[2]; return true; }; /** * The <code>guiTabActivate</code> event handler for the tab panel which holds * the color mixer and the color palettes. When switching back to the color * mixer, this method updates the Canvas. * * @private * @param {pwlib.appEvent.guiTabActivate} ev The application event object. */ this.ev_tabActivate = function (ev) { if (ev.tabId === 'mixer' && _self.update_canvas_needed) { _self.update_canvas(null, true); } }; /** * The <code>click</code> event handler for the Accept button. This method * dispatches the {@link pwlib.appEvent.configChange} application event for * the configuration property associated to the target input, and hides the * Color Mixer floating panel. * * @private * @param {Event} ev The DOM Event object. */ this.ev_click_accept = function (ev) { ev.preventDefault(); var configProperty = _self.targetInput.configProperty, configGroup = _self.targetInput.configGroup, configGroupRef = _self.targetInput.configGroupRef, prevVal = configGroupRef[configProperty], newVal = 'rgba(' + MathRound(_self.color.red * 255) + ',' + MathRound(_self.color.green * 255) + ',' + MathRound(_self.color.blue * 255) + ',' + _self.color.alpha + ')'; _self.hide(); if (prevVal !== newVal) { configGroupRef[configProperty] = newVal; app.events.dispatch(new pwlib.appEvent.configChange(newVal, prevVal, configProperty, configGroup, configGroupRef)); } }; /** * The <code>click</code> event handler for the Cancel button. This method * hides the Color Mixer floating panel. * * @private * @param {Event} ev The DOM Event object. */ this.ev_click_cancel = function (ev) { ev.preventDefault(); _self.hide(); }; /** * The <code>click</code> event handler for the "Save color" button. This * method adds the current color into the "_saved" color palette. * * @private * @param {Event} ev The DOM Event object. */ // TODO: provide a way to save the color palette permanently. This should use // some application event. this.ev_click_saveColor = function (ev) { ev.preventDefault(); var color = [_self.color.red, _self.color.green, _self.color.blue], saved = config.colorPalettes._saved; saved.colors.push(color); _self.elems.cpaletteInput.value = '_saved'; _self.cpalette_load('_saved'); _self.panelSelector.tabActivate('cpalettes'); return true; }; /** * The <code>click</code> event handler for the "Pick color" button. This * method activates the color picker tool. * * @private * @param {Event} ev The DOM Event object. */ this.ev_click_pickColor = function (ev) { ev.preventDefault(); app.toolActivate('cpicker', ev); }; /** * The <code>change</code> event handler for the color palette input element. * This loads the color palette the user selected. * * @private * @param {Event} ev The DOM Event object. */ this.ev_change_cpalette = function (ev) { _self.cpalette_load(this.value); }; /** * Load a color palette. Loading is performed asynchronously. * * @param {String} id The color palette ID. * * @returns {Boolean} True if the load was successful, or false if not. */ this.cpalette_load = function (id) { if (!id || !(id in config.colorPalettes)) { return false; } var palette = config.colorPalettes[id]; if (palette.file) { pwlib.xhrLoad(PaintWeb.baseFolder + palette.file, this.cpalette_loaded); return true; } else if (palette.colors) { return this.cpalette_show(palette.colors); } else { return false; } }; /** * The <code>onreadystatechange</code> event handler for the color palette * XMLHttpRequest object. * * @private * @param {XMLHttpRequest} xhr The XMLHttpRequest object. */ this.cpalette_loaded = function (xhr) { if (!xhr || xhr.readyState !== 4) { return; } if ((xhr.status !== 304 && xhr.status !== 200) || !xhr.responseText) { alert(lang.failedColorPaletteLoad); return; } var colors = JSON.parse(xhr.responseText); xhr = null; _self.cpalette_show(colors); }; /** * Show a color palette. This method adds all the colors in the DOM as * individual anchor elements which users can click on. * * @private * * @param {Array} colors The array which holds each color in the palette. * * @returns {Boolean} True if the operation was successful, or false if not. */ this.cpalette_show = function (colors) { if (!colors || !(colors instanceof Array)) { return false; } var color, anchor, rgbValue, frag = doc.createDocumentFragment(), dest = this.elems.cpaletteOutput; dest.style.display = 'none'; while (dest.hasChildNodes()) { dest.removeChild(dest.firstChild); } for (var i = 0, n = colors.length; i < n; i++) { color = colors[i]; // Do not allow values higher than 1. color[0] = MathMin(1, color[0]); color[1] = MathMin(1, color[1]); color[2] = MathMin(1, color[2]); rgbValue = 'rgb(' + MathRound(color[0] * 255) + ',' + MathRound(color[1] * 255) + ',' + MathRound(color[2] * 255) + ')'; anchor = doc.createElement('a'); anchor.href = '#'; anchor._color = color; anchor.style.backgroundColor = rgbValue; anchor.appendChild(doc.createTextNode(rgbValue)); frag.appendChild(anchor); } dest.appendChild(frag); dest.style.display = 'block'; colors = frag = null; return true; }; /** * The <code>click</code> event handler for colors in the color palette list. * This event handler is also used for the "old color" element. This method * updates the color mixer to use the color the user picked. * * @private * @param {Event} ev The DOM Event object. */ this.ev_click_color = function (ev) { var color = ev.target._color; if (!color) { return; } ev.preventDefault(); _self.color.red = color[0]; _self.color.green = color[1]; _self.color.blue = color[2]; if (typeof(color[3]) !== 'undefined') { _self.color.alpha = color[3]; } _self.update_color('rgb'); }; /** * Recalculate the dimensions and coordinates for the slider and for the color * space visualisation within the Canvas element. * * <p>This method is an event handler for the {@link * pwlib.appEvent.canvasSizeChange} application event. * * @private */ this.update_dimensions = function () { if (resScale === app.resolution.scale) { return; } resScale = app.resolution.scale; var canvas = _self.context2d.canvas, width = canvas.width, height = canvas.height, sWidth = width / resScale, sHeight = height / resScale, style; _self.sliderWidth = MathRound(width * config.sliderWidth); _self.sliderHeight = height - 1; _self.sliderSpacing = MathRound(width * config.sliderSpacing); _self.sliderX = width - _self.sliderWidth - 2; _self.chartWidth = _self.sliderX - _self.sliderSpacing; _self.chartHeight = height; style = _self.elems.controls.style; style.width = sWidth + 'px'; style.height = sHeight + 'px'; style = _self.elems.slider.style; style.width = (_self.sliderWidth / resScale) + 'px'; style.left = (_self.sliderX / resScale) + 'px'; style = canvas.style; style.width = sWidth + 'px'; style.height = sHeight + 'px'; if (_self.panel.state !== _self.panel.STATE_HIDDEN) { _self.update_canvas(); } }; /** * Calculate the product of two matrices. * * <p>Matrices are one-dimensional arrays of the form <code>[a0, a1, a2, ..., * b0, b1, b2, ...]</code> where each element from the matrix is given in * order, from the left to the right, row by row from the top to the bottom. * * @param {Array} a The first matrix must be one row and three columns. * @param {Array} b The second matrix must be three rows and three columns. * * @returns {Array} The matrix product, one row and three columns. */ // Note: for obvious reasons, this method is not a full-fledged matrix product // calculator. It's as simple as possible - fitting only the very specific // needs of the color mixer. this.calc_m1x3 = function (a, b) { if (!(a instanceof Array) || !(b instanceof Array)) { return false; } else { return [ a[0] * b[0] + a[1] * b[3] + a[2] * b[6], // x a[0] * b[1] + a[1] * b[4] + a[2] * b[7], // y a[0] * b[2] + a[1] * b[5] + a[2] * b[8] // z ]; } }; /** * Calculate the matrix inverse. * * <p>Matrices are one-dimensional arrays of the form <code>[a0, a1, a2, ..., * b0, b1, b2, ...]</code> where each element from the matrix is given in * order, from the left to the right, row by row from the top to the bottom. * * @private * * @param {Array} m The square matrix which must have three rows and three * columns. * * @returns {Array|false} The computed matrix inverse, or false if the matrix * determinant was 0 - the given matrix is not invertible. */ // Note: for obvious reasons, this method is not a full-fledged matrix inverse // calculator. It's as simple as possible - fitting only the very specific // needs of the color mixer. this.calc_m3inv = function (m) { if (!(m instanceof Array)) { return false; } var d = (m[0]*m[4]*m[8] + m[1]*m[5]*m[6] + m[2]*m[3]*m[7]) - (m[2]*m[4]*m[6] + m[5]*m[7]*m[0] + m[8]*m[1]*m[3]); // Matrix determinant is 0: the matrix is not invertible. if (d === 0) { return false; } var i = [ m[4]*m[8] - m[5]*m[7], -m[3]*m[8] + m[5]*m[6], m[3]*m[7] - m[4]*m[6], -m[1]*m[8] + m[2]*m[7], m[0]*m[8] - m[2]*m[6], -m[0]*m[7] + m[1]*m[6], m[1]*m[5] - m[2]*m[4], -m[0]*m[5] + m[2]*m[3], m[0]*m[4] - m[1]*m[3] ]; i = [1/d * i[0], 1/d * i[3], 1/d * i[6], 1/d * i[1], 1/d * i[4], 1/d * i[7], 1/d * i[2], 1/d * i[5], 1/d * i[8]]; return i; }; /** * The <code>change</code> event handler for the Color Mixer inputs of * type=radio. This method allows users to change the active color key - used * for the color space visualisation. * @private */ this.ev_change_ckey_active = function () { if (this.value && this.value !== _self.ckey_active) { _self.update_ckey_active(this.value); } }; /** * Update the active color key. This method updates the Canvas accordingly. * * @private * * @param {String} ckey The color key you want to be active. * @param {Boolean} [only_vars] Tells if you want only the variables to be * updated - no Canvas updates. This is true only during the Color Mixer * initialization. * * @return {Boolean} True if the operation was successful, or false if not. */ this.update_ckey_active = function (ckey, only_vars) { if (!_self.inputs[ckey]) { return false; } _self.ckey_active = ckey; var adjoint = [], group = _self.ckey_grouping[ckey]; // Determine the adjoint color keys. For example, if red is active, then adjoint = ['green', 'blue']. for (var i in _self.ckey_grouping) { if (_self.ckey_grouping[i] === group && i !== ckey) { adjoint.push(i); } } _self.ckey_active_group = group; _self.ckey_adjoint = adjoint; if (!only_vars) { if (_self.panelSelector.tabId !== 'mixer') { _self.update_canvas_needed = true; _self.panelSelector.tabActivate('mixer'); } else { _self.update_canvas(); } if (_self.panelInputs.tabId !== group) { _self.panelInputs.tabActivate(group); } } return true; }; /** * Show the Color Mixer. * * @param {Object} target The target input object. * * @param {Object} color The color you want to set before the Color Mixer is * shown. The object must have four properties: <var>red</var>, * <var>green</var>, <var>blue</var> and <var>alpha</var>. All the values must * be between 0 and 1. This color becomes the "active color" and the "old * color". * * @see this.targetInput for more information about the <var>target</var> * object. */ this.show = function (target, color) { var styleActive = _self.elems.colorActive.style, colorOld = _self.elems.colorOld, styleOld = colorOld.style; if (target) { if (_self.targetInput) { _self.targetInput.hide(); } _self.targetInput = target; _self.targetInput.show(); } if (color) { _self.color.red = color.red; _self.color.green = color.green; _self.color.blue = color.blue; _self.color.alpha = color.alpha; _self.update_color('rgb'); styleOld.backgroundColor = styleActive.backgroundColor; styleOld.opacity = styleActive.opacity; colorOld._color = [color.red, color.green, color.blue, color.alpha]; } _self.panel.show(); }; /** * Hide the Color Mixer floating panel. This method invokes the * <code>hide()</code> method provided by the target input. */ this.hide = function () { _self.panel.hide(); _self.ev_canvas_mode = false; }; /** * The <code>guiFloatingPanelStateChange</code> event handler for the Color * Mixer panel. This method ensures the Color Mixer is properly closed. * * @param {pwlib.appEvent.guiFloatingPanelStateChange} ev The application * event object. */ this.ev_panel_stateChange = function (ev) { if (ev.state === ev.STATE_HIDDEN) { if (_self.targetInput) { _self.targetInput.hide(); _self.targetInput = null; } _self.ev_canvas_mode = false; } }; /** * The <code>input</code> and <code>change</code> event handler for all the * Color Mixer inputs. * @private */ this.ev_input_change = function () { if (!this._ckey) { return; } // Validate and restrict the possible values. // If the input is unchanged, or if the new value is invalid, the function // stops. // The hexadecimal input is checked with a simple regular expression. if ((this._ckey === 'hex' && !/^\#[a-f0-9]{6}$/i.test(this.value))) { return; } if (this.getAttribute('type') === 'number') { var val = parseInt(this.value), min = this.getAttribute('min'), max = this.getAttribute('max'); if (isNaN(val)) { val = min; } if (val < min) { val = min; } else if (val > max) { val = max; } if (val != this.value) { this.value = val; } } // Update the internal color value. if (this._ckey === 'hex') { _self.color[this._ckey] = this.value; } else if (_self.ckey_grouping[this._ckey] === 'lab') { _self.color[this._ckey] = parseInt(this.value); } else { _self.color[this._ckey] = parseInt(this.value) / config.inputValues[this._ckey][1]; } _self.update_color(this._ckey); }; /** * Update the current color. Once a color value is updated, this method is * called to keep the rest of the color mixer in sync: for example, when a RGB * value is updated, it needs to be converted to HSV, CMYK and all of the * other formats. Additionally, this method updates the color preview, the * controls on the Canvas and the input values. * * <p>You need to call this function whenever you update the color manually. * * @param {String} ckey The color key that was updated. */ this.update_color = function (ckey) { var group = _self.ckey_grouping[ckey] || ckey; switch (group) { case 'rgb': _self.rgb2hsv(); _self.rgb2hex(); _self.rgb2lab(); _self.rgb2cmyk(); break; case 'hsv': _self.hsv2rgb(); _self.rgb2hex(); _self.rgb2lab(); _self.rgb2cmyk(); break; case 'hex': _self.hex2rgb(); _self.rgb2hsv(); _self.rgb2lab(); _self.rgb2cmyk(); break; case 'lab': _self.lab2rgb(); _self.rgb2hsv(); _self.rgb2hex(); _self.rgb2cmyk(); break; case 'cmyk': _self.cmyk2rgb(); _self.rgb2lab(); _self.rgb2hsv(); _self.rgb2hex(); } _self.update_preview(); _self.update_inputs(); if (ckey !== 'alpha') { _self.update_canvas(ckey); } }; /** * Update the color preview. * @private */ this.update_preview = function () { var red = MathRound(_self.color.red * 255), green = MathRound(_self.color.green * 255), blue = MathRound(_self.color.blue * 255), style = _self.elems.colorActive.style; style.backgroundColor = 'rgb(' + red + ',' + green + ',' + blue + ')'; style.opacity = _self.color.alpha; }; /** * Update the color inputs. This method takes the internal color values and * shows them in the DOM input elements. * @private */ this.update_inputs = function () { var input; for (var i in _self.inputs) { input = _self.inputs[i]; input._old_value = input.value; if (input._ckey === 'hex') { input.value = _self.color[i]; } else if (_self.ckey_grouping[input._ckey] === 'lab') { input.value = MathRound(_self.color[i]); } else { input.value = MathRound(_self.color[i] * config.inputValues[i][1]); } } }; /** * Convert RGB to CMYK. This uses the current color RGB values and updates the * CMYK values accordingly. * @private */ // Quote from Wikipedia: // "Since RGB and CMYK spaces are both device-dependent spaces, there is no // simple or general conversion formula that converts between them. // Conversions are generally done through color management systems, using // color profiles that describe the spaces being converted. Nevertheless, the // conversions cannot be exact, since these spaces have very different // gamuts." // Translation: this is just a simple RGB to CMYK conversion function. this.rgb2cmyk = function () { var color = _self.color, cyan, magenta, yellow, black, red = color.red, green = color.green, blue = color.blue; cyan = 1 - red; magenta = 1 - green; yellow = 1 - blue; black = MathMin(cyan, magenta, yellow, 1); if (black === 1) { cyan = magenta = yellow = 0; } else { var w = 1 - black; cyan = (cyan - black) / w; magenta = (magenta - black) / w; yellow = (yellow - black) / w; } color.cyan = cyan; color.magenta = magenta; color.yellow = yellow; color.black = black; }; /** * Convert CMYK to RGB (internally). * @private */ this.cmyk2rgb = function () { var color = _self.color, w = 1 - color.black; color.red = 1 - color.cyan * w - color.black; color.green = 1 - color.magenta * w - color.black; color.blue = 1 - color.yellow * w - color.black; }; /** * Convert RGB to HSV (internally). * @private */ this.rgb2hsv = function () { var hue, sat, val, // HSV red = _self.color.red, green = _self.color.green, blue = _self.color.blue, min = MathMin(red, green, blue), max = MathMax(red, green, blue), delta = max - min, val = max; // This is gray (red==green==blue) if (delta === 0) { hue = sat = 0; } else { sat = delta / max; if (max === red) { hue = (green - blue) / delta; } else if (max === green) { hue = (blue - red) / delta + 2; } else if (max === blue) { hue = (red - green) / delta + 4; } hue /= 6; if (hue < 0) { hue += 1; } } _self.color.hue = hue; _self.color.sat = sat; _self.color.val = val; }; /** * Convert HSV to RGB. * * @private * * @param {Boolean} [no_update] Tells the function to not update the internal * RGB color values. * @param {Array} [hsv] The array holding the HSV values you want to convert * to RGB. This array must have three elements ordered as: <var>hue</var>, * <var>saturation</var> and <var>value</var> - all between 0 and 1. If you do * not provide the array, then the internal HSV color values are used. * * @returns {Array} The RGB values converted from HSV. The array has three * elements ordered as: <var>red</var>, <var>green</var> and <var>blue</var> * - all with values between 0 and 1. */ this.hsv2rgb = function (no_update, hsv) { var color = _self.color, red, green, blue, hue, sat, val; // Use custom HSV values or the current color. if (hsv) { hue = hsv[0]; sat = hsv[1]; val = hsv[2]; } else { hue = color.hue, sat = color.sat, val = color.val; } // achromatic (grey) if (sat === 0) { red = green = blue = val; } else { var h = hue * 6; var i = MathFloor(h); var t1 = val * ( 1 - sat ), t2 = val * ( 1 - sat * ( h - i ) ), t3 = val * ( 1 - sat * ( 1 - (h - i) ) ); if (i === 0 || i === 6) { // 0° Red red = val; green = t3; blue = t1; } else if (i === 1) { // 60° Yellow red = t2; green = val; blue = t1; } else if (i === 2) { // 120° Green red = t1; green = val; blue = t3; } else if (i === 3) { // 180° Cyan red = t1; green = t2; blue = val; } else if (i === 4) { // 240° Blue red = t3; green = t1; blue = val; } else if (i === 5) { // 300° Magenta red = val; green = t1; blue = t2; } } if (!no_update) { color.red = red; color.green = green; color.blue = blue; } return [red, green, blue]; }; /** * Convert RGB to hexadecimal representation (internally). * @private */ this.rgb2hex = function () { var hex = '#', rgb = ['red', 'green', 'blue'], i, val, color = _self.color; for (i = 0; i < 3; i++) { val = MathRound(color[rgb[i]] * 255).toString(16); if (val.length === 1) { val = '0' + val; } hex += val; } color.hex = hex; }; /** * Convert the hexadecimal representation of color to RGB values (internally). * @private */ this.hex2rgb = function () { var rgb = ['red', 'green', 'blue'], i, val, color = _self.color, hex = color.hex; hex = hex.substr(1); if (hex.length !== 6) { return; } for (i = 0; i < 3; i++) { val = hex.substr(i*2, 2); color[rgb[i]] = parseInt(val, 16)/255; } }; /** * Convert RGB to CIE Lab (internally). * @private */ this.rgb2lab = function () { var color = _self.color, lab = _self.xyz2lab(_self.rgb2xyz([color.red, color.green, color.blue])); color.cie_l = lab[0]; color.cie_a = lab[1]; color.cie_b = lab[2]; }; /** * Convert CIE Lab values to RGB values (internally). * @private */ this.lab2rgb = function () { var color = _self.color, rgb = _self.xyz2rgb(_self.lab2xyz(color.cie_l, color.cie_a, color.cie_b)); color.red = rgb[0]; color.green = rgb[1]; color.blue = rgb[2]; }; /** * Convert XYZ color values into CIE Lab values. * * @private * * @param {Array} xyz The array holding the XYZ color values in order: * <var>X</var>, <var>Y</var> and <var>Z</var>. * * @returns {Array} An array holding the CIE Lab values in order: * <var>L</var>, <var>a</var> and <var>b</var>. */ this.xyz2lab = function (xyz) { var cfg = config.lab, // 216/24389 or (6/29)^3 (both = 0.008856...) e = 216/24389, // 903.296296... k = 24389/27; xyz[0] /= cfg.w_x; xyz[1] /= cfg.w_y; xyz[2] /= cfg.w_z; if (xyz[0] > e) { xyz[0] = MathPow(xyz[0], 1/3); } else { xyz[0] = (k*xyz[0] + 16)/116; } if (xyz[1] > e) { xyz[1] = MathPow(xyz[1], 1/3); } else { xyz[1] = (k*xyz[1] + 16)/116; } if (xyz[2] > e) { xyz[2] = MathPow(xyz[2], 1/3); } else { xyz[2] = (k*xyz[2] + 16)/116; } var cie_l = 116 * xyz[1] - 16, cie_a = 500 * (xyz[0] - xyz[1]), cie_b = 200 * (xyz[1] - xyz[2]); return [cie_l, cie_a, cie_b]; }; /** * Convert CIE Lab values to XYZ color values. * * @private * * @param {Number} cie_l The color lightness value. * @param {Number} cie_a The a* color opponent. * @param {Number} cie_b The b* color opponent. * * @returns {Array} An array holding the XYZ color values in order: * <var>X</var>, <var>Y</var> and <var>Z</var>. */ this.lab2xyz = function (cie_l, cie_a, cie_b) { var y = (cie_l + 16) / 116, x = y + cie_a / 500, z = y - cie_b / 200, // 0.206896551... e = 6/29, // 7.787037... k = 1/3 * MathPow(29/6, 2), // 0.137931... t = 16/116, cfg = config.lab; if (x > e) { x = MathPow(x, 3); } else { x = (x - t) / k; } if (y > e) { y = MathPow(y, 3); } else { y = (y - t) / k; } if (z > e) { z = MathPow(z, 3); } else { z = (z - t) / k; } x *= cfg.w_x; y *= cfg.w_y; z *= cfg.w_z; return [x, y, z]; }; /** * Convert XYZ color values to RGB. * * @private * * @param {Array} xyz The array holding the XYZ color values in order: * <var>X</var>, <var>Y</var> and <var>Z</var> * * @returns {Array} An array holding the RGB values in order: <var>red</var>, * <var>green</var> and <var>blue</var>. */ this.xyz2rgb = function (xyz) { var rgb = _self.calc_m1x3(xyz, config.lab.m_i); if (rgb[0] > 0.0031308) { rgb[0] = 1.055 * MathPow(rgb[0], 1 / 2.4) - 0.055; } else { rgb[0] *= 12.9232; } if (rgb[1] > 0.0031308) { rgb[1] = 1.055 * MathPow(rgb[1], 1 / 2.4) - 0.055; } else { rgb[1] *= 12.9232; } if (rgb[2] > 0.0031308) { rgb[2] = 1.055 * MathPow(rgb[2], 1 / 2.4) - 0.055; } else { rgb[2] *= 12.9232; } if (rgb[0] < 0) { rgb[0] = 0; } else if (rgb[0] > 1) { rgb[0] = 1; } if (rgb[1] < 0) { rgb[1] = 0; } else if (rgb[1] > 1) { rgb[1] = 1; } if (rgb[2] < 0) { rgb[2] = 0; } else if (rgb[2] > 1) { rgb[2] = 1; } return rgb; }; /** * Convert RGB values to XYZ color values. * * @private * * @param {Array} rgb The array holding the RGB values in order: * <var>red</var>, <var>green</var> and <var>blue</var>. * * @returns {Array} An array holding the XYZ color values in order: * <var>X</var>, <var>Y</var> and <var>Z</var>. */ this.rgb2xyz = function (rgb) { if (rgb[0] > 0.04045) { rgb[0] = MathPow(( rgb[0] + 0.055 ) / 1.055, 2.4); } else { rgb[0] /= 12.9232; } if (rgb[1] > 0.04045) { rgb[1] = MathPow(( rgb[1] + 0.055 ) / 1.055, 2.4); } else { rgb[1] /= 12.9232; } if (rgb[2] > 0.04045) { rgb[2] = MathPow(( rgb[2] + 0.055 ) / 1.055, 2.4); } else { rgb[2] /= 12.9232; } return _self.calc_m1x3(rgb, config.lab.m); }; /** * Update the color space visualisation. This method updates the color chart * and/or the color slider, and the associated controls, each as needed when * a color key is updated. * * @private * * @param {String} updated_ckey The color key that was updated. * @param {Boolean} [force=false] Tells the function to force an update. The * Canvas is not updated when the color mixer panel is not visible. * * @returns {Boolean} If the operation was successful, or false if not. */ this.update_canvas = function (updated_ckey, force) { if (_self.panelSelector.tabId !== 'mixer' && !force) { _self.update_canvas_needed = true; return true; } _self.update_canvas_needed = false; var slider = _self.elems.slider.style, chart = _self.elems.chartDot.style, color = _self.color, ckey = _self.ckey_active, group = _self.ckey_active_group, adjoint = _self.ckey_adjoint, width = _self.chartWidth / resScale, height = _self.chartHeight / resScale, mx, my, sy; // Update the slider which shows the position of the active ckey. if (updated_ckey !== adjoint[0] && updated_ckey !== adjoint[1] && _self.ev_canvas_mode !== 'chart') { if (group === 'lab') { sy = (color[ckey] - config.inputValues[ckey][0]) / _self.abs_max[ckey]; } else { sy = color[ckey]; } if (ckey !== 'hue' && group !== 'lab') { sy = 1 - sy; } slider.top = MathRound(sy * height) + 'px'; } // Update the chart dot. if (updated_ckey !== ckey) { if (group === 'lab') { mx = (color[adjoint[0]] - config.inputValues[adjoint[0]][0]) / _self.abs_max[adjoint[0]]; my = (color[adjoint[1]] - config.inputValues[adjoint[1]][0]) / _self.abs_max[adjoint[1]]; } else { mx = color[adjoint[0]]; my = 1 - color[adjoint[1]]; } chart.top = MathRound(my * height) + 'px'; chart.left = MathRound(mx * width) + 'px'; } if (!_self.draw_chart(updated_ckey) || !_self.draw_slider(updated_ckey)) { return false; } else { return true; } }; /** * The mouse events handler for the Canvas controls. This method determines * the region the user is using, and it also updates the color values for the * active color key. The Canvas and all the inputs in the color mixer are * updated as needed. * * @private * @param {Event} ev The DOM Event object. */ this.ev_canvas = function (ev) { ev.preventDefault(); // Initialize color picking only on mousedown. if (ev.type === 'mousedown' && !_self.ev_canvas_mode) { _self.ev_canvas_mode = true; doc.addEventListener('mouseup', _self.ev_canvas, false); } if (!_self.ev_canvas_mode) { return false; } // The mouseup event stops the effect of any further mousemove events. if (ev.type === 'mouseup') { _self.ev_canvas_mode = false; doc.removeEventListener('mouseup', _self.ev_canvas, false); } var elems = _self.elems; // If the user is on top of the 'controls' element, determine the mouse coordinates and the 'mode' for this function: the user is either working with the slider, or he/she is working with the color chart itself. if (ev.target === elems.controls) { var mx, my, width = _self.context2d.canvas.width, height = _self.context2d.canvas.height; // Get the mouse position, relative to the event target. if (ev.layerX || ev.layerX === 0) { // Firefox mx = ev.layerX * resScale; my = ev.layerY * resScale; } else if (ev.offsetX || ev.offsetX === 0) { // Opera mx = ev.offsetX * resScale; my = ev.offsetY * resScale; } if (mx >= 0 && mx <= _self.chartWidth) { mode = 'chart'; } else if (mx >= _self.sliderX && mx <= width) { mode = 'slider'; } } else { // The user might have clicked on the chart dot, or on the slider graphic // itself. // If yes, then determine the mode based on this. if (ev.target === elems.chartDot) { mode = 'chart'; } else if (ev.target === elems.slider) { mode = 'slider'; } } // Update the ev_canvas_mode value to include the mode name, if it's simply // the true boolean. // This ensures that the continuous mouse movements do not go from one mode // to another when the user moves out from the slider to the chart (and // vice-versa). if (mode && _self.ev_canvas_mode === true) { _self.ev_canvas_mode = mode; } // Do not continue if the mode wasn't determined (the mouse is not on the // slider, nor on the chart). // Also don't continue if the mouse is not in the same place (different // mode). if (!mode || _self.ev_canvas_mode !== mode || ev.target !== elems.controls) { return false; } var color = _self.color, val_x = mx / _self.chartWidth, val_y = my / height; if (mode === 'slider') { if (_self.ckey_active === 'hue') { color[_self.ckey_active] = val_y; } else if (_self.ckey_active_group === 'lab') { color[_self.ckey_active] = _self.abs_max[_self.ckey_active] * val_y + config.inputValues[_self.ckey_active][0]; } else { color[_self.ckey_active] = 1 - val_y; } return _self.update_color(_self.ckey_active); } else if (mode === 'chart') { if (val_x > 1) { return false; } if (_self.ckey_active_group === 'lab') { val_x = _self.abs_max[_self.ckey_adjoint[0]] * val_x + config.inputValues[_self.ckey_adjoint[0]][0]; val_y = _self.abs_max[_self.ckey_adjoint[1]] * val_y + config.inputValues[_self.ckey_adjoint[1]][0]; } else { val_y = 1 - val_y; } color[_self.ckey_adjoint[0]] = val_x; color[_self.ckey_adjoint[1]] = val_y; return _self.update_color(_self.ckey_active_group); } return false; }; /** * Draw the color space visualisation. * * @private * * @param {String} updated_ckey The color key that was updated. This is used * to determine if the Canvas needs to be updated or not. */ this.draw_chart = function (updated_ckey) { var context = _self.context2d, gradient, color, opacity, i; if (updated_ckey === _self.ckey_adjoint[0] || updated_ckey === _self.ckey_adjoint[1] || (_self.ev_canvas_mode === 'chart' && updated_ckey === _self.ckey_active_group)) { return true; } var w = _self.chartWidth, h = _self.chartHeight; context.clearRect(0, 0, w, h); if (_self.ckey_active === 'sat') { // In saturation mode the user has the slider which allows him/her to // change the saturation (hSv) of the current color. // The chart shows the hue spectrum on the X axis, while the Y axis gives // the Value (hsV). if (_self.color.sat > 0) { // Draw the hue spectrum gradient on the X axis. gradient = context.createLinearGradient(0, 0, w, 0); for (i = 0; i <= 6; i++) { color = 'rgb(' + hueSpectrum[i][0] + ', ' + hueSpectrum[i][1] + ', ' + hueSpectrum[i][2] + ')'; gradient.addColorStop(i * 1/6, color); } context.fillStyle = gradient; context.fillRect(0, 0, w, h); // Draw the gradient which darkens the hue spectrum on the Y axis. gradient = context.createLinearGradient(0, 0, 0, h); gradient.addColorStop(0, 'rgba(0, 0, 0, 0)'); gradient.addColorStop(1, 'rgba(0, 0, 0, 1)'); context.fillStyle = gradient; context.fillRect(0, 0, w, h); } if (_self.color.sat < 1) { // Draw the white to black gradient. This is used for creating the // saturation effect. Lowering the saturation value makes the gradient // more visible, hence the hue colors desaturate. opacity = 1 - _self.color.sat; gradient = context.createLinearGradient(0, 0, 0, h); gradient.addColorStop(0, 'rgba(255, 255, 255, ' + opacity + ')'); gradient.addColorStop(1, 'rgba( 0, 0, 0, ' + opacity + ')'); context.fillStyle = gradient; context.fillRect(0, 0, w, h); } } else if (_self.ckey_active === 'val') { // In value mode the user has the slider which allows him/her to change the value (hsV) of the current color. // The chart shows the hue spectrum on the X axis, while the Y axis gives the saturation (hSv). if (_self.color.val > 0) { // Draw the hue spectrum gradient on the X axis. gradient = context.createLinearGradient(0, 0, w, 0); for (i = 0; i <= 6; i++) { color = 'rgb(' + hueSpectrum[i][0] + ', ' + hueSpectrum[i][1] + ', ' + hueSpectrum[i][2] + ')'; gradient.addColorStop(i * 1/6, color); } context.fillStyle = gradient; context.fillRect(0, 0, w, h); // Draw the gradient which lightens the hue spectrum on the Y axis. gradient = context.createLinearGradient(0, 0, 0, h); gradient.addColorStop(0, 'rgba(255, 255, 255, 0)'); gradient.addColorStop(1, 'rgba(255, 255, 255, 1)'); context.fillStyle = gradient; context.fillRect(0, 0, w, h); } if (_self.color.val < 1) { // Draw a solid black color on top. This is used for darkening the hue colors gradient when the user reduces the Value (hsV). context.fillStyle = 'rgba(0, 0, 0, ' + (1 - _self.color.val) +')'; context.fillRect(0, 0, w, h); } } else if (_self.ckey_active === 'hue') { // In hue mode the user has the slider which allows him/her to change the hue (Hsv) of the current color. // The chart shows the current color in the background. The X axis gives the saturation (hSv), and the Y axis gives the value (hsV). if (_self.color.sat === 1 && _self.color.val === 1) { color = [_self.color.red, _self.color.green, _self.color.blue]; } else { // Determine the RGB values for the current color which has the same hue, but maximum saturation and value (hSV). color = _self.hsv2rgb(true, [_self.color.hue, 1, 1]); } for (i = 0; i < 3; i++) { color[i] = MathRound(color[i] * 255); } context.fillStyle = 'rgb(' + color[0] + ', ' + color[1] + ', ' + color[2] + ')'; context.fillRect(0, 0, w, h); // Draw the white gradient for saturation (X axis, hSv). gradient = context.createLinearGradient(0, 0, w, 0); gradient.addColorStop(0, 'rgba(255, 255, 255, 1)'); gradient.addColorStop(1, 'rgba(255, 255, 255, 0)'); context.fillStyle = gradient; context.fillRect(0, 0, w, h); // Draw the black gradient for value (Y axis, hsV). gradient = context.createLinearGradient(0, 0, 0, h); gradient.addColorStop(0, 'rgba(0, 0, 0, 0)'); gradient.addColorStop(1, 'rgba(0, 0, 0, 1)'); context.fillStyle = gradient; context.fillRect(0, 0, w, h); } else if (_self.ckey_active_group === 'rgb') { // In any red/green/blue mode the background color becomes the one of the ckey_active. Say, for ckey_active=red the background color would be the current red value (green and blue are both set to 0). // On the X/Y axes the other two colors are shown. E.g. for red the X axis gives the green gradient, and the Y axis gives the blue gradient. The two gradients are drawn on top of the red background using a global composite operation (lighter) - to create the color addition effect. var color2, color3; color = {'red' : 0, 'green' : 0, 'blue' : 0}; color[_self.ckey_active] = MathRound(_self.color[_self.ckey_active] * 255); color2 = {'red' : 0, 'green' : 0, 'blue' : 0}; color2[_self.ckey_adjoint[1]] = 255; color3 = {'red' : 0, 'green' : 0, 'blue' : 0}; color3[_self.ckey_adjoint[0]] = 255; // The background. context.fillStyle = 'rgb(' + color.red + ',' + color.green + ',' + color.blue + ')'; context.fillRect(0, 0, w, h); // This doesn't work in Opera 9.2 and older versions. var op = context.globalCompositeOperation; context.globalCompositeOperation = 'lighter'; // The Y axis gradient. gradient = context.createLinearGradient(0, 0, 0, h); gradient.addColorStop(0, 'rgba(' + color2.red + ',' + color2.green + ',' + color2.blue + ', 1)'); gradient.addColorStop(1, 'rgba(' + color2.red + ',' + color2.green + ',' + color2.blue + ', 0)'); context.fillStyle = gradient; context.fillRect(0, 0, w, h); // The X axis gradient. gradient = context.createLinearGradient(0, 0, w, 0); gradient.addColorStop(0, 'rgba(' + color3.red + ',' + color3.green + ',' + color3.blue + ', 0)'); gradient.addColorStop(1, 'rgba(' + color3.red + ',' + color3.green + ',' + color3.blue + ', 1)'); context.fillStyle = gradient; context.fillRect(0, 0, w, h); context.globalCompositeOperation = op; } else if (_self.ckey_active_group === 'lab') { // The chart plots the CIE Lab colors. The non-active color keys give the X/Y axes. For example, if cie_l (lightness) is active, then the cie_a values give the X axis, and the Y axis is given by the values of cie_b. // The chart is drawn manually, pixel-by-pixel, due to the special way CIE Lab works. This is very slow in today's UAs. var imgd = false; if (context.createImageData) { imgd = context.createImageData(w, h); } else if (context.getImageData) { imgd = context.getImageData(0, 0, w, h); } else { imgd = { 'width' : w, 'height' : h, 'data' : new Array(w*h*4) }; } var pix = imgd.data, n = imgd.data.length - 1, i = -1, p = 0, inc_x, inc_y, xyz = [], rgb = [], cie_x, cie_y; cie_x = _self.ckey_adjoint[0]; cie_y = _self.ckey_adjoint[1]; color = { 'cie_l' : _self.color.cie_l, 'cie_a' : _self.color.cie_a, 'cie_b' : _self.color.cie_b }; inc_x = _self.abs_max[cie_x] / w; inc_y = _self.abs_max[cie_y] / h; color[cie_x] = config.inputValues[cie_x][0]; color[cie_y] = config.inputValues[cie_y][0]; while (i < n) { xyz = _self.lab2xyz(color.cie_l, color.cie_a, color.cie_b); rgb = _self.xyz2rgb(xyz); pix[++i] = MathRound(rgb[0]*255); pix[++i] = MathRound(rgb[1]*255); pix[++i] = MathRound(rgb[2]*255); pix[++i] = 255; p++; color[cie_x] += inc_x; if ((p % w) === 0) { color[cie_x] = config.inputValues[cie_x][0]; color[cie_y] += inc_y; } } context.putImageData(imgd, 0, 0); } return true; }; /** * Draw the color slider on the Canvas element. * * @private * * @param {String} updated_ckey The color key that was updated. This is used * to determine if the Canvas needs to be updated or not. */ this.draw_slider = function (updated_ckey) { if (_self.ckey_active === updated_ckey) { return true; } var context = _self.context2d, slider_w = _self.sliderWidth, slider_h = _self.sliderHeight, slider_x = _self.sliderX, slider_y = 0, gradient, color, i; gradient = context.createLinearGradient(slider_x, slider_y, slider_x, slider_h); if (_self.ckey_active === 'hue') { // Draw the hue spectrum gradient. for (i = 0; i <= 6; i++) { color = 'rgb(' + hueSpectrum[i][0] + ', ' + hueSpectrum[i][1] + ', ' + hueSpectrum[i][2] + ')'; gradient.addColorStop(i * 1/6, color); } context.fillStyle = gradient; context.fillRect(slider_x, slider_y, slider_w, slider_h); if (_self.color.sat < 1) { context.fillStyle = 'rgba(255, 255, 255, ' + (1 - _self.color.sat) + ')'; context.fillRect(slider_x, slider_y, slider_w, slider_h); } if (_self.color.val < 1) { context.fillStyle = 'rgba(0, 0, 0, ' + (1 - _self.color.val) + ')'; context.fillRect(slider_x, slider_y, slider_w, slider_h); } } else if (_self.ckey_active === 'sat') { // Draw the saturation gradient for the slider. // The start color is the current color with maximum saturation. The bottom gradient color is the same "color" without saturation. // The slider allows you to desaturate the current color. // Determine the RGB values for the current color which has the same hue and value (HsV), but maximum saturation (hSv). if (_self.color.sat === 1) { color = [_self.color.red, _self.color.green, _self.color.blue]; } else { color = _self.hsv2rgb(true, [_self.color.hue, 1, _self.color.val]); } for (i = 0; i < 3; i++) { color[i] = MathRound(color[i] * 255); } var gray = MathRound(_self.color.val * 255); gradient.addColorStop(0, 'rgb(' + color[0] + ', ' + color[1] + ', ' + color[2] + ')'); gradient.addColorStop(1, 'rgb(' + gray + ', ' + gray + ', ' + gray + ')'); context.fillStyle = gradient; context.fillRect(slider_x, slider_y, slider_w, slider_h); } else if (_self.ckey_active === 'val') { // Determine the RGB values for the current color which has the same hue and saturation, but maximum value (hsV). if (_self.color.val === 1) { color = [_self.color.red, _self.color.green, _self.color.blue]; } else { color = _self.hsv2rgb(true, [_self.color.hue, _self.color.sat, 1]); } for (i = 0; i < 3; i++) { color[i] = MathRound(color[i] * 255); } gradient.addColorStop(0, 'rgb(' + color[0] + ', ' + color[1] + ', ' + color[2] + ')'); gradient.addColorStop(1, 'rgb(0, 0, 0)'); context.fillStyle = gradient; context.fillRect(slider_x, slider_y, slider_w, slider_h); } else if (_self.ckey_active_group === 'rgb') { var red = MathRound(_self.color.red * 255), green = MathRound(_self.color.green * 255), blue = MathRound(_self.color.blue * 255); color = { 'red' : red, 'green' : green, 'blue' : blue }; color[_self.ckey_active] = 255; var color2 = { 'red' : red, 'green' : green, 'blue' : blue }; color2[_self.ckey_active] = 0; gradient.addColorStop(0, 'rgb(' + color.red + ',' + color.green + ',' + color.blue + ')'); gradient.addColorStop(1, 'rgb(' + color2.red + ',' + color2.green + ',' + color2.blue + ')'); context.fillStyle = gradient; context.fillRect(slider_x, slider_y, slider_w, slider_h); } else if (_self.ckey_active_group === 'lab') { // The slider shows a gradient with the current color key going from the minimum to the maximum value. The gradient is calculated pixel by pixel, due to the special way CIE Lab is defined. var imgd = false; if (context.createImageData) { imgd = context.createImageData(1, slider_h); } else if (context.getImageData) { imgd = context.getImageData(0, 0, 1, slider_h); } else { imgd = { 'width' : 1, 'height' : slider_h, 'data' : new Array(slider_h*4) }; } var pix = imgd.data, n = imgd.data.length - 1, ckey = _self.ckey_active, i = -1, inc, xyz, rgb; color = { 'cie_l' : _self.color.cie_l, 'cie_a' : _self.color.cie_a, 'cie_b' : _self.color.cie_b }; color[ckey] = config.inputValues[ckey][0]; inc = _self.abs_max[ckey] / slider_h; while (i < n) { xyz = _self.lab2xyz(color.cie_l, color.cie_a, color.cie_b); rgb = _self.xyz2rgb(xyz); pix[++i] = MathRound(rgb[0]*255); pix[++i] = MathRound(rgb[1]*255); pix[++i] = MathRound(rgb[2]*255); pix[++i] = 255; color[ckey] += inc; } for (i = 0; i <= slider_w; i++) { context.putImageData(imgd, slider_x+i, slider_y); } } context.strokeStyle = '#6d6d6d'; context.strokeRect(slider_x, slider_y, slider_w, slider_h); return true; }; }; // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * Copyright (C) 2009 Mihai Şucan * * This file is part of PaintWeb. * * PaintWeb is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PaintWeb is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PaintWeb. If not, see <http://www.gnu.org/licenses/>. * * $URL: http://code.google.com/p/paintweb $ * $Date: 2009-10-29 19:05:49 +0200 $ */ /** * @author <a lang="ro" href="http://www.robodesign.ro/mihai">Mihai Şucan</a> * @fileOverview Holds the integration code for PaintWeb inside <a * href="http://www.moodle.org">Moodle</a>. */ /** * @class The Moodle extension for PaintWeb. This extension handles the Moodle * integration inside the PaintWeb code. * * <p><strong>Note:</strong> This extension is supposed to work with Moodle 1.9 * and Moodle 2.0. * * @param {PaintWeb} app Reference to the main paint application object. */ pwlib.extensions.moodle = function (app) { var _self = this, appEvent = pwlib.appEvent, config = app.config, gui = app.gui, lang = app.lang.moodle, moodleServer = config.moodleServer, tinymceEditor = null, qfErrorShown = false; // Holds information related to Moodle. var moodleInfo = { // Holds the URL of the image the user is saving. imageURL: null, // The class name for the element which holds the textarea buttons (toggle // on/off). // This element exists only in Moodle 1.9. textareaButtons: 'textareaicons', // The image save handler script on the server-side. The path is relative to // the PaintWeb base folder. // This used with Moodle 2.0. imageSaveHandler20: '../ext/moodle/imagesave20.php', // The image save handler script for Moodle 1.9. imageSaveHandler19: '../ext/moodle/imagesave19.php', // This holds the release version of Moodle being used. This should be 1.9 // or 2.0. release: 0, // Moodle 2.0 draft item ID used for file storage. draftitemid: null }; /** * The <code>extensionRegister</code> event handler. Setup event listeners, * determine Moodle version, and more. * * @returns {Boolean} True if the extension initialized successfully, or false * if not. */ this.extensionRegister = function () { // Register application events. app.events.add('guiShow', this.guiShow); app.events.add('guiHide', this.guiHide); app.events.add('imageSave', this.imageSave); if (moodleServer && moodleServer.release) { var matches = moodleServer.release.match(/^\s*(\d+\.\d+)/); if (matches && matches[1]) { moodleInfo.release = parseFloat(matches[1]); } } if (typeof window.qf_errorHandler === 'function' && config.tinymce && !config.tinymce.onSubmitUnsaved) { config.tinymce.onSubmitUnsaved = this.onSubmitUnsaved; } return true; }; /** * The <code>submit</code> event handler for the form to which the PaintWeb * instance is attached to. This method is invoked by the TinyMCE plugin when * the form is submitted while the user edits an image with unsaved changes. * @private */ this.onSubmitUnsaved = function () { var tmce = config.tinymceEditor, textarea = tmce ? tmce.getElement() : null, guiPlaceholder = config.guiPlaceholder, prevSibling = guiPlaceholder.previousSibling; if (tmce && textarea && window.qf_errorHandler) { try { qf_errorHandler(textarea, "\n - " + lang.errorSubmitUnsaved); } catch (err) { return; } qfErrorShown = true; // Due to the styling of the error shown by Moodle, PaintWeb must have // clear:right. if (prevSibling && prevSibling.className && prevSibling.className.indexOf('paintweb_tinymce_status') !== -1) { prevSibling.style.clear = 'right'; } else { guiPlaceholder.style.clear = 'right'; } } }; /** * The <code>imageSave</code> application event handler. When the user * attempts to save an image, this extension handles the event by sending the * image data to the Moodle server, to perform the actual save operation. * * @private * @param {pwlib.appEvent.imageSave} ev The application event object. */ this.imageSave = function (ev) { if (!ev.dataURL) { return; } ev.preventDefault(); moodleInfo.imageURL = config.imageLoad.src; if (!moodleInfo.imageURL || moodleInfo.imageURL.substr(0, 5) === 'data:') { moodleInfo.imageURL = '-'; } if (config.moodleSaveMethod === 'dataURL') { app.events.dispatch(new appEvent.imageSaveResult(true, moodleInfo.imageURL, ev.dataURL)); } else { var handlerURL = PaintWeb.baseFolder, send = 'url=' + encodeURIComponent(moodleInfo.imageURL) + '&dataURL=' + encodeURIComponent(ev.dataURL), headers = {'Content-Type': 'application/x-www-form-urlencoded'}; // In Moodle 2.0 we include the context ID and the draft item ID, such // that the image save script can properly save the new image inside the // current draft area of the current textarea element. if (moodleInfo.release >= 2) { handlerURL += moodleInfo.imageSaveHandler20; if (moodleServer.contextid) { send += '&contextid=' + encodeURIComponent(moodleServer.contextid); } if (moodleInfo.draftitemid) { send += '&draftitemid=' + encodeURIComponent(moodleInfo.draftitemid); } } else { handlerURL += moodleInfo.imageSaveHandler19; } pwlib.xhrLoad(handlerURL, imageSaveReady, 'POST', send, headers); } }; /** * The image save <code>onreadystatechange</code> event handler for the * <code>XMLHttpRequest</code> which performs the image save. This function * uses the reply to determine if the image save operation is successful or * not. * * <p>The {@link pwlib.appEvent.imageSaveResult} application event is * dispatched. * * <p>The server-side script must reply with a JSON object with the following * properties: * * <ul> * <li><var>successful</var> which tells if the image save operation was * successful or not; * * <li><var>url</var> which must tell the same URL as the image we just * saved (sanity/security check); * * <li><var>urlNew</var> is optional. This allows the server-side script to * change the image URL; * * <li><var>errorMessage</var> is optional. When the image save was not * successful, an error message can be displayed. * </ul> * * @private * @param {XMLHttpRequest} xhr The XMLHttpRequest object. */ function imageSaveReady (xhr) { if (!xhr || xhr.readyState !== 4) { return; } var result = {successful: false, url: moodleInfo.imageURL}; if ((xhr.status !== 304 && xhr.status !== 200) || !xhr.responseText) { alert(lang.xhrRequestFailed); app.events.dispatch(new appEvent.imageSaveResult(false, result.url, null, lang.xhrRequestFailed)); return; } try { result = JSON.parse(xhr.responseText); } catch (err) { result.errorMessage = lang.jsonParseFailed + "\n" + err; alert(result.errorMessage); } if (result.successful) { if (result.url !== moodleInfo.imageURL) { alert(pwlib.strf(lang.urlMismatch, { url: moodleInfo.imageURL, urlServer: result.url || 'null'})); } } else { if (result.errorMessage) { alert(lang.imageSaveFailed + "\n" + result.errorMessage); } else { alert(lang.imageSaveFailed); } } app.events.dispatch(new appEvent.imageSaveResult(result.successful, result.url, result.urlNew, result.errorMessage)); }; /** * The <code>guiShow</code> application event handler. When the PaintWeb GUI * is shown, we must hide the textarea icons for the current textarea element, * inside a Moodle page. * @private */ this.guiShow = function () { var pNode = config.guiPlaceholder.parentNode, textareaButtons = pNode.getElementsByClassName(moodleInfo.textareaButtons)[0]; // These show in Moodle 1.9. if (textareaButtons) { textareaButtons.style.display = 'none'; } qfErrorShown = false; // For Moodle 2.0 we must determine the draft item ID in order to properly // perform the image save operation into the current draft area. if (moodleInfo.release < 2) { return; } // Typically the TinyMCE editor instance is attached to a textarea element // which has a name=whatever[text] or similar form. In the same form as the // textarea, there must be a hidden input element with the // name=whatever[itemid]. The value of that input holds the draft item ID. var tmce = config.tinymceEditor, textarea = tmce ? tmce.getElement() : null, frm = textarea ? textarea.form : null; if (!tmce || !textarea || !textarea.name || !frm) { return; } var fieldname = textarea.name.replace(/\[text\]$/, ''); if (!fieldname) { return; } var draftitemid = frm.elements.namedItem(fieldname + '[itemid]'), format = frm.elements.namedItem(fieldname + '[format]'); if (draftitemid) { moodleInfo.draftitemid = draftitemid.value; } if (format) { format.style.display = 'none'; } }; /** * The <code>guiHide</code> application event handler. When the PaintWeb GUI * is hidden, we must show again the textarea icons for the current textarea * element, inside a Moodle page. * @private */ this.guiHide = function () { var guiPlaceholder = config.guiPlaceholder, prevSibling = guiPlaceholder.previousSibling; pNode = guiPlaceholder.parentNode, textareaButtons = pNode.getElementsByClassName(moodleInfo.textareaButtons)[0]; // These show in Moodle 1.9. if (textareaButtons) { textareaButtons.style.display = ''; } var tmce = config.tinymceEditor, textarea = tmce ? tmce.getElement() : null, frm = textarea ? textarea.form : null; if (!tmce || !textarea || !textarea.name || !frm) { return; } if (qfErrorShown) { if (window.qf_errorHandler) { qf_errorHandler(textarea, ''); } if (prevSibling && prevSibling.className && prevSibling.className.indexOf('paintweb_tinymce_status') !== -1) { prevSibling.style.clear = ''; } else { guiPlaceholder.style.clear = ''; } } // The format input element only shows in Moodle 2.0. if (moodleInfo.release >= 2) { var fieldname = textarea.name.replace(/\[text\]$/, ''); if (!fieldname) { return; } var format = frm.elements.namedItem(fieldname + '[format]'); if (format) { format.style.display = ''; } } }; }; // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * Copyright (C) 2008, 2009 Mihai Şucan * * This file is part of PaintWeb. * * PaintWeb is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PaintWeb is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PaintWeb. If not, see <http://www.gnu.org/licenses/>. * * $URL: http://code.google.com/p/paintweb $ * $Date: 2009-06-16 21:56:40 +0300 $ */ /** * @author <a lang="ro" href="http://www.robodesign.ro/mihai">Mihai Şucan</a> * @fileOverview Allows users to draw in PaintWeb using the keyboard, without * any pointing device. */ /** * @class The MouseKeys extension. * * @param {PaintWeb} app Reference to the main paint application object. */ pwlib.extensions.mousekeys = function (app) { var _self = this, canvas = app.buffer.canvas, config = app.config, container = app.gui.elems.canvasContainer, doc = app.doc, gui = app.gui, image = app.image, MathCeil = Math.ceil, mouse = app.mouse, tool = app.tool || {}; /** * Holds the current mouse movement speed in pixels. * * @private * @type Number */ var speed = 1; /** * Holds the current mouse movement acceleration, taken from the * configuration. * * @private * @type Number * @see PaintWeb.config.mousekeys.accel The mouse keys acceleration setting. */ var accel = 0.1; /** * Holds a reference to the DOM element representing the pointer on top of the * canvas element. * * @private * @type Element */ var pointer = null; var pointerStyle = null; /** * The <code>extensionRegister</code> event handler. This initializes the * extension by adding the pointer DOM element and by setting up the keyboard * shortcuts. * * @returns {Boolean} True if the extension initialized successfully, or false * if not. */ this.extensionRegister = function () { accel = config.mousekeys.accel; pointer = doc.createElement('div'); if (!pointer) { return false; } pointerStyle = pointer.style; pointer.className = gui.classPrefix + 'mousekeysPointer'; pointerStyle.display = 'none'; container.appendChild(pointer); canvas.addEventListener('mousemove', pointerMousemove, false); var action, keys, i, n, result = {}; for (action in config.mousekeys.actions) { keys = config.mousekeys.actions[action]; for (i = 0, n = keys.length; i < n; i++) { result[keys[i]] = {'extension': _self._id, 'action': action}; } }; pwlib.extend(config.keys, result); return true; }; /** * The <code>extensionUnregister</code> event handler. This will remove the * pointer DOM element and the canvas event listener. */ this.extensionUnregister = function () { container.removeChild(pointer); canvas.removeEventListener('mousemove', pointerMousemove, false); var key, kobj; for (key in config.keys) { kobj = config.keys[key]; if (kobj.extension === _self._id) { delete config.keys[key]; } } }; /** * Track the virtual pointer coordinates, by updating the position of the * <var>pointer</var> element. This allows the keyboard users to see where * they moved the virtual pointer. * * @param {Event} ev The DOM Event object. */ function pointerMousemove (ev) { if (!('kobj_' in ev) || !('extension' in ev.kobj_) || ev.kobj_.extension !== _self._id) { if (pointerStyle.display === 'block') { pointerStyle.display = 'none'; } } }; /** * The <code>keydown</code> event handler. * * <p>This method requires a DOM Event object which has the * <var>ev.kobj_</var> object reference from the keyboard shortcuts * configuration. The <var>kobj_</var> object must have the <var>action</var> * property. Support for the "ButtonToggle" and the "ButtonClick" actions is * implemented. * * <p>The "ButtonToggle" action essentially means that a mouse event will be * generated, either <code>mousedown</code> or <code>mouseup</code>. By * alternating these two events, this method allows the user to start and stop * the drawing operation at any moment using the keyboard shortcut they have * configured. * * <p>Under typical usage, the "ButtonClick" action translates the * <code>keydown</code> event to <code>mousedown</code>. The * <code>keyup</code> event handler will also fire the <code>mouseup</code> * event. This allows the user to simulate holding down the mouse button, * while he/she holds down a key. * * <p>A <code>click</code> event is always fired after the firing of * a <code>mouseup</code> event. * * <p>Irrespective of the key the user pressed, this method does always reset * the speed and acceleration of the pointer movement. * * @param {Event} ev The DOM Event object. * * @returns {Boolean} True if the keyboard shortcut was recognized, or false * if not. * * @see PaintWeb.config.mousekeys.actions The keyboard shortcuts configuration * object. */ this.keydown = function (ev) { speed = 1; accel = config.mousekeys.accel; if (pointerStyle.display === 'none') { pointerStyle.display = 'block'; pointerStyle.top = (mouse.y * image.canvasScale) + 'px'; pointerStyle.left = (mouse.x * image.canvasScale) + 'px'; if (mouse.buttonDown) { pointer.className += ' ' + gui.classPrefix + 'mouseDown'; } else { pointer.className = pointer.className.replace(' ' + gui.classPrefix + 'mouseDown', ''); } } tool = app.tool || {}; switch (ev.kobj_.action) { case 'ButtonToggle': if (mouse.buttonDown) { mouse.buttonDown = false; if ('mouseup' in tool) { tool.mouseup(ev); } if ('click' in tool) { tool.click(ev); } } else { mouse.buttonDown = true; if ('mousedown' in tool) { tool.mousedown(ev); } } break; case 'ButtonClick': if (!mouse.buttonDown) { mouse.buttonDown = true; if ('mousedown' in tool) { tool.mousedown(ev); } } break; default: return false; } if (mouse.buttonDown) { pointer.className += ' ' + gui.classPrefix + 'mouseDown'; } else { pointer.className = pointer.className.replace(' ' + gui.classPrefix + 'mouseDown', ''); } return true; }; /** * The <code>keypress</code> event handler. * * <p>This method requires a DOM Event object with a <var>ev.kobj_</var> * object reference to the keyboard shortcut configuration. The keyboard * shortcut configuration object must have the <var>action</var> property. * * <p>This event handler implements support for the following <var>param</var> * values: "SouthWest", "South", "SouthEast", "West", "East", "NorthWest", * "North" and "NorthEast", All of these values indicate the movement * direction. This method generates synthetic <var>movemove</var> events based * on the direction desired, effectively emulating the use of a real pointing * device. * * @param {Event} ev The DOM Event object. * * @returns {Boolean} True if the keyboard shortcut was recognized, or false * if not. * * @see PaintWeb.config.mousekeys.actions The keyboard shortcuts configuration * object. */ this.keypress = function (ev) { if (ev.shiftKey) { speed += speed * accel * 3; } else { speed += speed * accel; } var step = MathCeil(speed); switch (ev.kobj_.action) { case 'SouthWest': mouse.x -= step; mouse.y += step; break; case 'South': mouse.y += step; break; case 'SouthEast': mouse.x += step; mouse.y += step; break; case 'West': mouse.x -= step; break; case 'East': mouse.x += step; break; case 'NorthWest': mouse.x -= step; mouse.y -= step; break; case 'North': mouse.y -= step; break; case 'NorthEast': mouse.x += step; mouse.y -= step; break; default: return false; } if (mouse.x < 0) { mouse.x = 0; } else if (mouse.x > image.width) { mouse.x = image.width; } if (mouse.y < 0) { mouse.y = 0; } else if (mouse.y > image.height) { mouse.y = image.height; } pointerStyle.top = (mouse.y * image.canvasScale) + 'px'; pointerStyle.left = (mouse.x * image.canvasScale) + 'px'; if ('mousemove' in tool) { tool.mousemove(ev); } return true; }; /** * The <code>keyup</code> event handler. * * <p>This method requires a DOM Event object which has the * <var>ev.kobj_</var> object reference from the keyboard shortcuts * configuration. The <var>kobj_</var> object must have the <var>action</var> * property. Support for the "ButtonClick" action is implemented. * * <p>Under typical usage, the "ButtonClick" action translates the * <code>keydown</code> event to <code>mousedown</code>. This event handler * fires the <code>mouseup</code> event. This allows the user to simulate * holding down the mouse button, while he/she holds down a key. * * <p>A <code>click</code> event is always fired after the firing of the * <code>mouseup</code> event. * * @param {Event} ev The DOM Event object. * * @returns {Boolean} True if the keyboard shortcut was recognized, or false * if not. * * @see PaintWeb.config.mousekeys.actions The keyboard shortcuts configuration * object. */ this.keyup = function (ev) { if (ev.kobj_.action == 'ButtonClick' && mouse.buttonDown) { mouse.buttonDown = false; if ('mouseup' in tool) { tool.mouseup(ev); } if ('click' in tool) { tool.click(ev); } pointer.className = pointer.className.replace(' ' + gui.classPrefix + 'mouseDown', ''); return true; } return false; }; }; // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * Copyright (C) 2008, 2009, 2010 Mihai Şucan * * This file is part of PaintWeb. * * PaintWeb is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PaintWeb is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PaintWeb. If not, see <http://www.gnu.org/licenses/>. * * $URL: http://code.google.com/p/paintweb $ * $Date: 2011-01-05 14:37:59 $ */ /** * @author <a lang="ro" href="http://www.robodesign.ro/mihai">Mihai Şucan</a> * @fileOverview The main PaintWeb application code. */ /** * @class The PaintWeb application object. * * @param {Window} [win=window] The window object to use. * @param {Document} [doc=document] The document object to use. */ function PaintWeb (win, doc) { var _self = this; if (!win) { win = window; } if (!doc) { doc = document; } /** * PaintWeb version. * @type Number */ this.version = 0.9; //! /** * PaintWeb build date (YYYYMMDD). * @type Number */ this.build = -1; //! /** * Holds all the PaintWeb configuration. * @type Object */ this.config = { showErrors: true }; /** * Holds all language strings used within PaintWeb. */ // Here we include a minimal set of strings, used in case the language file will // not load. this.lang = { "noComputedStyle": "Error: window.getComputedStyle is not available.", "noXMLHttpRequest": "Error: window.XMLHttpRequest is not available.", "noCanvasSupport": "Error: Your browser does not support Canvas.", "guiPlaceholderWrong": "Error: The config.guiPlaceholder property must " + "reference a DOM element!", "initHandlerMustBeFunction": "The first argument must be a function.", "noConfigFile": "Error: You must point to a configuration file by " + "setting the config.configFile property!", "failedConfigLoad": "Error: Failed loading the configuration file.", "failedLangLoad": "Error: Failed loading the language file." }; /** * Holds the buffer canvas and context references. * @type Object */ this.buffer = {canvas: null, context: null}; /** * Holds the current layer ID, canvas and context references. * @type Object */ this.layer = {id: null, canvas: null, context: null}; /** * The instance of the active tool object. * * @type Object * * @see PaintWeb.config.toolDefault holds the ID of the tool which is * activated when the application loads. * @see PaintWeb#toolActivate Activate a drawing tool by ID. * @see PaintWeb#toolRegister Register a new drawing tool. * @see PaintWeb#toolUnregister Unregister a drawing tool. * @see pwlib.tools holds the drawing tools. */ this.tool = null; /** * Holds references to DOM elements. * * @private * @type Object */ this.elems = {}; /** * Holds the last recorded mouse coordinates and the button state (if it's * down or not). * * @private * @type Object */ this.mouse = {x: 0, y: 0, buttonDown: false}; /** * Holds all the PaintWeb extensions. * * @type Object * @see PaintWeb#extensionRegister Register a new extension. * @see PaintWeb#extensionUnregister Unregister an extension. * @see PaintWeb.config.extensions Holds the list of extensions to be loaded * automatically when PaintWeb is initialized. */ this.extensions = {}; /** * Holds all the PaintWeb commands. Each property in this object must * reference a simple function which can be executed by keyboard shortcuts * and/or GUI elements. * * @type Object * @see PaintWeb#commandRegister Register a new command. * @see PaintWeb#commandUnregister Unregister a command. */ this.commands = {}; /** * The graphical user interface object instance. * @type pwlib.gui */ this.gui = null; /** * The document element PaintWeb is working with. * * @private * @type Document * @default document */ this.doc = doc; /** * The window object PaintWeb is working with. * * @private * @type Window * @default window */ this.win = win; /** * Holds image information: width, height, zoom and more. * * @type Object */ this.image = { /** * Image width. * * @type Number */ width: 0, /** * Image height. * * @type Number */ height: 0, /** * Image zoom level. This property holds the current image zoom level used * by the user for viewing the image. * * @type Number * @default 1 */ zoom: 1, /** * Image scaling. The canvas elements are scaled from CSS using this value * as the scaling factor. This value is dependant on the browser rendering * resolution and on the user-defined image zoom level. * * @type Number * @default 1 */ canvasScale: 1, /** * Tells if the current image has been modified since the initial load. * * @type Boolean * @default false */ modified: false }; /** * Resolution information. * * @type Object */ this.resolution = { /** * The DOM element holding information about the current browser rendering * settings (zoom / DPI). * * @private * @type Element */ elem: null, /** * The ID of the DOM element holding information about the current browser * rendering settings (zoom / DPI). * * @private * @type String * @default 'paintweb_resInfo' */ elemId: 'paintweb_resInfo', /** * The styling necessary for the DOM element. * * @private * @type String */ cssText: '@media screen and (resolution:96dpi){' + '#paintweb_resInfo{width:96px}}' + '@media screen and (resolution:134dpi){' + '#paintweb_resInfo{width:134px}}' + '@media screen and (resolution:200dpi){' + '#paintweb_resInfo{width:200px}}' + '@media screen and (resolution:300dpi){' + '#paintweb_resInfo{width:300px}}' + '#paintweb_resInfo{' + 'display:block;' + 'height:100%;' + 'left:-3000px;' + 'position:fixed;' + 'top:0;' + 'visibility:hidden;' + 'z-index:-32}', /** * Optimal DPI for the canvas elements. * * @private * @type Number * @default 96 */ dpiOptimal: 96, /** * The current DPI used by the browser for rendering the entire page. * * @type Number * @default 96 */ dpiLocal: 96, /** * The current zoom level used by the browser for rendering the entire page. * * @type Number * @default 1 */ browserZoom: 1, /** * The scaling factor used by the browser for rendering the entire page. For * example, on Gecko using DPI 200 the scale factor is 2. * * @private * @type Number * @default -1 */ scale: -1 }; /** * The image history. * * @private * @type Object */ this.history = { /** * History position. * * @type Number * @default 0 */ pos: 0, /** * The ImageDatas for each history state. * * @private * @type Array */ states: [] }; /** * Tells if the browser supports the Canvas Shadows API. * * @type Boolean * @default true */ this.shadowSupported = true; /** * Tells if the current tool allows the drawing of shadows. * * @type Boolean * @default true */ this.shadowAllowed = true; /** * Image in the clipboard. This is used when some selection is copy/pasted. * * @type ImageData */ this.clipboard = false; /** * Application initialization state. This property can be in one of the * following states: * * <ul> * <li>{@link PaintWeb.INIT_NOT_STARTED} - The initialization is not * started. * * <li>{@link PaintWeb.INIT_STARTED} - The initialization process is * running. * * <li>{@link PaintWeb.INIT_DONE} - The initialization process has completed * successfully. * * <li>{@link PaintWeb.INIT_ERROR} - The initialization process has failed. * </ul> * * @type Number * @default PaintWeb.INIT_NOT_STARTED */ this.initialized = PaintWeb.INIT_NOT_STARTED; /** * Custom application events object. * * @type pwlib.appEvents */ this.events = null; /** * Unique ID for the current PaintWeb instance. * * @type Number */ this.UID = 0; /** * List of Canvas context properties to save and restore. * * <p>When the Canvas is resized the state is lost. Using context.save/restore * state does work only in Opera. In Firefox/Gecko and WebKit saved states are * lost after resize, so there's no state to restore. As such, PaintWeb has * its own simple state save/restore mechanism. The property values are saved * into a JavaScript object. * * @private * @type Array * * @see PaintWeb#stateSave to save the canvas context state. * @see PaintWeb#stateRestore to restore a canvas context state. */ this.stateProperties = ['strokeStyle', 'fillStyle', 'globalAlpha', 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit', 'shadowOffsetX', 'shadowOffsetY', 'shadowBlur', 'shadowColor', 'globalCompositeOperation', 'font', 'textAlign', 'textBaseline']; /** * Holds the keyboard event listener object. * * @private * @type pwlib.dom.KeyboardEventListener * @see pwlib.dom.KeyboardEventListener The class dealing with the * cross-browser differences in the DOM keyboard events. */ var kbListener_ = null; /** * Holds temporary state information during PaintWeb initialization. * * @private * @type Object */ var temp_ = {onInit: null, toolsLoadQueue: 0, extensionsLoadQueue: 0}; // Avoid global scope lookup. var MathAbs = Math.abs, MathFloor = Math.floor, MathMax = Math.max, MathMin = Math.min, MathRound = Math.round, pwlib = null, appEvent = null, lang = this.lang; /** * Element node type constant. * * @constant * @type Number */ this.ELEMENT_NODE = window.Node ? Node.ELEMENT_NODE : 1; /** * PaintWeb pre-initialization code. This runs when the PaintWeb instance is * constructed. * @private */ function preInit() { var d = new Date(); // If PaintWeb is running directly from the source code, then the build date // is always today. if (_self.build === -1) { var dateArr = [d.getFullYear(), d.getMonth()+1, d.getDate()]; if (dateArr[1] < 10) { dateArr[1] = '0' + dateArr[1]; } if (dateArr[2] < 10) { dateArr[2] = '0' + dateArr[2]; } _self.build = dateArr.join(''); } _self.UID = d.getMilliseconds() * MathRound(Math.random() * 100); _self.elems.head = doc.getElementsByTagName('head')[0] || doc.body; }; /** * Initialize PaintWeb. * * <p>This method is asynchronous, meaning that it will return much sooner * before the application initialization is completed. * * @param {Function} [handler] The <code>appInit</code> event handler. Your * event handler will be invoked automatically when PaintWeb completes * loading, or when an error occurs. * * @returns {Boolean} True if the initialization has been started * successfully, or false if not. */ this.init = function (handler) { if (this.initialized === PaintWeb.INIT_DONE) { return true; } this.initialized = PaintWeb.INIT_STARTED; if (handler && typeof handler !== 'function') { throw new TypeError(lang.initHandlerMustBeFunction); } temp_.onInit = handler; // Check Canvas support. if (!doc.createElement('canvas').getContext) { this.initError(lang.noCanvasSupport); return false; } // Basic functionality used within the Web application. if (!window.getComputedStyle) { try { if (!win.getComputedStyle(doc.createElement('div'), null)) { this.initError(lang.noComputedStyle); return false; } } catch (err) { this.initError(lang.noComputedStyle); return false; } } if (!window.XMLHttpRequest) { this.initError(lang.noXMLHttpRequest); return false; } if (!this.config.configFile) { this.initError(lang.noConfigFile); return false; } if (typeof this.config.guiPlaceholder !== 'object' || this.config.guiPlaceholder.nodeType !== this.ELEMENT_NODE) { this.initError(lang.guiPlaceholderWrong); return false; } // Silently ignore any wrong value for the config.imageLoad property. if (typeof this.config.imageLoad !== 'object' || this.config.imageLoad.nodeType !== this.ELEMENT_NODE) { this.config.imageLoad = null; } // JSON parser and serializer. if (!window.JSON) { this.scriptLoad(PaintWeb.baseFolder + 'includes/json2.js', this.jsonlibReady); } else { this.jsonlibReady(); } return true; }; /** * The <code>load</code> event handler for the JSON library script. * @private */ this.jsonlibReady = function () { if (window.pwlib) { _self.pwlibReady(); } else { _self.scriptLoad(PaintWeb.baseFolder + 'includes/lib.js', _self.pwlibReady); } }; /** * The <code>load</code> event handler for the PaintWeb library script. * @private */ this.pwlibReady = function () { pwlib = window.pwlib; appEvent = pwlib.appEvent; // Create the custom application events object. _self.events = new pwlib.appEvents(_self); _self.configLoad(); }; /** * Report an initialization error. * * <p>This method dispatches the {@link pwlib.appEvent.appInit} event. * * @private * * @param {String} msg The error message. * * @see pwlib.appEvent.appInit */ this.initError = function (msg) { switch (this.initialized) { case PaintWeb.INIT_ERROR: case PaintWeb.INIT_DONE: case PaintWeb.INIT_NOT_STARTED: return; } this.initialized = PaintWeb.INIT_ERROR; var ev = null; if (this.events && 'dispatch' in this.events && appEvent && 'appInit' in appEvent) { ev = new appEvent.appInit(this.initialized, msg); this.events.dispatch(ev); } if (typeof temp_.onInit === 'function') { if (!ev) { // fake an event dispatch. ev = {type: 'appInit', state: this.initialized, errorMessage: msg}; } temp_.onInit.call(this, ev); } if (this.config.showErrors) { alert(msg); } else if (window.console && console.log) { console.log(msg); } }; /** * Asynchronously load the configuration file. This method issues an * XMLHttpRequest to load the JSON file. * * @private * * @see PaintWeb.config.configFile The configuration file. * @see pwlib.xhrLoad The library function being used for creating the * XMLHttpRequest object. */ this.configLoad = function () { pwlib.xhrLoad(PaintWeb.baseFolder + this.config.configFile, this.configReady); }; /** * The configuration reader. This is the event handler for the XMLHttpRequest * object, for the <code>onreadystatechange</code> event. * * @private * * @param {XMLHttpRequest} xhr The XMLHttpRequest object being handled. * * @see PaintWeb#configLoad The method which issues the XMLHttpRequest request * for loading the configuration file. */ this.configReady = function (xhr) { /* * readyState values: * 0 UNINITIALIZED open() has not been called yet. * 1 LOADING send() has not been called yet. * 2 LOADED send() has been called, headers and status are available. * 3 INTERACTIVE Downloading, responseText holds the partial data. * 4 COMPLETED Finished with all operations. */ if (!xhr || xhr.readyState !== 4) { return; } if ((xhr.status !== 304 && xhr.status !== 200) || !xhr.responseText) { _self.initError(lang.failedConfigLoad); return; } var config = pwlib.jsonParse(xhr.responseText); pwlib.extend(_self.config, config); _self.langLoad(); }; /** * Asynchronously load the language file. This method issues an XMLHttpRequest * to load the JSON file. * * @private * * @see PaintWeb.config.lang The language you want for the PaintWeb user * interface. * @see pwlib.xhrLoad The library function being used for creating the * XMLHttpRequest object. */ this.langLoad = function () { var id = this.config.lang, file = PaintWeb.baseFolder; // If the language is not available, always fallback to English. if (!(id in this.config.languages)) { id = this.config.lang = 'en'; } if ('file' in this.config.languages[id]) { file += this.config.languages[id].file; } else { file += this.config.langFolder + '/' + id + '.json'; } pwlib.xhrLoad(file, this.langReady); }; /** * The language file reader. This is the event handler for the XMLHttpRequest * object, for the <code>onreadystatechange</code> event. * * @private * * @param {XMLHttpRequest} xhr The XMLHttpRequest object being handled. * * @see PaintWeb#langLoad The method which issues the XMLHttpRequest request * for loading the language file. */ this.langReady = function (xhr) { if (!xhr || xhr.readyState !== 4) { return; } if ((xhr.status !== 304 && xhr.status !== 200) || !xhr.responseText) { _self.initError(lang.failedLangLoad); return; } pwlib.extend(_self.lang, pwlib.jsonParse(xhr.responseText)); if (_self.initCanvas() && _self.initContext()) { // Start GUI load now. _self.guiLoad(); } else { _self.initError(lang.errorInitCanvas); } }; /** * Initialize the PaintWeb commands. * * @private * @returns {Boolean} True if the initialization was successful, or false if * not. */ this.initCommands = function () { if (this.commandRegister('historyUndo', this.historyUndo) && this.commandRegister('historyRedo', this.historyRedo) && this.commandRegister('selectAll', this.selectAll) && this.commandRegister('selectionCut', this.selectionCut) && this.commandRegister('selectionCopy', this.selectionCopy) && this.commandRegister('clipboardPaste', this.clipboardPaste) && this.commandRegister('imageSave', this.imageSave) && this.commandRegister('imageClear', this.imageClear) && this.commandRegister('swapFillStroke', this.swapFillStroke) && this.commandRegister('imageZoomIn', this.imageZoomIn) && this.commandRegister('imageZoomOut', this.imageZoomOut) && this.commandRegister('imageZoomReset', this.imageZoomReset)) { return true; } else { this.initError(lang.errorInitCommands); return false; } }; /** * Load th PaintWeb GUI. This method loads the GUI markup file, the stylesheet * and the script. * * @private * * @see PaintWeb.config.guiStyle The interface style file. * @see PaintWeb.config.guiScript The interface script file. * @see pwlib.gui The interface object. */ this.guiLoad = function () { var cfg = this.config, gui = this.config.gui, base = PaintWeb.baseFolder + cfg.interfacesFolder + '/' + gui + '/', style = base + cfg.guiStyle, script = base + cfg.guiScript; this.styleLoad(gui + 'style', style); if (pwlib.gui) { this.guiScriptReady(); } else { this.scriptLoad(script, this.guiScriptReady); } }; /** * The <code>load</code> event handler for the PaintWeb GUI script. This * method creates an instance of the GUI object that just loaded and starts * loading the GUI markup. * * @private * * @see PaintWeb.config.guiScript The interface script file. * @see PaintWeb.config.guiMarkup The interface markup file. * @see pwlib.gui The interface object. * @see pwlib.xhrLoad The library function being used for creating the * XMLHttpRequest object. */ this.guiScriptReady = function () { var cfg = _self.config, gui = _self.config.gui, base = cfg.interfacesFolder + '/' + gui + '/', markup = base + cfg.guiMarkup; _self.gui = new pwlib.gui(_self); // Check if the interface markup is cached already. if (markup in pwlib.fileCache) { if (_self.gui.init(pwlib.fileCache[markup])) { _self.initTools(); } else { _self.initError(lang.errorInitGUI); } } else { pwlib.xhrLoad(PaintWeb.baseFolder + markup, _self.guiMarkupReady); } }; /** * The GUI markup reader. This is the event handler for the XMLHttpRequest * object, for the <code>onreadystatechange</code> event. * * @private * * @param {XMLHttpRequest} xhr The XMLHttpRequest object being handled. * * @see PaintWeb#guiScriptReady The method which issues the XMLHttpRequest * request for loading the interface markup file. */ this.guiMarkupReady = function (xhr) { if (!xhr || xhr.readyState !== 4) { return; } if (xhr.status !== 304 && xhr.status !== 200) { _self.initError(lang.failedMarkupLoad); return; } var param; if (xhr.responseXML && xhr.responseXML.documentElement) { param = xhr.responseXML; } else if (xhr.responseText) { param = xhr.responseText; } else { _self.initError(lang.failedMarkupLoad); return; } if (_self.gui.init(param)) { _self.initTools(); } else { _self.initError(lang.errorInitGUI); } }; /** * Initialize the Canvas elements. This method creates the elements and * sets-up their dimensions. * * <p>The layer Canvas element will have the background rendered with the * color from {@link PaintWeb.config.backgroundColor}. * * <p>If {@link PaintWeb.config.imageLoad} is defined, then the image element * is inserted into the Canvas image. * * <p>All the Canvas event listeners are also attached to the buffer Canvas * element. * * @private * @returns {Boolean} True if the initialization was successful, or false if * not. * * @see PaintWeb#ev_canvas The global Canvas events handler. */ this.initCanvas = function () { var cfg = this.config, res = this.resolution, resInfo = doc.getElementById(res.elemId), layerCanvas = doc.createElement('canvas'), bufferCanvas = doc.createElement('canvas'), layerContext = layerCanvas.getContext('2d'), bufferContext = bufferCanvas.getContext('2d'), width = cfg.imageWidth, height = cfg.imageHeight, imageLoad = cfg.imageLoad; if (!resInfo) { var style = doc.createElement('style'); style.type = 'text/css'; style.appendChild(doc.createTextNode(res.cssText)); _self.elems.head.appendChild(style); resInfo = doc.createElement('div'); resInfo.id = res.elemId; doc.body.appendChild(resInfo); } if (!resInfo) { this.initError(lang.errorInitCanvas); return false; } if (!layerCanvas || !bufferCanvas || !layerContext || !bufferContext) { this.initError(lang.noCanvasSupport); return false; } if (!pwlib.isSameHost(imageLoad.src, win.location.host)) { cfg.imageLoad = imageLoad = null; alert(lang.imageLoadDifferentHost); } if (imageLoad) { width = parseInt(imageLoad.width); height = parseInt(imageLoad.height); } res.elem = resInfo; this.image.width = layerCanvas.width = bufferCanvas.width = width; this.image.height = layerCanvas.height = bufferCanvas.height = height; this.layer.canvas = layerCanvas; this.layer.context = layerContext; this.buffer.canvas = bufferCanvas; this.buffer.context = bufferContext; if (imageLoad) { layerContext.drawImage(imageLoad, 0, 0); } else { // Set the configured background color. var fillStyle = layerContext.fillStyle; layerContext.fillStyle = cfg.backgroundColor; layerContext.fillRect(0, 0, width, height); layerContext.fillStyle = fillStyle; } /* * Setup the event listeners for the canvas element. * * The event handler (ev_canvas) calls the event handlers associated with * the active tool (e.g. tool.mousemove). */ var events = ['dblclick', 'click', 'mousedown', 'mouseup', 'mousemove', 'contextmenu'], n = events.length; for (var i = 0; i < n; i++) { bufferCanvas.addEventListener(events[i], this.ev_canvas, false); } return true; }; /** * Initialize the Canvas buffer context. This method updates the context * properties to reflect the values defined in the PaintWeb configuration * file. * * <p>Shadows support is also determined. The {@link PaintWeb#shadowSupported} * value is updated accordingly. * * @private * @returns {Boolean} True if the initialization was successful, or false if * not. */ this.initContext = function () { var bufferContext = this.buffer.context; // Opera does not render shadows, at the moment. if (!pwlib.browser.opera && bufferContext.shadowColor && 'shadowOffsetX' in bufferContext && 'shadowOffsetY' in bufferContext && 'shadowBlur' in bufferContext) { this.shadowSupported = true; } else { this.shadowSupported = false; } var cfg = this.config, props = { fillStyle: cfg.fillStyle, font: cfg.text.fontSize + 'px ' + cfg.text.fontFamily, lineCap: cfg.line.lineCap, lineJoin: cfg.line.lineJoin, lineWidth: cfg.line.lineWidth, miterLimit: cfg.line.miterLimit, strokeStyle: cfg.strokeStyle, textAlign: cfg.text.textAlign, textBaseline: cfg.text.textBaseline }; if (cfg.text.bold) { props.font = 'bold ' + props.font; } if (cfg.text.italic) { props.font = 'italic ' + props.font; } // Support Gecko 1.9.0 if (!bufferContext.fillText && 'mozTextStyle' in bufferContext) { props.mozTextStyle = props.font; } for (var prop in props) { bufferContext[prop] = props[prop]; } // shadows are only for the layer context. if (cfg.shadow.enable && this.shadowSupported) { var layerContext = this.layer.context; layerContext.shadowColor = cfg.shadow.shadowColor; layerContext.shadowBlur = cfg.shadow.shadowBlur; layerContext.shadowOffsetX = cfg.shadow.shadowOffsetX; layerContext.shadowOffsetY = cfg.shadow.shadowOffsetY; } return true; }; /** * Initialization procedure which runs after the configuration, language and * GUI files have loaded. * * <p>This method dispatches the {@link pwlib.appEvent.appInit} event. * * @private * * @see pwlib.appEvent.appInit */ this.initComplete = function () { if (!this.initCommands()) { this.initError(lang.errorInitCommands); return; } // The initial blank state of the image this.historyAdd(); this.image.modified = false; // The global keyboard events handler implements everything needed for // switching between tools and for accessing any other functionality of the // Web application. kbListener_ = new pwlib.dom.KeyboardEventListener(this.config.guiPlaceholder, {keydown: this.ev_keyboard, keypress: this.ev_keyboard, keyup: this.ev_keyboard}); this.updateCanvasScaling(); this.win.addEventListener('resize', this.updateCanvasScaling, false); this.events.add('configChange', this.configChangeHandler); this.events.add('imageSaveResult', this.imageSaveResultHandler); // Add the init event handler. if (typeof temp_.onInit === 'function') { _self.events.add('appInit', temp_.onInit); delete temp_.onInit; } this.initialized = PaintWeb.INIT_DONE; this.events.dispatch(new appEvent.appInit(this.initialized)); }; /** * Load all the configured drawing tools. * @private */ this.initTools = function () { var id = '', cfg = this.config, n = cfg.tools.length, base = PaintWeb.baseFolder + cfg.toolsFolder + '/'; if (n < 1) { this.initError(lang.noToolConfigured); return; } temp_.toolsLoadQueue = n; for (var i = 0; i < n; i++) { id = cfg.tools[i]; if (id in pwlib.tools) { this.toolLoaded(); } else { this.scriptLoad(base + id + '.js' , this.toolLoaded); } } }; /** * The <code>load</code> event handler for each tool script. * @private */ this.toolLoaded = function () { temp_.toolsLoadQueue--; if (temp_.toolsLoadQueue === 0) { var t = _self.config.tools, n = t.length; for (var i = 0; i < n; i++) { if (!_self.toolRegister(t[i])) { _self.initError(pwlib.strf(lang.toolRegisterFailed, {id: t[i]})); return; } } _self.initExtensions(); } }; /** * Load all the extensions. * @private */ this.initExtensions = function () { var id = '', cfg = this.config, n = cfg.extensions.length, base = PaintWeb.baseFolder + cfg.extensionsFolder + '/'; if (n < 1) { this.initComplete(); return; } temp_.extensionsLoadQueue = n; for (var i = 0; i < n; i++) { id = cfg.extensions[i]; if (id in pwlib.extensions) { this.extensionLoaded(); } else { this.scriptLoad(base + id + '.js', this.extensionLoaded); } } }; /** * The <code>load</code> event handler for each extension script. * @private */ this.extensionLoaded = function () { temp_.extensionsLoadQueue--; if (temp_.extensionsLoadQueue === 0) { var e = _self.config.extensions, n = e.length; for (var i = 0; i < n; i++) { if (!_self.extensionRegister(e[i])) { _self.initError(pwlib.strf(lang.extensionRegisterFailed, {id: e[i]})); return; } } _self.initComplete(); } }; /** * Update the canvas scaling. This method determines the DPI and/or zoom level * used by the browser to render the application. Based on these values, the * canvas elements are scaled down to cancel any upscaling performed by the * browser. * * <p>The {@link pwlib.appEvent.canvasSizeChange} application event is * dispatched. */ this.updateCanvasScaling = function () { var res = _self.resolution, cs = win.getComputedStyle(res.elem, null), image = _self.image; bufferStyle = _self.buffer.canvas.style, layerStyle = _self.layer.canvas.style, scaleNew = 1, width = parseInt(cs.width), height = parseInt(cs.height); if (pwlib.browser.opera) { // Opera zoom level detection. // The scaling factor is sufficiently accurate for zoom levels between // 100% and 200% (in steps of 10%). scaleNew = win.innerHeight / height; scaleNew = MathRound(scaleNew * 10) / 10; } else if (width && !isNaN(width) && width !== res.dpiOptimal) { // Page DPI detection. This only works in Gecko 1.9.1. res.dpiLocal = width; // The scaling factor is the same as in Gecko. scaleNew = MathFloor(res.dpiLocal / res.dpiOptimal); } else if (pwlib.browser.olpcxo && pwlib.browser.gecko) { // Support for the default Gecko included on the OLPC XO-1 system. // // See: // http://www.robodesign.ro/mihai/blog/paintweb-performance // http://mxr.mozilla.org/mozilla-central/source/gfx/src/thebes/nsThebesDeviceContext.cpp#725 // dotsArePixels = false on the XO due to a hard-coded patch. // Thanks go to roc from Mozilla for his feedback on making this work. res.dpiLocal = 134; // hard-coded value, we cannot determine it var appUnitsPerCSSPixel = 60, // hard-coded internally in Gecko devPixelsPerCSSPixel = res.dpiLocal / res.dpiOptimal; // 1.3958333333 appUnitsPerDevPixel = appUnitsPerCSSPixel / devPixelsPerCSSPixel; // 42.9850746278... scaleNew = appUnitsPerCSSPixel / MathFloor(appUnitsPerDevPixel); // 1.4285714285... // New in Gecko 1.9.2. if ('mozImageSmoothingEnabled' in layerStyle) { layerStyle.mozImageSmoothingEnabled = bufferStyle.mozImageSmoothingEnabled = false; } } if (scaleNew === res.scale) { return; } res.scale = scaleNew; var styleWidth = image.width / res.scale * image.zoom, styleHeight = image.height / res.scale * image.zoom; image.canvasScale = styleWidth / image.width; // FIXME: MSIE 9 clears the Canvas element when you change the // elem.style.width/height... *argh* bufferStyle.width = layerStyle.width = styleWidth + 'px'; bufferStyle.height = layerStyle.height = styleHeight + 'px'; _self.events.dispatch(new appEvent.canvasSizeChange(styleWidth, styleHeight, image.canvasScale)); }; /** * The Canvas events handler. * * <p>This method determines the mouse position relative to the canvas * element, after which it invokes the method of the currently active tool * with the same name as the current event type. For example, for the * <code>mousedown</code> event the <code><var>tool</var>.mousedown()</code> * method is invoked. * * <p>The mouse coordinates are stored in the {@link PaintWeb#mouse} object. * These properties take into account the current zoom level and the image * scroll. * * @private * * @param {Event} ev The DOM Event object. * * @returns {Boolean} True if the tool event handler executed, or false * otherwise. */ this.ev_canvas = function (ev) { if (!_self.tool) { return false; } switch (ev.type) { case 'mousedown': /* * If the mouse is down already, skip the event. * This is needed to allow the user to go out of the drawing canvas, * release the mouse button, then come back and click to end the drawing * operation. * Additionally, this is needed to allow extensions like MouseKeys to * perform their actions during a drawing operation, even when a real * mouse is used. For example, allow the user to start drawing with the * keyboard (press 0) then use the real mouse to move and click to end * the drawing operation. */ if (_self.mouse.buttonDown) { return false; } _self.mouse.buttonDown = true; break; case 'mouseup': // Skip the event if the mouse button was not down. if (!_self.mouse.buttonDown) { return false; } _self.mouse.buttonDown = false; } /* * Update the event, to include the mouse position, relative to the canvas * element. */ if ('layerX' in ev) { if (_self.image.canvasScale === 1) { _self.mouse.x = ev.layerX; _self.mouse.y = ev.layerY; } else { _self.mouse.x = MathRound(ev.layerX / _self.image.canvasScale); _self.mouse.y = MathRound(ev.layerY / _self.image.canvasScale); } } else if ('offsetX' in ev) { if (_self.image.canvasScale === 1) { _self.mouse.x = ev.offsetX; _self.mouse.y = ev.offsetY; } else { _self.mouse.x = MathRound(ev.offsetX / _self.image.canvasScale); _self.mouse.y = MathRound(ev.offsetY / _self.image.canvasScale); } } // The event handler of the current tool. if (ev.type in _self.tool && _self.tool[ev.type](ev)) { ev.preventDefault(); return true; } else { return false; } }; /** * The global keyboard events handler. This makes all the keyboard shortcuts * work in the web application. * * <p>This method determines the key the user pressed, based on the * <var>ev</var> DOM Event object, taking into consideration any browser * differences. Two new properties are added to the <var>ev</var> object: * * <ul> * <li><var>ev.kid_</var> is a string holding the key and the modifiers list * (<kbd>Control</kbd>, <kbd>Alt</kbd> and/or <kbd>Shift</kbd>). For * example, if the user would press the key <kbd>A</kbd> while holding down * <kbd>Control</kbd>, then <var>ev.kid_</var> would be "Control A". If the * user would press "9" while holding down <kbd>Shift</kbd>, then * <var>ev.kid_</var> would be "Shift 9". * * <li><var>ev.kobj_</var> holds a reference to the keyboard shortcut * definition object from the configuration. This is useful for reuse, for * passing parameters from the keyboard shortcut configuration object to the * event handler. * </ul> * * <p>In {@link PaintWeb.config.keys} one can setup the keyboard shortcuts. * If the keyboard combination is found in that list, then the associated tool * is activated. * * <p>Note: this method includes some work-around for making the image zoom * keys work well both in Opera and Firefox. * * @private * * @param {Event} ev The DOM Event object. * * @see PaintWeb.config.keys The keyboard shortcuts configuration. * @see pwlib.dom.KeyboardEventListener The class dealing with the * cross-browser differences in the DOM keyboard events. */ this.ev_keyboard = function (ev) { // Do not continue if the key was not recognized by the lib. if (!ev.key_) { return; } if (ev.target && ev.target.nodeName) { switch (ev.target.nodeName.toLowerCase()) { case 'input': if (ev.type === 'keypress' && (ev.key_ === 'Up' || ev.key_ === 'Down') && ev.target.getAttribute('type') === 'number') { _self.ev_numberInput(ev); } case 'select': case 'textarea': case 'button': return; } } // Rather ugly, but the only way, at the moment, to detect these keys in // Opera and Firefox. if (ev.type === 'keypress' && ev.char_) { var isZoomKey = true, imageZoomKeys = _self.config.imageZoomKeys; // Check if this is a zoom key and execute the commands as needed. switch (ev.char_) { case imageZoomKeys['in']: _self.imageZoomIn(ev); break; case imageZoomKeys['out']: _self.imageZoomOut(ev); break; case imageZoomKeys['reset']: _self.imageZoomReset(ev); break; default: isZoomKey = false; } if (isZoomKey) { ev.preventDefault(); return; } } // Determine the key ID. ev.kid_ = ''; var i, kmods = {altKey: 'Alt', ctrlKey: 'Control', shiftKey: 'Shift'}; for (i in kmods) { if (ev[i] && ev.key_ !== kmods[i]) { ev.kid_ += kmods[i] + ' '; } } ev.kid_ += ev.key_; // Send the keyboard event to the event handler of the active tool. If it // returns true, we consider it recognized the keyboard shortcut. if (_self.tool && ev.type in _self.tool && _self.tool[ev.type](ev)) { return true; } // If there's no event handler within the active tool, or if the event // handler does otherwise return false, then we continue with the global // keyboard shortcuts. var gkey = _self.config.keys[ev.kid_]; if (!gkey) { return false; } ev.kobj_ = gkey; // Check if the keyboard shortcut has some extension associated. if ('extension' in gkey) { var extension = _self.extensions[gkey.extension], method = gkey.method || ev.type; // Call the extension method. if (method in extension) { extension[method].call(this, ev); } } else if ('command' in gkey && gkey.command in _self.commands) { // Invoke the command associated with the key. _self.commands[gkey.command].call(this, ev); } else if (ev.type === 'keydown' && 'toolActivate' in gkey) { // Active the tool associated to the key. _self.toolActivate(gkey.toolActivate, ev); } if (ev.type === 'keypress') { ev.preventDefault(); } }; /** * This is the <code>keypress</code> event handler for inputs of type=number. * This function only handles cases when the key is <kbd>Up</kbd> or * <kbd>Down</kbd>. For the <kbd>Up</kbd> key the input value is increased, * and for the <kbd>Down</kbd> the value is decreased. * * @private * @param {Event} ev The DOM Event object. * @see PaintWeb#ev_keyboard */ this.ev_numberInput = function (ev) { var target = ev.target; // Process the value. var val, max = parseFloat(target.getAttribute('max')), min = parseFloat(target.getAttribute('min')), step = parseFloat(target.getAttribute('step')); if (target.value === '' || target.value === null) { val = !isNaN(min) ? min : 0; } else { val = parseFloat(target.value.replace(/[,.]+/g, '.'). replace(/[^0-9.\-]/g, '')); } // If target is not a number, then set the old value, or the minimum value. If all fails, set 0. if (isNaN(val)) { val = min || 0; } if (isNaN(step)) { step = 1; } if (ev.shiftKey) { step *= 2; } if (ev.key_ === 'Down') { step *= -1; } val += step; if (!isNaN(max) && val > max) { val = max; } else if (!isNaN(min) && val < min) { val = min; } if (val == target.value) { return; } target.value = val; // Dispatch the 'change' events to make sure that any associated event // handlers pick up the changes. if (doc.createEvent && target.dispatchEvent) { var ev_change = doc.createEvent('HTMLEvents'); ev_change.initEvent('change', true, true); target.dispatchEvent(ev_change); } }; /** * Zoom into the image. * * @param {mixed} ev An event object which might have the <var>shiftKey</var> * property. If the property evaluates to true, then the zoom level will * increase twice more than normal. * * @returns {Boolean} True if the operation was successful, or false if not. * * @see PaintWeb#imageZoomTo The method used for changing the zoom level. * @see PaintWeb.config.zoomStep The value used for increasing the zoom level. */ this.imageZoomIn = function (ev) { if (ev && ev.shiftKey) { _self.config.imageZoomStep *= 2; } var res = _self.imageZoomTo('+'); if (ev && ev.shiftKey) { _self.config.imageZoomStep /= 2; } return res; }; /** * Zoom out of the image. * * @param {mixed} ev An event object which might have the <var>shiftKey</var> * property. If the property evaluates to true, then the zoom level will * decrease twice more than normal. * * @returns {Boolean} True if the operation was successful, or false if not. * * @see PaintWeb#imageZoomTo The method used for changing the zoom level. * @see PaintWeb.config.zoomStep The value used for decreasing the zoom level. */ this.imageZoomOut = function (ev) { if (ev && ev.shiftKey) { _self.config.imageZoomStep *= 2; } var res = _self.imageZoomTo('-'); if (ev && ev.shiftKey) { _self.config.imageZoomStep /= 2; } return res; }; /** * Reset the image zoom level to normal. * * @returns {Boolean} True if the operation was successful, or false if not. * * @see PaintWeb#imageZoomTo The method used for changing the zoom level. */ this.imageZoomReset = function (ev) { return _self.imageZoomTo(1); }; /** * Change the image zoom level. * * <p>This method dispatches the {@link pwlib.appEvent.imageZoom} application * event before zooming the image. Once the image zoom is applied, the {@link * pwlib.appEvent.canvasSizeChange} event is dispatched. * * @param {Number|String} level The level you want to zoom the image to. * * <p>If the value is a number, it must be a floating point positive number, * where 0.5 means 50%, 1 means 100% (normal) zoom, 4 means 400% and so on. * * <p>If the value is a string it must be "+" or "-". This means that the zoom * level will increase/decrease using the configured {@link * PaintWeb.config.zoomStep}. * * @returns {Boolean} True if the image zoom level changed successfully, or * false if not. */ this.imageZoomTo = function (level) { var image = this.image, config = this.config, res = this.resolution; if (!level) { return false; } else if (level === '+') { level = image.zoom + config.imageZoomStep; } else if (level === '-') { level = image.zoom - config.imageZoomStep; } else if (typeof level !== 'number') { return false; } if (level > config.imageZoomMax) { level = config.imageZoomMax; } else if (level < config.imageZoomMin) { level = config.imageZoomMin; } if (level === image.zoom) { return true; } var cancel = this.events.dispatch(new appEvent.imageZoom(level)); if (cancel) { return false; } var styleWidth = image.width / res.scale * level, styleHeight = image.height / res.scale * level, bufferStyle = this.buffer.canvas.style, layerStyle = this.layer.canvas.style; image.canvasScale = styleWidth / image.width; // FIXME: MSIE 9 clears the Canvas element when you change the // elem.style.width/height... *argh* bufferStyle.width = layerStyle.width = styleWidth + 'px'; bufferStyle.height = layerStyle.height = styleHeight + 'px'; image.zoom = level; this.events.dispatch(new appEvent.canvasSizeChange(styleWidth, styleHeight, image.canvasScale)); return true; }; /** * Crop the image. * * <p>The content of the image is retained only if the browser implements the * <code>getImageData</code> and <code>putImageData</code> methods. * * <p>This method dispatches three application events: {@link * pwlib.appEvent.imageSizeChange}, {@link pwlib.appEvent.canvasSizeChange} * and {@link pwlib.appEvent.imageCrop}. The <code>imageCrop</code> event is * dispatched before the image is cropped. The <code>imageSizeChange</code> * and <code>canvasSizeChange</code> events are dispatched after the image is * cropped. * * @param {Number} cropX Image cropping start position on the x-axis. * @param {Number} cropY Image cropping start position on the y-axis. * @param {Number} cropWidth Image crop width. * @param {Number} cropHeight Image crop height. * * @returns {Boolean} True if the image was cropped successfully, or false if * not. */ this.imageCrop = function (cropX, cropY, cropWidth, cropHeight) { var bufferCanvas = this.buffer.canvas, bufferContext = this.buffer.context, image = this.image, layerCanvas = this.layer.canvas, layerContext = this.layer.context; cropX = parseInt(cropX); cropY = parseInt(cropY); cropWidth = parseInt(cropWidth); cropHeight = parseInt(cropHeight); if (!cropWidth || !cropHeight || isNaN(cropX) || isNaN(cropY) || isNaN(cropWidth) || isNaN(cropHeight) || cropX >= image.width || cropY >= image.height) { return false; } var cancel = this.events.dispatch(new appEvent.imageCrop(cropX, cropY, cropWidth, cropHeight)); if (cancel) { return false; } if (cropWidth > this.config.imageWidthMax) { cropWidth = this.config.imageWidthMax; } if (cropHeight > this.config.imageHeightMax) { cropHeight = this.config.imageHeightMax; } if (cropX === 0 && cropY === 0 && image.width === cropWidth && image.height === cropHeight) { return true; } var layerData = null, bufferData = null, layerState = this.stateSave(layerContext), bufferState = this.stateSave(bufferContext), scaledWidth = cropWidth * image.canvasScale, scaledHeight = cropHeight * image.canvasScale, dataWidth = MathMin(image.width, cropWidth), dataHeight = MathMin(image.height, cropHeight), sumX = cropX + dataWidth, sumY = cropY + dataHeight; if (sumX > image.width) { dataWidth -= sumX - image.width; } if (sumY > image.height) { dataHeight -= sumY - image.height; } if (layerContext.getImageData) { // TODO: handle "out of memory" errors. try { layerData = layerContext.getImageData(cropX, cropY, dataWidth, dataHeight); } catch (err) { } } if (bufferContext.getImageData) { try { bufferData = bufferContext.getImageData(cropX, cropY, dataWidth, dataHeight); } catch (err) { } } bufferCanvas.style.width = layerCanvas.style.width = scaledWidth + 'px'; bufferCanvas.style.height = layerCanvas.style.height = scaledHeight + 'px'; layerCanvas.width = cropWidth; layerCanvas.height = cropHeight; if (layerData && layerContext.putImageData) { layerContext.putImageData(layerData, 0, 0); } this.stateRestore(layerContext, layerState); state = this.stateSave(bufferContext); bufferCanvas.width = cropWidth; bufferCanvas.height = cropHeight; if (bufferData && bufferContext.putImageData) { bufferContext.putImageData(bufferData, 0, 0); } this.stateRestore(bufferContext, bufferState); image.width = cropWidth; image.height = cropHeight; bufferState = layerState = layerData = bufferData = null; this.events.dispatch(new appEvent.imageSizeChange(cropWidth, cropHeight)); this.events.dispatch(new appEvent.canvasSizeChange(scaledWidth, scaledHeight, image.canvasScale)); return true; }; /** * Save the state of a Canvas context. * * @param {CanvasRenderingContext2D} context The 2D context of the Canvas * element you want to save the state. * * @returns {Object} The object has all the state properties and values. */ this.stateSave = function (context) { if (!context || !context.canvas || !this.stateProperties) { return false; } var stateObj = {}, prop = null, n = this.stateProperties.length; for (var i = 0; i < n; i++) { prop = this.stateProperties[i]; stateObj[prop] = context[prop]; } return stateObj; }; /** * Restore the state of a Canvas context. * * @param {CanvasRenderingContext2D} context The 2D context where you want to * restore the state. * * @param {Object} stateObj The state object saved by the {@link * PaintWeb#stateSave} method. * * @returns {Boolean} True if the operation was successful, or false if not. */ this.stateRestore = function (context, stateObj) { if (!context || !context.canvas) { return false; } for (var state in stateObj) { context[state] = stateObj[state]; } return true; }; /** * Allow shadows. This method re-enabled shadow rendering, if it was enabled * before shadows were disallowed. * * <p>The {@link pwlib.appEvent.shadowAllow} event is dispatched. */ this.shadowAllow = function () { if (this.shadowAllowed || !this.shadowSupported) { return; } // Note that some daily builds of Webkit in Chromium fail to render the // shadow when context.drawImage() is used (see the this.layerUpdate()). var context = this.layer.context, cfg = this.config.shadow; if (cfg.enable) { context.shadowColor = cfg.shadowColor; context.shadowOffsetX = cfg.shadowOffsetX; context.shadowOffsetY = cfg.shadowOffsetY; context.shadowBlur = cfg.shadowBlur; } this.shadowAllowed = true; this.events.dispatch(new appEvent.shadowAllow(true)); }; /** * Disallow shadows. This method disables shadow rendering, if it is enabled. * * <p>The {@link pwlib.appEvent.shadowAllow} event is dispatched. */ this.shadowDisallow = function () { if (!this.shadowAllowed || !this.shadowSupported) { return; } if (this.config.shadow.enable) { var context = this.layer.context; context.shadowColor = 'rgba(0,0,0,0)'; context.shadowOffsetX = 0; context.shadowOffsetY = 0; context.shadowBlur = 0; } this.shadowAllowed = false; this.events.dispatch(new appEvent.shadowAllow(false)); }; /** * Update the current image layer by moving the pixels from the buffer onto * the layer. This method also adds a point into the history. * * @returns {Boolean} True if the operation was successful, or false if not. */ this.layerUpdate = function () { this.layer.context.drawImage(this.buffer.canvas, 0, 0); this.buffer.context.clearRect(0, 0, this.image.width, this.image.height); this.historyAdd(); return true; }; /** * Add the current image layer to the history. * * <p>Once the history state has been updated, this method dispatches the * {@link pwlib.appEvent.historyUpdate} event. * * @returns {Boolean} True if the operation was successful, or false if not. */ // TODO: some day it would be nice to implement a hybrid history system. this.historyAdd = function () { var layerContext = this.layer.context, history = this.history, prevPos = history.pos; if (!layerContext.getImageData) { return false; } // We are in an undo-step, trim until the end, eliminating any possible redo-steps. if (prevPos < history.states.length) { history.states.splice(prevPos, history.states.length); } // TODO: in case of "out of memory" errors... I should show up some error. try { history.states.push(layerContext.getImageData(0, 0, this.image.width, this.image.height)); } catch (err) { return false; } // If we have too many history ImageDatas, remove the oldest ones if ('historyLimit' in this.config && history.states.length > this.config.historyLimit) { history.states.splice(0, history.states.length - this.config.historyLimit); } history.pos = history.states.length; this.image.modified = true; this.events.dispatch(new appEvent.historyUpdate(history.pos, prevPos, history.pos)); return true; }; /** * Jump to any ImageData/position in the history. * * <p>Once the history state has been updated, this method dispatches the * {@link pwlib.appEvent.historyUpdate} event. * * @param {Number|String} pos The history position to jump to. * * <p>If the value is a number, then it must point to an existing index in the * <var>{@link PaintWeb#history}.states</var> array. * * <p>If the value is a string, it must be "undo" or "redo". * * @returns {Boolean} True if the operation was successful, or false if not. */ this.historyGoto = function (pos) { var layerContext = this.layer.context, image = this.image, history = this.history; if (!history.states.length || !layerContext.putImageData) { return false; } var cpos = history.pos; if (pos === 'undo') { pos = cpos-1; } else if (pos === 'redo') { pos = cpos+1; } if (pos < 1 || pos > history.states.length) { return false; } var himg = history.states[pos-1]; if (!himg) { return false; } // Each image in the history can have a different size. As such, the script // must take this into consideration. var w = MathMin(image.width, himg.width), h = MathMin(image.height, himg.height); layerContext.clearRect(0, 0, image.width, image.height); try { // Firefox 3 does not clip the image, if needed. layerContext.putImageData(himg, 0, 0, 0, 0, w, h); } catch (err) { // The workaround is to use a new canvas from which we can copy the // history image without causing any exceptions. var tmp = doc.createElement('canvas'); tmp.width = himg.width; tmp.height = himg.height; var tmp2 = tmp.getContext('2d'); tmp2.putImageData(himg, 0, 0); layerContext.drawImage(tmp, 0, 0); tmp2 = tmp = null; delete tmp2, tmp; } history.pos = pos; this.events.dispatch(new appEvent.historyUpdate(pos, cpos, history.states.length)); return true; }; /** * Clear the image history. * * <p>This method dispatches the {@link pwlib.appEvent.historyUpdate} event. * * @private */ this.historyReset = function () { this.history.pos = 0; this.history.states = []; this.events.dispatch(new appEvent.historyUpdate(0, 0, 0)); }; /** * Perform horizontal/vertical line snapping. This method updates the mouse * coordinates to "snap" with the given coordinates. * * @param {Number} x The x-axis location. * @param {Number} y The y-axis location. */ this.toolSnapXY = function (x, y) { var diffx = MathAbs(_self.mouse.x - x), diffy = MathAbs(_self.mouse.y - y); if (diffx > diffy) { _self.mouse.y = y; } else { _self.mouse.x = x; } }; /** * Activate a drawing tool by ID. * * <p>The <var>id</var> provided must be of an existing drawing tool, one that * has been installed. * * <p>The <var>ev</var> argument is an optional DOM Event object which is * useful when dealing with different types of tool activation, either by * keyboard or by mouse events. Tool-specific code can implement different * functionality based on events. * * <p>This method dispatches the {@link pwlib.appEvent.toolPreactivate} event * before creating the new tool instance. Once the new tool is successfully * activated, the {@link pwlib.appEvent.toolActivate} event is also * dispatched. * * @param {String} id The ID of the drawing tool to be activated. * @param {Event} [ev] The DOM Event object. * * @returns {Boolean} True if the tool has been activated, or false if not. * * @see PaintWeb#toolRegister Register a new drawing tool. * @see PaintWeb#toolUnregister Unregister a drawing tool. * * @see pwlib.tools The object holding all the drawing tools. * @see pwlib.appEvent.toolPreactivate * @see pwlib.appEvent.toolActivate */ this.toolActivate = function (id, ev) { if (!id || !(id in pwlib.tools) || typeof pwlib.tools[id] !== 'function') { return false; } var tool = pwlib.tools[id], prevId = this.tool ? this.tool._id : null; if (prevId && this.tool instanceof pwlib.tools[id]) { return true; } var cancel = this.events.dispatch(new appEvent.toolPreactivate(id, prevId)); if (cancel) { return false; } var tool_obj = new tool(this, ev); if (!tool_obj) { return false; } /* * Each tool can implement its own mouse and keyboard events handler. * Additionally, tool objects can implement handlers for the deactivation * and activation events. * Given tool1 is active and tool2 is going to be activated, then the * following event handlers will be called: * * tool2.preActivate * tool1.deactivate * tool2.activate * * In the "preActivate" event handler you can cancel the tool activation by * returning a value which evaluates to false. */ if ('preActivate' in tool_obj && !tool_obj.preActivate(ev)) { tool_obj = null; return false; } // Deactivate the previously active tool if (this.tool && 'deactivate' in this.tool) { this.tool.deactivate(ev); } this.tool = tool_obj; this.mouse.buttonDown = false; // Besides the "constructor", each tool can also have code which is run // after the deactivation of the previous tool. if ('activate' in this.tool) { this.tool.activate(ev); } this.events.dispatch(new appEvent.toolActivate(id, prevId)); return true; }; /** * Register a new drawing tool into PaintWeb. * * <p>This method dispatches the {@link pwlib.appEvent.toolRegister} * application event. * * @param {String} id The ID of the new tool. The tool object must exist in * {@link pwlib.tools}. * * @returns {Boolean} True if the tool was successfully registered, or false * if not. * * @see PaintWeb#toolUnregister allows you to unregister tools. * @see pwlib.tools Holds all the drawing tools. * @see pwlib.appEvent.toolRegister */ this.toolRegister = function (id) { if (typeof id !== 'string' || !id) { return false; } // TODO: it would be very nice to create the tool instance on register, for // further extensibility. var tool = pwlib.tools[id]; if (typeof tool !== 'function') { return false; } tool.prototype._id = id; this.events.dispatch(new appEvent.toolRegister(id)); if (!this.tool && id === this.config.toolDefault) { return this.toolActivate(id); } else { return true; } }; /** * Unregister a drawing tool from PaintWeb. * * <p>This method dispatches the {@link pwlib.appEvent.toolUnregister} * application event. * * @param {String} id The ID of the tool you want to unregister. * * @returns {Boolean} True if the tool was unregistered, or false if it does * not exist or some error occurred. * * @see PaintWeb#toolRegister allows you to register new drawing tools. * @see pwlib.tools Holds all the drawing tools. * @see pwlib.appEvent.toolUnregister */ this.toolUnregister = function (id) { if (typeof id !== 'string' || !id || !(id in pwlib.tools)) { return false; } this.events.dispatch(new appEvent.toolUnregister(id)); return true; }; /** * Register a new extension into PaintWeb. * * <p>If the extension object being constructed has the * <code>extensionRegister()</code> method, then it will be invoked, allowing * any custom extension registration code to run. If the method returns false, * then the extension will not be registered. * * <p>Once the extension is successfully registered, this method dispatches * the {@link pwlib.appEvent.extensionRegister} application event. * * @param {String} id The ID of the new extension. The extension object * constructor must exist in {@link pwlib.extensions}. * * @returns {Boolean} True if the extension was successfully registered, or * false if not. * * @see PaintWeb#extensionUnregister allows you to unregister extensions. * @see PaintWeb#extensions Holds all the instances of registered extensions. * @see pwlib.extensions Holds all the extension classes. */ this.extensionRegister = function (id) { if (typeof id !== 'string' || !id) { return false; } var func = pwlib.extensions[id]; if (typeof func !== 'function') { return false; } func.prototype._id = id; var obj = new func(_self); if ('extensionRegister' in obj && !obj.extensionRegister()) { return false; } this.extensions[id] = obj; this.events.dispatch(new appEvent.extensionRegister(id)); return true; }; /** * Unregister an extension from PaintWeb. * * <p>If the extension object being destructed has the * <code>extensionUnregister()</code> method, then it will be invoked, * allowing any custom extension removal code to run. * * <p>Before the extension is unregistered, this method dispatches the {@link * pwlib.appEvent.extensionUnregister} application event. * * @param {String} id The ID of the extension object you want to unregister. * * @returns {Boolean} True if the extension was removed, or false if it does * not exist or some error occurred. * * @see PaintWeb#extensionRegister allows you to register new extensions. * @see PaintWeb#extensions Holds all the instances of registered extensions. * @see pwlib.extensions Holds all the extension classes. */ this.extensionUnregister = function (id) { if (typeof id !== 'string' || !id || !(id in this.extensions)) { return false; } this.events.dispatch(new appEvent.extensionUnregister(id)); if ('extensionUnregister' in this.extensions[id]) { this.extensions[id].extensionUnregister(); } delete this.extensions[id]; return true; }; /** * Register a new command in PaintWeb. Commands are simple function objects * which can be invoked by keyboard shortcuts or by GUI elements. * * <p>Once the command is successfully registered, this method dispatches the * {@link pwlib.appEvent.commandRegister} application event. * * @param {String} id The ID of the new command. * @param {Function} func The command function. * * @returns {Boolean} True if the command was successfully registered, or * false if not. * * @see PaintWeb#commandUnregister allows you to unregister commands. * @see PaintWeb#commands Holds all the registered commands. */ this.commandRegister = function (id, func) { if (typeof id !== 'string' || !id || typeof func !== 'function' || id in this.commands) { return false; } this.commands[id] = func; this.events.dispatch(new appEvent.commandRegister(id)); return true; }; /** * Unregister a command from PaintWeb. * * <p>Before the command is unregistered, this method dispatches the {@link * pwlib.appEvent.commandUnregister} application event. * * @param {String} id The ID of the command you want to unregister. * * @returns {Boolean} True if the command was removed successfully, or false * if not. * * @see PaintWeb#commandRegister allows you to register new commands. * @see PaintWeb#commands Holds all the registered commands. */ this.commandUnregister = function (id) { if (typeof id !== 'string' || !id || !(id in this.commands)) { return false; } this.events.dispatch(new appEvent.commandUnregister(id)); delete this.commands[id]; return true; }; /** * Load a script into the document. * * @param {String} url The script URL you want to insert. * @param {Function} [handler] The <code>load</code> event handler you want. */ this.scriptLoad = function (url, handler) { if (!handler) { var elem = doc.createElement('script'); elem.type = 'text/javascript'; elem.src = url; this.elems.head.appendChild(elem); return; } // huh, use XHR then eval() the code. // browsers do not dispatch the 'load' event reliably for script elements. /** @ignore */ var xhr = new XMLHttpRequest(); /** @ignore */ xhr.onreadystatechange = function () { if (!xhr || xhr.readyState !== 4) { return; } else if ((xhr.status !== 304 && xhr.status !== 200) || !xhr.responseText) { handler(false, xhr); } else { try { eval.call(win, xhr.responseText); } catch (err) { eval(xhr.responseText, win); } handler(true, xhr); } xhr = null; }; xhr.open('GET', url); xhr.send(''); }; /** * Insert a stylesheet into the document. * * @param {String} id The stylesheet ID. This is used to avoid inserting the * same style in the document. * @param {String} url The URL of the stylesheet you want to insert. * @param {String} [media='screen, projection'] The media attribute. * @param {Function} [handler] The <code>load</code> event handler. */ this.styleLoad = function (id, url, media, handler) { id = 'paintweb_style_' + id; var elem = doc.getElementById(id); if (elem) { return; } if (!media) { media = 'screen, projection'; } elem = doc.createElement('link'); if (handler) { elem.addEventListener('load', handler, false); } elem.id = id; elem.rel = 'stylesheet'; elem.type = 'text/css'; elem.media = media; elem.href = url; this.elems.head.appendChild(elem); }; /** * Perform action undo. * * @returns {Boolean} True if the operation was successful, or false if not. * * @see PaintWeb#historyGoto The method invoked by this command. */ this.historyUndo = function () { return _self.historyGoto('undo'); }; /** * Perform action redo. * * @returns {Boolean} True if the operation was successful, or false if not. * * @see PaintWeb#historyGoto The method invoked by this command. */ this.historyRedo = function () { return _self.historyGoto('redo'); }; /** * Load an image. By loading an image the history is cleared and the Canvas * dimensions are updated to fit the new image. * * <p>This method dispatches two application events: {@link * pwlib.appEvent.imageSizeChange} and {@link * pwlib.appEvent.canvasSizeChange}. * * @param {Element} importImage The image element you want to load into the * Canvas. * * @returns {Boolean} True if the operation was successful, or false if not. */ this.imageLoad = function (importImage) { if (!importImage || !importImage.width || !importImage.height || importImage.nodeType !== this.ELEMENT_NODE || !pwlib.isSameHost(importImage.src, win.location.host)) { return false; } this.historyReset(); var layerContext = this.layer.context, layerCanvas = this.layer.canvas, layerStyle = layerCanvas.style, bufferCanvas = this.buffer.canvas, bufferStyle = bufferCanvas.style, image = this.image, styleWidth = importImage.width * image.canvasScale, styleHeight = importImage.height * image.canvasScale, result = true; bufferCanvas.width = layerCanvas.width = importImage.width; bufferCanvas.height = layerCanvas.height = importImage.height; bufferStyle.width = layerStyle.width = styleWidth + 'px'; bufferStyle.height = layerStyle.height = styleHeight + 'px'; try { layerContext.drawImage(importImage, 0, 0); } catch (err) { result = false; bufferCanvas.width = layerCanvas.width = image.width; bufferCanvas.height = layerCanvas.height = image.height; styleWidth = image.width * image.canvasScale; styleHeight = image.height * image.canvasScale; bufferStyle.width = layerStyle.width = styleWidth + 'px'; bufferStyle.height = layerStyle.height = styleHeight + 'px'; } if (result) { image.width = importImage.width; image.height = importImage.height; _self.config.imageLoad = importImage; this.events.dispatch(new appEvent.imageSizeChange(image.width, image.height)); this.events.dispatch(new appEvent.canvasSizeChange(styleWidth, styleHeight, image.canvasScale)); } this.historyAdd(); image.modified = false; return result; }; /** * Clear the image. */ this.imageClear = function (ev) { var layerContext = _self.layer.context, image = _self.image; layerContext.clearRect(0, 0, image.width, image.height); // Set the configured background color. var fillStyle = layerContext.fillStyle; layerContext.fillStyle = _self.config.backgroundColor; layerContext.fillRect(0, 0, image.width, image.height); layerContext.fillStyle = fillStyle; _self.historyAdd(); }; /** * Save the image. * * <p>This method dispatches the {@link pwlib.appEvent.imageSave} event. * * <p><strong>Note:</strong> the "Save image" operation relies on integration * extensions. A vanilla configuration of PaintWeb will simply open the the * image in a new tab using a data: URL. You must have some event listener for * the <code>imageSave</code> event and you must prevent the default action. * * <p>If the default action for the <code>imageSave</code> application event * is not prevented, then this method will also dispatch the {@link * pwlib.appEvent.imageSaveResult} application event. * * <p>Your event handler for the <code>imageSave</code> event must dispatch * the <code>imageSaveResult</code> event. * * @param {String} [type="auto"] Image MIME type. This tells the browser which * format to use when saving the image. If the image format type is not * supported, then the image is saved as PNG. * * <p>You can use the resulting data URL to check which is the actual image * format. * * <p>When <var>type</var> is "auto" then PaintWeb checks the type of the * image currently loaded ({@link PaintWeb.config.imageLoad}). If the format * is recognized, then the same format is used to save the image. * * @returns {Boolean} True if the operation was successful, or false if not. */ this.imageSave = function (type) { var canvas = _self.layer.canvas, cfg = _self.config, img = _self.image, imageLoad = _self.config.imageLoad, ext = 'png', idata = null, src = null, pos; if (!canvas.toDataURL) { return false; } var extMap = {'jpg' : 'image/jpeg', 'jpeg' : 'image/jpeg', 'png' : 'image/png', 'gif' : 'image/gif'}; // Detect the MIME type of the image currently loaded. if (typeof type !== 'string' || !type) { if (imageLoad && imageLoad.src && imageLoad.src.substr(0, 5) !== 'data:') { src = imageLoad.src; pos = src.indexOf('?'); if (pos !== -1) { src = src.substr(0, pos); } ext = src.substr(src.lastIndexOf('.') + 1).toLowerCase(); } type = extMap[ext] || 'image/png'; } // We consider that other formats than PNG do not support transparencies. // Thus, we create a new Canvas element for which we set the configured // background color, and we render the image onto it. if (type !== 'image/png') { canvas = doc.createElement('canvas'); var context = canvas.getContext('2d'); canvas.width = img.width; canvas.height = img.height; context.fillStyle = cfg.backgroundColor; context.fillRect(0, 0, img.width, img.height); context.drawImage(_self.layer.canvas, 0, 0); context = null; } try { // canvas.toDataURL('image/jpeg', quality) fails in Gecko due to security // concerns, uh-oh. if (type === 'image/jpeg' && !pwlib.browser.gecko) { idata = canvas.toDataURL(type, cfg.jpegSaveQuality); } else { idata = canvas.toDataURL(type); } } catch (err) { alert(lang.errorImageSave + "\n" + err); return false; } canvas = null; if (!idata || idata === 'data:,') { return false; } var ev = new appEvent.imageSave(idata, img.width, img.height), cancel = _self.events.dispatch(ev); if (cancel) { return true; } var imgwin = _self.win.open(); if (!imgwin) { return false; } imgwin.location = idata; idata = null; _self.events.dispatch(new appEvent.imageSaveResult(true)); return true; }; /** * The <code>imageSaveResult</code> application event handler. This method * PaintWeb-related stuff: for example, the {@link PaintWeb.image.modified} * flag is turned to false. * * @private * * @param {pwlib.appEvent.imageSaveResult} ev The application event object. * * @see {PaintWeb#imageSave} The method which allows you to save the image. */ this.imageSaveResultHandler = function (ev) { if (ev.successful) { _self.image.modified = false; } }; /** * Swap the fill and stroke styles. This is just like in Photoshop, if the * user presses X, the fill/stroke colors are swapped. * * <p>This method dispatches the {@link pwlib.appEvent.configChange} event * twice for each color (strokeStyle and fillStyle). */ this.swapFillStroke = function () { var fillStyle = _self.config.fillStyle, strokeStyle = _self.config.strokeStyle; _self.config.fillStyle = strokeStyle; _self.config.strokeStyle = fillStyle; var ev = new appEvent.configChange(strokeStyle, fillStyle, 'fillStyle', '', _self.config); _self.events.dispatch(ev); ev = new appEvent.configChange(fillStyle, strokeStyle, 'strokeStyle', '', _self.config); _self.events.dispatch(ev); }; /** * Select all the pixels. This activates the selection tool, and selects the * entire image. * * @param {Event} [ev] The DOM Event object which generated the request. * @returns {Boolean} True if the operation was successful, or false if not. * * @see {pwlib.tools.selection.selectAll} The command implementation. */ this.selectAll = function (ev) { if (_self.toolActivate('selection', ev)) { return _self.tool.selectAll(ev); } else { return false; } }; /** * Cut the available selection. This only works when the selection tool is * active and when some selection is available. * * @param {Event} [ev] The DOM Event object which generated the request. * @returns {Boolean} True if the operation was successful, or false if not. * * @see {pwlib.tools.selection.selectionCut} The command implementation. */ this.selectionCut = function (ev) { if (!_self.tool || _self.tool._id !== 'selection') { return false; } else { return _self.tool.selectionCut(ev); } }; /** * Copy the available selection. This only works when the selection tool is * active and when some selection is available. * * @param {Event} [ev] The DOM Event object which generated the request. * @returns {Boolean} True if the operation was successful, or false if not. * * @see {pwlib.tools.selection.selectionCopy} The command implementation. */ this.selectionCopy = function (ev) { if (!_self.tool || _self.tool._id !== 'selection') { return false; } else { return _self.tool.selectionCopy(ev); } }; /** * Paste the current clipboard image. This only works when some ImageData is * available in {@link PaintWeb#clipboard}. * * @param {Event} [ev] The DOM Event object which generated the request. * @returns {Boolean} True if the operation was successful, or false if not. * * @see {pwlib.tools.selection.clipboardPaste} The command implementation. */ this.clipboardPaste = function (ev) { if (!_self.clipboard || !_self.toolActivate('selection', ev)) { return false; } else { return _self.tool.clipboardPaste(ev); } }; /** * The <code>configChange</code> application event handler. This method * updates the Canvas context properties depending on which configuration * property changed. * * @private * @param {pwlib.appEvent.configChange} ev The application event object. */ this.configChangeHandler = function (ev) { if (ev.group === 'shadow' && _self.shadowSupported && _self.shadowAllowed) { var context = _self.layer.context, cfg = ev.groupRef; // Enable/disable shadows if (ev.config === 'enable') { if (ev.value) { context.shadowColor = cfg.shadowColor; context.shadowOffsetX = cfg.shadowOffsetX; context.shadowOffsetY = cfg.shadowOffsetY; context.shadowBlur = cfg.shadowBlur; } else { context.shadowColor = 'rgba(0,0,0,0)'; context.shadowOffsetX = 0; context.shadowOffsetY = 0; context.shadowBlur = 0; } return; } // Do not update any context properties if shadows are not enabled. if (!cfg.enable) { return; } switch (ev.config) { case 'shadowBlur': case 'shadowOffsetX': case 'shadowOffsetY': ev.value = parseInt(ev.value); case 'shadowColor': context[ev.config] = ev.value; } } else if (ev.group === 'line') { switch (ev.config) { case 'lineWidth': case 'miterLimit': ev.value = parseInt(ev.value); case 'lineJoin': case 'lineCap': _self.buffer.context[ev.config] = ev.value; } } else if (ev.group === 'text') { switch (ev.config) { case 'textAlign': case 'textBaseline': _self.buffer.context[ev.config] = ev.value; } } else if (!ev.group) { switch (ev.config) { case 'fillStyle': case 'strokeStyle': _self.buffer.context[ev.config] = ev.value; } } }; /** * Destroy a PaintWeb instance. This method allows you to unload a PaintWeb * instance. Extensions, tools and commands are unregistered, and the GUI * elements are removed. * * <p>The scripts and styles loaded are not removed, since they might be used * by other PaintWeb instances. * * <p>The {@link pwlib.appEvent.appDestroy} application event is dispatched * before the current instance is destroyed. */ this.destroy = function () { this.events.dispatch(new appEvent.appDestroy()); for (var cmd in this.commands) { this.commandUnregister(cmd); } for (var ext in this.extensions) { this.extensionUnregister(ext); } for (var tool in this.gui.tools) { this.toolUnregister(tool); } this.gui.destroy(); this.initialized = PaintWeb.INIT_NOT_STARTED; }; this.toString = function () { return 'PaintWeb v' + this.version + ' (build ' + this.build + ')'; }; preInit(); }; /** * Application initialization not started. * @constant */ PaintWeb.INIT_NOT_STARTED = 0; /** * Application initialization started. * @constant */ PaintWeb.INIT_STARTED = 1; /** * Application initialization completed successfully. * @constant */ PaintWeb.INIT_DONE = 2; /** * Application initialization failed. * @constant */ PaintWeb.INIT_ERROR = -1; /** * PaintWeb base folder. This is determined automatically when the PaintWeb * script is added in a page. * @type String */ PaintWeb.baseFolder = ''; (function () { var scripts = document.getElementsByTagName('script'), n = scripts.length, pos, src; // Determine the baseFolder. for (var i = 0; i < n; i++) { src = scripts[i].src; if (!src || !/paintweb(\.dev|\.src|\.dryice)?\.js/.test(src)) { continue; } pos = src.lastIndexOf('/'); if (pos !== -1) { PaintWeb.baseFolder = src.substr(0, pos + 1); } break; } })(); // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
{ // $Date: 2009-11-16 18:13:48 +0200 $ "errorInitBufferCanvas": "Error: adding the new buffer canvas element failed.", "errorInitContext": "Error while initializing the canvas context.", "errorElementNotFound": "Error: the following element was not found: {id}.", "noComputedStyle": "Error: window.getComputedStyle is not available.", "noXMLHttpRequest": "Error: window.XMLHttpRequest is not available.", "errorInitCanvas": "Error: Canvas initialization failed.", "noCanvasSupport": "Error: Your browser does not support Canvas.", "failedConfigLoad": "Error: Failed loading the configuration.", "failedLangLoad": "Error: Failed loading the language file.", "failedMarkupLoad": "Error: Failed loading the interface markup file.", "errorInitCommands": "Error: failed to initialize the PaintWeb commands!", "noToolConfigured": "Error: you have no drawing tool configured to load!", "imageLoadDifferentHost": "Warning: the configured image cannot be loaded because it is from a different domain.", "toolRegisterFailed": "Error: failed to register tool '{id}'!", "extensionRegisterFailed": "Error: failed to register extension '{id}'!", "errorToolActivate": "Error: the tool you want could not be properly activated!", "errorInitGUI": "Error: the interface failed to initialize!", "failedSelectionCopy": "Error: failed to copy the selected pixels into memory.", "noMainTabPanel": "Error: the interface layout has no tabbed panel with ID = main.", "guiMarkupImportFailed": "Error: the interface markup code could not be imported into the main document.", "guiMarkupParseFailed": "Error: the interface markup code could not be properly parsed.", "missingViewport": "Error: the interface markup does not have the image viewport element.", "missingViewportResizer": "Error: the interface markup does not have the image viewport resize handle.", "missingCanvasResizer": "Error: the interface markup does not have the Canvas resize handle.", "missingCanvasContainer": "Error: the interface markup does not have the Canvas container.", "errorCpickerUnsupported": "Error: your browser does not implement the get/putImageData methods! The color picker tool cannot be used.", "errorCbucketUnsupported": "Error: your browser does not implement the get/putImageData methods! The color bucket tool cannot be used.", "errorClipboardUnsupported": "Error: your browser does not support get/putImageData! Clipboard operations like cut/copy/paste cannot be used.", "errorTextUnsupported": "Error: your browser does not implement the Canvas Text API! The text tool cannot be used.", "errorInsertimg": "The image could not be inserted. Maybe the address does not point to an image.", "errorInsertimgHost": "The URL you provided points to a different host. The image cannot be added for security reasons.", "errorInsertimgNotLoaded": "The image did not load yet, or the URL you provided does not point to an image.", "promptInsertimg": "Type the address of the image you want to insert:", "promptImageDimensions": "Please input the new image dimensions you want.", "promptTextFont": "Type the name of the font you want:", "errorImageSave": "The image cannot be saved!", "guiCanvasResizer": "Resize the image canvas.", "guiViewportResizer": "Resize the image viewport.", "imageZoomTitle": "Zoom image", "imageZoomLabel": "Zoom:", "tabs": { "main": { "bcurve": "Bézier curve", "ellipse": "Ellipse", "eraser": "Eraser", "line": "Line", "main": "Main", "pencil": "Pencil", "polygon": "Polygon", "rectangle": "Rectangle", "selection": "Selection", "shadow": "Shadow", "text": "Text", "textBorder": "Border" }, "colormixer_inputs": { "rgb": "RGB", "rgbTitle": "sRGB: Standard Red, Green and Blue", "hsv": "HSV", "hsvTitle": "Hue, Saturation and Value", "lab": "Lab", "labTitle": "CIE Lab: Standard observer 2° D65", "cmyk": "CMYK", "cmykTitle": "Cyan, Magenta, Yellow and Key (Black)" }, "colormixer_selector": { "mixer": "Mixer", "mixerTitle": "Color space visualisation", "cpalettes": "Palettes", "cpalettesTitle": "Predefined color palettes" } }, "floatingPanelMinimize": "Minimize", "floatingPanelRestore": "Restore", "floatingPanelClose": "Close", "floatingPanels": { "about": "About PaintWeb", "colormixer": "Color mixer" }, "tools": { "cbucket": "Color bucket", "cpicker": "Color picker", "bcurve": "Bézier curve", "hand": "Viewport drag", "ellipse": "Ellipse", "eraser": "Eraser", "insertimg": "Insert image", "line": "Line", "pencil": "Pencil", "polygon": "Polygon", "rectangle": "Rectangle", "selection": "Rectangle selection", "text": "Text", "textUnsupported": "The text tool is not supported by your browser." }, "commands": { "about": "About PaintWeb", "clipboardPaste": "Paste clipboard", "historyRedo": "Redo", "historyUndo": "Undo", "imageClear": "Clear image", "imageSave": "Save image", "selectionCopy": "Copy selection", "selectionCrop": "Crop selection", "selectionCut": "Cut selection", "selectionDelete": "Delete selection", "selectionFill": "Fill the selection" }, "inputs": { "line": { "lineCap": "Line cap", "lineCap_butt": "Butt", "lineCap_round": "Round", "lineCap_square": "Square", "lineJoin": "Line join", "lineJoin_bevel": "Bevel", "lineJoin_miter": "Miter", "lineJoin_round": "Round", "lineWidth": "Line width:", "miterLimit": "Miter limit:" }, "shadow": { "enable": "Enable shadows", "enableTitle": "If checked, a shadow will render after each drawing operation you do.", "shadowBlur": "Blur:", "shadowOffsetX": "Distance X:", "shadowOffsetY": "Distance Y:", "shadowColor": "Color: ", "shadowColorTitle": "Shadow color" }, "selection": { "transform": "Image manipulation", "transformTitle": "If checked, the selected pixels will also be dragged/resized when you make changes to the selection. If unchecked, only the selection marquee will be dragged/resized - pixels will remain unaffected by any such changes.", "transparent": "Transparent selection", "transparentTitle": "If checked, the background will remain transparent. If unchecked, the background will be filled with the current fill color." }, "text": { "bold": "Bold", "italic": "Italic", "fontFamily": "Font family:", "fontFamily_add": "Another font...", "fontSize": "Font size:", "textAlign": "Text alignment", "textAlign_left": "Left", "textAlign_center": "Center", "textAlign_right": "Right", "textString_value": "Hello world!" }, "shapeType": "Shape type", "shapeType_both": "Both", "shapeType_fill": "Fill", "shapeType_stroke": "Stroke", "pencilSize": "Pencil size:", "eraserSize": "Eraser size:", "borderWidth": "Border width:", "fillStyle": "Fill ", "fillStyleTitle": "Fill color", "strokeStyle": "Stroke ", "strokeStyleTitle": "Stroke color", "colorInputAnchorContent": "Click to pick color" }, "colormixer": { "failedColorPaletteLoad": "Error: failed to load the color palette.", "colorPalettes": { "_saved": "Saved colors", "anpa": "ANPA", "dic": "DIC Color Guide", "macos": "Mac OS", "pantone-solid-coated": "PANTONE solid coated", "toyo94": "TOYO 94 color finder", "trumatch": "TRUMATCH colors", "web": "Web safe", "windows": "Windows" }, "inputs": { "hex": "Hex", "alpha": "Alpha", "hsv_hue": "Hue", "hsv_sat": "Saturation", "hsv_val": "Value", "rgb_red": "Red", "rgb_green": "Green", "rgb_blue": "Blue", "lab_cie_l": "Lightness", "lab_cie_a": "a*", "lab_cie_b": "b*", "cmyk_cyan": "Cyan", "cmyk_magenta": "Magenta", "cmyk_yellow": "Yellow", "cmyk_black": "Key / Black" }, "buttons": { "accept": "Accept", "cancel": "Cancel", "saveColor": "Save color", "pickColor": "Pick color" } }, "status": { "cbucketActive": "Click to start flood filling with the current fill color. Right click to use the stroke color for filling.", "cpickerNormal": "Click to change the fill color, or Shift+Click to change the stroke color.", "cpicker_fillStyle": "Click to pick the fill color.", "cpicker_strokeStyle": "Click to pick the stroke color.", "cpicker_shadow_shadowColor": "Click to pick the shadow color.", "bcurveActive": "Click to start drawing the curve. You need four points: start, end and two control points.", "bcurveControlPoint1": "Click to draw the first control point.", "bcurveControlPoint2": "Click to draw the second control point. This will also end the drawing operation.", "bcurveSnapping": "Hold the Shift key down for vertical/horizontal snapping.", "handActive": "Click and drag the image to scroll.", "ellipseActive": "Click and drag to draw an ellipse.", "ellipseMousedown": "Hold the Shift key down to draw a circle.", "eraserActive": "Click and drag to erase.", "insertimgActive": "Waiting for the image to load...", "insertimgLoaded": "Pick where you want to place the image. Click and drag to resize the image.", "insertimgResize": "Hold the Shift key down to preserve the aspect ratio.", "lineActive": "Click anywhere to start drawing a line.", "lineMousedown": "Hold the Shift key down for vertical/horizontal snapping.", "pencilActive": "Click and drag to draw.", "polygonActive": "Click anywhere to start drawing a polygon.", "polygonAddPoint": "Click to add another point to the polygon.", "polygonEnd": "To end drawing the polygon simply click in the same place as the last point.", "polygonMousedown": "Hold the Shift key down for vertical/horizontal snapping.", "rectangleActive": "Click and drag to draw a rectangle.", "rectangleMousedown": "Hold the Shift key down to draw a square.", "selectionActive": "Click and drag to draw a selection.", "selectionAvailable": "Drag or resize the selection. Hold the Control key down to toggle the transformation mode.", "selectionDrag": "Hold the Shift key down for vertical/horizontal snapping.", "selectionDraw": "Hold the Shift key down to draw a square selection.", "selectionResize": "Hold the Shift key down to preserve the aspect ratio.", "textActive": "Pick where you want to place the text. Make sure you adjust the properties as desired.", "guiCanvasResizerActive": "Move the mouse to resize the image canvas." }, // Moodle-related language strings "moodle": { "xhrRequestFailed": "The image save request failed.", "jsonParseFailed": "Parsing the JSON result from the server failed!", "imageSaveFailed": "The image save operation failed.", "urlMismatch": "Image address mismatch!\nThe current image is {url}.\nThe server replied a successful save for {urlServer}.", "errorSubmitUnsaved": "This image is not saved!" }, "moodleServer": { "permissionDenied": "Permission denied.", "saveEmptyDataUrl": "Your request has no data URL.", "proxyNotFound": "Could not find the PaintWeb image file proxy script.", "malformedDataUrl": "The data URL is malformed.", "failedMkdir": "Failed to create the PaintWeb images folder inside the Moodle data folder.", "saveFailed": "Saving the image failed.", "backingupImages": "Backing-up images saved with PaintWeb...", "backupFailed": "An error occurred while copying images saved by PaintWeb." } // vim:set spell spl=en fo=wan1croql tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix ft=javascript: }
JavaScript
{ // $Date: 2009-11-08 19:54:46 +0200 $ // TODO: try jsdoc-toolkit on this json (!) /** * The list of available languages. This associated language IDs to their * language titles. * * @type Object */ "languages": { // Besides the language title, you may also tell the file name. The 'file' // property needs to be relative to the PaintWeb baseFolder. If no 'file' is // given, then the 'en.json' file name is used, and the file will be loaded // from the 'langFolder' you specify below. "en": { "title": "English" } }, /** * The default language. * * @type String * @default "en" */ "lang": "en", /** * The folder which holds the language files. * * @type String * @default "lang" */ "langFolder": "lang", /** * The graphical user interface you want to use. * * @type String * @default "default" */ "gui": "default", /** * The folder contains all the interfaces. * * @type String * @default "interfaces" */ "interfacesFolder": "interfaces", /** * The interface markup file. The file must be an XHTML valid document. * * @type String * @default "layout.xhtml" */ "guiMarkup": "layout.xhtml", /** * The interface style file. * * @type String * @default "style.css" */ "guiStyle": "style.css", /** * The interface script file. * * @type String * @default script.js */ "guiScript": "script.js", /** * The image viewport width. Make sure the value is a CSS length, like "50%", * "450px" or "30em". * * <p>Note: the GUI implementation might ignore this value. * * @type String * @default "100%" */ "viewportWidth": "100%", /** * The image viewport height. Make sure the value is a CSS length, like "50%", * "450px" or "30em". * * <p>Note: the GUI implementation might ignore this value. * * @type String * @default "400px" */ "viewportHeight": "400px", /** * Image save quality for the JPEG format. * * @type Number * @default 0.9 */ "jpegSaveQuality": 0.9, /** * The default image width. * * @type Number * @default 400 */ "imageWidth": 400, /** * The default image width. * * @type Number * @default 300 */ "imageHeight": 300, /** * Image preload. The image you want to display when PaintWeb loads. This must * be a reference to an HTML Image element. * * @type HTMLImageElement * @default null */ "imagePreload": null, /** * Default background color. * * @type CSS3Color * @default "#fff" */ "backgroundColor": "#fff", /** * Default fill style. * * @type CSS3Color-rgba functional notation * @default "rgba(0,0,0,1)" */ "fillStyle": "rgba(0,0,0,1)", /** * Default stroke style. * * @type CSS3Color-rgba functional notation * @default "rgba(0,0,255,1)" */ "strokeStyle": "rgba(0,0,255,1)", /** * Enable checkers background. This tells the user interface to render * checkers in the image background. These are visible only when parts of * the image being edited are transparent. * * <p>If the device you are running PaintWeb on has limited resources, * disabling the checkers background should improve the drawing performance. * * @type Boolean * @default true */ "checkersBackground": true, /** * GUI placeholder element. This element will hold all the PaintWeb interface * elements. * * <p>For a successful initialization of PaintWeb, you must define this * configuration value programatically from your scripts. * * @type Element * @default null */ "guiPlaceholder": null, /** * Shape drawing "type": filled, only stroke, or both. Possible values: * "filled", "stroke" or "both". * * @type String * @default "both" */ "shapeType": "both", /** * Number of available history steps. * * @type Number * @default 10 */ "historyLimit": 10, /** * Zoom factor when the user increases/decreases the image zoom level. * * @type Number * @default 0.05 */ // 0.05 means 5% zoom. "imageZoomStep": 0.05, /** * The maximum allowed image zoom level. * * @type Number * @default 4 */ // 4 means 400% zoom. "imageZoomMax": 4, /** * The minimum allowed image zoom level. * * @type Number * @default 0.2 */ // 0.2 means 20% zoom. "imageZoomMin": 0.2, /** * The image zoom control keys, for zoom in, zoom out and zoom reset. * @type Object */ "imageZoomKeys": { "in": "+", "out": "-", "reset": "*" }, /** * Holds the list of drawing tools you want to load. * @type Array */ "tools": ["bcurve", "cbucket", "cpicker", "ellipse", "eraser", "hand", "insertimg", "line", "pencil", "polygon", "rectangle", "selection", "text"], /** * Tools folder. * @type String * @default "tools" */ "toolsFolder": "tools", /** * The default tool ID. * * @type String * @default "line" * @see this.tools The array holding the list of drawing tools you want * loaded. */ "toolDefault": "line", /** * Tool drawing delay (milliseconds). Some tools delay their drawing * operations for performance reasons. * * @type Number * @default 80 */ "toolDrawDelay": 80, /** * Holds the list of extensions you want to load. * @type Array */ "extensions": ["colormixer", "mousekeys"], /** * Extensions folder. * * @type String * @default "extensions" */ "extensionsFolder": "extensions", /** * @namespace Line tool options. */ "line": { /** * Line cap. Possible values: "butt", "round", "square". * * @type String * @default "round" */ "lineCap": "round", /** * Line join. Possible values: "round", "bevel", "miter". * * @type String * @default "round" */ "lineJoin": "round", /** * Line width. * * @type Number * @default 1 */ "lineWidth": 1, /** * Miter limit. * * @type Number * @default 10 */ "miterLimit": 10 }, /** * @namespace Shadow options. */ "shadow": { /** * Tells if a shadow should render or not. * * @type Boolean * @default false */ "enable": false, /** * Shadow color * * @type CSS3Color-rgba() functional notation * @default "rgba(0,0,0,1)" */ "shadowColor": "rgba(0,0,0,1)", /** * Shadow blur. * * @type Number * @default 5 */ "shadowBlur": 5, /** * Shadow offset X. * * @type Number * @default 5 */ "shadowOffsetX": 5, /** * Shadow offset %. * * @type Number * @default 5 */ "shadowOffsetY": 5 }, /** * @namespace Selection tool options. */ "selection": { /** * Selection transformation mode. This tells if any drag/resize would also * affect the selected pixels or not. * * @type Boolean * @default false */ "transform": false, /** * Transparent selection. * * @type Boolean * @default true */ "transparent": true, /** * Selection marquee border width. * * @type Number * @default 3 */ "borderWidth": 3, /** * Keyboard shortcuts for several selection-related commands. * @type Object */ "keys": { "selectionCrop": "Control K", "selectionDelete": "Delete", "selectionDrop": "Escape", "selectionFill": "Alt Backspace", "transformToggle": "Enter" } }, /** * Text tool options. * @type Object */ "text": { "bold": false, "italic": false, /** * The default list of font families available in font family drop-down. * @type Array */ "fontFamilies": ["sans-serif", "serif", "cursive", "fantasy", "monospace"], /** * The font family used for rendering the text. * @type String * @default "sans-serif" */ "fontFamily": "sans-serif", "fontSize": 36, /** * Horizontal text alignment. Possible values: "left", "center", "right". * * <p>Note that the Canvas Text API also defines the "start" and "end" * values, which are not "supported" by PaintWeb. * * @type String * @default "left" */ "textAlign": "left", /** * Vertical text alignment. Possible values: "top", "hanging", "middle", * "alphabetic", "ideographic", or "bottom". * * @type String * @default "alphabetic" */ "textBaseline": "top" }, /** * @namespace Color Mixer extension configuration. */ "colormixer": { /** * Holds the minimum and maximum value for each color channel input field. * The value incrementation step is also included - this is used the user * presses the up/down arrow keys in the input of the color channel. * * @type Object */ "inputValues": { // RGB // order: minimum, maximum, step "red": [0, 255, 1], "green": [0, 255, 1], "blue": [0, 255, 1], // HSV // Hue - degrees "hue": [0, 360, 1], "sat": [0, 255, 1], "val": [0, 255, 1], // CMYK - all are percentages "cyan": [0, 100, 1], "magenta": [0, 100, 1], "yellow": [0, 100, 1], "black": [0, 100, 1], // CIE Lab // cie_l = Lightness, it's a percentage value // cie_a and cie_b are the color-opponent dimensions "cie_l": [ 0, 100, 1], "cie_a": [ -86, 98, 1], "cie_b": [-107, 94, 1], "alpha": [0, 100, 1] }, /** * CIE Lab configuration. * @type Object */ "lab": { // The RGB working space is sRGB which has the reference white point of // D65. // These are the chromaticity coordinates for the red, green and blue // primaries. "x_r": 0.64, "y_r": 0.33, "x_g": 0.3, "y_g": 0.6, "x_b": 0.13, "y_b": 0.06, // Standard observer: D65 (daylight), 2° (CIE 1931). // Chromaticity coordinates. "ref_x": 0.31271, "ref_y": 0.32902, // This is the calculated reference white point (xyY to XYZ) for D65, also // known as the reference illuminant tristimulus. // These values are updated based on chromaticity coordinates, during // initialization. "w_x": 0.95047, "w_y": 1, "w_z": 1.08883, // The 3x3 matrix used for multiplying the RGB values when converting RGB // to XYZ. // These values are updated based on the chromaticity coordinates, during // initialization. "m": [ 0.412424, 0.212656, 0.0193324, 0.357579, 0.715158, 0.119193, 0.180464, 0.0721856, 0.950444], // The same matrix, but inverted. This is used for the XYZ to RGB conversion. "m_i": [ 3.24071, -0.969258, 0.0556352, -1.53726, 1.87599, -0.203996, -0.498571, 0.0415557, 1.05707] }, /** * Slider width. This value must be relative to the color space * visualisation canvas element: 1 means full width, 0.5 means half width, * etc. * * @type Number * @default 0.10 (which is 10% of the canvas element width) */ "sliderWidth": 0.10, /** * Spacing between the slider and the color chart. * * @type Number * @default 0.03 (which is 3% of the canvas element width) */ "sliderSpacing": 0.03, /** * Holds the list of color palettes. * @type Object */ "colorPalettes": { "_saved" : { // Color values are: red, green, blue. All three channels have values // ranging between 0 and 1. "colors" : [[1,1,1], [1,1,0], [1,0,1], [0,1,1], [1,0,0], [0,1,0], [0,0,1], [0,0,0]] }, "windows" : { "file" : "colors/windows.json" }, "macos" : { "file" : "colors/macos.json" }, "web" : { "file" : "colors/web.json" } }, "paletteDefault": "windows" }, /** * @namespace Holds the MouseKeys extension options. */ "mousekeys": { /** * The mouse keys movement acceleration. * * @type Number * @default 0.1 * @see PaintMouseKeys The MouseKeys extension. */ "accel": 0.1, /** * Holds the list of actions, associated to keyboard shortcuts. * * @type Object */ // We make sure the number keys on the NumPad also work when the Shift key // is down. "actions": { "ButtonToggle": [0], "SouthWest": [1], "South": [2], "SouthEast": [3], "West": [4], "ButtonClick": [5], "East": [6], "NorthWest": [7], "North": [8], "NorthEast": [9] /* You might want Shift+NumPad keys as well ... Shift+Arrows breaks spatial navigation in Opera. "ButtonToggle": [0, "Shift Insert"], "SouthWest": [1, "Shift End"], "South": [2, "Shift Down"], "SouthEast": [3, "Shift PageDown"], "West": [4, "Shift Left"], "ButtonClick": [5, "Shift Clear"], "East": [6, "Shift Right"], "NorthWest": [7, "Shift Home"], "North": [8, "Shift Up"], "NorthEast": [9, "Shift PageUp"] */ } }, /** * Keyboard shortcuts associated to drawing tools and other actions. * * @type Object * @see PaintTools The object holding all the drawing tools. */ "keys": { // Use "command": "id" to execute some command. "Control Z": { "command": "historyUndo" }, "Control Y": { "command": "historyRedo" }, "Control N": { "command": "imageClear" }, "Control S": { "command": "imageSave" }, "Control A": { "command": "selectAll" }, "Control X": { "command": "selectionCut" }, "Shift Delete": { "command": "selectionCut" }, "Control C": { "command": "selectionCopy" }, "Control V": { "command": "clipboardPaste" }, // Use "toolActivate": "id" to activate the tool with the given ID. "C": { "toolActivate": "cpicker" }, "E": { "toolActivate": "ellipse" }, "F": { "toolActivate": "cbucket" }, "G": { "toolActivate": "polygon" }, "H": { "toolActivate": "hand" }, "I": { "toolActivate": "insertimg" }, "L": { "toolActivate": "line" }, "O": { "toolActivate": "eraser" }, "P": { "toolActivate": "pencil" }, "R": { "toolActivate": "rectangle" }, "S": { "toolActivate": "selection" }, "T": { "toolActivate": "text" }, "V": { "toolActivate": "bcurve" }, // Miscellaneous commands. "X": { "command": "swapFillStroke" }, "F1": { "command": "about" } } // vim:set spell spl=en fo=wan1croql tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix ft=javascript: }
JavaScript
/* * Copyright (C) 2008, 2009 Mihai Şucan * * This file is part of PaintWeb. * * PaintWeb is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PaintWeb is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PaintWeb. If not, see <http://www.gnu.org/licenses/>. * * $URL: http://code.google.com/p/paintweb $ * $Date: 2009-05-11 19:37:56 +0300 $ */ /** * @author <a lang="ro" href="http://www.robodesign.ro/mihai">Mihai Şucan</a> * @fileOverview Minimal code used for aiding debugging PaintWeb. */ // Opera compatibility if (!window.console) { /** * @namespace Holds a simple method used for debugging. Opera doesn't have the * window.console API like Firefox+Firebug has. */ window.console = {}; } if (!window.console.log) { /** * Display a message in the debugger. If available, opera.postError is used, * otherwise no message is displayed. * * @param {mixed} mixed Any number of arguments, each one is displayed in the * debugger. */ window.console.log = function () { var msg = ''; for (var i = 0, n = arguments.length; i < n; i++) { msg += arguments[i] + ' '; } if (window.opera && window.opera.postError) { opera.postError(msg); } }; } if (!window.console.warn) { /** * Display a message in the debugger. If available, opera.postError is used, * otherwise no warning is displayed. * * @param {mixed} mixed Any number of arguments, each one is displayed in the * debugger. */ window.console.warn = function () { console.log.apply(null, arguments); }; } /** * JavaScript code performance profiler. * <p>Nested timers are accounted for - see the example below. * * @example * <code>// To profile your code just do: * var profiler = new $.profiler(); * * profiler.start('long test'); * // ... more code ... * profiler.start('function 1'); * // ... more code ... * profiler.stop('function 1'); * // ... more code ... * profiler.start('function 2'); * // ... more code ... * profiler.stop('function 2'); * // ... more code ... * profiler.stop('long test'); * * // To see the results do: * profiler.reportText(); * // or .. * profiler.reportData();</code> * * @class JavaScript code performance profiler. */ var libProfiler = function () { /** * @ignore * @class Function timer. This is the constructor used for instancing a single * timer object created by the profiler. * * @private * @param {String} name_ The timer name. * @param {Boolean} [independent_=false] Tells if the timer is independent. * Means this timer will not affect the timers execution stack. */ function fnTimer (name_, independent_) { this.avgOwnTimePerCall = 0; this.avgRunTimePerCall = 0; this.calls = 0; this.maxOwnTimePerCall = 0; this.maxRunTimePerCall = 0; this.minOwnTimePerCall = 0; this.minRunTimePerCall = 0; this.name = name_; this.ownTimeTotal = 0; this.runTimeTotal = 0; this.state = fnTimer.STATE_NONE; this.independent = independent_; var startTime_ = 0, subTimerStart_ = 0, subTime_ = 0, stack_ = 0; /* * Start timing function execution. */ this.start = function () { if (this.state == fnTimer.STATE_START || this.state == fnTimer.STATE_SUB) { stack_++; return; } startTime_ = (new Date ()).getTime(); this.state = fnTimer.STATE_START; }; /* * Stop timing function execution. */ this.stop = function () { if (this.state == fnTimer.STATE_SUB) { this.subTimerEnd(); } if (this.state != fnTimer.STATE_START) { return; } this.calls++; if (stack_) { stack_--; return; } var runTime = (new Date ()).getTime() - startTime_; var ownTime = runTime - subTime_; subTime_ = 0; this.runTimeTotal += runTime; this.ownTimeTotal += ownTime; this.avgRunTimePerCall = this.runTimeTotal / this.calls; this.avgOwnTimePerCall = this.ownTimeTotal / this.calls; if (runTime < this.minRunTimePerCall) { this.minRunTimePerCall = runTime; } if (runTime > this.maxRunTimePerCall) { this.maxRunTimePerCall = runTime; } if (ownTime < this.minOwnTimePerCall) { this.minOwnTimePerCall = ownTime; } if (ownTime > this.maxOwnTimePerCall) { this.maxOwnTimePerCall = ownTime; } this.state = fnTimer.STATE_STOP; }; /* * Start timing sub-function execution. The sub-function execution timer is * used for calculating the ownTime (runTime - sub-function execution time). */ this.subTimerStart = function () { if (this.independent || this.state != fnTimer.STATE_START) { return; } subTimerStart_ = (new Date()).getTime(); this.state = fnTimer.STATE_SUB; }; /* * Stop timing sub-function execution. */ this.subTimerEnd = function () { if (this.independent || this.state != fnTimer.STATE_SUB) { return; } subTime_ += (new Date()).getTime() - subTimerStart_; this.state = fnTimer.STATE_START; }; }; fnTimer.STATE_NONE = 0; fnTimer.STATE_START = 1; fnTimer.STATE_SUB = 2; fnTimer.STATE_STOP = 3; /** * Holds the timer objects. */ this.timers = {}; var activeTimer_ = null, timersStack_ = []; /** * Start/create a function timer. * * @param {String} name The timer name. * @param {Boolean} [independent=false] Tells if the timer should be * independent or not. This means that this new function timer is not be * considered affecting the execution time of existing function timers in the * call stack. */ this.start = function (name, independent) { var timer = this.timers[name]; if (!timer) { timer = this.timers[name] = new fnTimer(name, independent); } if (!timer.independent && activeTimer_ != name) { var activeTimer = activeTimer_ ? this.timers[activeTimer_] : null; if (activeTimer && activeTimer.state == fnTimer.STATE_START) { timersStack_.push(activeTimer_); activeTimer.subTimerStart(); } activeTimer_ = name; } timer.start(); }; /** * Stop a function timer. */ this.stop = function (name) { var timer = this.timers[name]; if (!timer) { return; } timer.stop(); if (timer.independent || name != activeTimer_ || name == activeTimer_ && timer.state == fnTimer.STATE_START) { return; } if (timersStack_.length > 0) { activeTimer_ = timersStack_.pop(); var activeTimer = this.timers[activeTimer_]; activeTimer.subTimerEnd(); } else { activeTimer_ = null; } }; /** * Generate timers report data. * * @returns {Object} Holds all the information gathered by the timers. */ this.reportData = function () { var name, timer, timerDetails, data = { avgCallsPerTimer: 0, avgOwnTimePerCall: 0, avgOwnTimePerTimer: 0, avgRunTimePerCall: 0, avgRunTimePerTimer: 0, callsTotal: 0, maxCallsPerTimer: 0, maxCallsPerTimerName: '', maxOwnTimePerCall: 0, maxOwnTimePerCallName: '', maxRunTimePerCall: 0, maxRunTimePerCallName: '', minCallsPerTimer: 0, minCallsPerTimerName: '', minOwnTimePerCall: 0, minOwnTimePerCallName: '', minRunTimePerCall: 0, minRunTimePerCallName: '', ownTimeTotal: 0, runTimeTotal: 0, timers: 0, timerDetails: [] }; for (name in this.timers) { timer = this.timers[name]; if (timer.state != fnTimer.STATE_STOP) { continue; } timerDetails = { name: name, avgOwnTimePerCall: timer.avgOwnTimePerCall, avgRunTimePerCall: timer.avgRunTimePerCall, calls: timer.calls, maxOwnTimePerCall: timer.maxOwnTimePerCall, maxRunTimePerCall: timer.maxRunTimePerCall, minOwnTimePerCall: timer.minOwnTimePerCall, minRunTimePerCall: timer.minRunTimePerCall, runTimeTotal: timer.runTimeTotal, ownTimeTotal: timer.ownTimeTotal }; data.timerDetails.push(timerDetails); if (timer.calls > data.maxCallsPerTimer || !data.timers) { data.maxCallsPerTimer = timer.calls; data.maxCallsPerTimerName = name; } if (timer.maxOwnTimePerCall > data.maxOwnTimePerCall || !data.timers) { data.maxOwnTimePerCall = timer.maxOwnTimePerCall; data.maxOwnTimePerCallName = name; } if (timer.maxRunTimePerCall > data.maxRunTimePerCall || !data.timers) { data.maxRunTimePerCall = timer.maxRunTimePerCall; data.maxRunTimePerCallName = name; } if (timer.calls < data.minCallsPerTimer || !data.timers) { data.minCallsPerTimer = timer.calls; data.minCallsPerTimerName = name; } if (timer.minOwnTimePerCall < data.minOwnTimePerCall || !data.timers) { data.minOwnTimePerCall = timer.minOwnTimePerCall; data.minOwnTimePerCallName = name; } if (timer.minRunTimePerCall < data.minRunTimePerCall || !data.timers) { data.minRunTimePerCall = timer.minRunTimePerCall; data.minRunTimePerCallName = name; } data.runTimeTotal += timer.runTimeTotal; data.ownTimeTotal += timer.ownTimeTotal; data.callsTotal += timer.calls; data.timers++; } if (data.timers == 0) { return data; } data.avgCallsPerTimer = data.callsTotal / data.timers; data.avgOwnTimePerCall = data.ownTimeTotal / data.callsTotal; data.avgOwnTimePerTimer = data.ownTimeTotal / data.timers; data.avgRunTimePerCall = data.runTimeTotal / data.callsTotal; data.avgRunTimePerTimer = data.runTimeTotal / data.timers; return data; }; /** * Generate a report in text format. * * @returns {String} All the information gathered by the timers, as text. */ this.reportText = function () { var data = this.reportData(), timer, result = ''; if (!data.timers) { return ''; } for (var i = 0; i < data.timers; i++) { timer = data.timerDetails[i]; result += timer.name + ":\n" + ' Avg ownTime / call: ' + timer.avgOwnTimePerCall + " ms\n" + ' Avg runTime / call: ' + timer.avgRunTimePerCall + " ms\n" + ' Calls: ' + timer.calls + "\n"+ ' Max ownTime / call: ' + timer.maxOwnTimePerCall + " ms\n" + ' Max runTime / call: ' + timer.maxRunTimePerCall + " ms\n" + ' Min ownTime / call: ' + timer.minOwnTimePerCall + " ms\n" + ' Min runTime / call: ' + timer.minRunTimePerCall + " ms\n" + ' runTime: ' + timer.runTimeTotal + " ms\n" + ' ownTime: ' + timer.ownTimeTotal + " ms\n\n"; } result += "Overview info:\n" + ' Avg calls / timer: ' + data.avgCallsPerTimer + "\n" + ' Avg ownTime / call: ' + data.avgOwnTimePerCall + " ms\n" + ' Avg ownTime / timer: ' + data.avgOwnTimePerTimer + " ms\n" + ' Avg runTime / call: ' + data.avgRunTimePerCall + " ms\n" + ' Avg runTime / timer: ' + data.avgRunTimePerTimer + " ms\n" + ' Calls total: ' + data.callsTotal + "\n" + ' Max calls / timer: ' + data.maxCallsPerTimer + ' (' + data.maxCallsPerTimerName + ")\n" + ' Max ownTime / call: ' + data.maxOwnTimePerCall + ' ms (' + data.maxOwnTimePerCallName + ")\n" + ' Max runTime / call: ' + data.maxRunTimePerCall + ' ms (' + data.maxRunTimePerCallName + ")\n" + ' Min calls / timer: ' + data.minCallsPerTimer + ' (' + data.minCallsPerTimerName + ")\n" + ' Min ownTime / call: ' + data.minOwnTimePerCall + ' ms (' + data.minOwnTimePerCallName + ")\n" + ' Min runTime / call: ' + data.minRunTimePerCall + ' ms (' + data.minRunTimePerCallName + ")\n" + ' Accumulated ownTime: ' + data.ownTimeTotal + " ms\n" + ' Accumulated runTime: ' + data.runTimeTotal + " ms\n" + ' Timers: ' + data.timers; return result; }; /** * Reset/clear all the timers. */ this.reset = function () { this.timers = {}; activeTimer_ = null; timersStack_ = []; }; }; // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * Copyright (C) 2008, 2009, 2010 Mihai Şucan * * This file is part of PaintWeb. * * PaintWeb is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PaintWeb is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PaintWeb. If not, see <http://www.gnu.org/licenses/>. * * $URL: http://code.google.com/p/paintweb $ * $Date: 2010-06-26 20:35:34 +0300 $ */ /** * @author <a lang="ro" href="http://www.robodesign.ro/mihai">Mihai Şucan</a> * @fileOverview Minimal JavaScript library which provides functionality for * cross-browser compatibility support. */ /** * @namespace Holds methods and properties necessary throughout the entire * application. */ var pwlib = {}; /** * @namespace Holds pre-packaged files. * @type Object */ pwlib.fileCache = {}; /** * @namespace Holds the implementation of each drawing tool. * * @type Object * * @see PaintWeb#toolRegister Register a new drawing tool into a PaintWeb * instance. * @see PaintWeb#toolActivate Activate a drawing tool in a PaintWeb instance. * @see PaintWeb#toolUnregister Unregister a drawing tool from a PaintWeb * instance. * * @see PaintWeb.config.toolDefault The default tool being activated when * a PaintWeb instance is initialized. * @see PaintWeb.config.tools Holds the list of tools to be loaded automatically * when a PaintWeb instance is initialized. */ pwlib.tools = {}; /** * @namespace Holds all the PaintWeb extensions. * * @type Object * @see PaintWeb#extensionRegister Register a new extension into a PaintWeb * instance. * @see PaintWeb#extensionUnregister Unregister an extension from a PaintWeb * instance. * @see PaintWeb.config.extensions Holds the list of extensions to be loaded * automatically when a PaintWeb instance is initialized. */ pwlib.extensions = {}; /** * This function extends objects. * * @example * <code>var <var>obj1</var> = {a: 'a1', b: 'b1', d: 'd1'}, * <var>obj2</var> = {a: 'a2', b: 'b2', c: 'c2'}; * * pwlib.extend(<var>obj1</var>, <var>obj2</var>);</code> * * // Now <var>obj1.c == 'c2'</var>, while <var>obj1.a</var>, <var>obj1.b</var> * // and <var>obj1.d</var> remain the same. * * // If <code>pwlib.extend(true, <var>obj1</var>, <var>obj2</var>)</code> is * // called, then <var>obj1.a</var>, <var>obj1.b</var>, <var>obj1.c</var> * // become all the same as in <var>obj2</var>. * * @example * <code>var <var>obj1</var> = {a: 'a1', b: 'b1', extend: pwlib.extend}; * <var>obj1</var>.extend({c: 'c1', d: 'd1'});</code> * * // In this case the destination object which is to be extend is * // <var>obj1</var>. * * @param {Boolean} [overwrite=false] If the first argument is a boolean, then * it will be considered as a boolean flag for overwriting (or not) any existing * methods and properties in the destination object. Thus, any method and * property from the source object will take over those in the destination. The * argument is optional, and if it's omitted, then no method/property will be * overwritten. * * @param {Object} [destination=this] The second argument is the optional * destination object: the object which will be extended. By default, the * <var>this</var> object will be extended. * * @param {Object} source The third argument must provide list of methods and * properties which will be added to the destination object. */ pwlib.extend = function () { var name, src, sval, dval; if (typeof arguments[0] === 'boolean') { force = arguments[0]; dest = arguments[1]; src = arguments[2]; } else { force = false; dest = arguments[0]; src = arguments[1]; } if (typeof src === 'undefined') { src = dest; dest = this; } if (typeof dest === 'undefined') { return; } for (name in src) { sval = src[name]; dval = dest[name]; if (force || typeof dval === 'undefined') { dest[name] = sval; } } }; /** * Retrieve a string formatted with the provided variables. * * <p>The language string must be available in the global <var>lang</var> * object. * * <p>The string can contain any number of variables in the form of * <code>{var_name}</code>. * * @example * lang.table_cells = "The table {name} has {n} cells."; * * // later ... * console.log(pwlib.strf(lang.table_cells, {'name' : 'tbl1', 'n' : 11})); * // The output is 'The table tbl1 has 11 cells.' * * @param {String} str The string you want to output. * * @param {Object} [vars] The variables you want to set in the language string. * * @returns {String} The string updated with the variables you provided. */ pwlib.strf = function (str, vars) { if (!str) { return str; } var re, i; for (i in vars) { re = new RegExp('{' + i + '}', 'g'); str = str.replace(re, vars[i]); } return str; }; /** * Parse a JSON string. This method uses the global JSON parser provided by * the browser natively. The small difference is that this method allows * normal JavaScript comments in the JSON string. * * @param {String} str The JSON string to parse. * @returns The JavaScript object that was parsed. */ pwlib.jsonParse = function (str) { str = str.replace(/\s*\/\*(\s|.)+?\*\//g, ''). replace(/^\s*\/\/.*$/gm, ''); return JSON.parse(str); }; /** * Load a file from a given URL using XMLHttpRequest. * * @param {String} url The URL you want to load. * * @param {Function} handler The <code>onreadystatechange</code> event handler * for the XMLHttpRequest object. Your event handler will always receive the * XMLHttpRequest object as the first parameter. * * @param {String} [method="GET"] The HTTP method to use for loading the URL. * * @param {String} [send=null] The string you want to send in an HTTP POST * request. * * @param {Object} [headers] An object holding the header names and values you * want to set for the request. * * @returns {XMLHttpRequest} The XMLHttpRequest object created by this method. * * @throws {TypeError} If the <var>url</var> is not a string. */ pwlib.xhrLoad = function (url, handler, method, send, headers) { if (typeof url !== 'string') { throw new TypeError('The first argument must be a string!'); } if (!method) { method = 'GET'; } if (!headers) { headers = {}; } if (!send) { send = null; } /** @ignore */ var xhr = new XMLHttpRequest(); /** @ignore */ xhr.onreadystatechange = function () { handler(xhr); }; xhr.open(method, url); for (var header in headers) { xhr.setRequestHeader(header, headers[header]); } xhr.send(send); return xhr; }; /** * Check if an URL points to a resource from the same host as the desired one. * * <p>Note that data URIs always return true. * * @param {String} url The URL you want to check. * @param {String} host The host you want in the URL. The host name can include * the port definition as well. * * @returns {Boolean} True if the <var>url</var> points to a resource from the * <var>host</var> given, or false otherwise. */ pwlib.isSameHost = function (url, host) { if (!url || !host) { return false; } var pos = url.indexOf(':'), proto = url.substr(0, pos + 1).toLowerCase(); if (proto === 'data:') { return true; } if (proto !== 'http:' && proto !== 'https:') { return false; } var urlHost = url.replace(/^https?:\/\//i, ''); pos = urlHost.indexOf('/'); if (pos > -1) { urlHost = urlHost.substr(0, pos); } // remove default port (80) urlHost = urlHost.replace(/:80$/, ''); host = host.replace(/:80$/, ''); if (!urlHost || !host || urlHost !== host) { return false; } return true; }; /** * @class Custom application event. * * @param {String} type Event type. * @param {Boolean} [cancelable=false] Tells if the event can be cancelled or * not. * * @throws {TypeError} If the <var>type</var> parameter is not a string. * @throws {TypeError} If the <var>cancelable</var> parameter is not a string. * * @see pwlib.appEvents for the application events interface which allows adding * and removing event listeners. */ pwlib.appEvent = function (type, cancelable) { if (typeof type !== 'string') { throw new TypeError('The first argument must be a string'); } else if (typeof cancelable === 'undefined') { cancelable = false; } else if (typeof cancelable !== 'boolean') { throw new TypeError('The second argument must be a boolean'); } /** * Event target object. * @type Object */ this.target = null; /** * Tells if the event can be cancelled or not. * @type Boolean */ this.cancelable = cancelable; /** * Tells if the event has the default action prevented or not. * @type Boolean */ this.defaultPrevented = false; /** * Event type. * @type String */ this.type = type; /** * Prevent the default action of the event. */ this.preventDefault = function () { if (cancelable) { this.defaultPrevented = true; } }; /** * Stop the event propagation to other event handlers. */ this.stopPropagation = function () { this.propagationStopped_ = true; }; this.toString = function () { return '[pwlib.appEvent.' + this.type + ']'; }; }; /** * @class Application initialization event. This event is not cancelable. * * @augments pwlib.appEvent * * @param {Number} state The initialization state. * @param {String} [errorMessage] The error message, if any. * * @throws {TypeError} If the <var>state</var> is not a number. */ pwlib.appEvent.appInit = function (state, errorMessage) { if (typeof state !== 'number') { throw new TypeError('The first argument must be a number.'); } /** * Application initialization not started. * @constant */ this.INIT_NOT_STARTED = 0; /** * Application initialization started. * @constant */ this.INIT_STARTED = 1; /** * Application initialization completed successfully. * @constant */ this.INIT_DONE = 2; /** * Application initialization failed. * @constant */ this.INIT_ERROR = -1; /** * Initialization state. * @type Number */ this.state = state; /** * Initialization error message, if any. * @type String|null */ this.errorMessage = errorMessage || null; pwlib.appEvent.call(this, 'appInit'); }; /** * @class Application destroy event. This event is not cancelable. * * @augments pwlib.appEvent */ pwlib.appEvent.appDestroy = function () { pwlib.appEvent.call(this, 'appDestroy'); }; /** * @class GUI show event. This event is not cancelable. * * @augments pwlib.appEvent */ pwlib.appEvent.guiShow = function () { pwlib.appEvent.call(this, 'guiShow'); }; /** * @class GUI hide event. This event is not cancelable. * * @augments pwlib.appEvent */ pwlib.appEvent.guiHide = function () { pwlib.appEvent.call(this, 'guiHide'); }; /** * @class Tool preactivation event. This event is cancelable. * * @augments pwlib.appEvent * * @param {String} id The ID of the new tool being activated. * @param {String|null} prevId The ID of the previous tool. * * @throws {TypeError} If the <var>id</var> is not a string. * @throws {TypeError} If the <var>prevId</var> is not a string or null. */ pwlib.appEvent.toolPreactivate = function (id, prevId) { if (typeof id !== 'string') { throw new TypeError('The first argument must be a string.'); } else if (prevId !== null && typeof prevId !== 'string') { throw new TypeError('The second argument must be a string or null.'); } /** * Tool ID. * @type String */ this.id = id; /** * Previous tool ID. * @type String */ this.prevId = prevId; pwlib.appEvent.call(this, 'toolPreactivate', true); }; /** * @class Tool activation event. This event is not cancelable. * * @augments pwlib.appEvent * * @param {String} id The ID the tool which was activated. * @param {String|null} prevId The ID of the previous tool. * * @throws {TypeError} If the <var>id</var> is not a string. * @throws {TypeError} If the <var>prevId</var> is not a string or null. */ pwlib.appEvent.toolActivate = function (id, prevId) { if (typeof id !== 'string') { throw new TypeError('The first argument must be a string.'); } else if (prevId !== null && typeof prevId !== 'string') { throw new TypeError('The second argument must be a string or null.'); } /** * Tool ID. * @type String */ this.id = id; /** * Previous tool ID. * @type String */ this.prevId = prevId; pwlib.appEvent.call(this, 'toolActivate'); }; /** * @class Tool registration event. This event is not cancelable. * * @augments pwlib.appEvent * * @param {String} id The ID of the tool being registered in an active PaintWeb * instance. * * @throws {TypeError} If the <var>id</var> is not a string. */ pwlib.appEvent.toolRegister = function (id) { if (typeof id !== 'string') { throw new TypeError('The first argument must be a string.'); } /** * Tool ID. * @type String */ this.id = id; pwlib.appEvent.call(this, 'toolRegister'); }; /** * @class Tool removal event. This event is not cancelable. * * @augments pwlib.appEvent * * @param {String} id The ID of the tool being unregistered in an active * PaintWeb instance. * * @throws {TypeError} If the <var>id</var> is not a string. */ pwlib.appEvent.toolUnregister = function (id) { if (typeof id !== 'string') { throw new TypeError('The first argument must be a string.'); } /** * Tool ID. * @type String */ this.id = id; pwlib.appEvent.call(this, 'toolUnregister'); }; /** * @class Extension registration event. This event is not cancelable. * * @augments pwlib.appEvent * * @param {String} id The ID of the extension being registered in an active * PaintWeb instance. * * @throws {TypeError} If the <var>id</var> is not a string. */ pwlib.appEvent.extensionRegister = function (id) { if (typeof id !== 'string') { throw new TypeError('The first argument must be a string.'); } /** * Extension ID. * @type String */ this.id = id; pwlib.appEvent.call(this, 'extensionRegister'); }; /** * @class Extension removal event. This event is not cancelable. * * @augments pwlib.appEvent * * @param {String} id The ID of the extension being unregistered in an active * PaintWeb instance. * * @throws {TypeError} If the <var>id</var> is not a string. */ pwlib.appEvent.extensionUnregister = function (id) { if (typeof id !== 'string') { throw new TypeError('The first argument must be a string.'); } /** * Extension ID. * @type String */ this.id = id; pwlib.appEvent.call(this, 'extensionUnregister'); }; /** * @class Command registration event. This event is not cancelable. * * @augments pwlib.appEvent * * @param {String} id The ID of the command being registered in an active * PaintWeb instance. * * @throws {TypeError} If the <var>id</var> is not a string. */ pwlib.appEvent.commandRegister = function (id) { if (typeof id !== 'string') { throw new TypeError('The first argument must be a string.'); } /** * Command ID. * @type String */ this.id = id; pwlib.appEvent.call(this, 'commandRegister'); }; /** * @class Command removal event. This event is not cancelable. * * @augments pwlib.appEvent * * @param {String} id The ID of the command being unregistered in an active * PaintWeb instance. * * @throws {TypeError} If the <var>id</var> is not a string. */ pwlib.appEvent.commandUnregister = function (id) { if (typeof id !== 'string') { throw new TypeError('The first argument must be a string.'); } /** * Command ID. * @type String */ this.id = id; pwlib.appEvent.call(this, 'commandUnregister'); }; /** * @class The image save event. This event is cancelable. * * @augments pwlib.appEvent * * @param {String} dataURL The data URL generated by the browser holding the * pixels of the image being saved, in PNG format. * @param {Number} width The image width. * @param {Number} height The image height. */ pwlib.appEvent.imageSave = function (dataURL, width, height) { /** * The image saved by the browser, using the base64 encoding. * @type String */ this.dataURL = dataURL; /** * Image width. * @type Number */ this.width = width; /** * Image height. * @type Number */ this.height = height; pwlib.appEvent.call(this, 'imageSave', true); }; /** * @class The image save result event. This event is not cancelable. * * @augments pwlib.appEvent * * @param {Boolean} successful Tells if the image save was successful or not. * @param {String} [url] The image address. * @param {String} [urlNew] The new image address. Provide this parameter, if, * for example, you allow saving images from a remote server to a local server. * In such cases the image address changes. */ pwlib.appEvent.imageSaveResult = function (successful, url, urlNew) { /** * Tells if the image save was successful or not. * @type String */ this.successful = successful; /** * The image address. * @type String|null */ this.url = url; /** * The new image address. * @type String|null */ this.urlNew = urlNew; pwlib.appEvent.call(this, 'imageSaveResult'); }; /** * @class History navigation event. This event is not cancelable. * * @augments pwlib.appEvent * * @param {Number} currentPos The new history position. * @param {Number} previousPos The previous history position. * @param {Number} states The number of history states available. * * @throws {TypeError} If any of the arguments are not numbers. */ pwlib.appEvent.historyUpdate = function (currentPos, previousPos, states) { if (typeof currentPos !== 'number' || typeof previousPos !== 'number' || typeof states !== 'number') { throw new TypeError('All arguments must be numbers.'); } /** * Current history position. * @type Number */ this.currentPos = currentPos; /** * Previous history position. * @type Number */ this.previousPos = previousPos; /** * History states count. * @type Number */ this.states = states; pwlib.appEvent.call(this, 'historyUpdate'); }; /** * @class Image size change event. This event is not cancelable. * * @augments pwlib.appEvent * * @param {Number} width The new image width. * @param {Number} height The new image height. * * @throws {TypeError} If any of the arguments are not numbers. */ pwlib.appEvent.imageSizeChange = function (width, height) { if (typeof width !== 'number' || typeof height !== 'number') { throw new TypeError('Both arguments must be numbers.'); } /** * New image width. * @type Number */ this.width = width; /** * New image height. * @type Number */ this.height = height; pwlib.appEvent.call(this, 'imageSizeChange'); }; /** * @class Canvas size change event. This event is not cancelable. * * <p>Note that the Canvas size is not the same as the image size. Canvas size * refers to the scaling of the Canvas elements being applied (due to image * zooming or due to browser zoom / DPI). * * @augments pwlib.appEvent * * @param {Number} width The new Canvas style width. * @param {Number} height The new Canvas style height. * @param {Number} scale The new Canvas scaling factor. * * @throws {TypeError} If any of the arguments are not numbers. */ pwlib.appEvent.canvasSizeChange = function (width, height, scale) { if (typeof width !== 'number' || typeof height !== 'number' || typeof scale !== 'number') { throw new TypeError('All the arguments must be numbers.'); } /** * New Canvas style width. * @type Number */ this.width = width; /** * New Canvas style height. * @type Number */ this.height = height; /** * The new Canvas scaling factor. * @type Number */ this.scale = scale; pwlib.appEvent.call(this, 'canvasSizeChange'); }; /** * @class Image viewport size change event. This event is not cancelable. * * @augments pwlib.appEvent * * @param {String} width The new viewport width. This must be a CSS length * value, like "100px", "100%" or "100em". * * @param {String} height The new viewport height. This must be a CSS length * value, like "100px", "100%" or "100em". */ pwlib.appEvent.viewportSizeChange = function (width, height) { /** * New viewport width. * @type String */ this.width = width; /** * New viewport height. * @type String */ this.height = height; pwlib.appEvent.call(this, 'viewportSizeChange'); }; /** * @class Image zoom event. This event is cancelable. * * @augments pwlib.appEvent * * @param {Number} zoom The new image zoom level. * * @throws {TypeError} If the <var>zoom</var> argument is not a number. */ pwlib.appEvent.imageZoom = function (zoom) { if (typeof zoom !== 'number') { throw new TypeError('The first argument must be a number.'); } /** * The new image zoom level. * @type Number */ this.zoom = zoom; pwlib.appEvent.call(this, 'imageZoom', true); }; /** * @class Image crop event. This event is cancelable. * * @augments pwlib.appEvent * * @param {Number} x The crop start position on the x-axis. * @param {Number} y The crop start position on the y-axis. * @param {Number} width The cropped image width. * @param {Number} height The cropped image height. * * @throws {TypeError} If any of the arguments are not numbers. */ pwlib.appEvent.imageCrop = function (x, y, width, height) { if (typeof x !== 'number' || typeof y !== 'number' || typeof width !== 'number' || typeof height !== 'number') { throw new TypeError('All arguments must be numbers.'); } /** * The crop start position the x-axis. * @type Number */ this.x = x; /** * The crop start position the y-axis. * @type Number */ this.y = y; /** * The cropped image width. * @type Number */ this.width = width; /** * The cropped image height. * @type Number */ this.height = height; pwlib.appEvent.call(this, 'imageCrop', true); }; /** * @class Configuration change event. This event is not cancelable. * * @augments pwlib.appEvent * * @param {String|Number|Boolean} value The new value. * @param {String|Number|Boolean} previousValue The previous value. * @param {String} config The configuration property that just changed. * @param {String} group The configuration group where the property is found. * @param {Object} groupRef The configuration group object reference. * * @throws {TypeError} If the <var>prop</var> argument is not a string. * @throws {TypeError} If the <var>group</var> argument is not a string. * @throws {TypeError} If the <var>groupRef</var> argument is not an object. */ pwlib.appEvent.configChange = function (value, previousValue, config, group, groupRef) { if (typeof config !== 'string') { throw new TypeError('The third argument must be a string.'); } else if (typeof group !== 'string') { throw new TypeError('The fourth argument must be a string.'); } else if (typeof groupRef !== 'object') { throw new TypeError('The fifth argument must be an object.'); } /** * The new value. */ this.value = value; /** * The previous value. */ this.previousValue = previousValue; /** * Configuration property name. * @type String */ this.config = config; /** * Configuration group name. * @type String */ this.group = group; /** * Reference to the object holding the configuration property. * @type Object */ this.groupRef = groupRef; pwlib.appEvent.call(this, 'configChange'); }; /** * @class Canvas shadows allowed change event. This event is not cancelable. * * @augments pwlib.appEvent * * @param {Boolean} allowed Tells the new allowance value. * * @throws {TypeError} If the argument is not a boolean value. */ pwlib.appEvent.shadowAllow = function (allowed) { if (typeof allowed !== 'boolean') { throw new TypeError('The first argument must be a boolean.'); } /** * Tells if the Canvas shadows are allowed or not. * @type Boolean */ this.allowed = allowed; pwlib.appEvent.call(this, 'shadowAllow'); }; /** * @class Clipboard update event. This event is not cancelable. * * @augments pwlib.appEvent * * @param {ImageData} data Holds the clipboard ImageData. */ pwlib.appEvent.clipboardUpdate = function (data) { /** * The clipboard image data. * @type ImageData */ this.data = data; pwlib.appEvent.call(this, 'clipboardUpdate'); }; /** * @class An interface for adding, removing and dispatching of custom * application events. * * @param {Object} target_ The target for all the events. * * @see pwlib.appEvent to create application event objects. */ pwlib.appEvents = function (target_) { /** * Holds the list of event types and event handlers. * * @private * @type Object */ var events_ = {}; var eventID_ = 1; /** * Add an event listener. * * @param {String} type The event you want to listen for. * @param {Function} handler The event handler. * * @returns {Number} The event ID. * * @throws {TypeError} If the <var>type</var> argument is not a string. * @throws {TypeError} If the <var>handler</var> argument is not a function. * * @see pwlib.appEvents#remove to remove events. * @see pwlib.appEvents#dispatch to dispatch an event. */ this.add = function (type, handler) { if (typeof type !== 'string') { throw new TypeError('The first argument must be a string.'); } else if (typeof handler !== 'function') { throw new TypeError('The second argument must be a function.'); } var id = eventID_++; if (!(type in events_)) { events_[type] = {}; } events_[type][id] = handler; return id; }; /** * Remove an event listener. * * @param {String} type The event type. * @param {Number} id The event ID. * * @throws {TypeError} If the <var>type</var> argument is not a string. * * @see pwlib.appEvents#add to add events. * @see pwlib.appEvents#dispatch to dispatch an event. */ this.remove = function (type, id) { if (typeof type !== 'string') { throw new TypeError('The first argument must be a string.'); } if (!(type in events_) || !(id in events_[type])) { return; } delete events_[type][id]; }; /** * Dispatch an event. * * @param {String} type The event type. * @param {pwlib.appEvent} ev The event object. * * @returns {Boolean} True if the <code>event.preventDefault()</code> has been * invoked by one of the event handlers, or false if not. * * @throws {TypeError} If the <var>type</var> parameter is not a string. * @throws {TypeError} If the <var>ev</var> parameter is not an object. * * @see pwlib.appEvents#add to add events. * @see pwlib.appEvents#remove to remove events. * @see pwlib.appEvent the generic event object. */ this.dispatch = function (ev) { if (typeof ev !== 'object') { throw new TypeError('The second argument must be an object.'); } else if (typeof ev.type !== 'string') { throw new TypeError('The second argument must be an application event ' + 'object.'); } // No event handlers. if (!(ev.type in events_)) { return false; } ev.target = target_; var id, handlers = events_[ev.type]; for (id in handlers) { handlers[id].call(target_, ev); if (ev.propagationStopped_) { break; } } return ev.defaultPrevented; }; }; /** * @namespace Holds browser information. */ pwlib.browser = {}; (function () { var ua = ''; if (window.navigator && window.navigator.userAgent) { ua = window.navigator.userAgent.toLowerCase(); } /** * @type Boolean */ pwlib.browser.opera = window.opera || /\bopera\b/.test(ua); /** * Webkit is the render engine used primarily by Safari. It's also used by * Google Chrome and GNOME Epiphany. * * @type Boolean */ pwlib.browser.webkit = !pwlib.browser.opera && /\b(applewebkit|webkit)\b/.test(ua); /** * Firefox uses the Gecko render engine. * * @type Boolean */ // In some variations of the User Agent strings provided by Opera, Firefox is // mentioned. pwlib.browser.firefox = /\bfirefox\b/.test(ua) && !pwlib.browser.opera; /** * Gecko is the render engine used by Firefox and related products. * * @type Boolean */ // Typically, the user agent string of WebKit also mentions Gecko. Additionally, // Opera mentions Gecko for tricking some sites. pwlib.browser.gecko = /\bgecko\b/.test(ua) && !pwlib.browser.opera && !pwlib.browser.webkit; /** * Microsoft Internet Explorer. The future of computing. * * @type Boolean */ // Again, Opera allows users to easily fake the UA. pwlib.browser.msie = /\bmsie\b/.test(ua) && !pwlib.browser.opera; /** * Presto is the render engine used by Opera. * * @type Boolean */ // Older versions of Opera did not mention Presto in the UA string. pwlib.browser.presto = /\bpresto\b/.test(ua) || pwlib.browser.opera; /** * Browser operating system * * @type String */ pwlib.browser.os = (ua.match(/\b(windows|linux)\b/) || [])[1]; /** * Tells if the browser is running on an OLPC XO. Typically, only the default * Gecko-based browser includes the OLPC XO tokens in the user agent string. * * @type Boolean */ pwlib.browser.olpcxo = /\bolpc\b/.test(ua) && /\bxo\b/.test(ua); delete ua; })(); /** * @namespace Holds methods and properties necessary for DOM manipulation. */ pwlib.dom = {}; /** * @namespace Holds the list of virtual key identifiers and a few characters, * each being associated to a key code commonly used by Web browsers. * * @private */ pwlib.dom.keyNames = { Help: 6, Backspace: 8, Tab: 9, Clear: 12, Enter: 13, Shift: 16, Control: 17, Alt: 18, Pause: 19, CapsLock: 20, Cancel: 24, 'Escape': 27, Space: 32, PageUp: 33, PageDown: 34, End: 35, Home: 36, Left: 37, Up: 38, Right: 39, Down: 40, PrintScreen: 44, Insert: 45, 'Delete': 46, Win: 91, ContextMenu: 93, '*': 106, '+': 107, F1: 112, F2: 113, F3: 114, F4: 115, F5: 116, F6: 117, F7: 118, F8: 119, F9: 120, F10: 121, F11: 122, F12: 123, NumLock: 144, ';': 186, '=': 187, ',': 188, '-': 189, '.': 190, '/': 191, '`': 192, '[': 219, '\\': 220, ']': 221, "'": 222 }; /** * @namespace Holds the list of codes, each being associated to a virtual key * identifier. * * @private */ pwlib.dom.keyCodes = { /* * For almost each key code, these comments give the key name, the * keyIdentifier from the DOM 3 Events spec and the Unicode character * information (if you would use the decimal code for direct conversion to * a character, e.g. String.fromCharCode()). Obviously, the Unicode character * information is not to be used, since these are only virtual key codes (not * really char codes) associated to key names. * * Each key name in here tries to follow the same style as the defined * keyIdentifiers from the DOM 3 Events. Thus for the Page Down button, * 'PageDown' is used (not other variations like 'pag-up'), and so on. * * Multiple key codes might be associated to the same key - it's not an error. * * Note that this list is not an exhaustive key codes list. This means that * for key A or for key 0, the script will do String.fromCharCode(keyCode), to * determine the key. For the case of alpha-numeric keys, this works fine. */ /* * Key: Enter * Unicode: U+0003 [End of text] * * Note 1: This keyCode is only used in Safari 2 (older Webkit) for the Enter * key. * * Note 2: In Gecko this keyCode is used for the Cancel key (see * DOM_VK_CANCEL). */ 3: 'Enter', /* * Key: Help * Unicode: U+0006 [Acknowledge] * * Note: Taken from Gecko (DOM_VK_HELP). */ 6: 'Help', /* * Key: Backspace * Unicode: U+0008 [Backspace] * keyIdentifier: U+0008 */ 8: 'Backspace', /* * Key: Tab * Unicode: U+0009 [Horizontal tab] * keyIdentifier: U+0009 */ 9: 'Tab', /* * Key: Enter * Unicode: U+0010 [Line feed (LF) / New line (NL) / End of line (EOL)] * * Note: Taken from the Unicode characters list. If it ends up as a keyCode in * some event, it's simply considered as being the Enter key. */ 10: 'Enter', /* * Key: NumPad_Center * Unicode: U+000C [Form feed] * keyIdentifier: Clear * * Note 1: This keyCode is used when NumLock is off, and the user pressed the * 5 key on the numeric pad. * * Note 2: Safari 2 (older Webkit) assigns this keyCode to the NumLock key * itself. */ 12: 'Clear', /* * Key: Enter * Unicode: U+000D [Carriage return (CR)] * keyIdentifier: Enter * * Note 1: This is the keyCode used by most of the Web browsers when the Enter * key is pressed. * * Note 2: Gecko associates the DOM_VK_RETURN to this keyCode. */ 13: 'Enter', /* * Key: Enter * Unicode: U+000E [Shift out] * * Note: Taken from Gecko (DOM_VK_ENTER). */ 14: 'Enter', /* * Key: Shift * Unicode: U+0010 [Data link escape] * keyIdentifier: Shift * * Note: In older Safari (Webkit) versions Shift+Tab is assigned a different * keyCode: keyCode 25. */ 16: 'Shift', /* * Key: Control * Unicode: U+0011 [Device control one] * keyIdentifier: Control */ 17: 'Control', /* * Key: Alt * Unicode: U+0012 [Device control two] * keyIdentifier: Alt */ 18: 'Alt', /* * Key: Pause * Unicode: U+0013 [Device control three] * keyIdentifier: Pause */ 19: 'Pause', /* * Key: CapsLock * Unicode: U+0014 [Device control four] * keyIdentifier: CapsLock */ 20: 'CapsLock', /* * Key: Cancel * Unicode: U+0018 [Cancel] * keyIdentifier: U+0018 */ 24: 'Cancel', /* * Key: Escape * Unicode: U+001B [Escape] * keyIdentifier: U+001B */ 27: 'Escape', /* * Key: Space * Unicode: U+0020 [Space] * keyIdentifier: U+0020 */ 32: 'Space', /* * Key: PageUp or NumPad_North_East * Unicode: U+0021 ! [Exclamation mark] * keyIdentifier: PageUp */ 33: 'PageUp', /* * Key: PageDown or NumPad_South_East * Unicode: U+0022 " [Quotation mark] * keyIdentifier: PageDown */ 34: 'PageDown', /* * Key: End or NumPad_South_West * Unicode: U+0023 # [Number sign] * keyIdentifier: PageDown */ 35: 'End', /* * Key: Home or NumPad_North_West * Unicode: U+0024 $ [Dollar sign] * keyIdentifier: Home */ 36: 'Home', /* * Key: Left or NumPad_West * Unicode: U+0025 % [Percent sign] * keyIdentifier: Left */ 37: 'Left', /* * Key: Up or NumPad_North * Unicode: U+0026 & [Ampersand] * keyIdentifier: Up */ 38: 'Up', /* * Key: Right or NumPad_East * Unicode: U+0027 ' [Apostrophe] * keyIdentifier: Right */ 39: 'Right', /* * Key: Down or NumPad_South * Unicode: U+0028 ( [Left parenthesis] * keyIdentifier: Down */ 40: 'Down', /* * Key: PrintScreen * Unicode: U+002C , [Comma] * keyIdentifier: PrintScreen */ //44: 'PrintScreen', /* * Key: Insert or NumPad_Insert * Unicode: U+002D - [Hyphen-Minus] * keyIdentifier: Insert */ 45: 'Insert', /* * Key: Delete or NumPad_Delete * Unicode: U+002E . [Full stop / period] * keyIdentifier: U+007F */ 46: 'Delete', /* * Key: WinLeft * Unicode: U+005B [ [Left square bracket] * keyIdentifier: Win * * Disabled: rarely needed. */ //91: 'Win', /* * Key: WinRight * Unicode: U+005C \ [Reverse solidus / Backslash] * keyIdentifier: Win */ //92: 'Win', /* * Key: Menu/ContextMenu * Unicode: U+005D ] [Right square bracket] * keyIdentifier: ... * * Disabled: Is it Meta? Is it Menu, ContextMenu, what? Too much mess. */ //93: 'ContextMenu', /* * Key: NumPad_0 * Unicode: U+0060 ` [Grave accent] * keyIdentifier: 0 */ 96: '0', /* * Key: NumPad_1 * Unicode: U+0061 a [Latin small letter a] * keyIdentifier: 1 */ 97: '1', /* * Key: NumPad_2 * Unicode: U+0062 b [Latin small letter b] * keyIdentifier: 2 */ 98: '2', /* * Key: NumPad_3 * Unicode: U+0063 c [Latin small letter c] * keyIdentifier: 3 */ 99: '3', /* * Key: NumPad_4 * Unicode: U+0064 d [Latin small letter d] * keyIdentifier: 4 */ 100: '4', /* * Key: NumPad_5 * Unicode: U+0065 e [Latin small letter e] * keyIdentifier: 5 */ 101: '5', /* * Key: NumPad_6 * Unicode: U+0066 f [Latin small letter f] * keyIdentifier: 6 */ 102: '6', /* * Key: NumPad_7 * Unicode: U+0067 g [Latin small letter g] * keyIdentifier: 7 */ 103: '7', /* * Key: NumPad_8 * Unicode: U+0068 h [Latin small letter h] * keyIdentifier: 8 */ 104: '8', /* * Key: NumPad_9 * Unicode: U+0069 i [Latin small letter i] * keyIdentifier: 9 */ 105: '9', /* * Key: NumPad_Multiply * Unicode: U+0070 j [Latin small letter j] * keyIdentifier: U+002A * [Asterisk / Star] */ 106: '*', /* * Key: NumPad_Plus * Unicode: U+0071 k [Latin small letter k] * keyIdentifier: U+002B + [Plus] */ 107: '+', /* * Key: NumPad_Minus * Unicode: U+0073 m [Latin small letter m] * keyIdentifier: U+002D + [Hyphen / Minus] */ 109: '-', /* * Key: NumPad_Period * Unicode: U+0074 n [Latin small letter n] * keyIdentifier: U+002E . [Period] */ 110: '.', /* * Key: NumPad_Division * Unicode: U+0075 o [Latin small letter o] * keyIdentifier: U+002F / [Solidus / Slash] */ 111: '/', 112: 'F1', // p 113: 'F2', // q 114: 'F3', // r 115: 'F4', // s 116: 'F5', // t 117: 'F6', // u 118: 'F7', // v 119: 'F8', // w 120: 'F9', // x 121: 'F10', // y 122: 'F11', // z 123: 'F12', // { /* * Key: Delete * Unicode: U+007F [Delete] * keyIdentifier: U+007F */ 127: 'Delete', /* * Key: NumLock * Unicode: U+0090 [Device control string] * keyIdentifier: NumLock */ 144: 'NumLock', 186: ';', // º (Masculine ordinal indicator) 187: '=', // » 188: ',', // ¼ 189: '-', // ½ 190: '.', // ¾ 191: '/', // ¿ 192: '`', // À 219: '[', // Û 220: '\\', // Ü 221: ']', // Ý 222: "'" // Þ (Latin capital letter thorn) //224: 'Win', // à //229: 'WinIME', // å or WinIME or something else in Webkit //255: 'NumLock', // ÿ, Gecko and Chrome, Windows XP in VirtualBox //376: 'NumLock' // Ÿ, Opera, Windows XP in VirtualBox }; if (pwlib.browser.gecko) { pwlib.dom.keyCodes[3] = 'Cancel'; // DOM_VK_CANCEL } /** * @namespace Holds a list of common wrong key codes in Web browsers. * * @private */ pwlib.dom.keyCodes_fixes = { 42: pwlib.dom.keyNames['*'], // char * to key * 47: pwlib.dom.keyNames['/'], // char / to key / 59: pwlib.dom.keyNames[';'], // char ; to key ; 61: pwlib.dom.keyNames['='], // char = to key = 96: 48, // NumPad_0 to char 0 97: 49, // NumPad_1 to char 1 98: 50, // NumPad_2 to char 2 99: 51, // NumPad_3 to char 3 100: 52, // NumPad_4 to char 4 101: 53, // NumPad_5 to char 5 102: 54, // NumPad_6 to char 6 103: 55, // NumPad_7 to char 7 104: 56, // NumPad_8 to char 8 105: 57, // NumPad_9 to char 9 //106: 56, // NumPad_Multiply to char 8 //107: 187, // NumPad_Plus to key = 109: pwlib.dom.keyNames['-'], // NumPad_Minus to key - 110: pwlib.dom.keyNames['.'], // NumPad_Period to key . 111: pwlib.dom.keyNames['/'] // NumPad_Division to key / }; /** * @namespace Holds the list of broken key codes generated by older Webkit * (Safari 2). * * @private */ pwlib.dom.keyCodes_Safari2 = { 63232: pwlib.dom.keyNames.Up, // 38 63233: pwlib.dom.keyNames.Down, // 40 63234: pwlib.dom.keyNames.Left, // 37 63235: pwlib.dom.keyNames.Right, // 39 63236: pwlib.dom.keyNames.F1, // 112 63237: pwlib.dom.keyNames.F2, // 113 63238: pwlib.dom.keyNames.F3, // 114 63239: pwlib.dom.keyNames.F4, // 115 63240: pwlib.dom.keyNames.F5, // 116 63241: pwlib.dom.keyNames.F6, // 117 63242: pwlib.dom.keyNames.F7, // 118 63243: pwlib.dom.keyNames.F8, // 119 63244: pwlib.dom.keyNames.F9, // 120 63245: pwlib.dom.keyNames.F10, // 121 63246: pwlib.dom.keyNames.F11, // 122 63247: pwlib.dom.keyNames.F12, // 123 63248: pwlib.dom.keyNames.PrintScreen, // 44 63272: pwlib.dom.keyNames['Delete'], // 46 63273: pwlib.dom.keyNames.Home, // 36 63275: pwlib.dom.keyNames.End, // 35 63276: pwlib.dom.keyNames.PageUp, // 33 63277: pwlib.dom.keyNames.PageDown, // 34 63289: pwlib.dom.keyNames.NumLock, // 144 63302: pwlib.dom.keyNames.Insert // 45 }; /** * A complete keyboard events cross-browser compatibility layer. * * <p>Unfortunately, due to the important differences across Web browsers, * simply using the available properties in a single keyboard event is not * enough to accurately determine the key the user pressed. Thus, one needs to * have event handlers for all keyboard-related events <code>keydown</code>, * <code>keypress</code> and <code>keyup</code>. * * <p>This class provides a complete keyboard event compatibility layer. For any * new instance you provide the DOM element you want to listen events for, and * the event handlers for any of the three events <code>keydown</code> * / <code>keypress</code> / <code>keyup</code>. * * <p>Your event handlers will receive the original DOM Event object, with * several new properties defined: * * <ul> * <li><var>event.keyCode_</var> holds the correct code for event key. * * <li><var>event.key_</var> holds the key the user pressed. It can be either * a key name like "PageDown", "Delete", "Enter", or it is a character like * "A", "1", or "[". * * <li><var>event.charCode_</var> holds the Unicode character decimal code. * * <li><var>event.char_</var> holds the character generated by the event. * * <li><var>event.repeat_</var> is a boolean property telling if the * <code>keypress</code> event is repeated - the user is holding down the key * for a long-enough period of time to generate multiple events. * </ul> * * <p>The character-related properties, <var>charCode_</var> and * <var>char_</var> are only available in the <code>keypress</code> and * <code>keyup</code> event objects. * * <p>This class will ensure that the <code>keypress</code> event is always * fired in Webkit and MSIE for all keys, except modifiers. For modifier keys * like <kbd>Shift</kbd>, <kbd>Control</kbd>, and <kbd>Alt</kbd>, the * <code>keypress</code> event will not be fired, even if the Web browser does * it. * * <p>Some user agents like Webkit repeat the <code>keydown</code> event while * the user holds down a key. This class will ensure that only the * <code>keypress</code> event is repeated. * * <p>If you want to prevent the default action for an event, you should prevent * it on <code>keypress</code>. This class will prevent the default action for * <code>keydown</code> if need (in MSIE). * * @example * <code>var <var>klogger</var> = function (<var>ev</var>) { * console.log(<var>ev</var>.type + * ' keyCode_ ' + <var>ev</var>.keyCode_ + * ' key_ ' + <var>ev</var>.key_ + * ' charCode_ ' + <var>ev</var>.charCode_ + * ' char_ ' + <var>ev</var>.char_ + * ' repeat_ ' + <var>ev</var>.repeat_); * }; * * var <var>kbListener</var> = new pwlib.dom.KeyboardEventListener(window, * {keydown: <var>klogger</var>, * keypress: <var>klogger</var>, * keyup: <var>klogger</var>});</code> * * // later when you're done... * <code><var>kbListener</var>.detach();</code> * * @class A complete keyboard events cross-browser compatibility layer. * * @param {Element} elem_ The DOM Element you want to listen events for. * * @param {Object} handlers_ The object holding the list of event handlers * associated to the name of each keyboard event you want to listen. To listen * for all the three keyboard events use <code>{keydown: <var>fn1</var>, * keypress: <var>fn2</var>, keyup: <var>fn3</var>}</code>. * * @throws {TypeError} If the <var>handlers_</var> object does not contain any * event handler. */ pwlib.dom.KeyboardEventListener = function (elem_, handlers_) { /* Technical details: For the keyup and keydown events the keyCode provided is that of the virtual key irrespective of other modifiers (e.g. Shift). Generally, during the keypress event, the keyCode holds the Unicode value of the character resulted from the key press, say an alphabetic upper/lower-case char, depending on the actual intent of the user and depending on the currently active keyboard layout. Examples: * Pressing p you get keyCode 80 in keyup/keydown, and keyCode 112 in keypress. String.fromCharCode(80) = 'P' and String.fromCharCode(112) = 'p'. * Pressing P you get keyCode 80 in all events. * Pressing F1 you get keyCode 112 in keyup, keydown and keypress. * Pressing 9 you get keyCode 57 in all events. * Pressing Shift+9 you get keyCode 57 in keyup/keydown, and keyCode 40 in keypress. String.fromCharCode(57) = '9' and String.fromCharCode(40) = '('. * Using the Greek layout when you press v on an US keyboard you get the output character ω. The keyup/keydown events hold keyCode 86 which is V. This does make sense, since it's the virtual key code we are dealing with - not the character code, not the result of pressing the key. The keypress event will hold keyCode 969 (ω). * Pressing NumPad_Minus you get keyCode 109 in keyup/keydown and keyCode 45 in keypress. Again, this happens because in keyup/keydown you don't get the character code, you get the key code, as indicated above. For your information: String.fromCharCode(109) = 'm' and String.fromCharCode(45) = '-'. Therefore, we need to map all the codes of several keys, like F1-F12, Escape, Enter, Tab, etc. This map is held by pwlib.dom.keyCodes. It associates, for example, code 112 to F1, or 13 to Enter. This map is used to detect virtual keys in all events. (This is only the general story, details about browser-specific differences follow below.) If the code given by the browser doesn't appear in keyCode maps, it's used as is. The key_ returned is that of String.fromCharCode(keyCode). In all browsers we consider all events having keyCode <= 32, as being events generated by a virtual key (not a character). As such, the keyCode value is always searched in pwlib.dom.keyCodes. As you might notice from the above description, in the keypress event we cannot tell the difference from say F1 and p, because both give the code 112. In Gecko and Webkit we can tell the difference because these UAs also set the charCode event property when the key generates a character. If F1 is pressed, or some other virtual key, charCode is never set. In Opera the charCode property is never set. However, the 'which' event property is not set for several virtual keys. This means we can tell the difference between a character and a virtual key. However, there's a catch: not *all* virtual keys have the 'which' property unset. Known exceptions: Backspace (8), Tab (9), Enter (13), Shift (16), Control (17), Alt (18), Pause (19), Escape (27), End (35), Home (36), Insert (45), Delete (46) and NumLock (144). Given we already consider any keyCode <= 32 being one of some virtual key, fewer exceptions remain. We only have the End, Home, Insert, Delete and the NumLock keys which cannot be 100% properly detected in the keypress event, in Opera. To properly detect End/Home we can check if the Shift modifier is active or not. If the user wants # instead of End, then Shift must be active. The same goes for $ and Home. Thus we now only have the '-' (Insert) and the '.' (Delete) characters incorrectly detected as being Insert/Delete. The above brings us to one of the main visible difference, when comparing the pwlib.dom.KeyboardEventListener class and the simple pwlib.dom.KeyboardEvent.getKey() function. In getKey(), for the keypress event we cannot accurately determine the exact key, because it requires checking the keyCode used for the keydown event. The KeyboardEventListener class monitors all the keyboard events, ensuring a more accurate key detection. Different keyboard layouts and international characters are generally supported. Tested and known to work with the Cyrillic alphabet (Greek keyboard layout) and with the US Dvorak keyboard layouts. Opera does not fire the keyup event for international characters when running on Linux. For example, this happens with the Greek keyboard layout, when trying Cyrillic characters. Gecko gives no keyCode/charCode/which for international characters when running on Linux, in the keyup/keydown events. Thus, all such keys remain unidentified for these two events. For the keypress event there are no issues with such characters. Webkit and Konqueror 4 also implement the keyIdentifier property from the DOM 3 Events specification. In theory, this should be great, but it's not without problems. Sometimes keyCode/charCode/which are all 0, but keyIdentifier is properly set. For several virtual keys the keyIdentifier value is simply 'U+0000'. Thus, the keyIdentifier is used only if the value is not 'Unidentified' / 'U+0000', and only when keyCode/charCode/which are not available. Konqueror 4 does not use the 'U+XXXX' notation for Unicode characters. It simply gives the character, directly. Additionally, Konqueror seems to have some problems with several keyCodes in keydown/keyup. For example, the key '[' gives keyCode 91 instead of 219. Thus, it effectively gives the Unicode for the character, not the key code. This issue is visible with other key as well. NumPad_Clear is unidentified on Linux in all browsers, but it works on Windows. In MSIE the keypress event is only fired for characters and for Escape, Space and Enter. Similarly, Webkit only fires the keypress event for characters. However, Webkit does not fire keypress for Escape. International characters and different keyboard layouts seem to work fine in MSIE as well. As of MSIE 4.0, the keypress event fires for the following keys: * Letters: A - Z (uppercase and lowercase) * Numerals: 0 - 9 * Symbols: ! @ # $ % ^ & * ( ) _ - + = < [ ] { } , . / ? \ | ' ` " ~ * System: Escape (27), Space (32), Enter (13) Documentation about the keypress event: http://msdn.microsoft.com/en-us/library/ms536939(VS.85).aspx As of MSIE 4.0, the keydown event fires for the following keys: * Editing: Delete (46), Insert (45) * Function: F1 - F12 * Letters: A - Z (uppercase and lowercase) * Navigation: Home, End, Left, Right, Up, Down * Numerals: 0 - 9 * Symbols: ! @ # $ % ^ & * ( ) _ - + = < [ ] { } , . / ? \ | ' ` " ~ * System: Escape (27), Space (32), Shift (16), Tab (9) As of MSIE 5, the event also fires for the following keys: * Editing: Backspace (8) * Navigation: PageUp (33), PageDown (34) * System: Shift+Tab (9) Documentation about the keydown event: http://msdn.microsoft.com/en-us/library/ms536938(VS.85).aspx As of MSIE 4.0, the keyup event fires for the following keys: * Editing: Delete, Insert * Function: F1 - F12 * Letters: A - Z (uppercase and lowercase) * Navigation: Home (36), End (35), Left (37), Right (39), Up (38), Down (40) * Numerals: 0 - 9 * Symbols: ! @ # $ % ^ & * ( ) _ - + = < [ ] { } , . / ? \ | ' ` " ~ * System: Escape (27), Space (32), Shift (16), Tab (9) As of MSIE 5, the event also fires for the following keys: * Editing: Backspace (8) * Navigation: PageUp (33), PageDown (34) * System: Shift+Tab (9) Documentation about the keyup event: http://msdn.microsoft.com/en-us/library/ms536940(VS.85).aspx For further gory details and a different implementation see: http://code.google.com/p/doctype/source/browse/trunk/goog/events/keycodes.js http://code.google.com/p/doctype/source/browse/trunk/goog/events/keyhandler.js Opera keydown/keyup: These events fire for all keys, including for modifiers. keyCode is always set. charCode is never set. which is always set. keyIdentifier is always undefined. Opera keypress: This event fires for all keys, except for modifiers themselves. keyCode is always set. charCode is never set. which is set for all characters. which = 0 for several virtual keys. which is known to be set for: Backspace (8), Tab (9), Enter (13), Shift (16), Control (17), Alt (18), Pause (19), Escape (27), End (35), Home (36), Insert (45), Delete (46), NumLock (144). which is known to be unset for: F1 - F12, PageUp (33), PageDown (34), Left (37), Up (38), Right (39), Down (40). keyIdentifier is always undefined. MSIE keyup/keypress/keydown: Event firing conditions are described above. keyCode is always set. charCode is never set. which is never set. keyIdentifier is always undefined. Webkit keydown/keyup: These events fires for all keys, including for modifiers. keyCode is always set. charCode is never set. which is always set. keyIdentifier is always set. Webkit keypress: This event fires for characters keys, similarly to MSIE (see above info). keyCode is always set. charCode is always set for all characters. which is always set. keyIdentifier is null. Gecko keydown/keyup: These events fire for all keys, including for modifiers. keyCode is always set. charCode is never set. which is always set. keyIdentifier is always undefined. Gecko keypress: This event fires for all keys, except for modifiers themselves. keyCode is only set for virtual keys, not for characters. charCode is always set for all characters. which is always set for all characters and for the Enter virtual key. keyIdentifier is always undefined. Another important difference between the KeyboardEventListener class and the getKey() function is that the class tries to ensure that the keypress event is fired for the handler, even if the Web browser does not do it natively. Also, the class tries to provide a consistent approach to keyboard event repetition when the user holds down a key for longer periods of time, by repeating only the keypress event. On Linux, Opera, Firefox and Konqueror do not repeat the keydown event, only keypress. On Windows, Opera, Firefox and MSIE do repeat the keydown and keypress events while the user holds down the key. Webkit repeats the keydown and the keypress (when it fires) events on both systems. The default action can be prevented for during keydown in MSIE, and during keypress for the other browsers. In Webkit when keypress doesn't fire, keydown needs to be prevented. The KeyboardEventListener class tries to bring consistency. The keydown event never repeats, only the keypress event repeats and it always fires for all keys. The keypress event never fires for modifiers. Events should always be prevented during keypress - the class deals with preventing the event during keydown or keypress as needed in Webkit and MSIE. If no code/keyIdentifier is given by the browser, the getKey() function returns null. In the case of the KeyboardEventListener class, keyCode_ / key_ / charCode_ / char_ will be null or undefined. */ /** * During a keyboard event flow, this holds the current key code, starting * from the <code>keydown</code> event. * * @private * @type Number */ var keyCode_ = null; /** * During a keyboard event flow, this holds the current key, starting from the * <code>keydown</code> event. * * @private * @type String */ var key_ = null; /** * During a keyboard event flow, this holds the current character code, * starting from the <code>keypress</code> event. * * @private * @type Number */ var charCode_ = null; /** * During a keyboard event flow, this holds the current character, starting * from the <code>keypress</code> event. * * @private * @type String */ var char_ = null; /** * True if the current keyboard event is repeating. This happens when the user * holds down a key for longer periods of time. * * @private * @type Boolean */ var repeat_ = false; if (!handlers_) { throw new TypeError('The first argument must be of type an object.'); } if (!handlers_.keydown && !handlers_.keypress && !handlers_.keyup) { throw new TypeError('The provided handlers object has no keyboard event' + 'handler.'); } if (handlers_.keydown && typeof handlers_.keydown !== 'function') { throw new TypeError('The keydown event handler is not a function!'); } if (handlers_.keypress && typeof handlers_.keypress !== 'function') { throw new TypeError('The keypress event handler is not a function!'); } if (handlers_.keyup && typeof handlers_.keyup !== 'function') { throw new TypeError('The keyup event handler is not a function!'); } /** * Attach the keyboard event listeners to the current DOM element. */ this.attach = function () { keyCode_ = null; key_ = null; charCode_ = null; char_ = null; repeat_ = false; // FIXME: I have some ideas for a solution to the problem of having multiple // event handlers like these attached to the same element. Somehow, only one // should do all the needed work. elem_.addEventListener('keydown', keydown, false); elem_.addEventListener('keypress', keypress, false); elem_.addEventListener('keyup', keyup, false); }; /** * Detach the keyboard event listeners from the current DOM element. */ this.detach = function () { elem_.removeEventListener('keydown', keydown, false); elem_.removeEventListener('keypress', keypress, false); elem_.removeEventListener('keyup', keyup, false); keyCode_ = null; key_ = null; charCode_ = null; char_ = null; repeat_ = false; }; /** * Dispatch an event. * * <p>This function simply invokes the handler for the event of the given * <var>type</var>. The handler receives the <var>ev</var> event. * * @private * @param {String} type The event type to dispatch. * @param {Event} ev The DOM Event object to dispatch to the handler. */ function dispatch (type, ev) { if (!handlers_[type]) { return; } var handler = handlers_[type]; if (type === ev.type) { handler.call(elem_, ev); } else { // This happens when the keydown event tries to dispatch a keypress event. // FIXME: I could use createEvent() ... food for thought for later. /** @ignore */ var ev_new = {}; pwlib.extend(ev_new, ev); ev_new.type = type; // Make sure preventDefault() is not borked... /** @ignore */ ev_new.preventDefault = function () { ev.preventDefault(); }; handler.call(elem_, ev_new); } }; /** * The <code>keydown</code> event handler. This function determines the key * pressed by the user, and checks if the <code>keypress</code> event will * fire in the current Web browser, or not. If it does not, a synthetic * <code>keypress</code> event will be fired. * * @private * @param {Event} ev The DOM Event object. */ function keydown (ev) { var prevKey = key_; charCode_ = null; char_ = null; findKeyCode(ev); ev.keyCode_ = keyCode_; ev.key_ = key_; ev.repeat_ = key_ && prevKey === key_ ? true : false; repeat_ = ev.repeat_; // When the user holds down a key for a longer period of time, the keypress // event is generally repeated. However, in Webkit keydown is repeated (and // keypress if it fires keypress for the key). As such, we do not dispatch // the keydown event when a key event starts to be repeated. if (!repeat_) { dispatch('keydown', ev); } // MSIE and Webkit only fire the keypress event for characters // (alpha-numeric and symbols). if (!isModifierKey(key_) && !firesKeyPress(ev)) { ev.type_ = 'keydown'; keypress(ev); } }; /** * The <code>keypress</code> event handler. This function determines the * character generated by the keyboard event. * * @private * @param {Event} ev The DOM Event object. */ function keypress (ev) { // We reuse the keyCode_/key_ from the keydown event, because ev.keyCode // generally holds the character code during the keypress event. // However, if keyCode_ is not available, try to determine the key for this // event as well. if (!keyCode_) { findKeyCode(ev); repeat_ = false; } ev.keyCode_ = keyCode_; ev.key_ = key_; findCharCode(ev); ev.charCode_ = charCode_; ev.char_ = char_; // Any subsequent keypress event is considered a repeated keypress (the user // is holding down the key). ev.repeat_ = repeat_; if (!repeat_) { repeat_ = true; } if (!isModifierKey(key_)) { dispatch('keypress', ev); } }; /** * The <code>keyup</code> event handler. * * @private * @param {Event} ev The DOM Event object. */ function keyup (ev) { /* * Try to determine the keyCode_ for keyup again, even if we might already * have it from keydown. This is needed because the user might press some * key which only generates the keydown and keypress events, after which * a sudden keyup event is fired for a completely different key. * * Example: in Opera press F2 then Escape. It will first generate two * events, keydown and keypress, for the F2 key. When you press Escape to * close the dialog box, the script receives keyup for Escape. */ findKeyCode(ev); ev.keyCode_ = keyCode_; ev.key_ = key_; // Provide the character info from the keypress event in keyup as well. ev.charCode_ = charCode_; ev.char_ = char_; dispatch('keyup', ev); keyCode_ = null; key_ = null; charCode_ = null; char_ = null; repeat_ = false; }; /** * Tells if the <var>key</var> is a modifier or not. * * @private * @param {String} key The key name. * @returns {Boolean} True if the <var>key</var> is a modifier, or false if * not. */ function isModifierKey (key) { switch (key) { case 'Shift': case 'Control': case 'Alt': case 'Meta': case 'Win': return true; default: return false; } }; /** * Tells if the current Web browser will fire the <code>keypress</code> event * for the current <code>keydown</code> event object. * * @private * @param {Event} ev The DOM Event object. * @returns {Boolean} True if the Web browser will fire * a <code>keypress</code> event, or false if not. */ function firesKeyPress (ev) { // Gecko does not fire keypress for the Up/Down arrows when the target is an // input element. if ((key_ === 'Up' || key_ === 'Down') && pwlib.browser.gecko && ev.target && ev.target.tagName.toLowerCase() === 'input') { return false; } if (!pwlib.browser.msie && !pwlib.browser.webkit) { return true; } // Check if the key is a character key, or not. // If it's not a character, then keypress will not fire. // Known exceptions: keypress fires for Space, Enter and Escape in MSIE. if (key_ && key_ !== 'Space' && key_ !== 'Enter' && key_ !== 'Escape' && key_.length !== 1) { return false; } // Webkit doesn't fire keypress for Escape as well ... if (pwlib.browser.webkit && key_ === 'Escape') { return false; } // MSIE does not fire keypress if you hold Control / Alt down, while Shift // is off. Albeit, based on testing I am not completely sure if Shift needs // to be down or not. Sometimes MSIE won't fire keypress even if I hold // Shift down, and sometimes it does. Eh. if (pwlib.browser.msie && !ev.shiftKey && (ev.ctrlKey || ev.altKey)) { return false; } return true; }; /** * Determine the key and the key code for the current DOM Event object. This * function updates the <var>keyCode_</var> and the <var>key_</var> variables * to hold the result. * * @private * @param {Event} ev The DOM Event object. */ function findKeyCode (ev) { /* * If the event has no keyCode/which/keyIdentifier values, then simply do * not overwrite any existing keyCode_/key_. */ if (ev.type === 'keyup' && !ev.keyCode && !ev.which && (!ev.keyIdentifier || ev.keyIdentifier === 'Unidentified' || ev.keyIdentifier === 'U+0000')) { return; } keyCode_ = null; key_ = null; // Try to use keyCode/which. if (ev.keyCode || ev.which) { keyCode_ = ev.keyCode || ev.which; // Fix Webkit quirks if (pwlib.browser.webkit) { // Old Webkit gives keyCode 25 when Shift+Tab is used. if (keyCode_ == 25 && this.shiftKey) { keyCode_ = pwlib.dom.keyNames.Tab; } else if (keyCode_ >= 63232 && keyCode_ in pwlib.dom.keyCodes_Safari2) { // Old Webkit gives wrong values for several keys. keyCode_ = pwlib.dom.keyCodes_Safari2[keyCode_]; } } // Fix keyCode quirks in all browsers. if (keyCode_ in pwlib.dom.keyCodes_fixes) { keyCode_ = pwlib.dom.keyCodes_fixes[keyCode_]; } key_ = pwlib.dom.keyCodes[keyCode_] || String.fromCharCode(keyCode_); return; } // Try to use ev.keyIdentifier. This is only available in Webkit and // Konqueror 4, each having some quirks. Sometimes the property is needed, // because keyCode/which are not always available. var key = null, keyCode = null, id = ev.keyIdentifier; if (!id || id === 'Unidentified' || id === 'U+0000') { return; } if (id.substr(0, 2) === 'U+') { // Webkit gives character codes using the 'U+XXXX' notation, as per spec. keyCode = parseInt(id.substr(2), 16); } else if (id.length === 1) { // Konqueror 4 implements keyIdentifier, and they provide the Unicode // character directly, instead of using the 'U+XXXX' notation. keyCode = id.charCodeAt(0); key = id; } else { /* * Common keyIdentifiers like 'PageDown' are used as they are. * We determine the common keyCode used by Web browsers, from the * pwlib.dom.keyNames object. */ keyCode_ = pwlib.dom.keyNames[id] || null; key_ = id; return; } // Some keyIdentifiers like 'U+007F' (127: Delete) need to become key names. if (keyCode in pwlib.dom.keyCodes && (keyCode <= 32 || keyCode == 127 || keyCode == 144)) { key_ = pwlib.dom.keyCodes[keyCode]; } else { if (!key) { key = String.fromCharCode(keyCode); } // Konqueror gives lower-case chars key_ = key.toUpperCase(); if (key !== key_) { keyCode = key_.charCodeAt(0); } } // Correct the keyCode, make sure it's a common keyCode, not the Unicode // decimal representation of the character. if (key_ === 'Delete' || key_.length === 1 && key_ in pwlib.dom.keyNames) { keyCode = pwlib.dom.keyNames[key_]; } keyCode_ = keyCode; }; /** * Determine the character and the character code for the current DOM Event * object. This function updates the <var>charCode_</var> and the * <var>char_</var> variables to hold the result. * * @private * @param {Event} ev The DOM Event object. */ function findCharCode (ev) { charCode_ = null; char_ = null; // Webkit and Gecko implement ev.charCode. if (ev.charCode) { charCode_ = ev.charCode; char_ = String.fromCharCode(ev.charCode); return; } // Try the keyCode mess. if (ev.keyCode || ev.which) { var keyCode = ev.keyCode || ev.which; var force = false; // We accept some keyCodes. switch (keyCode) { case pwlib.dom.keyNames.Tab: case pwlib.dom.keyNames.Enter: case pwlib.dom.keyNames.Space: force = true; } // Do not consider the keyCode a character code, if during the keydown // event it was determined the key does not generate a character, unless // it's Tab, Enter or Space. if (!force && key_ && key_.length !== 1) { return; } // If the keypress event at hand is synthetically dispatched by keydown, // then special treatment is needed. This happens only in Webkit and MSIE. if (ev.type_ === 'keydown') { var key = pwlib.dom.keyCodes[keyCode]; // Check if the keyCode points to a single character. // If it does, use it. if (key && key.length === 1) { charCode_ = key.charCodeAt(0); // keyCodes != charCodes char_ = key; } } else if (keyCode >= 32 || force) { // For normal keypress events, we are done. charCode_ = keyCode; char_ = String.fromCharCode(keyCode); } if (charCode_) { return; } } /* * Webkit and Konqueror do not provide a keyIdentifier in the keypress * event, as per spec. However, in the unlikely case when the keyCode is * missing, and the keyIdentifier is available, we use it. * * This property might be used when a synthetic keypress event is generated * by the keydown event, and keyCode/charCode/which are all not available. */ var c = null, charCode = null, id = ev.keyIdentifier; if (id && id !== 'Unidentified' && id !== 'U+0000' && (id.substr(0, 2) === 'U+' || id.length === 1)) { // Characters in Konqueror... if (id.length === 1) { charCode = id.charCodeAt(0); c = id; } else { // Webkit uses the 'U+XXXX' notation as per spec. charCode = parseInt(id.substr(2), 16); } if (charCode == pwlib.dom.keyNames.Tab || charCode == pwlib.dom.keyNames.Enter || charCode >= 32 && charCode != 127 && charCode != pwlib.dom.keyNames.NumLock) { charCode_ = charCode; char_ = c || String.fromCharCode(charCode); return; } } // Try to use the key determined from the previous keydown event, if it // holds a character. if (key_ && key_.length === 1) { charCode_ = key_.charCodeAt(0); char_ = key_; } }; this.attach(); }; // Check out the libmacrame project: http://code.google.com/p/libmacrame. // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* http://www.JSON.org/json2.js 2009-04-16 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the object holding the key. For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. */ /*jslint evil: true */ /*global JSON */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. if (!this.JSON) { JSON = {}; } (function () { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/. test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@'). replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } }());
JavaScript
/* * © 2009 ROBO Design * http://www.robodesign.ro * * $Date: 2009-05-11 23:12:24 +0300 $ */ var PaintWebInstance = new (function () { var _self = this; this.layer = {canvas: null, context: null}; this.tool = null; this.doc = document; this.win = window; function init () { profiler.start('init'); _self.layer.canvas = _self.doc.getElementById('imageView'); _self.layer.context = _self.layer.canvas.getContext('2d'); _self.tool = new tool_pencil(); _self.layer.canvas.addEventListener('mousedown', _self.tool.mousedown, false); _self.layer.canvas.addEventListener('mousemove', _self.tool.mousemove, false); _self.layer.canvas.addEventListener('mouseup', _self.tool.mouseup, false); profiler.stop('init'); }; function tool_pencil () { profiler.start('pencil.constructor'); var tool = this, context = _self.layer.context; this.started = false; this.mousedown = function (ev) { if (typeof ev.x_ == 'undefined') { if (typeof ev.layerX != 'undefined') { tool.x = ev.layerX; tool.y = ev.layerY; } else if (typeof ev.offsetX != 'undefined') { tool.x = ev.offsetX; tool.y = ev.offsetY; } } else { tool.x = ev.x_; tool.y = ev.y_; } tool.started = true; }; this.mousemove = function (ev) { if (tool.started) { context.beginPath(); context.moveTo(tool.x, tool.y); if (typeof ev.x_ == 'undefined') { if (typeof ev.layerX != 'undefined') { context.lineTo(ev.layerX, ev.layerY); tool.x = ev.layerX; tool.y = ev.layerY; } else if (typeof ev.offsetX != 'undefined') { context.lineTo(ev.offsetX, ev.offsetY); tool.x = ev.offsetX; tool.y = ev.offsetY; } } else { context.lineTo(ev.x_, ev.y_); tool.x = ev.x_; tool.y = ev.y_; } context.stroke(); context.closePath(); } }; this.mouseup = function (ev) { if (tool.started) { tool.mousemove(ev); tool.started = false; } }; profiler.stop('pencil.constructor'); }; init(); })(); // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * © 2009 ROBO Design * http://www.robodesign.ro * * $Date: 2009-05-11 23:34:52 +0300 $ */ var PaintWebInstance = new (function () { var _self = this; this.layer = {canvas: null, context: null}; this.tool = null; this.doc = document; this.win = window; function init () { profiler.start('init'); _self.layer.canvas = _self.doc.getElementById('imageView'); _self.layer.context = _self.layer.canvas.getContext('2d'); _self.tool = new tool_pencil(); _self.layer.canvas.addEventListener('mousedown', _self.tool.mousedown, false); _self.layer.canvas.addEventListener('mousemove', _self.tool.mousemove, false); _self.layer.canvas.addEventListener('mouseup', _self.tool.mouseup, false); profiler.stop('init'); }; function tool_pencil () { profiler.start('pencil.constructor'); var tool = this, context = _self.layer.context; this.started = false; this.mousedown = function (ev) { profiler.start('pencil.mousedown'); if (typeof ev.x_ == 'undefined') { if (typeof ev.layerX != 'undefined') { tool.x = ev.layerX; tool.y = ev.layerY; } else if (typeof ev.offsetX != 'undefined') { tool.x = ev.offsetX; tool.y = ev.offsetY; } } else { tool.x = ev.x_; tool.y = ev.y_; } tool.started = true; profiler.stop('pencil.mousedown'); }; this.mousemove = function (ev) { profiler.start('pencil.mousemove'); if (tool.started) { context.beginPath(); context.moveTo(tool.x, tool.y); if (typeof ev.x_ == 'undefined') { if (typeof ev.layerX != 'undefined') { context.lineTo(ev.layerX, ev.layerY); tool.x = ev.layerX; tool.y = ev.layerY; } else if (typeof ev.offsetX != 'undefined') { context.lineTo(ev.offsetX, ev.offsetY); tool.x = ev.offsetX; tool.y = ev.offsetY; } } else { context.lineTo(ev.x_, ev.y_); tool.x = ev.x_; tool.y = ev.y_; } context.stroke(); context.closePath(); } profiler.stop('pencil.mousemove'); }; this.mouseup = function (ev) { profiler.start('pencil.mouseup'); if (tool.started) { tool.mousemove(ev); tool.started = false; } profiler.stop('pencil.mouseup'); }; profiler.stop('pencil.constructor'); }; init(); })(); // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * © 2009 ROBO Design * http://www.robodesign.ro * * $Date: 2009-05-12 15:35:12 +0300 $ */ var PaintWebInstance = new (function () { var _self = this; this.layer = {canvas: null, context: null}; this.tool = null; this.doc = document; this.win = window; function init () { profiler.start('init'); _self.layer.canvas = _self.doc.getElementById('imageView'); _self.layer.context = _self.layer.canvas.getContext('2d'); _self.tool = new tool_pencil(); _self.layer.canvas.addEventListener('mousedown', _self.tool.mousedown, false); _self.layer.canvas.addEventListener('mousemove', _self.tool.mousemove, false); _self.layer.canvas.addEventListener('mouseup', _self.tool.mouseup, false); profiler.stop('init'); }; function tool_pencil () { profiler.start('pencil.constructor'); var tool = this, context = _self.layer.context; this.started = false; this.mousedown = function (ev) { if (!('x_' in ev)) { if ('layerX' in ev) { tool.x = ev.layerX; tool.y = ev.layerY; } else if ('offsetX' in ev) { tool.x = ev.offsetX; tool.y = ev.offsetY; } } else { tool.x = ev.x_; tool.y = ev.y_; } tool.started = true; }; this.mousemove = function (ev) { if (tool.started) { context.beginPath(); context.moveTo(tool.x, tool.y); if (!('x_' in ev)) { if ('layerX' in ev) { context.lineTo(ev.layerX, ev.layerY); tool.x = ev.layerX; tool.y = ev.layerY; } else if ('offsetX' in ev) { context.lineTo(ev.offsetX, ev.offsetY); tool.x = ev.offsetX; tool.y = ev.offsetY; } } else { context.lineTo(ev.x_, ev.y_); tool.x = ev.x_; tool.y = ev.y_; } context.stroke(); context.closePath(); } }; this.mouseup = function (ev) { if (tool.started) { tool.mousemove(ev); tool.started = false; } }; profiler.stop('pencil.constructor'); }; init(); })(); // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * © 2009 ROBO Design * http://www.robodesign.ro * * $Date: 2009-05-17 22:58:52 +0300 $ */ /** * @author <a lang="ro" href="http://www.robodesign.ro/mihai">Mihai Şucan</a> * @fileOverview Minimal code used for aiding debugging PaintWeb. */ // Opera compatibility if (!window.console) { /** * @namespace Holds a simple method used for debugging. Opera doesn't have the * window.console API like Firefox+Firebug has. */ window.console = {}; } if (!window.console.log) { /** * Display a message in the debugger. If available, opera.postError is used, * otherwise no message is displayed. * * @param {mixed} mixed Any number of arguments, each one is displayed in the * debugger. */ window.console.log = function () { var msg = ''; for (var i = 0, n = arguments.length; i < n; i++) { msg += arguments[i] + ' '; } if (window.opera && window.opera.postError) { opera.postError(msg); } else { alert(msg); } }; } if (!window.console.warn) { /** * Display a message in the debugger. If available, opera.postError is used, * otherwise no warning is displayed. * * @param {mixed} mixed Any number of arguments, each one is displayed in the * debugger. */ window.console.warn = function () { console.log.apply(null, arguments); }; } /** * JavaScript code performance profiler. * <p>Nested timers are accounted for - see the example below. * * @example * <code>// To profile your code just do: * var profiler = new $.profiler(); * * profiler.start('long test'); * // ... more code ... * profiler.start('function 1'); * // ... more code ... * profiler.stop('function 1'); * // ... more code ... * profiler.start('function 2'); * // ... more code ... * profiler.stop('function 2'); * // ... more code ... * profiler.stop('long test'); * * // To see the results do: * profiler.reportText(); * // or .. * profiler.reportData();</code> * * @class JavaScript code performance profiler. */ var libProfiler = function () { /** * @ignore * @class Function timer. This is the constructor used for instancing a single * timer object created by the profiler. * * @private * @param {String} name_ The timer name. * @param {Boolean} [independent_=false] Tells if the timer is independent. * Means this timer will not affect the timers execution stack. */ function fnTimer (name_, independent_) { this.avgOwnTimePerCall = 0; this.avgRunTimePerCall = 0; this.calls = 0; this.maxOwnTimePerCall = 0; this.maxRunTimePerCall = 0; this.minOwnTimePerCall = 0; this.minRunTimePerCall = 0; this.name = name_; this.ownTimeTotal = 0; this.runTimeTotal = 0; this.state = fnTimer.STATE_NONE; this.independent = independent_; var startTime_ = 0, subTimerStart_ = 0, subTime_ = 0, stack_ = 0; /* * Start timing function execution. */ this.start = function () { if (this.state == fnTimer.STATE_START || this.state == fnTimer.STATE_SUB) { stack_++; return; } startTime_ = (new Date ()).getTime(); this.state = fnTimer.STATE_START; }; /* * Stop timing function execution. */ this.stop = function () { if (this.state == fnTimer.STATE_SUB) { this.subTimerEnd(); } if (this.state != fnTimer.STATE_START) { return; } this.calls++; if (stack_) { stack_--; return; } var runTime = (new Date ()).getTime() - startTime_; var ownTime = runTime - subTime_; subTime_ = 0; this.runTimeTotal += runTime; this.ownTimeTotal += ownTime; this.avgRunTimePerCall = this.runTimeTotal / this.calls; this.avgOwnTimePerCall = this.ownTimeTotal / this.calls; if (runTime < this.minRunTimePerCall) { this.minRunTimePerCall = runTime; } if (runTime > this.maxRunTimePerCall) { this.maxRunTimePerCall = runTime; } if (ownTime < this.minOwnTimePerCall) { this.minOwnTimePerCall = ownTime; } if (ownTime > this.maxOwnTimePerCall) { this.maxOwnTimePerCall = ownTime; } this.state = fnTimer.STATE_STOP; }; /* * Start timing sub-function execution. The sub-function execution timer is * used for calculating the ownTime (runTime - sub-function execution time). */ this.subTimerStart = function () { if (this.independent || this.state != fnTimer.STATE_START) { return; } subTimerStart_ = (new Date()).getTime(); this.state = fnTimer.STATE_SUB; }; /* * Stop timing sub-function execution. */ this.subTimerEnd = function () { if (this.independent || this.state != fnTimer.STATE_SUB) { return; } subTime_ += (new Date()).getTime() - subTimerStart_; this.state = fnTimer.STATE_START; }; }; fnTimer.STATE_NONE = 0; fnTimer.STATE_START = 1; fnTimer.STATE_SUB = 2; fnTimer.STATE_STOP = 3; /** * Holds the timer objects. */ this.timers = {}; var activeTimer_ = null, timersStack_ = []; /** * Start/create a function timer. * * @param {String} name The timer name. * @param {Boolean} [independent=false] Tells if the timer should be * independent or not. This means that this new function timer is not be * considered affecting the execution time of existing function timers in the * call stack. */ this.start = function (name, independent) { var timer = this.timers[name]; if (!timer) { timer = this.timers[name] = new fnTimer(name, independent); } if (!timer.independent && activeTimer_ != name) { var activeTimer = activeTimer_ ? this.timers[activeTimer_] : null; if (activeTimer && activeTimer.state == fnTimer.STATE_START) { timersStack_.push(activeTimer_); activeTimer.subTimerStart(); } activeTimer_ = name; } timer.start(); }; /** * Stop a function timer. */ this.stop = function (name) { var timer = this.timers[name]; if (!timer) { return; } timer.stop(); if (timer.independent || name != activeTimer_ || name == activeTimer_ && timer.state == fnTimer.STATE_START) { return; } if (timersStack_.length > 0) { activeTimer_ = timersStack_.pop(); var activeTimer = this.timers[activeTimer_]; activeTimer.subTimerEnd(); } else { activeTimer_ = null; } }; /** * Generate timers report data. * * @returns {Object} Holds all the information gathered by the timers. */ this.reportData = function () { var name, timer, timerDetails, data = { avgCallsPerTimer: 0, avgOwnTimePerCall: 0, avgOwnTimePerTimer: 0, avgRunTimePerCall: 0, avgRunTimePerTimer: 0, callsTotal: 0, maxCallsPerTimer: 0, maxCallsPerTimerName: '', maxOwnTimePerCall: 0, maxOwnTimePerCallName: '', maxRunTimePerCall: 0, maxRunTimePerCallName: '', minCallsPerTimer: 0, minCallsPerTimerName: '', minOwnTimePerCall: 0, minOwnTimePerCallName: '', minRunTimePerCall: 0, minRunTimePerCallName: '', ownTimeTotal: 0, runTimeTotal: 0, timers: 0, timerDetails: [] }; for (name in this.timers) { timer = this.timers[name]; if (timer.state != fnTimer.STATE_STOP) { continue; } timerDetails = { name: name, avgOwnTimePerCall: timer.avgOwnTimePerCall, avgRunTimePerCall: timer.avgRunTimePerCall, calls: timer.calls, maxOwnTimePerCall: timer.maxOwnTimePerCall, maxRunTimePerCall: timer.maxRunTimePerCall, minOwnTimePerCall: timer.minOwnTimePerCall, minRunTimePerCall: timer.minRunTimePerCall, runTimeTotal: timer.runTimeTotal, ownTimeTotal: timer.ownTimeTotal }; data.timerDetails.push(timerDetails); if (timer.calls > data.maxCallsPerTimer || !data.timers) { data.maxCallsPerTimer = timer.calls; data.maxCallsPerTimerName = name; } if (timer.maxOwnTimePerCall > data.maxOwnTimePerCall || !data.timers) { data.maxOwnTimePerCall = timer.maxOwnTimePerCall; data.maxOwnTimePerCallName = name; } if (timer.maxRunTimePerCall > data.maxRunTimePerCall || !data.timers) { data.maxRunTimePerCall = timer.maxRunTimePerCall; data.maxRunTimePerCallName = name; } if (timer.calls < data.minCallsPerTimer || !data.timers) { data.minCallsPerTimer = timer.calls; data.minCallsPerTimerName = name; } if (timer.minOwnTimePerCall < data.minOwnTimePerCall || !data.timers) { data.minOwnTimePerCall = timer.minOwnTimePerCall; data.minOwnTimePerCallName = name; } if (timer.minRunTimePerCall < data.minRunTimePerCall || !data.timers) { data.minRunTimePerCall = timer.minRunTimePerCall; data.minRunTimePerCallName = name; } data.runTimeTotal += timer.runTimeTotal; data.ownTimeTotal += timer.ownTimeTotal; data.callsTotal += timer.calls; data.timers++; } if (data.timers == 0) { return data; } data.avgCallsPerTimer = data.callsTotal / data.timers; data.avgOwnTimePerCall = data.ownTimeTotal / data.callsTotal; data.avgOwnTimePerTimer = data.ownTimeTotal / data.timers; data.avgRunTimePerCall = data.runTimeTotal / data.callsTotal; data.avgRunTimePerTimer = data.runTimeTotal / data.timers; return data; }; /** * Generate a report in text format. * * @returns {String} All the information gathered by the timers, as text. */ this.reportText = function () { var data = this.reportData(), timer, result = ''; if (!data.timers) { return ''; } for (var i = 0; i < data.timers; i++) { timer = data.timerDetails[i]; result += timer.name + ":\n" + ' Avg ownTime / call: ' + timer.avgOwnTimePerCall + " ms\n" + ' Avg runTime / call: ' + timer.avgRunTimePerCall + " ms\n" + ' Calls: ' + timer.calls + "\n"+ ' Max ownTime / call: ' + timer.maxOwnTimePerCall + " ms\n" + ' Max runTime / call: ' + timer.maxRunTimePerCall + " ms\n" + ' Min ownTime / call: ' + timer.minOwnTimePerCall + " ms\n" + ' Min runTime / call: ' + timer.minRunTimePerCall + " ms\n" + ' runTime: ' + timer.runTimeTotal + " ms\n" + ' ownTime: ' + timer.ownTimeTotal + " ms\n\n"; } result += "Overview info:\n" + ' Avg calls / timer: ' + data.avgCallsPerTimer + "\n" + ' Avg ownTime / call: ' + data.avgOwnTimePerCall + " ms\n" + ' Avg ownTime / timer: ' + data.avgOwnTimePerTimer + " ms\n" + ' Avg runTime / call: ' + data.avgRunTimePerCall + " ms\n" + ' Avg runTime / timer: ' + data.avgRunTimePerTimer + " ms\n" + ' Calls total: ' + data.callsTotal + "\n" + ' Max calls / timer: ' + data.maxCallsPerTimer + ' (' + data.maxCallsPerTimerName + ")\n" + ' Max ownTime / call: ' + data.maxOwnTimePerCall + ' ms (' + data.maxOwnTimePerCallName + ")\n" + ' Max runTime / call: ' + data.maxRunTimePerCall + ' ms (' + data.maxRunTimePerCallName + ")\n" + ' Min calls / timer: ' + data.minCallsPerTimer + ' (' + data.minCallsPerTimerName + ")\n" + ' Min ownTime / call: ' + data.minOwnTimePerCall + ' ms (' + data.minOwnTimePerCallName + ")\n" + ' Min runTime / call: ' + data.minRunTimePerCall + ' ms (' + data.minRunTimePerCallName + ")\n" + ' Accumulated ownTime: ' + data.ownTimeTotal + " ms\n" + ' Accumulated runTime: ' + data.runTimeTotal + " ms\n" + ' Timers: ' + data.timers; return result; }; /** * Reset/clear all the timers. */ this.reset = function () { this.timers = {}; activeTimer_ = null; timersStack_ = []; }; }; (function () { window.profiler = new libProfiler(); var container = document.getElementById('container'), profilerOutput = document.createElement('pre'), runTest = document.createElement('button'), resetProfiler = document.createElement('button'), updateReport = document.createElement('button'); runTest.appendChild(document.createTextNode('Run test')); resetProfiler.appendChild(document.createTextNode('Reset profiler')); updateReport.appendChild(document.createTextNode('Update report')); var target = container.parentNode, sibling = container.nextSibling; target.insertBefore(runTest, sibling); target.insertBefore(resetProfiler, sibling); target.insertBefore(updateReport, sibling); target.insertBefore(profilerOutput, sibling); var context = null, canvas = null; runTest.addEventListener('click', function () { profiler.reset(); profiler.start('runTest'); canvas = PaintWebInstance.layer.canvas; context = PaintWebInstance.layer.context; var x = 0, y = 0, width = canvas.width, height = canvas.height; context.clearRect(0, 0, width, height); dispatch('mousedown', x, y); for (var i = 0; i < 10000; i++) { x += 5; if (x >= width) { x = 0; y += 5; dispatch('mouseup', x, y); dispatch('mousedown', x, y); if (y >= height) { break; } } dispatch('mousemove', x, y); } dispatch('mouseup', x, y); profilerOutput.innerHTML = ''; profiler.stop('runTest'); profilerOutput.appendChild(document.createTextNode(profiler.reportText())); }, false); resetProfiler.addEventListener('click', function () { profiler.reset(); profilerOutput.innerHTML = ''; }, false); updateReport.addEventListener('click', function () { profilerOutput.innerHTML = ''; profilerOutput.appendChild(document.createTextNode(profiler.reportText())); }, false); function dispatch (type, x, y) { var ev = document.createEvent('MouseEvents'); ev.initMouseEvent(type, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); ev.x_ = x; ev.y_ = y; canvas.dispatchEvent(ev); }; })();
JavaScript
/* * © 2009 ROBO Design * http://www.robodesign.ro * * $Date: 2009-05-11 20:20:59 +0300 $ */ var PaintWebInstance = new (function () { var _self = this; this.layer = {canvas: null, context: null}; this.tool = null; this.doc = document; this.win = window; function init () { profiler.start('init'); _self.layer.canvas = _self.doc.getElementById('imageView'); _self.layer.context = _self.layer.canvas.getContext('2d'); _self.tool = new tool_pencil(); _self.layer.canvas.addEventListener('mousedown', _self.ev_canvas, false); _self.layer.canvas.addEventListener('mousemove', _self.ev_canvas, false); _self.layer.canvas.addEventListener('mouseup', _self.ev_canvas, false); profiler.stop('init'); }; function tool_pencil () { profiler.start('pencil.constructor'); var tool = this, context = _self.layer.context, width = _self.layer.canvas.width, height = _self.layer.canvas.height; this.started = false; this.mousedown = function (ev) { profiler.start('pencil.mousedown'); tool.x = ev.x_; tool.y = ev.y_; tool.started = true; profiler.stop('pencil.mousedown'); }; this.mousemove = function (ev) { profiler.start('pencil.mousemove'); if (tool.started) { context.beginPath(); context.moveTo(tool.x, tool.y); context.lineTo(ev.x_, ev.y_); context.stroke(); context.closePath(); tool.x = ev.x_; tool.y = ev.y_; } profiler.stop('pencil.mousemove'); }; this.mouseup = function (ev) { profiler.start('pencil.mouseup'); if (tool.started) { tool.mousemove(ev); tool.started = false; } profiler.stop('pencil.mouseup'); }; profiler.stop('pencil.constructor'); }; // The general-purpose event handler. This function just determines the mouse // position relative to the canvas element. this.ev_canvas = function (ev) { profiler.start('ev_canvas'); if (typeof ev.x_ == 'undefined') { if (typeof ev.layerX != 'undefined') { ev.x_ = ev.layerX; ev.y_ = ev.layerY; } else if (typeof ev.offsetX != 'undefined') { ev.x_ = ev.offsetX; ev.y_ = ev.offsetY; } } var func = _self.tool[ev.type]; if (func) { func(ev); } profiler.stop('ev_canvas'); }; init(); })(); // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * © 2009 ROBO Design * http://www.robodesign.ro * * $Date: 2009-05-13 13:46:51 +0300 $ */ function tool_pencil (app) { profiler.start('pencil.constructor'); var _self = this, context = app.layer.context, mouse = app.mouse, width = app.image.width, height = app.image.height; this.mousedown = function (ev) { profiler.start('pencil.mousedown'); _self.x = ev.x_; _self.y = ev.y_; profiler.stop('pencil.mousedown'); return true; }; this.mousemove = function (ev) { profiler.start('pencil.mousemove'); if (mouse.buttonDown) { context.beginPath(); context.moveTo(_self.x, _self.y); context.lineTo(ev.x_, ev.y_); context.stroke(); context.closePath(); _self.x = ev.x_; _self.y = ev.y_; profiler.stop('pencil.mousemove'); return true; } profiler.stop('pencil.mousemove'); return false; }; this.mouseup = function (ev) { profiler.start('pencil.mouseup'); _self.mousemove(ev); profiler.stop('pencil.mouseup'); return true; }; profiler.stop('pencil.constructor'); }; var PaintWebInstance = new (function () { var _self = this; this.layer = {canvas: null, context: null}; this.tool = null; this.doc = document; this.win = window; this.mouse = {x: 0, y: 0, buttonDown: false}; this.image = {width: 0, height: 0, zoom: 1}; var MathRound = Math.round, mouse = this.mouse, image = this.image, tool = null; function init () { profiler.start('init'); _self.layer.canvas = _self.doc.getElementById('imageView'); _self.layer.context = _self.layer.canvas.getContext('2d'); _self.image.width = _self.layer.canvas.width; _self.image.height = _self.layer.canvas.height; _self.tool = new tool_pencil(_self); tool = _self.tool; _self.layer.canvas.addEventListener('mousedown', _self.ev_canvas, false); _self.layer.canvas.addEventListener('mousemove', _self.ev_canvas, false); _self.layer.canvas.addEventListener('mouseup', _self.ev_canvas, false); profiler.stop('init'); }; // The general-purpose event handler. This function just determines the mouse // position relative to the canvas element. this.ev_canvas = function (ev) { profiler.start('ev_canvas'); if (!tool) { profiler.stop('ev_canvas'); return false; } else if (ev.type == 'mousedown') { if (mouse.buttonDown) { profiler.stop('ev_canvas'); return false; } mouse.buttonDown = true; } else if (ev.type == 'mouseup') { if (!mouse.buttonDown) { profiler.stop('ev_canvas'); return false; } mouse.buttonDown = false; } if (!('x_' in ev)) { if ('layerX' in ev) { if (image.zoom == 1) { ev.x_ = mouse.x = ev.layerX; ev.y_ = mouse.y = ev.layerY; } else { ev.x_ = mouse.x = MathRound(ev.layerX / image.zoom); ev.y_ = mouse.y = MathRound(ev.layerY / image.zoom); } } else if ('offsetX' in ev) { if (image.zoom == 1) { ev.x_ = mouse.x = ev.offsetX; ev.y_ = mouse.y = ev.offsetY; } else { ev.x_ = mouse.x = MathRound(ev.offsetX / image.zoom); ev.y_ = mouse.y = MathRound(ev.offsetY / image.zoom); } } } if (ev.type in tool && tool[ev.type](ev)) { ev.preventDefault(); profiler.stop('ev_canvas'); return true; } else { profiler.stop('ev_canvas'); return false; } }; init(); })(); // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * © 2009 ROBO Design * http://www.robodesign.ro * * $Date: 2009-05-13 13:47:25 +0300 $ */ function tool_pencil (app) { profiler.start('pencil.constructor'); var _self = this, context = app.layer.context, mouse = app.mouse, width = app.image.width, height = app.image.height; this.mousedown = function (ev) { profiler.start('pencil.mousedown'); _self.x = ev.x_; _self.y = ev.y_; profiler.stop('pencil.mousedown'); }; this.mousemove = function (ev) { profiler.start('pencil.mousemove'); if (mouse.buttonDown) { context.beginPath(); context.moveTo(_self.x, _self.y); context.lineTo(ev.x_, ev.y_); context.stroke(); context.closePath(); _self.x = ev.x_; _self.y = ev.y_; } profiler.stop('pencil.mousemove'); }; this.mouseup = function (ev) { profiler.start('pencil.mouseup'); if (mouse.buttonDown) { _self.mousemove(ev); } profiler.stop('pencil.mouseup'); }; profiler.stop('pencil.constructor'); }; var PaintWebInstance = new (function () { var _self = this; this.layer = {canvas: null, context: null}; this.tool = null; this.doc = document; this.win = window; this.mouse = {x: 0, y: 0, buttonDown: false}; this.image = {width: 0, height: 0, zoom: 1}; function init () { profiler.start('init'); _self.layer.canvas = _self.doc.getElementById('imageView'); _self.layer.context = _self.layer.canvas.getContext('2d'); _self.image.width = _self.layer.canvas.width; _self.image.height = _self.layer.canvas.height; _self.tool = new tool_pencil(_self); _self.layer.canvas.addEventListener('mousedown', _self.ev_canvas, false); _self.layer.canvas.addEventListener('mousemove', _self.ev_canvas, false); _self.layer.canvas.addEventListener('mouseup', _self.ev_canvas, false); profiler.stop('init'); }; // The general-purpose event handler. This function just determines the mouse // position relative to the canvas element. this.ev_canvas = function (ev) { profiler.start('ev_canvas'); if (!_self.tool) { profiler.stop('ev_canvas'); return false; } if (_self.mouse.buttonDown && ev.type == 'mousedown') { profiler.stop('ev_canvas'); return false; } if (typeof ev.x_ == 'undefined') { if (typeof ev.layerX != 'undefined') { ev.x_ = ev.layerX; ev.y_ = ev.layerY; } else if (typeof ev.offsetX != 'undefined') { ev.x_ = ev.offsetX; ev.y_ = ev.offsetY; } if (_self.image.zoom != 1 && (ev.x_ || ev.y_)) { ev.x_ = Math.round(ev.x_ / _self.image.zoom); ev.y_ = Math.round(ev.y_ / _self.image.zoom); } switch (ev.type) { case 'mousedown': case 'mousemove': case 'mouseup': _self.mouse.x = ev.x_; _self.mouse.y = ev.y_; } } if (ev.type == 'mousedown') { _self.mouse.buttonDown = true; } var result = false, event_action = _self.tool[ev.type]; if (typeof event_action == 'function') { result = event_action(ev); } if (ev.type == 'mouseup') { _self.mouse.buttonDown = false; } // Do not call preventDefault() when the result is false. if (result && ev.preventDefault) { ev.preventDefault(); } profiler.stop('ev_canvas'); return result; }; init(); })(); // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * © 2009 ROBO Design * http://www.robodesign.ro * * $Date: 2009-05-12 20:18:25 +0300 $ */ var PaintWebInstance = new (function () { var _self = this; this.layer = {canvas: null, context: null}; this.tool = null; this.doc = document; this.win = window; function init () { profiler.start('init'); _self.layer.canvas = _self.doc.getElementById('imageView'); _self.layer.context = _self.layer.canvas.getContext('2d'); _self.tool = new tool_pencil(); _self.layer.canvas.addEventListener('mousedown', _self.ev_canvas, false); _self.layer.canvas.addEventListener('mousemove', _self.ev_canvas, false); _self.layer.canvas.addEventListener('mouseup', _self.ev_canvas, false); profiler.stop('init'); }; function tool_pencil () { profiler.start('pencil.constructor'); var tool = this, context = _self.layer.context, width = _self.layer.canvas.width, height = _self.layer.canvas.height; this.started = false; this.mousedown = function (ev) { profiler.start('pencil.mousedown'); context.beginPath(); context.moveTo(ev.x_, ev.y_); tool.started = true; profiler.stop('pencil.mousedown'); }; this.mousemove = function (ev) { profiler.start('pencil.mousemove'); if (tool.started) { context.clearRect(0, 0, width, height); context.lineTo(ev.x_, ev.y_); context.stroke(); } profiler.stop('pencil.mousemove'); }; this.mouseup = function (ev) { profiler.start('pencil.mouseup'); if (tool.started) { tool.mousemove(ev); context.closePath(); tool.started = false; } profiler.stop('pencil.mouseup'); }; profiler.stop('pencil.constructor'); }; // The general-purpose event handler. This function just determines the mouse // position relative to the canvas element. this.ev_canvas = function (ev) { profiler.start('ev_canvas'); if (typeof ev.x_ == 'undefined') { if (typeof ev.layerX != 'undefined') { ev.x_ = ev.layerX; ev.y_ = ev.layerY; } else if (typeof ev.offsetX != 'undefined') { ev.x_ = ev.offsetX; ev.y_ = ev.offsetY; } } var func = _self.tool[ev.type]; if (func) { func(ev); } profiler.stop('ev_canvas'); }; init(); })(); // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * © 2009 ROBO Design * http://www.robodesign.ro * * $Date: 2009-05-13 14:32:21 +0300 $ */ function tool_pencil (app) { profiler.start('pencil.constructor'); var _self = this, context = app.layer.context, mouse = app.mouse, width = app.image.width, height = app.image.height; this.mousedown = function (ev) { _self.x = ev.x_; _self.y = ev.y_; return true; }; this.mousemove = function (points) { if (!mouse.buttonDown) { return false; } var i = 0, x = 0, y = 0, n = points.length; context.beginPath(); context.moveTo(_self.x, _self.y); while (i < n) { x = points[i++]; y = points[i++]; context.lineTo(x, y); } _self.x = x; _self.y = y; context.stroke(); context.closePath(); return true; }; this.mouseup = function (ev) { return _self.mousemove(ev); }; profiler.stop('pencil.constructor'); }; var PaintWebInstance = new (function () { var _self = this; this.layer = {canvas: null, context: null}; this.tool = null; this.doc = document; this.win = window; this.mouse = {x: 0, y: 0, buttonDown: false}; this.image = {width: 0, height: 0, zoom: 1}; var MathRound = Math.round, mouse = this.mouse, image = this.image, tool = null, mousemove_timer = null, mousemove_points = [], mousemove_delay = 100, setInterval = window.setInterval, clearInterval = window.clearInterval; function init () { profiler.start('init'); var canvas = _self.doc.getElementById('imageView'); _self.layer.canvas = canvas; _self.layer.context = canvas.getContext('2d'); _self.image.width = canvas.width; _self.image.height = canvas.height; _self.tool = new tool_pencil(_self); tool = _self.tool; canvas.addEventListener('mouseover', _self.ev_canvas, false); canvas.addEventListener('mouseout', _self.ev_canvas, false); canvas.addEventListener('mousedown', _self.ev_canvas, false); canvas.addEventListener('mousemove', _self.ev_canvas, false); canvas.addEventListener('mouseup', _self.ev_canvas, false); profiler.stop('init'); }; // The general-purpose event handler. This function just determines the mouse // position relative to the canvas element. this.ev_canvas = function (ev) { if (!tool) { return false; } switch (ev.type) { case 'mousedown': if (mouse.buttonDown) { return false; } _self.mousemove_flush(); mouse.buttonDown = true; break; case 'mouseup': if (!mouse.buttonDown) { return false; } _self.mousemove_flush(); mouse.buttonDown = false; break; case 'mouseover': if ('mousemove' in tool) { mousemove_points = []; mousemove_timer = setInterval(_self.mousemove_flush, mousemove_delay); } return true; case 'mouseout': if (mousemove_timer) { clearInterval(mousemove_timer); mousemove_timer = null; _self.mousemove_flush(); } return true; } if (!('x_' in ev)) { if ('layerX' in ev) { if (image.zoom == 1) { ev.x_ = mouse.x = ev.layerX; ev.y_ = mouse.y = ev.layerY; } else { ev.x_ = mouse.x = MathRound(ev.layerX / image.zoom); ev.y_ = mouse.y = MathRound(ev.layerY / image.zoom); } } else if ('offsetX' in ev) { if (image.zoom == 1) { ev.x_ = mouse.x = ev.offsetX; ev.y_ = mouse.y = ev.offsetY; } else { ev.x_ = mouse.x = MathRound(ev.offsetX / image.zoom); ev.y_ = mouse.y = MathRound(ev.offsetY / image.zoom); } } } if (ev.type == 'mousemove' && 'mousemove' in tool) { mousemove_points.push(ev.x_, ev.y_); ev.preventDefault(); return true; } else if (ev.type in tool && tool[ev.type](ev)) { ev.preventDefault(); return true; } else { return false; } }; this.mousemove_flush = function () { if ('mousemove' in tool && '0' in mousemove_points) { tool.mousemove(mousemove_points); } mousemove_points = []; }; init(); })(); // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * © 2009 ROBO Design * http://www.robodesign.ro * * $Date: 2009-05-25 21:48:09 +0300 $ */ function tool_pencil (app) { profiler.start('pencil.constructor'); var _self = this, context = app.layer.context, mouse = app.mouse, width = app.image.width, height = app.image.height, timer = null, points = [], delay = 100, setInterval = window.setInterval, clearInterval = window.clearInterval; this.mousedown = function (ev) { _self.x = ev.x_; _self.y = ev.y_; points = []; timer = setInterval(draw, delay); return true; }; this.mousemove = function (ev) { if (mouse.buttonDown) { points.push(ev.x_, ev.y_); } }; this.mouseup = function () { clearInterval(timer); draw(); return true; }; function draw () { var i = 0, x = 0, y = 0, n = points.length; if (!n) { return; } context.beginPath(); context.moveTo(_self.x, _self.y); while (i < n) { x = points[i++]; y = points[i++]; context.lineTo(x, y); } _self.x = x; _self.y = y; context.stroke(); context.closePath(); points = []; }; profiler.stop('pencil.constructor'); }; var PaintWebInstance = new (function () { var _self = this; this.layer = {canvas: null, context: null}; this.tool = null; this.doc = document; this.win = window; this.mouse = {x: 0, y: 0, buttonDown: false}; this.image = {width: 0, height: 0, zoom: 1}; var MathRound = Math.round, mouse = this.mouse, image = this.image, dpiOptimal = 96, tool = null; var dpiLocal = dpiOptimal; function init () { profiler.start('init'); var canvas = _self.doc.getElementById('imageView'); _self.layer.canvas = canvas; _self.layer.context = canvas.getContext('2d'); _self.image.width = canvas.width; _self.image.height = canvas.height; var resInfo = _self.doc.getElementById('resInfo'); var cs = _self.win.getComputedStyle(resInfo, null); var width = parseInt(cs.width), height = parseInt(cs.height), scale = 1; if (_self.win.opera) { // Opera zoom level detection. // The scaling factor is sufficiently accurate for zoom levels between // 100% and 200% (in steps of 10%). scale = _self.win.innerHeight / height; scale = MathRound(scale * 10) / 10; /*console.log('scale ' + scale + ' innerHeight ' + _self.win.innerHeight + ' height ' + height);*/ } else if (width && !isNaN(width) && width != dpiOptimal) { // Page DPI detection. This only works in Gecko 1.9.1. dpiLocal = width; // The scaling factor is the same as in Gecko. scale = Math.floor(dpiLocal / dpiOptimal); //console.log('dpiLocal ' + dpiLocal + ' scale ' + scale); } else if (_self.win.navigator.userAgent.indexOf('olpc') != -1) { // Support for the default Gecko included on the OLPC XO-1 system. // // See: // http://mxr.mozilla.org/mozilla-central/source/gfx/src/thebes/nsThebesDeviceContext.cpp#725 // dotsArePixels = false on the XO due to a hard-coded patch. // Thanks go to roc from Mozilla for his feedback on making this work. dpiLocal = 134; var appUnitsPerCSSPixel = 60; var devPixelsPerCSSPixel = dpiLocal / dpiOptimal; var appUnitsPerDevPixel = appUnitsPerCSSPixel / devPixelsPerCSSPixel; scale = appUnitsPerCSSPixel / Math.floor(appUnitsPerDevPixel); /*console.log('dpiLocal ' + dpiLocal + ' scale ' + scale + ' devPixelsPerCSSPixel ' + devPixelsPerCSSPixel + ' appUnitsPerDevPixel ' + appUnitsPerDevPixel);*/ } if (scale != 1) { image.zoom = 1 / scale; var sw = canvas.width / scale, sh = canvas.height / scale; /*console.log('w ' + canvas.width + ' h ' + canvas.height + ' sw ' + sw + ' sh ' + sh);*/ canvas.style.width = sw + 'px'; canvas.style.height = sh + 'px'; } _self.tool = new tool_pencil(_self); tool = _self.tool; canvas.addEventListener('mousedown', _self.ev_canvas, false); canvas.addEventListener('mousemove', _self.ev_canvas, false); canvas.addEventListener('mouseup', _self.ev_canvas, false); profiler.stop('init'); }; // The general-purpose event handler. This function just determines the mouse // position relative to the canvas element. this.ev_canvas = function (ev) { if (!tool) { return false; } switch (ev.type) { case 'mousedown': if (mouse.buttonDown) { return false; } mouse.buttonDown = true; break; case 'mouseup': if (!mouse.buttonDown) { return false; } mouse.buttonDown = false; } if (!('x_' in ev)) { if ('layerX' in ev) { if (image.zoom == 1) { ev.x_ = mouse.x = ev.layerX; ev.y_ = mouse.y = ev.layerY; } else { ev.x_ = mouse.x = MathRound(ev.layerX / image.zoom); ev.y_ = mouse.y = MathRound(ev.layerY / image.zoom); } } else if ('offsetX' in ev) { if (image.zoom == 1) { ev.x_ = mouse.x = ev.offsetX; ev.y_ = mouse.y = ev.offsetY; } else { ev.x_ = mouse.x = MathRound(ev.offsetX / image.zoom); ev.y_ = mouse.y = MathRound(ev.offsetY / image.zoom); } } } //console.log(ev.x_ + ' ' + ev.y_ + ' ' + ev.layerX + ' ' + ev.layerY); if (ev.type in tool && tool[ev.type](ev)) { ev.preventDefault(); return true; } else { return false; } }; init(); })(); // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * © 2009 ROBO Design * http://www.robodesign.ro * * $Date: 2009-05-12 16:14:01 +0300 $ */ var PaintWebInstance = new (function () { var _self = this; this.layer = {canvas: null, context: null}; this.tool = null; this.doc = document; this.win = window; function init () { profiler.start('init'); _self.layer.canvas = _self.doc.getElementById('imageView'); _self.layer.context = _self.layer.canvas.getContext('2d'); _self.tool = new tool_pencil(); _self.layer.canvas.addEventListener('mousedown', _self.tool.mousedown, false); _self.layer.canvas.addEventListener('mousemove', _self.tool.mousemove, false); _self.layer.canvas.addEventListener('mouseup', _self.tool.mouseup, false); profiler.stop('init'); }; // known, it fails... you can't actuall draw. you simply run the test. function tool_pencil () { profiler.start('pencil.constructor'); var tool = this, context = _self.layer.context; var started = false, x0, y0; this.mousedown = function (ev) { profiler.start('pencil.mousedown'); x0 = ev.x_; y0 = ev.y_; started = true; profiler.stop('pencil.mousedown'); }; this.mousemove = function (ev) { profiler.start('pencil.mousemove'); if (started) { context.beginPath(); context.moveTo(x0, y0); context.lineTo(ev.x_, ev.y_); context.stroke(); context.closePath(); x0 = ev.x_; y0 = ev.y_; } profiler.stop('pencil.mousemove'); }; this.mouseup = function (ev) { profiler.start('pencil.mouseup'); if (started) { tool.mousemove(ev); started = false; } profiler.stop('pencil.mouseup'); }; profiler.stop('pencil.constructor'); }; init(); })(); // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * © 2009 ROBO Design * http://www.robodesign.ro * * $Date: 2009-05-12 18:23:21 +0300 $ */ function tool_pencil (app) { profiler.start('pencil.constructor'); var _self = this, context = app.layer.context, mouse = app.mouse, width = app.image.width, height = app.image.height; this.mousedown = function (ev) { _self.x = ev.x_; _self.y = ev.y_; return true; }; this.mousemove = function (ev) { if (mouse.buttonDown) { context.beginPath(); context.moveTo(_self.x, _self.y); context.lineTo(ev.x_, ev.y_); context.stroke(); context.closePath(); _self.x = ev.x_; _self.y = ev.y_; return true; } return false; }; this.mouseup = function (ev) { return _self.mousemove(ev); }; profiler.stop('pencil.constructor'); }; var PaintWebInstance = new (function () { var _self = this; this.layer = {canvas: null, context: null}; this.tool = null; this.doc = document; this.win = window; this.mouse = {x: 0, y: 0, buttonDown: false}; this.image = {width: 0, height: 0, zoom: 1}; var MathRound = Math.round, mouse = this.mouse, image = this.image, tool = null; function init () { profiler.start('init'); _self.layer.canvas = _self.doc.getElementById('imageView'); _self.layer.context = _self.layer.canvas.getContext('2d'); _self.image.width = _self.layer.canvas.width; _self.image.height = _self.layer.canvas.height; _self.tool = new tool_pencil(_self); tool = _self.tool; _self.layer.canvas.addEventListener('mousedown', _self.ev_canvas, false); _self.layer.canvas.addEventListener('mousemove', _self.ev_canvas, false); _self.layer.canvas.addEventListener('mouseup', _self.ev_canvas, false); profiler.stop('init'); }; // The general-purpose event handler. This function just determines the mouse // position relative to the canvas element. this.ev_canvas = function (ev) { if (!tool) { return false; } switch (ev.type) { case 'mousedown': if (mouse.buttonDown) { return false; } mouse.buttonDown = true; break; case 'mouseup': if (!mouse.buttonDown) { return false; } mouse.buttonDown = false; } if (!('x_' in ev)) { if ('layerX' in ev) { if (image.zoom == 1) { ev.x_ = mouse.x = ev.layerX; ev.y_ = mouse.y = ev.layerY; } else { ev.x_ = mouse.x = MathRound(ev.layerX / image.zoom); ev.y_ = mouse.y = MathRound(ev.layerY / image.zoom); } } else if ('offsetX' in ev) { if (image.zoom == 1) { ev.x_ = mouse.x = ev.offsetX; ev.y_ = mouse.y = ev.offsetY; } else { ev.x_ = mouse.x = MathRound(ev.offsetX / image.zoom); ev.y_ = mouse.y = MathRound(ev.offsetY / image.zoom); } } } if (ev.type in tool && tool[ev.type](ev)) { ev.preventDefault(); return true; } else { return false; } }; init(); })(); // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * © 2009 ROBO Design * http://www.robodesign.ro * * $Date: 2009-05-13 19:22:36 +0300 $ */ function tool_pencil (app) { profiler.start('pencil.constructor'); var _self = this, context = app.layer.context, mouse = app.mouse, width = app.image.width, height = app.image.height, timer = null, points = [], delay = 100, setInterval = window.setInterval, clearInterval = window.clearInterval; this.mousedown = function (ev) { _self.x = ev.x_; _self.y = ev.y_; points = []; timer = setInterval(draw, delay); return true; }; this.mousemove = function (ev) { if (mouse.buttonDown) { points.push(ev.x_, ev.y_); } }; this.mouseup = function () { clearInterval(timer); draw(); return true; }; function draw () { var i = 0, x = 0, y = 0, n = points.length; if (!n) { return; } context.beginPath(); context.moveTo(_self.x, _self.y); while (i < n) { x = points[i++]; y = points[i++]; context.lineTo(x, y); } _self.x = x; _self.y = y; context.stroke(); context.closePath(); points = []; }; profiler.stop('pencil.constructor'); }; var PaintWebInstance = new (function () { var _self = this; this.layer = {canvas: null, context: null}; this.tool = null; this.doc = document; this.win = window; this.mouse = {x: 0, y: 0, buttonDown: false}; this.image = {width: 0, height: 0, zoom: 1}; var MathRound = Math.round, mouse = this.mouse, image = this.image, tool = null; function init () { profiler.start('init'); var canvas = _self.doc.getElementById('imageView'); _self.layer.canvas = canvas; _self.layer.context = canvas.getContext('2d'); _self.image.width = canvas.width; _self.image.height = canvas.height; _self.tool = new tool_pencil(_self); tool = _self.tool; canvas.addEventListener('mousedown', _self.ev_canvas, false); canvas.addEventListener('mousemove', _self.ev_canvas, false); canvas.addEventListener('mouseup', _self.ev_canvas, false); profiler.stop('init'); }; // The general-purpose event handler. This function just determines the mouse // position relative to the canvas element. this.ev_canvas = function (ev) { if (!tool) { return false; } switch (ev.type) { case 'mousedown': if (mouse.buttonDown) { return false; } mouse.buttonDown = true; break; case 'mouseup': if (!mouse.buttonDown) { return false; } mouse.buttonDown = false; } if (!('x_' in ev)) { if ('layerX' in ev) { if (image.zoom == 1) { ev.x_ = mouse.x = ev.layerX; ev.y_ = mouse.y = ev.layerY; } else { ev.x_ = mouse.x = MathRound(ev.layerX / image.zoom); ev.y_ = mouse.y = MathRound(ev.layerY / image.zoom); } } else if ('offsetX' in ev) { if (image.zoom == 1) { ev.x_ = mouse.x = ev.offsetX; ev.y_ = mouse.y = ev.offsetY; } else { ev.x_ = mouse.x = MathRound(ev.offsetX / image.zoom); ev.y_ = mouse.y = MathRound(ev.offsetY / image.zoom); } } } if (ev.type in tool && tool[ev.type](ev)) { ev.preventDefault(); return true; } else { return false; } }; init(); })(); // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
{ // $Date: 2009-11-08 20:39:21 +0200 $ /** * The list of available languages. This associated language IDs to their * language titles. * * @type Object */ "languages": { // Besides the language title, you may also tell the file name. The 'file' // property needs to be relative to the PaintWeb baseFolder. If no 'file' is // given, then the 'en.json' file name is used, and the file will be loaded // from the 'langFolder' you specify below. "en": { "title": "English" }, "moodle": { "title": "The current Moodle language", "file" : "../ext/moodle/lang.json.php" } }, /** * The default language. * * @type String * @default "en" */ "lang": "moodle", /** * The folder which holds the language files. * * @type String * @default "lang" */ "langFolder": "lang", /** * The graphical user interface you want to use. * * @type String * @default "default" */ "gui": "default", /** * The folder contains all the interfaces. * * @type String * @default "interfaces" */ "interfacesFolder": "interfaces", /** * The interface markup file. The file must be an XHTML valid document. * * @type String * @default "layout.xhtml" */ "guiMarkup": "layout.xhtml", /** * The interface style file. * * @type String * @default "style.css" */ "guiStyle": "style.css", /** * The interface script file. * * @type String * @default script.js */ "guiScript": "script.js", /** * The image viewport width. Make sure the value is a CSS length, like "50%", * "450px" or "30em". * * <p>Note: the GUI implementation might ignore this value. * * @type String * @default "100%" */ "viewportWidth": "100%", /** * The image viewport height. Make sure the value is a CSS length, like "50%", * "450px" or "30em". * * <p>Note: the GUI implementation might ignore this value. * * @type String * @default "400px" */ "viewportHeight": "400px", /** * Image save quality for the JPEG format. * * @type Number * @default 0.9 */ "jpegSaveQuality": 0.9, /** * The default image width. * * @type Number * @default 400 */ "imageWidth": 400, /** * The default image width. * * @type Number * @default 300 */ "imageHeight": 300, /** * Image preload. The image you want to display when PaintWeb loads. This must * be a reference to an HTML Image element. * * @type HTMLImageElement * @default null */ "imagePreload": null, /** * Default background color. * * @type CSS3Color * @default "#fff" */ "backgroundColor": "#fff", /** * Default fill style. * * @type CSS3Color-rgba functional notation * @default "rgba(0,0,0,1)" */ "fillStyle": "rgba(0,0,0,1)", /** * Default stroke style. * * @type CSS3Color-rgba functional notation * @default "rgba(0,0,255,1)" */ "strokeStyle": "rgba(0,0,255,1)", /** * Enable checkers background. This tells the user interface to render * checkers in the image background. These are visible only when parts of * the image being edited are transparent. * * <p>If the device you are running PaintWeb on has limited resources, * disabling the checkers background should improve the drawing performance. * * @type Boolean * @default true */ "checkersBackground": true, /** * GUI placeholder element. This element will hold all the PaintWeb interface * elements. * * <p>For a successful initialization of PaintWeb, you must define this * configuration value programatically from your scripts. * * @type Element * @default null */ "guiPlaceholder": null, /** * Shape drawing "type": filled, only stroke, or both. Possible values: * "filled", "stroke" or "both". * * @type String * @default "both" */ "shapeType": "both", /** * Number of available history steps. * * @type Number * @default 10 */ "historyLimit": 10, /** * Zoom factor when the user increases/decreases the image zoom level. * * @type Number * @default 0.05 */ // 0.05 means 5% zoom. "imageZoomStep": 0.05, /** * The maximum allowed image zoom level. * * @type Number * @default 4 */ // 4 means 400% zoom. "imageZoomMax": 4, /** * The minimum allowed image zoom level. * * @type Number * @default 0.2 */ // 0.2 means 20% zoom. "imageZoomMin": 0.2, /** * The image zoom control keys, for zoom in, zoom out and zoom reset. * @type Object */ "imageZoomKeys": { "in": "+", "out": "-", "reset": "*" }, /** * Holds the list of drawing tools you want to load. * @type Array */ "tools": ["bcurve", "cbucket", "cpicker", "ellipse", "eraser", "hand", "insertimg", "line", "pencil", "polygon", "rectangle", "selection", "text"], /** * Tools folder. * @type String * @default "tools" */ "toolsFolder": "tools", /** * The default tool ID. * * @type String * @default "line" * @see this.tools The array holding the list of drawing tools you want * loaded. */ "toolDefault": "line", /** * Tool drawing delay (milliseconds). Some tools delay their drawing * operations for performance reasons. * * @type Number * @default 80 */ "toolDrawDelay": 80, /** * Holds the list of extensions you want to load. * @type Array */ "extensions": ["colormixer", "moodle"], //"extensions": ["colormixer", "mousekeys"], /** * Extensions folder. * * @type String * @default "extensions" */ "extensionsFolder": "extensions", /** * @namespace Line tool options. */ "line": { /** * Line cap. Possible values: "butt", "round", "square". * * @type String * @default "round" */ "lineCap": "round", /** * Line join. Possible values: "round", "bevel", "miter". * * @type String * @default "round" */ "lineJoin": "round", /** * Line width. * * @type Number * @default 1 */ "lineWidth": 1, /** * Miter limit. * * @type Number * @default 10 */ "miterLimit": 10 }, /** * @namespace Shadow options. */ "shadow": { /** * Tells if a shadow should render or not. * * @type Boolean * @default false */ "enable": false, /** * Shadow color * * @type CSS3Color-rgba() functional notation * @default "rgba(0,0,0,1)" */ "shadowColor": "rgba(0,0,0,1)", /** * Shadow blur. * * @type Number * @default 5 */ "shadowBlur": 5, /** * Shadow offset X. * * @type Number * @default 5 */ "shadowOffsetX": 5, /** * Shadow offset %. * * @type Number * @default 5 */ "shadowOffsetY": 5 }, /** * @namespace Selection tool options. */ "selection": { /** * Selection transformation mode. This tells if any drag/resize would also * affect the selected pixels or not. * * @type Boolean * @default false */ "transform": false, /** * Transparent selection. * * @type Boolean * @default true */ "transparent": true, /** * Selection marquee border width. * * @type Number * @default 3 */ "borderWidth": 3, /** * Keyboard shortcuts for several selection-related commands. * @type Object */ "keys": { "selectionCrop": "Control K", "selectionDelete": "Delete", "selectionDrop": "Escape", "selectionFill": "Alt Backspace", "transformToggle": "Enter" } }, /** * Text tool options. * @type Object */ "text": { "bold": false, "italic": false, /** * The default list of font families available in font family drop-down. * @type Array */ "fontFamilies": ["sans-serif", "serif", "cursive", "fantasy", "monospace"], /** * The font family used for rendering the text. * @type String * @default "sans-serif" */ "fontFamily": "sans-serif", "fontSize": 36, /** * Horizontal text alignment. Possible values: "left", "center", "right". * * <p>Note that the Canvas Text API also defines the "start" and "end" * values, which are not "supported" by PaintWeb. * * @type String * @default "left" */ "textAlign": "left", /** * Vertical text alignment. Possible values: "top", "hanging", "middle", * "alphabetic", "ideographic", or "bottom". * * @type String * @default "alphabetic" */ "textBaseline": "top" }, /** * @namespace Color Mixer extension configuration. */ "colormixer": { /** * Holds the minimum and maximum value for each color channel input field. * The value incrementation step is also included - this is used the user * presses the up/down arrow keys in the input of the color channel. * * @type Object */ "inputValues": { // RGB // order: minimum, maximum, step "red": [0, 255, 1], "green": [0, 255, 1], "blue": [0, 255, 1], // HSV // Hue - degrees "hue": [0, 360, 1], "sat": [0, 255, 1], "val": [0, 255, 1], // CMYK - all are percentages "cyan": [0, 100, 1], "magenta": [0, 100, 1], "yellow": [0, 100, 1], "black": [0, 100, 1], // CIE Lab // cie_l = Lightness, it's a percentage value // cie_a and cie_b are the color-opponent dimensions "cie_l": [ 0, 100, 1], "cie_a": [ -86, 98, 1], "cie_b": [-107, 94, 1], "alpha": [0, 100, 1] }, /** * CIE Lab configuration. * @type Object */ "lab": { // The RGB working space is sRGB which has the reference white point of // D65. // These are the chromaticity coordinates for the red, green and blue // primaries. "x_r": 0.64, "y_r": 0.33, "x_g": 0.3, "y_g": 0.6, "x_b": 0.13, "y_b": 0.06, // Standard observer: D65 (daylight), 2° (CIE 1931). // Chromaticity coordinates. "ref_x": 0.31271, "ref_y": 0.32902, // This is the calculated reference white point (xyY to XYZ) for D65, also // known as the reference illuminant tristimulus. // These values are updated based on chromaticity coordinates, during // initialization. "w_x": 0.95047, "w_y": 1, "w_z": 1.08883, // The 3x3 matrix used for multiplying the RGB values when converting RGB // to XYZ. // These values are updated based on the chromaticity coordinates, during // initialization. "m": [ 0.412424, 0.212656, 0.0193324, 0.357579, 0.715158, 0.119193, 0.180464, 0.0721856, 0.950444], // The same matrix, but inverted. This is used for the XYZ to RGB conversion. "m_i": [ 3.24071, -0.969258, 0.0556352, -1.53726, 1.87599, -0.203996, -0.498571, 0.0415557, 1.05707] }, /** * Slider width. This value must be relative to the color space * visualisation canvas element: 1 means full width, 0.5 means half width, * etc. * * @type Number * @default 0.10 (which is 10% of the canvas element width) */ "sliderWidth": 0.10, /** * Spacing between the slider and the color chart. * * @type Number * @default 0.03 (which is 3% of the canvas element width) */ "sliderSpacing": 0.03, /** * Holds the list of color palettes. * @type Object */ "colorPalettes": { "_saved" : { // Color values are: red, green, blue. All three channels have values // ranging between 0 and 1. "colors" : [[1,1,1], [1,1,0], [1,0,1], [0,1,1], [1,0,0], [0,1,0], [0,0,1], [0,0,0]] }, "windows" : { "file" : "colors/windows.json" }, "macos" : { "file" : "colors/macos.json" }, "web" : { "file" : "colors/web.json" } }, "paletteDefault": "windows" }, /** * @namespace Holds the MouseKeys extension options. */ "mousekeys": { /** * The mouse keys movement acceleration. * * @type Number * @default 0.1 * @see PaintMouseKeys The MouseKeys extension. */ "accel": 0.1, /** * Holds the list of actions, associated to keyboard shortcuts. * * @type Object */ // We make sure the number keys on the NumPad also work when the Shift key // is down. "actions": { "ButtonToggle": [0], "SouthWest": [1], "South": [2], "SouthEast": [3], "West": [4], "ButtonClick": [5], "East": [6], "NorthWest": [7], "North": [8], "NorthEast": [9] /* You might want Shift+NumPad keys as well ... Shift+Arrows breaks spatial navigation in Opera. "ButtonToggle": [0, "Shift Insert"], "SouthWest": [1, "Shift End"], "South": [2, "Shift Down"], "SouthEast": [3, "Shift PageDown"], "West": [4, "Shift Left"], "ButtonClick": [5, "Shift Clear"], "East": [6, "Shift Right"], "NorthWest": [7, "Shift Home"], "North": [8, "Shift Up"], "NorthEast": [9, "Shift PageUp"] */ } }, /** * Keyboard shortcuts associated to drawing tools and other actions. * * @type Object * @see PaintTools The object holding all the drawing tools. */ "keys": { // Use "command": "id" to execute some command. "Control Z": { "command": "historyUndo" }, "Control Y": { "command": "historyRedo" }, "Control N": { "command": "imageClear" }, "Control S": { "command": "imageSave" }, "Control A": { "command": "selectAll" }, "Control X": { "command": "selectionCut" }, "Shift Delete": { "command": "selectionCut" }, "Control C": { "command": "selectionCopy" }, "Control V": { "command": "clipboardPaste" }, // Use "toolActivate": "id" to activate the tool with the given ID. "C": { "toolActivate": "cpicker" }, "E": { "toolActivate": "ellipse" }, "F": { "toolActivate": "cbucket" }, "G": { "toolActivate": "polygon" }, "H": { "toolActivate": "hand" }, "I": { "toolActivate": "insertimg" }, "L": { "toolActivate": "line" }, "O": { "toolActivate": "eraser" }, "P": { "toolActivate": "pencil" }, "R": { "toolActivate": "rectangle" }, "S": { "toolActivate": "selection" }, "T": { "toolActivate": "text" }, "V": { "toolActivate": "bcurve" }, // Miscellaneous commands. "X": { "command": "swapFillStroke" }, "F1": { "command": "about" } }, /** * The image save method used by the Moodle extension: * <ul> * <li><code>"file"</code> - to save the image on the server using files * (with the server-side script imagesave.php). * * <li><code>"dataURL"</code> - to save the image as a data URL inside the * textarea, in TinyMCE 3. * </ul> * * @type String * @default "file" */ "moodleSaveMethod": "file" // vim:set spell spl=en fo=wan1croql tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix ft=javascript: }
JavaScript
/* * Copyright (C) 2009 Mihai Şucan * * This file is part of PaintWeb. * * PaintWeb is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PaintWeb is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PaintWeb. If not, see <http://www.gnu.org/licenses/>. * * $URL: http://code.google.com/p/paintweb $ * $Date: 2009-08-19 20:09:54 +0300 $ */ /** * @author <a lang="ro" href="http://www.robodesign.ro/mihai">Mihai Şucan</a> * @fileOverview This script allows the user to create a new image to edit * inside PaintWeb, directly from TinyMCE. */ tinyMCEPopup.requireLangPack(); tinyMCEPopup.onInit.add(function() { var newImageForm = document.getElementById('newimageform'), imgWidth = document.getElementById('imgWidth'), imgHeight = document.getElementById('imgHeight'), imgBgrColor = document.getElementById('imgBgrColor'), imgTitle = document.getElementById('imgTitle'), altText = document.getElementById('altText'), btnCancel = document.getElementById('cancel'); newImageForm.onsubmit = function (ev) { var fn = tinyMCEPopup.getWindowArg('newImageFn'); if (fn) { fn(imgWidth.value, imgHeight.value, imgBgrColor.value, altText.value, imgTitle.value); } tinyMCEPopup.close(); }; imgBgrColor.parentNode.lastChild.innerHTML = ' ' + getColorPickerHTML('imgBgrColor_pick', 'imgBgrColor'); imgBgrColor.onchange = function () { updateColor('imgBgrColor_pick', 'imgBgrColor'); }; updateColor('imgBgrColor_pick', 'imgBgrColor'); btnCancel.onclick = function () { tinyMCEPopup.close(); }; }); // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
/* * Copyright (C) 2009, 2010 Mihai Şucan * * This file is part of PaintWeb. * * PaintWeb is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PaintWeb is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PaintWeb. If not, see <http://www.gnu.org/licenses/>. * * $URL: http://code.google.com/p/paintweb $ * $Date: 2010-06-26 22:10:30 +0300 $ */ /** * @author <a lang="ro" href="http://www.robodesign.ro/mihai">Mihai Şucan</a> * @fileOverview This is a plugin for TinyMCE which integrates PaintWeb. */ (function() { // The plugin URL. This points to the location of this TinyMCE plugin. var pluginUrl = null; // Reference to the DOM element of the overlay button displayed on top of the // selected image. var overlayButton = null; // Reference to the PaintWeb configuration object. var paintwebConfig = null; // Reference to the current PaintWeb instance object. var paintwebInstance = null; // Reference to the TinyMCE "plugin bar" displayed above PaintWeb, when PaintWeb // is displayed. This "plugin bar" allows the user to save/cancel image edits. var pluginBar = null; // The delay used for displaying temporary messages in the plugin bar. var pluginBarDelay = 10000; // 10 seconds // The timeout ID used for the plugin bar when a temporary message is displayed. var pluginBarTimeout = null; // Once PaintWeb is closed, the instance remains active. This value controls how // long the PaintWeb instance is kept alive. Once the time elapsed, the PaintWeb // instance is destroyed entirely. var pwDestroyDelay = 30000; // 30 seconds // The timeout ID used for destroying the PaintWeb instance. var pwDestroyTimer = null; // Tells if the user intends to save the image and return to TinyMCE or not. // This value is set to true when the user clicks the "Save" button in the // plugin bar. var pwSaveReturn = false; // Reference to the container of the current TinyMCE editor instance. var targetContainer = null; // The current TinyMCE editor instance. var targetEditor = null; // Reference to the image element being edited. var targetImage = null; // Tells if the image being edited uses a data URL or not. var imgIsDataURL = false; // The new image URL. Once the user saves the image, the remote server might // require a change for the image URL. var imgNewUrl = null; // Tells if the current image has been ever updated using "image save". var imgSaved = false; var pwlib = null; if (!window.tinymce) { alert('It looks like the PaintWeb plugin for TinyMCE cannot run.' + 'TinyMCE was not detected!'); return; } // Basic functionality used by PaintWeb. if (!window.XMLHttpRequest || !document.createElement('canvas').getContext) { return; } if (!window.getComputedStyle) { try { if (!window.getComputedStyle(document.createElement('div'), null)) { return; } } catch (err) { return; } } var isOpera, isWebkit, isGecko; // Image data URLs are considered external resources when they are drawn in // a Canvas element. This happens only in Gecko 1.9.0 or older (Firefox 3.0) and // in Webkit (Chrome/Safari). This is a problem because PaintWeb cannot save the // image once such data URL is loaded. var dataURLfilterNeeded = (function () { var ua = navigator.userAgent.toLowerCase(); isOpera = window.opera || /\b(opera|presto)\b/.test(ua); isWebkit = !isOpera && /\b(applewebkit|webkit)\b/.test(ua); isGecko = !isOpera && !isWebkit && /\bgecko\b/.test(ua); if (isWebkit) { return true; } if (isGecko) { var geckoRev = /\brv\:([^;\)\s]+)[;\)\s]/.exec(ua); if (geckoRev && geckoRev[1]) { geckoRev = geckoRev[1].replace(/[^\d]+$/, '').split('.'); if (geckoRev[0] == 1 && geckoRev[1] <= 9 && geckoRev[2] < 1) { return true; } } } return false; })(); /** * Load PaintWeb. This function tells TinyMCE to load the PaintWeb script. */ function paintwebLoad () { if (window.PaintWeb) { paintwebLoaded(); return; } var config = targetEditor.getParam('paintweb_config'), src = config.tinymce.paintwebFolder + 'paintweb.js'; tinymce.ScriptLoader.load(src, paintwebLoaded); }; /** * The event handler for the PaintWeb script load. This function creates a new * instance of PaintWeb and configures it. */ function paintwebLoaded () { if (paintwebInstance) { return; } paintwebInstance = new PaintWeb(); paintwebConfig = paintwebInstance.config; var config = targetEditor.getParam('paintweb_config'), textarea = targetEditor.getElement(); pNode = targetContainer.parentNode, pwContainer = tinymce.DOM.create('div'); pNode.insertBefore(pwContainer, textarea.nextSibling); if (!PaintWeb.baseFolder) { PaintWeb.baseFolder = config.tinymce.paintwebFolder; } config.imageLoad = targetImage; config.guiPlaceholder = pwContainer; if (!config.lang) { config.lang = targetEditor.getParam('language'); } for (var prop in config) { paintwebConfig[prop] = config[prop]; } // Give PaintWeb access to the TinyMCE editor instance. paintwebConfig.tinymceEditor = targetEditor; paintwebInstance.init(paintwebInitialized); }; /** * The initialization event handler for PaintWeb. When PaintWeb is initialized * this method configures the PaintWeb instance to work properly. A bar * representing the plugin is also added, to let the user save/cancel image * edits. * * @param {pwlib.appEvent.appInit} ev The PaintWeb application event object. */ function paintwebInitialized (ev) { if (overlayButton && targetEditor) { overlayButton.value = targetEditor.getLang('paintweb.overlayButton', 'Edit'); } if (ev.state !== PaintWeb.INIT_DONE) { alert('PaintWeb initialization failed! ' + ev.errorMessage); paintwebInstance = null; targetImage = null; targetEditor = null; return; } pwlib = window.pwlib; paintwebInstance.events.add('imageSave', paintwebSave); paintwebInstance.events.add('imageSaveResult', paintwebSaveResult); if (pluginBar) { paintwebInstance.events.add('viewportSizeChange', paintwebViewportSizeChange); } paintwebShow(ev); }; /** * The <code>click</code> event handler for the Save button displayed on the * plugin bar. */ function pluginSaveButton () { pwSaveReturn = true; paintwebInstance.imageSave(); }; /** * The <code>click</code> event handler for the Cancel button displayed on the * plugin bar. */ function pluginCancelButton () { paintwebHide(); }; /** * The <code>imageSave</code> application event handler for PaintWeb. When the * user elects to save the image in PaintWeb, this function is invoked to * provide visual feedback in the plugin bar. * * <p>If the <var>imageSaveDataURL</var> boolean property is set to true, then * the source of the image is also updated to hold the new data URL. * * @param {pwlib.appEvent.imageSave} ev The PaintWeb application event object. */ function paintwebSave (ev) { if (paintwebConfig.tinymce.imageSaveDataURL) { ev.preventDefault(); var url = imgIsDataURL ? '-' : targetEditor.dom.getAttrib(targetImage, 'src'); paintwebInstance.events.dispatch(new pwlib.appEvent.imageSaveResult(true, url, ev.dataURL)); } else if (pluginBar) { if (pluginBarTimeout) { clearTimeout(pluginBarTimeout); pluginBarTimeout = null; } pluginBar.firstChild.innerHTML = targetEditor.getLang('paintweb.statusSavingImage', 'Saving image...'); } }; /** * The <code>imageSaveResult</code> application event handler for PaintWeb. * * @param {pwlib.appEvent.imageSaveResult} ev The PaintWeb application event * object. */ function paintwebSaveResult (ev) { if (!targetImage) { return; } // Update the status message in the "plugin bar". if (pluginBar) { if (ev.successful) { pluginBar.firstChild.innerHTML = targetEditor.getLang('paintweb.statusImageSaved', 'Image save was succesful!'); } else { pluginBar.firstChild.innerHTML = targetEditor.getLang('paintweb.statusImageSaveFailed', 'Image save failed!'); } if (pluginBarTimeout) { clearTimeout(pluginBarTimeout); } pluginBarTimeout = setTimeout(pluginBarResetContent, pluginBarDelay); } if (ev.successful) { imgSaved = true; if (ev.urlNew) { // store the new URL. When PaintWeb is closed, the image src attribute is // updated. imgNewUrl = ev.urlNew; } if (pwSaveReturn) { pwSaveReturn = false; paintwebHide(); } } }; /** * Reset the text content of the plugin bar. */ function pluginBarResetContent () { if (!pluginBar) { return; } pluginBarTimeout = null; pluginBar.firstChild.innerHTML = targetEditor.getLang('paintweb.statusImageEditing', 'You are editing an image from TinyMCE.'); }; /** * The <code>viewportSizeChange</code> PaintWeb application event handler. This * synchronises the size of the TinyMCE plugin bar with that of the PaintWeb * GUI. * * @param {pwlib.appEvent.viewportSizeChange} ev The application event object. */ function paintwebViewportSizeChange (ev) { tinymce.DOM.setStyle(pluginBar, 'width', ev.width); }; /** * Start PaintWeb. This function performs the actual PaintWeb invocation. * * @returns {Boolean} True PaintWeb is about to start, or false otherwise. */ function paintwebEditStart () { if (!checkEditableImage(targetImage)) { targetImage = null; return false; } if (pwDestroyTimer) { clearTimeout(pwDestroyTimer); pwDestroyTimer = null; } var pwStart = function () { if (overlayButton && overlayButton.parentNode) { overlayButton.value = targetEditor.getLang('paintweb.overlayLoading', 'Loading PaintWeb...'); } if (paintwebInstance) { paintwebInstance.imageLoad(targetImage); paintwebShow(); } else { paintwebLoad(); } }; var dataURLfilterLoaded = function () { tinymce.dom.Event.remove(targetImage, 'load', dataURLfilterLoaded); imgIsDataURL = false; pwStart(); }; var src = targetEditor.dom.getAttrib(targetImage, 'src'); if (src.substr(0, 5) === 'data:') { imgIsDataURL = true; } else { imgIsDataURL = false; } var cfg = imgIsDataURL && dataURLfilterNeeded ? targetEditor.getParam('paintweb_config') : null; if (cfg && cfg.tinymce.imageDataURLfilter) { tinymce.util.XHR.send({ url: cfg.tinymce.imageDataURLfilter, content_type: 'application/x-www-form-urlencoded', data: 'url=-&dataURL=' + encodeURIComponent(src), error: function () { if (window.console && console.log) { console.log('TinyMCE.PaintWeb: failed to preload image data URL!'); } pwStart(); }, success: function (result) { if (!result) { pwStart(); return; } result = tinymce.util.JSON.parse(result); if (!result || !result.successful || !result.urlNew) { pwStart(); return; } imgNewUrl = targetImage.src; tinymce.dom.Event.add(targetImage, 'load', dataURLfilterLoaded); targetEditor.dom.setAttrib(targetImage, 'src', result.urlNew); } }); } else { pwStart(); } src = null; return true; }; /** * Create a new image and start PaintWeb. * * @param {Number} width The image width. * @param {Number} height The image height. * @param {String} [bgrColor] The image background color. * @param {String} [alt] The alternative text / the value for the "alt" * attribute. * @param {String} [title] */ function paintwebNewImage (width, height, bgrColor, alt, title) { width = parseInt(width) || 0; height = parseInt(height) || 0; if (!width || !height) { return; } var canvas = tinymce.DOM.create('canvas', { 'width': width, 'height': height}), context = canvas.getContext('2d'); if (bgrColor) { context.fillStyle = bgrColor; context.fillRect(0, 0, width, height); } targetEditor.execCommand('mceInsertContent', false, '<img id="paintwebNewImage">'); var elem = targetEditor.dom.get('paintwebNewImage'); if (!elem || elem.id !== 'paintwebNewImage' || elem.nodeName.toLowerCase() !== 'img') { return; } if (alt) { targetEditor.dom.setAttrib(elem, 'alt', alt); } if (title) { targetEditor.dom.setAttrib(elem, 'title', title); } elem.src = canvas.toDataURL(); elem.setAttribute('mce_src', elem.src); elem.removeAttribute('id'); targetImage = elem; canvas = null; context = null; paintwebEditStart(); }; /** * Show PaintWeb on-screen. This function hides the current TinyMCE editor * instance and shows up the PaintWeb instance. * * @param [ev] Event object. */ function paintwebShow (ev) { var rect = null; if (paintwebConfig.tinymce.syncViewportSize) { rect = tinymce.DOM.getRect(targetEditor.getContentAreaContainer()); } tinymce.DOM.setStyle(targetContainer, 'display', 'none'); // Give PaintWeb access to the TinyMCE editor instance. paintwebConfig.tinymceEditor = targetEditor; if (!ev || ev.type !== 'appInit') { paintwebInstance.gui.show(); } if (rect && rect.w && rect.h) { paintwebInstance.gui.resizeTo(rect.w + 'px', rect.h + 'px'); } if (pluginBar) { pluginBarResetContent(); var placeholder = paintwebConfig.guiPlaceholder; if (!pluginBar.parentNode) { placeholder.parentNode.insertBefore(pluginBar, placeholder); } } }; /** * Hide PaintWeb from the screen. This hides the PaintWeb target object of the * current instance, and displays back the TinyMCE container element. */ function paintwebHide () { paintwebInstance.gui.hide(); if (overlayButton && targetEditor) { overlayButton.value = targetEditor.getLang('paintweb.overlayButton', 'Edit'); } if (pluginBar && pluginBar.parentNode) { targetContainer.parentNode.removeChild(pluginBar); } // Update the target image src attribute if needed. if (imgNewUrl) { // The tinymce.utl.URI class mangles data URLs. if (imgNewUrl.substr(0, 5) !== 'data:') { targetEditor.dom.setAttrib(targetImage, 'src', imgNewUrl); } else { targetImage.src = imgNewUrl; if (targetImage.hasAttribute('mce_src')) { targetImage.setAttribute('mce_src', imgNewUrl); } } imgNewUrl = null; } else if (!imgIsDataURL && imgSaved) { // Force a refresh for the target image from the server. var src = targetEditor.dom.getAttrib(targetImage, 'src'), rnd = (new Date()).getMilliseconds() * Math.round(Math.random() * 100); if (src.indexOf('?') === -1) { src += '?' + rnd; } else { if (/\?[0-9]+$/.test(src)) { src = src.replace(/\?[0-9]+$/, '?' + rnd); } else if (/&[0-9]+$/.test(src)) { src = src.replace(/&[0-9]+$/, '&' + rnd); } else { src += '&' + rnd; } } targetEditor.dom.setAttrib(targetImage, 'src', src); } targetContainer.style.display = ''; targetImage = null; imgSaved = false; targetEditor.focus(); if (!pwDestroyTimer) { pwDestroyTimer = setTimeout(paintwebDestroy, pwDestroyDelay); } }; /** * After a given time of idleness, when the user stops from working with * PaintWeb, we destroy the current PaintWeb instance, to release some memory. */ function paintwebDestroy () { if (paintwebInstance) { paintwebInstance.destroy(); var pNode = paintwebConfig.guiPlaceholder.parentNode; pNode.removeChild(paintwebConfig.guiPlaceholder); paintwebInstance = null; paintwebConfig = null; pwDestroyTimer = null; } }; /** * The "paintwebEdit" command. This function is invoked when the user clicks the * PaintWeb button on the toolbar. */ function paintwebEditCommand () { if (targetImage) { return; } var n = this.selection.getNode(), tag = n.nodeName.toLowerCase(); if (tag !== 'img' && overlayButton && overlayButton.parentNode && overlayButton._targetImage) { n = overlayButton._targetImage; tag = n.nodeName.toLowerCase(); } targetEditor = this; targetContainer = this.getContainer(); targetImage = n; // If PaintWeb won't start, then we create a new image. if (!paintwebEditStart() && tag !== 'img') { this.windowManager.open( { file: pluginUrl + '/newimage.html', width: 350 + parseInt(this.getLang('paintweb.dlg_delta_width', 0)), height: 200 + parseInt(this.getLang('paintweb.dlg_delta_height', 0)), inline: 1 }, { plugin_url: pluginUrl, newImageFn: paintwebNewImage } ); } }; /** * Check if an image element can be edited with PaintWeb. The image element * source must be a data URI or it must be an image from the same domain as * the page. * * @param {HTMLImageElement} n The image element. * @returns {Boolean} True if the image can be edited, or false otherwise. */ function checkEditableImage (n) { if (!n) { return false; } var url = n.src; if (n.nodeName.toLowerCase() !== 'img' || !url) { return false; } var pos = url.indexOf(':'), proto = url.substr(0, pos + 1).toLowerCase(); if (proto === 'data:') { return true; } if (proto !== 'http:' && proto !== 'https:') { return false; } var host = url.replace(/^https?:\/\//i, ''); pos = host.indexOf('/'); if (pos > -1) { host = host.substr(0, pos); } if (host !== window.location.host) { return false; } return true; }; /** * Add the overlay button to an image element node. * * @param {tinymce.Editor} ed The TinyMCE editor instance. * @param {Element} n The image element node you want to add to the overlay * button. */ function overlayButtonAdd (ed, n) { if (!overlayButton || !ed || !n) { return; } var offsetTop = 5, offsetLeft = 5, sibling = null, pNode; // Try to avoid adding the overlay button inside an anchor. if (n.parentNode.nodeName.toLowerCase() === 'a') { pNode = n.parentNode.parentNode; sibling = n.parentNode.nextSibling; } else { pNode = n.parentNode; sibling = n.nextSibling; } overlayButton._targetImage = n; ed.dom.setStyles(overlayButton, { 'top': (n.offsetTop + offsetTop) + 'px', 'left': (n.offsetLeft + offsetLeft) + 'px'}); overlayButton.value = ed.getLang('paintweb.overlayButton', 'Edit'); pNode.insertBefore(overlayButton, sibling); }; /** * Clear the document of the TinyMCE editor instance of any possible PaintWeb * overlay button remnant. This makes sure that the iframe DOM document does not * contain any PaintWeb overlay button. Firefox remembers the overlay button * after a page refresh. * * @param {tinymce.Editor} ed The editor instance that the plugin is * initialized in. */ function overlayButtonCleanup (ed) { if (!overlayButton || !ed || !ed.getDoc) { return; } var root, elems, pNode; if (overlayButton) { if (overlayButton.parentNode) { pNode = overlayButton.parentNode; pNode.removeChild(overlayButton); } overlayButton._targetImage = null; } root = ed.getDoc(); if (!root || !root.getElementsByClassName) { return; } elems = root.getElementsByClassName(overlayButton.className); for (var i = 0; i < elems.length; i++) { pNode = elems[i].parentNode; pNode.removeChild(elems[i]); } }; // Load plugin specific language pack tinymce.PluginManager.requireLangPack('paintweb'); tinymce.create('tinymce.plugins.paintweb', { /** * Initializes the plugin. This method sets-up the current editor instance, by * adding a new button, <var>paintwebEdit</var>, and by setting up several * event listeners. * * @param {tinymce.Editor} ed Editor instance that the plugin is initialized * in. * @param {String} url Absolute URL to where the plugin is located. */ init: function (ed, url) { var t = this; pluginUrl = url; // Register the command so that it can be invoked by using // tinyMCE.activeEditor.execCommand('paintwebEdit'); ed.addCommand('paintwebEdit', paintwebEditCommand, ed); // Register PaintWeb button ed.addButton('paintwebEdit', { title: 'paintweb.toolbarButton', cmd: 'paintwebEdit', image: pluginUrl + '/img/paintweb2.gif' }); // Add a node change handler which enables the PaintWeb button in the UI // when an image is selected. if (isOpera) { // In Opera, due to bug DSK-265135, we only listen for the keyup and // mouseup events. ed.onKeyUp.add(this.edNodeChange); ed.onMouseUp.add(this.edNodeChange); } else { ed.onNodeChange.add(this.edNodeChange); } var config = ed.getParam('paintweb_config') || {}; if (!config.tinymce) { config.tinymce = {}; } // Integrate into the ContextMenu plugin if the user desires so. if (config.tinymce.contextMenuItem && ed.plugins.contextmenu) { ed.plugins.contextmenu.onContextMenu.add(this.pluginContextMenu); } // Listen for the form submission event. This is needed when the user is // inside PaintWeb, editing an image. The user is warned that image changed // and it's not saved, and the form submission event is cancelled. ed.onSubmit.add(this.edSubmit); // Create the overlay button element if the configuration allows so. if (config.tinymce.overlayButton) { // Make sure the button doesn't show up in the article. ed.onBeforeGetContent.add(overlayButtonCleanup); ed.onInit.add(function (ed) { // Cleanup after initialization. Firefox remembers the content between // page reloads. overlayButtonCleanup(ed); ed.onKeyDown.addToTop(t.overlayButtonEvent); ed.onMouseDown.addToTop(t.overlayButtonEvent); }); overlayButton = tinymce.DOM.create('input', { 'type': 'button', 'class': 'paintweb_tinymce_overlayButton', 'style': 'position:absolute', 'value': ed.getLang('paintweb.overlayButton', 'Edit')}); } // Handle the dblclick events for image elements, if the user wants it. if (config.tinymce.dblclickHandler) { ed.onDblClick.add(this.edDblClick); } // Add a "plugin bar" above the PaintWeb editor, when PaintWeb is active. // This bar shows the image file name being edited, and provides two buttons // for image save and for cancelling any image edits. if (config.tinymce.pluginBar) { pluginBar = tinymce.DOM.create('div', { 'class': 'paintweb_tinymce_status', 'style': 'display:none'}); var saveBtn = tinymce.DOM.create('input', { 'type': 'button', 'class': 'paintweb_tinymce_save', 'title': ed.getLang('paintweb.imageSaveButtonTitle', 'Save the image and return to TinyMCE.'), 'value': ed.getLang('paintweb.imageSaveButton', 'Save')}); saveBtn.addEventListener('click', pluginSaveButton, false); var cancelBtn = tinymce.DOM.create('input', { 'type': 'button', 'class': 'paintweb_tinymce_cancel', 'title': ed.getLang('paintweb.cancelEditButtonTitle', 'Cancel image edits and return to TinyMCE.'), 'value': ed.getLang('paintweb.cancelEditButton', 'Cancel')}); cancelBtn.addEventListener('click', pluginCancelButton, false); var textSpan = tinymce.DOM.create('span'); pluginBar.appendChild(textSpan); pluginBar.appendChild(saveBtn); pluginBar.appendChild(cancelBtn); } }, /** * The <code>nodeChange</code> event handler for the TinyMCE editor. This * method provides visual feedback for editable image elements. * * @private * * @param {tinymce.Editor} ed The editor instance that the plugin is * initialized in. */ edNodeChange: function (ed) { var cm = ed.controlManager, n = ed.selection.getNode(); // Do not do anything inside the overlay button. if (!n || overlayButton && overlayButton._targetImage && n && n.className === overlayButton.className) { return; } var disabled = !checkEditableImage(n); if (n.nodeName.toLowerCase() === 'img' && disabled) { cm.setDisabled('paintwebEdit', true); cm.setActive('paintwebEdit', false); } else { cm.setDisabled('paintwebEdit', false); cm.setActive('paintwebEdit', !disabled); } if (!overlayButton) { return; } if (!disabled) { overlayButtonAdd(ed, n); } else if (overlayButton._targetImage) { overlayButton._targetImage = null; } }, /** * The <code>mousedown</code> and <code>keydown</code> event handler for the * editor. This method starts PaintWeb when the user clicks the "Edit" overlay * button, or cleans the document of any overlay button element. * * @param {tinymce.Editor} ed The TinyMCE editor instance. * @param {Event} ev The DOM Event object. */ overlayButtonEvent: function (ed, ev) { var n = ev.type === 'mousedown' ? ev.target : ed.selection.getNode(); // If the user clicked the Edit overlay button, then we consider the user // wants to start PaintWeb. if (!targetImage && ev.type === 'mousedown' && overlayButton && n && n.className === overlayButton.className && overlayButton._targetImage) { targetEditor = ed; targetContainer = ed.getContainer(); targetImage = overlayButton._targetImage; paintwebEditStart(); } else if (n && n.nodeName.toLowerCase() !== 'img') { // ... otherwise make sure the document is clean. overlayButtonCleanup(ed); } }, /** * The <code>dblclick</code> event handler for the editor. This method starts * PaintWeb when the user double clicks an editable image element. * * @param {tinymce.Editor} ed The TinyMCE editor instance. * @param {Event} ev The DOM Event object. */ edDblClick: function (ed, ev) { if (!targetImage && checkEditableImage(ev.target)) { targetEditor = ed; targetContainer = ed.getContainer(); targetImage = ev.target; ev.target.focus(); paintwebEditStart(); } }, /** * The <code>submit</code> event handler for the form associated to the * textarea of the current TinyMCE editor instance. This method checks if the * current PaintWeb instance is open and if the user has made changes to the * image. If yes, then the form submission is cancelled and the user is warned * about losing unsaved changes. * * @param {tinymce.Editor} ed The TinyMCE editor instance. * @param {Event} ev The DOM Event object. */ edSubmit: function (ed, ev) { // Check if PaintWeb is active. if (!targetImage || !paintwebInstance) { return; } // Check if the image has been modified. if (!paintwebInstance.image.modified) { // If not, then hide PaintWeb so we can update the target image. paintwebHide(); // Save the textarea content once again. ed.save(); return; } // The image is not saved, thus we prevent form submission. ev.preventDefault(); if (pluginBar) { var str = ed.getLang('paintweb.submitUnsaved', 'The image is not saved! You cannot submit the form. Please save ' + 'the image changes, or cancel image editing, then try again.'); pluginBar.firstChild.innerHTML = str; if (pluginBarTimeout) { clearTimeout(pluginBarTimeout); } pluginBarTimeout = setTimeout(pluginBarResetContent, pluginBarDelay); // tabIndex is needed so we can focus and scroll to the plugin bar. pluginBar.tabIndex = 5; pluginBar.focus(); pluginBar.tabIndex = -1; } if (typeof paintwebConfig.tinymce.onSubmitUnsaved === 'function') { paintwebConfig.tinymce.onSubmitUnsaved(ev, ed, paintwebInstance); } }, /** * This is the <code>contextmenu</code> event handler for the ContextMenu * plugin provided in the default TinyMCE installation. * * @param {tinymce.plugin.contextmenu} plugin Instance of the ContextMenu * plugin of TinyMCE. * @param {tinymce.ui.DropMenu} menu The dropmenu instance. * @param {Element} elem The selected element. */ pluginContextMenu: function (plugin, menu, elem) { if (checkEditableImage(elem)) { menu.add({ title: 'paintweb.contextMenuEdit', cmd: 'paintwebEdit', image: pluginUrl + '/img/paintweb2.gif' }); } }, /** * Returns information about the plugin as a name/value array. * The current keys are longname, author, authorurl, infourl and version. * * @returns {Object} Name/value array containing information about the plugin. */ getInfo: function () { return { longname: 'PaintWeb - online painting application', author: 'Mihai Şucan', authorurl: 'http://www.robodesign.ro/mihai', infourl: 'http://code.google.com/p/paintweb', version: '0.9' }; } }); // Register the PaintWeb plugin tinymce.PluginManager.add('paintweb', tinymce.plugins.paintweb); })(); // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
tinyMCE.addI18n('en.paintweb_dlg',{ dlg_title: 'Create a new image', widthLabel: 'Width: ', heightLabel: 'Height: ', bgrColorLabel: 'Background color: ', imgTitleLabel: 'Title: ', altTextLabel: 'Alternate text: ', altTextTitle: 'This text is displayed when the image cannot render.', });
JavaScript
tinyMCE.addI18n('en.paintweb',{ toolbarButton: 'Edit the selected image in PaintWeb. If no image is selected, then you can create a new drawing.', overlayButton: 'Edit', contextMenuEdit: 'Edit the image in PaintWeb', overlayLoading: 'PaintWeb is loading...', statusImageEditing: 'You are editing an image from TinyMCE.', statusSavingImage: 'Saving image changes...', statusImageSaved: 'Image save completed successfully!', statusImageSaveFailed: 'Image save failed!', imageSaveButton: 'Save', imageSaveButtonTitle: 'Save the image and return to TinyMCE.', cancelButton: 'Cancel', cancelButtonTitle: 'Cancel image edits and return to TinyMCE.', submitUnsaved: 'The image is not saved! You cannot submit the form. Please save the image changes, or cancel image editing, then try again.', dlg_delta_width: 0, dlg_delta_height: 0 });
JavaScript
#! /usr/bin/env node /* * Copyright (C) 2011 Mihai Şucan * * This file is part of PaintWeb. * * PaintWeb is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PaintWeb is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PaintWeb. If not, see <http://www.gnu.org/licenses/>. * * $URL: http://code.google.com/p/paintweb $ * $Date: 2011-01-05 14:47:37 $ */ // This is an experimental build script for PaintWeb which must be run in NodeJS // (see nodejs.org). // // You also need: // - dryice - http://github.com/mozilla/dryice // - Step - http://github.com/creationix/step var dryice = require("dryice"); var Step = require("step"); var fs = require("fs"); var folder_base = __dirname; var folder_src = "src"; var folder_tools = folder_src + "/tools"; var folder_extensions = folder_src + "/extensions"; var folder_interface = "interfaces/default"; var file_interface_script = folder_src + "/" + folder_interface + "/script.js"; var folder_includes = folder_src + "/includes"; var file_library = folder_includes + "/lib.js"; var file_paintweb = folder_src + "/paintweb.js"; var folder_build = "build"; var file_paintweb_build = folder_build + "/paintweb.dryice.js"; var file_interface_layout = "layout.xhtml"; var jsvar_filecache = "pwlib.fileCache"; function run() { var files = [file_library]; Step( function readToolsDir() { fs.readdir(folder_tools, this); }, function addTools(err, tools) { if (err) { throw err; } tools.forEach(function(tool) { if (tool != "." && tool != "..") { files.push(folder_tools + "/" + tool); } }); return 1; }, function readExtensionsDir(err) { if (err) { throw err; } fs.readdir(folder_extensions, this); }, function addExtensions(err, extensions) { if (err) { throw err; } extensions.forEach(function(extension) { if (extension != "." && extension != "..") { files.push(folder_extensions + "/" + extension); } }); files.push(file_interface_script, file_paintweb); return 1; }, function buildPaintWeb(err) { if (err) { throw err; } var build = new dryice.build(); build.basedir = folder_base; build.input_files = files; build.output_filters = [filter_addInterfaceLayout, "uglifyjs"]; build.output_file = file_paintweb_build; build.run(this); }, function buildDone(err) { if (err) { throw err; } console.log("build completed"); } ); } function filter_addInterfaceLayout(input) { var data = fs.readFileSync(folder_base + "/" + folder_src + "/" + folder_interface + "/" + file_interface_layout, "utf8"); // cleanup the markup, remove indentation, trailing whitespace and comments. data = data.replace(/^\s+/gm, ""). replace(/\s+$/gm, ""). replace(/<!-- [\x00-\xff]+? -->/g, ""); data = JSON.stringify(data); return input + "\n" + jsvar_filecache + "['" + folder_interface + "/" + file_interface_layout + "'] = " + data + ";"; } run(); // vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
JavaScript
function loadHash() { // This method looks for anchor tags, or hashes, in the URL and sets up the tabs appropriately // var hash = location.hash; // // // if we have a hash value from the URL // if(hash != "") { // // We need to strip off the "#!" which is included in the hash value // hash = hash.substring(2); // var splitHash = hash.split(":"); // var controller = splitHash[0]; // // // if(splitHash[1] != undefined) { // var action = splitHash[1]; // } // else { // //Default action is 'index'' // var action = 'index'; // } // //Load the page // loadPage(controller, action); // } // else { // loadPage("home", "index"); // } } //Ajax cache array var ajax_cache = []; var cacheable = new Array("home:index","users:index", "chat:index"); Array.prototype.contains = function(obj) { var i = this.length; while (i--) { if (this[i] == obj) { return true; } } return false; } var xmlhttp = initXHT(); function initXHT() { if(window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } return xmlhttp; } function loadPage(controller, action, div) { xmlhttp.abort(); div = typeof div !== 'undefined' ? div : 'content'; //Check if file has been called before xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById(div).innerHTML = xmlhttp.responseText; //Cache AJAX call // if(cacheable.contains(controller + ":" + action)) { // ajax_cache[controller + ":" + action] = xmlhttp.responseText; // } } } var url = "router.php?controller=" + controller; if(action != "") { url = url + "&action=" + action; } xmlhttp.open("POST",url + "&uniqueid=" + new Date().getTime(),true); xmlhttp.send(); //loadContents(controller, action); } function postData(form, page) { xmlhttp.abort(); var div = 'content'; var formData = new FormData(form); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById(div).innerHTML = xmlhttp.responseText; //update ajax cache // if(page in ajax_cache) { // ajax_cache[page] = xmlhttp.responseText; // } } } xmlhttp.open("POST", form.getAttribute('action') + "&uniqueid=" + new Date().getTime(), true); xmlhttp.send(formData); return false; } //Check if browser supports webworkers //if(typeof(Worker)!== "undefined") { // //Start a webworker which loads webpages in the ajax_cache // var pageloader = new Worker('scripts/ww_pageloader.js'); // // pageloader.onmessage = function (e) { // ajax_cache[e.data.page_action] = e.data.content; // }; // pageloader.postMessage(ajax_cache); //}
JavaScript
function select(obj) { var items = document.getElementsByClassName('nav_item'); for(var i = 0; i < items.length; i++) { items[i].style.fontWeight = "normal"; } obj.style.fontWeight = "bold"; }
JavaScript
function resetLabels() { document.getElementById('usernameLabel').innerText = '*'; document.getElementById('emailLabel').innerText = '*'; document.getElementById('passwordLabel').innerText = '*'; document.getElementById('confirmedPasswordLabel').innerText = '*'; document.getElementById('firstnameLabel').innerText = '*'; document.getElementById('lastnameLabel').innerText = '*'; } function checkRegisterInput() { resetLabels(); var validRegister = true; var email = document.register.email.value; var password = document.register.password.value; var confirmedPassword = document.register.confirmedPassword.value; var firstname = document.register.firstname.value; var lastname = document.register.lastname.value; if (email != "") { if (!validateEmail(email)) { document.getElementById('emailLabel').innerText = '* invalid email!'; validRegister = false; } } else { document.getElementById('emailLabel').innerText = '* fill in a email!'; validRegister = false; } if (password != "") { if(password != confirmedPassword) { document.getElementById('confirmedPasswordLabel').innerText = '* Not equal to password!'; validRegister = false; } } else { document.getElementById('passwordLabel').innerText = '* Fill in a password!'; validRegister = false; } if (firstname == "") { document.getElementById('firstnameLabel').innerText = '* Fill in a name!'; validRegister = false; } if (lastname == "") { document.getElementById('lastnameLabel').innerText = '* Fill in a name!'; validRegister = false; } return validRegister; } function validateEmail(email) { var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); }
JavaScript
function drag(user, event) { event.dataTransfer.setData("User", user.id); } function allowDrop(event) { event.preventDefault(); } function drop(target, event) { event.preventDefault(); event.dataTransfer.effectAllowed = 'all'; var data=event.dataTransfer.getData("User"); document.getElementById(data).appendChild(target); target.parentNode.insertBefore(document.getElementById(data), target); }
JavaScript
function confirmFields(field1, field2) { var text1 = document.getElementById(field1).innerHTML; var text2 = document.getElementById(field2).innerHTML; if (text1 == text2)) return true; return false; }
JavaScript
var xhr; var cacheable = new Array("home:index","users:index", "chat:index"); self.onmessage = function m (e) { for (var i = 0;i < cacheable.length; i++) { //Check if page_action is already in ajax_cache xhr = new XMLHttpRequest(); var split = cacheable[i].split(':'); var url = "../router.php?controller=" + split[0] + "&action=" + split[1]; xhr.open('POST', url, false); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { self.postMessage({page_action: cacheable[i], content: xhr.responseText}); } }; xhr.send(); } //Update cache every minute self.setInterval(m, 10000); }
JavaScript
#pragma strict var target : GameObject; function Start() { //Colocar o jogador como alvo para ser perseguido if(target == null) { target = GameObject.FindGameObjectWithTag("Player"); print ("Player capturado pela camera com sucesso!"); } else { print ("Jogador nao encontrado"); } } function Update() { //transform.position.y = target.transform.position.y; transform.position.x = target.transform.position.x; }
JavaScript
/** * dat.globe Javascript WebGL Globe Toolkit * http://dataarts.github.com/dat.globe * * Copyright 2011 Data Arts Team, Google Creative Lab * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 */ var DAT = DAT || {}; DAT.Globe = function(container, colorFn) { colorFn = colorFn || function(x) { var c = new THREE.Color(); c.setHSV( ( 0.6 - ( x * 0.5 ) ), 1.0, 1.0 ); return c; }; var Shaders = { 'earth' : { uniforms: { 'texture': { type: 't', value: 0, texture: null } }, vertexShader: [ 'varying vec3 vNormal;', 'varying vec2 vUv;', 'void main() {', 'gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', 'vNormal = normalize( normalMatrix * normal );', 'vUv = uv;', '}' ].join('\n'), fragmentShader: [ 'uniform sampler2D texture;', 'varying vec3 vNormal;', 'varying vec2 vUv;', 'void main() {', 'vec3 diffuse = texture2D( texture, vUv ).xyz;', 'float intensity = 1.05 - dot( vNormal, vec3( 0.0, 0.0, 1.0 ) );', 'vec3 atmosphere = vec3( 1.0, 1.0, 1.0 ) * pow( intensity, 3.0 );', 'gl_FragColor = vec4( diffuse + atmosphere, 1.0 );', '}' ].join('\n') }, 'atmosphere' : { uniforms: {}, vertexShader: [ 'varying vec3 vNormal;', 'void main() {', 'vNormal = normalize( normalMatrix * normal );', 'gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}' ].join('\n'), fragmentShader: [ 'varying vec3 vNormal;', 'void main() {', 'float intensity = pow( 0.8 - dot( vNormal, vec3( 0, 0, 1.0 ) ), 12.0 );', 'gl_FragColor = vec4( 1.0, 1.0, 1.0, 1.0 ) * intensity;', '}' ].join('\n') } }; var camera, scene, sceneAtmosphere, renderer, w, h; var vector, mesh, atmosphere, point; var overRenderer; var imgDir = '/globe/'; var curZoomSpeed = 0; var zoomSpeed = 50; var mouse = { x: 0, y: 0 }, mouseOnDown = { x: 0, y: 0 }; var rotation = { x: 0, y: 0 }, target = { x: Math.PI*3/2, y: Math.PI / 6.0 }, targetOnDown = { x: 0, y: 0 }; var distance = 100000, distanceTarget = 100000; var padding = 40; var PI_HALF = Math.PI / 2; function init() { container.style.color = '#fff'; container.style.font = '13px/20px Arial, sans-serif'; var shader, uniforms, material; w = container.offsetWidth || window.innerWidth; h = container.offsetHeight || window.innerHeight; camera = new THREE.Camera( 30, w / h, 1, 10000); camera.position.z = distance; vector = new THREE.Vector3(); scene = new THREE.Scene(); sceneAtmosphere = new THREE.Scene(); var geometry = new THREE.Sphere(200, 40, 30); shader = Shaders['earth']; uniforms = THREE.UniformsUtils.clone(shader.uniforms); uniforms['texture'].texture = THREE.ImageUtils.loadTexture(imgDir+'world' + '.jpg'); material = new THREE.MeshShaderMaterial({ uniforms: uniforms, vertexShader: shader.vertexShader, fragmentShader: shader.fragmentShader }); mesh = new THREE.Mesh(geometry, material); mesh.matrixAutoUpdate = false; scene.addObject(mesh); shader = Shaders['atmosphere']; uniforms = THREE.UniformsUtils.clone(shader.uniforms); material = new THREE.MeshShaderMaterial({ uniforms: uniforms, vertexShader: shader.vertexShader, fragmentShader: shader.fragmentShader }); mesh = new THREE.Mesh(geometry, material); mesh.scale.x = mesh.scale.y = mesh.scale.z = 1.1; mesh.flipSided = true; mesh.matrixAutoUpdate = false; mesh.updateMatrix(); sceneAtmosphere.addObject(mesh); geometry = new THREE.Cube(0.75, 0.75, 1, 1, 1, 1, null, false, { px: true, nx: true, py: true, ny: true, pz: false, nz: true}); for (var i = 0; i < geometry.vertices.length; i++) { var vertex = geometry.vertices[i]; vertex.position.z += 0.5; } point = new THREE.Mesh(geometry); renderer = new THREE.WebGLRenderer({antialias: true}); renderer.autoClear = false; renderer.setClearColorHex(0x000000, 0.0); renderer.setSize(w, h); renderer.domElement.style.position = 'absolute'; container.appendChild(renderer.domElement); container.addEventListener('mousedown', onMouseDown, false); container.addEventListener('mousewheel', onMouseWheel, false); document.addEventListener('keydown', onDocumentKeyDown, false); window.addEventListener('resize', onWindowResize, false); container.addEventListener('mouseover', function() { overRenderer = true; }, false); container.addEventListener('mouseout', function() { overRenderer = false; }, false); } addData = function(data, opts) { var lat, lng, size, color, i, step, colorFnWrapper; opts.animated = opts.animated || false; this.is_animated = opts.animated; opts.format = opts.format || 'magnitude'; // other option is 'legend' console.log(opts.format); if (opts.format === 'magnitude') { step = 3; colorFnWrapper = function(data, i) { return colorFn(data[i+2]); } } else if (opts.format === 'legend') { step = 4; colorFnWrapper = function(data, i) { return colorFn(data[i+3]); } } else { throw('error: format not supported: '+opts.format); } if (opts.animated) { if (this._baseGeometry === undefined) { this._baseGeometry = new THREE.Geometry(); for (i = 0; i < data.length; i += step) { lat = data[i]; lng = data[i + 1]; // size = data[i + 2]; color = colorFnWrapper(data,i); size = 0; addPoint(lat, lng, size, color, this._baseGeometry); } } if(this._morphTargetId === undefined) { this._morphTargetId = 0; } else { this._morphTargetId += 1; } opts.name = opts.name || 'morphTarget'+this._morphTargetId; } var subgeo = new THREE.Geometry(); for (i = 0; i < data.length; i += step) { lat = data[i]; lng = data[i + 1]; color = colorFnWrapper(data,i); size = data[i + 2]; size = size*200; addPoint(lat, lng, size, color, subgeo); } if (opts.animated) { this._baseGeometry.morphTargets.push({'name': opts.name, vertices: subgeo.vertices}); } else { this._baseGeometry = subgeo; } }; function createPoints() { if (this._baseGeometry !== undefined) { if (this.is_animated === false) { this.points = new THREE.Mesh(this._baseGeometry, new THREE.MeshBasicMaterial({ color: 0xffffff, vertexColors: THREE.FaceColors, morphTargets: false })); } else { if (this._baseGeometry.morphTargets.length < 8) { console.log('t l',this._baseGeometry.morphTargets.length); var padding = 8-this._baseGeometry.morphTargets.length; console.log('padding', padding); for(var i=0; i<=padding; i++) { console.log('padding',i); this._baseGeometry.morphTargets.push({'name': 'morphPadding'+i, vertices: this._baseGeometry.vertices}); } } this.points = new THREE.Mesh(this._baseGeometry, new THREE.MeshBasicMaterial({ color: 0xffffff, vertexColors: THREE.FaceColors, morphTargets: true })); } scene.addObject(this.points); } } function addPoint(lat, lng, size, color, subgeo) { var phi = (90 - lat) * Math.PI / 180; var theta = (180 - lng) * Math.PI / 180; point.position.x = 200 * Math.sin(phi) * Math.cos(theta); point.position.y = 200 * Math.cos(phi); point.position.z = 200 * Math.sin(phi) * Math.sin(theta); point.lookAt(mesh.position); point.scale.z = -size; point.updateMatrix(); var i; for (i = 0; i < point.geometry.faces.length; i++) { point.geometry.faces[i].color = color; } GeometryUtils.merge(subgeo, point); } function onMouseDown(event) { event.preventDefault(); container.addEventListener('mousemove', onMouseMove, false); container.addEventListener('mouseup', onMouseUp, false); container.addEventListener('mouseout', onMouseOut, false); mouseOnDown.x = - event.clientX; mouseOnDown.y = event.clientY; targetOnDown.x = target.x; targetOnDown.y = target.y; container.style.cursor = 'move'; } function onMouseMove(event) { mouse.x = - event.clientX; mouse.y = event.clientY; var zoomDamp = distance/1000; target.x = targetOnDown.x + (mouse.x - mouseOnDown.x) * 0.005 * zoomDamp; target.y = targetOnDown.y + (mouse.y - mouseOnDown.y) * 0.005 * zoomDamp; target.y = target.y > PI_HALF ? PI_HALF : target.y; target.y = target.y < - PI_HALF ? - PI_HALF : target.y; } function onMouseUp(event) { container.removeEventListener('mousemove', onMouseMove, false); container.removeEventListener('mouseup', onMouseUp, false); container.removeEventListener('mouseout', onMouseOut, false); container.style.cursor = 'auto'; } function onMouseOut(event) { container.removeEventListener('mousemove', onMouseMove, false); container.removeEventListener('mouseup', onMouseUp, false); container.removeEventListener('mouseout', onMouseOut, false); } function onMouseWheel(event) { event.preventDefault(); if (overRenderer) { zoom(event.wheelDeltaY * 0.3); } return false; } function onDocumentKeyDown(event) { switch (event.keyCode) { case 38: zoom(100); event.preventDefault(); break; case 40: zoom(-100); event.preventDefault(); break; } } function onWindowResize( event ) { console.log('resize'); camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize( window.innerWidth, window.innerHeight ); } function zoom(delta) { distanceTarget -= delta; distanceTarget = distanceTarget > 1000 ? 1000 : distanceTarget; distanceTarget = distanceTarget < 350 ? 350 : distanceTarget; } function animate() { requestAnimationFrame(animate); render(); } function render() { zoom(curZoomSpeed); rotation.x += (target.x - rotation.x) * 0.1; rotation.y += (target.y - rotation.y) * 0.1; distance += (distanceTarget - distance) * 0.3; camera.position.x = distance * Math.sin(rotation.x) * Math.cos(rotation.y); camera.position.y = distance * Math.sin(rotation.y); camera.position.z = distance * Math.cos(rotation.x) * Math.cos(rotation.y); vector.copy(camera.position); renderer.clear(); renderer.render(scene, camera); renderer.render(sceneAtmosphere, camera); } init(); this.animate = animate; this.__defineGetter__('time', function() { return this._time || 0; }); this.__defineSetter__('time', function(t) { var validMorphs = []; var morphDict = this.points.morphTargetDictionary; for(var k in morphDict) { if(k.indexOf('morphPadding') < 0) { validMorphs.push(morphDict[k]); } } validMorphs.sort(); var l = validMorphs.length-1; var scaledt = t*l+1; var index = Math.floor(scaledt); for (i=0;i<validMorphs.length;i++) { this.points.morphTargetInfluences[validMorphs[i]] = 0; } var lastIndex = index - 1; var leftover = scaledt - index; if (lastIndex >= 0) { this.points.morphTargetInfluences[lastIndex] = 1 - leftover; } this.points.morphTargetInfluences[index] = leftover; this._time = t; }); this.addData = addData; this.createPoints = createPoints; this.renderer = renderer; this.scene = scene; return this; };
JavaScript
$().ready(function() { albumView.galeryInit(); }); function albumView(){}; /** * Метод вызывается при загрузке страницы, чтобы инициировать галерею */ albumView.galeryInit = function(){ //Создаем панель $('#photosPreviewIn').jScrollPane({scrollbarWidth:10, showArrows:true, scrollbarMargin:0, arrowSize:9}); //Определяем текущий основной элемент var intIdMainPhoto = $('#mainPhotoBlock img.selected').attr('id').substr(10); //Подсвечиваем нужное превью $('#preview_' + intIdMainPhoto).parent().removeClass('preview').addClass('previewSel'); //Назначаем события клика по превью $('img.preview').each(function (i) { $(this).click(function () { albumView.previewClick(this); } ); }); //Подгружаем ближайших потомков var currentPreview = $('#preview_' + intIdMainPhoto); for(var i = 0; i < 3; i++) { currentPreview = currentPreview.parent().next().find('img'); if(currentPreview.size) { var currentPreviewId = $(currentPreview).attr('id').substr(8); albumView.addMainPhotoHtml(currentPreview, currentPreviewId); } else break; } }; /** * Метод обрабатывает клик по превью * @param {Object} elPreview */ albumView.addMainPhotoHtml = function(elPreview, idPhoto){ // Можно в td еще background добавить var previewSrc = $(elPreview).attr('src'); var folder = previewSrc.substring(0, previewSrc.lastIndexOf('/') + 1); var src = folder + $(elPreview).attr('big'); var htmlToAppend = '<table class="mainPhoto" cellpadding="0" cellspacing="0"><tbody><tr><td class="mainPhotoCell">'; htmlToAppend += '<img src="' + src + '" id="mainPhoto_' + idPhoto + '" alt="">'; htmlToAppend += '</td></tr></tbody></table>'; $('#mainPhotoBlock').append(htmlToAppend); }; /** * Метод обрабатывает клик по превью * @param {Object} elPreview */ albumView.previewClick = function(elPreview){ var intIdNewPhoto = $(elPreview).attr('id').substr(8); var indIdPrevPhoto = $('#photosPreviewIn .previewSel img').attr('id').substr(8); $('#photosPreviewIn .previewSel').removeClass('previewSel').addClass('preview'); $(elPreview).parent().removeClass('preview').addClass('previewSel'); $('#mainPhoto_' + indIdPrevPhoto).fadeOut(2000); if($('#mainPhoto_' + intIdNewPhoto).size()) { $('#mainPhoto_' + intIdNewPhoto).fadeIn(2000/*, function(){$(this).addClass('selected'); }*/); } else { albumView.addMainPhotoHtml(elPreview, intIdNewPhoto); setTimeout(function(){ $('#mainPhoto_' + intIdNewPhoto).fadeIn(2000); }, 50); } }; /** * Метод переключает галерею на следующее фото */ albumView.showNextPhoto = function(){ var nextPreviewImage = $('#photosPreviewIn .previewSel').next().find('img'); if($(nextPreviewImage).size) albumView.previewClick(nextPreviewImage); }; /** * Метод переключает галерею на предыдущее фото */ albumView.showPrevPhoto = function(){ var prevPreviewImage = $('#photosPreviewIn .previewSel').prev().find('img'); if($(prevPreviewImage).size) albumView.previewClick(prevPreviewImage); };
JavaScript
function md5 (str) { // http://kevin.vanzonneveld.net // + original by: Webtoolkit.info (http://www.webtoolkit.info/) // + namespaced by: Michael White (http://getsprink.com) // + tweaked by: Jack // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // - depends on: utf8_encode // * example 1: md5('Kevin van Zonneveld'); // * returns 1: '6e658d4bfcb59cc13f96c14450ac40b9' var xl; var rotateLeft = function (lValue, iShiftBits) { return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits)); }; var addUnsigned = function (lX, lY) { var lX4, lY4, lX8, lY8, lResult; lX8 = (lX & 0x80000000); lY8 = (lY & 0x80000000); lX4 = (lX & 0x40000000); lY4 = (lY & 0x40000000); lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF); if (lX4 & lY4) { return (lResult ^ 0x80000000 ^ lX8 ^ lY8); } if (lX4 | lY4) { if (lResult & 0x40000000) { return (lResult ^ 0xC0000000 ^ lX8 ^ lY8); } else { return (lResult ^ 0x40000000 ^ lX8 ^ lY8); } } else { return (lResult ^ lX8 ^ lY8); } }; var _F = function (x, y, z) { return (x & y) | ((~x) & z); }; var _G = function (x, y, z) { return (x & z) | (y & (~z)); }; var _H = function (x, y, z) { return (x ^ y ^ z); }; var _I = function (x, y, z) { return (y ^ (x | (~z))); }; var _FF = function (a, b, c, d, x, s, ac) { a = addUnsigned(a, addUnsigned(addUnsigned(_F(b, c, d), x), ac)); return addUnsigned(rotateLeft(a, s), b); }; var _GG = function (a, b, c, d, x, s, ac) { a = addUnsigned(a, addUnsigned(addUnsigned(_G(b, c, d), x), ac)); return addUnsigned(rotateLeft(a, s), b); }; var _HH = function (a, b, c, d, x, s, ac) { a = addUnsigned(a, addUnsigned(addUnsigned(_H(b, c, d), x), ac)); return addUnsigned(rotateLeft(a, s), b); }; var _II = function (a, b, c, d, x, s, ac) { a = addUnsigned(a, addUnsigned(addUnsigned(_I(b, c, d), x), ac)); return addUnsigned(rotateLeft(a, s), b); }; var convertToWordArray = function (str) { var lWordCount; var lMessageLength = str.length; var lNumberOfWords_temp1 = lMessageLength + 8; var lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64; var lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16; var lWordArray = new Array(lNumberOfWords - 1); var lBytePosition = 0; var lByteCount = 0; while (lByteCount < lMessageLength) { lWordCount = (lByteCount - (lByteCount % 4)) / 4; lBytePosition = (lByteCount % 4) * 8; lWordArray[lWordCount] = (lWordArray[lWordCount] | (str.charCodeAt(lByteCount) << lBytePosition)); lByteCount++; } lWordCount = (lByteCount - (lByteCount % 4)) / 4; lBytePosition = (lByteCount % 4) * 8; lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition); lWordArray[lNumberOfWords - 2] = lMessageLength << 3; lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29; return lWordArray; }; var wordToHex = function (lValue) { var wordToHexValue = "", wordToHexValue_temp = "", lByte, lCount; for (lCount = 0; lCount <= 3; lCount++) { lByte = (lValue >>> (lCount * 8)) & 255; wordToHexValue_temp = "0" + lByte.toString(16); wordToHexValue = wordToHexValue + wordToHexValue_temp.substr(wordToHexValue_temp.length - 2, 2); } return wordToHexValue; }; var x = [], k, AA, BB, CC, DD, a, b, c, d, S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20, S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21; str = this.utf8_encode(str); x = convertToWordArray(str); a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476; xl = x.length; for (k = 0; k < xl; k += 16) { AA = a; BB = b; CC = c; DD = d; a = _FF(a, b, c, d, x[k + 0], S11, 0xD76AA478); d = _FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756); c = _FF(c, d, a, b, x[k + 2], S13, 0x242070DB); b = _FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE); a = _FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF); d = _FF(d, a, b, c, x[k + 5], S12, 0x4787C62A); c = _FF(c, d, a, b, x[k + 6], S13, 0xA8304613); b = _FF(b, c, d, a, x[k + 7], S14, 0xFD469501); a = _FF(a, b, c, d, x[k + 8], S11, 0x698098D8); d = _FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF); c = _FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1); b = _FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE); a = _FF(a, b, c, d, x[k + 12], S11, 0x6B901122); d = _FF(d, a, b, c, x[k + 13], S12, 0xFD987193); c = _FF(c, d, a, b, x[k + 14], S13, 0xA679438E); b = _FF(b, c, d, a, x[k + 15], S14, 0x49B40821); a = _GG(a, b, c, d, x[k + 1], S21, 0xF61E2562); d = _GG(d, a, b, c, x[k + 6], S22, 0xC040B340); c = _GG(c, d, a, b, x[k + 11], S23, 0x265E5A51); b = _GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA); a = _GG(a, b, c, d, x[k + 5], S21, 0xD62F105D); d = _GG(d, a, b, c, x[k + 10], S22, 0x2441453); c = _GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681); b = _GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8); a = _GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6); d = _GG(d, a, b, c, x[k + 14], S22, 0xC33707D6); c = _GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87); b = _GG(b, c, d, a, x[k + 8], S24, 0x455A14ED); a = _GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905); d = _GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8); c = _GG(c, d, a, b, x[k + 7], S23, 0x676F02D9); b = _GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A); a = _HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942); d = _HH(d, a, b, c, x[k + 8], S32, 0x8771F681); c = _HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122); b = _HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C); a = _HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44); d = _HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9); c = _HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60); b = _HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70); a = _HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6); d = _HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA); c = _HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085); b = _HH(b, c, d, a, x[k + 6], S34, 0x4881D05); a = _HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039); d = _HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5); c = _HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8); b = _HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665); a = _II(a, b, c, d, x[k + 0], S41, 0xF4292244); d = _II(d, a, b, c, x[k + 7], S42, 0x432AFF97); c = _II(c, d, a, b, x[k + 14], S43, 0xAB9423A7); b = _II(b, c, d, a, x[k + 5], S44, 0xFC93A039); a = _II(a, b, c, d, x[k + 12], S41, 0x655B59C3); d = _II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92); c = _II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D); b = _II(b, c, d, a, x[k + 1], S44, 0x85845DD1); a = _II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F); d = _II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0); c = _II(c, d, a, b, x[k + 6], S43, 0xA3014314); b = _II(b, c, d, a, x[k + 13], S44, 0x4E0811A1); a = _II(a, b, c, d, x[k + 4], S41, 0xF7537E82); d = _II(d, a, b, c, x[k + 11], S42, 0xBD3AF235); c = _II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB); b = _II(b, c, d, a, x[k + 9], S44, 0xEB86D391); a = addUnsigned(a, AA); b = addUnsigned(b, BB); c = addUnsigned(c, CC); d = addUnsigned(d, DD); } var temp = wordToHex(a) + wordToHex(b) + wordToHex(c) + wordToHex(d); return temp.toLowerCase(); } function utf8_encode (argString) { // http://kevin.vanzonneveld.net // + original by: Webtoolkit.info (http://www.webtoolkit.info/) // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: sowberry // + tweaked by: Jack // + bugfixed by: Onno Marsman // + improved by: Yves Sucaet // + bugfixed by: Onno Marsman // + bugfixed by: Ulrich // + bugfixed by: Rafal Kukawski // + improved by: kirilloid // * example 1: utf8_encode('Kevin van Zonneveld'); // * returns 1: 'Kevin van Zonneveld' if (argString === null || typeof argString === "undefined") { return ""; } var string = (argString + ''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n"); var utftext = '', start, end, stringl = 0; start = end = 0; stringl = string.length; for (var n = 0; n < stringl; n++) { var c1 = string.charCodeAt(n); var enc = null; if (c1 < 128) { end++; } else if (c1 > 127 && c1 < 2048) { enc = String.fromCharCode((c1 >> 6) | 192, (c1 & 63) | 128); } else { enc = String.fromCharCode((c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128); } if (enc !== null) { if (end > start) { utftext += string.slice(start, end); } utftext += enc; start = end = n + 1; } } if (end > start) { utftext += string.slice(start, stringl); } return utftext; } function urlencode (str) { // http://kevin.vanzonneveld.net // + original by: Philip Peterson // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: AJ // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: travc // + input by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Lars Fischer // + input by: Ratheous // + reimplemented by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Joris // + reimplemented by: Brett Zamir (http://brett-zamir.me) // % note 1: This reflects PHP 5.3/6.0+ behavior // % note 2: Please be aware that this function expects to encode into UTF-8 encoded strings, as found on // % note 2: pages served as UTF-8 // * example 1: urlencode('Kevin van Zonneveld!'); // * returns 1: 'Kevin+van+Zonneveld%21' // * example 2: urlencode('http://kevin.vanzonneveld.net/'); // * returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F' // * example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'); // * returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a' str = (str + '').toString(); // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following. return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28'). replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+'); } function urldecode (str) { // http://kevin.vanzonneveld.net // + original by: Philip Peterson // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: AJ // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Brett Zamir (http://brett-zamir.me) // + input by: travc // + input by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Lars Fischer // + input by: Ratheous // + improved by: Orlando // + reimplemented by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Rob // + input by: e-mike // + improved by: Brett Zamir (http://brett-zamir.me) // % note 1: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/ // % note 2: Please be aware that this function expects to decode from UTF-8 encoded strings, as found on // % note 2: pages served as UTF-8 // * example 1: urldecode('Kevin+van+Zonneveld%21'); // * returns 1: 'Kevin van Zonneveld!' // * example 2: urldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F'); // * returns 2: 'http://kevin.vanzonneveld.net/' // * example 3: urldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'); // * returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a' return decodeURIComponent((str + '').replace(/\+/g, '%20')); } function http_build_query (formdata, numeric_prefix, arg_separator) { // http://kevin.vanzonneveld.net // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Legaev Andrey // + improved by: Michael White (http://getsprink.com) // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Brett Zamir (http://brett-zamir.me) // + revised by: stag019 // + input by: Dreamer // + bugfixed by: Brett Zamir (http://brett-zamir.me) // - depends on: urlencode // * example 1: http_build_query({foo: 'bar', php: 'hypertext processor', baz: 'boom', cow: 'milk'}, '', '&amp;'); // * returns 1: 'foo=bar&amp;php=hypertext+processor&amp;baz=boom&amp;cow=milk' // * example 2: http_build_query({'php': 'hypertext processor', 0: 'foo', 1: 'bar', 2: 'baz', 3: 'boom', 'cow': 'milk'}, 'myvar_'); // * returns 2: 'php=hypertext+processor&myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&cow=milk' var value, key, tmp = [], that = this; var _http_build_query_helper = function (key, val, arg_separator) { var k, tmp = []; if (val === true) { val = "1"; } else if (val === false) { val = "0"; } if (val !== null && typeof(val) === "object") { for (k in val) { if (val[k] !== null) { tmp.push(_http_build_query_helper(key + "[" + k + "]", val[k], arg_separator)); } } return tmp.join(arg_separator); } else if (typeof(val) !== "function") { return that.urlencode(key) + "=" + that.urlencode(val); } else { throw new Error('There was an error processing for http_build_query().'); } }; if (!arg_separator) { arg_separator = "&"; } for (key in formdata) { value = formdata[key]; if (numeric_prefix && !isNaN(key)) { key = String(numeric_prefix) + key; } tmp.push(_http_build_query_helper(key, value, arg_separator)); } return tmp.join(arg_separator); } function count (mixed_var, mode) { // http://kevin.vanzonneveld.net // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: Waldo Malqui Silva // + bugfixed by: Soren Hansen // + input by: merabi // + improved by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Olivier Louvignes (http://mg-crea.com/) // * example 1: count([[0,0],[0,-4]], 'COUNT_RECURSIVE'); // * returns 1: 6 // * example 2: count({'one' : [1,2,3,4,5]}, 'COUNT_RECURSIVE'); // * returns 2: 6 var key, cnt = 0; if (mixed_var === null || typeof mixed_var === 'undefined') { return 0; } else if (mixed_var.constructor !== Array && mixed_var.constructor !== Object) { return 1; } if (mode === 'COUNT_RECURSIVE') { mode = 1; } if (mode != 1) { mode = 0; } for (key in mixed_var) { if (mixed_var.hasOwnProperty(key)) { cnt++; if (mode == 1 && mixed_var[key] && (mixed_var[key].constructor === Array || mixed_var[key].constructor === Object)) { cnt += this.count(mixed_var[key], 1); } } } return cnt; } function array_keys (input, search_value, argStrict) { // http://kevin.vanzonneveld.net // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: jd // + improved by: Brett Zamir (http://brett-zamir.me) // + input by: P // + bugfixed by: Brett Zamir (http://brett-zamir.me) // * example 1: array_keys( {firstname: 'Kevin', surname: 'van Zonneveld'} ); // * returns 1: {0: 'firstname', 1: 'surname'} var search = typeof search_value !== 'undefined', tmp_arr = [], strict = !!argStrict, include = true, key = ''; if (input && typeof input === 'object' && input.change_key_case) { // Duck-type check for our own array()-created PHPJS_Array return input.keys(search_value, argStrict); } for (key in input) { if (input.hasOwnProperty(key)) { include = true; if (search) { if (strict && input[key] !== search_value) { include = false; } else if (input[key] != search_value) { include = false; } } if (include) { tmp_arr[tmp_arr.length] = key; } } } return tmp_arr; } function uasort (inputArr, sorter) { // http://kevin.vanzonneveld.net // + original by: Brett Zamir (http://brett-zamir.me) // + improved by: Brett Zamir (http://brett-zamir.me) // + improved by: Theriault // % note 1: This function deviates from PHP in returning a copy of the array instead // % note 1: of acting by reference and returning true; this was necessary because // % note 1: IE does not allow deleting and re-adding of properties without caching // % note 1: of property position; you can set the ini of "phpjs.strictForIn" to true to // % note 1: get the PHP behavior, but use this only if you are in an environment // % note 1: such as Firefox extensions where for-in iteration order is fixed and true // % note 1: property deletion is supported. Note that we intend to implement the PHP // % note 1: behavior by default if IE ever does allow it; only gives shallow copy since // % note 1: is by reference in PHP anyways // * example 1: fruits = {d: 'lemon', a: 'orange', b: 'banana', c: 'apple'}; // * example 1: fruits = uasort(fruits, function (a, b) { if (a > b) {return 1;}if (a < b) {return -1;} return 0;}); // * results 1: fruits == {c: 'apple', b: 'banana', d: 'lemon', a: 'orange'} var valArr = [], tempKeyVal, tempValue, ret, k = '', i = 0, strictForIn = false, populateArr = {}; if (typeof sorter === 'string') { sorter = this[sorter]; } else if (Object.prototype.toString.call(sorter) === '[object Array]') { sorter = this[sorter[0]][sorter[1]]; } // BEGIN REDUNDANT this.php_js = this.php_js || {}; this.php_js.ini = this.php_js.ini || {}; // END REDUNDANT strictForIn = this.php_js.ini['phpjs.strictForIn'] && this.php_js.ini['phpjs.strictForIn'].local_value && this.php_js.ini['phpjs.strictForIn'].local_value !== 'off'; populateArr = strictForIn ? inputArr : populateArr; for (k in inputArr) { // Get key and value arrays if (inputArr.hasOwnProperty(k)) { valArr.push([k, inputArr[k]]); if (strictForIn) { delete inputArr[k]; } } } valArr.sort(function (a, b) { return sorter(a[1], b[1]); }); for (i = 0; i < valArr.length; i++) { // Repopulate the old array populateArr[valArr[i][0]] = valArr[i][1]; } return strictForIn || populateArr; } function i18n_loc_set_default (name) { // http://kevin.vanzonneveld.net // + original by: Brett Zamir (http://brett-zamir.me) // % note 1: Renamed in PHP6 from locale_set_default(). Not listed yet at php.net // % note 2: List of locales at http://demo.icu-project.org/icu-bin/locexp (use for implementing other locales here) // % note 3: To be usable with sort() if it is passed the SORT_LOCALE_STRING sorting flag: http://php.net/manual/en/function.sort.php // * example 1: i18n_loc_set_default('pt_PT'); // * returns 1: true // BEGIN REDUNDANT this.php_js = this.php_js || {}; // END REDUNDANT this.php_js.i18nLocales = { en_US_POSIX: { sorting: function (str1, str2) { // Fix: This one taken from strcmp, but need for other locales; we don't use localeCompare since its locale is not settable return (str1 == str2) ? 0 : ((str1 > str2) ? 1 : -1); } } }; this.php_js.i18nLocale = name; return true; } function i18n_loc_get_default () { // http://kevin.vanzonneveld.net // + original by: Brett Zamir (http://brett-zamir.me) // % note 1: Renamed in PHP6 from locale_get_default(). Not listed yet at php.net // % note 2: List of locales at http://demo.icu-project.org/icu-bin/locexp // % note 3: To be usable with sort() if it is passed the SORT_LOCALE_STRING sorting flag: http://php.net/manual/en/function.sort.php // - depends on: i18n_loc_set_default // * example 1: i18n_loc_get_default(); // * returns 1: 'en_US_POSIX' // BEGIN REDUNDANT this.php_js = this.php_js || {}; // END REDUNDANT return this.php_js.i18nLocale || (i18n_loc_set_default('en_US_POSIX')); // Ensure defaults are set up } function sort (inputArr, sort_flags) { // http://kevin.vanzonneveld.net // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + revised by: Brett Zamir (http://brett-zamir.me) // + improved by: Brett Zamir (http://brett-zamir.me) // % note 1: SORT_STRING (as well as natsort and natcasesort) might also be // % note 1: integrated into all of these functions by adapting the code at // % note 1: http://sourcefrog.net/projects/natsort/natcompare.js // % note 2: This function deviates from PHP in returning a copy of the array instead // % note 2: of acting by reference and returning true; this was necessary because // % note 2: IE does not allow deleting and re-adding of properties without caching // % note 2: of property position; you can set the ini of "phpjs.strictForIn" to true to // % note 2: get the PHP behavior, but use this only if you are in an environment // % note 2: such as Firefox extensions where for-in iteration order is fixed and true // % note 2: property deletion is supported. Note that we intend to implement the PHP // % note 2: behavior by default if IE ever does allow it; only gives shallow copy since // % note 2: is by reference in PHP anyways // % note 3: Since JS objects' keys are always strings, and (the // % note 3: default) SORT_REGULAR flag distinguishes by key type, // % note 3: if the content is a numeric string, we treat the // % note 3: "original type" as numeric. // - depends on: i18n_loc_get_default // * example 1: sort(['Kevin', 'van', 'Zonneveld']); // * returns 1: ['Kevin', 'Zonneveld', 'van'] // * example 2: ini_set('phpjs.strictForIn', true); // * example 2: fruits = {d: 'lemon', a: 'orange', b: 'banana', c: 'apple'}; // * example 2: sort(fruits); // * results 2: fruits == {0: 'apple', 1: 'banana', 2: 'lemon', 3: 'orange'} // * returns 2: true var valArr = [], keyArr = [], k = '', i = 0, sorter = false, that = this, strictForIn = false, populateArr = []; switch (sort_flags) { case 'SORT_STRING': // compare items as strings sorter = function (a, b) { return that.strnatcmp(a, b); }; break; case 'SORT_LOCALE_STRING': // compare items as strings, based on the current locale (set with i18n_loc_set_default() as of PHP6) var loc = this.i18n_loc_get_default(); sorter = this.php_js.i18nLocales[loc].sorting; break; case 'SORT_NUMERIC': // compare items numerically sorter = function (a, b) { return (a - b); }; break; case 'SORT_REGULAR': // compare items normally (don't change types) default: sorter = function (a, b) { var aFloat = parseFloat(a), bFloat = parseFloat(b), aNumeric = aFloat + '' === a, bNumeric = bFloat + '' === b; if (aNumeric && bNumeric) { return aFloat > bFloat ? 1 : aFloat < bFloat ? -1 : 0; } else if (aNumeric && !bNumeric) { return 1; } else if (!aNumeric && bNumeric) { return -1; } return a > b ? 1 : a < b ? -1 : 0; }; break; } // BEGIN REDUNDANT this.php_js = this.php_js || {}; this.php_js.ini = this.php_js.ini || {}; // END REDUNDANT strictForIn = this.php_js.ini['phpjs.strictForIn'] && this.php_js.ini['phpjs.strictForIn'].local_value && this.php_js.ini['phpjs.strictForIn'].local_value !== 'off'; populateArr = strictForIn ? inputArr : populateArr; for (k in inputArr) { // Get key and value arrays if (inputArr.hasOwnProperty(k)) { valArr.push(inputArr[k]); if (strictForIn) { delete inputArr[k]; } } } valArr.sort(sorter); for (i = 0; i < valArr.length; i++) { // Repopulate the old array populateArr[i] = valArr[i]; } return strictForIn || populateArr; } function array_unique (inputArr) { // http://kevin.vanzonneveld.net // + original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com) // + input by: duncan // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfixed by: Nate // + input by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Michael Grier // + bugfixed by: Brett Zamir (http://brett-zamir.me) // % note 1: The second argument, sort_flags is not implemented; // % note 1: also should be sorted (asort?) first according to docs // * example 1: array_unique(['Kevin','Kevin','van','Zonneveld','Kevin']); // * returns 1: {0: 'Kevin', 2: 'van', 3: 'Zonneveld'} // * example 2: array_unique({'a': 'green', 0: 'red', 'b': 'green', 1: 'blue', 2: 'red'}); // * returns 2: {a: 'green', 0: 'red', 1: 'blue'} var key = '', tmp_arr2 = {}, val = ''; var __array_search = function (needle, haystack) { var fkey = ''; for (fkey in haystack) { if (haystack.hasOwnProperty(fkey)) { if ((haystack[fkey] + '') === (needle + '')) { return fkey; } } } return false; }; for (key in inputArr) { if (inputArr.hasOwnProperty(key)) { val = inputArr[key]; if (false === __array_search(val, tmp_arr2)) { tmp_arr2[key] = val; } } } return tmp_arr2; } function array_values (input) { // http://kevin.vanzonneveld.net // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Brett Zamir (http://brett-zamir.me) // * example 1: array_values( {firstname: 'Kevin', surname: 'van Zonneveld'} ); // * returns 1: {0: 'Kevin', 1: 'van Zonneveld'} var tmp_arr = [], key = ''; if (input && typeof input === 'object' && input.change_key_case) { // Duck-type check for our own array()-created PHPJS_Array return input.values(); } for (key in input) { tmp_arr[tmp_arr.length] = input[key]; } return tmp_arr; } function array_keys (input, search_value, argStrict) { // http://kevin.vanzonneveld.net // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: jd // + improved by: Brett Zamir (http://brett-zamir.me) // + input by: P // + bugfixed by: Brett Zamir (http://brett-zamir.me) // * example 1: array_keys( {firstname: 'Kevin', surname: 'van Zonneveld'} ); // * returns 1: {0: 'firstname', 1: 'surname'} var search = typeof search_value !== 'undefined', tmp_arr = [], strict = !!argStrict, include = true, key = ''; if (input && typeof input === 'object' && input.change_key_case) { // Duck-type check for our own array()-created PHPJS_Array return input.keys(search_value, argStrict); } for (key in input) { if (input.hasOwnProperty(key)) { include = true; if (search) { if (strict && input[key] !== search_value) { include = false; } else if (input[key] != search_value) { include = false; } } if (include) { tmp_arr[tmp_arr.length] = key; } } } return tmp_arr; } function number_format (number, decimals, dec_point, thousands_sep) { number = (number + '').replace(/[^0-9+\-Ee.]/g, ''); var n = !isFinite(+number) ? 0 : +number, prec = !isFinite(+decimals) ? 0 : Math.abs(decimals), sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep, dec = (typeof dec_point === 'undefined') ? '.' : dec_point, s = '', toFixedFix = function (n, prec) { var k = Math.pow(10, prec); return '' + Math.round(n * k) / k; }; // Fix for IE parseFloat(0.55).toFixed(0) = 0; s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.'); if (s[0].length > 3) { s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep); } if ((s[1] || '').length < prec) { s[1] = s[1] || ''; s[1] += new Array(prec - s[1].length + 1).join('0'); } return s.join(dec); } function trim (str, charlist) { // http://kevin.vanzonneveld.net // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: mdsjack (http://www.mdsjack.bo.it) // + improved by: Alexander Ermolaev (http://snippets.dzone.com/user/AlexanderErmolaev) // + input by: Erkekjetter // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: DxGx // + improved by: Steven Levithan (http://blog.stevenlevithan.com) // + tweaked by: Jack // + bugfixed by: Onno Marsman // * example 1: trim(' Kevin van Zonneveld '); // * returns 1: 'Kevin van Zonneveld' // * example 2: trim('Hello World', 'Hdle'); // * returns 2: 'o Wor' // * example 3: trim(16, 1); // * returns 3: 6 var whitespace, l = 0, i = 0; str += ''; if (!charlist) { // default list whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000"; } else { // preg_quote custom list charlist += ''; whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1'); } l = str.length; for (i = 0; i < l; i++) { if (whitespace.indexOf(str.charAt(i)) === -1) { str = str.substring(i); break; } } l = str.length; for (i = l - 1; i >= 0; i--) { if (whitespace.indexOf(str.charAt(i)) === -1) { str = str.substring(0, i + 1); break; } } return whitespace.indexOf(str.charAt(0)) === -1 ? str : ''; }
JavaScript
var App = $.extend(App,{}); var tmpl = {template:{}}; //АУТЕНТИФИКАЦИЯ auth = function(){}; auth.loggedIn = false; // По умолчанию пользователь не зарегистрирован (function(){ App.getTemplates = function() { if(arguments.length == 0) return false; $.each(arguments, function(i, el){ $.get(W_TMPL + el, function(data){ if($('templates', data).length == 0) return false; $('templates', data).children().each(function(){ tmpl.template[$(this).attr('name')] = $(this).text(); $.template($(this).attr('name'), tmpl.template[$(this).attr('name')]); }); }, 'xml'); }); }; // Навешиваем событие на выбор города $('#chooseCityButton').live('click', function(){ $('#chooseCityButton').popUpBox({width: 300, inlineId: 'chooseCityBlockOut', verticalPosition: 'bottom'}); //$('#chooseCityBlockOut').show(); return false; }); // Навешиваем события на аутентификации $('#signInButton, #signUpButton, #openSocial, #signInHeader, #signUpHeader, #openSocialHeader').live('click', function(){ auth.showAuthenticationBlock($(this).attr('id').replace('Button', '').replace('Header', '') + 'Block'); return false; }); })(); $().ready(function() { //alert(auth.loggedIn); }); // Отображение формы регистрации auth.showAuthenticationBlock = function (blockId) { if (!$('#authentication').length) { $('body').popUpBox({width: 600, html: '<div id="authenticationPopUp"></div>', modal: true, 'absCenter': true, 'verticalPosition': 'center'}); $.tmpl('auth.authentication').appendTo('#authenticationPopUp'); } $('#signInBlock, #signUpBlock, #openSocialBlock').not('#' + blockId).hide(); $('#' + blockId).show(); $('#signInHeader, #signUpHeader, #openSocialHeader').not('#' + blockId.replace('Block', 'Header')).removeClass('selected'); $('#' + blockId.replace('Block', 'Header')).addClass('selected'); }; // Отправка формы входа auth.signIn = function() { var url = W_AJAX + 'auth/sign_in/'; var params = { loginOrEMail: $('#signInLogin').val(), password: $('#signInPassword').val() }; $.post(url, params, function(objData) { console.log(objData); }, 'json' ); }; // Отправка формы регистрации auth.signUp = function() { var url = W_AJAX + 'auth/sign_up/'; var params = { login: $('#signUpLogin').val(), e_mail: $('#signUpEMail').val() }; $.post(url, params, function(objData) { console.log(objData); }, 'json' ); }; album = function(){}; /** * Инициализирует загрузчик фотографий */ album.initAlbumLoader = function(ajaxParameters) { var flashvars = { image_size: "1024", max_images: "50", upload_url: W_FULLPATH + "ajax/album/add_album_photo/", redirect_url: W_FULLPATH + 'album/', //post_uid: "29", post_album_id: ajaxParameters.albumId }; //$.extend(flashvars, ajaxParameters); //console.log(flashvars); var params = { menu: "false", scale: "noScale", allowFullscreen: "true", allowScriptAccess: "always", bgcolor: "#EEEEEE" }; var attributes = { id:"uploader" }; swfobject.embedSWF( W_SWF + "uploader.swf", "altContent", "600", "500", "9.0.0", W_SWF + "expressInstall.swf", flashvars, params, attributes ); }; /** * Проверяет, поддерживает ли браузер пользователя flash-версию загрузчика */ album.hasFlash = function () { var plugin; var version = 5; var flash = false; if (navigator.plugins) { if (navigator.plugins["Shockwave Flash"]) { plugin = navigator.plugins["Shockwave Flash"].description; flash = parseInt(plugin.indexOf('Flash') + 6) >= version; alert(flash); alert(plugin); } else { if ((navigator.userAgent.indexOf('MSIE') != -1) && (navigator.userAgent.indexOf('Win') != -1)) { var vb = '<script language="vbscript">\n' + 'if ScriptEngineMajorVersion >= 2 then\n' + ' on error resume next\n' + ' flash = IsObject(CreateObject(' + ' "ShockwaveFlash.ShockwaveFlash.' + version + '"))\n' + 'end if\n' + '<' + '/script>'; document.write(vb); } } } return flash; }; city = function() {};
JavaScript
$('.faqHeader').live('click', function() { $(this).parents('.oneFaq').find('.text').slideToggle("slow"); $(this).parents('.header').toggleClass('active'); return false; });
JavaScript