code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
(function( window, undefined ) { // Use the correct document accordingly with window argument (sandbox) var document = window.document; var jQuery = (function() { // Define a local copy of jQuery var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context ); }, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // A central reference to the root jQuery(document) rootjQuery, // A simple way to check for HTML strings or ID strings // (both of which we optimize for) quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/, // Is it a simple selector isSimple = /^.[^:#\[\.,]*$/, // Check if a string has a non-whitespace character in it rnotwhite = /\S/, rwhite = /\s/, // Used for trimming whitespace trimLeft = /^\s+/, trimRight = /\s+$/, // Check for non-word characters rnonword = /\W/, // Check for digits rdigit = /\d/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, // Useragent RegExp rwebkit = /(webkit)[ \/]([\w.]+)/, ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, rmsie = /(msie) ([\w.]+)/, rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, // Keep a UserAgent string for use with jQuery.browser userAgent = navigator.userAgent, // For matching the engine and version of the browser browserMatch, // Has the ready events already been bound? readyBound = false, // The functions to execute on DOM ready readyList = [], // The ready event handler DOMContentLoaded, // Save a reference to some core methods toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty, push = Array.prototype.push, slice = Array.prototype.slice, trim = String.prototype.trim, indexOf = Array.prototype.indexOf, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { init: function( selector, context ) { var match, elem, ret, doc; // Handle $(""), $(null), or $(undefined) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // The body element only exists once, optimize finding it if ( selector === "body" && !context && document.body ) { this.context = document; this[0] = document.body; this.selector = "body"; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { // Are we dealing with HTML string or an ID? match = quickExpr.exec( selector ); // Verify a match, and that no context was specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { doc = (context ? context.ownerDocument || context : document); // If a single string is passed in and it's a single tag // just do a createElement and skip the rest ret = rsingleTag.exec( selector ); if ( ret ) { if ( jQuery.isPlainObject( context ) ) { selector = [ document.createElement( ret[1] ) ]; jQuery.fn.attr.call( selector, context, true ); } else { selector = [ doc.createElement( ret[1] ) ]; } } else { ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes; } return jQuery.merge( this, selector ); // HANDLE: $("#id") } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $("TAG") } else if ( !context && !rnonword.test( selector ) ) { this.selector = selector; this.context = document; selector = document.getElementsByTagName( selector ); return jQuery.merge( this, selector ); // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return (context || rootjQuery).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return jQuery( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if (selector.selector !== undefined) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.4.4", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return slice.call( this, 0 ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this.slice(num)[ 0 ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = jQuery(); if ( jQuery.isArray( elems ) ) { push.apply( ret, elems ); } else { jQuery.merge( ret, elems ); } // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + (this.selector ? " " : "") + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Attach the listeners jQuery.bindReady(); // If the DOM is already ready if ( jQuery.isReady ) { // Execute the function immediately fn.call( document, jQuery ); // Otherwise, remember the function for later } else if ( readyList ) { // Add the function to the wait list readyList.push( fn ); } return this; }, eq: function( i ) { return i === -1 ? this.slice( i ) : this.slice( i, +i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ), "slice", slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || jQuery(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { window.$ = _$; if ( deep ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Handle when the DOM is ready ready: function( wait ) { // A third-party is pushing the ready event forwards if ( wait === true ) { jQuery.readyWait--; } // Make sure that the DOM is not already loaded if ( !jQuery.readyWait || (wait !== true && !jQuery.isReady) ) { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute if ( readyList ) { // Execute all of them var fn, i = 0, ready = readyList; // Reset the list of functions readyList = null; while ( (fn = ready[ i++ ]) ) { fn.call( document, jQuery ); } // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger( "ready" ).unbind( "ready" ); } } } }, bindReady: function() { if ( readyBound ) { return; } readyBound = true; // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready return setTimeout( jQuery.ready, 1 ); } // Mozilla, Opera and webkit nightlies currently support this event if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else if ( document.attachEvent ) { // ensure firing before onload, // maybe late but safe also for iframes document.attachEvent("onreadystatechange", DOMContentLoaded); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var toplevel = false; try { toplevel = window.frameElement == null; } catch(e) {} if ( document.documentElement.doScroll && toplevel ) { doScrollCheck(); } } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, // A crude way of determining if an object is a window isWindow: function( obj ) { return obj && typeof obj === "object" && "setInterval" in obj; }, isNaN: function( obj ) { return obj == null || !rdigit.test( obj ) || isNaN( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ toString.call(obj) ] || "object"; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { for ( var name in obj ) { return false; } return true; }, error: function( msg ) { throw msg; }, parseJSON: function( data ) { if ( typeof data !== "string" || !data ) { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test(data.replace(rvalidescape, "@") .replace(rvalidtokens, "]") .replace(rvalidbraces, "")) ) { // Try to use the native JSON parser first return window.JSON && window.JSON.parse ? window.JSON.parse( data ) : (new Function("return " + data))(); } else { jQuery.error( "Invalid JSON: " + data ); } }, noop: function() {}, // Evalulates a script in a global context globalEval: function( data ) { if ( data && rnotwhite.test(data) ) { // Inspired by code by Andrea Giammarchi // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html var head = document.getElementsByTagName("head")[0] || document.documentElement, script = document.createElement("script"); script.type = "text/javascript"; if ( jQuery.support.scriptEval ) { script.appendChild( document.createTextNode( data ) ); } else { script.text = data; } // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709). head.insertBefore( script, head.firstChild ); head.removeChild( script ); } }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); }, // args is for internal usage only each: function( object, callback, args ) { var name, i = 0, length = object.length, isObj = length === undefined || jQuery.isFunction(object); if ( args ) { if ( isObj ) { for ( name in object ) { if ( callback.apply( object[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( object[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in object ) { if ( callback.call( object[ name ], name, object[ name ] ) === false ) { break; } } } else { for ( var value = object[0]; i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {} } } return object; }, // Use native String.trim function wherever possible trim: trim ? function( text ) { return text == null ? "" : trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); }, // results is for internal usage only makeArray: function( array, results ) { var ret = results || []; if ( array != null ) { // The window, strings (and functions) also have 'length' // The extra typeof function check is to prevent crashes // in Safari 2 (See: #3039) // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 var type = jQuery.type(array); if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { push.call( ret, array ); } else { jQuery.merge( ret, array ); } } return ret; }, inArray: function( elem, array ) { if ( array.indexOf ) { return array.indexOf( elem ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[ i ] === elem ) { return i; } } return -1; }, merge: function( first, second ) { var i = first.length, j = 0; if ( typeof second.length === "number" ) { for ( var l = second.length; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var ret = [], retVal; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( var i = 0, length = elems.length; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var ret = [], value; // Go through the array, translating each of the items to their // new value (or values). for ( var i = 0, length = elems.length; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, proxy: function( fn, proxy, thisObject ) { if ( arguments.length === 2 ) { if ( typeof proxy === "string" ) { thisObject = fn; fn = thisObject[ proxy ]; proxy = undefined; } else if ( proxy && !jQuery.isFunction( proxy ) ) { thisObject = proxy; proxy = undefined; } } if ( !proxy && fn ) { proxy = function() { return fn.apply( thisObject || this, arguments ); }; } // Set the guid of unique handler to the same of original handler, so it can be removed if ( fn ) { proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; } // So proxy can be declared as an argument return proxy; }, // Mutifunctional method to get and set values to a collection // The value/s can be optionally by executed if its a function access: function( elems, key, value, exec, fn, pass ) { var length = elems.length; // Setting many attributes if ( typeof key === "object" ) { for ( var k in key ) { jQuery.access( elems, k, key[k], exec, fn, value ); } return elems; } // Setting one attribute if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = !pass && exec && jQuery.isFunction(value); for ( var i = 0; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } return elems; } // Getting an attribute return length ? fn( elems[0], key ) : undefined; }, now: function() { return (new Date()).getTime(); }, // Use of jQuery.browser is frowned upon. // More details: http://docs.jquery.com/Utilities/jQuery.browser uaMatch: function( ua ) { ua = ua.toLowerCase(); var match = rwebkit.exec( ua ) || ropera.exec( ua ) || rmsie.exec( ua ) || ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || []; return { browser: match[1] || "", version: match[2] || "0" }; }, browser: {} }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); browserMatch = jQuery.uaMatch( userAgent ); if ( browserMatch.browser ) { jQuery.browser[ browserMatch.browser ] = true; jQuery.browser.version = browserMatch.version; } // Deprecated, use jQuery.browser.webkit instead if ( jQuery.browser.webkit ) { jQuery.browser.safari = true; } if ( indexOf ) { jQuery.inArray = function( elem, array ) { return indexOf.call( array, elem ); }; } // Verify that \s matches non-breaking spaces // (IE fails on this test) if ( !rwhite.test( "\xA0" ) ) { trimLeft = /^[\s\xA0]+/; trimRight = /[\s\xA0]+$/; } // All jQuery objects should point back to these rootjQuery = jQuery(document); // Cleanup functions for the document ready method if ( document.addEventListener ) { DOMContentLoaded = function() { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); }; } else if ( document.attachEvent ) { DOMContentLoaded = function() { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( document.readyState === "complete" ) { document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }; } // The DOM ready check for Internet Explorer function doScrollCheck() { if ( jQuery.isReady ) { return; } try { // If IE is used, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); } catch(e) { setTimeout( doScrollCheck, 1 ); return; } // and execute any waiting functions jQuery.ready(); } // Expose jQuery to the global object return (window.jQuery = window.$ = jQuery); })(); (function() { jQuery.support = {}; var root = document.documentElement, script = document.createElement("script"), div = document.createElement("div"), id = "script" + jQuery.now(); div.style.display = "none"; div.innerHTML = " <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; var all = div.getElementsByTagName("*"), a = div.getElementsByTagName("a")[0], select = document.createElement("select"), opt = select.appendChild( document.createElement("option") ); // Can't get basic test support if ( !all || !all.length || !a ) { return; } jQuery.support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: div.firstChild.nodeType === 3, // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText insted) style: /red/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: a.getAttribute("href") === "/a", // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.55$/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: div.getElementsByTagName("input")[0].value === "on", // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Will be defined later deleteExpando: true, optDisabled: false, checkClone: false, scriptEval: false, noCloneEvent: true, boxModel: null, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableHiddenOffsets: true }; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as diabled) select.disabled = true; jQuery.support.optDisabled = !opt.disabled; script.type = "text/javascript"; try { script.appendChild( document.createTextNode( "window." + id + "=1;" ) ); } catch(e) {} root.insertBefore( script, root.firstChild ); // Make sure that the execution of code works by injecting a script // tag with appendChild/createTextNode // (IE doesn't support this, fails, and uses .text instead) if ( window[ id ] ) { jQuery.support.scriptEval = true; delete window[ id ]; } // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete script.test; } catch(e) { jQuery.support.deleteExpando = false; } root.removeChild( script ); if ( div.attachEvent && div.fireEvent ) { div.attachEvent("onclick", function click() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) jQuery.support.noCloneEvent = false; div.detachEvent("onclick", click); }); div.cloneNode(true).fireEvent("onclick"); } div = document.createElement("div"); div.innerHTML = "<input type='radio' name='radiotest' checked='checked'/>"; var fragment = document.createDocumentFragment(); fragment.appendChild( div.firstChild ); // WebKit doesn't clone checked state correctly in fragments jQuery.support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked; // Figure out if the W3C box model works as expected // document.body must exist before we can do this jQuery(function() { var div = document.createElement("div"); div.style.width = div.style.paddingLeft = "1px"; document.body.appendChild( div ); jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2; if ( "zoom" in div.style ) { // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout // (IE < 8 does this) div.style.display = "inline"; div.style.zoom = 1; jQuery.support.inlineBlockNeedsLayout = div.offsetWidth === 2; // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = ""; div.innerHTML = "<div style='width:4px;'></div>"; jQuery.support.shrinkWrapBlocks = div.offsetWidth !== 2; } div.innerHTML = "<table><tr><td style='padding:0;display:none'></td><td>t</td></tr></table>"; var tds = div.getElementsByTagName("td"); // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). // (only IE 8 fails this test) jQuery.support.reliableHiddenOffsets = tds[0].offsetHeight === 0; tds[0].style.display = ""; tds[1].style.display = "none"; // Check if empty table cells still have offsetWidth/Height // (IE < 8 fail this test) jQuery.support.reliableHiddenOffsets = jQuery.support.reliableHiddenOffsets && tds[0].offsetHeight === 0; div.innerHTML = ""; document.body.removeChild( div ).style.display = "none"; div = tds = null; }); // Technique from Juriy Zaytsev // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ var eventSupported = function( eventName ) { var el = document.createElement("div"); eventName = "on" + eventName; var isSupported = (eventName in el); if ( !isSupported ) { el.setAttribute(eventName, "return;"); isSupported = typeof el[eventName] === "function"; } el = null; return isSupported; }; jQuery.support.submitBubbles = eventSupported("submit"); jQuery.support.changeBubbles = eventSupported("change"); // release memory in IE root = script = div = all = a = null; })(); var windowData = {}, rbrace = /^(?:\{.*\}|\[.*\])$/; jQuery.extend({ cache: {}, // Please use with caution uuid: 0, // Unique for each copy of jQuery on the page expando: "jQuery" + jQuery.now(), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, data: function( elem, name, data ) { if ( !jQuery.acceptData( elem ) ) { return; } elem = elem == window ? windowData : elem; var isNode = elem.nodeType, id = isNode ? elem[ jQuery.expando ] : null, cache = jQuery.cache, thisCache; if ( isNode && !id && typeof name === "string" && data === undefined ) { return; } // Get the data from the object directly if ( !isNode ) { cache = elem; // Compute a unique ID for the element } else if ( !id ) { elem[ jQuery.expando ] = id = ++jQuery.uuid; } // Avoid generating a new cache unless none exists and we // want to manipulate it. if ( typeof name === "object" ) { if ( isNode ) { cache[ id ] = jQuery.extend(cache[ id ], name); } else { jQuery.extend( cache, name ); } } else if ( isNode && !cache[ id ] ) { cache[ id ] = {}; } thisCache = isNode ? cache[ id ] : cache; // Prevent overriding the named cache with undefined values if ( data !== undefined ) { thisCache[ name ] = data; } return typeof name === "string" ? thisCache[ name ] : thisCache; }, removeData: function( elem, name ) { if ( !jQuery.acceptData( elem ) ) { return; } elem = elem == window ? windowData : elem; var isNode = elem.nodeType, id = isNode ? elem[ jQuery.expando ] : elem, cache = jQuery.cache, thisCache = isNode ? cache[ id ] : id; // If we want to remove a specific section of the element's data if ( name ) { if ( thisCache ) { // Remove the section of cache data delete thisCache[ name ]; // If we've removed all the data, remove the element's cache if ( isNode && jQuery.isEmptyObject(thisCache) ) { jQuery.removeData( elem ); } } // Otherwise, we want to remove all of the element's data } else { if ( isNode && jQuery.support.deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); // Completely remove the data cache } else if ( isNode ) { delete cache[ id ]; // Remove all fields from the object } else { for ( var n in elem ) { delete elem[ n ]; } } } }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { if ( elem.nodeName ) { var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; if ( match ) { return !(match === true || elem.getAttribute("classid") !== match); } } return true; } }); jQuery.fn.extend({ data: function( key, value ) { var data = null; if ( typeof key === "undefined" ) { if ( this.length ) { var attr = this[0].attributes, name; data = jQuery.data( this[0] ); for ( var i = 0, l = attr.length; i < l; i++ ) { name = attr[i].name; if ( name.indexOf( "data-" ) === 0 ) { name = name.substr( 5 ); dataAttr( this[0], name, data[ name ] ); } } } return data; } else if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } var parts = key.split("."); parts[1] = parts[1] ? "." + parts[1] : ""; if ( value === undefined ) { data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); // Try to fetch any internally stored data first if ( data === undefined && this.length ) { data = jQuery.data( this[0], key ); data = dataAttr( this[0], key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } else { return this.each(function() { var $this = jQuery( this ), args = [ parts[0], value ]; $this.triggerHandler( "setData" + parts[1] + "!", args ); jQuery.data( this, key, value ); $this.triggerHandler( "changeData" + parts[1] + "!", args ); }); } }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { data = elem.getAttribute( "data-" + key ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : !jQuery.isNaN( data ) ? parseFloat( data ) : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend({ queue: function( elem, type, data ) { if ( !elem ) { return; } type = (type || "fx") + "queue"; var q = jQuery.data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( !data ) { return q || []; } if ( !q || jQuery.isArray(data) ) { q = jQuery.data( elem, type, jQuery.makeArray(data) ); } else { q.push( data ); } return q; }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), fn = queue.shift(); // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift("inprogress"); } fn.call(elem, function() { jQuery.dequeue(elem, type); }); } } }); jQuery.fn.extend({ queue: function( type, data ) { if ( typeof type !== "string" ) { data = type; type = "fx"; } if ( data === undefined ) { return jQuery.queue( this[0], type ); } return this.each(function( i ) { var queue = jQuery.queue( this, type, data ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; type = type || "fx"; return this.queue( type, function() { var elem = this; setTimeout(function() { jQuery.dequeue( elem, type ); }, time ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); } }); var rclass = /[\n\t]/g, rspaces = /\s+/, rreturn = /\r/g, rspecialurl = /^(?:href|src|style)$/, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea)?$/i, rradiocheck = /^(?:radio|checkbox)$/i; jQuery.props = { "for": "htmlFor", "class": "className", readonly: "readOnly", maxlength: "maxLength", cellspacing: "cellSpacing", rowspan: "rowSpan", colspan: "colSpan", tabindex: "tabIndex", usemap: "useMap", frameborder: "frameBorder" }; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, name, value, true, jQuery.attr ); }, removeAttr: function( name, fn ) { return this.each(function(){ jQuery.attr( this, name, "" ); if ( this.nodeType === 1 ) { this.removeAttribute( name ); } }); }, addClass: function( value ) { if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); self.addClass( value.call(this, i, self.attr("class")) ); }); } if ( value && typeof value === "string" ) { var classNames = (value || "").split( rspaces ); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 ) { if ( !elem.className ) { elem.className = value; } else { var className = " " + elem.className + " ", setClass = elem.className; for ( var c = 0, cl = classNames.length; c < cl; c++ ) { if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) { setClass += " " + classNames[c]; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); self.removeClass( value.call(this, i, self.attr("class")) ); }); } if ( (value && typeof value === "string") || value === undefined ) { var classNames = (value || "").split( rspaces ); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 && elem.className ) { if ( value ) { var className = (" " + elem.className + " ").replace(rclass, " "); for ( var c = 0, cl = classNames.length; c < cl; c++ ) { className = className.replace(" " + classNames[c] + " ", " "); } elem.className = jQuery.trim( className ); } else { elem.className = ""; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this); self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.split( rspaces ); while ( (className = classNames[ i++ ]) ) { // check each className given, space seperated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery.data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery.data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " "; for ( var i = 0, l = this.length; i < l; i++ ) { if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { return true; } } return false; }, val: function( value ) { if ( !arguments.length ) { var elem = this[0]; if ( elem ) { if ( jQuery.nodeName( elem, "option" ) ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } // We need to handle select boxes special if ( jQuery.nodeName( elem, "select" ) ) { var index = elem.selectedIndex, values = [], options = elem.options, one = elem.type === "select-one"; // Nothing was selected if ( index < 0 ) { return null; } // Loop through all the selected options for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { var option = options[ i ]; // Don't return options that are disabled or in a disabled optgroup if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { // Get the specific value for the option value = jQuery(option).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; } // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) { return elem.getAttribute("value") === null ? "on" : elem.value; } // Everything else, we just grab the value return (elem.value || "").replace(rreturn, ""); } return undefined; } var isFunction = jQuery.isFunction(value); return this.each(function(i) { var self = jQuery(this), val = value; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call(this, i, self.val()); } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray(val) ) { val = jQuery.map(val, function (value) { return value == null ? "" : value + ""; }); } if ( jQuery.isArray(val) && rradiocheck.test( this.type ) ) { this.checked = jQuery.inArray( self.val(), val ) >= 0; } else if ( jQuery.nodeName( this, "select" ) ) { var values = jQuery.makeArray(val); jQuery( "option", this ).each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { this.selectedIndex = -1; } } else { this.value = val; } }); } }); jQuery.extend({ attrFn: { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true }, attr: function( elem, name, value, pass ) { // don't set attributes on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { return undefined; } if ( pass && name in jQuery.attrFn ) { return jQuery(elem)[name](value); } var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ), // Whether we are setting (or getting) set = value !== undefined; // Try to normalize/fix the name name = notxml && jQuery.props[ name ] || name; // These attributes require special treatment var special = rspecialurl.test( name ); // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( name === "selected" && !jQuery.support.optSelected ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } } // If applicable, access the attribute via the DOM 0 way // 'in' checks fail in Blackberry 4.7 #6931 if ( (name in elem || elem[ name ] !== undefined) && notxml && !special ) { if ( set ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } if ( value === null ) { if ( elem.nodeType === 1 ) { elem.removeAttribute( name ); } } else { elem[ name ] = value; } } // browsers index elements by id/name on forms, give priority to attributes. if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) { return elem.getAttributeNode( name ).nodeValue; } // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ if ( name === "tabIndex" ) { var attributeNode = elem.getAttributeNode( "tabIndex" ); return attributeNode && attributeNode.specified ? attributeNode.value : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } return elem[ name ]; } if ( !jQuery.support.style && notxml && name === "style" ) { if ( set ) { elem.style.cssText = "" + value; } return elem.style.cssText; } if ( set ) { // convert the value to a string (all browsers do this but IE) see #1070 elem.setAttribute( name, "" + value ); } // Ensure that missing attributes return undefined // Blackberry 4.7 returns "" from getAttribute #6938 if ( !elem.attributes[ name ] && (elem.hasAttribute && !elem.hasAttribute( name )) ) { return undefined; } var attr = !jQuery.support.hrefNormalized && notxml && special ? // Some attributes require a special call on IE elem.getAttribute( name, 2 ) : elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return attr === null ? undefined : attr; } }); var rnamespaces = /\.(.*)$/, rformElems = /^(?:textarea|input|select)$/i, rperiod = /\./g, rspace = / /g, rescape = /[^\w\s.|`]/g, fcleanup = function( nm ) { return nm.replace(rescape, "\\$&"); }, focusCounts = { focusin: 0, focusout: 0 }; /* * A number of helper functions used for managing events. * Many of the ideas behind this code originated from * Dean Edwards' addEvent library. */ jQuery.event = { // Bind an event to an element // Original by Dean Edwards add: function( elem, types, handler, data ) { if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // For whatever reason, IE has trouble passing the window object // around, causing it to be cloned in the process if ( jQuery.isWindow( elem ) && ( elem !== window && !elem.frameElement ) ) { elem = window; } if ( handler === false ) { handler = returnFalse; } else if ( !handler ) { // Fixes bug #7229. Fix recommended by jdalton return; } var handleObjIn, handleObj; if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; } // Make sure that the function being executed has a unique ID if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure var elemData = jQuery.data( elem ); // If no elemData is found then we must be trying to bind to one of the // banned noData elements if ( !elemData ) { return; } // Use a key less likely to result in collisions for plain JS objects. // Fixes bug #7150. var eventKey = elem.nodeType ? "events" : "__events__", events = elemData[ eventKey ], eventHandle = elemData.handle; if ( typeof events === "function" ) { // On plain objects events is a fn that holds the the data // which prevents this data from being JSON serialized // the function does not need to be called, it just contains the data eventHandle = events.handle; events = events.events; } else if ( !events ) { if ( !elem.nodeType ) { // On plain objects, create a fn that acts as the holder // of the values to avoid JSON serialization of event data elemData[ eventKey ] = elemData = function(){}; } elemData.events = events = {}; } if ( !eventHandle ) { elemData.handle = eventHandle = function() { // Handle the second event of a trigger and when // an event is called after a page has unloaded return typeof jQuery !== "undefined" && !jQuery.event.triggered ? jQuery.event.handle.apply( eventHandle.elem, arguments ) : undefined; }; } // Add elem as a property of the handle function // This is to prevent a memory leak with non-native events in IE. eventHandle.elem = elem; // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = types.split(" "); var type, i = 0, namespaces; while ( (type = types[ i++ ]) ) { handleObj = handleObjIn ? jQuery.extend({}, handleObjIn) : { handler: handler, data: data }; // Namespaced event handlers if ( type.indexOf(".") > -1 ) { namespaces = type.split("."); type = namespaces.shift(); handleObj.namespace = namespaces.slice(0).sort().join("."); } else { namespaces = []; handleObj.namespace = ""; } handleObj.type = type; if ( !handleObj.guid ) { handleObj.guid = handler.guid; } // Get the current list of functions bound to this event var handlers = events[ type ], special = jQuery.event.special[ type ] || {}; // Init the event handler queue if ( !handlers ) { handlers = events[ type ] = []; // Check for a special event handler // Only use addEventListener/attachEvent if the special // events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add the function to the element's handler list handlers.push( handleObj ); // Keep track of which events have been used, for global triggering jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, pos ) { // don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } if ( handler === false ) { handler = returnFalse; } var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType, eventKey = elem.nodeType ? "events" : "__events__", elemData = jQuery.data( elem ), events = elemData && elemData[ eventKey ]; if ( !elemData || !events ) { return; } if ( typeof events === "function" ) { elemData = events; events = events.events; } // types is actually an event object here if ( types && types.type ) { handler = types.handler; types = types.type; } // Unbind all events for the element if ( !types || typeof types === "string" && types.charAt(0) === "." ) { types = types || ""; for ( type in events ) { jQuery.event.remove( elem, type + types ); } return; } // Handle multiple events separated by a space // jQuery(...).unbind("mouseover mouseout", fn); types = types.split(" "); while ( (type = types[ i++ ]) ) { origType = type; handleObj = null; all = type.indexOf(".") < 0; namespaces = []; if ( !all ) { // Namespaced event handlers namespaces = type.split("."); type = namespaces.shift(); namespace = new RegExp("(^|\\.)" + jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)"); } eventType = events[ type ]; if ( !eventType ) { continue; } if ( !handler ) { for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( all || namespace.test( handleObj.namespace ) ) { jQuery.event.remove( elem, origType, handleObj.handler, j ); eventType.splice( j--, 1 ); } } continue; } special = jQuery.event.special[ type ] || {}; for ( j = pos || 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( handler.guid === handleObj.guid ) { // remove the given handler for the given type if ( all || namespace.test( handleObj.namespace ) ) { if ( pos == null ) { eventType.splice( j--, 1 ); } if ( special.remove ) { special.remove.call( elem, handleObj ); } } if ( pos != null ) { break; } } } // remove generic event handler if no more handlers exist if ( eventType.length === 0 || pos != null && eventType.length === 1 ) { if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } ret = null; delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { var handle = elemData.handle; if ( handle ) { handle.elem = null; } delete elemData.events; delete elemData.handle; if ( typeof elemData === "function" ) { jQuery.removeData( elem, eventKey ); } else if ( jQuery.isEmptyObject( elemData ) ) { jQuery.removeData( elem ); } } }, // bubbling is internal trigger: function( event, data, elem /*, bubbling */ ) { // Event object or event type var type = event.type || event, bubbling = arguments[3]; if ( !bubbling ) { event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal jQuery.extend( jQuery.Event(type), event ) : // Just the event type (string) jQuery.Event(type); if ( type.indexOf("!") >= 0 ) { event.type = type = type.slice(0, -1); event.exclusive = true; } // Handle a global trigger if ( !elem ) { // Don't bubble custom events when global (to avoid too much overhead) event.stopPropagation(); // Only trigger if we've ever bound an event for it if ( jQuery.event.global[ type ] ) { jQuery.each( jQuery.cache, function() { if ( this.events && this.events[type] ) { jQuery.event.trigger( event, data, this.handle.elem ); } }); } } // Handle triggering a single element // don't do events on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { return undefined; } // Clean up in case it is reused event.result = undefined; event.target = elem; // Clone the incoming data, if any data = jQuery.makeArray( data ); data.unshift( event ); } event.currentTarget = elem; // Trigger the event, it is assumed that "handle" is a function var handle = elem.nodeType ? jQuery.data( elem, "handle" ) : (jQuery.data( elem, "__events__" ) || {}).handle; if ( handle ) { handle.apply( elem, data ); } var parent = elem.parentNode || elem.ownerDocument; // Trigger an inline bound script try { if ( !(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) ) { if ( elem[ "on" + type ] && elem[ "on" + type ].apply( elem, data ) === false ) { event.result = false; event.preventDefault(); } } // prevent IE from throwing an error for some elements with some event types, see #3533 } catch (inlineError) {} if ( !event.isPropagationStopped() && parent ) { jQuery.event.trigger( event, data, parent, true ); } else if ( !event.isDefaultPrevented() ) { var old, target = event.target, targetType = type.replace( rnamespaces, "" ), isClick = jQuery.nodeName( target, "a" ) && targetType === "click", special = jQuery.event.special[ targetType ] || {}; if ( (!special._default || special._default.call( elem, event ) === false) && !isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) { try { if ( target[ targetType ] ) { // Make sure that we don't accidentally re-trigger the onFOO events old = target[ "on" + targetType ]; if ( old ) { target[ "on" + targetType ] = null; } jQuery.event.triggered = true; target[ targetType ](); } // prevent IE from throwing an error for some elements with some event types, see #3533 } catch (triggerError) {} if ( old ) { target[ "on" + targetType ] = old; } jQuery.event.triggered = false; } } }, handle: function( event ) { var all, handlers, namespaces, namespace_re, events, namespace_sort = [], args = jQuery.makeArray( arguments ); event = args[0] = jQuery.event.fix( event || window.event ); event.currentTarget = this; // Namespaced event handlers all = event.type.indexOf(".") < 0 && !event.exclusive; if ( !all ) { namespaces = event.type.split("."); event.type = namespaces.shift(); namespace_sort = namespaces.slice(0).sort(); namespace_re = new RegExp("(^|\\.)" + namespace_sort.join("\\.(?:.*\\.)?") + "(\\.|$)"); } event.namespace = event.namespace || namespace_sort.join("."); events = jQuery.data(this, this.nodeType ? "events" : "__events__"); if ( typeof events === "function" ) { events = events.events; } handlers = (events || {})[ event.type ]; if ( events && handlers ) { // Clone the handlers to prevent manipulation handlers = handlers.slice(0); for ( var j = 0, l = handlers.length; j < l; j++ ) { var handleObj = handlers[ j ]; // Filter the functions by class if ( all || namespace_re.test( handleObj.namespace ) ) { // Pass in a reference to the handler function itself // So that we can later remove it event.handler = handleObj.handler; event.data = handleObj.data; event.handleObj = handleObj; var ret = handleObj.handler.apply( this, args ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } if ( event.isImmediatePropagationStopped() ) { break; } } } } return event.result; }, props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // store a copy of the original event object // and "clone" to set read-only properties var originalEvent = event; event = jQuery.Event( originalEvent ); for ( var i = this.props.length, prop; i; ) { prop = this.props[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary if ( !event.target ) { // Fixes #1925 where srcElement might not be defined either event.target = event.srcElement || document; } // check if target is a textnode (safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Add relatedTarget, if necessary if ( !event.relatedTarget && event.fromElement ) { event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; } // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && event.clientX != null ) { var doc = document.documentElement, body = document.body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Add which for key events if ( event.which == null && (event.charCode != null || event.keyCode != null) ) { event.which = event.charCode != null ? event.charCode : event.keyCode; } // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) if ( !event.metaKey && event.ctrlKey ) { event.metaKey = event.ctrlKey; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && event.button !== undefined ) { event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); } return event; }, // Deprecated, use jQuery.guid instead guid: 1E8, // Deprecated, use jQuery.proxy instead proxy: jQuery.proxy, special: { ready: { // Make sure the ready event is setup setup: jQuery.bindReady, teardown: jQuery.noop }, live: { add: function( handleObj ) { jQuery.event.add( this, liveConvert( handleObj.origType, handleObj.selector ), jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) ); }, remove: function( handleObj ) { jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj ); } }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( jQuery.isWindow( this ) ) { this.onbeforeunload = eventHandle; } }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { if ( elem.detachEvent ) { elem.detachEvent( "on" + type, handle ); } }; jQuery.Event = function( src ) { // Allow instantiation without the 'new' keyword if ( !this.preventDefault ) { return new jQuery.Event( src ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Event type } else { this.type = src; } // timeStamp is buggy for some events on Firefox(#3843) // So we won't rely on the native value this.timeStamp = jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); // otherwise set the returnValue property of the original event to false (IE) } else { e.returnValue = false; } }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Checks if an event happened on an element within another element // Used in jQuery.event.special.mouseenter and mouseleave handlers var withinElement = function( event ) { // Check if mouse(over|out) are still within the same parent element var parent = event.relatedTarget; // Firefox sometimes assigns relatedTarget a XUL element // which we cannot access the parentNode property of try { // Traverse up the tree while ( parent && parent !== this ) { parent = parent.parentNode; } if ( parent !== this ) { // set the correct event type event.type = event.data; // handle event if we actually just moused on to a non sub-element jQuery.event.handle.apply( this, arguments ); } // assuming we've left the element since we most likely mousedover a xul element } catch(e) { } }, // In case of event delegation, we only need to rename the event.type, // liveHandler will take care of the rest. delegate = function( event ) { event.type = event.data; jQuery.event.handle.apply( this, arguments ); }; // Create mouseenter and mouseleave events jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { setup: function( data ) { jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig ); }, teardown: function( data ) { jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement ); } }; }); // submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function( data, namespaces ) { if ( this.nodeName.toLowerCase() !== "form" ) { jQuery.event.add(this, "click.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) { e.liveFired = undefined; return trigger( "submit", this, arguments ); } }); jQuery.event.add(this, "keypress.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) { e.liveFired = undefined; return trigger( "submit", this, arguments ); } }); } else { return false; } }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialSubmit" ); } }; } // change delegation, happens here so we have bind. if ( !jQuery.support.changeBubbles ) { var changeFilters, getVal = function( elem ) { var type = elem.type, val = elem.value; if ( type === "radio" || type === "checkbox" ) { val = elem.checked; } else if ( type === "select-multiple" ) { val = elem.selectedIndex > -1 ? jQuery.map( elem.options, function( elem ) { return elem.selected; }).join("-") : ""; } else if ( elem.nodeName.toLowerCase() === "select" ) { val = elem.selectedIndex; } return val; }, testChange = function testChange( e ) { var elem = e.target, data, val; if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) { return; } data = jQuery.data( elem, "_change_data" ); val = getVal(elem); // the current data will be also retrieved by beforeactivate if ( e.type !== "focusout" || elem.type !== "radio" ) { jQuery.data( elem, "_change_data", val ); } if ( data === undefined || val === data ) { return; } if ( data != null || val ) { e.type = "change"; e.liveFired = undefined; return jQuery.event.trigger( e, arguments[1], elem ); } }; jQuery.event.special.change = { filters: { focusout: testChange, beforedeactivate: testChange, click: function( e ) { var elem = e.target, type = elem.type; if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) { return testChange.call( this, e ); } }, // Change has to be called before submit // Keydown will be called before keypress, which is used in submit-event delegation keydown: function( e ) { var elem = e.target, type = elem.type; if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") || (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || type === "select-multiple" ) { return testChange.call( this, e ); } }, // Beforeactivate happens also before the previous element is blurred // with this event you can't trigger a change event, but you can store // information beforeactivate: function( e ) { var elem = e.target; jQuery.data( elem, "_change_data", getVal(elem) ); } }, setup: function( data, namespaces ) { if ( this.type === "file" ) { return false; } for ( var type in changeFilters ) { jQuery.event.add( this, type + ".specialChange", changeFilters[type] ); } return rformElems.test( this.nodeName ); }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialChange" ); return rformElems.test( this.nodeName ); } }; changeFilters = jQuery.event.special.change.filters; // Handle when the input is .focus()'d changeFilters.focus = changeFilters.beforeactivate; } function trigger( type, elem, args ) { args[0].type = type; return jQuery.event.handle.apply( elem, args ); } // Create "bubbling" focus and blur events if ( document.addEventListener ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { jQuery.event.special[ fix ] = { setup: function() { if ( focusCounts[fix]++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --focusCounts[fix] === 0 ) { document.removeEventListener( orig, handler, true ); } } }; function handler( e ) { e = jQuery.event.fix( e ); e.type = fix; return jQuery.event.trigger( e, null, e.target ); } }); } jQuery.each(["bind", "one"], function( i, name ) { jQuery.fn[ name ] = function( type, data, fn ) { // Handle object literals if ( typeof type === "object" ) { for ( var key in type ) { this[ name ](key, data, type[key], fn); } return this; } if ( jQuery.isFunction( data ) || data === false ) { fn = data; data = undefined; } var handler = name === "one" ? jQuery.proxy( fn, function( event ) { jQuery( this ).unbind( event, handler ); return fn.apply( this, arguments ); }) : fn; if ( type === "unload" && name !== "one" ) { this.one( type, data, fn ); } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.add( this[i], type, handler, data ); } } return this; }; }); jQuery.fn.extend({ unbind: function( type, fn ) { // Handle object literals if ( typeof type === "object" && !type.preventDefault ) { for ( var key in type ) { this.unbind(key, type[key]); } } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.remove( this[i], type, fn ); } } return this; }, delegate: function( selector, types, data, fn ) { return this.live( types, data, fn, selector ); }, undelegate: function( selector, types, fn ) { if ( arguments.length === 0 ) { return this.unbind( "live" ); } else { return this.die( types, null, fn, selector ); } }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { var event = jQuery.Event( type ); event.preventDefault(); event.stopPropagation(); jQuery.event.trigger( event, data, this[0] ); return event.result; } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, i = 1; // link all the functions, so any of them can unbind this click handler while ( i < args.length ) { jQuery.proxy( fn, args[ i++ ] ); } return this.click( jQuery.proxy( fn, function( event ) { // Figure out which function to execute var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; })); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); var liveMap = { focus: "focusin", blur: "focusout", mouseenter: "mouseover", mouseleave: "mouseout" }; jQuery.each(["live", "die"], function( i, name ) { jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) { var type, i = 0, match, namespaces, preType, selector = origSelector || this.selector, context = origSelector ? this : jQuery( this.context ); if ( typeof types === "object" && !types.preventDefault ) { for ( var key in types ) { context[ name ]( key, data, types[key], selector ); } return this; } if ( jQuery.isFunction( data ) ) { fn = data; data = undefined; } types = (types || "").split(" "); while ( (type = types[ i++ ]) != null ) { match = rnamespaces.exec( type ); namespaces = ""; if ( match ) { namespaces = match[0]; type = type.replace( rnamespaces, "" ); } if ( type === "hover" ) { types.push( "mouseenter" + namespaces, "mouseleave" + namespaces ); continue; } preType = type; if ( type === "focus" || type === "blur" ) { types.push( liveMap[ type ] + namespaces ); type = type + namespaces; } else { type = (liveMap[ type ] || type) + namespaces; } if ( name === "live" ) { // bind live handler for ( var j = 0, l = context.length; j < l; j++ ) { jQuery.event.add( context[j], "live." + liveConvert( type, selector ), { data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } ); } } else { // unbind live handler context.unbind( "live." + liveConvert( type, selector ), fn ); } } return this; }; }); function liveHandler( event ) { var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret, elems = [], selectors = [], events = jQuery.data( this, this.nodeType ? "events" : "__events__" ); if ( typeof events === "function" ) { events = events.events; } // Make sure we avoid non-left-click bubbling in Firefox (#3861) if ( event.liveFired === this || !events || !events.live || event.button && event.type === "click" ) { return; } if ( event.namespace ) { namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)"); } event.liveFired = this; var live = events.live.slice(0); for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) { selectors.push( handleObj.selector ); } else { live.splice( j--, 1 ); } } match = jQuery( event.target ).closest( selectors, event.currentTarget ); for ( i = 0, l = match.length; i < l; i++ ) { close = match[i]; for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) ) { elem = close.elem; related = null; // Those two events require additional checking if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) { event.type = handleObj.preType; related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0]; } if ( !related || related !== elem ) { elems.push({ elem: elem, handleObj: handleObj, level: close.level }); } } } } for ( i = 0, l = elems.length; i < l; i++ ) { match = elems[i]; if ( maxLevel && match.level > maxLevel ) { break; } event.currentTarget = match.elem; event.data = match.handleObj.data; event.handleObj = match.handleObj; ret = match.handleObj.origHandler.apply( match.elem, arguments ); if ( ret === false || event.isPropagationStopped() ) { maxLevel = match.level; if ( ret === false ) { stop = false; } if ( event.isImmediatePropagationStopped() ) { break; } } } return stop; } function liveConvert( type, selector ) { return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspace, "&"); } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.bind( name, data, fn ) : this.trigger( name ); }; if ( jQuery.attrFn ) { jQuery.attrFn[ name ] = true; } }); // Prevent memory leaks in IE // Window isn't included so as not to unbind existing unload events // More info: // - http://isaacschlueter.com/2006/10/msie-memory-leaks/ if ( window.attachEvent && !window.addEventListener ) { jQuery(window).bind("unload", function() { for ( var id in jQuery.cache ) { if ( jQuery.cache[ id ].handle ) { // Try/Catch is to handle iframes being unloaded, see #4280 try { jQuery.event.remove( jQuery.cache[ id ].handle.elem ); } catch(e) {} } } }); } /*! * Sizzle CSS Selector Engine - v1.0 * Copyright 2009, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true; // Here we check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. [0, 0].sort(function() { baseHasDuplicate = false; return 0; }); var Sizzle = function( selector, context, results, seed ) { results = results || []; context = context || document; var origContext = context; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var m, set, checkSet, extra, ret, cur, pop, i, prune = true, contextXML = Sizzle.isXML( context ), parts = [], soFar = selector; // Reset the position of the chunker regexp (start from head) do { chunker.exec( "" ); m = chunker.exec( soFar ); if ( m ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } } while ( m ); if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : Sizzle( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) { selector += parts.shift(); } set = posProcess( selector, set ); } } } else { // Take a shortcut and set the context if the root selector is an ID // (but not if it'll be faster if the inner selector is an ID) if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray( set ); } else { prune = false; } while ( parts.length ) { cur = parts.pop(); pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { Sizzle.error( cur || selector ); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { Sizzle( extra, origContext, results, seed ); Sizzle.uniqueSort( results ); } return results; }; Sizzle.uniqueSort = function( results ) { if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[ i - 1 ] ) { results.splice( i--, 1 ); } } } } return results; }; Sizzle.matches = function( expr, set ) { return Sizzle( expr, null, null, set ); }; Sizzle.matchesSelector = function( node, expr ) { return Sizzle( expr, null, null, [node] ).length > 0; }; Sizzle.find = function( expr, context, isXML ) { var set; if ( !expr ) { return []; } for ( var i = 0, l = Expr.order.length; i < l; i++ ) { var match, type = Expr.order[i]; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { var left = match[1]; match.splice( 1, 1 ); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace(/\\/g, ""); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = context.getElementsByTagName( "*" ); } return { set: set, expr: expr }; }; Sizzle.filter = function( expr, set, inplace, not ) { var match, anyFound, old = expr, result = [], curLoop = set, isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); while ( expr && set.length ) { for ( var type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { var found, item, filter = Expr.filter[ type ], left = match[1]; anyFound = false; match.splice(1,1); if ( left.substr( left.length - 1 ) === "\\" ) { continue; } if ( curLoop === result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( var i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); var pass = not ^ !!found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr === old ) { if ( anyFound == null ) { Sizzle.error( expr ); } else { break; } } old = expr; } return curLoop; }; Sizzle.error = function( msg ) { throw "Syntax error, unrecognized expression: " + msg; }; var Expr = Sizzle.selectors = { order: [ "ID", "NAME", "TAG" ], match: { ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function( elem ) { return elem.getAttribute( "href" ); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !/\W/.test( part ), isPartStrNotTag = isPartStr && !isTag; if ( isTag ) { part = part.toLowerCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { Sizzle.filter( part, checkSet, true ); } }, ">": function( checkSet, part ) { var elem, isPartStr = typeof part === "string", i = 0, l = checkSet.length; if ( isPartStr && !/\W/.test( part ) ) { part = part.toLowerCase(); for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { Sizzle.filter( part, checkSet, true ); } } }, "": function(checkSet, part, isXML){ var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !/\W/.test(part) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); }, "~": function( checkSet, part, isXML ) { var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !/\W/.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); } }, find: { ID: function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }, NAME: function( match, context ) { if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName( match[1] ); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, TAG: function( match, context ) { return context.getElementsByTagName( match[1] ); } }, preFilter: { CLASS: function( match, curLoop, inplace, result, not, isXML ) { match = " " + match[1].replace(/\\/g, "") + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function( match ) { return match[1].replace(/\\/g, ""); }, TAG: function( match, curLoop ) { return match[1].toLowerCase(); }, CHILD: function( match ) { if ( match[1] === "nth" ) { // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec( match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function( match, curLoop, inplace, result, not, isXML ) { var name = match[1].replace(/\\/g, ""); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function( match, curLoop, inplace, result, not ) { if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = Sizzle(match[3], null, null, curLoop); } else { var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function( match ) { match.unshift( true ); return match; } }, filters: { enabled: function( elem ) { return elem.disabled === false && elem.type !== "hidden"; }, disabled: function( elem ) { return elem.disabled === true; }, checked: function( elem ) { return elem.checked === true; }, selected: function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly elem.parentNode.selectedIndex; return elem.selected === true; }, parent: function( elem ) { return !!elem.firstChild; }, empty: function( elem ) { return !elem.firstChild; }, has: function( elem, i, match ) { return !!Sizzle( match[3], elem ).length; }, header: function( elem ) { return (/h\d/i).test( elem.nodeName ); }, text: function( elem ) { return "text" === elem.type; }, radio: function( elem ) { return "radio" === elem.type; }, checkbox: function( elem ) { return "checkbox" === elem.type; }, file: function( elem ) { return "file" === elem.type; }, password: function( elem ) { return "password" === elem.type; }, submit: function( elem ) { return "submit" === elem.type; }, image: function( elem ) { return "image" === elem.type; }, reset: function( elem ) { return "reset" === elem.type; }, button: function( elem ) { return "button" === elem.type || elem.nodeName.toLowerCase() === "button"; }, input: function( elem ) { return (/input|select|textarea|button/i).test( elem.nodeName ); } }, setFilters: { first: function( elem, i ) { return i === 0; }, last: function( elem, i, match, array ) { return i === array.length - 1; }, even: function( elem, i ) { return i % 2 === 0; }, odd: function( elem, i ) { return i % 2 === 1; }, lt: function( elem, i, match ) { return i < match[3] - 0; }, gt: function( elem, i, match ) { return i > match[3] - 0; }, nth: function( elem, i, match ) { return match[3] - 0 === i; }, eq: function( elem, i, match ) { return match[3] - 0 === i; } }, filter: { PSEUDO: function( elem, match, i, array ) { var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var j = 0, l = not.length; j < l; j++ ) { if ( not[j] === elem ) { return false; } } return true; } else { Sizzle.error( "Syntax error, unrecognized expression: " + name ); } }, CHILD: function( elem, match ) { var type = match[1], node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; case "nth": var first = match[2], last = match[3]; if ( first === 1 && last === 0 ) { return true; } var doneName = match[0], parent = elem.parentNode; if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { var count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent.sizcache = doneName; } var diff = elem.nodeIndex - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } } }, ID: function( elem, match ) { return elem.nodeType === 1 && elem.getAttribute("id") === match; }, TAG: function( elem, match ) { return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; }, CLASS: function( elem, match ) { return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function( elem, match ) { var name = match[1], result = Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value !== check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function( elem, match, i, array ) { var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS, fescape = function(all, num){ return "\\" + (num - 0 + 1); }; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); } var makeArray = function( array, results ) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. // Also verifies that the returned array holds DOM nodes // (which is not the case in the Blackberry browser) try { Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; // Provide a fallback method if it does not work } catch( e ) { makeArray = function( array, results ) { var i = 0, ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( ; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder, siblingCheck; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { return a.compareDocumentPosition ? -1 : 1; } return a.compareDocumentPosition(b) & 4 ? -1 : 1; }; } else { sortOrder = function( a, b ) { var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // If the nodes are siblings (or identical) we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; siblingCheck = function( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; }; } // Utility function for retreiving the text value of an array of DOM nodes Sizzle.getText = function( elems ) { var ret = "", elem; for ( var i = 0; elems[i]; i++ ) { elem = elems[i]; // Get the text from text nodes and CDATA nodes if ( elem.nodeType === 3 || elem.nodeType === 4 ) { ret += elem.nodeValue; // Traverse everything else, except comment nodes } else if ( elem.nodeType !== 8 ) { ret += Sizzle.getText( elem.childNodes ); } } return ret; }; // Check to see if the browser returns elements by name when // querying by getElementById (and provide a workaround) (function(){ // We're going to inject a fake input element with a specified name var form = document.createElement("div"), id = "script" + (new Date()).getTime(), root = document.documentElement; form.innerHTML = "<a name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly root.insertBefore( form, root.firstChild ); // The workaround has to do additional checks after a getElementById // Which slows things down for other browsers (hence the branching) if ( document.getElementById( id ) ) { Expr.find.ID = function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }; Expr.filter.ID = function( elem, match ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }; } root.removeChild( form ); // release memory in IE root = form = null; })(); (function(){ // Check to see if the browser returns only elements // when doing getElementsByTagName("*") // Create a fake element var div = document.createElement("div"); div.appendChild( document.createComment("") ); // Make sure no comments are found if ( div.getElementsByTagName("*").length > 0 ) { Expr.find.TAG = function( match, context ) { var results = context.getElementsByTagName( match[1] ); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; }; } // Check to see if an attribute returns normalized href attributes div.innerHTML = "<a href='#'></a>"; if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && div.firstChild.getAttribute("href") !== "#" ) { Expr.attrHandle.href = function( elem ) { return elem.getAttribute( "href", 2 ); }; } // release memory in IE div = null; })(); if ( document.querySelectorAll ) { (function(){ var oldSizzle = Sizzle, div = document.createElement("div"), id = "__sizzle__"; div.innerHTML = "<p class='TEST'></p>"; // Safari can't handle uppercase or unicode characters when // in quirks mode. if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { return; } Sizzle = function( query, context, extra, seed ) { context = context || document; // Make sure that attribute selectors are quoted query = query.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); // Only use querySelectorAll on non-XML documents // (ID selectors don't work in non-HTML documents) if ( !seed && !Sizzle.isXML(context) ) { if ( context.nodeType === 9 ) { try { return makeArray( context.querySelectorAll(query), extra ); } catch(qsaError) {} // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { var old = context.getAttribute( "id" ), nid = old || id; if ( !old ) { context.setAttribute( "id", nid ); } try { return makeArray( context.querySelectorAll( "#" + nid + " " + query ), extra ); } catch(pseudoError) { } finally { if ( !old ) { context.removeAttribute( "id" ); } } } } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } // release memory in IE div = null; })(); } (function(){ var html = document.documentElement, matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector, pseudoWorks = false; try { // This should fail with an exception // Gecko does not error, returns false instead matches.call( document.documentElement, "[test!='']:sizzle" ); } catch( pseudoError ) { pseudoWorks = true; } if ( matches ) { Sizzle.matchesSelector = function( node, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); if ( !Sizzle.isXML( node ) ) { try { if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { return matches.call( node, expr ); } } catch(e) {} } return Sizzle(expr, null, null, [node]).length > 0; }; } })(); (function(){ var div = document.createElement("div"); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; // Opera can't find a second classname (in 9.6) // Also, make sure that getElementsByClassName actually exists if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { return; } // Safari caches class attributes, doesn't catch changes (in 3.2) div.lastChild.className = "e"; if ( div.getElementsByClassName("e").length === 1 ) { return; } Expr.order.splice(1, 0, "CLASS"); Expr.find.CLASS = function( match, context, isXML ) { if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { return context.getElementsByClassName(match[1]); } }; // release memory in IE div = null; })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem.sizcache = doneName; elem.sizset = i; } if ( elem.nodeName.toLowerCase() === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem.sizcache = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } if ( document.documentElement.contains ) { Sizzle.contains = function( a, b ) { return a !== b && (a.contains ? a.contains(b) : true); }; } else if ( document.documentElement.compareDocumentPosition ) { Sizzle.contains = function( a, b ) { return !!(a.compareDocumentPosition(b) & 16); }; } else { Sizzle.contains = function() { return false; }; } Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; var posProcess = function( selector, context ) { var match, tmpSet = [], later = "", root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { Sizzle( selector, root[i], tmpSet ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.filters; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })(); var runtil = /Until$/, rparentsprev = /^(?:parents|prevUntil|prevAll)/, // Note: This RegExp should be improved, or likely pulled from Sizzle rmultiselector = /,/, isSimple = /^.[^:#\[\.,]*$/, slice = Array.prototype.slice, POS = jQuery.expr.match.POS; jQuery.fn.extend({ find: function( selector ) { var ret = this.pushStack( "", "find", selector ), length = 0; for ( var i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( var n = length; n < ret.length; n++ ) { for ( var r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var targets = jQuery( target ); return this.filter(function() { for ( var i = 0, l = targets.length; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && jQuery.filter( selector, this ).length > 0; }, closest: function( selectors, context ) { var ret = [], i, l, cur = this[0]; if ( jQuery.isArray( selectors ) ) { var match, selector, matches = {}, level = 1; if ( cur && selectors.length ) { for ( i = 0, l = selectors.length; i < l; i++ ) { selector = selectors[i]; if ( !matches[selector] ) { matches[selector] = jQuery.expr.match.POS.test( selector ) ? jQuery( selector, context || this.context ) : selector; } } while ( cur && cur.ownerDocument && cur !== context ) { for ( selector in matches ) { match = matches[selector]; if ( match.jquery ? match.index(cur) > -1 : jQuery(cur).is(match) ) { ret.push({ selector: selector, elem: cur, level: level }); } } cur = cur.parentNode; level++; } } return ret; } var pos = POS.test( selectors ) ? jQuery( selectors, context || this.context ) : null; for ( i = 0, l = this.length; i < l; i++ ) { cur = this[i]; while ( cur ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } else { cur = cur.parentNode; if ( !cur || !cur.ownerDocument || cur === context ) { break; } } } } ret = ret.length > 1 ? jQuery.unique(ret) : ret; return this.pushStack( ret, "closest", selectors ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { if ( !elem || typeof elem === "string" ) { return jQuery.inArray( this[0], // If it receives a string, the selector is used // If it receives nothing, the siblings are used elem ? jQuery( elem ) : this.parent().children() ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context || this.context ) : jQuery.makeArray( selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, andSelf: function() { return this.add( this.prevObject ); } }); // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return jQuery.nth( elem, 2, "nextSibling" ); }, prev: function( elem ) { return jQuery.nth( elem, 2, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( elem.parentNode.firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.makeArray( elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 ? jQuery.unique( ret ) : ret; if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, slice.call(arguments).join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, nth: function( cur, result, dir, elem ) { result = result || 1; var num = 0; for ( ; cur; cur = cur[dir] ) { if ( cur.nodeType === 1 && ++num === result ) { break; } } return cur; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return (elem === qualifier) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return (jQuery.inArray( elem, qualifier ) >= 0) === keep; }); } var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnocache = /<(?:script|object|embed|option|style)/i, // checked="checked" or checked (html5) rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, raction = /\=([^="'>\s]+\/)>/g, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }; wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE can't serialize <link> and <script> tags normally if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "div<div>", "</div>" ]; } jQuery.fn.extend({ text: function( text ) { if ( jQuery.isFunction(text) ) { return this.each(function(i) { var self = jQuery( this ); self.text( text.call(this, i, self.text()) ); }); } if ( typeof text !== "object" && text !== undefined ) { return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); } return jQuery.text( this ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append(this); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { return this.each(function() { jQuery( this ).wrapAll( html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } else if ( arguments.length ) { var set = jQuery(arguments[0]); set.push.apply( set, this.toArray() ); return this.pushStack( set, "before", arguments ); } }, after: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } else if ( arguments.length ) { var set = this.pushStack( this, "after", arguments ); set.push.apply( set, jQuery(arguments[0]).toArray() ); return set; } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( events ) { // Do the clone var ret = this.map(function() { if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) { // IE copies events bound via attachEvent when // using cloneNode. Calling detachEvent on the // clone will also remove the events from the orignal // In order to get around this, we use innerHTML. // Unfortunately, this means some modifications to // attributes in IE that are actually only stored // as properties will not be copied (such as the // the name attribute on an input). var html = this.outerHTML, ownerDocument = this.ownerDocument; if ( !html ) { var div = ownerDocument.createElement("div"); div.appendChild( this.cloneNode(true) ); html = div.innerHTML; } return jQuery.clean([html.replace(rinlinejQuery, "") // Handle the case in IE 8 where action=/test/> self-closes a tag .replace(raction, '="$1">') .replace(rleadingWhitespace, "")], ownerDocument)[0]; } else { return this.cloneNode(true); } }); // Copy the events from the original to the clone if ( events === true ) { cloneCopyEvent( this, ret ); cloneCopyEvent( this.find("*"), ret.find("*") ); } // Return the cloned set return ret; }, html: function( value ) { if ( value === undefined ) { return this[0] && this[0].nodeType === 1 ? this[0].innerHTML.replace(rinlinejQuery, "") : null; // See if we can take a shortcut and just use innerHTML } else if ( typeof value === "string" && !rnocache.test( value ) && (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) && !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) { value = value.replace(rxhtmlTag, "<$1></$2>"); try { for ( var i = 0, l = this.length; i < l; i++ ) { // Remove element nodes and prevent memory leaks if ( this[i].nodeType === 1 ) { jQuery.cleanData( this[i].getElementsByTagName("*") ); this[i].innerHTML = value; } } // If using innerHTML throws an exception, use the fallback method } catch(e) { this.empty().append( value ); } } else if ( jQuery.isFunction( value ) ) { this.each(function(i){ var self = jQuery( this ); self.html( value.call(this, i, self.html()) ); }); } else { this.empty().append( value ); } return this; }, replaceWith: function( value ) { if ( this[0] && this[0].parentNode ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery( value ).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery( this ).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } else { return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ); } }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { var results, first, fragment, parent, value = args[0], scripts = []; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback, true ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call(this, i, table ? self.html() : undefined); self.domManip( args, table, callback ); }); } if ( this[0] ) { parent = value && value.parentNode; // If we're in a fragment, just use that instead of building a new one if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) { results = { fragment: parent }; } else { results = jQuery.buildFragment( args, this, scripts ); } fragment = results.fragment; if ( fragment.childNodes.length === 1 ) { first = fragment = fragment.firstChild; } else { first = fragment.firstChild; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); for ( var i = 0, l = this.length; i < l; i++ ) { callback.call( table ? root(this[i], first) : this[i], i > 0 || results.cacheable || this.length > 1 ? fragment.cloneNode(true) : fragment ); } } if ( scripts.length ) { jQuery.each( scripts, evalScript ); } } return this; } }); function root( elem, cur ) { return jQuery.nodeName(elem, "table") ? (elem.getElementsByTagName("tbody")[0] || elem.appendChild(elem.ownerDocument.createElement("tbody"))) : elem; } function cloneCopyEvent(orig, ret) { var i = 0; ret.each(function() { if ( this.nodeName !== (orig[i] && orig[i].nodeName) ) { return; } var oldData = jQuery.data( orig[i++] ), curData = jQuery.data( this, oldData ), events = oldData && oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( var type in events ) { for ( var handler in events[ type ] ) { jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data ); } } } }); } jQuery.buildFragment = function( args, nodes, scripts ) { var fragment, cacheable, cacheresults, doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document); // Only cache "small" (1/2 KB) strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) { cacheable = true; cacheresults = jQuery.fragments[ args[0] ]; if ( cacheresults ) { if ( cacheresults !== 1 ) { fragment = cacheresults; } } } if ( !fragment ) { fragment = doc.createDocumentFragment(); jQuery.clean( args, doc, fragment, scripts ); } if ( cacheable ) { jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1; } return { fragment: fragment, cacheable: cacheable }; }; jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var ret = [], insert = jQuery( selector ), parent = this.length === 1 && this[0].parentNode; if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = (i > 0 ? this.clone(true) : this).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); jQuery.extend({ clean: function( elems, context, fragment, scripts ) { context = context || document; // !context.createElement fails in IE with an error but returns typeof 'object' if ( typeof context.createElement === "undefined" ) { context = context.ownerDocument || context[0] && context[0].ownerDocument || document; } var ret = []; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" && !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else if ( typeof elem === "string" ) { // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Trim whitespace, otherwise indexOf won't work as expected var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(), wrap = wrapMap[ tag ] || wrapMap._default, depth = wrap[0], div = context.createElement("div"); // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> var hasBody = rtbody.test(elem), tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( var j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; } if ( elem.nodeType ) { ret.push( elem ); } else { ret = jQuery.merge( ret, elem ); } } if ( fragment ) { for ( i = 0; ret[i]; i++ ) { if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) { scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] ); } else { if ( ret[i].nodeType === 1 ) { ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) ); } fragment.appendChild( ret[i] ); } } } return ret; }, cleanData: function( elems ) { var data, id, cache = jQuery.cache, special = jQuery.event.special, deleteExpando = jQuery.support.deleteExpando; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { continue; } id = elem[ jQuery.expando ]; if ( id ) { data = cache[ id ]; if ( data && data.events ) { for ( var type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); } else { jQuery.removeEvent( elem, type, data.handle ); } } } if ( deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } delete cache[ id ]; } } } }); function evalScript( i, elem ) { if ( elem.src ) { jQuery.ajax({ url: elem.src, async: false, dataType: "script" }); } else { jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, rdashAlpha = /-([a-z])/ig, rupper = /([A-Z])/g, rnumpx = /^-?\d+(?:px)?$/i, rnum = /^-?\d/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssWidth = [ "Left", "Right" ], cssHeight = [ "Top", "Bottom" ], curCSS, getComputedStyle, currentStyle, fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn.css = function( name, value ) { // Setting 'undefined' is a no-op if ( arguments.length === 2 && value === undefined ) { return this; } return jQuery.access( this, name, value, true, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }); }; jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity", "opacity" ); return ret === "" ? "1" : ret; } else { return elem.style.opacity; } } } }, // Exclude the following css properties to add px cssNumber: { "zIndex": true, "fontWeight": true, "opacity": true, "zoom": true, "lineHeight": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, origName = jQuery.camelCase( name ), style = elem.style, hooks = jQuery.cssHooks[ origName ]; name = jQuery.cssProps[ origName ] || origName; // Check if we're setting a value if ( value !== undefined ) { // Make sure that NaN and null values aren't set. See: #7116 if ( typeof value === "number" && isNaN( value ) || value == null ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( typeof value === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra ) { // Make sure that we're working with the right name var ret, origName = jQuery.camelCase( name ), hooks = jQuery.cssHooks[ origName ]; name = jQuery.cssProps[ origName ] || origName; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) { return ret; // Otherwise, if a way to get the computed value exists, use that } else if ( curCSS ) { return curCSS( elem, name, origName ); } }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var old = {}; // Remember the old values, and insert the new ones for ( var name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } }, camelCase: function( string ) { return string.replace( rdashAlpha, fcamelCase ); } }); // DEPRECATED, Use jQuery.css() instead jQuery.curCSS = jQuery.css; jQuery.each(["height", "width"], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { var val; if ( computed ) { if ( elem.offsetWidth !== 0 ) { val = getWH( elem, name, extra ); } else { jQuery.swap( elem, cssShow, function() { val = getWH( elem, name, extra ); }); } if ( val <= 0 ) { val = curCSS( elem, name, name ); if ( val === "0px" && currentStyle ) { val = currentStyle( elem, name, name ); } if ( val != null ) { // Should return "auto" instead of 0, use 0 for // temporary backwards-compat return val === "" || val === "auto" ? "0px" : val; } } if ( val < 0 || val == null ) { val = elem.style[ name ]; // Should return "auto" instead of 0, use 0 for // temporary backwards-compat return val === "" || val === "auto" ? "0px" : val; } return typeof val === "string" ? val : val + "px"; } }, set: function( elem, value ) { if ( rnumpx.test( value ) ) { // ignore negative width and height values #1599 value = parseFloat(value); if ( value >= 0 ) { return value + "px"; } } else { return value; } } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test((computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "") ? (parseFloat(RegExp.$1) / 100) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // Set the alpha filter to set the opacity var opacity = jQuery.isNaN(value) ? "" : "alpha(opacity=" + value * 100 + ")", filter = style.filter || ""; style.filter = ralpha.test(filter) ? filter.replace(ralpha, opacity) : style.filter + ' ' + opacity; } }; } if ( document.defaultView && document.defaultView.getComputedStyle ) { getComputedStyle = function( elem, newName, name ) { var ret, defaultView, computedStyle; name = name.replace( rupper, "-$1" ).toLowerCase(); if ( !(defaultView = elem.ownerDocument.defaultView) ) { return undefined; } if ( (computedStyle = defaultView.getComputedStyle( elem, null )) ) { ret = computedStyle.getPropertyValue( name ); if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { ret = jQuery.style( elem, name ); } } return ret; }; } if ( document.documentElement.currentStyle ) { currentStyle = function( elem, name ) { var left, rsLeft, ret = elem.currentStyle && elem.currentStyle[ name ], style = elem.style; // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels if ( !rnumpx.test( ret ) && rnum.test( ret ) ) { // Remember the original values left = style.left; rsLeft = elem.runtimeStyle.left; // Put in the new values to get a computed value out elem.runtimeStyle.left = elem.currentStyle.left; style.left = name === "fontSize" ? "1em" : (ret || 0); ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; elem.runtimeStyle.left = rsLeft; } return ret === "" ? "auto" : ret; }; } curCSS = getComputedStyle || currentStyle; function getWH( elem, name, extra ) { var which = name === "width" ? cssWidth : cssHeight, val = name === "width" ? elem.offsetWidth : elem.offsetHeight; if ( extra === "border" ) { return val; } jQuery.each( which, function() { if ( !extra ) { val -= parseFloat(jQuery.css( elem, "padding" + this )) || 0; } if ( extra === "margin" ) { val += parseFloat(jQuery.css( elem, "margin" + this )) || 0; } else { val -= parseFloat(jQuery.css( elem, "border" + this + "Width" )) || 0; } }); return val; } if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { var width = elem.offsetWidth, height = elem.offsetHeight; return (width === 0 && height === 0) || (!jQuery.support.reliableHiddenOffsets && (elem.style.display || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } var jsc = jQuery.now(), rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rselectTextarea = /^(?:select|textarea)/i, rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, rnoContent = /^(?:GET|HEAD)$/, rbracket = /\[\]$/, jsre = /\=\?(&|$)/, rquery = /\?/, rts = /([?&])_=[^&]*/, rurl = /^(\w+:)?\/\/([^\/?#]+)/, r20 = /%20/g, rhash = /#.*$/, // Keep a copy of the old load method _load = jQuery.fn.load; jQuery.fn.extend({ load: function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); // Don't do a request if no elements are being requested } else if ( !this.length ) { return this; } var off = url.indexOf(" "); if ( off >= 0 ) { var selector = url.slice(off, url.length); url = url.slice(0, off); } // Default to a GET request var type = "GET"; // If the second parameter was provided if ( params ) { // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = null; // Otherwise, build a param string } else if ( typeof params === "object" ) { params = jQuery.param( params, jQuery.ajaxSettings.traditional ); type = "POST"; } } var self = this; // Request the remote document jQuery.ajax({ url: url, type: type, dataType: "html", data: params, complete: function( res, status ) { // If successful, inject the HTML into all the matched elements if ( status === "success" || status === "notmodified" ) { // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append(res.responseText.replace(rscript, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result res.responseText ); } if ( callback ) { self.each( callback, [res.responseText, status, res] ); } } }); return this; }, serialize: function() { return jQuery.param(this.serializeArray()); }, serializeArray: function() { return this.map(function() { return this.elements ? jQuery.makeArray(this.elements) : this; }) .filter(function() { return this.name && !this.disabled && (this.checked || rselectTextarea.test(this.nodeName) || rinput.test(this.type)); }) .map(function( i, elem ) { var val = jQuery(this).val(); return val == null ? null : jQuery.isArray(val) ? jQuery.map( val, function( val, i ) { return { name: elem.name, value: val }; }) : { name: elem.name, value: val }; }).get(); } }); // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function( i, o ) { jQuery.fn[o] = function( f ) { return this.bind(o, f); }; }); jQuery.extend({ get: function( url, data, callback, type ) { // shift arguments if data argument was omited if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = null; } return jQuery.ajax({ type: "GET", url: url, data: data, success: callback, dataType: type }); }, getScript: function( url, callback ) { return jQuery.get(url, null, callback, "script"); }, getJSON: function( url, data, callback ) { return jQuery.get(url, data, callback, "json"); }, post: function( url, data, callback, type ) { // shift arguments if data argument was omited if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = {}; } return jQuery.ajax({ type: "POST", url: url, data: data, success: callback, dataType: type }); }, ajaxSetup: function( settings ) { jQuery.extend( jQuery.ajaxSettings, settings ); }, ajaxSettings: { url: location.href, global: true, type: "GET", contentType: "application/x-www-form-urlencoded", processData: true, async: true, /* timeout: 0, data: null, username: null, password: null, traditional: false, */ // This function can be overriden by calling jQuery.ajaxSetup xhr: function() { return new window.XMLHttpRequest(); }, accepts: { xml: "application/xml, text/xml", html: "text/html", script: "text/javascript, application/javascript", json: "application/json, text/javascript", text: "text/plain", _default: "*/*" } }, ajax: function( origSettings ) { var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings), jsonp, status, data, type = s.type.toUpperCase(), noContent = rnoContent.test(type); s.url = s.url.replace( rhash, "" ); // Use original (not extended) context object if it was provided s.context = origSettings && origSettings.context != null ? origSettings.context : s; // convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Handle JSONP Parameter Callbacks if ( s.dataType === "jsonp" ) { if ( type === "GET" ) { if ( !jsre.test( s.url ) ) { s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?"; } } else if ( !s.data || !jsre.test(s.data) ) { s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?"; } s.dataType = "json"; } // Build temporary JSONP function if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) { jsonp = s.jsonpCallback || ("jsonp" + jsc++); // Replace the =? sequence both in the query string and the data if ( s.data ) { s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1"); } s.url = s.url.replace(jsre, "=" + jsonp + "$1"); // We need to make sure // that a JSONP style response is executed properly s.dataType = "script"; // Handle JSONP-style loading var customJsonp = window[ jsonp ]; window[ jsonp ] = function( tmp ) { if ( jQuery.isFunction( customJsonp ) ) { customJsonp( tmp ); } else { // Garbage collect window[ jsonp ] = undefined; try { delete window[ jsonp ]; } catch( jsonpError ) {} } data = tmp; jQuery.handleSuccess( s, xhr, status, data ); jQuery.handleComplete( s, xhr, status, data ); if ( head ) { head.removeChild( script ); } }; } if ( s.dataType === "script" && s.cache === null ) { s.cache = false; } if ( s.cache === false && noContent ) { var ts = jQuery.now(); // try replacing _= if it is there var ret = s.url.replace(rts, "$1_=" + ts); // if nothing was replaced, add timestamp to the end s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : ""); } // If data is available, append data to url for GET/HEAD requests if ( s.data && noContent ) { s.url += (rquery.test(s.url) ? "&" : "?") + s.data; } // Watch for a new set of requests if ( s.global && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // Matches an absolute URL, and saves the domain var parts = rurl.exec( s.url ), remote = parts && (parts[1] && parts[1].toLowerCase() !== location.protocol || parts[2].toLowerCase() !== location.host); // If we're requesting a remote document // and trying to load JSON or Script with a GET if ( s.dataType === "script" && type === "GET" && remote ) { var head = document.getElementsByTagName("head")[0] || document.documentElement; var script = document.createElement("script"); if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Handle Script loading if ( !jsonp ) { var done = false; // Attach handlers for all browsers script.onload = script.onreadystatechange = function() { if ( !done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) { done = true; jQuery.handleSuccess( s, xhr, status, data ); jQuery.handleComplete( s, xhr, status, data ); // Handle memory leak in IE script.onload = script.onreadystatechange = null; if ( head && script.parentNode ) { head.removeChild( script ); } } }; } // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); // We handle everything using the script element injection return undefined; } var requestDone = false; // Create the request object var xhr = s.xhr(); if ( !xhr ) { return; } // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open(type, s.url, s.async, s.username, s.password); } else { xhr.open(type, s.url, s.async); } // Need an extra try/catch for cross domain requests in Firefox 3 try { // Set content-type if data specified and content-body is valid for this type if ( (s.data != null && !noContent) || (origSettings && origSettings.contentType) ) { xhr.setRequestHeader("Content-Type", s.contentType); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[s.url] ) { xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]); } if ( jQuery.etag[s.url] ) { xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]); } } // Set header so the called script knows that it's an XMLHttpRequest // Only send the header if it's not a remote XHR if ( !remote ) { xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); } // Set the Accepts header for the server, depending on the dataType xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ? s.accepts[ s.dataType ] + ", */*; q=0.01" : s.accepts._default ); } catch( headerError ) {} // Allow custom headers/mimetypes and early abort if ( s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false ) { // Handle the global AJAX counter if ( s.global && jQuery.active-- === 1 ) { jQuery.event.trigger( "ajaxStop" ); } // close opended socket xhr.abort(); return false; } if ( s.global ) { jQuery.triggerGlobal( s, "ajaxSend", [xhr, s] ); } // Wait for a response to come back var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) { // The request was aborted if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) { // Opera doesn't call onreadystatechange before this point // so we simulate the call if ( !requestDone ) { jQuery.handleComplete( s, xhr, status, data ); } requestDone = true; if ( xhr ) { xhr.onreadystatechange = jQuery.noop; } // The transfer is complete and the data is available, or the request timed out } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) { requestDone = true; xhr.onreadystatechange = jQuery.noop; status = isTimeout === "timeout" ? "timeout" : !jQuery.httpSuccess( xhr ) ? "error" : s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? "notmodified" : "success"; var errMsg; if ( status === "success" ) { // Watch for, and catch, XML document parse errors try { // process the data (runs the xml through httpData regardless of callback) data = jQuery.httpData( xhr, s.dataType, s ); } catch( parserError ) { status = "parsererror"; errMsg = parserError; } } // Make sure that the request was successful or notmodified if ( status === "success" || status === "notmodified" ) { // JSONP handles its own success callback if ( !jsonp ) { jQuery.handleSuccess( s, xhr, status, data ); } } else { jQuery.handleError( s, xhr, status, errMsg ); } // Fire the complete handlers if ( !jsonp ) { jQuery.handleComplete( s, xhr, status, data ); } if ( isTimeout === "timeout" ) { xhr.abort(); } // Stop memory leaks if ( s.async ) { xhr = null; } } }; // Override the abort handler, if we can (IE 6 doesn't allow it, but that's OK) // Opera doesn't fire onreadystatechange at all on abort try { var oldAbort = xhr.abort; xhr.abort = function() { if ( xhr ) { // oldAbort has no call property in IE7 so // just do it this way, which works in all // browsers Function.prototype.call.call( oldAbort, xhr ); } onreadystatechange( "abort" ); }; } catch( abortError ) {} // Timeout checker if ( s.async && s.timeout > 0 ) { setTimeout(function() { // Check to see if the request is still happening if ( xhr && !requestDone ) { onreadystatechange( "timeout" ); } }, s.timeout); } // Send the data try { xhr.send( noContent || s.data == null ? null : s.data ); } catch( sendError ) { jQuery.handleError( s, xhr, null, sendError ); // Fire the complete handlers jQuery.handleComplete( s, xhr, status, data ); } // firefox 1.5 doesn't fire statechange for sync requests if ( !s.async ) { onreadystatechange(); } // return XMLHttpRequest to allow aborting the request etc. return xhr; }, // Serialize an array of form elements or a set of // key/values into a query string param: function( a, traditional ) { var s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction(value) ? value() : value; s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray(a) || a.jquery ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( var prefix in a ) { buildParams( prefix, a[prefix], traditional, add ); } } // Return the resulting serialization return s.join("&").replace(r20, "+"); } }); function buildParams( prefix, obj, traditional, add ) { if ( jQuery.isArray(obj) && obj.length ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && obj != null && typeof obj === "object" ) { if ( jQuery.isEmptyObject( obj ) ) { add( prefix, "" ); // Serialize object item. } else { jQuery.each( obj, function( k, v ) { buildParams( prefix + "[" + k + "]", v, traditional, add ); }); } } else { // Serialize scalar item. add( prefix, obj ); } } // This is still on the jQuery object... for now // Want to move this to jQuery.ajax some day jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, handleError: function( s, xhr, status, e ) { // If a local callback was specified, fire it if ( s.error ) { s.error.call( s.context, xhr, status, e ); } // Fire the global callback if ( s.global ) { jQuery.triggerGlobal( s, "ajaxError", [xhr, s, e] ); } }, handleSuccess: function( s, xhr, status, data ) { // If a local callback was specified, fire it and pass it the data if ( s.success ) { s.success.call( s.context, data, status, xhr ); } // Fire the global callback if ( s.global ) { jQuery.triggerGlobal( s, "ajaxSuccess", [xhr, s] ); } }, handleComplete: function( s, xhr, status ) { // Process result if ( s.complete ) { s.complete.call( s.context, xhr, status ); } // The request was completed if ( s.global ) { jQuery.triggerGlobal( s, "ajaxComplete", [xhr, s] ); } // Handle the global AJAX counter if ( s.global && jQuery.active-- === 1 ) { jQuery.event.trigger( "ajaxStop" ); } }, triggerGlobal: function( s, type, args ) { (s.context && s.context.url == null ? jQuery(s.context) : jQuery.event).trigger(type, args); }, // Determines if an XMLHttpRequest was successful or not httpSuccess: function( xhr ) { try { // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450 return !xhr.status && location.protocol === "file:" || xhr.status >= 200 && xhr.status < 300 || xhr.status === 304 || xhr.status === 1223; } catch(e) {} return false; }, // Determines if an XMLHttpRequest returns NotModified httpNotModified: function( xhr, url ) { var lastModified = xhr.getResponseHeader("Last-Modified"), etag = xhr.getResponseHeader("Etag"); if ( lastModified ) { jQuery.lastModified[url] = lastModified; } if ( etag ) { jQuery.etag[url] = etag; } return xhr.status === 304; }, httpData: function( xhr, type, s ) { var ct = xhr.getResponseHeader("content-type") || "", xml = type === "xml" || !type && ct.indexOf("xml") >= 0, data = xml ? xhr.responseXML : xhr.responseText; if ( xml && data.documentElement.nodeName === "parsererror" ) { jQuery.error( "parsererror" ); } // Allow a pre-filtering function to sanitize the response // s is checked to keep backwards compatibility if ( s && s.dataFilter ) { data = s.dataFilter( data, type ); } // The filter can actually parse the response if ( typeof data === "string" ) { // Get the JavaScript object, if JSON is used. if ( type === "json" || !type && ct.indexOf("json") >= 0 ) { data = jQuery.parseJSON( data ); // If the type is "script", eval it in global context } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) { jQuery.globalEval( data ); } } return data; } }); /* * Create the request object; Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ if ( window.ActiveXObject ) { jQuery.ajaxSettings.xhr = function() { if ( window.location.protocol !== "file:" ) { try { return new window.XMLHttpRequest(); } catch(xhrError) {} } try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch(activeError) {} }; } // Does this browser support XHR requests? jQuery.support.ajax = !!jQuery.ajaxSettings.xhr(); var elemdisplay = {}, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = /^([+\-]=)?([\d+.\-]+)(.*)$/, timerId, fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ]; jQuery.fn.extend({ show: function( speed, easing, callback ) { var elem, display; if ( speed || speed === 0 ) { return this.animate( genFx("show", 3), speed, easing, callback); } else { for ( var i = 0, j = this.length; i < j; i++ ) { elem = this[i]; display = elem.style.display; // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !jQuery.data(elem, "olddisplay") && display === "none" ) { display = elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( display === "" && jQuery.css( elem, "display" ) === "none" ) { jQuery.data(elem, "olddisplay", defaultDisplay(elem.nodeName)); } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { elem = this[i]; display = elem.style.display; if ( display === "" || display === "none" ) { elem.style.display = jQuery.data(elem, "olddisplay") || ""; } } return this; } }, hide: function( speed, easing, callback ) { if ( speed || speed === 0 ) { return this.animate( genFx("hide", 3), speed, easing, callback); } else { for ( var i = 0, j = this.length; i < j; i++ ) { var display = jQuery.css( this[i], "display" ); if ( display !== "none" ) { jQuery.data( this[i], "olddisplay", display ); } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { this[i].style.display = "none"; } return this; } }, // Save the old toggle function _toggle: jQuery.fn.toggle, toggle: function( fn, fn2, callback ) { var bool = typeof fn === "boolean"; if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) { this._toggle.apply( this, arguments ); } else if ( fn == null || bool ) { this.each(function() { var state = bool ? fn : jQuery(this).is(":hidden"); jQuery(this)[ state ? "show" : "hide" ](); }); } else { this.animate(genFx("toggle", 3), fn, fn2, callback); } return this; }, fadeTo: function( speed, to, easing, callback ) { return this.filter(":hidden").css("opacity", 0).show().end() .animate({opacity: to}, speed, easing, callback); }, animate: function( prop, speed, easing, callback ) { var optall = jQuery.speed(speed, easing, callback); if ( jQuery.isEmptyObject( prop ) ) { return this.each( optall.complete ); } return this[ optall.queue === false ? "each" : "queue" ](function() { // XXX 'this' does not always have a nodeName when running the // test suite var opt = jQuery.extend({}, optall), p, isElement = this.nodeType === 1, hidden = isElement && jQuery(this).is(":hidden"), self = this; for ( p in prop ) { var name = jQuery.camelCase( p ); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; p = name; } if ( prop[p] === "hide" && hidden || prop[p] === "show" && !hidden ) { return opt.complete.call(this); } if ( isElement && ( p === "height" || p === "width" ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height // animated if ( jQuery.css( this, "display" ) === "inline" && jQuery.css( this, "float" ) === "none" ) { if ( !jQuery.support.inlineBlockNeedsLayout ) { this.style.display = "inline-block"; } else { var display = defaultDisplay(this.nodeName); // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( display === "inline" ) { this.style.display = "inline-block"; } else { this.style.display = "inline"; this.style.zoom = 1; } } } } if ( jQuery.isArray( prop[p] ) ) { // Create (if needed) and add to specialEasing (opt.specialEasing = opt.specialEasing || {})[p] = prop[p][1]; prop[p] = prop[p][0]; } } if ( opt.overflow != null ) { this.style.overflow = "hidden"; } opt.curAnim = jQuery.extend({}, prop); jQuery.each( prop, function( name, val ) { var e = new jQuery.fx( self, opt, name ); if ( rfxtypes.test(val) ) { e[ val === "toggle" ? hidden ? "show" : "hide" : val ]( prop ); } else { var parts = rfxnum.exec(val), start = e.cur() || 0; if ( parts ) { var end = parseFloat( parts[2] ), unit = parts[3] || "px"; // We need to compute starting value if ( unit !== "px" ) { jQuery.style( self, name, (end || 1) + unit); start = ((end || 1) / e.cur()) * start; jQuery.style( self, name, start + unit); } // If a +=/-= token was provided, we're doing a relative animation if ( parts[1] ) { end = ((parts[1] === "-=" ? -1 : 1) * end) + start; } e.custom( start, end, unit ); } else { e.custom( start, val, "" ); } } }); // For JS strict compliance return true; }); }, stop: function( clearQueue, gotoEnd ) { var timers = jQuery.timers; if ( clearQueue ) { this.queue([]); } this.each(function() { // go in reverse order so anything added to the queue during the loop is ignored for ( var i = timers.length - 1; i >= 0; i-- ) { if ( timers[i].elem === this ) { if (gotoEnd) { // force the next step to be the last timers[i](true); } timers.splice(i, 1); } } }); // start the next in the queue if the last step wasn't forced if ( !gotoEnd ) { this.dequeue(); } return this; } }); function genFx( type, num ) { var obj = {}; jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() { obj[ this ] = type; }); return obj; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show", 1), slideUp: genFx("hide", 1), slideToggle: genFx("toggle", 1), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.extend({ speed: function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction(easing) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default; // Queueing opt.old = opt.complete; opt.complete = function() { if ( opt.queue !== false ) { jQuery(this).dequeue(); } if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } }; return opt; }, easing: { linear: function( p, n, firstNum, diff ) { return firstNum + diff * p; }, swing: function( p, n, firstNum, diff ) { return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum; } }, timers: [], fx: function( elem, options, prop ) { this.options = options; this.elem = elem; this.prop = prop; if ( !options.orig ) { options.orig = {}; } } }); jQuery.fx.prototype = { // Simple function for setting a style value update: function() { if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this ); }, // Get the current size cur: function() { if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) { return this.elem[ this.prop ]; } var r = parseFloat( jQuery.css( this.elem, this.prop ) ); return r && r > -10000 ? r : 0; }, // Start an animation from one number to another custom: function( from, to, unit ) { var self = this, fx = jQuery.fx; this.startTime = jQuery.now(); this.start = from; this.end = to; this.unit = unit || this.unit || "px"; this.now = this.start; this.pos = this.state = 0; function t( gotoEnd ) { return self.step(gotoEnd); } t.elem = this.elem; if ( t() && jQuery.timers.push(t) && !timerId ) { timerId = setInterval(fx.tick, fx.interval); } }, // Simple 'show' function show: function() { // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.show = true; // Begin the animation // Make sure that we start at a small width/height to avoid any // flash of content this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur()); // Start by showing the element jQuery( this.elem ).show(); }, // Simple 'hide' function hide: function() { // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.hide = true; // Begin the animation this.custom(this.cur(), 0); }, // Each step of an animation step: function( gotoEnd ) { var t = jQuery.now(), done = true; if ( gotoEnd || t >= this.options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); this.options.curAnim[ this.prop ] = true; for ( var i in this.options.curAnim ) { if ( this.options.curAnim[i] !== true ) { done = false; } } if ( done ) { // Reset the overflow if ( this.options.overflow != null && !jQuery.support.shrinkWrapBlocks ) { var elem = this.elem, options = this.options; jQuery.each( [ "", "X", "Y" ], function (index, value) { elem.style[ "overflow" + value ] = options.overflow[index]; } ); } // Hide the element if the "hide" operation was done if ( this.options.hide ) { jQuery(this.elem).hide(); } // Reset the properties, if the item has been hidden or shown if ( this.options.hide || this.options.show ) { for ( var p in this.options.curAnim ) { jQuery.style( this.elem, p, this.options.orig[p] ); } } // Execute the complete function this.options.complete.call( this.elem ); } return false; } else { var n = t - this.startTime; this.state = n / this.options.duration; // Perform the easing function, defaults to swing var specialEasing = this.options.specialEasing && this.options.specialEasing[this.prop]; var defaultEasing = this.options.easing || (jQuery.easing.swing ? "swing" : "linear"); this.pos = jQuery.easing[specialEasing || defaultEasing](this.state, n, 0, 1, this.options.duration); this.now = this.start + ((this.end - this.start) * this.pos); // Perform the next step of the animation this.update(); } return true; } }; jQuery.extend( jQuery.fx, { tick: function() { var timers = jQuery.timers; for ( var i = 0; i < timers.length; i++ ) { if ( !timers[i]() ) { timers.splice(i--, 1); } } if ( !timers.length ) { jQuery.fx.stop(); } }, interval: 13, stop: function() { clearInterval( timerId ); timerId = null; }, speeds: { slow: 600, fast: 200, // Default speed _default: 400 }, step: { opacity: function( fx ) { jQuery.style( fx.elem, "opacity", fx.now ); }, _default: function( fx ) { if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) { fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit; } else { fx.elem[ fx.prop ] = fx.now; } } } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } function defaultDisplay( nodeName ) { if ( !elemdisplay[ nodeName ] ) { var elem = jQuery("<" + nodeName + ">").appendTo("body"), display = elem.css("display"); elem.remove(); if ( display === "none" || display === "" ) { display = "block"; } elemdisplay[ nodeName ] = display; } return elemdisplay[ nodeName ]; } var rtable = /^t(?:able|d|h)$/i, rroot = /^(?:body|html)$/i; if ( "getBoundingClientRect" in document.documentElement ) { jQuery.fn.offset = function( options ) { var elem = this[0], box; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } try { box = elem.getBoundingClientRect(); } catch(e) {} var doc = elem.ownerDocument, docElem = doc.documentElement; // Make sure we're not dealing with a disconnected DOM node if ( !box || !jQuery.contains( docElem, elem ) ) { return box || { top: 0, left: 0 }; } var body = doc.body, win = getWindow(doc), clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, scrollTop = (win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop ), scrollLeft = (win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft), top = box.top + scrollTop - clientTop, left = box.left + scrollLeft - clientLeft; return { top: top, left: left }; }; } else { jQuery.fn.offset = function( options ) { var elem = this[0]; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } jQuery.offset.initialize(); var computedStyle, offsetParent = elem.offsetParent, prevOffsetParent = elem, doc = elem.ownerDocument, docElem = doc.documentElement, body = doc.body, defaultView = doc.defaultView, prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle, top = elem.offsetTop, left = elem.offsetLeft; while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) { if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { break; } computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle; top -= elem.scrollTop; left -= elem.scrollLeft; if ( elem === offsetParent ) { top += elem.offsetTop; left += elem.offsetLeft; if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevOffsetParent = offsetParent; offsetParent = elem.offsetParent; } if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevComputedStyle = computedStyle; } if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) { top += body.offsetTop; left += body.offsetLeft; } if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { top += Math.max( docElem.scrollTop, body.scrollTop ); left += Math.max( docElem.scrollLeft, body.scrollLeft ); } return { top: top, left: left }; }; } jQuery.offset = { initialize: function() { var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.css(body, "marginTop") ) || 0, html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>"; jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } ); container.innerHTML = html; body.insertBefore( container, body.firstChild ); innerDiv = container.firstChild; checkDiv = innerDiv.firstChild; td = innerDiv.nextSibling.firstChild.firstChild; this.doesNotAddBorder = (checkDiv.offsetTop !== 5); this.doesAddBorderForTableAndCells = (td.offsetTop === 5); checkDiv.style.position = "fixed"; checkDiv.style.top = "20px"; // safari subtracts parent border width here which is 5px this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15); checkDiv.style.position = checkDiv.style.top = ""; innerDiv.style.overflow = "hidden"; innerDiv.style.position = "relative"; this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5); this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop); body.removeChild( container ); body = container = innerDiv = checkDiv = table = td = null; jQuery.offset.initialize = jQuery.noop; }, bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; jQuery.offset.initialize(); if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.css(body, "marginTop") ) || 0; left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = (position === "absolute" && jQuery.inArray('auto', [curCSSTop, curCSSLeft]) > -1), props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is absolute if ( calculatePosition ) { curPosition = curElem.position(); } curTop = calculatePosition ? curPosition.top : parseInt( curCSSTop, 10 ) || 0; curLeft = calculatePosition ? curPosition.left : parseInt( curCSSLeft, 10 ) || 0; if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if (options.top != null) { props.top = (options.top - curOffset.top) + curTop; } if (options.left != null) { props.left = (options.left - curOffset.left) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[0] ) { return null; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( ["Left", "Top"], function( i, name ) { var method = "scroll" + name; jQuery.fn[ method ] = function(val) { var elem = this[0], win; if ( !elem ) { return null; } if ( val !== undefined ) { // Set the scroll offset return this.each(function() { win = getWindow( this ); if ( win ) { win.scrollTo( !i ? val : jQuery(win).scrollLeft(), i ? val : jQuery(win).scrollTop() ); } else { this[ method ] = val; } }); } else { win = getWindow( elem ); // Return the scroll offset return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] : jQuery.support.boxModel && win.document.documentElement[ method ] || win.document.body[ method ] : elem[ method ]; } }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each([ "Height", "Width" ], function( i, name ) { var type = name.toLowerCase(); // innerHeight and innerWidth jQuery.fn["inner" + name] = function() { return this[0] ? parseFloat( jQuery.css( this[0], type, "padding" ) ) : null; }; // outerHeight and outerWidth jQuery.fn["outer" + name] = function( margin ) { return this[0] ? parseFloat( jQuery.css( this[0], type, margin ? "margin" : "border" ) ) : null; }; jQuery.fn[ type ] = function( size ) { // Get window width or height var elem = this[0]; if ( !elem ) { return size == null ? null : this; } if ( jQuery.isFunction( size ) ) { return this.each(function( i ) { var self = jQuery( this ); self[ type ]( size.call( this, i, self[ type ]() ) ); }); } if ( jQuery.isWindow( elem ) ) { // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode return elem.document.compatMode === "CSS1Compat" && elem.document.documentElement[ "client" + name ] || elem.document.body[ "client" + name ]; // Get document width or height } else if ( elem.nodeType === 9 ) { // Either scroll[Width/Height] or offset[Width/Height], whichever is greater return Math.max( elem.documentElement["client" + name], elem.body["scroll" + name], elem.documentElement["scroll" + name], elem.body["offset" + name], elem.documentElement["offset" + name] ); // Get or set width or height on the element } else if ( size === undefined ) { var orig = jQuery.css( elem, type ), ret = parseFloat( orig ); return jQuery.isNaN( ret ) ? orig : ret; // Set the width or height on the element (default to pixels if value is unitless) } else { return this.css( type, typeof size === "string" ? size : size + "px" ); } }; }); })(window);
zope2.zodbbrowser
/zope2.zodbbrowser-0.2.tar.gz/zope2.zodbbrowser-0.2/zope2/zodbbrowser/resources/jquery.js
jquery.js
;(function ($) { var $b = $.browser; /* * GENERIC $.layout METHODS - used by all layouts */ $.layout = { // can update code here if $.browser is phased out browser: { mozilla: !!$b.mozilla , webkit: !!$b.webkit || !!$b.safari // webkit = jQ 1.4 , msie: !!$b.msie , isIE6: !!$b.msie && $b.version == 6 , boxModel: false // page must load first, so will be updated set by _create //, version: $b.version - not used } /* * USER UTILITIES */ // calculate and return the scrollbar width, as an integer , scrollbarWidth: function () { return window.scrollbarWidth || $.layout.getScrollbarSize('width'); } , scrollbarHeight: function () { return window.scrollbarHeight || $.layout.getScrollbarSize('height'); } , getScrollbarSize: function (dim) { var $c = $('<div style="position: absolute; top: -10000px; left: -10000px; width: 100px; height: 100px; overflow: scroll;"></div>').appendTo("body"); var d = { width: $c.width() - $c[0].clientWidth, height: $c.height() - $c[0].clientHeight }; $c.remove(); window.scrollbarWidth = d.width; window.scrollbarHeight = d.height; return dim.match(/^(width|height)$/i) ? d[dim] : d; } /** * Returns hash container 'display' and 'visibility' * * @see $.swap() - swaps CSS, runs callback, resets CSS */ , showInvisibly: function ($E, force) { if (!$E) return {}; if (!$E.jquery) $E = $($E); var CSS = { display: $E.css('display') , visibility: $E.css('visibility') }; if (force || CSS.display == "none") { // only if not *already hidden* $E.css({ display: "block", visibility: "hidden" }); // show element 'invisibly' so can be measured return CSS; } else return {}; } /** * Returns data for setting size of an element (container or a pane). * * @see _create(), onWindowResize() for container, plus others for pane * @return JSON Returns a hash of all dimensions: top, bottom, left, right, outerWidth, innerHeight, etc */ , getElemDims: function ($E) { var d = {} // dimensions hash , x = d.css = {} // CSS hash , i = {} // TEMP insets , b, p // TEMP border, padding , off = $E.offset() ; d.offsetLeft = off.left; d.offsetTop = off.top; $.each("Left,Right,Top,Bottom".split(","), function (idx, e) { // e = edge b = x["border" + e] = $.layout.borderWidth($E, e); p = x["padding"+ e] = $.layout.cssNum($E, "padding"+e); i[e] = b + p; // total offset of content from outer side d["inset"+ e] = p; /* WRONG ??? // if BOX MODEL, then 'position' = PADDING (ignore borderWidth) if ($E == $Container) d["inset"+ e] = (browser.boxModel ? p : 0); */ }); d.offsetWidth = $E.innerWidth(); d.offsetHeight = $E.innerHeight(); d.outerWidth = $E.outerWidth(); d.outerHeight = $E.outerHeight(); d.innerWidth = d.outerWidth - i.Left - i.Right; d.innerHeight = d.outerHeight - i.Top - i.Bottom; // TESTING x.width = $E.width(); x.height = $E.height(); return d; } , getElemCSS: function ($E, list) { var CSS = {} , style = $E[0].style , props = list.split(",") , sides = "Top,Bottom,Left,Right".split(",") , attrs = "Color,Style,Width".split(",") , p, s, a, i, j, k ; for (i=0; i < props.length; i++) { p = props[i]; if (p.match(/(border|padding|margin)$/)) for (j=0; j < 4; j++) { s = sides[j]; if (p == "border") for (k=0; k < 3; k++) { a = attrs[k]; CSS[p+s+a] = style[p+s+a]; } else CSS[p+s] = style[p+s]; } else CSS[p] = style[p]; }; return CSS } /** * Contains logic to check boxModel & browser, and return the correct width/height for the current browser/doctype * * @see initPanes(), sizeMidPanes(), initHandles(), sizeHandles() * @param {Array.<Object>} $E Must pass a jQuery object - first element is processed * @param {number=} outerWidth/outerHeight (optional) Can pass a width, allowing calculations BEFORE element is resized * @return {number} Returns the innerWidth/Height of the elem by subtracting padding and borders */ , cssWidth: function ($E, outerWidth) { var b = $.layout.borderWidth , n = $.layout.cssNum ; // a 'calculated' outerHeight can be passed so borders and/or padding are removed if needed if (outerWidth <= 0) return 0; if (!$.layout.browser.boxModel) return outerWidth; // strip border and padding from outerWidth to get CSS Width var W = outerWidth - b($E, "Left") - b($E, "Right") - n($E, "paddingLeft") - n($E, "paddingRight") ; return W > 0 ? W : 0; } , cssHeight: function ($E, outerHeight) { var b = $.layout.borderWidth , n = $.layout.cssNum ; // a 'calculated' outerHeight can be passed so borders and/or padding are removed if needed if (outerHeight <= 0) return 0; if (!$.layout.browser.boxModel) return outerHeight; // strip border and padding from outerHeight to get CSS Height var H = outerHeight - b($E, "Top") - b($E, "Bottom") - n($E, "paddingTop") - n($E, "paddingBottom") ; return H > 0 ? H : 0; } /** * Returns the 'current CSS numeric value' for an element - returns 0 if property does not exist * * @see Called by many methods * @param {Array.<Object>} $E Must pass a jQuery object - first element is processed * @param {string} prop The name of the CSS property, eg: top, width, etc. * @return {*} Usually is used to get an integer value for position (top, left) or size (height, width) */ , cssNum: function ($E, prop) { if (!$E.jquery) $E = $($E); var CSS = $.layout.showInvisibly($E); var val = parseInt($.curCSS($E[0], prop, true), 10) || 0; $E.css( CSS ); // RESET return val; } , borderWidth: function (el, side) { if (el.jquery) el = el[0]; var b = "border"+ side.substr(0,1).toUpperCase() + side.substr(1); // left => Left return $.curCSS(el, b+"Style", true) == "none" ? 0 : (parseInt($.curCSS(el, b+"Width", true), 10) || 0); } /** * SUBROUTINE for preventPrematureSlideClose option * * @param {Object} evt * @param {Object=} el */ , isMouseOverElem: function (evt, el) { var $E = $(el || this) , d = $E.offset() , T = d.top , L = d.left , R = L + $E.outerWidth() , B = T + $E.outerHeight() , x = evt.pageX , y = evt.pageY ; // if X & Y are < 0, probably means is over an open SELECT return ($.layout.browser.msie && x < 0 && y < 0) || ((x >= L && x <= R) && (y >= T && y <= B)); } }; $.fn.layout = function (opts) { /* * ########################### * WIDGET CONFIG & OPTIONS * ########################### */ // LANGUAGE CUSTOMIZATION - will be *externally customizable* in next version var lang = { Pane: "Pane" , Open: "Open" // eg: "Open Pane" , Close: "Close" , Resize: "Resize" , Slide: "Slide Open" , Pin: "Pin" , Unpin: "Un-Pin" , selector: "selector" , msgNoRoom: "Not enough room to show this pane." , errContainerMissing: "UI Layout Initialization Error\n\nThe specified layout-container does not exist." , errCenterPaneMissing: "UI Layout Initialization Error\n\nThe center-pane element does not exist.\n\nThe center-pane is a required element." , errContainerHeight: "UI Layout Initialization Warning\n\nThe layout-container \"CONTAINER\" has no height.\n\nTherefore the layout is 0-height and hence 'invisible'!" , errButton: "Error Adding Button \n\nInvalid " }; // DEFAULT OPTIONS - CHANGE IF DESIRED var options = { name: "" // Not required, but useful for buttons and used for the state-cookie , scrollToBookmarkOnLoad: true // after creating a layout, scroll to bookmark in URL (.../page.htm#myBookmark) , resizeWithWindow: true // bind thisLayout.resizeAll() to the window.resize event , resizeWithWindowDelay: 200 // delay calling resizeAll because makes window resizing very jerky , resizeWithWindowMaxDelay: 0 // 0 = none - force resize every XX ms while window is being resized , onresizeall_start: null // CALLBACK when resizeAll() STARTS - NOT pane-specific , onresizeall_end: null // CALLBACK when resizeAll() ENDS - NOT pane-specific , onload: null // CALLBACK when Layout inits - after options initialized, but before elements , onunload: null // CALLBACK when Layout is destroyed OR onWindowUnload , autoBindCustomButtons: false // search for buttons with ui-layout-button class and auto-bind them , zIndex: null // the PANE zIndex - resizers and masks will be +1 // PANE SETTINGS , defaults: { // default options for 'all panes' - will be overridden by 'per-pane settings' applyDemoStyles: false // NOTE: renamed from applyDefaultStyles for clarity , closable: true // pane can open & close , resizable: true // when open, pane can be resized , slidable: true // when closed, pane can 'slide open' over other panes - closes on mouse-out , initClosed: false // true = init pane as 'closed' , initHidden: false // true = init pane as 'hidden' - no resizer-bar/spacing // SELECTORS //, paneSelector: "" // MUST be pane-specific - jQuery selector for pane , contentSelector: ".ui-layout-content" // INNER div/element to auto-size so only it scrolls, not the entire pane! , contentIgnoreSelector: ".ui-layout-ignore" // element(s) to 'ignore' when measuring 'content' , findNestedContent: false // true = $P.find(contentSelector), false = $P.children(contentSelector) // GENERIC ROOT-CLASSES - for auto-generated classNames , paneClass: "ui-layout-pane" // border-Pane - default: 'ui-layout-pane' , resizerClass: "ui-layout-resizer" // Resizer Bar - default: 'ui-layout-resizer' , togglerClass: "ui-layout-toggler" // Toggler Button - default: 'ui-layout-toggler' , buttonClass: "ui-layout-button" // CUSTOM Buttons - default: 'ui-layout-button-toggle/-open/-close/-pin' // ELEMENT SIZE & SPACING //, size: 100 // MUST be pane-specific -initial size of pane , minSize: 0 // when manually resizing a pane , maxSize: 0 // ditto, 0 = no limit , spacing_open: 6 // space between pane and adjacent panes - when pane is 'open' , spacing_closed: 6 // ditto - when pane is 'closed' , togglerLength_open: 50 // Length = WIDTH of toggler button on north/south sides - HEIGHT on east/west sides , togglerLength_closed: 50 // 100% OR -1 means 'full height/width of resizer bar' - 0 means 'hidden' , togglerAlign_open: "center" // top/left, bottom/right, center, OR... , togglerAlign_closed: "center" // 1 => nn = offset from top/left, -1 => -nn == offset from bottom/right , togglerTip_open: lang.Close // Toggler tool-tip (title) , togglerTip_closed: lang.Open // ditto , togglerContent_open: "" // text or HTML to put INSIDE the toggler , togglerContent_closed: "" // ditto // RESIZING OPTIONS , resizerDblClickToggle: true // , autoResize: true // IF size is 'auto' or a percentage, then recalc 'pixel size' whenever the layout resizes , autoReopen: true // IF a pane was auto-closed due to noRoom, reopen it when there is room? False = leave it closed , resizerDragOpacity: 1 // option for ui.draggable //, resizerCursor: "" // MUST be pane-specific - cursor when over resizer-bar , maskIframesOnResize: true // true = all iframes OR = iframe-selector(s) - adds masking-div during resizing/dragging , resizeNestedLayout: true // true = trigger nested.resizeAll() when a 'pane' of this layout is the 'container' for another , resizeWhileDragging: false // true = LIVE Resizing as resizer is dragged , resizeContentWhileDragging: false // true = re-measure header/footer heights as resizer is dragged // TIPS & MESSAGES - also see lang object , noRoomToOpenTip: lang.msgNoRoom , resizerTip: lang.Resize // Resizer tool-tip (title) , sliderTip: lang.Slide // resizer-bar triggers 'sliding' when pane is closed , sliderCursor: "pointer" // cursor when resizer-bar will trigger 'sliding' , slideTrigger_open: "click" // click, dblclick, mouseenter , slideTrigger_close: "mouseleave"// click, mouseleave , hideTogglerOnSlide: false // when pane is slid-open, should the toggler show? , preventQuickSlideClose: !!($.browser.webkit || $.browser.safari) // Chrome triggers slideClosed as is opening , preventPrematureSlideClose: false // HOT-KEYS & MISC , showOverflowOnHover: false // will bind allowOverflow() utility to pane.onMouseOver , enableCursorHotkey: true // enabled 'cursor' hotkeys //, customHotkey: "" // MUST be pane-specific - EITHER a charCode OR a character , customHotkeyModifier: "SHIFT" // either 'SHIFT', 'CTRL' or 'CTRL+SHIFT' - NOT 'ALT' // PANE ANIMATION // NOTE: fxSss_open & fxSss_close options (eg: fxName_open) are auto-generated if not passed , fxName: "slide" // ('none' or blank), slide, drop, scale , fxSpeed: null // slow, normal, fast, 200, nnn - if passed, will OVERRIDE fxSettings.duration , fxSettings: {} // can be passed, eg: { easing: "easeOutBounce", duration: 1500 } , fxOpacityFix: true // tries to fix opacity in IE to restore anti-aliasing after animation // CALLBACKS , triggerEventsOnLoad: false // true = trigger onopen OR onclose callbacks when layout initializes , triggerEventsWhileDragging: true // true = trigger onresize callback REPEATEDLY if resizeWhileDragging==true , onshow_start: null // CALLBACK when pane STARTS to Show - BEFORE onopen/onhide_start , onshow_end: null // CALLBACK when pane ENDS being Shown - AFTER onopen/onhide_end , onhide_start: null // CALLBACK when pane STARTS to Close - BEFORE onclose_start , onhide_end: null // CALLBACK when pane ENDS being Closed - AFTER onclose_end , onopen_start: null // CALLBACK when pane STARTS to Open , onopen_end: null // CALLBACK when pane ENDS being Opened , onclose_start: null // CALLBACK when pane STARTS to Close , onclose_end: null // CALLBACK when pane ENDS being Closed , onresize_start: null // CALLBACK when pane STARTS being Resized ***FOR ANY REASON*** , onresize_end: null // CALLBACK when pane ENDS being Resized ***FOR ANY REASON*** , onsizecontent_start: null // CALLBACK when sizing of content-element STARTS , onsizecontent_end: null // CALLBACK when sizing of content-element ENDS , onswap_start: null // CALLBACK when pane STARTS to Swap , onswap_end: null // CALLBACK when pane ENDS being Swapped , ondrag_start: null // CALLBACK when pane STARTS being ***MANUALLY*** Resized , ondrag_end: null // CALLBACK when pane ENDS being ***MANUALLY*** Resized } , north: { paneSelector: ".ui-layout-north" , size: "auto" // eg: "auto", "30%", 200 , resizerCursor: "n-resize" // custom = url(myCursor.cur) , customHotkey: "" // EITHER a charCode OR a character } , south: { paneSelector: ".ui-layout-south" , size: "auto" , resizerCursor: "s-resize" , customHotkey: "" } , east: { paneSelector: ".ui-layout-east" , size: 200 , resizerCursor: "e-resize" , customHotkey: "" } , west: { paneSelector: ".ui-layout-west" , size: 200 , resizerCursor: "w-resize" , customHotkey: "" } , center: { paneSelector: ".ui-layout-center" , minWidth: 0 , minHeight: 0 } // STATE MANAGMENT , useStateCookie: false // Enable cookie-based state-management - can fine-tune with cookie.autoLoad/autoSave , cookie: { name: "" // If not specified, will use Layout.name, else just "Layout" , autoSave: true // Save a state cookie when page exits? , autoLoad: true // Load the state cookie when Layout inits? // Cookie Options , domain: "" , path: "" , expires: "" // 'days' to keep cookie - leave blank for 'session cookie' , secure: false // List of options to save in the cookie - must be pane-specific , keys: "north.size,south.size,east.size,west.size,"+ "north.isClosed,south.isClosed,east.isClosed,west.isClosed,"+ "north.isHidden,south.isHidden,east.isHidden,west.isHidden" } }; // PREDEFINED EFFECTS / DEFAULTS var effects = { // LIST *PREDEFINED EFFECTS* HERE, even if effect has no settings slide: { all: { duration: "fast" } // eg: duration: 1000, easing: "easeOutBounce" , north: { direction: "up" } , south: { direction: "down" } , east: { direction: "right"} , west: { direction: "left" } } , drop: { all: { duration: "slow" } // eg: duration: 1000, easing: "easeOutQuint" , north: { direction: "up" } , south: { direction: "down" } , east: { direction: "right"} , west: { direction: "left" } } , scale: { all: { duration: "fast" } } }; // DYNAMIC DATA - IS READ-ONLY EXTERNALLY! var state = { // generate unique ID to use for event.namespace so can unbind only events added by 'this layout' id: "layout"+ new Date().getTime() // code uses alias: sID , initialized: false , container: {} // init all keys , north: {} , south: {} , east: {} , west: {} , center: {} , cookie: {} // State Managment data storage }; // INTERNAL CONFIG DATA - DO NOT CHANGE THIS! var _c = { allPanes: "north,south,west,east,center" , borderPanes: "north,south,west,east" , altSide: { north: "south" , south: "north" , east: "west" , west: "east" } // CSS used in multiple places , hidden: { visibility: "hidden" } , visible: { visibility: "visible" } // layout element settings , zIndex: { // set z-index values here pane_normal: 1 // normal z-index for panes , resizer_normal: 2 // normal z-index for resizer-bars , iframe_mask: 2 // overlay div used to mask pane(s) during resizing , pane_sliding: 100 // applied to *BOTH* the pane and its resizer when a pane is 'slid open' , pane_animate: 1000 // applied to the pane when being animated - not applied to the resizer , resizer_drag: 10000 // applied to the CLONED resizer-bar when being 'dragged' } , resizers: { cssReq: { position: "absolute" , padding: 0 , margin: 0 , fontSize: "1px" , textAlign: "left" // to counter-act "center" alignment! , overflow: "hidden" // prevent toggler-button from overflowing // SEE c.zIndex.resizer_normal } , cssDemo: { // DEMO CSS - applied if: options.PANE.applyDemoStyles=true background: "#DDD" , border: "none" } } , togglers: { cssReq: { position: "absolute" , display: "block" , padding: 0 , margin: 0 , overflow: "hidden" , textAlign: "center" , fontSize: "1px" , cursor: "pointer" , zIndex: 1 } , cssDemo: { // DEMO CSS - applied if: options.PANE.applyDemoStyles=true background: "#AAA" } } , content: { cssReq: { position: "relative" /* contain floated or positioned elements */ } , cssDemo: { // DEMO CSS - applied if: options.PANE.applyDemoStyles=true overflow: "auto" , padding: "10px" } , cssDemoPane: { // DEMO CSS - REMOVE scrolling from 'pane' when it has a content-div overflow: "hidden" , padding: 0 } } , panes: { // defaults for ALL panes - overridden by 'per-pane settings' below cssReq: { position: "absolute" , margin: 0 // SEE c.zIndex.pane_normal } , cssDemo: { // DEMO CSS - applied if: options.PANE.applyDemoStyles=true padding: "10px" , background: "#FFF" , border: "1px solid #BBB" , overflow: "auto" } } , north: { side: "Top" , sizeType: "Height" , dir: "horz" , cssReq: { top: 0 , bottom: "auto" , left: 0 , right: 0 , width: "auto" // height: DYNAMIC } , pins: [] // array of 'pin buttons' to be auto-updated on open/close (classNames) } , south: { side: "Bottom" , sizeType: "Height" , dir: "horz" , cssReq: { top: "auto" , bottom: 0 , left: 0 , right: 0 , width: "auto" // height: DYNAMIC } , pins: [] } , east: { side: "Right" , sizeType: "Width" , dir: "vert" , cssReq: { left: "auto" , right: 0 , top: "auto" // DYNAMIC , bottom: "auto" // DYNAMIC , height: "auto" // width: DYNAMIC } , pins: [] } , west: { side: "Left" , sizeType: "Width" , dir: "vert" , cssReq: { left: 0 , right: "auto" , top: "auto" // DYNAMIC , bottom: "auto" // DYNAMIC , height: "auto" // width: DYNAMIC } , pins: [] } , center: { dir: "center" , cssReq: { left: "auto" // DYNAMIC , right: "auto" // DYNAMIC , top: "auto" // DYNAMIC , bottom: "auto" // DYNAMIC , height: "auto" , width: "auto" } } }; /* * ########################### * INTERNAL HELPER FUNCTIONS * ########################### */ /** * Manages all internal timers */ var timer = { data: {} , set: function (s, fn, ms) { timer.clear(s); timer.data[s] = setTimeout(fn, ms); } , clear: function (s) { var t=timer.data; if (t[s]) {clearTimeout(t[s]); delete t[s];} } }; /** * Returns true if passed param is EITHER a simple string OR a 'string object' - otherwise returns false */ var isStr = function (o) { try { return typeof o == "string" || (typeof o == "object" && o.constructor.toString().match(/string/i) !== null); } catch (e) { return false; } }; /** * Returns a simple string if passed EITHER a simple string OR a 'string object', * else returns the original object */ var str = function (o) { // trim converts 'String object' to a simple string return isStr(o) ? $.trim(o) : o == undefined || o == null ? "" : o; }; /** * min / max * * Aliases for Math methods to simplify coding */ var min = function (x,y) { return Math.min(x,y); }; var max = function (x,y) { return Math.max(x,y); }; /** * Processes the options passed in and transforms them into the format used by layout() * Missing keys are added, and converts the data if passed in 'flat-format' (no sub-keys) * In flat-format, pane-specific-settings are prefixed like: north__optName (2-underscores) * To update effects, options MUST use nested-keys format, with an effects key ??? * * @see initOptions() * @param {Object} d Data/options passed by user - may be a single level or nested levels * @return {Object} Creates a data struture that perfectly matches 'options', ready to be imported */ var _transformData = function (d) { var a, json = { cookie:{}, defaults:{fxSettings:{}}, north:{fxSettings:{}}, south:{fxSettings:{}}, east:{fxSettings:{}}, west:{fxSettings:{}}, center:{fxSettings:{}} }; d = d || {}; if (d.effects || d.cookie || d.defaults || d.north || d.south || d.west || d.east || d.center) json = $.extend( true, json, d ); // already in json format - add to base keys else // convert 'flat' to 'nest-keys' format - also handles 'empty' user-options $.each( d, function (key,val) { a = key.split("__"); if (!a[1] || json[a[0]]) // check for invalid keys json[ a[1] ? a[0] : "defaults" ][ a[1] ? a[1] : a[0] ] = val; }); return json; }; /** * Set an INTERNAL callback to avoid simultaneous animation * Runs only if needed and only if all callbacks are not 'already set' * Called by open() and close() when isLayoutBusy=true * * @param {string} action Either 'open' or 'close' * @param {string} pane A valid border-pane name, eg 'west' * @param {boolean=} param Extra param for callback (optional) */ var _queue = function (action, pane, param) { var tried = []; // if isLayoutBusy, then some pane must be 'moving' $.each(_c.borderPanes.split(","), function (i, p) { if (_c[p].isMoving) { bindCallback(p); // TRY to bind a callback return false; // BREAK } }); // if pane does NOT have a callback, then add one, else follow the callback chain... function bindCallback (p) { var c = _c[p]; if (!c.doCallback) { c.doCallback = true; c.callback = action +","+ pane +","+ (param ? 1 : 0); } else { // try to 'chain' this callback tried.push(p); var cbPane = c.callback.split(",")[1]; // 2nd param of callback is 'pane' // ensure callback target NOT 'itself' and NOT 'target pane' and NOT already tried (avoid loop) if (cbPane != pane && !$.inArray(cbPane, tried) >= 0) bindCallback(cbPane); // RECURSE } } }; /** * RUN the INTERNAL callback for this pane - if one exists * * @param {string} pane A valid border-pane name, eg 'west' */ var _dequeue = function (pane) { var c = _c[pane]; // RESET flow-control flags _c.isLayoutBusy = false; delete c.isMoving; if (!c.doCallback || !c.callback) return; c.doCallback = false; // RESET logic flag // EXECUTE the callback var cb = c.callback.split(",") , param = (cb[2] > 0 ? true : false) ; if (cb[0] == "open") open( cb[1], param ); else if (cb[0] == "close") close( cb[1], param ); if (!c.doCallback) c.callback = null; // RESET - unless callback above enabled it again! }; /** * Executes a Callback function after a trigger event, like resize, open or close * * @param {?string} pane This is passed only so we can pass the 'pane object' to the callback * @param {(string|function())} v_fn Accepts a function name, OR a comma-delimited array: [0]=function name, [1]=argument */ var _execCallback = function (pane, v_fn) { if (!v_fn) return; var fn; try { if (typeof v_fn == "function") fn = v_fn; else if (!isStr(v_fn)) return; else if (v_fn.match(/,/)) { // function name cannot contain a comma, so must be a function name AND a 'name' parameter var args = v_fn.split(","); fn = eval(args[0]); if (typeof fn=="function" && args.length > 1) return fn(args[1]); // pass the argument parsed from 'list' } else // just the name of an external function? fn = eval(v_fn); if (typeof fn=="function") { if (pane && $Ps[pane]) // pass data: pane-name, pane-element, pane-state (copy), pane-options, and layout-name return fn( pane, $Ps[pane], $.extend({},state[pane]), options[pane], options.name ); else // must be a layout/container callback - pass suitable info return fn( Instance, $.extend({},state), options, options.name ); } } catch (ex) {} }; /** * Returns hash container 'display' and 'visibility' * * @see $.swap() - swaps CSS, runs callback, resets CSS * @param {!Object} $E * @param {boolean=} force */ var _showInvisibly = function ($E, force) { if (!$E) return {}; if (!$E.jquery) $E = $($E); var CSS = { display: $E.css('display') , visibility: $E.css('visibility') }; if (force || CSS.display == "none") { // only if not *already hidden* $E.css({ display: "block", visibility: "hidden" }); // show element 'invisibly' so can be measured return CSS; } else return {}; }; /** * cure iframe display issues in IE & other browsers */ var _fixIframe = function (pane) { if (state.browser.mozilla) return; // skip FireFox - it auto-refreshes iframes onShow var $P = $Ps[pane]; // if the 'pane' is an iframe, do it if (state[pane].tagName == "IFRAME") $P.css(_c.hidden).css(_c.visible); else // ditto for any iframes INSIDE the pane $P.find('IFRAME').css(_c.hidden).css(_c.visible); }; /** * Returns the 'current CSS numeric value' for a CSS property - 0 if property does not exist * * @see Called by many methods * @param {Array.<Object>} $E Must pass a jQuery object - first element is processed * @param {string} prop The name of the CSS property, eg: top, width, etc. * @return {(string|number)} Usually used to get an integer value for position (top, left) or size (height, width) */ var _cssNum = function ($E, prop) { if (!$E.jquery) $E = $($E); var CSS = _showInvisibly($E); var val = parseInt($.curCSS($E[0], prop, true), 10) || 0; $E.css( CSS ); // RESET return val; }; /** * @param {!Object} E Can accept a 'pane' (east, west, etc) OR a DOM object OR a jQuery object * @param {string} side Which border (top, left, etc.) is resized * @return {number} Returns the borderWidth */ var _borderWidth = function (E, side) { if (E.jquery) E = E[0]; var b = "border"+ side.substr(0,1).toUpperCase() + side.substr(1); // left => Left return $.curCSS(E, b+"Style", true) == "none" ? 0 : (parseInt($.curCSS(E, b+"Width", true), 10) || 0); }; /** * cssW / cssH / cssSize / cssMinDims * * Contains logic to check boxModel & browser, and return the correct width/height for the current browser/doctype * * @see initPanes(), sizeMidPanes(), initHandles(), sizeHandles() * @param {(string|!Object)} el Can accept a 'pane' (east, west, etc) OR a DOM object OR a jQuery object * @param {number=} outerWidth (optional) Can pass a width, allowing calculations BEFORE element is resized * @return {number} Returns the innerWidth of el by subtracting padding and borders */ var cssW = function (el, outerWidth) { var str = isStr(el) , $E = str ? $Ps[el] : $(el) ; if (isNaN(outerWidth)) // not specified outerWidth = str ? getPaneSize(el) : $E.outerWidth(); // a 'calculated' outerHeight can be passed so borders and/or padding are removed if needed if (outerWidth <= 0) return 0; if (!state.browser.boxModel) return outerWidth; // strip border and padding from outerWidth to get CSS Width var W = outerWidth - _borderWidth($E, "Left") - _borderWidth($E, "Right") - _cssNum($E, "paddingLeft") - _cssNum($E, "paddingRight") ; return W > 0 ? W : 0; }; /** * @param {(string|!Object)} el Can accept a 'pane' (east, west, etc) OR a DOM object OR a jQuery object * @param {number=} outerHeight (optional) Can pass a width, allowing calculations BEFORE element is resized * @return {number} Returns the innerHeight el by subtracting padding and borders */ var cssH = function (el, outerHeight) { var str = isStr(el) , $E = str ? $Ps[el] : $(el) ; if (isNaN(outerHeight)) // not specified outerHeight = str ? getPaneSize(el) : $E.outerHeight(); // a 'calculated' outerHeight can be passed so borders and/or padding are removed if needed if (outerHeight <= 0) return 0; if (!state.browser.boxModel) return outerHeight; // strip border and padding from outerHeight to get CSS Height var H = outerHeight - _borderWidth($E, "Top") - _borderWidth($E, "Bottom") - _cssNum($E, "paddingTop") - _cssNum($E, "paddingBottom") ; return H > 0 ? H : 0; }; /** * @param {string} pane Can accept ONLY a 'pane' (east, west, etc) * @param {number=} outerSize (optional) Can pass a width, allowing calculations BEFORE element is resized * @return {number} Returns the innerHeight/Width of el by subtracting padding and borders */ var cssSize = function (pane, outerSize) { if (_c[pane].dir=="horz") // pane = north or south return cssH(pane, outerSize); else // pane = east or west return cssW(pane, outerSize); }; var cssMinDims = function (pane) { // minWidth/Height means CSS width/height = 1px var dir = _c[pane].dir , d = { minWidth: 1001 - cssW(pane, 1000) , minHeight: 1001 - cssH(pane, 1000) } ; if (dir == "horz") d.minSize = d.minHeight; if (dir == "vert") d.minSize = d.minWidth; return d; }; // TODO: see if these methods can be made more useful... // TODO: *maybe* return cssW/H from these so caller can use this info /** * @param {(string|!Object)} el * @param {number=} outerWidth * @param {boolean=} autoHide */ var setOuterWidth = function (el, outerWidth, autoHide) { var $E = el, w; if (isStr(el)) $E = $Ps[el]; // west else if (!el.jquery) $E = $(el); w = cssW($E, outerWidth); $E.css({ width: w }); if (w > 0) { if (autoHide && $E.data('autoHidden') && $E.innerHeight() > 0) { $E.show().data('autoHidden', false); if (!state.browser.mozilla) // FireFox refreshes iframes - IE doesn't // make hidden, then visible to 'refresh' display after animation $E.css(_c.hidden).css(_c.visible); } } else if (autoHide && !$E.data('autoHidden')) $E.hide().data('autoHidden', true); }; /** * @param {(string|!Object)} el * @param {number=} outerHeight * @param {boolean=} autoHide */ var setOuterHeight = function (el, outerHeight, autoHide) { var $E = el, h; if (isStr(el)) $E = $Ps[el]; // west else if (!el.jquery) $E = $(el); h = cssH($E, outerHeight); $E.css({ height: h, visibility: "visible" }); // may have been 'hidden' by sizeContent if (h > 0 && $E.innerWidth() > 0) { if (autoHide && $E.data('autoHidden')) { $E.show().data('autoHidden', false); if (!state.browser.mozilla) // FireFox refreshes iframes - IE doesn't $E.css(_c.hidden).css(_c.visible); } } else if (autoHide && !$E.data('autoHidden')) $E.hide().data('autoHidden', true); }; /** * @param {(string|!Object)} el * @param {number=} outerSize * @param {boolean=} autoHide */ var setOuterSize = function (el, outerSize, autoHide) { if (_c[pane].dir=="horz") // pane = north or south setOuterHeight(el, outerSize, autoHide); else // pane = east or west setOuterWidth(el, outerSize, autoHide); }; /** * Converts any 'size' params to a pixel/integer size, if not already * If 'auto' or a decimal/percentage is passed as 'size', a pixel-size is calculated * /** * @param {string} pane * @param {(string|number)=} size * @param {string=} dir * @return {number} */ var _parseSize = function (pane, size, dir) { if (!dir) dir = _c[pane].dir; if (isStr(size) && size.match(/%/)) size = parseInt(size, 10) / 100; // convert % to decimal if (size === 0) return 0; else if (size >= 1) return parseInt(size, 10); else if (size > 0) { // percentage, eg: .25 var o = options, avail; if (dir=="horz") // north or south or center.minHeight avail = sC.innerHeight - ($Ps.north ? o.north.spacing_open : 0) - ($Ps.south ? o.south.spacing_open : 0); else if (dir=="vert") // east or west or center.minWidth avail = sC.innerWidth - ($Ps.west ? o.west.spacing_open : 0) - ($Ps.east ? o.east.spacing_open : 0); return Math.floor(avail * size); } else if (pane=="center") return 0; else { // size < 0 || size=='auto' || size==Missing || size==Invalid // auto-size the pane var $P = $Ps[pane] , dim = (dir == "horz" ? "height" : "width") , vis = _showInvisibly($P) // show pane invisibly if hidden , s = $P.css(dim); // SAVE current size ; $P.css(dim, "auto"); size = (dim == "height") ? $P.outerHeight() : $P.outerWidth(); // MEASURE $P.css(dim, s).css(vis); // RESET size & visibility return size; } }; /** * Calculates current 'size' (outer-width or outer-height) of a border-pane - optionally with 'pane-spacing' added * * @param {(string|!Object)} pane * @param {boolean=} inclSpace * @return {number} Returns EITHER Width for east/west panes OR Height for north/south panes - adjusted for boxModel & browser */ var getPaneSize = function (pane, inclSpace) { var $P = $Ps[pane] , o = options[pane] , s = state[pane] , oSp = (inclSpace ? o.spacing_open : 0) , cSp = (inclSpace ? o.spacing_closed : 0) ; if (!$P || s.isHidden) return 0; else if (s.isClosed || (s.isSliding && inclSpace)) return cSp; else if (_c[pane].dir == "horz") return $P.outerHeight() + oSp; else // dir == "vert" return $P.outerWidth() + oSp; }; /** * Calculate min/max pane dimensions and limits for resizing * * @param {string} pane * @param {boolean=} slide */ var setSizeLimits = function (pane, slide) { var o = options[pane] , s = state[pane] , c = _c[pane] , dir = c.dir , side = c.side.toLowerCase() , type = c.sizeType.toLowerCase() , isSliding = (slide != undefined ? slide : s.isSliding) // only open() passes 'slide' param , $P = $Ps[pane] , paneSpacing = o.spacing_open // measure the pane on the *opposite side* from this pane , altPane = _c.altSide[pane] , altS = state[altPane] , $altP = $Ps[altPane] , altPaneSize = (!$altP || altS.isVisible===false || altS.isSliding ? 0 : (dir=="horz" ? $altP.outerHeight() : $altP.outerWidth())) , altPaneSpacing = ((!$altP || altS.isHidden ? 0 : options[altPane][ altS.isClosed !== false ? "spacing_closed" : "spacing_open" ]) || 0) // limitSize prevents this pane from 'overlapping' opposite pane , containerSize = (dir=="horz" ? sC.innerHeight : sC.innerWidth) , minCenterDims = cssMinDims("center") , minCenterSize = dir=="horz" ? max(options.center.minHeight, minCenterDims.minHeight) : max(options.center.minWidth, minCenterDims.minWidth) // if pane is 'sliding', then ignore center and alt-pane sizes - because 'overlays' them , limitSize = (containerSize - paneSpacing - (isSliding ? 0 : (_parseSize("center", minCenterSize, dir) + altPaneSize + altPaneSpacing))) , minSize = s.minSize = max( _parseSize(pane, o.minSize), cssMinDims(pane).minSize ) , maxSize = s.maxSize = min( (o.maxSize ? _parseSize(pane, o.maxSize) : 100000), limitSize ) , r = s.resizerPosition = {} // used to set resizing limits , top = sC.insetTop , left = sC.insetLeft , W = sC.innerWidth , H = sC.innerHeight , rW = o.spacing_open // subtract resizer-width to get top/left position for south/east ; switch (pane) { case "north": r.min = top + minSize; r.max = top + maxSize; break; case "west": r.min = left + minSize; r.max = left + maxSize; break; case "south": r.min = top + H - maxSize - rW; r.max = top + H - minSize - rW; break; case "east": r.min = left + W - maxSize - rW; r.max = left + W - minSize - rW; break; }; }; /** * Returns data for setting the size/position of center pane. Also used to set Height for east/west panes * * @return JSON Returns a hash of all dimensions: top, bottom, left, right, (outer) width and (outer) height */ var calcNewCenterPaneDims = function () { var d = { top: getPaneSize("north", true) // true = include 'spacing' value for pane , bottom: getPaneSize("south", true) , left: getPaneSize("west", true) , right: getPaneSize("east", true) , width: 0 , height: 0 }; // NOTE: sC = state.container // calc center-pane's outer dimensions d.width = sC.innerWidth - d.left - d.right; // outerWidth d.height = sC.innerHeight - d.bottom - d.top; // outerHeight // add the 'container border/padding' to get final positions relative to the container d.top += sC.insetTop; d.bottom += sC.insetBottom; d.left += sC.insetLeft; d.right += sC.insetRight; return d; }; /** * Returns data for setting size of an element (container or a pane). * * @see _create(), onWindowResize() for container, plus others for pane * @return JSON Returns a hash of all dimensions: top, bottom, left, right, outerWidth, innerHeight, etc */ var getElemDims = function ($E) { var d = {} // dimensions hash , x = d.css = {} // CSS hash , i = {} // TEMP insets , b, p // TEMP border, padding , off = $E.offset() ; d.offsetLeft = off.left; d.offsetTop = off.top; $.each("Left,Right,Top,Bottom".split(","), function (idx, e) { b = x["border" + e] = _borderWidth($E, e); p = x["padding"+ e] = _cssNum($E, "padding"+e); i[e] = b + p; // total offset of content from outer side d["inset"+ e] = p; /* WRONG ??? // if BOX MODEL, then 'position' = PADDING (ignore borderWidth) if ($E == $Container) d["inset"+ e] = (state.browser.boxModel ? p : 0); */ }); d.offsetWidth = $E.innerWidth(); // true=include Padding d.offsetHeight = $E.innerHeight(); d.outerWidth = $E.outerWidth(); d.outerHeight = $E.outerHeight(); d.innerWidth = d.outerWidth - i.Left - i.Right; d.innerHeight = d.outerHeight - i.Top - i.Bottom; // TESTING x.width = $E.width(); x.height = $E.height(); return d; }; var getElemCSS = function ($E, list) { var CSS = {} , style = $E[0].style , props = list.split(",") , sides = "Top,Bottom,Left,Right".split(",") , attrs = "Color,Style,Width".split(",") , p, s, a, i, j, k ; for (i=0; i < props.length; i++) { p = props[i]; if (p.match(/(border|padding|margin)$/)) for (j=0; j < 4; j++) { s = sides[j]; if (p == "border") for (k=0; k < 3; k++) { a = attrs[k]; CSS[p+s+a] = style[p+s+a]; } else CSS[p+s] = style[p+s]; } else CSS[p] = style[p]; }; return CSS }; /** * @param {!Object} el * @param {boolean=} allStates */ var getHoverClasses = function (el, allStates) { var $El = $(el) , type = $El.data("layoutRole") , pane = $El.data("layoutEdge") , o = options[pane] , root = o[type +"Class"] , _pane = "-"+ pane // eg: "-west" , _open = "-open" , _closed = "-closed" , _slide = "-sliding" , _hover = "-hover " // NOTE the trailing space , _state = $El.hasClass(root+_closed) ? _closed : _open , _alt = _state == _closed ? _open : _closed , classes = (root+_hover) + (root+_pane+_hover) + (root+_state+_hover) + (root+_pane+_state+_hover) ; if (allStates) // when 'removing' classes, also remove alternate-state classes classes += (root+_alt+_hover) + (root+_pane+_alt+_hover); if (type=="resizer" && $El.hasClass(root+_slide)) classes += (root+_slide+_hover) + (root+_pane+_slide+_hover); return $.trim(classes); }; var addHover = function (evt, el) { var e = el || this; $(e).addClass( getHoverClasses(e) ); //if (evt && $(e).data("layoutRole") == "toggler") evt.stopPropagation(); }; var removeHover = function (evt, el) { var e = el || this; $(e).removeClass( getHoverClasses(e, true) ); }; var onResizerEnter = function (evt) { $('body').disableSelection(); addHover(evt, this); }; var onResizerLeave = function (evt, el) { var e = el || this // el is only passed when called by the timer , pane = $(e).data("layoutEdge") , name = pane +"ResizerLeave" ; timer.clear(name); if (!el) { // 1st call - mouseleave event removeHover(evt, this); // do this on initial call // this method calls itself on a timer because it needs to allow // enough time for dragging to kick-in and set the isResizing flag // dragging has a 100ms delay set, so this delay must be higher timer.set(name, function(){ onResizerLeave(evt, e); }, 200); } // if user is resizing, then dragStop will enableSelection() when done else if (!state[pane].isResizing) // 2nd call - by timer $('body').enableSelection(); }; /* * ########################### * INITIALIZATION METHODS * ########################### */ /** * Initialize the layout - called automatically whenever an instance of layout is created * * @see none - triggered onInit * @return An object pointer to the instance created */ var _create = function () { // initialize config/options initOptions(); var o = options; // onload will CANCEL resizing if returns false if (false === _execCallback(null, o.onload)) return false; // a center pane is required, so make sure it exists if (!getPane('center').length) { alert( lang.errCenterPaneMissing ); return null; } // update options with saved state, if option enabled if (o.useStateCookie && o.cookie.autoLoad) loadCookie(); // Update options from state-cookie // set environment - can update code here if $.browser is phased out state.browser = { mozilla: $.browser.mozilla , webkit: $.browser.webkit || $.browser.safari , msie: $.browser.msie , isIE6: $.browser.msie && $.browser.version == 6 , boxModel: $.support.boxModel //, version: $.browser.version - not used }; // initialize all layout elements initContainer(); // set CSS as needed and init state.container dimensions initPanes(); // size & position panes - calls initHandles() - which calls initResizable() sizeContent(); // AFTER panes & handles have been initialized, size 'content' divs if (o.scrollToBookmarkOnLoad) { var l = self.location; if (l.hash) l.replace( l.hash ); // scrollTo Bookmark } // search for and bind custom-buttons if (o.autoBindCustomButtons) initButtons(); // bind hotkey function - keyDown - if required initHotkeys(); // bind resizeAll() for 'this layout instance' to window.resize event if (o.resizeWithWindow && !$Container.data("layoutRole")) // skip if 'nested' inside a pane $(window).bind("resize."+ sID, windowResize); // bind window.onunload $(window).bind("unload."+ sID, unload); state.initialized = true; }; var windowResize = function () { var delay = Number(options.resizeWithWindowDelay) || 100; // there MUST be some delay! if (delay > 0) { // resizing uses a delay-loop because the resize event fires repeatly - except in FF, but delay anyway timer.clear("winResize"); // if already running timer.set("winResize", function(){ timer.clear("winResize"); timer.clear("winResizeRepeater"); resizeAll(); }, delay); // ALSO set fixed-delay timer, if not already running if (!timer.data["winResizeRepeater"]) setWindowResizeRepeater(); } }; var setWindowResizeRepeater = function () { var delay = Number(options.resizeWithWindowMaxDelay); if (delay > 0) timer.set("winResizeRepeater", function(){ setWindowResizeRepeater(); resizeAll(); }, delay); }; var unload = function () { var o = options; state.cookie = getState(); // save state in case onunload has custom state-management if (o.useStateCookie && o.cookie.autoSave) saveCookie(); _execCallback(null, o.onunload); }; /** * Validate and initialize container CSS and events * * @see _create() */ var initContainer = function () { var $C = $Container // alias , tag = sC.tagName = $C.attr("tagName") , fullPage= (tag == "BODY") , props = "position,margin,padding,border" , CSS = {} ; sC.selector = $C.selector.split(".slice")[0]; sC.ref = tag +"/"+ sC.selector; // used in messages $C .data("layout", Instance) .data("layoutContainer", sID) // unique identifier for internal use ; // SAVE original container CSS for use in destroy() if (!$C.data("layoutCSS")) { // handle props like overflow different for BODY & HTML - has 'system default' values if (fullPage) { CSS = $.extend( getElemCSS($C, props), { height: $C.css("height") , overflow: $C.css("overflow") , overflowX: $C.css("overflowX") , overflowY: $C.css("overflowY") }); // ALSO SAVE <HTML> CSS var $H = $("html"); $H.data("layoutCSS", { height: "auto" // FF would return a fixed px-size! , overflow: $H.css("overflow") , overflowX: $H.css("overflowX") , overflowY: $H.css("overflowY") }); } else // handle props normally for non-body elements CSS = getElemCSS($C, props+",top,bottom,left,right,width,height,overflow,overflowX,overflowY"); $C.data("layoutCSS", CSS); } try { // format html/body if this is a full page layout if (fullPage) { $("html").css({ height: "100%" , overflow: "hidden" , overflowX: "hidden" , overflowY: "hidden" }); $("body").css({ position: "relative" , height: "100%" , overflow: "hidden" , overflowX: "hidden" , overflowY: "hidden" , margin: 0 , padding: 0 // TODO: test whether body-padding could be handled? , border: "none" // a body-border creates problems because it cannot be measured! }); } else { // set required CSS for overflow and position CSS = { overflow: "hidden" } // make sure container will not 'scroll' var p = $C.css("position") , h = $C.css("height") ; // if this is a NESTED layout, then container/outer-pane ALREADY has position and height if (!$C.data("layoutRole")) { if (!p || !p.match(/fixed|absolute|relative/)) CSS.position = "relative"; // container MUST have a 'position' /* if (!h || h=="auto") CSS.height = "100%"; // container MUST have a 'height' */ } $C.css( CSS ); if ($C.is(":visible") && $C.innerHeight() < 2) alert( lang.errContainerHeight.replace(/CONTAINER/, sC.ref) ); } } catch (ex) {} // set current layout-container dimensions $.extend(state.container, getElemDims( $C )); }; /** * Bind layout hotkeys - if options enabled * * @see _create() */ var initHotkeys = function () { // bind keyDown to capture hotkeys, if option enabled for ANY pane $.each(_c.borderPanes.split(","), function (i, pane) { var o = options[pane]; if (o.enableCursorHotkey || o.customHotkey) { $(document).bind("keydown."+ sID, keyDown); // only need to bind this ONCE return false; // BREAK - binding was done } }); }; /** * Build final OPTIONS data * * @see _create() */ var initOptions = function () { // simplify logic by making sure passed 'opts' var has basic keys opts = _transformData( opts ); // TODO: create a compatibility add-on for new UI widget that will transform old option syntax var newOpts = { applyDefaultStyles: "applyDemoStyles" }; renameOpts(opts.defaults); $.each(_c.allPanes.split(","), function (i, pane) { renameOpts(opts[pane]); }); // update default effects, if case user passed key if (opts.effects) { $.extend( effects, opts.effects ); delete opts.effects; } $.extend( options.cookie, opts.cookie ); // see if any 'global options' were specified var globals = "name,zIndex,scrollToBookmarkOnLoad,resizeWithWindow,resizeWithWindowDelay,resizeWithWindowMaxDelay,"+ "onresizeall,onresizeall_start,onresizeall_end,onload,onunload,autoBindCustomButtons,useStateCookie"; $.each(globals.split(","), function (i, key) { if (opts[key] !== undefined) options[key] = opts[key]; else if (opts.defaults[key] !== undefined) { options[key] = opts.defaults[key]; delete opts.defaults[key]; } }); // remove any 'defaults' that MUST be set 'per-pane' $.each("paneSelector,resizerCursor,customHotkey".split(","), function (i, key) { delete opts.defaults[key]; } // is OK if key does not exist ); // now update options.defaults $.extend( true, options.defaults, opts.defaults ); // merge config for 'center-pane' - border-panes handled in the loop below _c.center = $.extend( true, {}, _c.panes, _c.center ); // update config.zIndex values if zIndex option specified var z = options.zIndex; if (z === 0 || z > 0) { _c.zIndex.pane_normal = z; _c.zIndex.resizer_normal = z+1; _c.zIndex.iframe_mask = z+1; } // merge options for 'center-pane' - border-panes handled in the loop below $.extend( options.center, opts.center ); // Most 'default options' do not apply to 'center', so add only those that DO var o_Center = $.extend( true, {}, options.defaults, opts.defaults, options.center ); // TEMP data var optionsCenter = ("paneClass,contentSelector,applyDemoStyles,triggerEventsOnLoad,showOverflowOnHover," + "onresize,onresize_start,onresize_end,resizeNestedLayout,resizeContentWhileDragging," + "onsizecontent,onsizecontent_start,onsizecontent_end").split(","); $.each(optionsCenter, function (i, key) { options.center[key] = o_Center[key]; } ); var o, defs = options.defaults; // create a COMPLETE set of options for EACH border-pane $.each(_c.borderPanes.split(","), function (i, pane) { // apply 'pane-defaults' to CONFIG.[PANE] _c[pane] = $.extend( true, {}, _c.panes, _c[pane] ); // apply 'pane-defaults' + user-options to OPTIONS.PANE o = options[pane] = $.extend( true, {}, options.defaults, options[pane], opts.defaults, opts[pane] ); // make sure we have base-classes if (!o.paneClass) o.paneClass = "ui-layout-pane"; if (!o.resizerClass) o.resizerClass = "ui-layout-resizer"; if (!o.togglerClass) o.togglerClass = "ui-layout-toggler"; // create FINAL fx options for each pane, ie: options.PANE.fxName/fxSpeed/fxSettings[_open|_close] $.each(["_open","_close",""], function (i,n) { var sName = "fxName"+n , sSpeed = "fxSpeed"+n , sSettings = "fxSettings"+n ; // recalculate fxName according to specificity rules o[sName] = opts[pane][sName] // opts.west.fxName_open || opts[pane].fxName // opts.west.fxName || opts.defaults[sName] // opts.defaults.fxName_open || opts.defaults.fxName // opts.defaults.fxName || o[sName] // options.west.fxName_open || o.fxName // options.west.fxName || defs[sName] // options.defaults.fxName_open || defs.fxName // options.defaults.fxName || "none" ; // validate fxName to be sure is a valid effect var fxName = o[sName]; if (fxName == "none" || !$.effects || !$.effects[fxName] || (!effects[fxName] && !o[sSettings] && !o.fxSettings)) fxName = o[sName] = "none"; // effect not loaded, OR undefined FX AND fxSettings not passed // set vars for effects subkeys to simplify logic var fx = effects[fxName] || {} // effects.slide , fx_all = fx.all || {} // effects.slide.all , fx_pane = fx[pane] || {} // effects.slide.west ; // RECREATE the fxSettings[_open|_close] keys using specificity rules o[sSettings] = $.extend( {} , fx_all // effects.slide.all , fx_pane // effects.slide.west , defs.fxSettings || {} // options.defaults.fxSettings , defs[sSettings] || {} // options.defaults.fxSettings_open , o.fxSettings // options.west.fxSettings , o[sSettings] // options.west.fxSettings_open , opts.defaults.fxSettings // opts.defaults.fxSettings , opts.defaults[sSettings] || {} // opts.defaults.fxSettings_open , opts[pane].fxSettings // opts.west.fxSettings , opts[pane][sSettings] || {} // opts.west.fxSettings_open ); // recalculate fxSpeed according to specificity rules o[sSpeed] = opts[pane][sSpeed] // opts.west.fxSpeed_open || opts[pane].fxSpeed // opts.west.fxSpeed (pane-default) || opts.defaults[sSpeed] // opts.defaults.fxSpeed_open || opts.defaults.fxSpeed // opts.defaults.fxSpeed || o[sSpeed] // options.west.fxSpeed_open || o[sSettings].duration // options.west.fxSettings_open.duration || o.fxSpeed // options.west.fxSpeed || o.fxSettings.duration // options.west.fxSettings.duration || defs.fxSpeed // options.defaults.fxSpeed || defs.fxSettings.duration// options.defaults.fxSettings.duration || fx_pane.duration // effects.slide.west.duration || fx_all.duration // effects.slide.all.duration || "normal" // DEFAULT ; }); }); function renameOpts (O) { for (var key in newOpts) { if (O[key] != undefined) { O[newOpts[key]] = O[key]; delete O[key]; } } } }; /** * Initialize module objects, styling, size and position for all panes * * @see _create() */ var getPane = function (pane) { var sel = options[pane].paneSelector if (sel.substr(0,1)==="#") // ID selector // NOTE: elements selected 'by ID' DO NOT have to be 'children' return $Container.find(sel).eq(0); else { // class or other selector var $P = $Container.children(sel).eq(0); // look for the pane nested inside a 'form' element return $P.length ? $P : $Container.children("form:first").children(sel).eq(0); } }; var initPanes = function () { // NOTE: do north & south FIRST so we can measure their height - do center LAST $.each(_c.allPanes.split(","), function (idx, pane) { var o = options[pane] , s = state[pane] , c = _c[pane] , fx = s.fx , dir = c.dir , spacing = o.spacing_open || 0 , isCenter = (pane == "center") , CSS = {} , $P, $C , size, minSize, maxSize ; $Cs[pane] = false; // init $P = $Ps[pane] = getPane(pane); if (!$P.length) { $Ps[pane] = false; // logic return true; // SKIP to next } // SAVE original Pane CSS if (!$P.data("layoutCSS")) { var props = "position,top,left,bottom,right,width,height,overflow,zIndex,display,backgroundColor,padding,margin,border"; $P.data("layoutCSS", getElemCSS($P, props)); } // add basic classes & attributes $P .data("parentLayout", Instance) .data("layoutRole", "pane") .data("layoutEdge", pane) .css(c.cssReq).css("zIndex", _c.zIndex.pane_normal) .css(o.applyDemoStyles ? c.cssDemo : {}) // demo styles .addClass( o.paneClass +" "+ o.paneClass+"-"+pane ) // default = "ui-layout-pane ui-layout-pane-west" - may be a dupe of 'paneSelector' .bind("mouseenter."+ sID, addHover ) .bind("mouseleave."+ sID, removeHover ) ; // see if this pane has a 'scrolling-content element' initContent(pane, false); // false = do NOT sizeContent() - called later if (!isCenter) { // call _parseSize AFTER applying pane classes & styles - but before making visible (if hidden) // if o.size is auto or not valid, then MEASURE the pane and use that as it's 'size' size = s.size = _parseSize(pane, o.size); minSize = _parseSize(pane,o.minSize) || 1; maxSize = _parseSize(pane,o.maxSize) || 100000; if (size > 0) size = max(min(size, maxSize), minSize); // state for border-panes s.isClosed = false; // true = pane is closed s.isSliding = false; // true = pane is currently open by 'sliding' over adjacent panes s.isResizing= false; // true = pane is in process of being resized s.isHidden = false; // true = pane is hidden - no spacing, resizer or toggler is visible! } // state for all panes s.tagName = $P.attr("tagName"); s.edge = pane // useful if pane is (or about to be) 'swapped' - easy find out where it is (or is going) s.noRoom = false; // true = pane 'automatically' hidden due to insufficient room - will unhide automatically s.isVisible = true; // false = pane is invisible - closed OR hidden - simplify logic // set css-position to account for container borders & padding switch (pane) { case "north": CSS.top = sC.insetTop; CSS.left = sC.insetLeft; CSS.right = sC.insetRight; break; case "south": CSS.bottom = sC.insetBottom; CSS.left = sC.insetLeft; CSS.right = sC.insetRight; break; case "west": CSS.left = sC.insetLeft; // top, bottom & height set by sizeMidPanes() break; case "east": CSS.right = sC.insetRight; // ditto break; case "center": // top, left, width & height set by sizeMidPanes() } if (dir == "horz") // north or south pane CSS.height = max(1, cssH(pane, size)); else if (dir == "vert") // east or west pane CSS.width = max(1, cssW(pane, size)); //else if (isCenter) {} $P.css(CSS); // apply size -- top, bottom & height will be set by sizeMidPanes if (dir != "horz") sizeMidPanes(pane, true); // true = skipCallback // NOW make the pane visible - in case was initially hidden $P.css({ visibility: "visible", display: "block" }); // close or hide the pane if specified in settings if (o.initClosed && o.closable) close(pane, true, true); // true, true = force, noAnimation else if (o.initHidden || o.initClosed) hide(pane); // will be completely invisible - no resizer or spacing // ELSE setAsOpen() - called later by initHandles() // check option for auto-handling of pop-ups & drop-downs if (o.showOverflowOnHover) $P.hover( allowOverflow, resetOverflow ); }); /* * init the pane-handles NOW in case we have to hide or close the pane below */ initHandles(); // now that all panes have been initialized and initially-sized, // make sure there is really enough space available for each pane $.each(_c.borderPanes.split(","), function (i, pane) { if ($Ps[pane] && state[pane].isVisible) { // pane is OPEN setSizeLimits(pane); makePaneFit(pane); // pane may be Closed, Hidden or Resized by makePaneFit() } }); // size center-pane AGAIN in case we 'closed' a border-pane in loop above sizeMidPanes("center"); // trigger onResize callbacks for all panes with triggerEventsOnLoad = true $.each(_c.allPanes.split(","), function (i, pane) { var o = options[pane]; if ($Ps[pane] && o.triggerEventsOnLoad && state[pane].isVisible) // pane is OPEN _execCallback(pane, o.onresize_end || o.onresize); // call onresize }); if ($Container.innerHeight() < 2) alert( lang.errContainerHeight.replace(/CONTAINER/, sC.ref) ); }; /** * Initialize module objects, styling, size and position for all resize bars and toggler buttons * * @see _create() * @param {string=} panes The edge(s) to process, blank = all */ var initHandles = function (panes) { if (!panes || panes == "all") panes = _c.borderPanes; // create toggler DIVs for each pane, and set object pointers for them, eg: $R.north = north toggler DIV $.each(panes.split(","), function (i, pane) { var $P = $Ps[pane]; $Rs[pane] = false; // INIT $Ts[pane] = false; if (!$P) return; // pane does not exist - skip var o = options[pane] , s = state[pane] , c = _c[pane] , rClass = o.resizerClass , tClass = o.togglerClass , side = c.side.toLowerCase() , spacing = (s.isVisible ? o.spacing_open : o.spacing_closed) , _pane = "-"+ pane // used for classNames , _state = (s.isVisible ? "-open" : "-closed") // used for classNames // INIT RESIZER BAR , $R = $Rs[pane] = $("<div></div>") // INIT TOGGLER BUTTON , $T = (o.closable ? $Ts[pane] = $("<div></div>") : false) ; //if (s.isVisible && o.resizable) ... handled by initResizable if (!s.isVisible && o.slidable) $R.attr("title", o.sliderTip).css("cursor", o.sliderCursor); $R // if paneSelector is an ID, then create a matching ID for the resizer, eg: "#paneLeft" => "paneLeft-resizer" .attr("id", (o.paneSelector.substr(0,1)=="#" ? o.paneSelector.substr(1) + "-resizer" : "")) .data("parentLayout", Instance) .data("layoutRole", "resizer") .data("layoutEdge", pane) .css(_c.resizers.cssReq).css("zIndex", _c.zIndex.resizer_normal) .css(o.applyDemoStyles ? _c.resizers.cssDemo : {}) // add demo styles .addClass(rClass +" "+ rClass+_pane) .appendTo($Container) // append DIV to container ; if ($T) { $T // if paneSelector is an ID, then create a matching ID for the resizer, eg: "#paneLeft" => "#paneLeft-toggler" .attr("id", (o.paneSelector.substr(0,1)=="#" ? o.paneSelector.substr(1) + "-toggler" : "")) .data("parentLayout", Instance) .data("layoutRole", "toggler") .data("layoutEdge", pane) .css(_c.togglers.cssReq) // add base/required styles .css(o.applyDemoStyles ? _c.togglers.cssDemo : {}) // add demo styles .addClass(tClass +" "+ tClass+_pane) .appendTo($R) // append SPAN to resizer DIV ; // ADD INNER-SPANS TO TOGGLER if (o.togglerContent_open) // ui-layout-open $("<span>"+ o.togglerContent_open +"</span>") .data("layoutRole", "togglerContent") .data("layoutEdge", pane) .addClass("content content-open") .css("display","none") .appendTo( $T ) .hover( addHover, removeHover ) ; if (o.togglerContent_closed) // ui-layout-closed $("<span>"+ o.togglerContent_closed +"</span>") .data("layoutRole", "togglerContent") .data("layoutEdge", pane) .addClass("content content-closed") .css("display","none") .appendTo( $T ) .hover( addHover, removeHover ) ; // ADD TOGGLER.click/.hover enableClosable(pane); } // add Draggable events initResizable(pane); // ADD CLASSNAMES & SLIDE-BINDINGS - eg: class="resizer resizer-west resizer-open" if (s.isVisible) setAsOpen(pane); // onOpen will be called, but NOT onResize else { setAsClosed(pane); // onClose will be called bindStartSlidingEvent(pane, true); // will enable events IF option is set } }); // SET ALL HANDLE DIMENSIONS sizeHandles("all"); }; /** * Initialize scrolling ui-layout-content div - if exists * * @see initPane() - or externally after an Ajax injection * @param {string} pane The pane to process * @param {boolean=} resize Size content after init, default = true */ var initContent = function (pane, resize) { var o = options[pane] , sel = o.contentSelector , $P = $Ps[pane] , $C ; if (sel) $C = $Cs[pane] = (o.findNestedContent) ? $P.find(sel).eq(0) // match 1-element only : $P.children(sel).eq(0) ; if ($C && $C.length) { $C.css( _c.content.cssReq ); if (o.applyDemoStyles) { $C.css( _c.content.cssDemo ); // add padding & overflow: auto to content-div $P.css( _c.content.cssDemoPane ); // REMOVE padding/scrolling from pane } state[pane].content = {}; // init content state if (resize !== false) sizeContent(pane); // sizeContent() is called AFTER init of all elements } else $Cs[pane] = false; }; /** * Searches for .ui-layout-button-xxx elements and auto-binds them as layout-buttons * * @see _create() */ var initButtons = function () { var pre = "ui-layout-button-", name; $.each("toggle,open,close,pin,toggle-slide,open-slide".split(","), function (i, action) { $.each(_c.borderPanes.split(","), function (ii, pane) { $("."+pre+action+"-"+pane).each(function(){ // if button was previously 'bound', data.layoutName was set, but is blank if layout has no 'name' name = $(this).data("layoutName") || $(this).attr("layoutName"); if (name == undefined || name == options.name) bindButton(this, action, pane); }); }); }); }; /** * Add resize-bars to all panes that specify it in options * -dependancy: $.fn.resizable - will skip if not found * * @see _create() * @param {string=} panes The edge(s) to process, blank = all */ var initResizable = function (panes) { var draggingAvailable = (typeof $.fn.draggable == "function") , $Frames, side // set in start() ; if (!panes || panes == "all") panes = _c.borderPanes; $.each(panes.split(","), function (idx, pane) { var o = options[pane] , s = state[pane] , c = _c[pane] , side = (c.dir=="horz" ? "top" : "left") , r, live // set in start because may change ; if (!draggingAvailable || !$Ps[pane] || !o.resizable) { o.resizable = false; return true; // skip to next } var $P = $Ps[pane] , $R = $Rs[pane] , base = o.resizerClass // 'drag' classes are applied to the ORIGINAL resizer-bar while dragging is in process , resizerClass = base+"-drag" // resizer-drag , resizerPaneClass = base+"-"+pane+"-drag" // resizer-north-drag // 'helper' class is applied to the CLONED resizer-bar while it is being dragged , helperClass = base+"-dragging" // resizer-dragging , helperPaneClass = base+"-"+pane+"-dragging" // resizer-north-dragging , helperLimitClass = base+"-dragging-limit" // resizer-drag , helperClassesSet = false // logic var ; if (!s.isClosed) $R .attr("title", o.resizerTip) .css("cursor", o.resizerCursor) // n-resize, s-resize, etc ; $R.bind("mouseenter."+ sID, onResizerEnter) .bind("mouseleave."+ sID, onResizerLeave); $R.draggable({ containment: $Container[0] // limit resizing to layout container , axis: (c.dir=="horz" ? "y" : "x") // limit resizing to horz or vert axis , delay: 0 , distance: 1 // basic format for helper - style it using class: .ui-draggable-dragging , helper: "clone" , opacity: o.resizerDragOpacity , addClasses: false // avoid ui-state-disabled class when disabled //, iframeFix: o.draggableIframeFix // TODO: consider using when bug is fixed , zIndex: _c.zIndex.resizer_drag , start: function (e, ui) { // REFRESH options & state pointers in case we used swapPanes o = options[pane]; s = state[pane]; // re-read options live = o.resizeWhileDragging; // ondrag_start callback - will CANCEL hide if returns false // TODO: dragging CANNOT be cancelled like this, so see if there is a way? if (false === _execCallback(pane, o.ondrag_start)) return false; _c.isLayoutBusy = true; // used by sizePane() logic during a liveResize s.isResizing = true; // prevent pane from closing while resizing timer.clear(pane+"_closeSlider"); // just in case already triggered // SET RESIZER LIMITS - used in drag() setSizeLimits(pane); // update pane/resizer state r = s.resizerPosition; $R.addClass( resizerClass +" "+ resizerPaneClass ); // add drag classes helperClassesSet = false; // reset logic var - see drag() // MASK PANES WITH IFRAMES OR OTHER TROUBLESOME ELEMENTS $Frames = $(o.maskIframesOnResize === true ? "iframe" : o.maskIframesOnResize).filter(":visible"); var id, i=0; // ID incrementer - used when 'resizing' masks during dynamic resizing $Frames.each(function() { id = "ui-layout-mask-"+ (++i); $(this).data("layoutMaskID", id); // tag iframe with corresponding maskID $('<div id="'+ id +'" class="ui-layout-mask ui-layout-mask-'+ pane +'"/>') .css({ background: "#fff" , opacity: "0.001" , zIndex: _c.zIndex.iframe_mask , position: "absolute" , width: this.offsetWidth+"px" , height: this.offsetHeight+"px" }) .css($(this).position()) // top & left -- changed from offset() .appendTo(this.parentNode) // put mask-div INSIDE pane to avoid zIndex issues ; }); // DISABLE TEXT SELECTION (though probably was already by resizer.mouseOver) $('body').disableSelection(); } , drag: function (e, ui) { if (!helperClassesSet) { // can only add classes after clone has been added to the DOM //$(".ui-draggable-dragging") ui.helper .addClass( helperClass +" "+ helperPaneClass ) // add helper classes .children().css("visibility","hidden") // hide toggler inside dragged resizer-bar ; helperClassesSet = true; // draggable bug!? RE-SET zIndex to prevent E/W resize-bar showing through N/S pane! if (s.isSliding) $Ps[pane].css("zIndex", _c.zIndex.pane_sliding); } // CONTAIN RESIZER-BAR TO RESIZING LIMITS var limit = 0; if (ui.position[side] < r.min) { ui.position[side] = r.min; limit = -1; } else if (ui.position[side] > r.max) { ui.position[side] = r.max; limit = 1; } // ADD/REMOVE dragging-limit CLASS if (limit) { ui.helper.addClass( helperLimitClass ); // at dragging-limit window.defaultStatus = "Panel has reached its " + ((limit>0 && pane.match(/north|west/)) || (limit<0 && pane.match(/south|east/)) ? "maximum" : "minimum") +" size"; } else { ui.helper.removeClass( helperLimitClass ); // not at dragging-limit window.defaultStatus = ""; } // DYNAMICALLY RESIZE PANES IF OPTION ENABLED if (live) resizePanes(e, ui, pane); } , stop: function (e, ui) { // RE-ENABLE TEXT SELECTION $('body').enableSelection(); window.defaultStatus = ""; // clear 'resizing limit' message from statusbar $R.removeClass( resizerClass +" "+ resizerPaneClass +" "+ helperLimitClass ); // remove drag classes from Resizer s.isResizing = false; _c.isLayoutBusy = false; // set BEFORE resizePanes so other logic can pick it up resizePanes(e, ui, pane, true); // true = resizingDone } }); /** * resizePanes * * Sub-routine called from stop() and optionally drag() * * @param {!Object} evt * @param {!Object} ui * @param {string} pane * @param {boolean=} resizingDone */ var resizePanes = function (evt, ui, pane, resizingDone) { var dragPos = ui.position , c = _c[pane] , resizerPos, newSize , i = 0 // ID incrementer ; switch (pane) { case "north": resizerPos = dragPos.top; break; case "west": resizerPos = dragPos.left; break; case "south": resizerPos = sC.offsetHeight - dragPos.top - o.spacing_open; break; case "east": resizerPos = sC.offsetWidth - dragPos.left - o.spacing_open; break; }; if (resizingDone) { // Remove OR Resize MASK(S) created in drag.start $("div.ui-layout-mask").each(function() { this.parentNode.removeChild(this); }); //$("div.ui-layout-mask").remove(); // TODO: Is this less efficient? // ondrag_start callback - will CANCEL hide if returns false if (false === _execCallback(pane, o.ondrag_end || o.ondrag)) return false; } else $Frames.each(function() { $("#"+ $(this).data("layoutMaskID")) // get corresponding mask by ID .css($(this).position()) // update top & left .css({ // update width & height width: this.offsetWidth +"px" , height: this.offsetHeight+"px" }) ; }); // remove container margin from resizer position to get the pane size newSize = resizerPos - sC["inset"+ c.side]; manualSizePane(pane, newSize); } }); }; /** * Destroy this layout and reset all elements */ var destroy = function () { // UNBIND layout events and remove global object $(window).unbind("."+ sID); $(document).unbind("."+ sID); var fullPage= (sC.tagName == "BODY") // create list of ALL pane-classes that need to be removed , _open = "-open" , _sliding= "-sliding" , _closed = "-closed" , $P, root, pRoot, pClasses // loop vars ; // loop all panes to remove layout classes, attributes and bindings $.each(_c.allPanes.split(","), function (i, pane) { $P = $Ps[pane]; if (!$P) return true; // no pane - SKIP // REMOVE pane's resizer and toggler elements if (pane != "center") { if ($Ts[pane]) $Ts[pane].remove(); $Rs[pane].remove(); } root = options[pane].paneClass; // default="ui-layout-pane" pRoot = root +"-"+ pane; // eg: "ui-layout-pane-west" pClasses = [ root, root+_open, root+_closed, root+_sliding, // generic classes pRoot, pRoot+_open, pRoot+_closed, pRoot+_sliding // pane-specific classes ]; $.merge(pClasses, getHoverClasses($P, true)); // ADD hover-classes $P .removeClass( pClasses.join(" ") ) // remove ALL pane-classes .removeData("layoutRole") .removeData("layoutEdge") .unbind("."+ sID) // remove ALL Layout events // TODO: remove these extra unbind commands when jQuery is fixed .unbind("mouseenter") .unbind("mouseleave") ; // do NOT reset CSS if this pane is STILL the container of a nested layout! // the nested layout will reset its 'container' when/if it is destroyed if (!$P.data("layoutContainer")) $P.css( $P.data("layoutCSS") ); }); // reset layout-container $Container.removeData("layoutContainer"); // do NOT reset container CSS if is a 'pane' in an outer-layout - ie, THIS layout is 'nested' if (!$Container.data("layoutEdge")) $Container.css( $Container.data("layoutCSS") ); // RESET CSS // for full-page layouts, must also reset the <HTML> CSS if (fullPage) $("html").css( $("html").data("layoutCSS") ); // RESET CSS // trigger state-management and onunload callback unload(); }; /* * ########################### * ACTION METHODS * ########################### */ /** * Completely 'hides' a pane, including its spacing - as if it does not exist * The pane is not actually 'removed' from the source, so can use 'show' to un-hide it * * @param {string} pane The pane being hidden, ie: north, south, east, or west * @param {boolean=} noAnimation */ var hide = function (pane, noAnimation) { var o = options[pane] , s = state[pane] , $P = $Ps[pane] , $R = $Rs[pane] ; if (!$P || s.isHidden) return; // pane does not exist OR is already hidden // onhide_start callback - will CANCEL hide if returns false if (state.initialized && false === _execCallback(pane, o.onhide_start)) return; s.isSliding = false; // just in case // now hide the elements if ($R) $R.hide(); // hide resizer-bar if (!state.initialized || s.isClosed) { s.isClosed = true; // to trigger open-animation on show() s.isHidden = true; s.isVisible = false; $P.hide(); // no animation when loading page sizeMidPanes(_c[pane].dir == "horz" ? "all" : "center"); if (state.initialized || o.triggerEventsOnLoad) _execCallback(pane, o.onhide_end || o.onhide); } else { s.isHiding = true; // used by onclose close(pane, false, noAnimation); // adjust all panes to fit } }; /** * Show a hidden pane - show as 'closed' by default unless openPane = true * * @param {string} pane The pane being opened, ie: north, south, east, or west * @param {boolean=} openPane * @param {boolean=} noAnimation * @param {boolean=} noAlert */ var show = function (pane, openPane, noAnimation, noAlert) { var o = options[pane] , s = state[pane] , $P = $Ps[pane] , $R = $Rs[pane] ; if (!$P || !s.isHidden) return; // pane does not exist OR is not hidden // onshow_start callback - will CANCEL show if returns false if (false === _execCallback(pane, o.onshow_start)) return; s.isSliding = false; // just in case s.isShowing = true; // used by onopen/onclose //s.isHidden = false; - will be set by open/close - if not cancelled // now show the elements //if ($R) $R.show(); - will be shown by open/close if (openPane === false) close(pane, true); // true = force else open(pane, false, noAnimation, noAlert); // adjust all panes to fit }; /** * Toggles a pane open/closed by calling either open or close * * @param {string} pane The pane being toggled, ie: north, south, east, or west * @param {boolean=} slide */ var toggle = function (pane, slide) { if (!isStr(pane)) { pane.stopImmediatePropagation(); // pane = event pane = $(this).data("layoutEdge"); // bound to $R.dblclick } var s = state[str(pane)]; if (s.isHidden) show(pane); // will call 'open' after unhiding it else if (s.isClosed) open(pane, !!slide); else close(pane); }; /** * Utility method used during init or other auto-processes * * @param {string} pane The pane being closed * @param {boolean=} setHandles */ var _closePane = function (pane, setHandles) { var $P = $Ps[pane] , s = state[pane] ; $P.hide(); s.isClosed = true; s.isVisible = false; // UNUSED: if (setHandles) setAsClosed(pane, true); // true = force }; /** * Close the specified pane (animation optional), and resize all other panes as needed * * @param {string} pane The pane being closed, ie: north, south, east, or west * @param {boolean=} force * @param {boolean=} noAnimation * @param {boolean=} skipCallback */ var close = function (pane, force, noAnimation, skipCallback) { if (!state.initialized) { _closePane(pane) return; } var $P = $Ps[pane] , $R = $Rs[pane] , $T = $Ts[pane] , o = options[pane] , s = state[pane] , doFX = !noAnimation && !s.isClosed && (o.fxName_close != "none") // transfer logic vars to temp vars , isShowing = s.isShowing , isHiding = s.isHiding , wasSliding = s.isSliding ; // now clear the logic vars delete s.isShowing; delete s.isHiding; if (!$P || (!o.closable && !isShowing && !isHiding)) return; // invalid request // (!o.resizable && !o.closable) ??? else if (!force && s.isClosed && !isShowing) return; // already closed if (_c.isLayoutBusy) { // layout is 'busy' - probably with an animation _queue("close", pane, force); // set a callback for this action, if possible return; // ABORT } // onclose_start callback - will CANCEL hide if returns false // SKIP if just 'showing' a hidden pane as 'closed' if (!isShowing && false === _execCallback(pane, o.onclose_start)) return; // SET flow-control flags _c[pane].isMoving = true; _c.isLayoutBusy = true; s.isClosed = true; s.isVisible = false; // update isHidden BEFORE sizing panes if (isHiding) s.isHidden = true; else if (isShowing) s.isHidden = false; if (s.isSliding) // pane is being closed, so UNBIND trigger events bindStopSlidingEvents(pane, false); // will set isSliding=false else // resize panes adjacent to this one sizeMidPanes(_c[pane].dir == "horz" ? "all" : "center", false); // false = NOT skipCallback // if this pane has a resizer bar, move it NOW - before animation setAsClosed(pane); // CLOSE THE PANE if (doFX) { // animate the close lockPaneForFX(pane, true); // need to set left/top so animation will work $P.hide( o.fxName_close, o.fxSettings_close, o.fxSpeed_close, function () { lockPaneForFX(pane, false); // undo close_2(); }); } else { // hide the pane without animation $P.hide(); close_2(); }; // SUBROUTINE function close_2 () { if (s.isClosed) { // make sure pane was not 'reopened' before animation finished! bindStartSlidingEvent(pane, true); // will enable if o.slidable = true // if opposite-pane was autoClosed, see if it can be autoOpened now var altPane = _c.altSide[pane]; if (state[ altPane ].noRoom) { setSizeLimits( altPane ); makePaneFit( altPane ); } if (!skipCallback && (state.initialized || o.triggerEventsOnLoad)) { // onclose callback - UNLESS just 'showing' a hidden pane as 'closed' if (!isShowing) _execCallback(pane, o.onclose_end || o.onclose); // onhide OR onshow callback if (isShowing) _execCallback(pane, o.onshow_end || o.onshow); if (isHiding) _execCallback(pane, o.onhide_end || o.onhide); } } // execute internal flow-control callback _dequeue(pane); } }; /** * @param {string} pane The pane just closed, ie: north, south, east, or west */ var setAsClosed = function (pane) { var $P = $Ps[pane] , $R = $Rs[pane] , $T = $Ts[pane] , o = options[pane] , s = state[pane] , side = _c[pane].side.toLowerCase() , inset = "inset"+ _c[pane].side , rClass = o.resizerClass , tClass = o.togglerClass , _pane = "-"+ pane // used for classNames , _open = "-open" , _sliding= "-sliding" , _closed = "-closed" ; $R .css(side, sC[inset]) // move the resizer .removeClass( rClass+_open +" "+ rClass+_pane+_open ) .removeClass( rClass+_sliding +" "+ rClass+_pane+_sliding ) .addClass( rClass+_closed +" "+ rClass+_pane+_closed ) .unbind("dblclick."+ sID) ; // DISABLE 'resizing' when closed - do this BEFORE bindStartSlidingEvent? if (o.resizable && typeof $.fn.draggable == "function") $R .draggable("disable") .removeClass("ui-state-disabled") // do NOT apply disabled styling - not suitable here .css("cursor", "default") .attr("title","") ; // if pane has a toggler button, adjust that too if ($T) { $T .removeClass( tClass+_open +" "+ tClass+_pane+_open ) .addClass( tClass+_closed +" "+ tClass+_pane+_closed ) .attr("title", o.togglerTip_closed) // may be blank ; // toggler-content - if exists $T.children(".content-open").hide(); $T.children(".content-closed").css("display","block"); } // sync any 'pin buttons' syncPinBtns(pane, false); if (state.initialized) { // resize 'length' and position togglers for adjacent panes sizeHandles("all"); } }; /** * Open the specified pane (animation optional), and resize all other panes as needed * * @param {string} pane The pane being opened, ie: north, south, east, or west * @param {boolean=} slide * @param {boolean=} noAnimation * @param {boolean=} noAlert */ var open = function (pane, slide, noAnimation, noAlert) { var $P = $Ps[pane] , $R = $Rs[pane] , $T = $Ts[pane] , o = options[pane] , s = state[pane] , doFX = !noAnimation && s.isClosed && (o.fxName_open != "none") // transfer logic var to temp var , isShowing = s.isShowing ; // now clear the logic var delete s.isShowing; if (!$P || (!o.resizable && !o.closable && !isShowing)) return; // invalid request else if (s.isVisible && !s.isSliding) return; // already open // pane can ALSO be unhidden by just calling show(), so handle this scenario if (s.isHidden && !isShowing) { show(pane, true); return; } if (_c.isLayoutBusy) { // layout is 'busy' - probably with an animation _queue("open", pane, slide); // set a callback for this action, if possible return; // ABORT } // onopen_start callback - will CANCEL hide if returns false if (false === _execCallback(pane, o.onopen_start)) return; // make sure there is enough space available to open the pane setSizeLimits(pane, slide); // update pane-state if (s.minSize > s.maxSize) { // INSUFFICIENT ROOM FOR PANE TO OPEN! syncPinBtns(pane, false); // make sure pin-buttons are reset if (!noAlert && o.noRoomToOpenTip) alert(o.noRoomToOpenTip); return; // ABORT } // SET flow-control flags _c[pane].isMoving = true; _c.isLayoutBusy = true; if (slide) // START Sliding - will set isSliding=true bindStopSlidingEvents(pane, true); // BIND trigger events to close sliding-pane else if (s.isSliding) // PIN PANE (stop sliding) - open pane 'normally' instead bindStopSlidingEvents(pane, false); // UNBIND trigger events - will set isSliding=false else if (o.slidable) bindStartSlidingEvent(pane, false); // UNBIND trigger events s.noRoom = false; // will be reset by makePaneFit if 'noRoom' makePaneFit(pane); s.isVisible = true; s.isClosed = false; // update isHidden BEFORE sizing panes - WHY??? Old? if (isShowing) s.isHidden = false; if (doFX) { // ANIMATE lockPaneForFX(pane, true); // need to set left/top so animation will work $P.show( o.fxName_open, o.fxSettings_open, o.fxSpeed_open, function() { lockPaneForFX(pane, false); // undo open_2(); // continue }); } else {// no animation $P.show(); // just show pane and... open_2(); // continue }; // SUBROUTINE function open_2 () { if (s.isVisible) { // make sure pane was not closed or hidden before animation finished! // cure iframe display issues _fixIframe(pane); // NOTE: if isSliding, then other panes are NOT 'resized' if (!s.isSliding) // resize all panes adjacent to this one sizeMidPanes(_c[pane].dir=="vert" ? "center" : "all", false); // false = NOT skipCallback // set classes, position handles and execute callbacks... setAsOpen(pane); } // internal flow-control callback _dequeue(pane); }; }; /** * @param {string} pane The pane just opened, ie: north, south, east, or west * @param {boolean=} skipCallback */ var setAsOpen = function (pane, skipCallback) { var $P = $Ps[pane] , $R = $Rs[pane] , $T = $Ts[pane] , o = options[pane] , s = state[pane] , side = _c[pane].side.toLowerCase() , inset = "inset"+ _c[pane].side , rClass = o.resizerClass , tClass = o.togglerClass , _pane = "-"+ pane // used for classNames , _open = "-open" , _closed = "-closed" , _sliding= "-sliding" ; $R .css(side, sC[inset] + getPaneSize(pane)) // move the resizer .removeClass( rClass+_closed +" "+ rClass+_pane+_closed ) .addClass( rClass+_open +" "+ rClass+_pane+_open ) ; if (s.isSliding) $R.addClass( rClass+_sliding +" "+ rClass+_pane+_sliding ) else // in case 'was sliding' $R.removeClass( rClass+_sliding +" "+ rClass+_pane+_sliding ) if (o.resizerDblClickToggle) $R.bind("dblclick", toggle ); removeHover( 0, $R ); // remove hover classes if (o.resizable && typeof $.fn.draggable == "function") $R .draggable("enable") .css("cursor", o.resizerCursor) .attr("title", o.resizerTip) ; else if (!s.isSliding) $R.css("cursor", "default"); // n-resize, s-resize, etc // if pane also has a toggler button, adjust that too if ($T) { $T .removeClass( tClass+_closed +" "+ tClass+_pane+_closed ) .addClass( tClass+_open +" "+ tClass+_pane+_open ) .attr("title", o.togglerTip_open) // may be blank ; removeHover( 0, $T ); // remove hover classes // toggler-content - if exists $T.children(".content-closed").hide(); $T.children(".content-open").css("display","block"); } // sync any 'pin buttons' syncPinBtns(pane, !s.isSliding); // update pane-state dimensions - BEFORE resizing content $.extend(s, getElemDims($P)); if (state.initialized) { // resize resizer & toggler sizes for all panes sizeHandles("all"); // resize content every time pane opens - to be sure sizeContent(pane, true); // true = remeasure headers/footers, even if 'isLayoutBusy' } if (!skipCallback && (state.initialized || o.triggerEventsOnLoad) && $P.is(":visible")) { // onopen callback _execCallback(pane, o.onopen_end || o.onopen); // onshow callback - TODO: should this be here? if (s.isShowing) _execCallback(pane, o.onshow_end || o.onshow); // ALSO call onresize because layout-size *may* have changed while pane was closed if (state.initialized) { _execCallback(pane, o.onresize_end || o.onresize); resizeNestedLayout(pane); } } }; /** * slideOpen / slideClose / slideToggle * * Pass-though methods for sliding */ var slideOpen = function (evt_or_pane) { var type = typeof evt_or_pane , pane = (type == "string" ? evt_or_pane : $(this).data("layoutEdge")) ; // prevent event from triggering on NEW resizer binding created below if (type == "object") { evt_or_pane.stopImmediatePropagation(); } if (state[pane].isClosed) open(pane, true); // true = slide - ie, called from here! else // skip 'open' if already open! // TODO: does this use-case make sense??? bindStopSlidingEvents(pane, true); // BIND trigger events to close sliding-pane }; var slideClose = function (evt_or_pane) { var evt = isStr(evt_or_pane) ? null : evt_or_pane $E = (evt ? $(this) : $Ps[evt_or_pane]) , pane= $E.data("layoutEdge") , o = options[pane] , s = state[pane] , $P = $Ps[pane] ; if (s.isClosed || s.isResizing) return; // skip if already closed OR in process of resizing else if (o.slideTrigger_close == "click") close_NOW(); // close immediately onClick else if (o.preventQuickSlideClose && _c.isLayoutBusy) return; // handle Chrome quick-close on slide-open else if (o.preventPrematureSlideClose && evt && $.layout.isMouseOverElem(evt, $P)) return; // handle incorrect mouseleave trigger, like when over a SELECT-list in IE else if (evt) // trigger = mouseleave - use a delay timer.set(pane+"_closeSlider", close_NOW, _c[pane].isMoving ? 1000 : 300); // 1 sec delay if 'opening', else .3 sec else // called programically close_NOW(); /** * SUBROUTINE for timed close * * @param {Object=} evt */ function close_NOW (evt) { if (s.isClosed) // skip 'close' if already closed! bindStopSlidingEvents(pane, false); // UNBIND trigger events else if (!_c[pane].isMoving) close(pane); // close will handle unbinding }; }; var slideToggle = function (pane) { toggle(pane, true); }; /** * Must set left/top on East/South panes so animation will work properly * * @param {string} pane The pane to lock, 'east' or 'south' - any other is ignored! * @param {boolean} doLock true = set left/top, false = remove */ var lockPaneForFX = function (pane, doLock) { var $P = $Ps[pane]; if (doLock) { $P.css({ zIndex: _c.zIndex.pane_animate }); // overlay all elements during animation if (pane=="south") $P.css({ top: sC.insetTop + sC.innerHeight - $P.outerHeight() }); else if (pane=="east") $P.css({ left: sC.insetLeft + sC.innerWidth - $P.outerWidth() }); } else { // animation DONE - RESET CSS // TODO: see if this can be deleted. It causes a quick-close when sliding in Chrome $P.css({ zIndex: (state[pane].isSliding ? _c.zIndex.pane_sliding : _c.zIndex.pane_normal) }); if (pane=="south") $P.css({ top: "auto" }); else if (pane=="east") $P.css({ left: "auto" }); // fix anti-aliasing in IE - only needed for animations that change opacity var o = options[pane]; if (state.browser.msie && o.fxOpacityFix && o.fxName_open != "slide" && $P.css("filter") && $P.css("opacity") == 1) $P[0].style.removeAttribute('filter'); } }; /** * Toggle sliding functionality of a specific pane on/off by adding removing 'slide open' trigger * * @see open(), close() * @param {string} pane The pane to enable/disable, 'north', 'south', etc. * @param {boolean} enable Enable or Disable sliding? */ var bindStartSlidingEvent = function (pane, enable) { var o = options[pane] , $P = $Ps[pane] , $R = $Rs[pane] , trigger = o.slideTrigger_open ; if (!$R || (enable && !o.slidable)) return; // make sure we have a valid event if (trigger.match(/mouseover/)) trigger = o.slideTrigger_open = "mouseenter"; else if (!trigger.match(/click|dblclick|mouseenter/)) trigger = o.slideTrigger_open = "click"; $R // add or remove trigger event [enable ? "bind" : "unbind"](trigger +'.'+ sID, slideOpen) // set the appropriate cursor & title/tip .css("cursor", enable ? o.sliderCursor : "default") .attr("title", enable ? o.sliderTip : "") ; }; /** * Add or remove 'mouseleave' events to 'slide close' when pane is 'sliding' open or closed * Also increases zIndex when pane is sliding open * See bindStartSlidingEvent for code to control 'slide open' * * @see slideOpen(), slideClose() * @param {string} pane The pane to process, 'north', 'south', etc. * @param {boolean} enable Enable or Disable events? */ var bindStopSlidingEvents = function (pane, enable) { var o = options[pane] , s = state[pane] , z = _c.zIndex , trigger = o.slideTrigger_close , action = (enable ? "bind" : "unbind") , $P = $Ps[pane] , $R = $Rs[pane] ; s.isSliding = enable; // logic timer.clear(pane+"_closeSlider"); // just in case // remove 'slideOpen' trigger event from resizer // ALSO will raise the zIndex of the pane & resizer if (enable) bindStartSlidingEvent(pane, false); // RE/SET zIndex - increases when pane is sliding-open, resets to normal when not $P.css("zIndex", enable ? z.pane_sliding : z.pane_normal); $R.css("zIndex", enable ? z.pane_sliding : z.resizer_normal); // make sure we have a valid event if (!trigger.match(/click|mouseleave/)) trigger = o.slideTrigger_close = "mouseleave"; // also catches 'mouseout' // add/remove slide triggers $R[action](trigger, slideClose); // base event on resize // need extra events for mouseleave if (trigger == "mouseleave") { // also close on pane.mouseleave $P[action]("mouseleave."+ sID, slideClose); // cancel timer when mouse moves between 'pane' and 'resizer' $R[action]("mouseenter."+ sID, cancelMouseOut); $P[action]("mouseenter."+ sID, cancelMouseOut); } if (!enable) timer.clear(pane+"_closeSlider"); else if (trigger == "click" && !o.resizable) { // IF pane is not resizable (which already has a cursor and tip) // then set the a cursor & title/tip on resizer when sliding $R.css("cursor", enable ? o.sliderCursor : "default"); $R.attr("title", enable ? o.togglerTip_open : ""); // use Toggler-tip, eg: "Close Pane" } // SUBROUTINE for mouseleave timer clearing function cancelMouseOut (evt) { timer.clear(pane+"_closeSlider"); evt.stopPropagation(); } }; /** * Hides/closes a pane if there is insufficient room - reverses this when there is room again * MUST have already called setSizeLimits() before calling this method * * @param {string} pane The pane being resized * @param {boolean=} isOpening Called from onOpen? * @param {boolean=} skipCallback Should the onresize callback be run? * @param {boolean=} force */ var makePaneFit = function (pane, isOpening, skipCallback, force) { var o = options[pane] , s = state[pane] , c = _c[pane] , $P = $Ps[pane] , $R = $Rs[pane] , isSidePane = c.dir=="vert" , hasRoom = false ; // special handling for center pane if (pane == "center" || (isSidePane && s.noVerticalRoom)) { // see if there is enough room to display the center-pane hasRoom = s.minHeight <= s.maxHeight && (isSidePane || s.minWidth <= s.maxWidth); if (hasRoom && s.noRoom) { // previously hidden due to noRoom, so show now $P.show(); if ($R) $R.show(); s.isVisible = true; s.noRoom = false; if (isSidePane) s.noVerticalRoom = false; _fixIframe(pane); } else if (!hasRoom && !s.noRoom) { // not currently hidden, so hide now $P.hide(); if ($R) $R.hide(); s.isVisible = false; s.noRoom = true; } } // see if there is enough room to fit the border-pane if (pane == "center") { // ignore center in this block } else if (s.minSize <= s.maxSize) { // pane CAN fit hasRoom = true; if (s.size > s.maxSize) // pane is too big - shrink it sizePane(pane, s.maxSize, skipCallback, force); else if (s.size < s.minSize) // pane is too small - enlarge it sizePane(pane, s.minSize, skipCallback, force); else if ($R && $P.is(":visible")) { // make sure resizer-bar is positioned correctly // handles situation where nested layout was 'hidden' when initialized var side = c.side.toLowerCase() , pos = s.size + sC["inset"+ c.side] ; if (_cssNum($R, side) != pos) $R.css( side, pos ); } // if was previously hidden due to noRoom, then RESET because NOW there is room if (s.noRoom) { // s.noRoom state will be set by open or show if (s.wasOpen && o.closable) { if (o.autoReopen) open(pane, false, true, true); // true = noAnimation, true = noAlert else // leave the pane closed, so just update state s.noRoom = false; } else show(pane, s.wasOpen, true, true); // true = noAnimation, true = noAlert } } else { // !hasRoom - pane CANNOT fit if (!s.noRoom) { // pane not set as noRoom yet, so hide or close it now... s.noRoom = true; // update state s.wasOpen = !s.isClosed && !s.isSliding; if (s.isClosed){} // SKIP else if (o.closable) // 'close' if possible close(pane, true, true); // true = force, true = noAnimation else // 'hide' pane if cannot just be closed hide(pane, true); // true = noAnimation } } }; /** * sizePane / manualSizePane * sizePane is called only by internal methods whenever a pane needs to be resized * manualSizePane is an exposed flow-through method allowing extra code when pane is 'manually resized' * * @param {string} pane The pane being resized * @param {number} size The *desired* new size for this pane - will be validated * @param {boolean=} skipCallback Should the onresize callback be run? */ var manualSizePane = function (pane, size, skipCallback) { // ANY call to sizePane will disabled autoResize var o = options[pane] // if resizing callbacks have been delayed and resizing is now DONE, force resizing to complete... , forceResize = o.resizeWhileDragging && !_c.isLayoutBusy // && !o.triggerEventsWhileDragging ; o.autoResize = false; // flow-through... sizePane(pane, size, skipCallback, forceResize); } /** * @param {string} pane The pane being resized * @param {number} size The *desired* new size for this pane - will be validated * @param {boolean=} skipCallback Should the onresize callback be run? * @param {boolean=} force Force resizing even if does not seem necessary */ var sizePane = function (pane, size, skipCallback, force) { var o = options[pane] , s = state[pane] , $P = $Ps[pane] , $R = $Rs[pane] , side = _c[pane].side.toLowerCase() , inset = "inset"+ _c[pane].side , skipResizeWhileDragging = _c.isLayoutBusy && !o.triggerEventsWhileDragging , oldSize ; // calculate 'current' min/max sizes setSizeLimits(pane); // update pane-state oldSize = s.size; size = _parseSize(pane, size); // handle percentages & auto size = max(size, _parseSize(pane, o.minSize)); size = min(size, s.maxSize); if (size < s.minSize) { // not enough room for pane! makePaneFit(pane, false, skipCallback); // will hide or close pane return; } // IF newSize is same as oldSize, then nothing to do - abort if (!force && size == oldSize) return; // onresize_start callback CANNOT cancel resizing because this would break the layout! if (!skipCallback && state.initialized && s.isVisible) _execCallback(pane, o.onresize_start); // resize the pane, and make sure its visible $P.css( _c[pane].sizeType.toLowerCase(), max(1, cssSize(pane, size)) ); // update pane-state dimensions s.size = size; $.extend(s, getElemDims($P)); // reposition the resizer-bar if ($R && $P.is(":visible")) $R.css( side, size + sC[inset] ); sizeContent(pane); if (!skipCallback && !skipResizeWhileDragging && state.initialized && s.isVisible) { _execCallback(pane, o.onresize_end || o.onresize); resizeNestedLayout(pane); } // resize all the adjacent panes, and adjust their toggler buttons // when skipCallback passed, it means the controlling method will handle 'other panes' if (!skipCallback) { // also no callback if live-resize is in progress and NOT triggerEventsWhileDragging if (!s.isSliding) sizeMidPanes(_c[pane].dir=="horz" ? "all" : "center", skipResizeWhileDragging, force); sizeHandles("all"); } // if opposite-pane was autoClosed, see if it can be autoOpened now var altPane = _c.altSide[pane]; if (size < oldSize && state[ altPane ].noRoom) { setSizeLimits( altPane ); makePaneFit( altPane, false, skipCallback ); } }; /** * @see initPanes(), sizePane(), resizeAll(), open(), close(), hide() * @param {string} panes The pane(s) being resized, comma-delmited string * @param {boolean=} skipCallback Should the onresize callback be run? * @param {boolean=} force */ var sizeMidPanes = function (panes, skipCallback, force) { if (!panes || panes == "all") panes = "east,west,center"; $.each(panes.split(","), function (i, pane) { if (!$Ps[pane]) return; // NO PANE - skip var o = options[pane] , s = state[pane] , $P = $Ps[pane] , $R = $Rs[pane] , isCenter= (pane=="center") , hasRoom = true , CSS = {} , d = calcNewCenterPaneDims() ; // update pane-state dimensions $.extend(s, getElemDims($P)); if (pane == "center") { if (!force && s.isVisible && d.width == s.outerWidth && d.height == s.outerHeight) return true; // SKIP - pane already the correct size // set state for makePaneFit() logic $.extend(s, cssMinDims(pane), { maxWidth: d.width , maxHeight: d.height }); CSS = d; // convert OUTER width/height to CSS width/height CSS.width = cssW(pane, d.width); CSS.height = cssH(pane, d.height); hasRoom = CSS.width > 0 && CSS.height > 0; // during layout init, try to shrink east/west panes to make room for center if (!hasRoom && !state.initialized && o.minWidth > 0) { var reqPx = o.minWidth - s.outerWidth , minE = options.east.minSize || 0 , minW = options.west.minSize || 0 , sizeE = state.east.size , sizeW = state.west.size , newE = sizeE , newW = sizeW ; if (reqPx > 0 && state.east.isVisible && sizeE > minE) { newE = max( sizeE-minE, sizeE-reqPx ); reqPx -= sizeE-newE; } if (reqPx > 0 && state.west.isVisible && sizeW > minW) { newW = max( sizeW-minW, sizeW-reqPx ); reqPx -= sizeW-newW; } // IF we found enough extra space, then resize the border panes as calculated if (reqPx == 0) { if (sizeE != minE) sizePane('east', newE, true); // true = skipCallback - initPanes will handle when done if (sizeW != minW) sizePane('west', newW, true); // now start over! sizeMidPanes('center', skipCallback, force); return; // abort this loop } } } else { // for east and west, set only the height, which is same as center height // set state.min/maxWidth/Height for makePaneFit() logic if (s.isVisible && !s.noVerticalRoom) $.extend(s, getElemDims($P), cssMinDims(pane)) if (!force && !s.noVerticalRoom && d.height == s.outerHeight) return true; // SKIP - pane already the correct size CSS.top = d.top; CSS.bottom = d.bottom; CSS.height = cssH(pane, d.height); s.maxHeight = max(0, CSS.height); hasRoom = (s.maxHeight > 0); if (!hasRoom) s.noVerticalRoom = true; // makePaneFit() logic } if (hasRoom) { // resizeAll passes skipCallback because it triggers callbacks after ALL panes are resized if (!skipCallback && state.initialized) _execCallback(pane, o.onresize_start); $P.css(CSS); // apply the CSS to pane if (s.isVisible) { $.extend(s, getElemDims($P)); // update pane dimensions if (s.noRoom) makePaneFit(pane); // will re-open/show auto-closed/hidden pane if (state.initialized) sizeContent(pane); // also resize the contents, if exists } } else if (!s.noRoom && s.isVisible) // no room for pane makePaneFit(pane); // will hide or close pane /* * Extra CSS for IE6 or IE7 in Quirks-mode - add 'width' to NORTH/SOUTH panes * Normally these panes have only 'left' & 'right' positions so pane auto-sizes * ALSO required when pane is an IFRAME because will NOT default to 'full width' */ if (pane == "center") { // finished processing midPanes var b = state.browser; var fix = b.isIE6 || (b.msie && !b.boxModel); if ($Ps.north && (fix || state.north.tagName=="IFRAME")) $Ps.north.css("width", cssW($Ps.north, sC.innerWidth)); if ($Ps.south && (fix || state.south.tagName=="IFRAME")) $Ps.south.css("width", cssW($Ps.south, sC.innerWidth)); } // resizeAll passes skipCallback because it triggers callbacks after ALL panes are resized if (!skipCallback && state.initialized && s.isVisible) { _execCallback(pane, o.onresize_end || o.onresize); resizeNestedLayout(pane); } }); }; /** * @see window.onresize(), callbacks or custom code */ var resizeAll = function () { var oldW = sC.innerWidth , oldH = sC.innerHeight ; $.extend( state.container, getElemDims( $Container ) ); // UPDATE container dimensions if (!sC.outerHeight) return; // cannot size layout when 'container' is hidden or collapsed // onresizeall_start will CANCEL resizing if returns false // state.container has already been set, so user can access this info for calcuations if (false === _execCallback(null, options.onresizeall_start)) return false; var // see if container is now 'smaller' than before shrunkH = (sC.innerHeight < oldH) , shrunkW = (sC.innerWidth < oldW) , $P, o, s, dir ; // NOTE special order for sizing: S-N-E-W $.each(["south","north","east","west"], function (i, pane) { if (!$Ps[pane]) return; // no pane - SKIP s = state[pane]; o = options[pane]; dir = _c[pane].dir; if (o.autoResize && s.size != o.size) // resize pane to original size set in options sizePane(pane, o.size, true, true); // true=skipCallback, true=forceResize else { setSizeLimits(pane); makePaneFit(pane, false, true, true); // true=skipCallback, true=forceResize } }); sizeMidPanes("all", true, true); // true=skipCallback, true=forceResize sizeHandles("all"); // reposition the toggler elements // trigger all individual pane callbacks AFTER layout has finished resizing o = options; // reuse alias $.each(_c.allPanes.split(","), function (i, pane) { $P = $Ps[pane]; if (!$P) return; // SKIP if (state[pane].isVisible) // undefined for non-existent panes _execCallback(pane, o[pane].onresize_end || o[pane].onresize); // callback - if exists resizeNestedLayout(pane); }); _execCallback(null, o.onresizeall_end || o.onresizeall); // onresizeall callback, if exists }; /** * Whenever a pane resizes or opens that has a nested layout, trigger resizeAll * * @param {string} pane The pane just resized or opened */ var resizeNestedLayout = function (pane) { var $P = $Ps[pane] , $C = $Cs[pane] , d = "layoutContainer" ; if (options[pane].resizeNestedLayout) { if ($P.data( d )) $P.layout().resizeAll(); else if ($C && $C.data( d )) $C.layout().resizeAll(); } }; /** * IF pane has a content-div, then resize all elements inside pane to fit pane-height * * @param {string=} panes The pane(s) being resized * @param {boolean=} remeasure Should the content (header/footer) be remeasured? */ var sizeContent = function (panes, remeasure) { if (!panes || panes == "all") panes = _c.allPanes; $.each(panes.split(","), function (idx, pane) { var $P = $Ps[pane] , $C = $Cs[pane] , o = options[pane] , s = state[pane] , m = s.content // m = measurements ; if (!$P || !$C || !$P.is(":visible")) return true; // NOT VISIBLE - skip // onsizecontent_start will CANCEL resizing if returns false if (false === _execCallback(null, o.onsizecontent_start)) return; // skip re-measuring offsets if live-resizing if (!_c.isLayoutBusy || m.top == undefined || remeasure || o.resizeContentWhileDragging) { _measure(); // if any footers are below pane-bottom, they may not measure correctly, // so allow pane overflow and re-measure if (m.hiddenFooters > 0 && $P.css("overflow") == "hidden") { $P.css("overflow", "visible"); _measure(); // remeasure while overflowing $P.css("overflow", "hidden"); } } // NOTE: spaceAbove/Below *includes* the pane's paddingTop/Bottom, but not pane.borders var newH = s.innerHeight - (m.spaceAbove - s.css.paddingTop) - (m.spaceBelow - s.css.paddingBottom); if (!$C.is(":visible") || m.height != newH) { // size the Content element to fit new pane-size - will autoHide if not enough room setOuterHeight($C, newH, true); // true=autoHide m.height = newH; // save new height }; if (state.initialized) { _execCallback(pane, o.onsizecontent_end || o.onsizecontent); resizeNestedLayout(pane); } function _below ($E) { return max(s.css.paddingBottom, (parseInt($E.css("marginBottom"), 10) || 0)); }; function _measure () { var ignore = options[pane].contentIgnoreSelector , $Fs = $C.nextAll().not(ignore || ':lt(0)') // not :lt(0) = ALL , $Fs_vis = $Fs.filter(':visible') , $F = $Fs_vis.filter(':last') ; m = { top: $C[0].offsetTop , height: $C.outerHeight() , numFooters: $Fs.length , hiddenFooters: $Fs.length - $Fs_vis.length , spaceBelow: 0 // correct if no content footer ($E) } m.spaceAbove = m.top; // just for state - not used in calc m.bottom = m.top + m.height; if ($F.length) //spaceBelow = (LastFooter.top + LastFooter.height) [footerBottom] - Content.bottom + max(LastFooter.marginBottom, pane.paddingBotom) m.spaceBelow = ($F[0].offsetTop + $F.outerHeight()) - m.bottom + _below($F); else // no footer - check marginBottom on Content element itself m.spaceBelow = _below($C); }; }); }; /** * Called every time a pane is opened, closed, or resized to slide the togglers to 'center' and adjust their length if necessary * * @see initHandles(), open(), close(), resizeAll() * @param {string=} panes The pane(s) being resized */ var sizeHandles = function (panes) { if (!panes || panes == "all") panes = _c.borderPanes; $.each(panes.split(","), function (i, pane) { var o = options[pane] , s = state[pane] , $P = $Ps[pane] , $R = $Rs[pane] , $T = $Ts[pane] , $TC ; if (!$P || !$R) return; var dir = _c[pane].dir , _state = (s.isClosed ? "_closed" : "_open") , spacing = o["spacing"+ _state] , togAlign = o["togglerAlign"+ _state] , togLen = o["togglerLength"+ _state] , paneLen , offset , CSS = {} ; if (spacing == 0) { $R.hide(); return; } else if (!s.noRoom && !s.isHidden) // skip if resizer was hidden for any reason $R.show(); // in case was previously hidden // Resizer Bar is ALWAYS same width/height of pane it is attached to if (dir == "horz") { // north/south paneLen = $P.outerWidth(); // s.outerWidth || s.resizerLength = paneLen; $R.css({ width: max(1, cssW($R, paneLen)) // account for borders & padding , height: max(0, cssH($R, spacing)) // ditto , left: _cssNum($P, "left") }); } else { // east/west paneLen = $P.outerHeight(); // s.outerHeight || s.resizerLength = paneLen; $R.css({ height: max(1, cssH($R, paneLen)) // account for borders & padding , width: max(0, cssW($R, spacing)) // ditto , top: sC.insetTop + getPaneSize("north", true) // TODO: what if no North pane? //, top: _cssNum($Ps["center"], "top") }); } // remove hover classes removeHover( o, $R ); if ($T) { if (togLen == 0 || (s.isSliding && o.hideTogglerOnSlide)) { $T.hide(); // always HIDE the toggler when 'sliding' return; } else $T.show(); // in case was previously hidden if (!(togLen > 0) || togLen == "100%" || togLen > paneLen) { togLen = paneLen; offset = 0; } else { // calculate 'offset' based on options.PANE.togglerAlign_open/closed if (isStr(togAlign)) { switch (togAlign) { case "top": case "left": offset = 0; break; case "bottom": case "right": offset = paneLen - togLen; break; case "middle": case "center": default: offset = Math.floor((paneLen - togLen) / 2); // 'default' catches typos } } else { // togAlign = number var x = parseInt(togAlign, 10); // if (togAlign >= 0) offset = x; else offset = paneLen - togLen + x; // NOTE: x is negative! } } if (dir == "horz") { // north/south var width = cssW($T, togLen); $T.css({ width: max(0, width) // account for borders & padding , height: max(1, cssH($T, spacing)) // ditto , left: offset // TODO: VERIFY that toggler positions correctly for ALL values , top: 0 }); // CENTER the toggler content SPAN $T.children(".content").each(function(){ $TC = $(this); $TC.css("marginLeft", Math.floor((width-$TC.outerWidth())/2)); // could be negative }); } else { // east/west var height = cssH($T, togLen); $T.css({ height: max(0, height) // account for borders & padding , width: max(1, cssW($T, spacing)) // ditto , top: offset // POSITION the toggler , left: 0 }); // CENTER the toggler content SPAN $T.children(".content").each(function(){ $TC = $(this); $TC.css("marginTop", Math.floor((height-$TC.outerHeight())/2)); // could be negative }); } // remove ALL hover classes removeHover( 0, $T ); } // DONE measuring and sizing this resizer/toggler, so can be 'hidden' now if (!state.initialized && o.initHidden) { $R.hide(); if ($T) $T.hide(); } }); }; var enableClosable = function (pane) { var $T = $Ts[pane], o = options[pane]; if (!$T) return; o.closable = true; $T .bind("click."+ sID, function(evt){ toggle(pane); evt.stopPropagation(); }) .bind("mouseenter."+ sID, addHover) .bind("mouseleave."+ sID, removeHover) .css("visibility", "visible") .css("cursor", "pointer") .attr("title", state[pane].isClosed ? o.togglerTip_closed : o.togglerTip_open) // may be blank .show() ; }; var disableClosable = function (pane, hide) { var $T = $Ts[pane]; if (!$T) return; options[pane].closable = false; // is closable is disable, then pane MUST be open! if (state[pane].isClosed) open(pane, false, true); $T .unbind("."+ sID) .css("visibility", hide ? "hidden" : "visible") // instead of hide(), which creates logic issues .css("cursor", "default") .attr("title", "") ; }; var enableSlidable = function (pane) { var $R = $Rs[pane], o = options[pane]; if (!$R || !$R.data('draggable')) return; options[pane].slidable = true; if (s.isClosed) bindStartSlidingEvent(pane, true); }; var disableSlidable = function (pane) { var $R = $Rs[pane]; if (!$R) return; options[pane].slidable = false; if (state[pane].isSliding) close(pane, false, true); else { bindStartSlidingEvent(pane, false); $R .css("cursor", "default") .attr("title", "") ; removeHover(null, $R[0]); // in case currently hovered } }; var enableResizable = function (pane) { var $R = $Rs[pane], o = options[pane]; if (!$R || !$R.data('draggable')) return; o.resizable = true; $R .draggable("enable") .bind("mouseenter."+ sID, onResizerEnter) .bind("mouseleave."+ sID, onResizerLeave) ; if (!state[pane].isClosed) $R .css("cursor", o.resizerCursor) .attr("title", o.resizerTip) ; }; var disableResizable = function (pane) { var $R = $Rs[pane]; if (!$R || !$R.data('draggable')) return; options[pane].resizable = false; $R .draggable("disable") .unbind("."+ sID) .css("cursor", "default") .attr("title", "") ; removeHover(null, $R[0]); // in case currently hovered }; /** * Move a pane from source-side (eg, west) to target-side (eg, east) * If pane exists on target-side, move that to source-side, ie, 'swap' the panes * * @param {string} pane1 The pane/edge being swapped * @param {string} pane2 ditto */ var swapPanes = function (pane1, pane2) { // change state.edge NOW so callbacks can know where pane is headed... state[pane1].edge = pane2; state[pane2].edge = pane1; // run these even if NOT state.initialized var cancelled = false; if (false === _execCallback(pane1, options[pane1].onswap_start)) cancelled = true; if (!cancelled && false === _execCallback(pane2, options[pane2].onswap_start)) cancelled = true; if (cancelled) { state[pane1].edge = pane1; // reset state[pane2].edge = pane2; return; } var oPane1 = copy( pane1 ) , oPane2 = copy( pane2 ) , sizes = {} ; sizes[pane1] = oPane1 ? oPane1.state.size : 0; sizes[pane2] = oPane2 ? oPane2.state.size : 0; // clear pointers & state $Ps[pane1] = false; $Ps[pane2] = false; state[pane1] = {}; state[pane2] = {}; // ALWAYS remove the resizer & toggler elements if ($Ts[pane1]) $Ts[pane1].remove(); if ($Ts[pane2]) $Ts[pane2].remove(); if ($Rs[pane1]) $Rs[pane1].remove(); if ($Rs[pane2]) $Rs[pane2].remove(); $Rs[pane1] = $Rs[pane2] = $Ts[pane1] = $Ts[pane2] = false; // transfer element pointers and data to NEW Layout keys move( oPane1, pane2 ); move( oPane2, pane1 ); // cleanup objects oPane1 = oPane2 = sizes = null; // make panes 'visible' again if ($Ps[pane1]) $Ps[pane1].css(_c.visible); if ($Ps[pane2]) $Ps[pane2].css(_c.visible); // fix any size discrepancies caused by swap resizeAll(); // run these even if NOT state.initialized _execCallback(pane1, options[pane1].onswap_end || options[pane1].onswap); _execCallback(pane2, options[pane2].onswap_end || options[pane2].onswap); return; function copy (n) { // n = pane var $P = $Ps[n] , $C = $Cs[n] ; return !$P ? false : { pane: n , P: $P ? $P[0] : false , C: $C ? $C[0] : false , state: $.extend({}, state[n]) , options: $.extend({}, options[n]) } }; function move (oPane, pane) { if (!oPane) return; var P = oPane.P , C = oPane.C , oldPane = oPane.pane , c = _c[pane] , side = c.side.toLowerCase() , inset = "inset"+ c.side // save pane-options that should be retained , s = $.extend({}, state[pane]) , o = options[pane] // RETAIN side-specific FX Settings - more below , fx = { resizerCursor: o.resizerCursor } , re, size, pos ; $.each("fxName,fxSpeed,fxSettings".split(","), function (i, k) { fx[k] = o[k]; fx[k +"_open"] = o[k +"_open"]; fx[k +"_close"] = o[k +"_close"]; }); // update object pointers and attributes $Ps[pane] = $(P) .data("layoutEdge", pane) .css(_c.hidden) .css(c.cssReq) ; $Cs[pane] = C ? $(C) : false; // set options and state options[pane] = $.extend({}, oPane.options, fx); state[pane] = $.extend({}, oPane.state); // change classNames on the pane, eg: ui-layout-pane-east ==> ui-layout-pane-west re = new RegExp(o.paneClass +"-"+ oldPane, "g"); P.className = P.className.replace(re, o.paneClass +"-"+ pane); // ALWAYS regenerate the resizer & toggler elements initHandles(pane); // create the required resizer & toggler // if moving to different orientation, then keep 'target' pane size if (c.dir != _c[oldPane].dir) { size = sizes[pane] || 0; setSizeLimits(pane); // update pane-state size = max(size, state[pane].minSize); // use manualSizePane to disable autoResize - not useful after panes are swapped manualSizePane(pane, size, true); // true = skipCallback } else // move the resizer here $Rs[pane].css(side, sC[inset] + (state[pane].isVisible ? getPaneSize(pane) : 0)); // ADD CLASSNAMES & SLIDE-BINDINGS if (oPane.state.isVisible && !s.isVisible) setAsOpen(pane, true); // true = skipCallback else { setAsClosed(pane); bindStartSlidingEvent(pane, true); // will enable events IF option is set } // DESTROY the object oPane = null; }; }; /** * Capture keys when enableCursorHotkey - toggle pane if hotkey pressed * * @see document.keydown() */ function keyDown (evt) { if (!evt) return true; var code = evt.keyCode; if (code < 33) return true; // ignore special keys: ENTER, TAB, etc var PANE = { 38: "north" // Up Cursor - $.ui.keyCode.UP , 40: "south" // Down Cursor - $.ui.keyCode.DOWN , 37: "west" // Left Cursor - $.ui.keyCode.LEFT , 39: "east" // Right Cursor - $.ui.keyCode.RIGHT } , ALT = evt.altKey // no worky! , SHIFT = evt.shiftKey , CTRL = evt.ctrlKey , CURSOR = (CTRL && code >= 37 && code <= 40) , o, k, m, pane ; if (CURSOR && options[PANE[code]].enableCursorHotkey) // valid cursor-hotkey pane = PANE[code]; else if (CTRL || SHIFT) // check to see if this matches a custom-hotkey $.each(_c.borderPanes.split(","), function (i, p) { // loop each pane to check its hotkey o = options[p]; k = o.customHotkey; m = o.customHotkeyModifier; // if missing or invalid, treated as "CTRL+SHIFT" if ((SHIFT && m=="SHIFT") || (CTRL && m=="CTRL") || (CTRL && SHIFT)) { // Modifier matches if (k && code == (isNaN(k) || k <= 9 ? k.toUpperCase().charCodeAt(0) : k)) { // Key matches pane = p; return false; // BREAK } } }); // validate pane if (!pane || !$Ps[pane] || !options[pane].closable || state[pane].isHidden) return true; toggle(pane); evt.stopPropagation(); evt.returnValue = false; // CANCEL key return false; }; /* * ###################################### * UTILITY METHODS * called externally or by initButtons * ###################################### */ /** * Change/reset a pane's overflow setting & zIndex to allow popups/drop-downs to work * * @param {Object=} el (optional) Can also be 'bound' to a click, mouseOver, or other event */ function allowOverflow (el) { if (this && this.tagName) el = this; // BOUND to element var $P; if (isStr(el)) $P = $Ps[el]; else if ($(el).data("layoutRole")) $P = $(el); else $(el).parents().each(function(){ if ($(this).data("layoutRole")) { $P = $(this); return false; // BREAK } }); if (!$P || !$P.length) return; // INVALID var pane = $P.data("layoutEdge") , s = state[pane] ; // if pane is already raised, then reset it before doing it again! // this would happen if allowOverflow is attached to BOTH the pane and an element if (s.cssSaved) resetOverflow(pane); // reset previous CSS before continuing // if pane is raised by sliding or resizing, or it's closed, then abort if (s.isSliding || s.isResizing || s.isClosed) { s.cssSaved = false; return; } var newCSS = { zIndex: (_c.zIndex.pane_normal + 2) } , curCSS = {} , of = $P.css("overflow") , ofX = $P.css("overflowX") , ofY = $P.css("overflowY") ; // determine which, if any, overflow settings need to be changed if (of != "visible") { curCSS.overflow = of; newCSS.overflow = "visible"; } if (ofX && !ofX.match(/visible|auto/)) { curCSS.overflowX = ofX; newCSS.overflowX = "visible"; } if (ofY && !ofY.match(/visible|auto/)) { curCSS.overflowY = ofX; newCSS.overflowY = "visible"; } // save the current overflow settings - even if blank! s.cssSaved = curCSS; // apply new CSS to raise zIndex and, if necessary, make overflow 'visible' $P.css( newCSS ); // make sure the zIndex of all other panes is normal $.each(_c.allPanes.split(","), function(i, p) { if (p != pane) resetOverflow(p); }); }; function resetOverflow (el) { if (this && this.tagName) el = this; // BOUND to element var $P; if (isStr(el)) $P = $Ps[el]; else if ($(el).data("layoutRole")) $P = $(el); else $(el).parents().each(function(){ if ($(this).data("layoutRole")) { $P = $(this); return false; // BREAK } }); if (!$P || !$P.length) return; // INVALID var pane = $P.data("layoutEdge") , s = state[pane] , CSS = s.cssSaved || {} ; // reset the zIndex if (!s.isSliding && !s.isResizing) $P.css("zIndex", _c.zIndex.pane_normal); // reset Overflow - if necessary $P.css( CSS ); // clear var s.cssSaved = false; }; /** * Helper function to validate params received by addButton utilities * * Two classes are added to the element, based on the buttonClass... * The type of button is appended to create the 2nd className: * - ui-layout-button-pin * - ui-layout-pane-button-toggle * - ui-layout-pane-button-open * - ui-layout-pane-button-close * * @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button" * @param {string} pane Name of the pane the button is for: 'north', 'south', etc. * @return {Array.<Object>} If both params valid, the element matching 'selector' in a jQuery wrapper - otherwise returns null */ function getBtn (selector, pane, action) { var $E = $(selector); if (!$E.length) // element not found alert(lang.errButton + lang.selector +": "+ selector); else if (_c.borderPanes.indexOf(pane) == -1) // invalid 'pane' sepecified alert(lang.errButton + lang.Pane.toLowerCase() +": "+ pane); else { // VALID var btn = options[pane].buttonClass +"-"+ action; $E .addClass( btn +" "+ btn +"-"+ pane ) .data("layoutName", options.name) // add layout identifier - even if blank! ; return $E; } return null; // INVALID }; /** * NEW syntax for binding layout-buttons - will eventually replace addToggleBtn, addOpenBtn, etc. * * @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button" * @param {string} action * @param {string} pane */ function bindButton (selector, action, pane) { switch (action.toLowerCase()) { case "toggle": addToggleBtn(selector, pane); break; case "open": addOpenBtn(selector, pane); break; case "close": addCloseBtn(selector, pane); break; case "pin": addPinBtn(selector, pane); break; case "toggle-slide": addToggleBtn(selector, pane, true); break; case "open-slide": addOpenBtn(selector, pane, true); break; } }; /** * Add a custom Toggler button for a pane * * @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button" * @param {string} pane Name of the pane the button is for: 'north', 'south', etc. * @param {boolean=} slide true = slide-open, false = pin-open */ function addToggleBtn (selector, pane, slide) { var $E = getBtn(selector, pane, "toggle"); if ($E) $E.click(function (evt) { toggle(pane, !!slide); evt.stopPropagation(); }); }; /** * Add a custom Open button for a pane * * @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button" * @param {string} pane Name of the pane the button is for: 'north', 'south', etc. * @param {boolean=} slide true = slide-open, false = pin-open */ function addOpenBtn (selector, pane, slide) { var $E = getBtn(selector, pane, "open"); if ($E) $E .attr("title", lang.Open) .click(function (evt) { open(pane, !!slide); evt.stopPropagation(); }) ; }; /** * Add a custom Close button for a pane * * @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button" * @param {string} pane Name of the pane the button is for: 'north', 'south', etc. */ function addCloseBtn (selector, pane) { var $E = getBtn(selector, pane, "close"); if ($E) $E .attr("title", lang.Close) .click(function (evt) { close(pane); evt.stopPropagation(); }) ; }; /** * addPinBtn * * Add a custom Pin button for a pane * * Four classes are added to the element, based on the paneClass for the associated pane... * Assuming the default paneClass and the pin is 'up', these classes are added for a west-pane pin: * - ui-layout-pane-pin * - ui-layout-pane-west-pin * - ui-layout-pane-pin-up * - ui-layout-pane-west-pin-up * * @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button" * @param {string} pane Name of the pane the pin is for: 'north', 'south', etc. */ function addPinBtn (selector, pane) { var $E = getBtn(selector, pane, "pin"); if ($E) { var s = state[pane]; $E.click(function (evt) { setPinState($(this), pane, (s.isSliding || s.isClosed)); if (s.isSliding || s.isClosed) open( pane ); // change from sliding to open else close( pane ); // slide-closed evt.stopPropagation(); }); // add up/down pin attributes and classes setPinState($E, pane, (!s.isClosed && !s.isSliding)); // add this pin to the pane data so we can 'sync it' automatically // PANE.pins key is an array so we can store multiple pins for each pane _c[pane].pins.push( selector ); // just save the selector string } }; /** * INTERNAL function to sync 'pin buttons' when pane is opened or closed * Unpinned means the pane is 'sliding' - ie, over-top of the adjacent panes * * @see open(), close() * @param {string} pane These are the params returned to callbacks by layout() * @param {boolean} doPin True means set the pin 'down', False means 'up' */ function syncPinBtns (pane, doPin) { $.each(_c[pane].pins, function (i, selector) { setPinState($(selector), pane, doPin); }); }; /** * Change the class of the pin button to make it look 'up' or 'down' * * @see addPinBtn(), syncPinBtns() * @param {Array.<Object>} $Pin The pin-span element in a jQuery wrapper * @param {string} pane These are the params returned to callbacks by layout() * @param {boolean} doPin true = set the pin 'down', false = set it 'up' */ function setPinState ($Pin, pane, doPin) { var updown = $Pin.attr("pin"); if (updown && doPin == (updown=="down")) return; // already in correct state var pin = options[pane].buttonClass +"-pin" , side = pin +"-"+ pane , UP = pin +"-up "+ side +"-up" , DN = pin +"-down "+side +"-down" ; $Pin .attr("pin", doPin ? "down" : "up") // logic .attr("title", doPin ? lang.Unpin : lang.Pin) .removeClass( doPin ? UP : DN ) .addClass( doPin ? DN : UP ) ; }; /* * LAYOUT STATE MANAGEMENT * * @example .layout({ cookie: { name: "myLayout", keys: "west.isClosed,east.isClosed" } }) * @example .layout({ cookie__name: "myLayout", cookie__keys: "west.isClosed,east.isClosed" }) * @example myLayout.getState( "west.isClosed,north.size,south.isHidden" ); * @example myLayout.saveCookie( "west.isClosed,north.size,south.isHidden", {expires: 7} ); * @example myLayout.deleteCookie(); * @example myLayout.loadCookie(); * @example var hSaved = myLayout.state.cookie; */ function isCookiesEnabled () { // TODO: is the cookieEnabled property common enough to be useful??? return (navigator.cookieEnabled != 0); }; /** * Read & return data from the cookie - as JSON * * @param {Object=} opts */ function getCookie (opts) { var o = $.extend( {}, options.cookie, opts || {} ) , name = o.name || options.name || "Layout" , c = document.cookie , cs = c ? c.split(';') : [] , pair // loop var ; for (var i=0, n=cs.length; i < n; i++) { pair = $.trim(cs[i]).split('='); // name=value pair if (pair[0] == name) // found the layout cookie // convert cookie string back to a hash return decodeJSON( decodeURIComponent(pair[1]) ); } return ""; }; /** * Get the current layout state and save it to a cookie * * @param {(string|Array)=} keys * @param {Object=} opts */ function saveCookie (keys, opts) { var o = $.extend( {}, options.cookie, opts || {} ) , name = o.name || options.name || "Layout" , params = '' , date = '' , clear = false ; if (o.expires.toUTCString) date = o.expires; else if (typeof o.expires == 'number') { date = new Date(); if (o.expires > 0) date.setDate(date.getDate() + o.expires); else { date.setYear(1970); clear = true; } } if (date) params += ';expires='+ date.toUTCString(); if (o.path) params += ';path='+ o.path; if (o.domain) params += ';domain='+ o.domain; if (o.secure) params += ';secure'; if (clear) { state.cookie = {}; // clear data document.cookie = name +'='+ params; // expire the cookie } else { state.cookie = getState(keys || o.keys); // read current panes-state document.cookie = name +'='+ encodeURIComponent( encodeJSON(state.cookie) ) + params; // write cookie } return $.extend({}, state.cookie); // return COPY of state.cookie }; /** * Remove the state cookie */ function deleteCookie () { saveCookie('', { expires: -1 }); }; /** * Get data from the cookie and USE IT to loadState * * @param {Object=} opts */ function loadCookie (opts) { var o = getCookie(opts); // READ the cookie if (o) { state.cookie = $.extend({}, o); // SET state.cookie loadState(o); // LOAD the retrieved state } return o; }; /** * Update layout options from the cookie, if one exists * * @param {Object=} opts */ function loadState (opts, animate) { $.extend( true, options, opts ); // update layout options // if layout has already been initialized, then UPDATE layout state if (state.initialized) { var pane, o, v, a = !animate; $.each(_c.allPanes.split(","), function (idx, pane) { o = opts[ pane ]; if (typeof o != 'object') return; // no key, continue v = o.initHidden; if (v === true) hide(pane, a); if (v === false) show(pane, 0, a); v = o.size; if (v > 0) sizePane(pane, v); v = o.initClosed; if (v === true) close(pane, 0, a); if (v === false) open(pane, 0, a ); }); } }; /** * Get the *current layout state* and return it as a hash * * @param {(string|Array)=} keys */ function getState (keys) { var data = {} , alt = { isClosed: 'initClosed', isHidden: 'initHidden' } , pair, pane, key, val ; if (!keys) keys = options.cookie.keys; // if called by user if ($.isArray(keys)) keys = keys.join(","); // convert keys to an array and change delimiters from '__' to '.' keys = keys.replace(/__/g, ".").split(','); // loop keys and create a data hash for (var i=0,n=keys.length; i < n; i++) { pair = keys[i].split("."); pane = pair[0]; key = pair[1]; if (_c.allPanes.indexOf(pane) < 0) continue; // bad pane! val = state[ pane ][ key ]; if (val == undefined) continue; if (key=="isClosed" && state[pane]["isSliding"]) val = true; // if sliding, then *really* isClosed ( data[pane] || (data[pane]={}) )[ alt[key] ? alt[key] : key ] = val; } return data; }; /** * Stringify a JSON hash so can save in a cookie or db-field */ function encodeJSON (JSON) { return parse( JSON ); function parse (h) { var D=[], i=0, k, v, t; // k = key, v = value for (k in h) { v = h[k]; t = typeof v; if (t == 'string') // STRING - add quotes v = '"'+ v +'"'; else if (t == 'object') // SUB-KEY - recurse into it v = parse(v); D[i++] = '"'+ k +'":'+ v; } return "{"+ D.join(",") +"}"; }; }; /** * Convert stringified JSON back to a hash object */ function decodeJSON (str) { try { return window["eval"]("("+ str +")") || {}; } catch (e) { return {}; } }; /* * ##################### * CREATE/RETURN LAYOUT * ##################### */ // validate that container exists var $Container = $(this).eq(0); // FIRST matching Container element if (!$Container.length) { //alert( lang.errContainerMissing ); return null; }; // Users retreive Instance of a layout with: $Container.layout() OR $Container.data("layout") // return the Instance-pointer if layout has already been initialized if ($Container.data("layoutContainer") && $Container.data("layout")) return $Container.data("layout"); // cached pointer // init global vars var $Ps = {} // Panes x5 - set in initPanes() , $Cs = {} // Content x5 - set in initPanes() , $Rs = {} // Resizers x4 - set in initHandles() , $Ts = {} // Togglers x4 - set in initHandles() // aliases for code brevity , sC = state.container // alias for easy access to 'container dimensions' , sID = state.id // alias for unique layout ID/namespace - eg: "layout435" ; // create Instance object to expose data & option Properties, and primary action Methods var Instance = { options: options // property - options hash , state: state // property - dimensions hash , container: $Container // property - object pointers for layout container , panes: $Ps // property - object pointers for ALL Panes: panes.north, panes.center , contents: $Cs // property - object pointers for ALL Content: content.north, content.center , resizers: $Rs // property - object pointers for ALL Resizers, eg: resizers.north , togglers: $Ts // property - object pointers for ALL Togglers, eg: togglers.north , toggle: toggle // method - pass a 'pane' ("north", "west", etc) , hide: hide // method - ditto , show: show // method - ditto , open: open // method - ditto , close: close // method - ditto , slideOpen: slideOpen // method - ditto , slideClose: slideClose // method - ditto , slideToggle: slideToggle // method - ditto , initContent: initContent // method - ditto , sizeContent: sizeContent // method - pass a 'pane' , sizePane: manualSizePane // method - pass a 'pane' AND an 'outer-size' in pixels or percent, or 'auto' , swapPanes: swapPanes // method - pass TWO 'panes' - will swap them , resizeAll: resizeAll // method - no parameters , destroy: destroy // method - no parameters , setSizeLimits: setSizeLimits // method - pass a 'pane' - update state min/max data , bindButton: bindButton // utility - pass element selector, 'action' and 'pane' (E, "toggle", "west") , addToggleBtn: addToggleBtn // utility - pass element selector and 'pane' (E, "west") , addOpenBtn: addOpenBtn // utility - ditto , addCloseBtn: addCloseBtn // utility - ditto , addPinBtn: addPinBtn // utility - ditto , allowOverflow: allowOverflow // utility - pass calling element (this) , resetOverflow: resetOverflow // utility - ditto , encodeJSON: encodeJSON // method - pass a JSON object , decodeJSON: decodeJSON // method - pass a string of encoded JSON , getState: getState // method - returns hash of current layout-state , getCookie: getCookie // method - update options from cookie - returns hash of cookie data , saveCookie: saveCookie // method - optionally pass keys-list and cookie-options (hash) , deleteCookie: deleteCookie // method , loadCookie: loadCookie // method - update options from cookie - returns hash of cookie data , loadState: loadState // method - pass a hash of state to use to update options , cssWidth: cssW // utility - pass element and target outerWidth , cssHeight: cssH // utility - ditto , enableClosable: enableClosable , disableClosable: disableClosable , enableSlidable: enableSlidable , disableSlidable: disableSlidable , enableResizable: enableResizable , disableResizable: disableResizable }; // create the border layout NOW _create(); // return the Instance object return Instance; } })( jQuery );
zope2.zodbbrowser
/zope2.zodbbrowser-0.2.tar.gz/zope2.zodbbrowser-0.2/zope2/zodbbrowser/resources/jquery.layout.js
jquery.layout.js
var emptyBottom = function(){ $("#bottom").text(""); $("#status").text(""); }; var bottom = function(nodepath, panelpath, nodename, kindof) { $.ajax({ url: nodepath + kindof + nodename, dataType: "json", success: function(data) { $('#bottom').html(data['bottom']); $('#status').html("# " + data['status']); } }); }; // right panel var emptyRight = function(){ $("#right").text(""); }; var right = function(nodepath, kind){ $("#right").dynatree({ initAjax: { url: nodepath + kind, data: { mode: "funnyMode" }, dataType: "json" }, onActivate: function(node) { elem = node.data.title; switch (kind) { case "/class_ancestors" : bottom(nodepath, getPath(node), node.data.title, "/class_source?"); break; case "/properties" : bottom(nodepath, getPath(node), node.data.title, "/property_source?"); break; case "/callables" : bottom(nodepath, getPath(node), node.data.title, "/method_source?"); break; case "/interfaces" : bottom(nodepath, getPath(node), node.data.title, "/interface_source?"); break; } } }); }; // midle panel var emptyMiddle = function(){ $("#middle").text(""); }; var middle = function(path){ $("#middle").dynatree({ children: [ { "title": "Class and Ancestors" }, { "title": "Properties" }, { "title": "Callables" }, { "title": "Interfaces Provided" } ] , onActivate: function(node) { switch (node.data.title) { case "Properties" : right(path, '/properties') ; break; case "Callables" : right(path, '/callables') ; break; case "Interfaces Provided" : right(path, '/interfaces') ; break; case "Adapts" : right(path, '/adapts') ; break; case "Class and Ancestors" : right(path, '/class_ancestors') ; break; } // XXX this forces a request twice sometimes var rightTree = $("#right").dynatree("getTree"); rightTree.reload(); }, onDeactivate: function(node) { emptyRight(); emptyBottom(); } }); }; // Just for the left: getPath builds the path traversing the tree var buildTree = function(node) { if (node.data.title) { return ( buildTree(node.parent) + "/" + node.data.title) ; } else { return "" ; } }; var getPath = function(node) { var mypath = buildTree(node); return mypath.slice(12); }; // left panel $(function(){ $("#left").dynatree({ initAjax: { url: "/tree", data: { mode: "funnyMode" }, dataType: "json" }, onActivate: function(node) { var mypath = getPath(node); middle(mypath); // XXX this forces a request twice sometimes var rightTree = $("#middle").dynatree("getTree"); rightTree.reload(); }, onDeactivate: function(node) { emptyRight(); emptyMiddle(); emptyBottom(); }, onLazyRead: function(node){ node.appendAjax({ url: function() { return getPath(node) + "/tree"; }(), data: {key: node.data.key, mode: "funnyMode" } }); } }); }); // Panels using jQuery UI.Layout var myLayout; // a var is required because this page utilizes: myLayout.allowOverflow() method $(document).ready(function () { myLayout = $('body').layout({ east__size : 433, west__size : 433, north__size : 50, south__size : 450 }); });
zope2.zodbbrowser
/zope2.zodbbrowser-0.2.tar.gz/zope2.zodbbrowser-0.2/zope2/zodbbrowser/resources/zodbbrowser.js
zodbbrowser.js
Changelog ========= 0.3.0 (2016-08-31) ------------------ - Upgrade Bootstrap 3.3.5 -> 3.3.7 0.2.0 (2015-07-19) ------------------ - Upgrade Bootstrap 3.1.1 -> 3.3.5 0.1.0 - 2014-02-26 ------------------ - Adjust button styles 0.0.9 - 2014-02-26 ------------------ - Bump Bootstrap version to 3.1.1 0.0.8 - 2013-12-08 ------------------ - Upgrade to Bootstrap 3 - Add Zope2-only splash screen based on Plone's - Fix JavaScript 0.0.7 - 2012-06-11 ------------------ - Use SERVER_URL and SERVER_URL for logo src and href respectively (instead of SERVER_URL, ACTUAL_URL) 0.0.6 - 2012-06-11 ------------------ - Use SERVER_URL and ACTUAL_URL for logo src and href respectively (instead of URLX, BASEX) - Add ZMI warning (suggested by vangheem) 0.0.5 - 2012-06-11 ------------------ - Add contextual logo above manage_tabs 0.0.4 - 2012-06-01 ------------------ - Re-apply Plone ZMI hacks 0.0.3 - 2012-06-01 ------------------ - Fix brown bag 0.0.2 - 2012-06-01 ------------------ - Add table styles 0.0.1 - 2012-06-01 ------------------ - Initial release
zope2_bootstrap
/zope2_bootstrap-0.3.0.tar.gz/zope2_bootstrap-0.3.0/CHANGES.rst
CHANGES.rst
Introduction ============ The Zope Management Interface, with `Bootstrap <https://getbootstrap.com>`_. Installation ------------ :: $ virtualenv-2.7 . $ bin/pip install zc.buildout $ cat > buildout.cfg << EOF [buildout] extends = https://raw.githubusercontent.com/plock/pins/master/plone-4-3 [plone] eggs = Zope2 zope2_bootstrap zcml = zope2_bootstrap EOF $ bin/buildout $ bin/plone fg | .. image:: https://github.com/aclark4life/zope2_bootstrap/raw/master/screenshot.png :class: align-center | .. image:: https://github.com/aclark4life/zope2_bootstrap/raw/master/screenshot2.png :class: align-center
zope2_bootstrap
/zope2_bootstrap-0.3.0.tar.gz/zope2_bootstrap-0.3.0/README.rst
README.rst
import os import shutil import sys import tempfile from optparse import OptionParser __version__ = '2015-07-01' # See zc.buildout's changelog if this version is up to date. tmpeggs = tempfile.mkdtemp(prefix='bootstrap-') usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --find-links to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("--version", action="store_true", default=False, help=("Return bootstrap.py version.")) parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", "--config-file", help=("Specify the path to the buildout configuration " "file to be used.")) parser.add_option("-f", "--find-links", help=("Specify a URL to search for buildout releases")) parser.add_option("--allow-site-packages", action="store_true", default=False, help=("Let bootstrap.py use existing site packages")) parser.add_option("--buildout-version", help="Use a specific zc.buildout version") parser.add_option("--setuptools-version", help="Use a specific setuptools version") parser.add_option("--setuptools-to-dir", help=("Allow for re-use of existing directory of " "setuptools versions")) options, args = parser.parse_args() if options.version: print("bootstrap.py version %s" % __version__) sys.exit(0) ###################################################################### # load/install setuptools try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen ez = {} if os.path.exists('ez_setup.py'): exec (open('ez_setup.py').read(), ez) else: exec (urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez) if not options.allow_site_packages: # ez_setup imports site, which adds site packages # this will remove them from the path to ensure that incompatible versions # of setuptools are not in the path import site # inside a virtualenv, there is no 'getsitepackages'. # We can't remove these reliably if hasattr(site, 'getsitepackages'): for sitepackage_path in site.getsitepackages(): # Strip all site-packages directories from sys.path that # are not sys.prefix; this is because on Windows # sys.prefix is a site-package directory. if sitepackage_path != sys.prefix: sys.path[:] = [x for x in sys.path if sitepackage_path not in x] setup_args = dict(to_dir=tmpeggs, download_delay=0) if options.setuptools_version is not None: setup_args['version'] = options.setuptools_version if options.setuptools_to_dir is not None: setup_args['to_dir'] = options.setuptools_to_dir ez['use_setuptools'](**setup_args) import setuptools import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) ###################################################################### # Install buildout ws = pkg_resources.working_set setuptools_path = ws.find(pkg_resources.Requirement.parse( 'setuptools')).location # Fix sys.path here as easy_install.pth added before PYTHONPATH cmd = [sys.executable, '-c', 'import sys; sys.path[0:0] = [%r]; ' % setuptools_path + 'from setuptools.command.easy_install import main; main()', '-mZqNxd', tmpeggs] find_links = os.environ.get('bootstrap-testing-find-links', options.find_links or ('http://downloads.buildout.org/' if options.accept_buildout_test_releases else None)) if find_links: cmd.extend(['-f', find_links]) requirement = 'zc.buildout' version = options.buildout_version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): try: return not parsed_version.is_prerelease except AttributeError: # Older setuptools for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setuptools_path]) if find_links: index.add_find_links((find_links, )) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) import subprocess if subprocess.call(cmd) != 0: raise Exception("Failed to execute command:\n%s" % repr(cmd)[1:-1]) ###################################################################### # Import and run buildout ws.add_entry(tmpeggs) ws.require(requirement) import zc.buildout.buildout if not [a for a in args if '=' not in a]: args.append('bootstrap') # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args[0:0] = ['-c', options.config_file] zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
zope2_bootstrap
/zope2_bootstrap-0.3.0.tar.gz/zope2_bootstrap-0.3.0/bootstrap-buildout.py
bootstrap-buildout.py
import os, shutil, sys, tempfile, urllib2 from optparse import OptionParser tmpeggs = tempfile.mkdtemp() is_jython = sys.platform.startswith('java') # parsing arguments parser = OptionParser() parser.add_option("-v", "--version", dest="version", help="use a specific zc.buildout version") parser.add_option("-d", "--distribute", action="store_true", dest="distribute", default=False, help="Use Disribute rather than Setuptools.") parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args += ['-c', options.config_file] if options.version is not None: VERSION = '==%s' % options.version else: VERSION = '' USE_DISTRIBUTE = options.distribute args = args + ['bootstrap'] to_reload = False try: import pkg_resources if not hasattr(pkg_resources, '_distribute'): to_reload = True raise ImportError except ImportError: ez = {} if USE_DISTRIBUTE: exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True) else: exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0) if to_reload: reload(pkg_resources) else: import pkg_resources if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: def quote (c): return c cmd = 'from setuptools.command.easy_install import main; main()' ws = pkg_resources.working_set if USE_DISTRIBUTE: requirement = 'distribute' else: requirement = 'setuptools' if is_jython: import subprocess assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd', quote(tmpeggs), 'zc.buildout' + VERSION], env=dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ).wait() == 0 else: assert os.spawnle( os.P_WAIT, sys.executable, quote (sys.executable), '-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION, dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ) == 0 ws.add_entry(tmpeggs) ws.require('zc.buildout' + VERSION) import zc.buildout.buildout zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
zope2instance
/zope2instance-1.1.tar.gz/zope2instance-1.1/bootstrap.py
bootstrap.py
************************************************* zope-fixtures: Fixtures for use in Zope projects. ************************************************* Copyright (c) 2011, Robert Collins <[email protected]> Licensed under either the Apache License, Version 2.0 or the BSD 3-clause license at the users choice. A copy of both licenses are available in the project source as Apache-2.0 and BSD. You may not use this file except in compliance with one of these two licences. Unless required by applicable law or agreed to in writing, software distributed under these licenses is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the license you chose for the specific language governing permissions and limitations under that license. Zope fixtures provides Fixtures (http://pypi.python.org/pypi/fixtures) for use with Zope tests. These permit easy unit testing in Zope environments. Dependencies ============ * Python 2.4+ This is the base language fixtures is written in and for. * zope.interfaces. * Fixtures (http://pypi.python.org/pypi/fixtures). For use in a unit test suite using the included glue, one of: * Python 2.7 * unittest2 * bzrlib.tests * Or any other test environment that supports TestCase.addCleanup. Writing your own glue code is easy, or you can simply use the fixtures directly without any support code. To run the test suite for zope_fixtures, testtools is needed. See the Fixtures documentation for overview and design information. Stock Fixtures ============== ComponentsFixture +++++++++++++++++ This permits overlaying registrations in the zope registry. While the fixture is setup any registrations made are local to the fixture, and will be thrown away when the fixture is torn down. >>> from zope_fixtures import ComponentsFixture >>> from zope.interface import Interface, implements >>> from zope.component import getSiteManager >>> class ITestUtility(Interface):pass >>> class TestUtility(object): ... implements(ITestUtility) >>> with ComponentsFixture(): ... getSiteManager().registerUtility(TestUtility()) UtilityFixture ++++++++++++++ This permits simple replacement of a single utility. >>> from zope_fixtures import UtilityFixture >>> with UtilityFixture(TestUtility()): ... pass
zope_fixtures
/zope_fixtures-0.0.3.tar.gz/zope_fixtures-0.0.3/README
README
.. contents:: **Table of contents** Introduction ============ This project adds to your system a new utility command: ``zope_lrr_analyzer``. This utility only works with Zope instance logs with `haufe.requestmonitoring`__ installed (and where the `monitoring long running requests hook`__ is enabled). __ http://pypi.python.org/pypi/haufe.requestmonitoring __ http://pypi.python.org/pypi/haufe.requestmonitoring#monitoring-long-running-requests So, your *instance.log* must be filled by entries like this:: ------ 2012-03-27T15:58:19 WARNING RequestMonitor.DumpTrace Long running request Request 28060 "/VirtualHostBase/http/www.mysite.com:80/mysiteid/VirtualHostRoot/myrequest/..." running in thread 1133545792 since 10.7206499577s Python call stack (innermost first) ... lot of lines, depends on Python traceback ... Module ZPublisherEventsBackport.patch, line 80, in publish Module ZPublisher.Publish, line 202, in publish_module_standard Module ZPublisher.Publish, line 401, in publish_module Module ZServer.PubCore.ZServerPublisher, line 25, in __init__ <BLANKLINE> The utility will help you to parse long running request collecting some statistical data. How to use ========== Usage: zope_lrr_analyzer [options] logfile [logfile...] Analyze Zope instance log with haufe.requestmonitoring entries Options: --version show program's version number and exit -h, --help show this help message and exit -s START_FROM, --start=START_FROM start analysis after a given date/time (format like "YYYY-MM-DD HH:MM:SS") -e END_AT, --end=END_AT stop analysis at given date/time (format like "YYYY- MM-DD HH:MM:SS") -l LOG_SIZE, --log-size=LOG_SIZE keep only an amount of slow requests. Default is: no limit. -i INCLUDE_REGEX, --include=INCLUDE_REGEX a regexp expression that a calling path must match or will be discarded. Can be called multiple times, expanding the set -t TRACEBACK_INCLUDE_REGEX, --traceback-include=TRACEBACK_INCLUDE_REGEX a regexp expression that the Python traceback must match or will be discarded. Can be called multiple times, expanding the set -r, --keep-request-id Use request and thread ids to handle every match as a different entry Results ======= Let's explain the results:: Stats from 2012-11-14 00:02:07 to 2012-11-15 09:55:41 (347 LRR catched) ... ---- 2 /VirtualHostBase/http/yoursite.com:80/siteid/VirtualHostRoot/foo/bar 25 - 3654.05561542 (1:00:54.055615) - from 2012-11-15 07:48:10 to 2012-11-15 08:45:29 ---- 1 /VirtualHostBase/http/yoursite.com:80/siteid/VirtualHostRoot/baz 77 - 16029.3731236 (4:27:09.373124) - from 2012-11-15 07:43:55 to 2012-11-15 08:45:30 You'll get a rank of slowest request paths (top one is fastest, last one is slowest). The order is done by collecting all request's performed to the same path and then getting the total time. This mean that a request called only once that needs 30 seconds is faster that another path that only requires 10 seconds, but is called ten times (30x1 < 10x10). If you use also the ``--keep-request-id`` option, every request is count as a separate entry, so the output change a little:: Stats from 2012-04-27 00:02:07 to 2012-04-27 16:55:41 (347 LRR catched) ... ---- 2 /VirtualHostBase/http/yoursite.com:80/siteid/VirtualHostRoot/foo/bar 1510.2860291 (0:25:10.286029) - from 2012-09-19 08:36:27 to 2012-09-19 09:01:22 ---- 1 /VirtualHostBase/http/yoursite.com:80/siteid/VirtualHostRoot/baz 1750.49365091 (0:29:10.493651) - from 2012-09-19 08:30:34 to 2012-09-19 09:00:58 Single entry meaning -------------------- Every entry gives that kind of data:: Entry position Called path | | 1 /VirtualHostBase/http/yoursite.com:80/siteid/VirtualHostRoot/... 15 - 171.913325071 (0:02:51.913325) - from 2012-09-19 08:30:34 to 2012-09-19 09:00:58 | | | | | Times called | Time needed (human readable) | | | | Slow request end date Time needed (in seconds) Slow request start date When ``--keep-request-id`` used:: Entry position Called path | | 1 /VirtualHostBase/http/yoursite.com:80/siteid/VirtualHostRoot/... 1750.49365091 (0:29:10.493651) - from 2012-09-19 08:30:34 to 2012-09-19 09:00:58 | | | | Time needed (in seconds) | Slow request start date | | | Time needed (human readable) Slow request end date Please note that the "*Time needed*" info is machine computation time. Authors ======= This product was developed by RedTurtle Technology team. .. image:: http://www.redturtle.it/redturtle_banner.png :alt: RedTurtle Technology Site :target: http://www.redturtle.it/
zope_lrr_analyzer
/zope_lrr_analyzer-0.5.tar.gz/zope_lrr_analyzer-0.5/README.rst
README.rst
import sys import re import logging import optparse from datetime import datetime, timedelta try: from collections import OrderedDict except ImportError: from ordereddict import OrderedDict version = "0.5" description = "Analyze Zope instance log with haufe.requestmonitoring entries" usage = "usage: %prog [options] logfile [logfile...]" p = optparse.OptionParser(usage=usage, version="%prog " + version, description=description, prog="zope_lrr_analyzer") p.add_option( '--start', '-s', type="string", dest="start_from", default=None, help='start analysis after a given date/time (format like "YYYY-MM-DD HH:MM:SS")' # noqa ) p.add_option( '--end', '-e', type="string", dest="end_at", default=None, help='stop analysis at given date/time (format like "YYYY-MM-DD HH:MM:SS")' ) p.add_option( '--log-size', '-l', type="int", dest="log_size", default=None, help='keep only an amount of slow requests. Default is: no limit.' ) p.add_option( '--include', '-i', dest="includes", default=[], action="append", metavar="INCLUDE_REGEX", help="a regexp expression that a calling path must match or will be discarded. " # noqa "Can be called multiple times, expanding the set" ) p.add_option( '--traceback-include', '-t', dest="traceback_includes", default=[], action="append", metavar="TRACEBACK_INCLUDE_REGEX", help="a regexp expression that the Python traceback must match or will be discarded. " # noqa "Can be called multiple times, expanding the set") p.add_option( '--keep-request-id', '-r', dest="keep_req_id", default=False, action="store_true", help="Use request and thread ids to handle every match as a different entry" ) logger = logging.getLogger("zope_lrr_analyzer") PATTERN = """^------$ ^(?P<date>\d{4}-\d{2}-\d{2})T(?P<time>\d\d\:\d\d\:\d\d).*?$ ^Request (?P<reqid>\d*?) "(?P<path>.*?)" running in thread (?P<threadid>\d*?) since (?P<reqtime>\d*?\.\d*?)s$ (?P<traceback>.*?) ^$""" PATH_PATTERN = """^(?P<path>.*?)(?:\?.*?)?$""" reqLine = re.compile(PATTERN, re.M | re.S) pathLine = re.compile(PATH_PATTERN, re.M | re.S) stats = {} stat_data = {'count': 0, 'totaltime': 0, 'req-thread-ids': [], 'start': None, 'end': None} def main(): options, arguments = p.parse_args(sys.argv[1:]) min_date = max_date = None start_from = None end_at = None if options.start_from: try: start_from = datetime.strptime( options.start_from, "%Y-%m-%d %H:%M:%S" ) except ValueError: start_from = datetime.strptime( options.start_from, "%Y-%m-%d" ) if options.end_at: try: end_at = datetime.strptime(options.end_at, "%Y-%m-%d %H:%M:%S") except ValueError: end_at = datetime.strptime( "{} 23:59:59".format(options.end_at), "%Y-%m-%d %H:%M:%S" ) if not arguments: print p.format_help() sys.exit(1) lrr_counter = {} # Step 1. collect raw data for param in arguments: f = open(param) log = f.read() f.close() matches = reqLine.finditer(log) for m in matches: data = m.groupdict() rpath = data.get('path') reqtime = data.get('reqtime') reqid = data.get('reqid') threadid = data.get('threadid') rdate = data.get('date') rtime = data.get('time') traceback = data.get('traceback') d = datetime.strptime("%s %s" % (rdate, rtime), "%Y-%m-%d %H:%M:%S") if start_from and d < start_from: continue if end_at and d > end_at: break # include only... (path) stop = False if options.includes: stop = True for i in options.includes: if re.search(i, rpath, re.IGNORECASE) is not None: stop = False break if stop: continue # include only... (traceback) stop = False if options.traceback_includes: stop = True for i in options.traceback_includes: if re.search(i, traceback, re.MULTILINE) is not None: stop = False break if stop: continue if not min_date or d < min_date: min_date = d if not max_date or d > min_date: max_date = d match = pathLine.match(rpath) if match: # default case: store a record for every different path if not options.keep_req_id: path = match.groups()[0] # alternative case: store a record for request/thread id else: path = "%s|%s|%s" % (match.groups()[0], reqid, threadid) if reqid not in lrr_counter.keys(): lrr_counter[reqid] = True if not stats.get(path): stats[path] = {} if not stats[path].get("%s-%s" % (reqid, threadid)): stats[path][ "%s-%s" % (reqid, threadid)] = { 'reqtime': 0, 'start': d, 'end': None } stats[path]["%s-%s" % (reqid, threadid)]['reqtime'] = reqtime stats[path]["%s-%s" % (reqid, threadid)]['end'] = d else: logger.error("Line %s does not match" % rpath) # Step 2. get stats unordered_stats = {} for path, tempstat in stats.items(): unordered_stats[path] = stat_data.copy() request_data = tempstat.values() unordered_stats[path]['count'] = len(tempstat.keys()) unordered_stats[path]['totaltime'] = sum( [float(x['reqtime']) for x in request_data]) unordered_stats[path]['req-thread-ids'] = tempstat.keys() if options.keep_req_id: # every thread can keep start/end date unordered_stats[path]['start'] = request_data[0]['start'] unordered_stats[path]['end'] = request_data[0]['end'] else: # we must store start/end date per request, ignoring thread unordered_stats[path]['start'] = min( [x['start'] for x in request_data]) unordered_stats[path]['end'] = max([x['end'] for x in request_data]) # Step 3. final results final_stats = OrderedDict( sorted(unordered_stats.items(), key=lambda t: float(t[1]['totaltime']))) print "Stats from %s to %s (%d LRR catched)\n" % ( min_date, max_date, len(lrr_counter) ) logset = final_stats.items() if options.log_size is not None and len(logset) > options.log_size: logset = logset[-options.log_size:] cnt = len(logset) for k, v in logset: if not options.keep_req_id: print "----\n%s %s\n %d - %s (%s) - from %s to %s\n" % (cnt, k, v['count'], v['totaltime'], timedelta(seconds=float( v['totaltime'])), v['start'], v[ 'end'], ) else: path, reqid, threadid = k.split('|') print "----\n%s %s (request %s/thread %s)\n %s (%s) - from %s to %s\n" % (cnt, path, reqid, threadid, v['totaltime'], timedelta(seconds=float( v['totaltime'])), v['start'], v[ 'end'], ) if cnt: cnt -= 1 if __name__ == '__main__': main()
zope_lrr_analyzer
/zope_lrr_analyzer-0.5.tar.gz/zope_lrr_analyzer-0.5/src/zope_lrr_analyzer.py
zope_lrr_analyzer.py
.. contents:: **Table of contents** Main idea ========= Old `Zope2`__ products were heavily based on *skins* resources. A lot of additional information for those resources are taken from ``.metadata`` file, so commonly if you have a:: my_icon.gif ...you will want to have also a:: my_icon.gif.metadata In old Zope/Plone installation (let me say "before Varnish begin to be a Plone standard") you can use those metadata for performing associations with *HttpCache* objects, making the user browser to perform some cache of resources:: [default] title=my_icon.gif cache=HTTPCache __ http://zope.org/ zopemetadatamaker ================= This product will install for you a new executable: ``zopemetadatamaker``. Using this you can automatically create your ``.metadata`` files. when you have a lot of static images, css and javascript files this can save you some times, for example: you downloaded a big Javascript library with a lot of sub-directories inside and other related resources. How to use ---------- The basic use of the command is something like this:: zopemetadatamaker *.gif This will create for you all ".metadata" related to all gif file found in the current directory. You need to know that: * you must provide at least one filter patters * the directory where files are searched is the current working directory (but you can customize this, see below). Complete list of options ------------------------ Here the full documentation:: Usage: zopemetadatamaker [options] pattern [patterns] Bulk creation of .metadata files for Zope skins resources Options: --version show program's version number and exit -h, --help show this help message and exit -c METADATA, --content=METADATA choose a metadata text different from default; use quoting for multiline input -d, --default print default metadata (if --content is not provided), then exit -p PATHS, --path=PATHS directories path where to look for metadata. You can use this multiple times. Default is the current working directory --dry-run dry run, simply print what I would like to do -f, --force force .metadata creation; if another one exists it will be replaced -r, --recursive search and create recursively inside subdirs What to put in the .metadata content ------------------------------------ The default metadata content is like this:: [default] title=%(filename)s cache=HTTPCache The ``%(filename)s`` section will be replaced with the original file name. You can use this, or omit it, when defining you custom ``.metadata``. I use this default content because it is the minimal "cache" information for `Plone CMS`__ static resouces. __ http://plone.org/
zopemetadatamaker
/zopemetadatamaker-0.1.0.tar.gz/zopemetadatamaker-0.1.0/README.txt
README.txt
================================================ FRS = File Repository System 文件库系统 ================================================ frs.core is a pure python package for a simple file repository system(FRS). FRS use a virtual file system which map to the physical disk using a configuration file. FRS support trash box, metadata and attachments storge, caching and more. 做什么 =============== 1. 定义了一套虚拟的文件路径系统,可和实际的存储路径映射,避免直接和操作系统的文件系统打交道 #. 支持版本管理,可存储文件的历史版本。存放到(.frs目录中) #. 支持缓存/数据转换,比如图片的各种大小的 格式转换和存储,word文件的html预览转换和存储 #. 支持垃圾箱,删除的文件可自动存放在垃圾箱里面 #. 三级目录映射 - 网站 (zpath) -> FRS (vpath) - FRS (vpath) -> ospath (path) 准备文件系统上的文件 ========================= 找到临时文件夹: /tmp/frs >>> import os, tempfile, shutil >>> temp_dir = tempfile.gettempdir() + '/frs' >>> if os.path.exists(temp_dir): ... shutil.rmtree(temp_dir) >>> os.mkdir(temp_dir) 创建缓存文件夹: /tmp/frscache >>> cache = temp_dir + '/frscache' >>> os.mkdir(cache) 创建文件夹结构:: /tmp/frs/d1/f11 /tmp/frs/lala/d2/d21 /tmp/frs/lala/d2/f21 >>> d1 = temp_dir + '/d1' >>> os.mkdir(d1) >>> f11 = d1 + '/f11' >>> open(f11, 'w').write('hello') >>> lala = temp_dir + '/lala' >>> os.mkdir(lala) >>> d2 = lala + '/d2' >>> os.mkdir(d2) >>> f21 = d2 + '/f21' >>> open(f21, 'w').write('hello') >>> d21 = d2 + '/d21' >>> os.mkdir(d21) 初始化 =================== 得到一个: >>> frs_root = FRS() 什么都没有: >>> frs_root.listdir('/') [] Now we can mount some paths to the top folders: >>> frs_root.mount('d1', d1) >>> frs_root.mount('d2', d2) 同时设置缓存目录 >>> frs_root.setCacheRoot(cache) 通过配置文件初始化 ========================= 上面很麻烦,通过配置文件更简单 配置文件:: >>> config = """ ... [cache] ... path = /tmp/frscache ... ... [root] ... aa = /tmp/a ... bb = /tmp/b ... ... [site] ... / = /aa ... """ 加载:: >>> from zopen.frs import loadFRSFromConfig >>> frs_root = loadFRSFromConfig(config) 基本的文件系统功能 ====================== >>> sorted(frs_root.listdir('/')) ['d1', 'd2'] >>> frs_root.isdir('/d1') True >>> frs_root.listdir('/d1') ['f11'] >>> frs_root.isdir('/d1/f1') False >>> sorted(frs_root.listdir('/d2')) ['d21', 'f21'] >>> frs_root.open('/d2/f21').read() 'hello' 现在还不能跨区移动! >>> frs_root.move('/d2/f21', '/d1') Traceback (most recent call last): ... Exception: ... 自动映射 ================== 其实配置文件中可以在site栏目中配置的。 也可以手工配置: >>> frs_root.mapSitepath2Vpath(u'/site1/members', u'/d2') >>> frs_root.mapSitepath2Vpath(u'/site2/members', u'/d2') >>> frs_root.mapSitepath2Vpath(u'/', u'/d1') 我们看看根据站点路径自动计算的路径: >>> frs_root.sitepath2Vpath('/58080_1/zopen/project/1222/files/uncategoried/aaa.doc') u'/d1/58080_1/zopen/project/1222/files/uncategoried/aaa.doc' 2个站点可以指向同一文件的: >>> frs_root.sitepath2Vpath('/site1/members/aaa.doc') u'/d2/aaa.doc' >>> frs_root.sitepath2Vpath('/site2/members/aaa.doc') u'/d2/aaa.doc'
zopen.frs
/zopen.frs-1.2.2.tar.gz/zopen.frs-1.2.2/README.md
README.md
import os, shutil import posixpath from types import UnicodeType from ConfigParser import SafeConfigParser from StringIO import StringIO from utils import ucopy2, ucopytree, umove from archive import ArchiveSupportMixin from recycle import RecycleMixin from cache import CacheMixin from config import FRS_ARCHIVED_FOLDER_NAME def loadFRSFromConfig(config): """ load frs from config file """ cp = SafeConfigParser() cp.readfp(StringIO(config)) frs = FRS() cache_path = cp.get('cache', 'path') frs.setCacheRoot(unicode(cache_path)) roots = cp.items('root') for name,path in roots: path = os.path.normpath(path) if not os.path.exists(path): os.makedirs(path) frs.mount(unicode(name), unicode(path)) roots = cp.items('site') for site_path, vpath in roots: frs.mapSitepath2Vpath( unicode(site_path), unicode(vpath) ) return frs class FRS(ArchiveSupportMixin, RecycleMixin, CacheMixin): def __init__(self, cache_root='/tmp', dotfrs='.frs', version="json"): self._top_paths = {} self.dotfrs = dotfrs self.cache_root = cache_root self.sitepaths2vpaths = [] self.version = version def mount(self, name, path): """ XXX only support mount top dirs only now mount filesystem path to vfs """ #if not os.path.exists(path): # raise OSError('no mount path: '+ path) if name.startswith('/'): name = name[1:] self._top_paths[name] = path def setCacheRoot(self, path): """ where to push caches """ self.cache_root = path self.mount('cache', path) def mapSitepath2Vpath(self, site_path, vpath): """ map vpath to site path """ self.sitepaths2vpaths.append( (site_path, vpath) ) def sitepath2Vpath(self, site_path): if site_path[-1] != '/': site_path += '/' # 历史版本,直接找到对应的历史版本文件夹 if '/++versions++/' in site_path: site_path, version = site_path.split('/++versions++/') site_path = site_path.split('/') site_path.insert(-1, self.dotfrs) #_, ext = os.path.splitext(site_path[-1]) site_path.append(FRS_ARCHIVED_FOLDER_NAME) site_path.append(version) site_path = '/'.join(site_path) for _spath, _vpath in self.sitepaths2vpaths: if _spath[-1] != '/': _spath += '/' if site_path.startswith(_spath): if _vpath[-1] != '/': _vpath += '/' result = _vpath + site_path[len(_spath):] if result[-1] == '/': return result[:-1] return result raise ValueError('can not find a frs path for site path %s' % site_path) def vpath(self, ospath): """ transform ospath to vpath """ for root, path in self._top_paths.items(): if ospath.startswith(path + '/'): return '/%s%s' % (root, ospath[len(path):]) def ospath(self, vPath): """ transform to a real os path """ if not vPath.startswith('/'): raise OSError(vPath) parts = vPath.split('/') try: toppath = self._top_paths[parts[1]] except KeyError: if parts[1] == self.dotfrs: try: toppath = self._top_paths[parts[2]] except: raise OSError(vPath) basename = os.path.basename(toppath) basedir = os.path.dirname(toppath) return os.path.join(basedir, self.dotfrs, basename, *parts[3:]) raise OSError(vPath) return os.path.join(toppath, *parts[2:]) def frspath(self, vpath, *frs_subpaths): """ It is another kind of joinpath, which returns path in the .frs folder. """ return self.joinpath(self.dirname(vpath), \ self.dotfrs, self.basename(vpath), *frs_subpaths) def exists(self, vPath): try: path = self.ospath(vPath) except OSError: return False return os.path.exists(path) def joinpath(self, *arg): return posixpath.join(*arg) def basename(self, path): return posixpath.basename(path) def splitext(self, name): return os.path.splitext(name) def stat(self, vPath): return os.stat(self.ospath(vPath)) def dirname(self, path): return posixpath.dirname(path) def ismount(self, vPath): """ return if vPath is a mount folder """ return vPath[1:] in self.listdir('/') def isdir(self, vPath): return os.path.isdir(self.ospath(vPath)) def isfile(self, vPath): return os.path.isfile(self.ospath(vPath)) def atime(self, vPath): return os.path.getatime( self.ospath(vPath) ) def mtime(self, vPath): return os.path.getmtime( self.ospath(vPath) ) def ctime(self, vPath): return os.path.getctime( self.ospath(vPath) ) def getsize(self, vPath): return os.path.getsize( self.ospath(vPath) ) def listdir(self, vPath, pattern=None): if vPath == '/': return self._top_paths.keys() names = os.listdir(self.ospath(vPath)) if pattern is not None: names = fnmatch.filter(names, pattern) names = [name for name in names if not name.startswith(self.dotfrs) ] return names def dirs(self, vPath, pattern=None): names = [ name for name in self.listdir(vPath, pattern)\ if self.isdir(self.joinpath(vPath, name))] return names def files(self, vPath, pattern=None): names = [ name for name in self.listdir(vPath, pattern)\ if self.isfile(self.joinpath(vPath, name))] return names def open(self, vPath, mode='r'): return file(self.ospath(vPath), mode) def move(self, vPath1, vPath2): # can't remove mount folder if self.ismount(vPath1): raise Exception("can't remove mount folder %s" % vPath1) if self.ismount(vPath2): raise Exception("can't move to mount folder %s" % vPath2) umove(self.ospath(vPath1), self.ospath(vPath2) ) #notify(AssetMoved(self, vPath1, vPath2)) def mkdir(self, vPath, mode=0777): os.mkdir(self.ospath(vPath), mode) def makedirs(self, vPath, mode=0777): os.makedirs(self.ospath(vPath), mode) def getNewName(self, path, name): while self.exists(self.joinpath(path, name)): name = 'copy_of_' + name return name def remove(self, vPath): """ remove a file path""" os.remove(self.ospath(vPath) ) #notify(AssetRemoved(self, vpath)) def copyfile(self, vSrc, vDst): shutil.copyfile(self.ospath(vSrc), self.ospath(vDst)) def copytree(self, vSrc, vDst): # copy2 don't work well with encoding # in fact it is os.utime don't work well ossrc = self.ospath(vSrc) osdst = self.ospath(vDst) ucopytree(ossrc, osdst, symlinks=False) def rmtree(self, vPath, ignore_errors=False, onerror=None): # can't remove mount folder if self.ismount(vPath): raise Exception("can't remove mount folder %s" % vPath) shutil.rmtree(self.ospath(vPath), ignore_errors, onerror) def touch(self, vpath): fd = os.open(self.ospath(vpath), os.O_WRONLY | os.O_CREAT, 0666) os.close(fd) def walk(self, top, topdown=True, onerror=None): if top == '/': mount_dirs = self._top_paths.keys() yield '/', mount_dirs,[] for name in mount_dirs: for item in self.walk('/' + name, topdown, onerror): yield item else: top_ospath = os.path.normpath(self.ospath(top)) top_ospath_len = len(top_ospath) for dirpath, dirnames, filenames in os.walk(top_ospath,topdown,onerror): if self.dotfrs in dirnames: dirnames.remove(self.dotfrs) if dirnames or filenames: dir_sub_path = dirpath[top_ospath_len+1:].replace(os.path.sep, '/') if dir_sub_path: yield self.joinpath(top, dirpath[top_ospath_len+1:].replace(os.path.sep, '/')), dirnames, filenames else: yield top, dirnames, filenames # asset management def removeAsset(self, path): frsPath = self.frspath(path) if self.exists(frsPath): self.rmtree(frsPath) if self.exists(path): if self.isfile(path): self.remove(path) else: self.rmtree(path) CacheMixin.removeCache(self, path) def moveAsset(self, src, dst): """ rename or move a file or folder """ frsSrc = self.frspath(src) if self.exists(frsSrc): frsDst = self.frspath(dst) if not self.exists( self.dirname(frsDst) ): self.makedirs(self.dirname(frsDst)) self.move(frsSrc, frsDst ) if not self.exists( self.dirname(dst) ): self.makedirs( self.dirname(dst) ) self.move(src, dst) CacheMixin.moveCache(self, src, dst) def copyAsset(self, src, dst, **kw): """ copy folder / file and associated subfiles, not include archives don't keep stat """ if not self.exists(src): raise ValueError("source path is not exists: %s" % src) if self.isfile(src): self.copyfile(src, dst) else: # copy folder if not self.exists(dst): self.makedirs(dst) for name in self.listdir(src): self.copyAsset(self.joinpath(src, name), self.joinpath(dst, name), copycache=0) # copy cache CacheMixin.copyCache(self, src,dst) def fullcopyAsset(self, src, dst): """ copy a folder or a file, include archives keep stat """ if self.isfile(src): self.copyfile(src, dst) else: self.copytree(src, dst) frsSrc = self.frspath(src) if self.exists(frsSrc): frsDst = self.frspath(dst) frsDstDir = self.dirname(frsDst) if not self.exists(frsDstDir ): self.makedirs(frsDstDir) self.copytree(frsSrc, frsDst )
zopen.frs
/zopen.frs-1.2.2.tar.gz/zopen.frs-1.2.2/zopen/frs/frs.py
frs.py
import os import shutil from config import FRS_CACHE_FOLDER_PREFIX, FRS_ARCHIVED_FOLDER_NAME from utils import ucopytree class CacheMixin: def getCacheFolder(self, vpath, cachename=None): """ get os path of cache folder for vpath """ cachebase = os.path.join(self.cache_root, *vpath.split('/') ) if cachename: foldername = FRS_CACHE_FOLDER_PREFIX + cachename return os.path.join(cachebase, foldername) else: return cachebase def getCacheDecompressFileVpath(self, vpath, cachename=None, subpath=''): return '/cache' + vpath + '/' + FRS_CACHE_FOLDER_PREFIX + cachename + '/decompress' + subpath # TODO remove def getCacheDecompress(self, vpath, cachename=None): """ get os path of cache decompress for vpath """ return os.path.join(self.getCacheFolder(vpath, cachename), 'decompress') # TODO remove def getCacheDecompressPreview(self, vpath, cachename=None): """ get os path of cache decompress preview for vpath """ return os.path.join(self.getCacheFolder(vpath, cachename), 'decompresspreview') def hasCache(self, vpath, cachename=None): return os.path.exists(self.getCacheFolder(vpath, cachename)) def removeCache(self, vpath,cachename=None): while True: vpath = '/cache' + vpath if self.exists(vpath): self.rmtree(vpath) else: break def moveCache(self, src, dst): while True: src, dst = '/cache' + src, '/cache' + dst if self.exists(src): self.move(src, dst) else: break def copyCache(self, src, dst, **kw): while True: src, dst = '/cache' + src, '/cache' + dst if self.exists(src): if self.exists(dst): # 有时候事务不干净,这个会存在 self.rmtree(dst) self.copytree(src, dst) else: break
zopen.frs
/zopen.frs-1.2.2.tar.gz/zopen.frs-1.2.2/zopen/frs/cache.py
cache.py
import time import datetime import os import shutil import socket from random import random from hashlib import md5 from config import FS_CHARSET from types import UnicodeType import array, binascii def int2ascii(value): return binascii.b2a_hex(buffer(array.array('l', (value,)))) # 4byte def ascii2int(value): bin = binascii.a2b_hex(value) index, sum = 0, 0 for c in bin: sum += ord(c) << index index += 8 return sum def timetag(timestamp=None): if the_time is None: # use gmt time the_time = time.gmtime() return time.strftime('%Y-%m-%d-%H-%M-%S', the_time) else: the_time = datetime.datetime.fromtimestamp(timstamp) return the_time.strftime('%Y-%m-%d-%H-%M-%S') def ucopy2(ossrc, osdst): # ucopy2 dosn't work with unicode filename yet if type(osdst) is UnicodeType and \ not os.path.supports_unicode_filenames: ossrc = ossrc.encode(FS_CHARSET) osdst = osdst.encode(FS_CHARSET) shutil.copy2(ossrc, osdst) def ucopytree(ossrc, osdst, symlinks=False): # ucopy2 dosn't work with unicode filename yet if type(osdst) is UnicodeType and \ not os.path.supports_unicode_filenames: ossrc = ossrc.encode(FS_CHARSET) osdst = osdst.encode(FS_CHARSET) shutil.copytree(ossrc, osdst, symlinks) def umove(ossrc, osdst): # umove dosn't work with unicode filename yet if type(osdst) is UnicodeType and \ not os.path.supports_unicode_filenames: ossrc = ossrc.encode(FS_CHARSET) osdst = osdst.encode(FS_CHARSET) # windows move 同一个文件夹会有bug,这里改为rename # 例子: c:\test move to c:\Test if ossrc.lower() == osdst.lower(): os.rename(ossrc, osdst) else: shutil.move(ossrc, osdst) try: _v_network = str(socket.gethostbyname(socket.gethostname())) except: _v_network = str(random() * 100000000000000000L) def make_uuid(*args): t = str(time.time() * 1000L) r = str(random()*100000000000000000L) data = t +' '+ r +' '+ _v_network +' '+ str(args) uid = md5(data).hexdigest() return uid def rst2frs(filename): """ 读取rst的参数,自动补充frs的json元数据 """ # TODO # 读取大标题 # 读取描述信息 # 读取作者 # 读取关键字 # 当前时间为创建时间 # 写入.frs文件夹
zopen.frs
/zopen.frs-1.2.2.tar.gz/zopen.frs-1.2.2/zopen/frs/utils.py
utils.py
from config import FRS_REMOVED_FOLDER_NAME from utils import timetag, int2ascii, ascii2int import datetime import time class RecycleMixin: """ trushcase enables mixin for file repository system """ def removedpath(self, path, timestamp): if type(timestamp) in [str, unicode]: timestamp = ascii2int(timestamp) root, subpath= path[1:].split('/', 1) removeName = "%s.%s" % ( int2ascii(int(timestamp)), int2ascii(hash(subpath))) return self.joinpath('/',root, FRS_REMOVED_FOLDER_NAME, removeName) def recycleAssets(self, path, srcNames,timestamp=None): """ remove file or tree to trush folder """ removedPath = self.removedpath(path, timestamp) for name in srcNames: srcPath = self.joinpath(path, name) dstPath = self.joinpath(removedPath, name) # remove cache file self.removeCache(srcPath) # just move to recycle self.moveAsset(srcPath, dstPath) def listRemoves(self, path): """ retime remved timestamps """ recyle = self.joinpath(root, FRS_REMOVED_FOLDER_NAME) removes = [] root, subpath= path[1:].split('/', 1) pathhash = int2ascii(hash(subpath)) for filename in self.listdir(recyle): timestamp , _pathhash = filename.split('.', 1) if _pathhash == pathhash: removes.append(timestamp) return removes def listRemovedAssets(self, path, timestamp): removedPath = self.removedpath(path, timestamp) return self.listdir(removedPath) def revertRemove(self, path, removeName, assetName, reset_parent=None, new_name=''): """ 恢复一个删除的文件 """ removedPath = self.removedpath(path, removeName) src_name = assetName srcPath = self.joinpath(removedPath, src_name) dst_name = src_name if not new_name else new_name if reset_parent: dst_name = self.getNewName(reset_parent, dst_name) dstPath = self.joinpath(reset_parent, dst_name) else: dst_name = self.getNewName(path, dst_name) dstPath = self.joinpath(path, dst_name) self.moveAsset(srcPath, dstPath) # 已经全部恢复,删除这个文件夹 if not self.listdir(removedPath): self.rmtree(removedPath) return dst_name def realRemove(self, path, removeName, assetNames=[]): removedPath = self.removedpath(path, removeName) if not self.exists(removedPath): return if not assetNames: self.rmtree(removedPath) return for name in assetNames: srcPath = self.joinpath(removedPath, name) self.removeAsset(srcPath) if not self.listdir(removedPath): self.rmtree(removedPath) def walkTrashBox(self, top_path='/', days=0, cmp_result=0): """ -1: older than history day; 0: all; 1: greater than history day """ # XXX need to rewrite cur_date = datetime.datetime(*time.gmtime()[:7]) history_date = cur_date - datetime.timedelta(days) history_date_name = timetag(history_date) if top_path != '/': removeNames = self.listRemoves(top_path) if cmp_result != 0: removeNames = [removeName for removeName in removeNames if cmp(removeName, history_date_name) == cmp_result] if removeNames: yield top_path, removeNames for parent_path, dirnames, filenames in self.walk(top_path): for dirname in dirnames: dir_vpath = self.joinpath(parent_path, dirname) removeNames = self.listRemoves(dir_vpath) if cmp_result != 0: removeNames = [removeName for removeName in removeNames if cmp(removeName, history_date_name) == cmp_result] if removeNames: yield dir_vpath, removeNames def cleanTrushBox(self, top_path='/', days=30, cmp_result=-1): """ delete all items in trushboxes older than <keepDays> """ for dir_vpath, remove_names in self.walkTrashBox(top_path, days, cmp_result): for remove_name in remove_names: self.realRemove(dir_vpath, remove_name)
zopen.frs
/zopen.frs-1.2.2.tar.gz/zopen.frs-1.2.2/zopen/frs/recycle.py
recycle.py
.. contents:: Quickstart ========== You can start a new Zope-based web application from scratch with just two commands:: $ easy_install zopeproject $ zopeproject HelloWorld The second command will ask you for a name and password for an initial administrator user. It will also ask you where to put the Python packages ("eggs") that it downloads. This way multiple projects created with ``zopeproject`` can share the same packages and won't have to download them each time (see also `Sharing eggs among sandboxes`_ below). (Note: Depending on how they installed Python, Unix/Linux users may have to invoke ``easy_install`` with ``sudo``. If that's not wanted or possible, ``easy_install`` can be invoked with normal privileges inside a `virtual-python`_ or workingenv_). After asking these questions, ``zopeproject`` will download the `zc.buildout`_ package that will be used to build the sandbox, unless it is already installed locally. Then it will invoke ``buildout`` to download Zope and its dependencies. If you're doing this for the first time or not sharing packages between different projects, this may take a while. When ``zopeproject`` is done, you will find a typical Python package development environment in the ``HelloWorld`` directory: the package itself (``helloworld``) and a ``setup.py`` script. There's also a ``bin`` directory that contains scripts, such as ``paster`` which can be used to start the application:: $ cd HelloWorld $ bin/paster serve deploy.ini You may also use the ``helloworld-ctl`` script which works much like the ``zopectl`` script from Zope instances:: $ bin/helloworld-ctl foreground After starting the application, you should now be able to go to http://localhost:8080 and see the default start screen of Zope. You will also be able to log in with the administrator user account that you specified earlier. Notes for Windows users ----------------------- Some packages required by Zope contain C extension modules. There may not always be binary Windows distributions available for these packages. In this case, setuptools will try to compile them from source which will likely fail if you don't have a compiler such as the Microsoft Visual C compiler installed. Alternatively, you can install the free MinGW_ compiler: 1. Download ``MinGW-x.y.z.exe`` from http://www.mingw.org/ and run it to do a full install into the standard location (ie. ``C:\MinGW``). 2. Tell Python to use the MinGW compiler by creating ``C:\Documents and Settings\YOUR USER\pydistutils.cfg`` with the following contents:: [build] compiler=mingw32 3. Let Python know about the MinGW installation and the ``pydistutils.cfg`` file. To do that, go to the *Control Panel*, *System* section, *Advanced* tab and click on the *Environment variables* button. Add the ``C:\MinGW\bin`` directory to your ``Path`` environment variable (individual paths are delimited by semicolons). Also add another environment variable called ``HOME`` with the following value:: C:\Documents and Settings\YOUR USER When installing packages from source, Python should now automatically use the MinGW compiler to build binaries. Sharing eggs among sandboxes ---------------------------- A great feature of `zc.buildout`_ is the ability to share downloaded Python packages ("eggs") between sandboxes. This is achieved by placing all eggs in a shared location. zopeproject will ask for this location each time. The setting will become part of ``buildout.cfg``. It could very well be that your shared eggs directory is different from the suggested default value, so it would be good to avoid having to type it in every time. Furthermore, you may want to avoid having system-dependent paths appear in ``buildout.cfg`` because they hinder the repeatibility of the setup on other machines. A way to solve these problems is to configure a user-specific default eggs directory for buildout in your home directory: ``~/.buildout/default.cfg``:: [buildout] eggs-directory = /home/philipp/eggs zopeproject will understand that you have this default value and change its own default when asking you for the eggs directory. If you just hit enter there (thereby accepting the default in ``~/.buildout/default.cfg``), the generated ``buildout.cfg`` will not contain a reference to a path. Command line options for zopeproject ==================================== ``--no-buildout`` When invoked with this option, ``zopeproject`` will only create the project directory with the standard files in it, but it won't download and invoke ``zc.buildout``. ``--newer`` This option enables the ``newest = true`` setting in ``buildout.cfg``. That way, buildout will always check for newer versions of eggs online. If, for example, you have outdated versions of your dependencies in your shared eggs directory, this switch will force the download of newer versions. Note that you can always edit ``buildout.cfg`` to change this behaviour in an existing project area, or you can invoke ``bin/buildout`` with the ``-n`` option. ``--svn-repository=REPOS`` This option will import the project directory and the files in it into the given subversion repository and provide you with a checkout of the ``trunk``. ``REPOS`` is supposed to be a repository path that is going to be created, along with ``tags``, ``branches`` and ``trunk`` below that. This checkin ignores any files and directories created by zc.buildout. ``-v``, ``--verbose`` When this option is enabled, ``zopeproject`` won't hide the output of ``easy_install`` (used to install ``zc.buildout``) and the ``buildout`` command. The sandbox =========== What are the different files and directories for? ------------------------------------------------- ``deploy.ini`` Configuration file for PasteDeploy_. It defines which server software to launch and which WSGI application to invoke upon each request (which is defined in ``src/helloworld/startup.py``). You may also define WSGI middlewares here. Invoke ``bin/paster serve`` with this file as an argument. ``debug.ini`` Alternate configuration for PasteDeploy_ that configures middleware which intercepts exceptions for interactive debugging. See `Debugging exceptions`_ below. ``zope.conf`` This file will be read by the application factory in ``src/helloworld/startup.py``. Here you can define which ZCML file the application factory should load upon startup, the ZODB database instance, an event log as well as whether developer mode is switched on or not. ``site.zcml`` This file is referred to by ``zope.conf`` and will be loaded by the application factory. It is the root ZCML file and includes everything else that needs to be loaded. 'Everything else' typically is just the application package itself, ``helloworld``, which then goes on to include its dependencies. Apart from this, ``site.zcml`` also defines the anonymous principal and the initial admin principal. ``setup.py`` This file defines the egg of your application. That definition includes listing the package's dependencies (mostly Zope eggs) and the entry point for the PasteDeploy_ application factory. ``buildout.cfg`` This file tells `zc.buildout`_ what to do when the buildout is executed. This mostly involves executing ``setup.py`` to enable the ``HelloWorld`` egg (which also includes downloading its dependencies), as well as installing PasteDeploy_ for the server. This files also refers to the shared eggs directory (``eggs-directory``) and determines whether buildout should check whether newer eggs are available online or not (``newest``). ``bin/`` This directory contains all executable scripts, e.g for starting the application (``paster``), installing or reinstalling dependencies (``buildout``), or invoking the debug prompt (``helloworld-debug``). It also contains a script (``python``) that invokes the standard interpreter prompt with all packages on the module search path. ``src/`` This directory contains the Python package(s) of your application. Normally there's just one package (``helloworld``), but you may add more to this directory if you like. The ``src`` directory will be placed on the interpreter's search path by `zc.buildout`_. ``var/`` The ZODB filestorage will place its files (``Data.fs``, lock files, etc.) here. Renaming -------- You can rename or move the sandbox directory any time you like. Just be sure to run ``bin/buildout`` again after doing so. Renaming the sandbox directory won't change the name of the egg, however. To do that, you'll have to change the ``name`` parameter in ``setup.py``. Sharing and archiving sandboxes ------------------------------- You can easily share sandboxes with co-developers or archive them in a version control system such as subversion. You can theoretically share or archive the whole sandbox directory, though it's recommended **not to include** the following files and directories because they can and will be generated by zc.buildout from the configuration files: * ``bin/`` * ``parts/`` * ``develop-eggs/`` * all files in ``var/`` * all files in ``log/`` * ``.installed.cfg`` If you receive a sandbox thas has been archived (e.g. by checking it out from a version control system), you will first have to bootstrap it in order to obtain the ``bin/buildout`` executable. To do that, use the ``buildout`` script from any other sandbox on your machine:: $ .../path/to/some/sandbox/bin/buildout bootstrap Now the sandbox has its own ``bin/buildout`` script and can be installed:: $ bin/buildout Developing ========== First steps with your application --------------------------------- After having started up Zope for the first time, you'll likely want to start developing your web application. Code for your application goes into the ``helloworld`` package that was created by zopeproject in the ``src`` directory. For example, to get a simple "Hello world!" message displayed, create ``src/helloworld/browser.py`` with the following contents:: from zope.publisher.browser import BrowserPage class HelloPage(BrowserPage): def __call__(self): return "<html><body><h1>Hello World!</h1></body></html>" Then all you need to do is hook up the page in ZCML. To do that, add the following directive towards the end of ``src/helloworld/configure.zcml``:: <browser:page for="*" name="hello" class=".browser.HelloPage" permission="zope.Public" /> Note that you'll likely need to define the ``browser`` namespace prefix at the top of the file:: <configure xmlns="http://namespaces.zope.org/zope" xmlns:browser="http://namespaces.zope.org/browser" > After having restarted the application using ``paster serve``, you can visit http://localhost:8080/hello to see the page in action. Adding dependencies to the application -------------------------------------- The standard ``setup.py`` and ``configure.zcml`` files list a set of standard dependencies that are typical for most Zope applications. You may obviously remove things from this list, but typically you'll want to re-use more libraries that others have written. Many, if not most, of additional Zope and third party libraries are `listed on the Python Cheeseshop`_. Let's say you wanted to reuse the ``some.library`` package in your application. The first step would be to add it to the list of dependencies in ``setup.py`` (``install_requires``). If this package defined any Zope components, you would probably also have to load its ZCML configuration by adding the following line to ``src/helloworld/configure.zcml``:: <include package="some.library" /> After having changed ``setup.py``, you would want the newly added dependency to be downloaded and added to the search path of ``bin/paster``. To do that, simply invoke the buildout:: $ bin/buildout Writing and running tests ------------------------- Automated tests should be placed in Python modules. If they all fit in one module, the module should simply be named ``tests``. If you need many modules, create a ``tests`` package and put the modules in there. Each module should start with ``test`` (for example, the full dotted name of a test module could be ``helloworld.tests.test_app``). If you prefer to separate functional tests from unit tests, you can put functional tests in an ``ftests`` module or package. Note that this doesn't matter to the test runner whatsoever, it doesn't care about the location of a test case. Each test module should define a ``test_suite`` function that constructs the test suites for the test runner, e.g.:: def test_suite(): return unittest.TestSuite([ unittest.makeSuite(ClassicTestCase), DocTestSuite(), DocFileSuite('README.txt', package='helloworld'), ]) To run all tests in your application's packages, simply invoke the ``bin/test`` script:: $ bin/test Functional tests ---------------- While unit test typically require no or very little test setup, functional tests normally bootstrap the whole application's configuration to create a real-life test harness. The configuration file that's responsible for this test harness is ``ftesting.zcml``. You can add more configuration directives to it if you have components that are specific to functional tests (e.g. mockup components). To let a particular test run inside this test harness, simply apply the ``helloworld.testing.FunctionalLayer`` layer to it:: from helloworld.testing import FunctionalLayer suite.layer = FunctionalLayer You can also simply use one of the convenience test suites in ``helloworld.testing``: * ``FunctionalDocTestSuite`` (based on ``doctest.DocTestSuite``) * ``FunctionalDocFileSuite`` (based on ``doctest.DocFileSuite``) * ``FunctionalTestCase`` (based on ``unittest.TestCase``) Debugging ========= The interpreter prompt ---------------------- Use the ``bin/python`` script if you'd like test some components from the interpreter prompt and don't need the component registrations nor access to the ZODB. If you do need those, go on to the next section. The interactive debug prompt ---------------------------- Occasionally, it is useful to be able to interactively debug the state of the application, such as walking the object hierarchy in the ZODB or looking up components manually. This can be done with the interactive debug prompt, which is available under ``bin/helloworld-debug``:: $ bin/helloworld-debug Welcome to the interactive debug prompt. The 'root' variable contains the ZODB root folder. The 'app' variable contains the Debugger, 'app.publish(path)' simulates a request. >>> You can now get a folder listing of the root folder, for example:: >>> list(root.keys()) [u'folder', u'file'] Debugging exceptions -------------------- In case your application fails with an exception, it can be useful to inspect the circumstances with a debugger. This is possible with the ``z3c.evalexception`` WSGI middleware. When an exception occurs in your application, stop the process and start it up again, now using the ``debug.ini`` configuration file:: $ bin/paster serve debug.ini When you then repeat the steps that led to the exception, you will see the relevant traceback in your browser, along with the ability to view the corresponding source code and to issue Python commands for inspection. If you prefer the Python debugger pdb_, replace ``ajax`` with ``pdb`` in the WSGI middleware definition in ``debug.ini``:: [filter-app:main] use = egg:z3c.evalexception#pdb next = zope Note: Even exceptions such as Unauthorized (which normally leads to a login screen) or NotFound (which normally leads to an HTTP 404 response) will trigger the debugger. Deploying ========= Disabling debugging tools ------------------------- Before deploying a zopeproject-based application, you should make sure that any debugging tools are disabled. In particular, this includes * making sure there's no debugging middleware in ``deploy.ini`` (normally these should be configured in ``debug.ini`` anyway), * switching off ``developer-mode`` in ``zope.conf``, * disabling the APIDoc tool in ``site.zcml``, * disabling the bootstrap administrator principal in ``site.zcml``. Linux/Unix ---------- You can use the ``helloworld-ctl`` script to start the server process in daemon mode. It works much like the ``apachectl`` tool as known from the Apache HTTPD server or INIT scripts known from Linux:: $ bin/helloworld-ctl start To stop the server, issue:: $ bin/helloworld-ctl stop Other commands, such as ``status`` and ``restart`` are supported as well. Windows ------- There's currently no particular support for deployment on Windows other than what ``paster`` provides. Integration with Windows services, much like what could be found in older versions of Zope, is planned. Reporting bugs or asking questions about zopeproject ==================================================== zopeproject maintains a bugtracker and help desk on Launchpad: https://launchpad.net/zopeproject Questions can also be directed to the zope3-users mailinglist: http://mail.zope.org/mailman/listinfo/zope3-users Credits ======= zopeproject is written and maintained by Philipp von Weitershausen. It was inspired by the similar grokproject_ tool from the same author. James Gardner, Martijn Faassen, Jan-Wijbrand Kolman and others gave valuable feedback on the early prototype presented at EuroPython 2007. Michael Bernstein gave valuable feedback and made many suggestions for improvements. zopeproject is distributed under the `Zope Public License, v2.1`_. Copyright (c) by Zope Corporation and Contributors. .. _virtual-python: http://peak.telecommunity.com/DevCenter/EasyInstall#creating-a-virtual-python .. _workingenv: http://cheeseshop.python.org/pypi/workingenv.py .. _zc.buildout: http://cheeseshop.python.org/pypi/zc.buildout .. _MingW: http://www.mingw.org .. _PasteDeploy: http://pythonpaste.org/deploy/ .. _listed on the Python Cheeseshop: http://cheeseshop.python.org/pypi?:action=browse&c=515 .. _pdb: http://docs.python.org/lib/module-pdb.html .. _grokproject: http://cheeseshop.python.org/pypi/grokproject .. _Zope Public License, v2.1: http://www.zope.org/Resources/ZPL
zopeproject
/zopeproject-0.4.2.tar.gz/zopeproject-0.4.2/README.txt
README.txt
Introduction ============ This is a ZopeSkel template package for creating a skeleton Plone add-on package. The skeleton package installs a plone.app.browserlayer browserlayer and associated css and js resources. Use this package when you want to build an add-on that adds css or js functionality without a theme. The advantage of this is that you may use the functionality with different themes. This is a development tool. You should be familiar with Plone and buildout to use it. Installation ============ Add these lines into buildout:: [buildout] parts = zopeskel [zopeskel] recipe = zc.recipe.egg eggs = ZopeSkel Paste PasteDeploy PasteScript zopeskel.browserlayer ${buildout:eggs} And run the buildout Usage ====== Creating a dexterity content package, typically done in your buildout's src directory:: ../bin/zopeskel browserlayer Notes ===== Egg Directories --------------- In order to support local commands, ZopeSkel/Paster will create Paste, PasteDeploy and PasteScript eggs inside your product. These are only needed for development. You can and should remove them from your add-on distribution. Errors ------ If you hit and error like this:: pkg_resources.DistributionNotFound: plone.app.relationfield: Not Found for: my.product (did you run python setup.py develop?) when attempting to run `paster addcontent`, then you need to ensure that Paster knows about all the relevant eggs from your buildout. Add `${instance:eggs}` to your `paster` section in your buildout, thusly:: [zopeskel] recipe = zc.recipe.egg eggs = ... ${instance:eggs} entry-points = paster=paste.script.command:run where `instance` is the name of your ``plone.recipe.zope2instance`` section. Re-run the buildout and the issue should be resolved.
zopeskel.browserlayer
/zopeskel.browserlayer-1.0.zip/zopeskel.browserlayer-1.0/README.rst
README.rst
import os, shutil, sys, tempfile, urllib2 from optparse import OptionParser tmpeggs = tempfile.mkdtemp() is_jython = sys.platform.startswith('java') # parsing arguments parser = OptionParser() parser.add_option("-v", "--version", dest="version", help="use a specific zc.buildout version") parser.add_option("-d", "--distribute", action="store_true", dest="distribute", default=False, help="Use Disribute rather than Setuptools.") parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args += ['-c', options.config_file] if options.version is not None: VERSION = '==%s' % options.version else: VERSION = '' USE_DISTRIBUTE = options.distribute args = args + ['bootstrap'] to_reload = False try: import pkg_resources if not hasattr(pkg_resources, '_distribute'): to_reload = True raise ImportError except ImportError: ez = {} if USE_DISTRIBUTE: exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True) else: exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0) if to_reload: reload(pkg_resources) else: import pkg_resources if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: def quote (c): return c cmd = 'from setuptools.command.easy_install import main; main()' ws = pkg_resources.working_set if USE_DISTRIBUTE: requirement = 'distribute' else: requirement = 'setuptools' if is_jython: import subprocess assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd', quote(tmpeggs), 'zc.buildout' + VERSION], env=dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ).wait() == 0 else: assert os.spawnle( os.P_WAIT, sys.executable, quote (sys.executable), '-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION, dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ) == 0 ws.add_entry(tmpeggs) ws.require('zc.buildout' + VERSION) import zc.buildout.buildout zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs) ############################################################################## # # Copyright (c) 2006 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Bootstrap a buildout-based project Simply run this script in a directory containing a buildout.cfg. The script accepts buildout command-line options, so you can use the -c option to specify an alternate configuration file. $Id$ """ import os, shutil, sys, tempfile, urllib2 from optparse import OptionParser tmpeggs = tempfile.mkdtemp() is_jython = sys.platform.startswith('java') # parsing arguments parser = OptionParser() parser.add_option("-v", "--version", dest="version", help="use a specific zc.buildout version") parser.add_option("-d", "--distribute", action="store_true", dest="distribute", default=False, help="Use Disribute rather than Setuptools.") parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args += ['-c', options.config_file] if options.version is not None: VERSION = '==%s' % options.version else: VERSION = '' USE_DISTRIBUTE = options.distribute args = args + ['bootstrap'] to_reload = False try: import pkg_resources if not hasattr(pkg_resources, '_distribute'): to_reload = True raise ImportError except ImportError: ez = {} if USE_DISTRIBUTE: exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True) else: exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0) if to_reload: reload(pkg_resources) else: import pkg_resources if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: def quote (c): return c cmd = 'from setuptools.command.easy_install import main; main()' ws = pkg_resources.working_set if USE_DISTRIBUTE: requirement = 'distribute' else: requirement = 'setuptools' if is_jython: import subprocess assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd', quote(tmpeggs), 'zc.buildout' + VERSION], env=dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ).wait() == 0 else: assert os.spawnle( os.P_WAIT, sys.executable, quote (sys.executable), '-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION, dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ) == 0 ws.add_entry(tmpeggs) ws.require('zc.buildout' + VERSION) import zc.buildout.buildout zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
zopeskel.browserlayer
/zopeskel.browserlayer-1.0.zip/zopeskel.browserlayer-1.0/zopeskel/browserlayer/templates/browserlayer/bootstrap.py
bootstrap.py
README for the 'browser/stylesheets/' directory =============================================== This folder is a Zope 3 Resource Directory acting as a repository for stylesheets. Its declaration is located in 'browser/configure.zcml': <!-- Resource directory for stylesheets --> <browser:resourceDirectory name="${namespace_package}.${package}.stylesheets" directory="stylesheets" layer=".interfaces.${blIFaceName}" /> A stylesheet placed in this directory (e.g. 'main.css') can be accessed from this relative URL: "++resource++${namespace_package}.${package}.stylesheets/main.css" Note that it might be better to register each of these resources separately if you want them to be overridable from zcml directives. The only way to override a resource in a resource directory is to override the entire directory (all elements have to be copied over). A Zope 3 browser resource declared like this in 'browser/configure.zcml': <browser:resource name="main.css" file="stylesheets/main.css" layer=".interfaces.${blIFaceName}" /> can be accessed from this relative URL: "++resource++main.css" Notes ----- * Stylesheets registered as Zope 3 resources might be flagged as not found in the 'portal_css' tool if the layer they are registered for doesn't match the default skin set in 'portal_skins'. This can be confusing but it must be considered as a minor bug in the CSS registry instead of a lack in the way Zope 3 resources are handled in Zope 2. * There might be a way to interpret DTML from a Zope 3 resource view. Although, if you need to use DTML for setting values in a stylesheet (the same way as in default Plone stylesheets where values are read from 'base_properties'), it is much easier to store it in a directory that is located in the 'skins/' folder of your package, registered as a File System Directory View in the 'portal_skins' tool, and added to the layers of your skin. * Customizing/overriding stylesheets that are originally accessed from the 'portal_skins' tool (e.g. Plone default stylesheets) can be done inside that tool only. There is no known way to do it with Zope 3 browser resources. Vice versa, there is no known way to override a Zope 3 browser resource from a skin layer in 'portal_skins'.
zopeskel.browserlayer
/zopeskel.browserlayer-1.0.zip/zopeskel.browserlayer-1.0/zopeskel/browserlayer/templates/browserlayer/+namespace_package+/+package+/browser/resources/README.txt_tmpl
README.txt_tmpl
This directory will be the home for internationalizations for your layer package. For more information on internationalization please consult the following sources: http://plone.org/documentation/kb/product-skin-localization http://plone.org/documentation/kb/i18n-for-developers http://www.mattdorn.com/content/plone-i18n-a-brief-tutorial/ http://grok.zope.org/documentation/how-to/how-to-internationalize-your-application http://maurits.vanrees.org/weblog/archive/2010/10/i18n-plone-4 http://maurits.vanrees.org/weblog/archive/2007/09/i18n-locales-and-plone-3.0 http://n2.nabble.com/Recipe-for-overriding-translations-td3045492ef221724.html http://dev.plone.org/plone/wiki/TranslationGuidelines
zopeskel.browserlayer
/zopeskel.browserlayer-1.0.zip/zopeskel.browserlayer-1.0/zopeskel/browserlayer/templates/browserlayer/+namespace_package+/+package+/locales/README.txt
README.txt
Introduction ============ Dexterity is a content-type development tool for Plone. It supports Through-The-Web and filesystem development of new content types for Plone. zopeskel.dexterity provides a mechanism to quickly create Dexterity add on skeletons. It also makes it easy to add new content types to an existing skeleton. New content types built with this tool will support round-trip elaboration with Dexterity's TTW schema editor. This is a development tool. You should be familiar with Plone and buildout to use it. You should have already installed Dexterity in your Plone development instance and be ready to start learning to use it. Installation ============ *zopeskel.dexterity is meant for use with the ZopeSkel 2.x series. It is not compatible with ZopeSkel > 3.0dev (aka Templer). For Dexterity templates for use with Templer, use templer.dexterity.* *zopeskel.dexterity 1.5+ is meant for use with Plone 4.3+. If you're using an earlier version of Plone, pick the latest zopeskel.dexterity 1.4.x.* Add these lines into buildout:: [buildout] parts = zopeskel [zopeskel] recipe = zc.recipe.egg eggs = ZopeSkel < 3.0dev Paste PasteDeploy PasteScript zopeskel.dexterity ${buildout:eggs} And run the buildout Usage ====== Creating a dexterity content package, typically done in your buildout's src directory:: ../bin/zopeskel dexterity Adding a content-type skeleton to an existing package:: cd yourbuildout/src/your-product ../../bin/paster addcontent dexterity_content Adding a behavior skeleton:: cd yourbuildout/src/your-product ../../bin/paster addcontent dexterity_behavior Notes ===== Egg Directories --------------- In order to support local commands, ZopeSkel/Paster will create Paste, PasteDeploy and PasteScript eggs inside your product. These are only needed for development. You can and should remove them from your add-on distribution. Errors ------ If you hit and error like this:: pkg_resources.DistributionNotFound: plone.app.relationfield: Not Found for: my.product (did you run python setup.py develop?) when attempting to run `paster addcontent`, then you need to ensure that Paster knows about all the relevant eggs from your buildout. Add `${instance:eggs}` to your `paster` section in your buildout, thusly:: [zopeskel] recipe = zc.recipe.egg eggs = ... ${instance:eggs} entry-points = paster=paste.script.command:run where `instance` is the name of your ``plone.recipe.zope2instance`` section. Re-run the buildout and the issue should be resolved.
zopeskel.dexterity
/zopeskel.dexterity-1.5.4.1.zip/zopeskel.dexterity-1.5.4.1/README.rst
README.rst
import os import os.path from zopeskel.base import var, StringChoiceVar from zopeskel.localcommands import ZopeSkelLocalTemplate from Cheetah.Template import Template as cheetah_template class DexteritySubTemplate(ZopeSkelLocalTemplate): use_cheetah = True parent_templates = ['dexterity'] class DexterityContent(DexteritySubTemplate): """ A Content Type skeleton """ _template_dir = 'templates/dexterity/content' summary = "A content type skeleton" vars = [ var('contenttype_name', 'Content type name ', default='Example Type'), var('contenttype_description', 'Content type description ', default='Description of the Example Type'), var('folderish', 'True/False: Content type should act as a container ', default=False), var('global_allow', 'True/False: Globally addable ', default=True), var('allow_discussion', 'True/False: Allow discussion ', default=False), ] def pre(self, command, output_dir, vars): cfg = open(os.path.join(output_dir, 'configure.zcml')) zcml = cfg.read() cfg.close() grokish = '<grok:grok package=' in zcml vars['grokish'] = grokish and 'True' or 'False' relations = 'plone.app.relationfield' in zcml vars['relations'] = relations and 'True' or 'False' vars['contenttype_classname'] = vars['contenttype_name'].replace(" ", "") vars['contenttype_dottedname'] = vars['package_dotted_name'] + '.' + vars['contenttype_classname'].lower() vars['schema_name'] = vars['contenttype_classname'] + "Schema" vars['content_class_filename'] = vars['contenttype_name'].replace(" ", "_").lower() vars['types_xml_filename'] = vars['contenttype_dottedname'] vars['interface_name'] = "I" + vars['contenttype_classname'] vars['add_permission_name'] = vars['package_dotted_name'] + ': Add ' + vars['contenttype_name'] class DexterityBehavior(DexteritySubTemplate): """ A Content Type skeleton """ _template_dir = 'templates/dexterity/behavior' summary = "A behavior skeleton" vars = [ var('behavior_name', 'Behavior name ', default='Example Behavior'), var('behavior_description', 'Behavior description ', default='Description of the Example behavior'), ] def pre(self, command, output_dir, vars): vars['behavior_classname'] = vars['behavior_name'].replace(" ", "") vars['behavior_interfacename'] = 'I' + vars['behavior_classname'] vars['behavior_filename'] = vars['behavior_classname'].lower() vars['behavior_short_dottedadapter'] = '.' + vars['behavior_filename'] + '.' + vars['behavior_classname'] vars['behavior_short_dottedinterface'] = '.' + vars['behavior_filename'] + '.' + vars['behavior_interfacename']
zopeskel.dexterity
/zopeskel.dexterity-1.5.4.1.zip/zopeskel.dexterity-1.5.4.1/zopeskel/dexterity/localcommands/dexterity.py
dexterity.py
import os, shutil, sys, tempfile, urllib2 from optparse import OptionParser tmpeggs = tempfile.mkdtemp() is_jython = sys.platform.startswith('java') # parsing arguments parser = OptionParser() parser.add_option("-v", "--version", dest="version", help="use a specific zc.buildout version") parser.add_option("-d", "--distribute", action="store_true", dest="distribute", default=False, help="Use Disribute rather than Setuptools.") parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args += ['-c', options.config_file] if options.version is not None: VERSION = '==%s' % options.version else: VERSION = '' USE_DISTRIBUTE = options.distribute args = args + ['bootstrap'] to_reload = False try: import pkg_resources if not hasattr(pkg_resources, '_distribute'): to_reload = True raise ImportError except ImportError: ez = {} if USE_DISTRIBUTE: exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True) else: exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0) if to_reload: reload(pkg_resources) else: import pkg_resources if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: def quote (c): return c cmd = 'from setuptools.command.easy_install import main; main()' ws = pkg_resources.working_set if USE_DISTRIBUTE: requirement = 'distribute' else: requirement = 'setuptools' if is_jython: import subprocess assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd', quote(tmpeggs), 'zc.buildout' + VERSION], env=dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ).wait() == 0 else: assert os.spawnle( os.P_WAIT, sys.executable, quote (sys.executable), '-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION, dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ) == 0 ws.add_entry(tmpeggs) ws.require('zc.buildout' + VERSION) import zc.buildout.buildout zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs) ############################################################################## # # Copyright (c) 2006 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Bootstrap a buildout-based project Simply run this script in a directory containing a buildout.cfg. The script accepts buildout command-line options, so you can use the -c option to specify an alternate configuration file. $Id$ """ import os, shutil, sys, tempfile, urllib2 from optparse import OptionParser tmpeggs = tempfile.mkdtemp() is_jython = sys.platform.startswith('java') # parsing arguments parser = OptionParser() parser.add_option("-v", "--version", dest="version", help="use a specific zc.buildout version") parser.add_option("-d", "--distribute", action="store_true", dest="distribute", default=False, help="Use Disribute rather than Setuptools.") parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args += ['-c', options.config_file] if options.version is not None: VERSION = '==%s' % options.version else: VERSION = '' USE_DISTRIBUTE = options.distribute args = args + ['bootstrap'] to_reload = False try: import pkg_resources if not hasattr(pkg_resources, '_distribute'): to_reload = True raise ImportError except ImportError: ez = {} if USE_DISTRIBUTE: exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True) else: exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0) if to_reload: reload(pkg_resources) else: import pkg_resources if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: def quote (c): return c cmd = 'from setuptools.command.easy_install import main; main()' ws = pkg_resources.working_set if USE_DISTRIBUTE: requirement = 'distribute' else: requirement = 'setuptools' if is_jython: import subprocess assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd', quote(tmpeggs), 'zc.buildout' + VERSION], env=dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ).wait() == 0 else: assert os.spawnle( os.P_WAIT, sys.executable, quote (sys.executable), '-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION, dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ) == 0 ws.add_entry(tmpeggs) ws.require('zc.buildout' + VERSION) import zc.buildout.buildout zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
zopeskel.dexterity
/zopeskel.dexterity-1.5.4.1.zip/zopeskel.dexterity-1.5.4.1/zopeskel/dexterity/templates/dexterity/bootstrap.py
bootstrap.py
Introduction ============ This is a ZopeSkel template package for creating a skeleton Plone add-on package. The skeleton package creates a Bootstrap Diazo (diaxotheme.framworks) childtheme package and associated css and js resources for use with plone.app.theming in Plone 4.2+. Use this package when you want to package a Diazo childtheme as a Plone add on, particularly if you need to override viewlet or skin templates in the process. This is a development tool. You should be familiar with Plone and buildout to use it. .. ATTENTION:: This package is compatible with ZopeSkel<3.0 only. Installation ============ Add these lines into buildout:: [buildout] parts = zopeskel [zopeskel] recipe = zc.recipe.egg eggs = ZopeSkel Paste PasteDeploy PasteScript zopeskel.diazochildtheme And run the buildout Usage ====== Add ons under development are typically created in your buildout's src directory. Command line for creating a package named diazochildtheme.mychildtheme would be:: ../bin/zopeskel diazochildtheme diazochildtheme.mychildtheme This will create a Python package with a directory structure like this:: diazochildtheme.mychildtheme/ |-- diazochildtheme | +-- mychildtheme | |-- diazo_resources | | +-- static | |-- locales | |-- profiles | | +-- default | +-- template_overrides |-- diazochildtheme.mychildtheme.egg-info +-- docs The typically customized parts are in the diazochildtheme.mychildtheme/diazochildtheme/mychildtheme subdirectory. diazo_resources --------------- This is where you'll put your Diazo resources including a rules XML file and one or more template HTML files. You may wish to interactively develop these childtheme elements in the theming editor (for Plone 4.3+), then export the resources and add them here. A sample childtheme is included to use as a starting point. Just replace it if you don't need it. The sample childtheme's key feature is that it makes use of all of Plone's CSS and JavaScript as a starting point. Everything you put in this directory and its subdirectories is publicly available at ++childtheme++namespace.package/resourcename.ext. NOTE: The Diazo childtheme will be available in Plone even if you have not installed the package. It will not be applied, though, until enabled in the ChildTheme configlet of site setup. diazo_resources/static ---------------------- This is the conventional place to put static resources like CSS, JS and image files. There's nothing magic about "static". Remove or replace it if it fits your needs. Everything you put in this directory and its subdirectories is publicly available at ++childtheme++namespace.package/static/resourcename.ext. locales ------- If your templates include translatable messages, you may provide translation files in this directory. Ignore it if you don't need translations. profiles, profiles/default -------------------------- This is the Generic Setup profile for the add on. The is applied when you use the "add ons" configlet in site setup to install the package. This profile has a couple of important features: * It sets up a BrowserLayer, which insures tha template overrides and registry settings do not affect other Plone installations unless this childtheme is installed. * It has sample resource registrations for CSS and JavaScript resource registries. These allow you to incorporate static resources which are part of the childtheme into the Plone resource registries for efficient merging with other CSS and JS resources. The samples are commented out. If you remove the comment markers and install/reinstall the childtheme, the main.css and main.js files from your diazo_resources/static directory will be incorporated into the CSS and JS delivered by Plone -- even if the Diazo childtheme is not active. The alternative to adding your resources to the registries is to load them directly in your childtheme's index.html. This is a better approach if you don't intend to use Plone's own CSS and JS resources. If you do, registering your own resources will allow them to be merged for more efficient delivery. template_overrides ------------------ You may use this directory to override any Plone viewlet, portlet or skin template. To override a template, copy or create a template in this directory using the full dotted name of the template you wish to override. For example, if you wish to override the standard Plone footer, you would find the original at:: plone.app.layout/plone/app/layout/viewlets/footer.pt The full, dotted name for this resource is:: plone.app.layout.viewlets.footer.pt Template overrides are only applied when the BrowserLayer is installed by installing your package. So, they won't affect Plone installations where this package is not installed. For details on template overrides, see the documentation for `z3c.jbot <https://pypi.python.org/pypi/z3c.jbot>`_.
zopeskel.diazochildtheme
/zopeskel.diazochildtheme-0.1.zip/zopeskel.diazochildtheme-0.1/README.rst
README.rst
import os, shutil, sys, tempfile, urllib2 from optparse import OptionParser tmpeggs = tempfile.mkdtemp() is_jython = sys.platform.startswith('java') # parsing arguments parser = OptionParser() parser.add_option("-v", "--version", dest="version", help="use a specific zc.buildout version") parser.add_option("-d", "--distribute", action="store_true", dest="distribute", default=False, help="Use Disribute rather than Setuptools.") parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args += ['-c', options.config_file] if options.version is not None: VERSION = '==%s' % options.version else: VERSION = '' USE_DISTRIBUTE = options.distribute args = args + ['bootstrap'] to_reload = False try: import pkg_resources if not hasattr(pkg_resources, '_distribute'): to_reload = True raise ImportError except ImportError: ez = {} if USE_DISTRIBUTE: exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True) else: exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0) if to_reload: reload(pkg_resources) else: import pkg_resources if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: def quote (c): return c cmd = 'from setuptools.command.easy_install import main; main()' ws = pkg_resources.working_set if USE_DISTRIBUTE: requirement = 'distribute' else: requirement = 'setuptools' if is_jython: import subprocess assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd', quote(tmpeggs), 'zc.buildout' + VERSION], env=dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ).wait() == 0 else: assert os.spawnle( os.P_WAIT, sys.executable, quote (sys.executable), '-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION, dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ) == 0 ws.add_entry(tmpeggs) ws.require('zc.buildout' + VERSION) import zc.buildout.buildout zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs) ############################################################################## # # Copyright (c) 2006 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Bootstrap a buildout-based project Simply run this script in a directory containing a buildout.cfg. The script accepts buildout command-line options, so you can use the -c option to specify an alternate configuration file. $Id$ """ import os, shutil, sys, tempfile, urllib2 from optparse import OptionParser tmpeggs = tempfile.mkdtemp() is_jython = sys.platform.startswith('java') # parsing arguments parser = OptionParser() parser.add_option("-v", "--version", dest="version", help="use a specific zc.buildout version") parser.add_option("-d", "--distribute", action="store_true", dest="distribute", default=False, help="Use Disribute rather than Setuptools.") parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args += ['-c', options.config_file] if options.version is not None: VERSION = '==%s' % options.version else: VERSION = '' USE_DISTRIBUTE = options.distribute args = args + ['bootstrap'] to_reload = False try: import pkg_resources if not hasattr(pkg_resources, '_distribute'): to_reload = True raise ImportError except ImportError: ez = {} if USE_DISTRIBUTE: exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True) else: exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0) if to_reload: reload(pkg_resources) else: import pkg_resources if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: def quote (c): return c cmd = 'from setuptools.command.easy_install import main; main()' ws = pkg_resources.working_set if USE_DISTRIBUTE: requirement = 'distribute' else: requirement = 'setuptools' if is_jython: import subprocess assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd', quote(tmpeggs), 'zc.buildout' + VERSION], env=dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ).wait() == 0 else: assert os.spawnle( os.P_WAIT, sys.executable, quote (sys.executable), '-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION, dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ) == 0 ws.add_entry(tmpeggs) ws.require('zc.buildout' + VERSION) import zc.buildout.buildout zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
zopeskel.diazochildtheme
/zopeskel.diazochildtheme-0.1.zip/zopeskel.diazochildtheme-0.1/zopeskel/diazochildtheme/templates/diazochildtheme/bootstrap.py
bootstrap.py
This directory will be the home for internationalizations for your layer package. For more information on internationalization please consult the following sources: http://plone.org/documentation/kb/product-skin-localization http://plone.org/documentation/kb/i18n-for-developers http://www.mattdorn.com/content/plone-i18n-a-brief-tutorial/ http://grok.zope.org/documentation/how-to/how-to-internationalize-your-application http://maurits.vanrees.org/weblog/archive/2010/10/i18n-plone-4 http://maurits.vanrees.org/weblog/archive/2007/09/i18n-locales-and-plone-3.0 http://n2.nabble.com/Recipe-for-overriding-translations-td3045492ef221724.html http://dev.plone.org/plone/wiki/TranslationGuidelines
zopeskel.diazochildtheme
/zopeskel.diazochildtheme-0.1.zip/zopeskel.diazochildtheme-0.1/zopeskel/diazochildtheme/templates/diazochildtheme/+namespace_package+/+package+/locales/README.txt
README.txt
Introduction ============ This is a ZopeSkel template package for creating a skeleton Plone add-on package. The skeleton package creates a Diazo (plone.app.theming) theme package and associated css and js resources for use with plone.app.theming in Plone 4.2+. Use this package when you want to package a Diazo theme as a Plone add on, particularly if you need to override viewlet or skin templates in the process. This is a development tool. You should be familiar with Plone and buildout to use it. Installation ============ Add these lines into buildout:: [buildout] parts = zopeskel [zopeskel] recipe = zc.recipe.egg eggs = ZopeSkel Paste PasteDeploy PasteScript zopeskel.diazotheme And run the buildout Usage ====== Add ons under development are typically created in your buildout's src directory. Command line for creating a package named diazotheme.mytheme would be:: ../bin/zopeskel diazotheme diazotheme.mytheme This will create a Python package with a directory structure like this:: diazotheme.mytheme/ |-- diazotheme | +-- mytheme | |-- diazo_resources | | +-- static | |-- locales | |-- profiles | | +-- default | +-- template_overrides |-- diazotheme.mytheme.egg-info +-- docs The typically customized parts are in the diazotheme.mytheme/diazotheme/mytheme subdirectory. diazo_resources --------------- This is where you'll put your Diazo resources including a rules XML file and one or more template HTML files. You may wish to interactively develop these theme elements in the theming editor (for Plone 4.3+), then export the resources and add them here. A sample theme is included to use as a starting point. Just replace it if you don't need it. The sample theme's key feature is that it makes use of all of Plone's CSS and JavaScript as a starting point. Everything you put in this directory and its subdirectories is publicly available at ++theme++namespace.package/resourcename.ext. NOTE: The Diazo theme will be available in Plone even if you have not installed the package. It will not be applied, though, until enabled in the Theme configlet of site setup. diazo_resources/static ---------------------- This is the conventional place to put static resources like CSS, JS and image files. There's nothing magic about "static". Remove or replace it if it fits your needs. Everything you put in this directory and its subdirectories is publicly available at ++theme++namespace.package/static/resourcename.ext. locales ------- If your templates include translatable messages, you may provide translation files in this directory. Ignore it if you don't need translations. profiles, profiles/default -------------------------- This is the Generic Setup profile for the add on. The is applied when you use the "add ons" configlet in site setup to install the package. This profile has a couple of important features: * It sets up a BrowserLayer, which insures tha template overrides and registry settings do not affect other Plone installations unless this theme is installed. * It has sample resource registrations for CSS and JavaScript resource registries. These allow you to incorporate static resources which are part of the theme into the Plone resource registries for efficient merging with other CSS and JS resources. The samples are commented out. If you remove the comment markers and install/reinstall the theme, the main.css and main.js files from your diazo_resources/static directory will be incorporated into the CSS and JS delivered by Plone -- even if the Diazo theme is not active. The alternative to adding your resources to the registries is to load them directly in your theme's index.html. This is a better approach if you don't intend to use Plone's own CSS and JS resources. If you do, registering your own resources will allow them to be merged for more efficient delivery. template_overrides ------------------ You may use this directory to override any Plone viewlet, portlet or skin template. To override a template, copy or create a template in this directory using the full dotted name of the template you wish to override. For example, if you wish to override the standard Plone footer, you would find the original at:: plone.app.layout/plone/app/layout/viewlets/footer.pt The full, dotted name for this resource is:: plone.app.layout.viewlets.footer.pt Template overrides are only applied when the BrowserLayer is installed by installing your package. So, they won't affect Plone installations where this package is not installed. A sample override for the Plone footer is included. Delete it if you don't need it. For details on template overrides, see the documentation for `z3c.jbot <https://pypi.python.org/pypi/z3c.jbot>`_.
zopeskel.diazotheme
/zopeskel.diazotheme-1.1.zip/zopeskel.diazotheme-1.1/README.rst
README.rst
import os, shutil, sys, tempfile, urllib2 from optparse import OptionParser tmpeggs = tempfile.mkdtemp() is_jython = sys.platform.startswith('java') # parsing arguments parser = OptionParser() parser.add_option("-v", "--version", dest="version", help="use a specific zc.buildout version") parser.add_option("-d", "--distribute", action="store_true", dest="distribute", default=False, help="Use Disribute rather than Setuptools.") parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args += ['-c', options.config_file] if options.version is not None: VERSION = '==%s' % options.version else: VERSION = '' USE_DISTRIBUTE = options.distribute args = args + ['bootstrap'] to_reload = False try: import pkg_resources if not hasattr(pkg_resources, '_distribute'): to_reload = True raise ImportError except ImportError: ez = {} if USE_DISTRIBUTE: exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True) else: exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0) if to_reload: reload(pkg_resources) else: import pkg_resources if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: def quote (c): return c cmd = 'from setuptools.command.easy_install import main; main()' ws = pkg_resources.working_set if USE_DISTRIBUTE: requirement = 'distribute' else: requirement = 'setuptools' if is_jython: import subprocess assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd', quote(tmpeggs), 'zc.buildout' + VERSION], env=dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ).wait() == 0 else: assert os.spawnle( os.P_WAIT, sys.executable, quote (sys.executable), '-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION, dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ) == 0 ws.add_entry(tmpeggs) ws.require('zc.buildout' + VERSION) import zc.buildout.buildout zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs) ############################################################################## # # Copyright (c) 2006 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Bootstrap a buildout-based project Simply run this script in a directory containing a buildout.cfg. The script accepts buildout command-line options, so you can use the -c option to specify an alternate configuration file. $Id$ """ import os, shutil, sys, tempfile, urllib2 from optparse import OptionParser tmpeggs = tempfile.mkdtemp() is_jython = sys.platform.startswith('java') # parsing arguments parser = OptionParser() parser.add_option("-v", "--version", dest="version", help="use a specific zc.buildout version") parser.add_option("-d", "--distribute", action="store_true", dest="distribute", default=False, help="Use Disribute rather than Setuptools.") parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args += ['-c', options.config_file] if options.version is not None: VERSION = '==%s' % options.version else: VERSION = '' USE_DISTRIBUTE = options.distribute args = args + ['bootstrap'] to_reload = False try: import pkg_resources if not hasattr(pkg_resources, '_distribute'): to_reload = True raise ImportError except ImportError: ez = {} if USE_DISTRIBUTE: exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True) else: exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0) if to_reload: reload(pkg_resources) else: import pkg_resources if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: def quote (c): return c cmd = 'from setuptools.command.easy_install import main; main()' ws = pkg_resources.working_set if USE_DISTRIBUTE: requirement = 'distribute' else: requirement = 'setuptools' if is_jython: import subprocess assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd', quote(tmpeggs), 'zc.buildout' + VERSION], env=dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ).wait() == 0 else: assert os.spawnle( os.P_WAIT, sys.executable, quote (sys.executable), '-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION, dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ) == 0 ws.add_entry(tmpeggs) ws.require('zc.buildout' + VERSION) import zc.buildout.buildout zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
zopeskel.diazotheme
/zopeskel.diazotheme-1.1.zip/zopeskel.diazotheme-1.1/zopeskel/diazotheme/templates/diazotheme/bootstrap.py
bootstrap.py
This directory will be the home for internationalizations for your layer package. For more information on internationalization please consult the following sources: http://plone.org/documentation/kb/product-skin-localization http://plone.org/documentation/kb/i18n-for-developers http://www.mattdorn.com/content/plone-i18n-a-brief-tutorial/ http://grok.zope.org/documentation/how-to/how-to-internationalize-your-application http://maurits.vanrees.org/weblog/archive/2010/10/i18n-plone-4 http://maurits.vanrees.org/weblog/archive/2007/09/i18n-locales-and-plone-3.0 http://n2.nabble.com/Recipe-for-overriding-translations-td3045492ef221724.html http://dev.plone.org/plone/wiki/TranslationGuidelines
zopeskel.diazotheme
/zopeskel.diazotheme-1.1.zip/zopeskel.diazotheme-1.1/zopeskel/diazotheme/templates/diazotheme/+namespace_package+/+package+/locales/README.txt
README.txt
# This should be changed into generating data structures, and having # Cheetah templates to render them from zopeskel.ui import list_sorted_templates import pkg_resources def _get_local_commands(): """Return dict of main_template -> [ local template1, ... localN ]""" out = {} for entry in pkg_resources.iter_entry_points('zopeskel.zopeskel_sub_template'): localc = entry.load() for parent in localc.parent_templates: out.setdefault(parent, []).append((entry.name, localc)) return out def make_html(): cats = list_sorted_templates(filter_group=True) subtemplates = _get_local_commands() for title, list_ in cats.items(): print "<h2>%s</h2>" % title for temp in list_: print "<h3>%(name)s</h3>" % temp tempc = temp['entry'].load() print '<p class="summary">%s</p>' % tempc.summary help = getattr(tempc, 'help', '') for para in help.split("\n\n"): print '<p>%s</p>' % para print "<h4>Fields:</h4>" print "<ul>" for var in tempc.vars: if hasattr(var, 'pretty_description'): print "<li>%s</li>" % var.pretty_description() else: print "<li>%s</li>" % var.name print "</ul>" subs = subtemplates.get(temp['name']) if subs: print "<h4>Local Commands:</h4>" print "<ul>" for sub in subs: subname, subc = sub print "<li>%s (%s)" % (subname, subc.summary) help = getattr(subc, 'help', '') for para in help.split("\n\n"): if para: print '<p>%s</p>' % para if subc.vars: print "<h5>Local Command Fields:</h5>" print "<ul>" for var in subc.vars: if hasattr(var, 'pretty_description'): print "<li>%s</li>" % var.pretty_description() else: print "<li>%s</li>" % var.name print "</ul>" print "</li>" print "</ul>" if __name__=="__main__": make_html()
zopeskel.doctools
/zopeskel.doctools-1.0.tar.gz/zopeskel.doctools-1.0/zopeskel/doctools/html_doc.py
html_doc.py
class Graph(object): """ Methods to visualize paster entry point dependencies. """ def __init__(self, template_bundle=None, entry_point_group_name=None, detail=False, default_bundle='zopeskel'): super(Graph,self).__init__() self.template_bundle = template_bundle self.entry_point_group_name = entry_point_group_name self.detail = detail self.default_bundle = default_bundle self.nodes = {} def create(self): """ Create the dot language commands for GraphViz. If no entry group specified, walk each entry group in the entry map. Walk each entry point in the entry group. Add nodes for entry point to graph. Create an edge for each base/class pair. Format a diagraph of edges. """ import pkg_resources if self.template_bundle: # filter to entry points in template bundle only if self.entry_point_group_name: # single entry point group entry_map = pkg_resources.get_entry_map(self.template_bundle) entry_point_group = \ entry_map[self.entry_point_group_name].values() self.parse(self.entry_point_group_name,entry_point_group) else: # all entry point groups entry_map = pkg_resources.get_entry_map(self.template_bundle) for entry_point_group_name in entry_map: entry_point_group = \ entry_map[entry_point_group_name].values() self.parse(entry_point_group_name,entry_point_group) else: # all entries points if self.entry_point_group_name: # single entry point group entry_point_group = [entry_point for entry_point in pkg_resources.iter_entry_points(self.entry_point_group_name)] self.parse(self.entry_point_group_name,entry_point_group) else: # all entry points in all entry point groups in default bundle entry_map = pkg_resources.get_entry_map(self.default_bundle) for entry_point_group_name in entry_map: entry_point_group = [entry_point for entry_point in pkg_resources.iter_entry_points(entry_point_group_name)] self.parse(entry_point_group_name,entry_point_group) if self.entry_point_group_name: title = self.entry_point_group_name elif self.template_bundle: title = self.template_bundle else: title = self.default_bundle graph = ['digraph %s {' % title] for class_name,node in self.nodes.items(): for base_name in node['base_names']: node['base_name'] = base_name graph.append('%(base_name)s -> %(class_name)s' % node) if node['module']: if self.detail: graph.append(('%(class_name)s [label=\"' + 'entry %(entry_point_name)s\\n' + 'group %(entry_point_group_name)s\\n' + 'class %(class_name)s\\n' + 'module %(module_name)s' '\",fillcolor=palegoldenrod]') % node) else: graph.append(('%(class_name)s [label=\"' + '%(entry_point_name)s' + '\",fillcolor=palegoldenrod]') % node) else: if self.detail: graph.append(('%(class_name)s [label=\"type %(class_name)s\",' + 'fillcolor=lightsalmon]') % node) else: graph.append(('%(class_name)s [label=\"%(class_name)s\",' + 'fillcolor=lightsalmon]') % node) if self.detail: graph.append('object [label=\"type object\",fillcolor=lightsalmon]') else: graph.append('object [label=\"object\",fillcolor=lightsalmon]') graph.append('}') graph = '\n'.join(graph) return graph def parse(self,entry_point_group_name,entry_point_group): """ Add the nodes for an entry point to graph. Add a node for the entry point's class. Recursively walk the base classes for each entry point. """ for entry_point in entry_point_group: entry_point_name = entry_point.name module_name = entry_point.module_name module = __import__(module_name, globals(),locals(),(module_name,)) class_names = entry_point.attrs for class_name in class_names: cls = getattr(module,class_name) if isinstance(cls,type): bases = cls.__bases__ base_names = [base.__name__ for base in bases] self.add_node(cls,class_name, bases,base_names, module,module_name, entry_point,entry_point_name, entry_point_group,entry_point_group_name) # recurse through the superclasses # for each entry point # adding a node for each while bases != (object,): bases_bases = [] for base in bases: base_name = base.__name__ base_bases = base.__bases__ for base_base in base_bases: if base_base not in bases_bases: bases_bases.append(base_base) base_base_names = [base_base.__name__ for base_base in base_bases] self.add_node(base,base_name, base_bases,base_base_names) bases = tuple(bases_bases) return self.nodes def add_node(self,cls,class_name, bases,base_names, module=None,module_name=None, entry_point=None,entry_point_name=None, entry_point_group=None,entry_point_group_name=None): """ Add a node to the directed graph. If the node has already been added to the graph, check if it needs entry point data. If the node has not already been added to the graph, then do so. """ if module: node = self.nodes.get(class_name) if node: if not node['module']: node['module'] = module node['module_name'] = module_name node['entry_point'] = entry_point node['entry_point_name'] = entry_point_name node['entry_point_group'] = entry_point_group node['entry_point_group_name'] = entry_point_group_name return self.nodes.setdefault(class_name,{'class':cls, 'class_name': class_name, 'bases':bases, 'base_names':base_names, 'module':module, 'module_name':module_name, 'entry_point':entry_point, 'entry_point_name': entry_point_name, 'entry_point_group': entry_point_group, 'entry_point_group_name' :entry_point_group_name, }) def _main(template_bundle=None,entry_point_group_name=None,detail=False): """ Visualize a directed graph of paster template dependencies. """ return Graph(template_bundle, entry_point_group_name, detail).create() def graph(): print _main('zopeskel','paste.paster_create_template') if __name__ == '__main__': graph()
zopeskel.doctools
/zopeskel.doctools-1.0.tar.gz/zopeskel.doctools-1.0/zopeskel/doctools/graph.py
graph.py
Starting, deploying and maintaining Plone 4 projects made easy ============================================================== zopeskel.niteoweb is collection of ZopeSkel templates to help you standardize and automate the task of starting, deploying and maintaining a new Plone project. Its particularly helpful for less experienced Plone developers as they can get a properly structured and deployed Plone 4 project in no time. A complete tutorial on how to use these templates for your own projects is at http://ploneboutique.com. It will help you to automate and standardize: * Starting a new Plone 4 project that includes old- and new-style python, zope page template and css overrides, collective.xdv, etc. * Adding your own functionalities and look to Plone 4. * Staging and deploying your Plone 4 project on Rackspace Cloud server instance running CentOS, with Nginx in front and secured with iptables firewall (only $11 per month per instance!) * Maintaining and upgrading your Plone 4 project on the production server. By default the Plone 4 project you create with these templates is equiped with: * latest collective.xdv with sample rules.xml and template.html, * .svnignore files to ignore files/folders that should not be stored inside your code repository, * base.cfg that holds global configuration for your buildout, * versions.cfg that pins all your eggs to specific versions to ensure repeatability, * development.cfg that builds a development environment, * production.cfg that builds a production environment with ZEO, * sphinx.cfg that is used to generate documentation for your code, * test_setup.py that shows you how to write tests for your project, * fabfile.py with Fabric commands to automatically deploy your code and data to a Rackspace Cloud server instance running CentOS, * Sphinx documentation for your project, * nginx.conf template to setup the Nginx web-proxy in front of your Zope, * basic iptables configuration to deny access on all ports but the ones you actually use, * munin-node.conf template to setup Munin system monitor node on your production server, * and much more. Installation ============ Installation is simple, just run 'sudo easy_install zopeskel.niteoweb' and you're good to go. Go where? To http://ploneboutique.com. Assumptions =========== Out-of-the-box, this package is intended for NiteoWeb's internal projects. However, at http://ploneboutique.com you'll find a comprehensive guide on how to use these templates for your own projects. To do ===== - add munin plugins for Zope and Nginx - audit iptables - audit sudoers - audit sshd_config - yum-security email notification - per-version separation of documentation on packages.python.org - test coverage plugin for Hudson - properify version extraction in conf.py - add docstrings to Fabric commands Contributors ============ - Nejc 'zupo' Zupan, NiteoWeb Ltd. - Domen 'iElectric' Kozar, NiteoWeb Ltd.
zopeskel.niteoweb
/zopeskel.niteoweb-1.0b1.tar.gz/zopeskel.niteoweb-1.0b1/README.txt
README.txt
import os, shutil, sys, tempfile, urllib2 from optparse import OptionParser tmpeggs = tempfile.mkdtemp() is_jython = sys.platform.startswith('java') # parsing arguments parser = OptionParser() parser.add_option("-v", "--version", dest="version", help="use a specific zc.buildout version") parser.add_option("-d", "--distribute", action="store_true", dest="distribute", default=False, help="Use Disribute rather than Setuptools.") parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args += ['-c', options.config_file] if options.version is not None: VERSION = '==%s' % options.version else: VERSION = '' # We decided to always use distribute, make sure this is the default for us # USE_DISTRIBUTE = options.distribute USE_DISTRIBUTE = True args = args + ['bootstrap'] to_reload = False try: import pkg_resources if not hasattr(pkg_resources, '_distribute'): to_reload = True raise ImportError except ImportError: ez = {} if USE_DISTRIBUTE: exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True) else: exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0) if to_reload: reload(pkg_resources) else: import pkg_resources if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: def quote (c): return c cmd = 'from setuptools.command.easy_install import main; main()' ws = pkg_resources.working_set if USE_DISTRIBUTE: requirement = 'distribute' else: requirement = 'setuptools' if is_jython: import subprocess assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd', quote(tmpeggs), 'zc.buildout' + VERSION], env=dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ).wait() == 0 else: assert os.spawnle( os.P_WAIT, sys.executable, quote (sys.executable), '-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION, dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ) == 0 ws.add_entry(tmpeggs) ws.require('zc.buildout' + VERSION) import zc.buildout.buildout zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
zopeskel.niteoweb
/zopeskel.niteoweb-1.0b1.tar.gz/zopeskel.niteoweb-1.0b1/bootstrap.py
bootstrap.py
import copy from zopeskel.plone import BasicZope from zopeskel.base import get_var from zopeskel.base import EXPERT, EASY from zopeskel.vars import StringVar from zopeskel import abstract_buildout class NiteoWeb(BasicZope): _template_dir = 'templates/niteoweb' summary = "A Plone Boutique project" help = """""" category = "Plone Development" required_templates = ['basic_namespace'] use_cheetah = True vars = copy.deepcopy(BasicZope.vars) # override default values for default questions get_var(vars, 'namespace_package').default = 'boutique' get_var(vars, 'package').default = 'ebar' get_var(vars, 'version').default = '0.1' get_var(vars, 'version').modes = (EXPERT) get_var(vars, 'description').default = 'Plone Boutique commercial project for eBar.si' get_var(vars, 'author').default = 'Plone Boutique Ltd.' get_var(vars, 'author_email').default = '[email protected]' get_var(vars, 'keywords').default = 'Python Zope Plone' # remove url question as it's ambigious vars.remove(get_var(vars, 'url')) # remove long_description question as we don't need it vars.remove(get_var(vars, 'long_description')) # add buildout-related questions vars.extend( [ abstract_buildout.VAR_PLONEVER, ] ) get_var(vars, 'plone_version').default = '4.0' get_var(vars, 'plone_version').modes = (EXPERT) # add custom questions vars.append( StringVar( 'xdv_version', title='collective.xdv version', description='Version of collective.xdv that you would like to use in your project.', modes=(EXPERT), default='1.0rc9', help=""" This value will be used to bind collective.xdv to an exact version to ensure repeatabily of your buildouts. If you do not want to use collective.xdv in your project, leave this value blank (''). """ ) ) vars.append( StringVar( 'hostname', title='Server Hostname', description='Domain on which this project will run on.', modes=(EASY, EXPERT), default='ebar.si', help="""""" ) ) vars.append( StringVar( 'server_ip', title='IP', description='IP of production server. Leave default if you don\'t have one yet', modes=(EASY, EXPERT), default='87.65.43.21', help=""" If you have already created a Rackspace Cloud server instance, enter here it's IP address. """ ) ) vars.append( StringVar( 'temp_root_pass', title='Temporary root password', description='Temporary password for root user on production server. Leave default if you don\'t have one yet', modes=(EASY, EXPERT), default='root_password_here', help=""" If you have already created a Rackspace Cloud server instance, enter here its root password. This password will only be used in the first steps of deployment and disabled immediately after. """ ) ) vars.append( StringVar( 'administrators', title='Administrators', description='Usernames of administrators that will have access to your production server, separated with commas.', modes=(EASY, EXPERT), default='bob,jane', help=""" This value will be used to create maintenance users that will have access to your production server. Separate usernames with commas: 'bob,jane' """ ) ) vars.append( StringVar( 'headquarters_hostname', title='Headquarters Hostname', description='Domain on which your Headquarters server is running.', modes=(EASY, EXPERT), default='ploneboutique.com', help=""" Domain on which your Headquarters server is running that hosts maintenance tools along with your main corporate website - such as Sphinx docs, Munin system monitor, etc. """ ) ) vars.append( StringVar( 'headquarters_ip', title='Headquarters IP', description='IP on which your Headquarters server is listening.', modes=(EASY, EXPERT), default='12.34.56.78', help=""" IP on which your main server is listening for requests from tools such as Munin system monitor, etc. """ ) ) vars.append( StringVar( 'office_ip', title='Office IP', description='Your office IP that you use daily and can VPN to', modes=(EASY, EXPERT), default='12.34.56.78', help=""" SSHing to this server will only be allowed from this IP. Make sure you have can VPN to this IP. """ ) )
zopeskel.niteoweb
/zopeskel.niteoweb-1.0b1.tar.gz/zopeskel.niteoweb-1.0b1/zopeskel/niteoweb/niteoweb.py
niteoweb.py
import os, shutil, sys, tempfile, urllib2 from optparse import OptionParser tmpeggs = tempfile.mkdtemp() is_jython = sys.platform.startswith('java') # parsing arguments parser = OptionParser() parser.add_option("-v", "--version", dest="version", help="use a specific zc.buildout version") parser.add_option("-d", "--distribute", action="store_true", dest="distribute", default=False, help="Use Disribute rather than Setuptools.") parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args += ['-c', options.config_file] if options.version is not None: VERSION = '==%s' % options.version else: VERSION = '' # We decided to always use distribute, make sure this is the default for us # USE_DISTRIBUTE = options.distribute USE_DISTRIBUTE = True args = args + ['bootstrap'] to_reload = False try: import pkg_resources if not hasattr(pkg_resources, '_distribute'): to_reload = True raise ImportError except ImportError: ez = {} if USE_DISTRIBUTE: exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True) else: exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0) if to_reload: reload(pkg_resources) else: import pkg_resources if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: def quote (c): return c cmd = 'from setuptools.command.easy_install import main; main()' ws = pkg_resources.working_set if USE_DISTRIBUTE: requirement = 'distribute' else: requirement = 'setuptools' if is_jython: import subprocess assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd', quote(tmpeggs), 'zc.buildout' + VERSION], env=dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ).wait() == 0 else: assert os.spawnle( os.P_WAIT, sys.executable, quote (sys.executable), '-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION, dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ) == 0 ws.add_entry(tmpeggs) ws.require('zc.buildout' + VERSION) import zc.buildout.buildout zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
zopeskel.niteoweb
/zopeskel.niteoweb-1.0b1.tar.gz/zopeskel.niteoweb-1.0b1/zopeskel/niteoweb/templates/niteoweb/bootstrap.py
bootstrap.py
########### Quick start ########### Note that we use ``boutique`` as a sample company short name and ``ebar`` as a sample project short name. You should use ids in the same manner (lower-case, letters only). #. Create a Cloud Servers account at Rackspace Cloud and create a new server instance with CentOS 5.5. Write down server's IP and root password. #. Create an account at Unfuddle and create a new project with Subversion repository. #. Prepare Unfuddle Subversion repository .. sourcecode:: bash ~$ svn mkdir http://boutique.unfuddle.com/svn/boutique_ebar/{trunk,branches,tags} -m 'Added base folders' #. Prepare ZopeSkel .. sourcecode:: bash # Install/Upgrade ZopeSkel to latest version ~$ sudo easy_install -U ZopeSkel # Install/Upgrade zopeskel.niteoweb to latest version ~$ sudo easy_install -U zopeskel.niteoweb #. Create project skeleton. Replace boutique.ebar with your custom string. Example: yourcompany.firstcustomer. :: ~$ cd ~/work work$ paster create -t niteoweb_project boutique.ebar --config=boutique.ebar/zopeskel.cfg Expert Mode? (What question mode would you like? (easy/expert/all)?) ['easy']: all Namespace Package Name (Name of outer namespace package) ['boutique']: Package Name (Name of the inner namespace package) ['ebar']: Version (Version number for project) ['0.1']: Description (One-line description of the project) ['NiteoWeb Plone project']: Example Plone Boutique project Long Description (Multi-line description (in ReST)) ['']: Imaginary presentation site for eBar Ltd. Author (Name of author for project) ['NiteoWeb Ltd.']: Plone Boutique Ltd. Author Email (Email of author for project) ['[email protected]']: [email protected] Keywords (List of keywords, space-separated) ['Python Zope Plone']: Project URL (URL of the homepage for this project) ['http://docs.niteoweb.com/']: http://ebar.si Project License (Name of license for the project) ['GPL']: Zip-Safe? (Can this project be used as a zipped egg? (true/false)) [False]: Zope2 Product? (Are you creating a product for Zope2/Plone or an Archetypes Product?) [True]: Plone Version (Plone version # to install) ['4.0rc1']: collective.xdv version (Version of collective.xdv that you would like to use in your project.)['1.0rc9']: Hostname (Domain on which this project will run on.) ['zulu.com']: ebar.si Maintenance users (Usernames of users that will have access to your production server, separated with commas.) ['iElectric,Kunta,zupo']: 'bob,jane' Maintenance hostname (Domain on which your main (maintenance) server is running.) ['niteoweb.com']: ploneboutique.com Maintenance email (Email on which you receive system notifications from production servers.) ['[email protected]']: [email protected] IP (IP of production server. Leave default if you don't have one yet) ['12.34.56.78']: <IP you wrote down above> Temporary root password (Temporary password for root user on production server. Leave default if you don't have one yet) ['root_password_here']: <root password you wrote down above> Creating template basic_namespace Creating directory ./boutique.ebar ... ... ... Running /Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python setup.py egg_info #. Checkout Subversion repository, commit project skeleton and set ``svn:ignore`` for files and folders that should not be in code repository. .. sourcecode:: bash # Checkout Unfuddle's Subversion repository for this project work$ cd boutique.ebar/ boutique.ebar$ svn co http://boutique.unfuddle.com/svn/boutique_ebar/trunk ./ # Commit code skeleton boutique.ebar$ svn add * boutique.ebar$ svn ci -m "added project skeleton" # Set svn:ignore, instructions how to do this are also in svnignore file itself boutique.ebar$ svn propset svn:ignore -F svnignore ./ boutique.ebar$ svn propset svn:ignore -F docs/svnignore ./docs boutique.ebar$ svn propset svn:ignore -F etc/svnignore ./etc boutique.ebar$ svn up boutique.ebar$ svn ci -m "set svn:ignore" #. Build development environment .. sourcecode:: bash # Create symlink to development.cfg so you don't have to append '-c buildout.cfg' all the time boutique.ebar$ ln -s development.cfg buildout.cfg boutique.ebar$ svn add buildout.cfg && svn ci -m "added soft-link to development.cfg" # Make an isolated Python environment boutique.ebar$ virtualenv -p python2.6 --no-site-packages ./ # Bootstrap zc.buildout boutique.ebar$ bin/python bootstrap.py # Build development environment boutique.ebar$ bin/buildout #. Pin down egg versions by copying version pins outputted by buildout. Search for ``*************** PICKED VERSIONS ****************`` and copy all lines except ``[versions]`` to your ``versions.cfg`` file under ``Bindings outputted by buildout.dumppickedversions for development.cfg``. #. Start Zope in debug mode and point your browser to http://localhost:8080 to confirm that it starts properly. Create a Plone site with id ``ebar`` and select ``boutique.ebar`` extension profile to confirm that your package installs correctly into Plone. .. sourcecode:: bash boutique.ebar$ bin/zope fg # stop with Ctrl+c #. Let's build a production environment so we get deployment tools prepared for us and test that production services are working. When done, point your browser to ``http://localhost:11401/ebar`` to confirm that Plone is running. .. sourcecode:: bash # build production environment boutique.ebar$ bin/buildout -c production.cfg boutique.ebar$ bin/zeo start boutique.ebar$ bin/zope1 start # test in browser boutique.ebar$ bin/zope1 stop boutique.ebar$ bin/zeo stop #. We're now ready to deploy this Plone site to a Rackspace Cloud server. If you haven't already done so, now is the time to create one and write down it's IP and root password into production.cfg. You also need to put your maintenance users' public keys in to ``./keys``. Filenames should match each user's id. .. sourcecode:: bash # for each maintenance user, add their public key; filename must match user's id boutique.ebar$ nano keys/bob.pub boutique.ebar$ nano keys/jane.pub # re-run buildout to update deployment tools with server IP and root password boutique.ebar$ bin/buildout -c production # bootstrap CentOS server and deploy your Plone site boutique.ebar$ bin/fab deploy #. This should be it! Add ``<server_ip> <hostname>`` line to your ``/etc/hosts`` file and point your browser to ``http://<hostname>``. You should see your Plone 4 project, deployed on a cloud server.
zopeskel.niteoweb
/zopeskel.niteoweb-1.0b1.tar.gz/zopeskel.niteoweb-1.0b1/docs/source/quick.rst
quick.rst
############ Headquarters ############ ************ Introduction ************ This chapter will guide you through the process of setting up you Headquarters server. This server will keep your code documentation, servers system information, etc. This chapter is by far the trickiest one. Make yourself your favorite tea, concentrate and read slowly. The juice is worth the squeeze. **************** Project skeleton **************** Plone will not be running on this server. However, you can still use ZopeSkel to create a skeleton of a project that will hold all configuration files, deployment scripts, etc. and remove Plone-specific stuff out of it. Later on you'll add HQ specific stuff such as install scripts for Munin andHudson. Prepare Unfuddle ================ Account ------- If you have not already, now is the time to `create an account at Unfuddle`_. For account id use ``boutique``. .. image:: sign_up.png :width: 600 Users ----- Create 3 Unfuddle users, 2 for Plone Boutique developers and one for Hudson (it needs access to your code to run automated tests): #. ``bob`` #. ``jane`` #. ``hudson`` .. image:: add_user.png :width: 600 Project ------- #. Create a new project (use ``headquarters`` for project id). .. image:: add_project.png :width: 500 #. Give users ``bob`` and ``jane`` read/write permissions on this project. #. Give user ``hudson`` read permissions on this project. #. Add a Subversion repository (use ``headquarters`` for repository id). .. image:: add_repository.png :width: 500 #. Prepare your new Unfuddle Subversion repository by adding base folders. Username and password for Subversion repository are the same you use to login to Unfuddle. .. sourcecode:: bash ~$ svn mkdir http://boutique.unfuddle.com/svn/boutique_headquarters/{trunk,branches,tags} -m 'Added base folders' Prepare ZopeSkel ================ Install/Upgrade ZopeSkel to latest version. .. sourcecode:: bash $ sudo easy_install -U ZopeSkel Install/Upgrade zopeskel.niteoweb to latest version. .. sourcecode:: bash $ sudo easy_install -U zopeskel.niteoweb Prepare Cloud server ==================== If you have not already, now is the time to `create an account at Rackspace Cloud`_ (aff link). #. Login to ``manage.rackspacecloud.com``. #. Navigate to ``Hosting`` -> ``Cloud Servers`` and click ``Add Server``. #. Select ``CentOS 5.5``. #. For ``Server Name`` enter ``headquarters``. #. For ``Server Size`` chose ``265 MB``. #. Click ``Create Server``. .. image:: add_server.png :width: 600 Write down server's IP and root password. You'll need it for generating a project skeleton with ZopeSkel. ..note :: You will be hardening server's security by locking it's access down only for your Office IP and disabling root login. Because of this some of Rackspace Cloud Control Panel features will not be able to work properly as they rely on root access to the server. Server backups -------------- Rackspace enables you to do daily and weekly backups for easily and free-of-charge. #. Navigate to ``Hosting`` -> ``Cloud Server`` -> select ``headquarters`` server -> tab ``Images``. #. Click ''Enable Scheduled Imaging`` button. #. Select ``0200-0400`` for ``Daily Backup Window``. #. Select ``Sunday`` for ``Weekly Backup Window``. #. Click ``Save schedule`` button. .. image:: backups.png :width: 600 Prepare skeleton ================ Generate using ZopeSkel ----------------------- Run ZopeSkel to generate a skeleton based on ``niteoweb_project`` template (the one used for all Plone Boutique projects). .. warning:: Since you don't yet have a Headquarters server running and you are just building one at the moment, enter server's IP for both ``Server IP`` and ``Headquarters IP`` questions. .. sourcecode:: bash # if you don't already have a folder for your projects, create one now $ mkdir $ cd ~/work # use ZopeSkel to create a project skeleton work$ paster create -t niteoweb_project boutique.headquarters Expert Mode? (What question mode would you like? (easy/expert/all)?) ['easy']: easy Description (One-line description of the project) ['Plone Boutique commercial project for eBar.si']: Configuration and install-scripts for Headquarters server Hostname (Domain on which this project will run on.) ['ebar.si']: ploneboutique.com IP (IP of production server. Leave default if you don't have one yet) ['87.65.43.21']: <your_server_ip> Temporary root password (Temporary password for root user on production server. Leave default if you don't have one yet) ['root_password_here']: <root_password_from_rackspace> Maintenance users (Usernames of administrators that will have access to your production server, separated with commas.) ['bob,jane']: bob,jane Headquarters hostname (Domain on which your Headquarters server is running.) ['ploneboutique.com']: ploneboutique.com Maintenance IP (IP on which your Headquarters server is listening.) ['12.34.56.78']: <your_server_ip> Office IP (Your office IP that you use daily and can VPN to) ['12.34.56.78']: <your_office_ip> Removing what you don't need now -------------------------------- Headquarters is a special case project. Instead of a Plone site it runs several other services, like Munin and Hudson. So first things first, you need to remove everything plone-specific that you will not need. .. sourcecode:: bash work$ cd boutique.headquarters boutique.headquarters$ rm coverage.cfg sphinx.cfg hudson.cfg production.cfg boutique.headquarters$ rm -rf src/boutique.headquarters.egg-info boutique.headquarters$ rm -rf src/boutique/headquarters/{browser,profiles,skins,tests,config.py,configure.zcml,interfaces.py,xdv} Customizing buildout files -------------------------- Since you don't need Plone on this server, buildout configuration files (\*.cfg's) are much simpler. base.cfg ^^^^^^^^ In base.cfg remove the following lines/sections:: find-links parts eggs zcml [ports] Then tell ``zopepy`` to only use ``fabric`` for extra eggs. Replace the line ``eggs = \${buildout:eggs}`` with this one: ``eggs = fabric``. development.cfg ^^^^^^^^^^^^^^^ In development.cfg remove the following lines/sections:: omelette test lxml zope eggs zcml [omelette] [lxml] [zope] [test] Customizing nginx.conf.in ------------------------- For now, we'll just make Nginx serve static files from ``/home/nginx/static``. More detailed configuration follows later. In ``boutique.headquarters/etc_templates/nginx.conf.in``, replace server block starting with ``# Plone`` with the one below. .. sourcecode:: nginx # ploneboutique.com server { listen 80; server_name ploneboutique.com; location / { expires 1h; index index.html; root /home/nginx/static; # restrict access allow 127.0.0.1; allow ${config:office_ip}; deny all; } } Commit skeleton --------------- Ok, skeleton is ready. Commit it to Subversion and continue working on it: .. sourcecode:: bash # Checkout Unfuddle's Subversion repository for this project boutique.headquarters$ svn co http://boutique.unfuddle.com/svn/boutique_headquarters/trunk ./ # Commit code skeleton boutique.headquarters$ svn add * boutique.headquarters$ svn ci -m "added project skeleton" # Set svn:ignore, instructions how to do this are also in svnignore files boutique.headquarters$ svn propset svn:ignore -F svnignore ./ boutique.headquarters$ svn propset svn:ignore -F docs/svnignore ./docs boutique.headquarters$ svn propset svn:ignore -F etc/svnignore ./etc boutique.headquarters$ svn up boutique.headquarters$ svn ci -m "set svn:ignore" ****************************** Prepare deployment environment ****************************** Even though you are not using Plone on Headquarters server you can still use zc.buildout to generate server config files and install scripts for you. With development.cfg, which builds development and deployment tools, you'll get all you need for deployment. This is how you build the environment: .. sourcecode:: bash # Create symlink to development.cfg so you don't have to append '-c buildout.cfg' all the time boutique.headquarters$ ln -s development.cfg buildout.cfg boutique.headquarters$ svn add buildout.cfg boutique.headquarters$ svn ci -m "added soft-link to development.cfg" # Make an isolated Python environment boutique.headquarters$ virtualenv -p python2.6 --no-site-packages ./ # Bootstrap zc.buildout boutique.headquarters$ bin/python bootstrap.py # Build development/deployment environment boutique.headquarters$ bin/buildout .. important:: Pin down egg versions by copying the last lines of output into versions.cfg. This makes sure that if you run this buildout in a year you will get the same versions of packages. **************** Basic deployment **************** Public keys =========== First you need to put administrators' public keys in ``boutique.headquarters/keys`` folder. If you have followed instructions in chapter :ref:`toolbox`, then you have all your colleagues' keys in ``~/SyncDisk/public_keys``. Each key's filename should match that administrator's user id. Example: Bob has a user id ``bob`` -> his public key should be copied into ``boutique.headquarters/keys/bob.pub`` .. sourcecode:: bash boutique.headquarters$ cp ~/SyncDisk/public_keys/bob.pub boutique.headquarters$ cp ~/SyncDisk/public_keys/jane.pub Fabric is your friend ===================== Great! You are ready to do basic deployment on your new Headquarters server. Since zc.buildout prepared a ``fabfile.py`` (a file with Fabric commands) for you, this is fairly easy. .. sourcecode:: bash boutique.headquarters$ bin/fab deploy_base .. warning:: Make sure you are using your Office IP because server access will be locked down to this IP only. .. note:: Fabric will use your local system username as username for accessing the server. If you want to use a different users, run Fabric with ` `bin/fab -u bob``. It's time make yourself another tea. Installing base software on CentOS normally takes about 10 minutes. .. note:: Note that Fabric will set a default ``sudo`` password (set in ``boutique.headquarters/base.cfg``) for all administrators. Tell all of them to login to the server and change their default ``sudo`` password to something unique and keep it to themselves. Make sure that all administrators have changed their ``sudo`` passwords before you go live with your site! .. note:: You can list available Fabric commands with ``bin/fab --list``. You server is now up and running. Open you browser and point it to ``http://<server_ip>/error.html``! If you see a ``Down for maintenance`` page then everything is fine. .. image:: down_for_maintenance.png ********** /etc/hosts ********** You don't have to use DNS yet, having IP's mapped to hostnames on your local machine is enough for now. Adding these lines to ``/etc/hosts`` does the trick. Note that you may have to restart your browser for changes to be applied. .. sourcecode:: bash boutique.headquarters$ sudo nano /etc/hosts :: <server_ip> ploneboutique.com sphinx.ploneboutique.com munin.ploneboutique.com hudson.ploneboutique.com You should be able to open http://ploneboutique.com/error.html in your browser and see a ``Down for maintenance`` page. ********************* Headquarters services ********************* ploneboutique.com ================= A simple HTML file with links to services running on this Headquarters server. index.html ---------- All you need is one file with links to services. Create a new file ``index.html`` in ``boutique.headquarters/src/boutique/headquarters/static``. Copy the markup below into this file. .. sourcecode:: bash boutique.headquarters$ nano src/boutique/headquarters/static/index.html .. sourcecode:: html <html> <head> <title> Services running on this Headquarters server. </title> </head> <body> <p> <ul> <li><a href="http://ploneboutique.com">ploneboutique.com</a> - this page</li> <li><a href="http://sphinx.ploneboutique.com">sphinx.ploneboutique.com</a> - Sphinx documentation for your projects</li> <li><a href="http://munin.ploneboutique.com">munin.ploneboutique.com</a> - Munin system information for your servers</li> <li><a href="http://hudson.ploneboutique.com">hudson.ploneboutique.com</a> - Automated unit tests for your projects</li> </ul> </p> </body> </html> Re-upload static files to server. .. sourcecode:: bash boutique.headquarters$ bin/buildout boutique.headquarters$ bin/fab reload_nginx_config At this point you should be able to point your browser to http://ploneboutique.com/index.html and see your page with links to Headquarters services. .. image:: ploneboutique.com.png :width: 600 hudson.ploneboutique.com ======================== Hudson will automatically pull code for your projects from your Subversion repository, run tests on them, report failures and also build Sphinx documentation. Installing Hudson ----------------- Copy/paste these lines somewhere into your ``boutique.headquarters/etc_templates/fabfile.py.in``. .. sourcecode:: python def install_hudson(): api.sudo('yum -y install ant apr-devel openssl-devel subversion') api.sudo('rpm --import http://hudson-ci.org/redhat/hudson-ci.org.key') api.sudo('wget -O /tmp/hudson.rpm http://hudson-ci.org/latest/redhat/hudson.rpm') api.sudo('rpm --install --replacepkgs /tmp/hudson.rpm') # limit hudson to 120MB RAM since it's a hungry thing sed('/etc/sysconfig/hudson', 'HUDSON_JAVA_OPTIONS="-Djava.awt.headless=true"', 'HUDSON_JAVA_OPTIONS="-Xss1024k -Xmn20M -Xms100M -Xmx120M -Djava.awt.headless=true"', use_sudo=True) api.sudo('chkconfig hudson on') api.sudo('/etc/init.d/hudson start') # create sphinx docs api.sudo('mkdir -p /var/www/sphinx') api.sudo('chown hudson:nginx /var/www/sphinx') api.sudo('gpasswd -a hudson nginx') Regenerate fabfile.py and run your new command:: boutique.headquarters$ bin/buildout boutique.headquarters$ bin/fab install_hudson Nginx server block ------------------ Below the ``# ploneboutique.com`` server block in ``boutique.headquarters/etc_templates/nginx.conf.in`` add another block to handle requests for ``hudson.ploneboutique.com``. .. sourcecode:: nginx # hudson.ploneboutique.com server { listen 80; server_name hudson.ploneboutique.com; location / { proxy_pass http://localhost:8080/; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X_FORWARDED_SERVER $server_name; proxy_set_header X_FORWARDED_FOR $proxy_add_x_forwarded_for; proxy_set_header X_FORWARDED_HOST $proxy_host; proxy_set_header Host $http_host; # restrict access allow 127.0.0.1; allow ${config:office_ip}; deny all; } } Reloading Nginx configuration is simple, thanks to Fabric commands prepared by zc.buildout: .. sourcecode:: bash # re-generate nginx.conf boutique.headquarters$ bin/buildout # reload nginx so changes to etc/nginx/nginx.conf take effect boutique.headquarters$ bin/fab reload_nginx_config At this point you should be able to point your browser to http://hudson.ploneboutique.com/. .. image:: hudson.png :width: 600 Configure Hudson ---------------- Not done quite yet. You now need to configure Hudson and install some plugins. #. In menu select ``Manage Hudson`` #. ``Configure System`` #. Scroll down to ``E-mail Notifications`` * SMTP server: ``localhost`` * System Admin E-mail Address: ``Hudson <[email protected]>`` #. Save #. ``Manage Hudson`` #. ``Manage Plugins`` #. Click tab ``Available`` and select following ones: * Plot Plugin * Dashboard View * Green Balls * Post build task * Python plugin #. Install #. After plugins are installed click the ``Restart`` button Add headquarters to Hudson -------------------------- Add new job with following configuration: * Project name: **headquarters.ploneboutique** * Source Code Management: * Subversion * repository URL: **http://boutique.unfuddle.com/svn/boutique_headquarters/trunk** * Local module directory (optional): **.** * Build triggers * Poll SCM * Schedule: **@hourly** * Build -> Add build step: * Execute shell .. sourcecode:: console cd $WORKSPACE virtualenv --no-site-packages -p python2.6 . ./bin/python bootstrap.py ./bin/buildout * Execute shell .. sourcecode:: console ./bin/sphinxbuilder mkdir -p /var/www/sphinx/${JOB_NAME}/ cp -R docs/html/* /var/www/sphinx/${JOB_NAME}/ chmod -R 774 /var/www/sphinx/${JOB_NAME}/ * Save .. todo:: default email for hudson .. todo:: add boutique.headquarters project to hudson so it builds Sphinx docs .. todo:: unfuddle hudson user sphinx.ploneboutique.com ======================== Sphinx documentation is automatically built by Hudson and placed into ``/var/www/sphinx``. You just need to add a new server block to Nginx to serve these files. Nginx server block ------------------ Below the ``# hudson.ploneboutique.com`` server block in ``boutique.headquarters/etc_templates/nginx.conf.in`` add another block to handle requests for ``sphinx.ploneboutique.com``. .. sourcecode:: nginx # sphinx.ploneboutique.com server { listen 80; server_name sphinx.ploneboutique.com; location / { expires 1h; autoindex on; root /var/www/sphinx; # restrict access allow 127.0.0.1; allow ${config:office_ip}; deny all; } } And reload Nginx config. .. sourcecode:: bash boutique.headquarters$ bin/buildout boutique.headquarters$ bin/fab reload_nginx_config At this point you should be able to point your browser to http://sphinx.ploneboutique.com/ and see your projects' documentation. .. todo:: this image is still missing -> waiting for iElectric to do Sphinx autogeneration so I can do a screenshot .. image:: sphinx.png :width: 600 munin.ploneboutique.com ======================= All project servers prepared with Plone Boutique have a Munin node installed. On Headquarters, you need to also install Munin master, which gathers information from these nodes and displays it graphically. Installing Munin-master ----------------------- Copy/paste these lines somewhere into your ``boutique.headquarters/etc_templates/fabfile.py.in``: .. sourcecode:: python def install_munin_master(): api.sudo('yum -y install munin') api.sudo('chkconfig munin-node on') Regenerate fabfile.py and run your new command. .. sourcecode:: bash boutique.headquarters$ bin/buildout boutique.headquarters$ bin/fab install_munin_master Nginx server block ------------------ Below the ``# sphinx.ploneboutique.com`` server block in ``boutique.headquarters/etc_templates/nginx.conf.in`` add another block to handle requests for ``munin.ploneboutique.com``. .. sourcecode:: nginx # munin.ploneboutique.com server { listen 80; server_name munin.ploneboutique.com; location / { index index.html; root /var/www/html/munin/; # restrict access allow 127.0.0.1; allow ${config:office_ip}; deny all; } } And reload Nginx. .. sourcecode:: bash boutique.headquarters$ bin/buildout boutique.headquarters$ bin/fab reload_nginx_config At this point you should be able to point your browser to http://munin.ploneboutique.com/ and see your website online. .. image:: munin.png :width: 600 ************ DNS settings ************ Finally, now that you have your server set-up and running, it's time to set DNS settings, so your site becomes visible to the world. First go to your domain registrar and enter the following two nameservers for you headquarters domain: - dns1.stabletransit.com - dns2.stabletransit.com #. Go to http://manage.rackspacecloud.com -> ``Hosting`` -> ``Cloud Servers`` -> ``headquarters`` -> ``DNS`` tab. #. Under ``Domain Management`` click ``Add`` and add ``ploneboutique.com``. .. image:: add_domain.png :width: 500 #. Click on a just-added domain and add a record: - Type: A - Name: ploneboutique.com - Content: <server_ip> - TTL: 86400 .. image:: add_a_record.png :width: 500 Save and wait for a day or so for DNS changes to propagate through the web. And this is it! Continue with the next chapter. .. note:: Use command line tool ``dig`` for debugging DNS settings. ************* Where to now? ************* Alright, now you have your :ref:`toolbox` ready, your Headquarters server configured and running and you are familiar with :doc:`assumptions this guide makes </prelude/index>`. It's time to continue to the last chapter, likely the easiest one, :ref:`plone-project`. .. _create an account at Unfuddle: https://secure.unfuddle.com/accounts/new?plan=micro .. _create an account at Rackspace Cloud: http://www.rackspacecloud.com/1320.html
zopeskel.niteoweb
/zopeskel.niteoweb-1.0b1.tar.gz/zopeskel.niteoweb-1.0b1/docs/source/headquarters/index.rst
index.rst
.. _plone-project: ########################## Commercial Plone 4 project ########################## ************ Introduction ************ Now that you have come this far, this chapter should feel like a walk in the park. Without further ado, let's get started. The guide is using an imaginary client ``eBar Ltd.`` that needs a website on ``ebar.si``. Imaginary Plone consultancy firm is still ``Plone Boutique Ltd.``. ************* Code skeleton ************* Unfuddle ======== Create a new project with Subversion repository (use ``ebar`` for project id). Give all your colleagues permissions on this project. Now prepare your new Unfuddle Subversion repository by adding base folders: .. sourcecode:: bash ~$ svn mkdir http://boutique.unfuddle.com/svn/boutique_ebar/{trunk,branches,tags} -m 'Added base folders' Cloud server ============ Login to ``manage.rackspacecloud.com`` and navigate to Cloud Server and click ``Add Server``. Choose ``CentOS 5.5`` for distro and ``265 MB`` for instance size. For ``Server Name`` enter ``ebar``. Write down server's IP and root password. You'll need it for generating a project skeleton with ZopeSkel. ZopeSkel ======== Prepare ZopeSkel ---------------- Install/Upgrade ZopeSkel to latest version. .. sourcecode:: bash $ sudo easy_install -U ZopeSkel Install/Upgrade zopeskel.niteoweb to latest version. .. sourcecode:: bash $ sudo easy_install -U zopeskel.niteoweb Generate code ------------- Run ZopeSkel to generate a skeleton based on niteoweb_project template (the one used for all Plone Boutique projects). .. sourcecode:: bash $ cd ~/work $ paster create -t niteoweb_project boutique.ebar Expert Mode? (What question mode would you like? (easy/expert/all)?) ['easy']: easy Description (One-line description of the project) ['Plone Boutique commercial project for eBar.si']: Hostname (Domain on which this project will run on.) ['ebar.si']: ebar.si IP (IP of production server. Leave default if you don't have one yet) ['87.65.43.21']: <server_ip> Temporary root password (Temporary password for root user on production server. Leave default if you don't have one yet) ['root_password_here']: ebarM4Q8fsN90 Maintenance users (Usernames of administrators that will have access to your production server, separated with commas.) ['bob,jane']: bob,jane Headquarters hostname (Domain on which your Headquarters server is running.) ['ploneboutique.com']: ploneboutique.com Maintenance IP (IP on which your Headquarters server is listening.) ['12.34.56.78']: <headquarters_ip> Office IP (Your office IP that you use daily and can VPN to) ['12.34.56.78']: <your_office_ip> Commit project skeleton ----------------------- Ok, skeleton is ready. Commit it to Subversion and continue working on it: .. sourcecode:: bash # Checkout Unfuddle's Subversion repository for this project work$ cd boutique.ebar/ boutique.ebar$ svn co http://boutique.unfuddle.com/svn/boutique_ebar/trunk ./ # Commit code skeleton boutique.ebar$ rm -rf src/boutique.ebar.egg-info boutique.ebar$ svn add * boutique.ebar$ svn ci -m "added project skeleton" # Set svn:ignore, instructions how to do this are also in svnignore files boutique.ebar$ svn propset svn:ignore -F svnignore ./ boutique.ebar$ svn propset svn:ignore -F docs/svnignore ./docs boutique.ebar$ svn propset svn:ignore -F etc/svnignore ./etc boutique.ebar$ svn up boutique.ebar$ svn ci -m "set svn:ignore" ***************** Plone Development ***************** Development environment ======================= Use zc.buildout to prepare your development environment for you. .. sourcecode:: bash # Create symlink to development.cfg so you don't have to append '-c buildout.cfg' all the time boutique.ebar$ ln -s development.cfg buildout.cfg boutique.ebar$ svn add buildout.cfg boutique.ebar$ svn ci -m "added soft-link to development.cfg" # Make an isolated Python environment boutique.ebar$ virtualenv -p python2.6 --no-site-packages ./ # Bootstrap zc.buildout boutique.ebar$ bin/python bootstrap.py # Build development/deployment environment boutique.ebar$ bin/buildout .. note:: Pin down egg versions by copying the last lines of output into versions.cfg. This makes sure that if you run this buildout in a year you will get the same versions of packages. Start it up! ============ You are now ready to start Zope in development mode, create your first Plone site and hack away:: boutique.ebar$ bin/zope fg .. warning:: For Nginx rewriting to work correctly your Plone's id needs to match your project's package name, e.g. ``ebar``. Plone Development ================= You are now ready to start customizing Plone to your needs. Properties ---------- Open src/boutique/ebar/profiles/default/properties.xml and set some site properties. Read more about these XMLs: (TODO: links and pointers to GenericSetup documentation) - http://plone.org/documentation/kb/genericsetup - http://plone.org/documentation/manual/developer-manual/generic-setup Theming ------- Add your custom CSS and JS to ``ebar.css`` and ``ebar.js`` that you have in ``src/boutique/ebar/skins/ebar_css/ebar.css`` and ``src/boutique/ebar/skins/ebar_js/ebar.js``. Both files are already registered with Plone, for your convenience. Plone theming is a broad subject and is out of scope of this guide. Read more about theming: - http://plone.org/products/collective.xdv/documentation/reference-manual/theming - http://plone.org/documentation/kb/advanced-xdv-theming Testing your code ================= Test if your product is correctly installed in Plone by running ``bin/test -s boutique.ebar``. Testing your Plone codeis a broad subject and is out of scope of this guide. Read more about testing: - http://plone.org/documentation/manual/developer-manual/testing - http://plone.org/documentation/kb/testing **************** Plone Deployment **************** Now here is where true fun begins and the value of zopeskel.niteoweb ZopeSkel template shows it's value. You will deploy your Plone site to a Rackspace Cloud server running CentOS in a matter of minutes without ever connecting to the server. Copy over public keys ===================== .. sourcecode:: bash boutique.ebar$ cp ~/SyncDisk/public_keys/*.pub ./keys Bootstrap the server ==================== Re-generate Fabric command file and deploy on server. .. sourcecode:: bash boutique.ebar$ bin/buildout boutique.ebar$ bin/deploy Set local DNS settings ====================== You don't have to use DNS yet, having IP's mapped to hostnames in your local machine is enough for now. Adding the lines below to ``/etc/hosts`` does the trick. Note that you may have to restart your browser for changes to be applied:: boutique.ebar$ sudo nano /etc/hosts .. sourcecode:: bash <server_ip> ebar.si You should be able to open http://ebar.si/ in your browser and see a your Plone site. Redeploy ======== Every time you do changes to your code, configuration or data, you simply use one of Fabric commands to perform deployment or update on the server: .. sourcecode:: bash boutique.ebar$ bin/fab reload_nginx_config boutique.ebar$ bin/fab update_static_files boutique.ebar$ bin/fab update_code boutique.ebar$ bin/fab run_buildout boutique.ebar$ bin/fab upload_data boutique.ebar$ bin/fab download_data boutique.ebar$ bin/fab restart supervisor_command
zopeskel.niteoweb
/zopeskel.niteoweb-1.0b1.tar.gz/zopeskel.niteoweb-1.0b1/docs/source/plone_project/index.rst
index.rst
####### Prelude ####### ****** Budget ****** Following this guide thoroughly will result in these monthly expenses: - $11 - Rackspace Cloud instance for Headquarters server, ploneboutique.com - $11 - Rackspace Cloud instance for one commercial project, ebar.si - $6 - 3 Rackspace Email accounts: [email protected], [email protected] and [email protected] - $9 - Micro plan at Unfuddle (code repository and task manager) - $4 - JungleDisk Desktop for syncing company documents and files among employees with approx. 8 GB storage - **SUM**: $41 ******* Purpose ******* Purpose of this guide is to guide a less experienced Plone developer/administrator through the whole process of starting and deploying a Plone project. This guide differs from other guides by taking choices instead of reader. Plone and it's stack has many movable parts and choosing right ones can be daunting. This guides makes this choices for you. They are not always the best, however they can get you from square 1 to a decently deployed Plone site in no time. *********** End product *********** Headquarters ============ End product of this guide is a Headquarters server with: - Sphinx documentation of all your code projects (on ``sphinx.yourcompany.com``) - system information for all your servers, gathered with `Munin`_ (on ``munin.yourcompany.com``) - Hudson continuous integration service which runs your unit-tests every time you commit new code (on ``hudson.yourcompany.com``) Commercial project ================== Besides your main server, you'll have another server which runs your commercial project, ``ebar.si``, based on Plone 4. End product =========== .. image:: ../end_product.png :width: 100% Legend: **Plone Boutique Ltd.** Imaginary Plone consultancy firm used throughout this guide. **EBar Ltd.** Plone Boutique Ltd.'s imaginary client that needs a commercial Plone 4 site, running on http://ebar.si **Bob** One of Plone Boutique Ltd. developers. **Jane** One of Plone Boutique Ltd. developers. **Unfuddle** Repository hosting and issue tracker for Plone Boutique Ltd.'s project. **Rackspace Email** Email provider for Plone Boutique Ltd. ****************************** Security on production servers ****************************** Users ===== #. Root SSH login is disabled. #. SSH login only with password is disabled. #. Administrator logs-in only with his dedicated maintenance account, then issues ``sudo su -`` to get higher privileges that enable him to do maintenance on the server. #. Zope and related services run under dedicated user ``production`` which also has SSH login disabled. Administrators access this account by running ``sudo su - production``. #. Nginx is running under a separate dedicated user ``nginx`` as it's the only service that is facing the internet directly. .. image:: users.png :width: 600 Ports ===== During deployment, a basic *iptables* firewall is installed on your server to block unwanted traffic. Allowed ports are: #. 80 from anywhere - for HTTP requests #. 22 from your office IP - for SSH access #. 4949 from your Headquarters server IP - for Munin system reports .. image:: ports.png :width: 600 *********** Assumptions *********** Example names ============= * Plone Boutique Ltd. - imaginary Plone company used as an example in this guide * ``boutique`` - short name of imaginary Plone company used for usernames, code package names, etc. * ``ebar`` - the name of an imaginary project of Plone Boutique Ltd., used as an example * ``bob`` - one of developers in Plone Boutique Ltd. * ``jane`` - another Plone Boutique Ltd. developer Strictly following recommendations in Toolbox chapter ===================================================== Since you want to make your life easier, acknowledge that this guide makes a lot of choices for you. Just stick to them now and once you get the whole picture you will be able to do things your way. Package structure ================= This is an example of what files are in an imaginary commercial project for website ``ebar.si``. For this project we have one package with code and configuration, called ``boutique.ebar``. :: boutique.ebar/ (root folder of your egg) |-- base.cfg (buildout configuration that is shared among other *.cfg's, like project eggs, constants, ...) |-- bootstrap.py (run this to bootstrap your buildout environment) |-- buildout.cfg (symlink file pointing to development.cfg) |-- coverage.cfg (.cfg used to calculate code test coverage of this project on Headquar) |-- development.cfg (.cfg for building development environment with debugging, testing and deployment tools) |-- ebar.tmproj (TextMate project file) |-- hudson.cfg (.cfg used by Hudson to build your project and run unit tests on Headquarters server) |-- production.cfg (.cfg for building production environment on the server) |-- README.txt (where to find more info) |-- setup.cfg (configuration file for setup.py) |-- setup.py (python setup file) |-- sphinx.cfg (.cfg used to build Sphinx documentation of this project on Headquarters server) |-- svnignore (list of files/folders that should be ignored by subversion) |-- versions.cfg (list of pinned egg versions used for this project) |-- zopeskel.cfg (Answers to ZopeSkel's questions to ensure repeatability of 'paster create -t niteoweb_project') |-- docs (directory containing source files for Sphinx documentation) | |-- HISTORY.txt (records changes made to this egg) | |-- INSTALL.txt (info on installing this egg) | |-- LICENSE.txt (info on licensing, normally its GPL) | |-- LICENSE.GPL (copy of Gnu Public License) | `-- source | |-- conf.py (Sphinx configuration file) | |-- index.rst (main documentation file) | |-- _static (Sphinx puts images in this folder when generating HTML) | `-- _templates (Sphinx puts files in this folder when generating HTML) |-- etc (folder containing configuration files generated by buildout from ./etc_templates) |-- etc_templates (containing templates that zc.buildout uses to generate system-level configuration) | |-- iptables.conf.in (template for iptables configuration file) | |-- fabfile.py.in (template for Fabric commands for deploymnent) | |-- munin-node.conf.in (template for configuration for Munin node) | `-- nginx.conf.in (template for Nginx configuration file) |-- keys (containing public keys of developers with access to production server) | |-- bob.pub (Bob's public key) | `-- jane.pub (Jane's public key) `-- boutique (directory containing actual code for this application) |-- __init__.py `-- ebar |-- __init__.py (initializer called when used as a Zope 2 product.) |-- config.py (defining project-wide code constants) |-- configure.zcml (main configure.zcml) |-- interfaces.py (defining project-wide interfaces and exceptions) |-- browser (directory containing Zope3 style resources) | |-- __init__.py | `-- configure.zcml (configuring Zope3 style resources) |-- profiles (directory containing GenericSetup configuration) | `-- default | |-- cssregistry.xml (configure Plone's portal_css) | |-- jsregistry.xml (configure Plone's portal_javascripts) | |-- metadata.xml (version and other information for Plone about this egg) | |-- properties.xml (configure Plone's main properties like site title) | `-- skins.xml (configure Plone's portal_skins) |-- skins (directory containing Zope2 style resources) | |-- ebar_css (directory containing your custom CSS) | |-- ebar_images (directory containing your custom images) | |-- ebar_js (directory containing your custom JavaScripts) | |-- ebar_scripts (directory containing your custom Script (Python) scripts) | `-- ebar_templates (directory containing your custom Zope Page Templates) |-- static (directory containing static resources that will be server directly by Nginx in front of Zope) | `-- error.html (static HTML error page that is displayed if something goes wrong with Zope) |-- tests (directory containing unit, functional and system tests) | |-- __init__.py (setup TestCases for your project) | |-- test_setup.py (test if this egg is correctly installed to Plone) | `-- test_windmill.py (real-browser test of your Plone project) `-- xdv (directory containing collective.xdv templates and rules) |-- template.html `-- rules.xml .. URLs for links in content. .. _Munin: http://munin-monitoring.org/
zopeskel.niteoweb
/zopeskel.niteoweb-1.0b1.tar.gz/zopeskel.niteoweb-1.0b1/docs/source/prelude/index.rst
index.rst
.. _toolbox: ####### Toolbox ####### ****************** Developer machines ****************** Whatever system you are using (hopefully not Windows) you need the following tools installed on your system: - a decent code editor (Kate on Kubuntu, TextMate on OSX, vim, emacs, etc.) - subversion - python 2.6 - whatever you need to be able to run buildout (``build-essentials`` package on Ubuntu, *XCode* on OSX, etc.) ************************* Outsourcing core services ************************* Let's say you charge $50 per hour for your work. If you have only a few hours of maintenance per year to do on your email/issuer-tracker/subversion server, you've already spent more than you would have if you'd paid someone else to take care of these services. And you'll have far more than 2 hours per year of maintenance work. Plus, your multi-purpose server will surely go down exactly when you are relaxing on some beach. Every single time. Subversion repository and issuer tracker ======================================== I'd recommend using Unfuddle as you get both of the above mentioned in on place. Commit messages can be nicely linked to issues and vice-versa. Also, they offer free plans for small projects, after that the plans start at $9/month. It has less features and cool factor than github or bitbucket, but for starters it's ok. It's simple, fast enough and has not had any serious downtime for the past 3 years. .. image:: unfuddle.png :width: 600 Email ===== Use Rackspace Email. I've learned the hard way that saving money when choosing email provider is plain stupid. A quality one ensures your emails get delivered on time, every time and into one's inbox instead of SPAM folder. They are a bit on the upper with the price being $2 per mailbox per month, but it's worth it. Since mailboxes have their price, think before you create a new one. Normally having one mailbox for your info@ email and one for each employee is enough. If you need additional email addresses sort it out with aliases. Aliases are free and you can add an unlimited amount of them. Some may say why not use Gmail which is free for up to 50 mailboxes? Well their support record is't really what is should be for such a critical service. It's logical if you consider that email isn't their primary business and they can decide to stop providing the service any time. .. image:: email.png :width: 600 Backups and archiving ===================== The recommendation here is JungleDisk. It's basically the same as DropBox, but with data encryption. For starters you can easily use Desktop Edition, which costs $3/month plus $0.15 per GB/month. Cheap enough. .. note:: JungleDisk allows you to choose where you want to store your data, Rackspace Cloud or Amazon S3. Both options cost the same for 1GB/month of storage, but Amazon S3 also charges for incoming and outgoing bandwidth. Ergo, Rackspace Cloud is a better pick here, obviously. With JungleDisk you have 3 options to chose from: - Simple Backup (daily backs up a folder on your machine) - Online Disk (file are stored on an online disk and do not take up space on your local disk) - Sync Folder (same funcitonality as dropbox, you have access to files even when offline) SyncDisk -------- This is a folder in your home folder which you and your colleagues use to share frequently used files. Use JungleDisk Desktop software to Sync Folder called SyncDisk and limit it to about 2GB or so. Normally you would want to have it at ``/home/bob/SyncDisk`` or ``/Users/bob/SyncDisk``. The name *SyncDisk* indicates that it's functionality is the same as DropBox's. Database containing passwords stored with KeePass should be contained in SyncDisk so all changes are immediately propagated to your colleagues' KeePasses. OnlineDisk ---------- This is a JungleDisk online disk that you use as an archive. Old documents and files, backups, archives. Since this data is not on you local disk you are not limited by your machine's capacity. Note that you don't have access to this files unless you have internet connections. Emergency files and documents should be stored in SyncDisk. Sum === Following the advice and creating a micro account at Unfuddle, creating 3 mailboxes at Rackspace Email and setting up a cca. 8GB online disk at JungleDisk, your monthly running costs are $19 ($9 + $6 + $4). A small price to pay for having a good night sleep, every night. ********* Passwords ********* Always use at least semi-strong passwords (at least 8 characters, letters and numbers, etc.) Never ever keep passwords in plain-text form. Always use a password manager. Seriously. The easiest way to do it is to use KeePass. It works on all major platforms and is easy to use. Put it's database into SynxBox and share it with all your colleagues. This way whenever someone adds a new password, others get to see it almost immediately. *********** Public keys *********** Using passwords to connect to production servers is bad. Google it a bit, using `Public Key Authentication`_ is several orders of magnitude more secure and convenient. All developers need to create their personal keys and upload them to SyncDisk. *********************** Virtual Private Network *********************** .. toctree:: :maxdepth: 3 vpn.rst .. URLs for links in content. .. _Public Key Authentication: http://sial.org/howto/openssh/publickey-auth/
zopeskel.niteoweb
/zopeskel.niteoweb-1.0b1.tar.gz/zopeskel.niteoweb-1.0b1/docs/source/toolbox/index.rst
index.rst
*********************** Virtual Private Network *********************** `Virtual Private Networks`_ or VPNs are just so great. You can lock all your servers down to listen for SSH requests only from your office's IP. And with VPN you can remotely connect to your office LAN and work as if you were physically there. Besides that, all traffic from you to your office is encrypted so you can safely work even when on public WiFi networks. This chapter will guide you step-by-step on how to install OpenVPN server on an affordable `Linksys WRT54G`_ wireless router and how to setup Linux and OS X clients for accessing your brand new VPN. You can probably use any router capable of running `DD-WRT`_ firmware but this guide assumes you have a Linksys WRT54G router. Certificates ============ First off, you need to create certificates for authorization and encryption of VPN tunnels. Let's not install extra libraries on our local machines just so we can generate some keys. Instead, let's leverage Rackspace Cloud servers. Creating a temporary 256MB Ubuntu instance is just 2 minutes away and costs only $0.015 per hour. .. note:: After you are done creating certificate remember to shut down this temporary Ubuntu server to not spend resources. Tutorial -------- Once you have a temporary Ubuntu instance up, follow instruction below. For more information on executed commands, read this `tutorial on dd-wrt.com`_. Variables --------- The tutorial suggests setting *vars*. Do that by editing file ``vars`` and making the bottom lines look like this:: local-macbook:~ bob$ ssh [email protected] root@vpn:~# cd /usr/share/doc/openvpn/examples/easy-rsa/2.0/ root@vpn:/usr/share/doc/openvpn/examples/easy-rsa/2.0# cp vars vars-org root@vpn:/usr/share/doc/openvpn/examples/easy-rsa/2.0# nano vars export KEY_COUNTRY="SI" export KEY_PROVINCE="Slovenia" export KEY_CITY="Ljubljana" export KEY_ORG="Plone Boutique" export KEY_EMAIL="[email protected]" Generating certificates ----------------------- Now start creating certificates:: local-macbook:~ bob$ ssh [email protected] root@vpn:~# apt-get install openvpn openssl root@vpn:~# cd /usr/share/doc/openvpn/examples/easy-rsa/2.0/ root@vpn:/usr/share/doc/openvpn/examples/easy-rsa/2.0# source ./vars root@vpn:/usr/share/doc/openvpn/examples/easy-rsa/2.0# ./clean-all root@vpn:/usr/share/doc/openvpn/examples/easy-rsa/2.0# ./build-ca Country Name (2 letter code) [SI]: State or Province Name (full name) [Slovenia]: Locality Name (eg, city) [Ljubljana]: Organization Name (eg, company) [Plone Boutique]: Organizational Unit Name (eg, section) []: Common Name (eg, your name or your server's hostname) [Plone Boutique CA]: Name []: Email Address [[email protected]]: root@vpn:/usr/share/doc/openvpn/examples/easy-rsa/2.0# ./build-key-server server Country Name (2 letter code) [SI]: State or Province Name (full name) [Slovenia]: Locality Name (eg, city) [Ljubljana]: Organization Name (eg, company) [Plone Boutique]: Organizational Unit Name (eg, section) []: Common Name (eg, your name or your server's hostname) [server]: Name []: Email Address [[email protected]]: A challenge password []: An optional company name []: Sign the certificate? [y/n]: y 1 out of 1 certificate requests certified, commit? [y/n] y root@vpn:/usr/share/doc/openvpn/examples/easy-rsa/2.0# ./build-key bob Country Name (2 letter code) [SI]: State or Province Name (full name) [Slovenia]: Locality Name (eg, city) [Ljubljana]: Organization Name (eg, company) [Plone Boutique]: Organizational Unit Name (eg, section) []: Common Name (eg, your name or your server's hostname) [bob]: Name []: Email Address [[email protected]]:[email protected] A challenge password []: An optional company name []: Sign the certificate? [y/n]:y 1 out of 1 certificate requests certified, commit? [y/n]y root@vpn:/usr/share/doc/openvpn/examples/easy-rsa/2.0# ./build-dh root@vpn:/usr/share/doc/openvpn/examples/easy-rsa/2.0# ls keys 01.pem ca.key index.txt.attr serial server.csr bob.csr 02.pem dh1024.pem index.txt.attr.old serial.old server.key bob.key ca.crt index.txt index.txt.old server.crt bob.crt Archiving certificates ---------------------- You need to store generated certificates so you can give them to colleagues that will use VPN to remotely connect to your office LAN. In order to be able to create new certificates later on you also need to store other files in folder ``keys``. So the best approach here is to compress and encrypt the whole ``vars`` folder and save it to your OnlineDisk. Save the encryption password to KeePass. First, copy ``vars`` file to keys folder, so we also archive this file:: root@vpn:/usr/share/doc/openvpn/examples/easy-rsa/2.0# cp vars keys/ Now you are ready to compress/encrypt ``keys`` folder and download it to your local machine to archive it to your OnlineDisk:: root@vpn:/usr/share/doc/openvpn/examples/easy-rsa/2.0# tar cz keys | openssl enc -aes-256-cbc -e > keys.tar.gz.enc root@vpn:/usr/share/doc/openvpn/examples/easy-rsa/2.0# apt-get install rsync local-macbook:~ bob$ rsync -avzhP [email protected]:/usr/share/doc/openvpn/examples/easy-rsa/2.0/keys.tar.gz.enc /Users/bob/OnlineDisk/vpn_keys.tar.gz.enc Creating additional certificates -------------------------------- Inevitably you'll be faced with creating additional certificates. Either you get a new team member or someone will loose their certificate. Since we have the everything we need archived on OnlineDisk, this is fairly easy. Create a new Ubuntu cloud server instance and install ``openssl`` and ``rsync``:: local-macbook:~ bob$ ssh [email protected] root@vpn:~# apt-get install openvpn openssl rsync Upload keys to temporary server:: local-macbook:~ bob$ rsync -avzhP /Users/bob/OnlineDisk/vpn_keys.tar.gz.enc [email protected]:/usr/share/doc/openvpn/examples/easy-rsa/2.0/keys.tar.gz.enc Decrypt and decompress keys on the server:: local-macbook:~ bob$ ssh [email protected] root@vpn:~# cd /usr/share/doc/openvpn/examples/easy-rsa/2.0/ root@vpn:/usr/share/doc/openvpn/examples/easy-rsa/2.0# openssl enc -d -aes-256-cbc -in keys.tar.gz.enc -out keys.tar.gz root@vpn:/usr/share/doc/openvpn/examples/easy-rsa/2.0# tar xf keys.tar.gz root@vpn:/usr/share/doc/openvpn/examples/easy-rsa/2.0# ls keys 01.pem ca.key index.txt.attr serial server.csr bob.crt 02.pem dh1024.pem index.txt.attr.old serial.old server.key bob.csr ca.crt index.txt index.txt.old server.crt vars bob.key Move file ``vars`` back to where it's expected to be find:: root@vpn:/usr/share/doc/openvpn/examples/easy-rsa/2.0# cp vars vars_orig root@vpn:/usr/share/doc/openvpn/examples/easy-rsa/2.0# cp keys/vars vars Create a new certificate:: root@vpn:/usr/share/doc/openvpn/examples/easy-rsa/2.0# source ./vars root@vpn:/usr/share/doc/openvpn/examples/easy-rsa/2.0# ./build-key jane Country Name (2 letter code) [SI]: State or Province Name (full name) [Slovenia]: Locality Name (eg, city) [Ljubljana]: Organization Name (eg, company) [Plone Boutique]: Organizational Unit Name (eg, section) []: Common Name (eg, your name or your server's hostname) [jane]: Name []: Email Address [[email protected]]: A challenge password []: An optional company name []: Sign the certificate? [y/n]:y 1 out of 1 certificate requests certified, commit? [y/n]y root@vpn:/usr/share/doc/openvpn/examples/easy-rsa/2.0# ls keys 01.pem ca.crt jane.csr index.txt index.txt.old server.crt vars bob.key 02.pem ca.key jane.key index.txt.attr serial server.csr bob.crt 03.pem jane.crt dh1024.pem index.txt.attr.old serial.old server.key bob.csr Archive the newly created certificate by repeating the procedure from the previous chapter (archiving the whole ./keys folder to OnlineDisk). OpenVPN Server ============== Now that we have certificates prepared we can start setting up an OpenVPN server on the WRT54G router. Installing ---------- Go to the DD-WRT download page and grab the package that also has OpenVPN support (dd-wrt.v24_vpn_generic.bin). Follow official DD-WRT instructions on how to flash of the router's firmware and continue below. Configuring ----------- - Enable OpenVPN server in Services tab and set it's Start type to WAN Up. - Paste in certificates created in advance on a temporary Ubuntu cloud instance. - To field ``Public Server Cert for OpenVPN`` insert contents of file ``ca.crt`` - To field ``Public Client Cert for OpenVPN`` insert contents of file ``server.crt`` - To field ``Private Client Cert for OpenVPN`` insert contents of file ``server.key`` - To field ``DH PEM for OpenVPN`` insert contents of file ``dh1024.pem`` - Paste in OpenVPN server config:: push "route 192.168.1.0 255.255.255.0" server 192.168.2.0 255.255.255.0 dev tun0 proto udp keepalive 10 120 dh /tmp/openvpn/dh.pem ca /tmp/openvpn/ca.crt cert /tmp/openvpn/cert.pem key /tmp/openvpn/key.pem # management parameter allows DD-WRT's OpenVPN Status web page to access the server's management port # port must be 5001 for scripts embedded in firmware to work management localhost 5001 - Configure *iptables* firewall by going to Administration -> Commands, pasting in iptables config and clicking save firewall:: # enable tunnel iptables -I INPUT 1 -p udp --dport 1194 -j ACCEPT iptables -I FORWARD 1 --source 192.168.2.0/24 -j ACCEPT iptables -I FORWARD -i br0 -o tun0 -j ACCEPT iptables -I FORWARD -i tun0 -o br0 -j ACCEPT # NAT the VPN client traffic to the internet iptables -t nat -A POSTROUTING -s 192.168.2.0/24 -o eth0 -j MASQUERADE - Restart router. OpenVPN Clients =============== Ok, we have certificates and we also have a running OpenVPN. Time to install OpenVPN client on your local machine and connect! OS X ---- For OS X users the recommended application for using OpenVPN is Tunnelblick. #. Go to `Tunnelblick's website`_, download Tunnelblick 3.0 application and install it. #. Run Tunnelblick. Click ``install and edit sample configuration file`` and paste into it this client configuration (replace ``bob`` with your nickname and add your office IP and your ISP's DNS):: # Specify that we are a client and that we will be pulling certain config file directives from the server. client # Use the same setting as you are using on the server. # On most systems, the VPN will not function unless you partially or fully disable the firewall for the TUN/TAP interface. dev tun0 # Are we connecting to a TCP or # UDP server? Use the same setting as on the server. proto udp # The hostname/IP and port of the server. remote <your office IP> 1194 # Keep trying indefinitely to resolve the host name of the OpenVPN server. # Very useful on machines which are not permanently connected to the internet such as laptops. resolv-retry infinite # Most clients don't need to bind to a specific local port number. nobind # Downgrade privileges after initialization (non-Windows only) # NOTE: this cause problems with reverting to default route once VPN is disconnected # user bob # group bob # Try to preserve some state across restarts. persist-key persist-tun # Wireless networks often produce a lot of duplicate packets. Set this flag to silence duplicate packet warnings. mute-replay-warnings # SSL/TLS parms. ca ca.crt cert bob.crt key bob.key # Enable compression on the VPN link. Don't enable this unless it is also enabled in the server config file. ;comp-lzo # Set log file verbosity. verb 3 # from wiki remote-cert-tls server float # route all traffic through VPN # if you don't know what to enter, you can use 8.8.8.8 and 8.8.4.4, Google's Public DNSes redirect-gateway def1 dhcp-option DNS <your ISP's primary DNS IP> dhcp-option DNS <your ISP's secondary DNS IP> #. Use Terminal to add certificate keys to your Tunnelblick configuration (keys created on Ubuntu cloud instance), again replacing ``bob`` in filename:: nano ~/Library/Application\ Support/Tunnelblick/Configurations/ca.crt nano ~/Library/Application\ Support/Tunnelblick/Configurations/bob.crt nano ~/Library/Application\ Support/Tunnelblick/Configurations/bob.key Now you are ready to use your VPN. Click on Tunnelblick icon next to *current time* in the top-right corner of your screen and select ``connect openvpn``. All your traffic should now be routed through a secure tunnel to your office. Confirm this by visiting `whatismyip.com`_. The IP displayed should be your office's IP, meaning you are accessing internet through a tunnel from your office. Hooray! Ubuntu ------ For Ubuntu users it's best to just use command-line commands from OpenVPN package. #. Install with ``sudo apt-get install openvpn`` #. Add certificates keys created on temporary Ubuntu cloud instance ``~/.ssh/``. You need to copy ``ca.crt``, ``bob.crt`` and ``bob.key`` (replace ``bob`` with your nickname). #. Configure OpenVPN by copying this configuration to ``/etc/openvpn/client.conf``. Change paths to certificate keys so that they match your real paths:: # Specify that we are a client and that we will be pulling certain config file directives from the server. client # Use the same setting as you are using on the server. # On most systems, the VPN will not function unless you partially or fully disable the firewall for the TUN/TAP interface. dev tun0 # Are we connecting to a TCP or # UDP server? Use the same setting as on the server. proto udp # The hostname/IP and port of the server. remote <your office IP> 1194 # Keep trying indefinitely to resolve the host name of the OpenVPN server. # Very useful on machines which are not permanently connected to the internet such as laptops. resolv-retry infinite # Most clients don't need to bind to a specific local port number. nobind # Downgrade privileges after initialization (non-Windows only) # NOTE: this cause problems with reverting to default route once VPN is disconnected # user bob # group bob # Try to preserve some state across restarts. persist-key persist-tun # Wireless networks often produce a lot of duplicate packets. Set this flag to silence duplicate packet warnings. mute-replay-warnings # SSL/TLS parms. ca ca.crt cert bob.crt key bob.key # Enable compression on the VPN link. Don't enable this unless it is also enabled in the server config file. ;comp-lzo # Set log file verbosity. verb 3 # from wiki remote-cert-tls server float # route all traffic through VPN # if you don't know what to enter, you can use 8.8.8.8 and 8.8.4.4, Google's Public DNSes redirect-gateway def1 dhcp-option DNS <your ISP's primary DNS IP> dhcp-option DNS <your ISP's secondary DNS IP> #. Start by running ``sudo openvpn --config /etc/openvpn/client.conf``. Confirm that you are using VPN by visiting `whatismyip.com`_. The IP displayed should be your office's IP, meaning you are accessing internet through a tunnel from your office. Hooray! .. URLs for links in content. .. _Linksys WRT54G: http://en.wikipedia.org/wiki/Linksys_WRT54G_series .. _DD-WRT: http://www.dd-wrt.com/ .. _Virtual Private Networks: http://en.wikipedia.org/wiki/Virtual_private_network .. _whatismyip.com: http://whatismyip.com .. _Tunnelblick's website: http://code.google.com/p/tunnelblick/ .. _tutorial on dd-wrt.com: http://www.dd-wrt.com/wiki/index.php/VPN_(the_easy_way)_v24%2B#Creating_Certificates_using_Ubuntu_Linux.
zopeskel.niteoweb
/zopeskel.niteoweb-1.0b1.tar.gz/zopeskel.niteoweb-1.0b1/docs/source/toolbox/vpn.rst
vpn.rst
Introduction ============ This egg contains some paste templates to help to build a Plone architecture with as little knowledge as possible about Python and Plone. The first target is Debian Lenny up-to-date with the lenny-backports repository enabled. In a second time Debian Squeeze and Ubuntu LTS should be added. No ReadHat, Suse, Mandriva, or any RPM-based linux is on the roadmap. The docs directory contains all necessary steps about server configuration before installing this egg. These documents can be distributed separately under the specified license in each of them. These templates was initiated by the UNIS Team of the ENS de Lyon <[email protected]> and by Quadra Informatique <[email protected]>. The CECILL-B license is a BSD like license. The english and the french version are available in this directory. If you want to make patch or to send us a success story you can use the mail addresses above.
zopeskel.unis
/zopeskel.unis-1.14.zip/zopeskel.unis-1.14/README.txt
README.txt
import copy import os from zopeskel.unis.abstract_buildout import AbstractBuildout from zopeskel.base import BaseTemplate from zopeskel.base import var, EASY, EXPERT from zopeskel.vars import StringVar, BooleanVar, IntVar, OnOffVar, BoundedIntVar, StringChoiceVar #-------------------------------------- # Allows to choose the customer name #-------------------------------------- VAR_CUSTOMER = StringVar( 'customer', title='Customer name', description='', default='', modes=(EASY,EXPERT), page='Main', help=""" This is the customer name. """ ) #-------------------------------------- # Allows to choose the Domain name #-------------------------------------- VAR_DOMAIN = StringVar( 'domain_name', title='Domain name', description="Domain name that will be used to access to your Plone", default='dev.plone.localdomain', modes=(EASY, EXPERT), page='Main', help=""" This is the domain name used to access from external resources to your Plone throught proxy. eg: type preproduction.project.plone.yourdomain.com for http://preproduction.project.plone.yourdomain.com """ ) #-------------------------------------- # Allows to choose the Plone site id #-------------------------------------- VAR_PLONESITE_PATH = StringVar( 'plonesite_path', title='Plonesite id in the Zope root', description="Domain name that will be used to access to your Plone", default='site', modes=(EASY, EXPERT), page='Main', help=""" This is the id of the plone site object in Zope. It is used for """ ) #-------------------------------------- # Allows to choose the Plone version #-------------------------------------- VAR_PLONEVER = StringVar( 'plone_version', title='Plone Version', description='Plone version # to install', default='4-latest', modes=(EASY, EXPERT), page='Main', help=""" This is the version of Plone that will be used for this buildout. You should enter the version number you wish to use. """ ) #------------------------------------------ # Allows to choose the deployment profile #------------------------------------------ VAR_BUILDOUT_PROFILE = StringChoiceVar( 'buildout_profile', title='Buildout Default Profile', description='The profile use by default when you will run buildout for the first time', default='development', choices=('development', 'standalone', 'production', 'preproduction', 'local_preproduction'), modes=(EASY, EXPERT), page='Main', help=""" You can choose the profile that is use when you will run buildout. Option are: - development (default) - standalone (No ZEO) - production (ZEO with 2 instances) - preproduction (ZEO with 1 instance) - local_preproduction (ZEO with 1 instance for local servers) """ ) VAR_INSTANCE_TYPE = StringChoiceVar( 'instance_type', title='Instance Type', description='How do you want to store your ZODB?', page='Main', modes=(EXPERT,), default='filestorage', choices=('filestorage','relstorage'), help=""" This option lets you select your ZODB storage mode. The RelStorage store all data in a relational database instead of a single file. Database supposed to work: PostgreSQL, Oracle, MySQL. """ ) VAR_INSTANCE_ENUM = BoundedIntVar( #XXX 'instance_enum', title='Number of instances', description='Number of instances managed in the cluster', default='2', modes=(EXPERT,), page='Main', help=""" This option let you choose how many client chould be installed in this cluster. """, min=1, max=128, ) VAR_SHARED_BLOBS = BooleanVar( 'shared_blobs', title='Shared Blobs', description='Do you want to share files stored in blobstorage?', default='true', modes=(EXPERT), page='Main', help=""" By default files stored in blobs are shared throught the ZEO server connexion. If you activate this option files will be served directly throught the filesystem for all clients. """ ) VAR_MEMCACHE = BooleanVar( #XXX 'enable_memcache', title='Enable memcache', description="Enable the memcache machinery for let zeo clients shared memory", default='true', modes=(EXPERT,), page='Main', help=""" Use a memcache server to share RAM between ZEO clients. """ ) #-------------------------------------- # Allows to define a port starting value #-------------------------------------- VAR_PORTS_STARTING_VALUE = BoundedIntVar( 'ports_starting_value', title='Ports stating value', description='Ports starting value use to generate buildout files', default='8080', modes=(EASY, EXPERT), page='Main', help=""" This options lets you select the ports starting value that the configuration will use to generate the instance configuration (instance,zeo,varnish,pound/squid,...). """, min=1024, max=65535, ) #-------------------------------------- # Allows to choose a cache utility #-------------------------------------- VAR_CACHE_UTILITY = StringChoiceVar( #XXX 'cache_utility', title='Cache utility', description='Which cache utility would you like? (Squid/Varnish)?', page='Main', modes=(EXPERT,), default='varnish', choices=('squid','varnish'), help=""" This option lets you select your cache utility. It will also generate a default configuration for the utility. """) #-------------------------------------- # Allows to choose a balancer utility #-------------------------------------- VAR_BALANCER_UTILITY = StringChoiceVar( 'balancer_utility', title='Balancer utility', description='Which balancer utility would you like? (HAProxy/Pound)?', page='Main', modes=(EXPERT,), default='haproxy', choices=('pound','haproxy'), help=""" This option lets you select your balancer utility. It will also generate a default configuration for the utility. """) #-------------------------------------- # Allows to choose a http utility #-------------------------------------- VAR_HTTP_UTILITY = StringChoiceVar( 'http_utility', title='Front http utility', description='Which front http utility would you like? (Apache/NGinx)?', page='Main', modes=(EXPERT,), default='apache', choices=('apache','nginx'), help=""" This option lets you select your front http utility. It will also generate a default configuration for the utility. """) VAR_MUNIN = BooleanVar( 'munin', title='Munin activation', description='Do you want munin stats for you instance', default='true', modes=(EXPERT), help=""" This option install and configure a Munin plugin for zope. It supposes that the current server has a munin node installed. """ ) VAR_DB_TYPE = StringChoiceVar( 'db_type', title='Database Connector', description='Which database connector we should use for RelStorage', page='Main', modes=(EXPERT,), default='postgresql', choices=('mysql', 'oracle', 'postgresql'), help=""" This option install the good python connector for RelStorage. """ ) VAR_DB_HOST = StringVar( 'db_host', title='Database Host', description="Database server address", page='Main', modes=(EXPERT,), default='127.0.0.1', help=""" This option should contain the ip address or the domain name of the database server """ ) VAR_DB_PORT = StringVar( 'db_port', title='Database Port', description="Database server port", page='Main', modes=(EXPERT,), default='5432', help=""" This option should contain the port of the database server """ ) VAR_DB_USERNAME = StringVar( 'db_username', title='Database Username', description="Database username", page='Main', modes=(EXPERT,), default='plone', help=""" """ ) VAR_DB_PASSWORD = StringVar( 'db_password', title='Database Password', description="Database password", page='Main', modes=(EXPERT,), default='azerty', help=""" """ ) VAR_APP_LDAP = BooleanVar( 'app_ldap', title='Install LDAP features', description='Do you want to connect a LDAP annuary?', default='false', modes=(EXPERT), help=""" This option install all needed LDAP products for Plone. It supposes that the current server has a python-ldap installed. """ ) VAR_APP_CAS = BooleanVar( 'app_cas', title='Install CAS features', description='Do you want to connect a CAS SSO?', default='false', modes=(EXPERT), help=""" This option install all needed CAS products for Plone. """ ) VAR_APP_METNAV = BooleanVar( 'app_metnav', title='Install Metnav products', description='Do you want to use Metnav features?', default='false', modes=(EXPERT), help=""" This option install all needed metnav products for Plone. """ ) VAR_APP_GETPAID = BooleanVar( 'app_getpaid', title='Install GetPaid products', description='Do you want to use GetPaid features?', default='false', modes=(EXPERT), help=""" This option install all needed to transform your Plone site in an e-commerce things. """ ) VAR_APP_THEMING = BooleanVar( 'app_theming', title='Install plone.app.theming products with Diazo', description='Do you want to use Diazo features?', default='true', modes=(EXPERT), help=""" This option install all needed have Diazo theming in your plone site. """ ) VAR_APP_DECO = BooleanVar( 'app_deco', title='Install plone.app.deco products', description='Do you want to use Deco features?', default='false', modes=(EXPERT), help=""" This option install all needed have Deco in your plone site. """ ) VAR_APP_IDE = BooleanVar( 'app_ide', title='Install plone IDE environmant', description='Do you want to use Plone IDE features?', default='false', modes=(EXPERT), help=""" This option install all needed to have plone IDE in the development mode. """ ) class UnisPlone4Buildout(AbstractBuildout): _template_dir = 'templates/unis_plone4_buildout' summary = "A buildout for Plone 4.x" help = """ This template creates a Plone 4 buildout based on the best practices of Quadra-Informatique """ pre_run_msg = """ Creating Zopeskel Plone 4.x instance """ post_run_msg = """ Generation finished. You probably want to run python bootstrap.py and then edit buildout.cfg before running bin/buildout -v DO NOT FORGET: IP Adresses and Ports are set by default. ------------- You HAVE to modify them in order to avoid conflict with existing instances. See README.txt for details. """ required_templates = [] use_cheetah = True port_vars = [ 'dev_instance', 'cache_locprep', 'cache_preprod', 'cache_prod', 'balancer_locprep', 'balancer_preprod', 'balancer_prod', 'zeoserv_locprep', 'zeoclient_locprep_1', 'zeoclient_locprep_2', 'zeoserv_preprod', 'zeoclient_preprod_1', 'zeoclient_preprod_2', 'zeoserv_prod', 'zeoclient_prod_1', 'zeoclient_prod_2', 'supervisor_locprep', 'supervisor_preprod', 'supervisor_prod',] VAR_PORTS_STARTING_VALUE.description += " (Generating %s ports )" % len(port_vars) vars = copy.deepcopy(AbstractBuildout.vars) vars.extend( [ VAR_CUSTOMER, VAR_DOMAIN, VAR_PLONESITE_PATH, VAR_PLONEVER, VAR_BUILDOUT_PROFILE, VAR_INSTANCE_TYPE, VAR_DB_TYPE, VAR_DB_HOST, VAR_DB_PORT, VAR_DB_USERNAME, VAR_DB_PASSWORD, VAR_INSTANCE_ENUM, VAR_SHARED_BLOBS, VAR_MEMCACHE, VAR_PORTS_STARTING_VALUE, VAR_BALANCER_UTILITY, VAR_CACHE_UTILITY, VAR_HTTP_UTILITY, VAR_MUNIN, VAR_APP_LDAP, VAR_APP_CAS, VAR_APP_METNAV, VAR_APP_GETPAID, VAR_APP_THEMING, VAR_APP_DECO, VAR_APP_IDE, ]) def run(self, command, output_dir, vars): ## /!\ output_dir = './'+vars['project'] ## vars['project'] can be a path if vars["customer"]: project_path = str(vars["project"]).lower().split(os.path.sep) project_path[-1] = '.'.join([str(vars["customer"]).lower(), project_path[-1]]) output_dir = (os.path.sep).join(project_path) self.pre(command, output_dir, vars) current_port = int(vars["ports_starting_value"]) for key in self.port_vars: vars[key] = current_port self.post_run_msg += '\n\t %s = %s\n' % (key, current_port) current_port += 1 self.write_files(command, output_dir, vars) self.post(command, output_dir, vars) def post(self, command, output_dir, vars): ## XXX We should cleanup unused modules super(UnisPlone4Buildout, self).post(command, output_dir, vars)
zopeskel.unis
/zopeskel.unis-1.14.zip/zopeskel.unis-1.14/zopeskel/unis/templates.py
templates.py
======================= Using a custom buildout ======================= Note: If you are using Windows, if you do not have PIL installed, or you are not using Python 2.4 as your main system Python, please see the relevant sections below. You probably got here by running something like: $ paster create -t plone3_buildout Now, you need to run: $ python bootstrap.py This will install zc.buildout for you. To create an instance immediately, run: $ bin/buildout This will download Plone's eggs and products for you, as well as other dependencies, create a new Zope 2 installation (unless you specified an existing one when you ran "paster create"), and create a new Zope instance configured with these products. You can start your Zope instance by running: $ bin/instance start or, to run in foreground mode: $ bin/instance fg To run unit tests, you can use: $ bin/instance test -s my.package Installing PIL -------------- To use Plone, you need PIL, the Python Imaging Library. If you don't already have this, download and install it from http://www.pythonware.com/products/pil. Using a different Python installation -------------------------------------- Buildout will use your system Python installation by default. However, Zope 2.10 (and by extension, Plone) will only work with Python 2.4. You can verify which version of Python you have, by running: $ python -V If that is not a 2.4 version, you need to install Python 2.4 from http://python.org. If you wish to keep another version as your main system Python, edit buildout.cfg and add an 'executable' option to the "[buildout]" section, pointing to a python interpreter binary: [buildout] ... executable = /path/to/python Working with buildout.cfg ------------------------- You can change any option in buildout.cfg and re-run bin/buildout to reflect the changes. This may delete things inside the 'parts' directory, but should keep your Data.fs and source files intact. To save time, you can run buildout in "offline" (-o) and non-updating (-N) mode, which will prevent it from downloading things and checking for new versions online: $ bin/buildout -Nov Creating new eggs ----------------- New packages you are working on (but which are not yet released as eggs and uploaded to the Python Package Index, aka PYPI) should be placed in src. You can do: $ cd src/ $ paster create -t plone my.package Use "paster create --list-templates" to see all available templates. Answer the questions and you will get a new egg. Then tell buildout about your egg by editing buildout.cfg and adding your source directory to 'develop': [buildout] ... develop = src/my.package You can list multiple packages here, separated by whitespace or indented newlines. You probably also want the Zope instance to know about the package. Add its package name to the list of eggs in the "[instance]" section, or under the main "[buildout]" section: [instance] ... eggs = ${buildout:eggs} ${plone:eggs} my.package Leave the ${buildout:eggs} part in place - it tells the instance to use the eggs that buildout will have downloaded from the Python Package Index previously. If you also require a ZCML slug for your package, buildout can create one automatically. Just add the package to the 'zcml' option: [instance] ... zcml = my.package When you are finished, re-run buildout. Offline, non-updating mode should suffice: $ bin/buildout -Nov Developing old-style products ----------------------------- If you are developing old-style Zope 2 products (not eggs) then you can do so by placing the product code in the top-level 'products' directory. This is analogous to the 'Products/' directory inside a normal Zope 2 instance and is scanned on start-up for new products. Depending on a new egg ---------------------- If you want to use a new egg that is in the Python Package Index, all you need to do is to add it to the "eggs" option under the main "[buildout]" section: [buildout] ... eggs = my.package If it's listed somewhere else than the Python Package Index, you can add a link telling buildout where to find it in the 'find-links' option: [buildout] ... find-links = http://dist.plone.org http://download.zope.org/distribution/ http://effbot.org/downloads http://some.host.com/packages Using existing old-style products --------------------------------- If you are using an old-style (non-egg) product, you can either add it as an automatically downloaded archive or put it in the top-level "products" folder. The former is probably better, because it means you can redistribute your buildout.cfg more easily: [productdistros] recipe = plone.recipe.distros urls = http://plone.org/products/someproduct/releases/1.3/someproduct-1.3.tar.gz If someproduct-1.3.tar.gz extracts into several products inside a top-level directory, e.g. SomeProduct-1.3/PartOne and SomeProduct-1.3/PartTwo, then add it as a "nested package": [productdistros] recipe = plone.recipe.distros urls = http://plone.org/products/someproduct/releases/1.3/someproduct-1.3.tar.gz nested-packages = someproduct-1.3.tar.gz Alternatively, if it extracts to a directory which contains the version number, add it as a "version suffix package": [productdistros] recipe = plone.recipe.distros urls = http://plone.org/products/someproduct/releases/1.3/someproduct-1.3.tar.gz version-suffix-packages = someproduct-1.3.tar.gz You can also track products by adding a new bundle checkout part. It doesn't strictly have to be an svn bundle at all, any svn location will do, and cvs is also supported: [buildout] ... parts = plone zope2 productdistros myproduct instance zopepy Note that "myproduct" comes before the "instance" part. You then need to add a new section to buildout.cfg: [myproduct] recipe = plone.recipe.bundlecheckout url = http://svn.plone.org/svn/collective/myproduct/trunk Finally, you need to tell Zope to find this new checkout and add it to its list of directories that are scanned for products: [instance] ... products = ${buildout:directory}/products ${productdistros:location} ${plonebundle:location} ${myproduct:location} Without this last step, the "myproduct" part is simply managing an svn checkout and could potentially be used for something else instead. ============= Using Windows ============= To use buildout on Windows, you will need to install a few dependencies which other platforms manage on their own. Here are the steps you need to follow (thanks to Hanno Schlichting for these): Python (http://python.org) -------------------------- - Download and install Python 2.4.4 using the Windows installer from http://www.python.org/ftp/python/2.4.4/python-2.4.4.msi Select 'Install for all users' and it will put Python into the "C:\Python24" folder by default. - You also want the pywin32 extensions available from http://downloads.sourceforge.net/pywin32/pywin32-210.win32-py2.4.exe?modtime=1159009237&big_mirror=0 - And as a last step you want to download the Python imaging library available from http://effbot.org/downloads/PIL-1.1.6.win32-py2.4.exe - If you develop Zope based applications you will usually only need Python 2.4 at the moment, so it's easiest to put the Python binary on the systems PATH, so you don't need to specify its location manually each time you call it. Thus, put "C:\Python24" and "C:\Python24\Scripts" onto the PATH. You can find the PATH definition in the control panel under system preferences on the advanced tab at the bottom. The button is called environment variables. You want to add it at the end of the already existing PATH in the system section. Paths are separated by a semicolons. - You can test if this was successful by opening a new shell (cmd) and type in 'python -V'. It should report version 2.4.4 (or whichever version you installed). Opening a new shell can be done quickly by using the key combination 'Windows-r' or if you are using Parallels on a Mac 'Apple-r'. Type in 'cmd' into the popup box that opens up and hit enter. Subversion (http://subversion.tigris.org) ----------------------------------------- - Download the nice installer from http://subversion.tigris.org/files/documents/15/35379/svn-1.4.2-setup.exe - Run the installer. It defaults to installing into "C:\Program Files\Subversion". - Now put the install locations bin subfolder (for example "C:\Program Files\Subversion\bin") on your system PATH in the same way you put Python on it. - Open a new shell again and type in: 'svn --version' it should report version 1.4.2 or newer. MinGW (http://www.mingw.org/) ----------------------------- This is a native port of the gcc compiler and its dependencies for Windows. There are other approaches enabling you to compile Python C extensions on Windows including Cygwin and using the official Microsoft C compiler, but this is a lightweight approach that uses only freely available tools. As it's used by a lot of people chances are high it will work for you and there's plenty of documentation out there to help you in troubleshooting problems. - Download the MinGW installer from http://downloads.sourceforge.net/mingw/MinGW-5.1.3.exe?modtime=1168794334&big_mirror=1 - The installer will ask you which options you would like to install. Choose base and make here. It will install into "C:\MinGW" by default. The install might take some time as it's getting files from sourceforge.net and you might need to hit 'retry' a couple of times. - Now put the install location's bin subfolder (for example "C:\MinGW\bin") on your system PATH in the same way you put Python on it. - Test this again by typing in: 'gcc --version' on a newly opened shell and it should report version 3.4.2 or newer. Configure Distutils to use MinGW -------------------------------- Some general information are available from http://www.mingw.org/MinGWiki/index.php/Python%20extensions for example but you don't need to read them all. - Create a file called 'distutils.cfg' in "C:\Python24\Lib\distutils". Open it with a text editor ('notepad distutils.cfg') and fill in the following lines: [build] compiler=mingw32 This will tell distutils to use MinGW as the default compiler, so you don't need to specify it manually using "--compiler=mingw32" while calling a package's setup.py with a command that involves building C extensions. This is extremely useful if the build command is written down in a buildout recipe where you cannot change the options without hacking the recipe itself. The z2c.recipe.zope2install used in ploneout is one such example.
zopeskel.unis
/zopeskel.unis-1.14.zip/zopeskel.unis-1.14/zopeskel/unis/templates/unis_plone4_buildout/README.txt
README.txt
import os, shutil, sys, tempfile, urllib, urllib2, subprocess from optparse import OptionParser if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: quote = str # See zc.buildout.easy_install._has_broken_dash_S for motivation and comments. stdout, stderr = subprocess.Popen( [sys.executable, '-Sc', 'try:\n' ' import ConfigParser\n' 'except ImportError:\n' ' print 1\n' 'else:\n' ' print 0\n'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() has_broken_dash_S = bool(int(stdout.strip())) # In order to be more robust in the face of system Pythons, we want to # run without site-packages loaded. This is somewhat tricky, in # particular because Python 2.6's distutils imports site, so starting # with the -S flag is not sufficient. However, we'll start with that: if not has_broken_dash_S and 'site' in sys.modules: # We will restart with python -S. args = sys.argv[:] args[0:0] = [sys.executable, '-S'] args = map(quote, args) os.execv(sys.executable, args) # Now we are running with -S. We'll get the clean sys.path, import site # because distutils will do it later, and then reset the path and clean # out any namespace packages from site-packages that might have been # loaded by .pth files. clean_path = sys.path[:] import site # imported because of its side effects sys.path[:] = clean_path for k, v in sys.modules.items(): if k in ('setuptools', 'pkg_resources') or ( hasattr(v, '__path__') and len(v.__path__) == 1 and not os.path.exists(os.path.join(v.__path__[0], '__init__.py'))): # This is a namespace package. Remove it. sys.modules.pop(k) is_jython = sys.platform.startswith('java') setuptools_source = 'http://peak.telecommunity.com/dist/ez_setup.py' distribute_source = 'http://python-distribute.org/distribute_setup.py' # parsing arguments def normalize_to_url(option, opt_str, value, parser): if value: if '://' not in value: # It doesn't smell like a URL. value = 'file://%s' % ( urllib.pathname2url( os.path.abspath(os.path.expanduser(value))),) if opt_str == '--download-base' and not value.endswith('/'): # Download base needs a trailing slash to make the world happy. value += '/' else: value = None name = opt_str[2:].replace('-', '_') setattr(parser.values, name, value) usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --setup-source and --download-base to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("-v", "--version", dest="version", help="use a specific zc.buildout version") parser.add_option("-d", "--distribute", action="store_true", dest="use_distribute", default=False, help="Use Distribute rather than Setuptools.") parser.add_option("--setup-source", action="callback", dest="setup_source", callback=normalize_to_url, nargs=1, type="string", help=("Specify a URL or file location for the setup file. " "If you use Setuptools, this will default to " + setuptools_source + "; if you use Distribute, this " "will default to " + distribute_source + ".")) parser.add_option("--download-base", action="callback", dest="download_base", callback=normalize_to_url, nargs=1, type="string", help=("Specify a URL or directory for downloading " "zc.buildout and either Setuptools or Distribute. " "Defaults to PyPI.")) parser.add_option("--eggs", help=("Specify a directory for storing eggs. Defaults to " "a temporary directory that is deleted when the " "bootstrap script completes.")) parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout's main function if options.config_file is not None: args += ['-c', options.config_file] if options.eggs: eggs_dir = os.path.abspath(os.path.expanduser(options.eggs)) else: eggs_dir = tempfile.mkdtemp() if options.setup_source is None: if options.use_distribute: options.setup_source = distribute_source else: options.setup_source = setuptools_source if options.accept_buildout_test_releases: args.append('buildout:accept-buildout-test-releases=true') args.append('bootstrap') try: import pkg_resources import setuptools # A flag. Sometimes pkg_resources is installed alone. if not hasattr(pkg_resources, '_distribute'): raise ImportError except ImportError: ez_code = urllib2.urlopen( options.setup_source).read().replace('\r\n', '\n') ez = {} exec ez_code in ez setup_args = dict(to_dir=eggs_dir, download_delay=0) if options.download_base: setup_args['download_base'] = options.download_base if options.use_distribute: setup_args['no_fake'] = True ez['use_setuptools'](**setup_args) if 'pkg_resources' in sys.modules: reload(sys.modules['pkg_resources']) import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) cmd = [quote(sys.executable), '-c', quote('from setuptools.command.easy_install import main; main()'), '-mqNxd', quote(eggs_dir)] if not has_broken_dash_S: cmd.insert(1, '-S') find_links = options.download_base if not find_links: find_links = os.environ.get('bootstrap-testing-find-links') if find_links: cmd.extend(['-f', quote(find_links)]) if options.use_distribute: setup_requirement = 'distribute' else: setup_requirement = 'setuptools' ws = pkg_resources.working_set setup_requirement_path = ws.find( pkg_resources.Requirement.parse(setup_requirement)).location env = dict( os.environ, PYTHONPATH=setup_requirement_path) requirement = 'zc.buildout' version = options.version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setup_requirement_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) if is_jython: import subprocess exitcode = subprocess.Popen(cmd, env=env).wait() else: # Windows prefers this, apparently; otherwise we would prefer subprocess exitcode = os.spawnle(*([os.P_WAIT, sys.executable] + cmd + [env])) if exitcode != 0: sys.stdout.flush() sys.stderr.flush() print ("An error occurred when trying to install zc.buildout. " "Look above this message for any errors that " "were output by easy_install.") sys.exit(exitcode) ws.add_entry(eggs_dir) ws.require(requirement) import zc.buildout.buildout zc.buildout.buildout.main(args) if not options.eggs: # clean up temporary egg directory shutil.rmtree(eggs_dir)
zopeskel.unis
/zopeskel.unis-1.14.zip/zopeskel.unis-1.14/zopeskel/unis/templates/unis_plone4_buildout/bootstrap.py
bootstrap.py
======================================================== Installation of a Plone 4 architecture on Debian Squeeze ======================================================== :Info: See <https://github.com/collective/zopeskel.unis> for more informations :Author: Encolpe DEGOUTE <[email protected]> :Description: This is a "docinfo block", or bibliographic field list Introduction ============ This installation is specific to Debian Squeeze 64bits. For this documentation the hostname is `debian` and the network domain is `localdomain`. This is a scalable architecture: a lot of software installed are not describe in the basic plone installation. How is it scalable? If you need to support more reader connections you can add more zope instances connected to the postgresql cluster; If you need to support more writing users you can add more postgresql servers in your cluster. If you have a simple site a configuration with one postgresql server and two zope instances should be enough. You should plan half a day for the server installation with the Python 2.6. OS Installation =============== First steps ----------- The installation starts from the last netinst CDROM boot. * We choose the graphical installation with our locale language * The network is acquired by the DHCP method * For the disk partition choose `Assisted with LVM` then `All in a single partition`. This should avoid problem with too little `/tmp` partition in the future. * Apply this modification and go to the next step. * Create a simple root password to take care of a possible bug in the keyboard configuration. * Create le 'Local admin' user. * In the task selection choose : web server, SQL databases and simple installation. It will take times to download and install packages at this step. * Install Grub * Reboot OS Configuration ---------------- All the following commands need to be logged as root or with sudo. Debian Backports ~~~~~~~~~~~~~~~~ Add a file called **/etc/apt/sources.list.d/squeeze-backports.list** with the following line: .. code-block:: bash deb http://backports.debian.org/debian-backports squeeze-backports main Create a **/etc/apt/preferences** file with these three lines: .. code-block:: bash Package: * Pin: release a=squeeze-backports Pin-Priority: 999 Then: .. code-block:: bash apt-get update apt-get dselect-upgrade This last command should propose you to update PostgreSQL that is the targeted goal. See `Debian Backports site`_ for more information. .. _`Debian Backports site`: http://backports.debian.org/Instructions Architecture requirement ~~~~~~~~~~~~~~~~~~~~~~~~ We will have to build zc.buildout and Python. With python we have three modules needed everywhere: python-imaging, python-ldap and python libxml2 binding. .. code-block:: bash sudo apt-get build-deps python sudo apt-get install build-essential libsqlite3-dev \ python-dev python-setuptools \ python-imaging python-lxml python-ldap \ python-celementree python-cjson \ libssl-dev libsasl2-dev libldap2-dev \ libgif-dev libjpeg62-dev libpng12-dev libfreetype6-dev \ libxml2-dev libxslt1-dev *Memcached* is a ramcache helper for distributed application. We use it between zope instances to reduce session overheads. .. code-block:: bash sudo apt-get install memcached libmemcache-dev We choose *PostgreSQL 8.4* to simplify the migration on Debian Sqeeze. .. code-block:: bash sudo apt-get install python-psycopg2 postgresql-8.4 \ postgresql-contrib-8.4 postgresql-8.4-slony1 \ postgresql-server-dev-8.4 pidentd Munin is installed by default on eash node .. code-block:: bash sudo apt-get install munin munin-node For Varnish cache server .. code-block:: bash sudo apt-get install pkg-config libpcre3-dev Plone requirements ~~~~~~~~~~~~~~~~~~ Unless python modules these requirements are there for specific needs: document conversion to html (preview) and to text (indexing). .. code-block:: bash sudo apt-get install lynx tidy xsltproc xpdf wv Developper tools ~~~~~~~~~~~~~~~~ .. code-block:: bash sudo apt-get install vim-python git mercurial subversion graphviz Python Sandbox Installation --------------------------- This step can be optionnal if you only want to use the python installed by the system or if you install your own python version. We recommend to build system independant version of Python for Plone hosting to not be impacted if a system upgrade turn into a nightmare. Zope 2.12 used by Plone dropped the Python 2.5 support to concentrate all effort on Python 2.6. Debian Squeeze contains this version. On the other hand Zope 2.10 only runs with Python 2.4 that is only present in Debian Lenny. Debian doesn't propose Python 2.4 and Python 2.6 on the same version. The Plone Community has a buildout to build all python versions for Plone with some dependencies. Python installation ~~~~~~~~~~~~~~~~~~~ At this step you can choose to compile python in user space or in superuser space. This buildout expect setuptools is installed at least at 0.6.11 version. .. code-block:: bash sudo adduser --home /opt/python-envs --disabled-password plone sudo easy_install -U setuptools sudo easy_install zc.buildout==1.4.4 sudo mkdir /opt/python /opt/python-envs sudo chown plone:plone /opt/python /opt/python-envs sudo -H -u plone -s svn checkout http://svn.plone.org/svn/collective/buildout/python cd python python bootstrap.py bin/buildout We will need to have a virtualenv installed in there to be able to duplicate Python2.6 installation quickly. .. code-block:: bash cd /opt/python/python-2.6 source bin/activate easy_install virtualenv Finalization ------------ As Zope, varnish and HAproxy don't need superuser rights we must create an user to install the application in the userspace. You should call it `zope` or `plone`. The next step is to install zopeskel.unis to deploy your project. If you want to be able to store ZODB in a PostgreSQL database you should create an user in your postgres database .. code-block:: bash sudo -u postgres createuser -e -d -i -l -P -R -S plone
zopeskel.unis
/zopeskel.unis-1.14.zip/zopeskel.unis-1.14/docs/installation-os-debian-6.0-squeeze.rst
installation-os-debian-6.0-squeeze.rst
====================================================== Installation of a Plone 4 architecture on Debian Lenny ====================================================== :Info: See <https://github.com/collective/zopeskel.unis> for more informations :Author: Encolpe DEGOUTE <[email protected]> :Description: This is a "docinfo block", or bibliographic field list Introduction ============ This installation is specific to Debian Lenny 64bits. For this documentation the hostname is `debian` and the network domain is `localdomain`. This is a scalable architecture: a lot of software installed are not describe in the basic plone installation. How is it scalable? If you need to support more reader connections you can add more zope instances connected to the postgresql cluster; If you need to support more writing users you can add more postgresql servers in your cluster. If you have a simple site a configuration with one postgresql server and two zope instances should be enough. You should plan half a day for the server installation with the Python 2.6. OS Installation =============== First steps ----------- The installation starts from the last netinst CDROM boot. * We choose the graphical installation with our locale language * The network is acquired by the DHCP method * For the disk partition choose `Assisted with LVM` then `All in a single partition`. This should avoid problem with too little `/tmp` partition in the future. * Apply this modification and go to the next step. * Create a simple root password to take care of a possible bug in the keyboard configuration. * Create le 'Local admin' user. * In the task selection choose : web server, SQL databases and simple installation. It will take times to download and install packages at this step. * Install Grub * Reboot OS Configuration ---------------- All the following commands need to be logged as root or with sudo. Debian Backports ~~~~~~~~~~~~~~~~ Add backports to your sources.list * Add this line to your *sources.list* (or add a new file to /etc/apt/sources.list.d/):: deb http://backports.debian.org/debian-backports lenny-backports main * Create a */etc/apt/preferences* file with these three lines:: Package: * Pin: release a=lenny-backports Pin-Priority: 999 * Run apt-get update * Run apt-get upgrade This last command should propose you to update PostgreSQL that is the targeted goal. See `Debian Backports site`_ for more information. .. _`Debian Backports site`: http://backports.debian.org/Instructions Architecture requirement ~~~~~~~~~~~~~~~~~~~~~~~~ We will have to build zc.buildout and Python. With python we have three modules needed everywhere: python-imaging, python-ldap and python libxml2 binding. * build-essential * python-dev * python-setuptools * python-imaging * python-lxml * python-ldap * python-celementree * python-cjson * libssl-dev * libsasl2-dev * libldap2-dev * libgif-dev * libjpeg62-dev * libpng12-dev * libfreetype6-dev * libxml2-dev * libxslt1-dev *Memcached* is a ramcache helper for distributed application. We use it between zope instances to reduce session overheads. * memcached * libmemcache-dev We choose *PostgreSQL 8.4* to simplify the migration on Debian Sqeeze. * python-psycopg2 * postgresql-8.4 * postgresql-contrib-8.4 * postgresql-8.4-slony1 * postgresql-server-dev-8.4 * pidentd Munin is installed by default on eash node * munin * munin-node Plone requirements ~~~~~~~~~~~~~~~~~~ Unless python modules these requirements are there for specific needs: document conversion to html (preview) and to text (indexing). * lynx * tidy * xsltproc * xpdf * wv Developper tools ~~~~~~~~~~~~~~~~ * vim-python * git * mercurial * subversion * graphviz Python Sandbox Installation --------------------------- This step can be optionnal if you only want to use the python installed by the system or if you install your own python version. We recommend to build system independant version of Python for Plone hosting to not be impacted if a system upgrade turn into a nightmare. Zope 2.12 used by Plone dropped the Python 2.5 support to concentrate all effort on Python 2.6. Debian Squeeze contains this version. On the other hand Zope 2.10 only runs with Python 2.4 that is only present in Debian Lenny. Debian doesn't propose Python 2.4 and Python 2.6 on the same version. The Plone Community has a buildout to build all python versions for Plone with some dependencies. Python installation ~~~~~~~~~~~~~~~~~~~ At this step you can choose to compile python in user space or in superuser space. This buildout expect setuptools is installed at least at 0.6.11 version. :: sudo adduser --no-create-home --home /opt --disabled-password plone sudo easy_install -U setuptools sudo easy_install zc.buildout==1.4.4 sudo mkdir /opt/python /opt/python-envs sudo chown plone:plone /opt/python /opt/python-envs sudo -H -u plone -s svn checkout http://svn.plone.org/svn/collective/buildout/python cd python python bootstrap.py bin/buildout We will need to have a virtualenv installed in there to be able to duplicate Python2.6 installation quickly. :: cd /opt/python/python-2.6 source bin/activate easy_install virtualenv Finalization ------------ As Zope, varnish and HAproxy don't need superuser rights we must create an user to install the application in the userspace. You should call it `zope` or `plone`. The next step is to install zopeskel.unis to deploy your project. If you want to be able to store ZODB in a PostgreSQL database you should create an user in your postgres database :: sudo -u postgres createuser -e -d -i -l -P -R -S plone
zopeskel.unis
/zopeskel.unis-1.14.zip/zopeskel.unis-1.14/docs/installation-os-debian-5.0-lenny.rst
installation-os-debian-5.0-lenny.rst
|Travis Build Status| |Appveyor Build Status| PYZOPFLI ======== cPython bindings for `zopfli <http://googledevelopers.blogspot.com/2013/02/compress-data-more-densely-with-zopfli.html>`__. USAGE ===== pyzopfli is a straight forward wrapper around zopfli's ZlibCompress method. :: from zopfli.zlib import compress from zlib import decompress s = 'Hello World' print decompress(compress(s)) pyzopfli also wrapps GzipCompress, but the API point does not try to mimic the gzip module. :: from zopfli.gzip import compress from StringIO import StringIO from gzip import GzipFile print GzipFile(fileobj=StringIO(compress("Hello World!"))).read() Both zopfli.zlib.compress and zopfli.gzip.compress support the following keyword arguements. All values should be integers; boolean parmaters are treated as expected, 0 and >0 as false and true. - *verbose* dumps zopfli debugging data to stderr - *numiterations* Maximum amount of times to rerun forward and backward pass to optimize LZ77 compression cost. Good values: 10, 15 for small files, 5 for files over several MB in size or it will be too slow. - *blocksplitting* If true, splits the data in multiple deflate blocks with optimal choice for the block boundaries. Block splitting gives better compression. Default: true (1). - *blocksplittinglast* If true, chooses the optimal block split points only after doing the iterative LZ77 compression. If false, chooses the block split points first, then does iterative LZ77 on each individual block. Depending on the file, either first or last gives the best compression. Default: false (0). - *blocksplittingmax* Maximum amount of blocks to split into (0 for unlimited, but this can give extreme results that hurt compression on some files). Default value: 15. TODO ==== - Stop reading the entire file into memory and support streaming - Monkey patch zlib and gzip so code with an overly tight binding can be easily modified to use zopfli. .. |Travis Build Status| image:: https://travis-ci.org/obp/py-zopfli.svg :target: https://travis-ci.org/obp/py-zopfli .. |Appveyor Build Status| image:: https://ci.appveyor.com/api/projects/status/w81mvlbci9dsow5d/branch/master?svg=true :target: https://ci.appveyor.com/project/anthrotype/zopfli/branch/master
zopfli
/zopfli-0.1.3-cp27-cp27m-manylinux1_x86_64.whl/zopfli-0.1.3.dist-info/DESCRIPTION.rst
DESCRIPTION.rst
import codecs import os import struct import sys import threading from typing import cast, Any, AnyStr, IO, Optional, Tuple, Union if sys.version_info >= (3, 8): from typing import Literal else: from typing_extensions import Literal import zipfile import zlib from ._zopfli import (ZOPFLI_FORMAT_GZIP, ZOPFLI_FORMAT_ZLIB, ZOPFLI_FORMAT_DEFLATE, ZopfliCompressor, ZopfliDeflater, ZopfliPNG) __all__ = ['ZOPFLI_FORMAT_GZIP', 'ZOPFLI_FORMAT_ZLIB', 'ZOPFLI_FORMAT_DEFLATE', 'ZopfliCompressor', 'ZopfliDeflater', 'ZopfliDecompressor', 'ZopfliPNG', 'ZipFile', 'ZipInfo'] __author__ = 'Akinori Hattori <[email protected]>' try: from .__version__ import version as __version__ except ImportError: __version__ = 'unknown' if sys.version_info >= (3, 9): P = Union[str, os.PathLike[str]] else: P = Union[str, os.PathLike] class ZopfliDecompressor: def __init__(self, format: int = ZOPFLI_FORMAT_DEFLATE) -> None: if format == ZOPFLI_FORMAT_GZIP: wbits = zlib.MAX_WBITS + 16 elif format == ZOPFLI_FORMAT_ZLIB: wbits = zlib.MAX_WBITS elif format == ZOPFLI_FORMAT_DEFLATE: wbits = -zlib.MAX_WBITS else: raise ValueError('unknown format') self.__z = zlib.decompressobj(wbits) @property def unused_data(self) -> bytes: return self.__z.unused_data @property def unconsumed_tail(self) -> bytes: return self.__z.unconsumed_tail @property def eof(self) -> bool: return self.__z.eof def decompress(self, data: bytes, max_length: int = 0) -> bytes: return self.__z.decompress(data, max_length) def flush(self, length: int = zlib.DEF_BUF_SIZE) -> bytes: return self.__z.flush(length) class ZipFile(zipfile.ZipFile): fp: IO[bytes] compression: int _lock: threading.RLock def __init__(self, file: Union[P, IO[bytes]], mode: Literal['r', 'w', 'x', 'a'] = 'r', compression: int = zipfile.ZIP_DEFLATED, allowZip64: bool = True, compresslevel: Optional[int] = None, *, strict_timestamps: bool = True, encoding: str = 'cp437', **kwargs: Any) -> None: self.encoding = encoding self._options = kwargs super().__init__(file, mode, compression, allowZip64, compresslevel) if sys.version_info >= (3, 8): self._strict_timestamps = strict_timestamps def _RealGetContents(self) -> None: super()._RealGetContents() for i, zi in enumerate(self.filelist): self.filelist[i] = zi = self._convert(zi) if not zi.flag_bits & 0x800: n = zi.orig_filename.encode('cp437').decode(self.encoding) if os.sep != '/': n = n.replace(os.sep, '/') del self.NameToInfo[zi.filename] zi.filename = n self.NameToInfo[zi.filename] = zi def open(self, name: Union[str, zipfile.ZipInfo], mode: Literal['r', 'w'] = 'r', pwd: Optional[bytes] = None, *, force_zip64: bool = False, **kwargs: Any) -> IO[bytes]: fp = super().open(name, mode, pwd, force_zip64=force_zip64) if (mode == 'w' and self._zopflify(None) and fp._compressor): opts = self._options.copy() opts.update(kwargs) fp._compressor = ZopfliCompressor(ZOPFLI_FORMAT_DEFLATE, **opts) return fp def _open_to_write(self, zinfo: zipfile.ZipInfo, force_zip64: bool = False) -> IO[bytes]: return cast(IO[bytes], super()._open_to_write(self._convert(zinfo), force_zip64)) def write(self, filename: P, arcname: Optional[P] = None, compress_type: Optional[int] = None, compresslevel: Optional[int] = None, **kwargs: Any) -> None: zopflify = self._zopflify(compress_type) z: Optional[ZopfliCompressor] = None if zopflify: compress_type = zipfile.ZIP_STORED opts = self._options.copy() opts.update(kwargs) z = ZopfliCompressor(ZOPFLI_FORMAT_DEFLATE, **opts) with self._lock: fp = self.fp try: self.fp = self._file(z) super().write(filename, arcname, compress_type, compresslevel) zi = self._convert(self.filelist[-1]) if zopflify: zi.compress_size = self.fp.size if not zi.is_dir(): zi.compress_type = zipfile.ZIP_DEFLATED finally: self.fp = fp if zopflify: self.fp.seek(zi.header_offset) self.fp.write(zi.FileHeader(self._zip64(zi))) self.fp.seek(self.start_dir) self.filelist[-1] = zi self.NameToInfo[zi.filename] = zi def writestr(self, zinfo_or_arcname: Union[str, zipfile.ZipInfo], data: AnyStr, compress_type: Optional[int] = None, compresslevel: Optional[int] = None, **kwargs: Any) -> None: if isinstance(zinfo_or_arcname, zipfile.ZipInfo): compress_type = zinfo_or_arcname.compress_type if isinstance(zinfo_or_arcname, ZipInfo): zinfo_or_arcname.encoding = self.encoding zopflify = self._zopflify(compress_type) z: Optional[ZopfliCompressor] = None if zopflify: compress_type = zipfile.ZIP_STORED opts = self._options.copy() opts.update(kwargs) z = ZopfliCompressor(ZOPFLI_FORMAT_DEFLATE, **opts) with self._lock: fp = self.fp try: self.fp = self._file(z) super().writestr(zinfo_or_arcname, data, compress_type, compresslevel) zi = self._convert(self.filelist[-1]) if zopflify: zi.compress_type = zipfile.ZIP_DEFLATED zi.compress_size = self.fp.size finally: self.fp = fp if zopflify: self.fp.seek(zi.header_offset) self.fp.write(zi.FileHeader(self._zip64(zi))) self.fp.seek(self.start_dir) self.filelist[-1] = zi self.NameToInfo[zi.filename] = zi if sys.version_info >= (3, 11): def mkdir(self, zinfo_or_directory: Union[str, zipfile.ZipInfo], mode: int = 511) -> None: with self._lock: fp = self.fp try: self.fp = self._file(None) super().mkdir(zinfo_or_directory, mode) zi = self._convert(self.filelist[-1]) finally: self.fp = fp self.filelist[-1] = zi self.NameToInfo[zi.filename] = zi def _convert(self, src: zipfile.ZipInfo) -> 'ZipInfo': if isinstance(src, ZipInfo): dst = src else: dst = ZipInfo() for n in src.__slots__: try: setattr(dst, n, getattr(src, n)) except AttributeError: pass dst.encoding = self.encoding return dst def _file(self, z: Optional[ZopfliCompressor]) -> IO[bytes]: LFH = '<4s5H3L2H' EFS = 1 << 11 class ZopfliFile: def __init__(self, zf: ZipFile, z: Optional[ZopfliCompressor]) -> None: self.size = 0 self._zf = zf self._fp = zf.fp self._pos = zf.start_dir self._z = z self._fh = 0 def __getattr__(self, name: str) -> Any: return getattr(self._fp, name) def seek(self, offset: int, whence: int = os.SEEK_SET) -> int: if (offset == self._pos and whence == os.SEEK_SET): self._fh = -self._fh + 1 if (self._fh > 1 and self._z): data = self._z.flush() self.size += len(data) self._fp.write(data) self._z = None self._zf.start_dir = self._fp.tell() return self._fp.seek(offset, whence) def write(self, data: bytes) -> None: if self._fh > 0: self._fp.write(self._rewrite(data)) self._fh = -self._fh else: if self._z: data = self._z.compress(data) self.size += len(data) self._fp.write(data) def _rewrite(self, fh: bytes) -> bytes: sig, ver, flag, meth, lmt, lmd, crc, csize, fsize, n, m = struct.unpack(LFH, fh[:30]) if flag & EFS: try: name = fh[30:30+n].decode('utf-8').encode(self._zf.encoding) if name != fh[30:30+n]: return struct.pack(LFH, sig, ver, flag & ~EFS, meth, lmt, lmd, crc, csize, fsize, len(name), m) + name + fh[30+n:] except UnicodeEncodeError: pass return fh return cast(IO[bytes], ZopfliFile(self, z)) def _zip64(self, zi: zipfile.ZipInfo) -> bool: return (zi.file_size > zipfile.ZIP64_LIMIT or zi.compress_size > zipfile.ZIP64_LIMIT) def _zopflify(self, compression: Optional[int]) -> bool: return (compression == zipfile.ZIP_DEFLATED or (compression is None and self.compression == zipfile.ZIP_DEFLATED)) class ZipInfo(zipfile.ZipInfo): __slots__ = ('encoding',) encoding: Optional[str] orig_filename: str def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self.encoding = None def _encodeFilenameFlags(self) -> Tuple[bytes, int]: if isinstance(self.filename, bytes): return self.filename, self.flag_bits encoding = codecs.lookup(self.encoding).name if self.encoding else 'ascii' if encoding != 'utf-8': try: return self.filename.encode(encoding), self.flag_bits except UnicodeEncodeError: pass return self.filename.encode('utf-8'), self.flag_bits | 0x800
zopflipy
/zopflipy-1.8-cp37-cp37m-macosx_10_9_x86_64.whl/zopfli/__init__.py
__init__.py
Zopkio - A Functional and Performance Test Framework for Distributed Systems ============================================================================ .. image:: https://travis-ci.org/linkedin/Zopkio.svg?branch=master :target: https://travis-ci.org/linkedin/Zopkio .. image:: https://coveralls.io/repos/linkedin/Zopkio/badge.svg?branch=master&service=github :target: https://coveralls.io/github/linkedin/Zopkio?branch=master Zopkio is a test framework built to support at scale performance and functional testing. Installation ------------ Zopkio is distributed via pip To install:: (sudo) pip install zopkio If you want to work with the latest code:: git clone [email protected]:linkedin/zopkio.git cd zopkio Once you have downloaded the code you can run the zopkio unit tests:: python setup.py test Or you can install zopkio and run the sample test:: (sudo) python setup.py install zopkio examples/server_client/server_client.py N.B the example code assumes you can ssh into your own box using your ssh keys so if your are having issues with the tests failing check your authorized_keys. In the past there have been issues installing one of our dependencies (Naarad) if you encounter errors installing naarad see https://github.com/linkedin/naarad/wiki/Installation Basic usage ----------- Use the zopkio main script:: zopkio testfile Zopkio takes several optional arguments:: --test-only [TEST_LIST [TEST_LIST ...]] run only the named tests to help debug broken tests --machine-list [MACHINE_LIST [MACHINE_LIST ...]] mapping of logical host names to physical names allowing the same test suite to run on different hardware, each argument is a pair of logical name and physical name separated by a = --config-overrides [CONFIG_OVERRIDES [CONFIG_OVERRIDES ...]] config overrides at execution time, each argument is a config with its value separated by a =. This has the highest priority of all configs -d OUTPUT_DIR, --output-dir OUTPUT_DIR Specify the output directory for logs and test results. By default, Zopkio will write to the current directory. --log-level LOG_LEVEL Log level (default INFO) --console-log-level CONSOLE_LEVEL Console Log level (default ERROR) --nopassword Disable password prompt --user USER user to run the test as (defaults to current user) Testing with Zopkio ------------------- Zopkio provides the ability to write tests that combine performance and functional testing across a distributed service or services. Writing tests using Zopkio should be nearly as simple as writing tests in xUnit or Nose etc. A test suite will consist of a single file specifying four required pieces: #. A deployment file #. One or more test files #. A dynamic configuration file #. A config directory For simplicity in the first iteratation this is assumed to be json or a python file with a dictionary called *test*. Deployment ~~~~~~~~~~ The deployment file should be pointed to by an entry in the dictionary called *deployment_code*. Deplyoment is one of the key features of Zopkio. Developers can write test in which they bring up arbtrary sets of services on multiple machines and then within the tests exercise a considerable degree of control over these machines. The deployment section of code will be similar to deployment in other test frameworks but because of the increased complexity and the expectation of reuse across multiple test suites, it can be broken into its own file. A deployment file can contain four functions: #. ``setup_suite`` #. ``setup`` #. ``teardown`` #. ``teardown_suite`` As in other test frameworks, ``setup_suite`` will run before any of tests, ``setup`` will run before each test, ``teardown`` will run if ``setup`` ran successfully regardless of the test status, and ``teardown_suite`` will run if ``setup_suite`` ran successfully regardless of any other conditions. The main distinction in the case of this framework will be in the extended libraries to support deployment. In many cases the main task of the deployment code is creating a Deployer. This can be done using the SSHDeployer provided by the framework or through custom code. For more information about deployers see the APIs. The ``runtime`` module provides a helpful ``set_deployer(service_name)`` and ``get_deployer(service_name)``. In addition to allowing the deployers to be easily shared across functions and modules, using these functions will allow the framework to automatically handle certain tasks such as copying logs from the remote hosts. Once the deployer is created it can be used in both the setup and teardown functions to start and stop the services. Since the ``setup`` and ``teardown`` functions run before and after each test a typical use is to restore the state of the system between tests to prevent tests from leaking bugs into other tests. If the ``setup`` or ``teardown`` fails we will skip the test and mark it as a failure. In an effort to avoid wasting time with a corrupted stack there is a configuration ``max_failures_per_suite_before_abort`` which can be set to determine how many times the frameworke will skip tests before autmatically skipping the remaining tests in that suite. In addition the entire suite is rerun parameterized by the configurations (See configs_) there is a second config ``max_suite_failures_before_abort`` which behaves similarly. Test Files ~~~~~~~~~~ Test files are specified by an entry in the test dictionary called *test_code*, which should point to a list of test files. For each test file, the framework will execute any function with *test* in the name (no matter the case) and track if the function executes successfully. In addition if there is a function ``test_foo`` and a function ``validate_foo``, after all cleanup and log collection is done, if ``test_foo`` executed successfully then ``validate_foo`` will be executed and tested for successful execution if it fails, the original test will fail and the logs from the post execution will be displayed. Test can be run in either a parallel mode or a serial mode. By default tests are run serially without any specified order. However each test file may specify an attribute *test_phase*. A test_phase of -1 is equivalent to serial testing. Otherwise all tests with the same test_phase will be run in parallel together. Phases proceed in ascending order. Dynamic Configuration File ~~~~~~~~~~~~~~~~~~~~~~~~~~ The dynamic configuration component may be specified as either *dynamic_configuration_code* or *perf_code*. This module contains a number of configurations that can be used during the running of the tests to provide inputs for the test runner. The required elements are a function to return Naarad configs, and functions to return the locations of the logs to fetch from the remote hosts. There are also several configs which can be placed either in this module as attributes or in the Master config file. The main focus of this module is support for Naarad. The output of the load generation can be any format supported by Naarad including JMeter and CSV. The performacnce file can also contain rules for Naarad to use to pass/fail the general performance of a run (beyond rules specific to individual tests). To get the most from Naarad, a Naarad config file can be provided (see https://github.com/linkedin/naarad/blob/master/README.md section Usage). In order to have Naarad support the module should provide a function ``naarad_config()``. There are also two functons ``machine_logs()`` and ``naarad_logs()`` that should return dictionaries from ``unique_ids`` to the list of logs to collect. Machine logs are the set of logs that should not be processed by naarad. .. _configs: Configs ------- Being able to test with different configurations is extremely important. The framework distinguishes between three types of configs: #. master config #. test configs #. application configs Master configs are properties which affect the way zopkio operates. Current properties that are supported include: * ``max_suite_failures_before_abort`` * ``max_failures_per_suite_before_abort`` * ``LOGS_DIRECTORY`` * ``OUTPUT_DIRECTORY`` Test configs are properties which affect how the tests are run. They are specific to the tests test writer and accessible from ``runtime.get_config(config_name)`` which will return the stored value or the empty string if no property with that name is present. These are the properties that can be overrode by the ``config-overrides`` command line flag. some of the test configs that zopkio recognizes are: * ``loop_all_tests`` * ``show_all_iterations`` * ``verify_after_each_test`` 'loop_all_tests' repeats the entire test suite for that config for the specified number of times 'show_all_iterations' shows the result in test page for each iteration of the test. 'verify_after_each_test' forces the validation before moving onto the next test Application configs are properties which affect how the remote services are configured. There is not currently an official way to copy these configs to remote hosts separately from the code, although there are several utilities to support it . In order to allow the same tests to run over multiple configurations, the framework interprets configs accoriding to the following rules. All configs are grouped under a single folder. If this folder contains at least one subfolder, then the config files at the top level are considered defaults and for each subfolder of the top folder, the entire test suite will be run using the configs within that folder (plus the defaults and config overrides). This is the case in which ``max_suite_failures_before_abort`` will be considered. Otherwise the suite will be run once with the top level config files and overrides. Example Tests ------------- 1) command : zopkio examples/server_client/server_client.py - Runs bunch of tests with multiple clients and servers deployed 2) command : zopkio examples/server_client/single_server_multipleiter_inorder.py --nopassword - The individual tests have the TEST_PHASE set to be 1,2,3 respectively. This enforces order. - To run multiple iterations set loop_all_tests to be <value> in config.json file - To validate each run of the test before moving to next one set verify_after_each_test in configs - To show the pass/fail for each iteration set show_all_iterations to be true in configs - sample settings to get mulitple runs for this test #. "show_all_iterations":true, #. "verify_after_each_test":true, #. "loop_all_tests":2, 3) command : zopkio examples/server_client/server_client_multiple_iteration.py - The base_tests_multiple_iteration.py module has TEST_ITER parameter set to 2. - This repeats all the tests twice but does not enfore any ordering 4) command : zopkio examples/server_client/client_resilience.py - This is an example of the test recipe feature of zopkio. See test_recipes.py for recipe and test_resilience.py for example used here - This tests the kill_recovery recipe to which you pass the deployer, process list, optional restart func, recovery func and timeout - Zopkio will kill a random process of the deployer and verifies if the system can recover correctly based on recovery function before the timeout value
zopkio
/zopkio-0.2.5.tar.gz/zopkio-0.2.5/README.rst
README.rst
import os from os.path import dirname from zerotk.zops import Console import click click.disable_unicode_literals_warning = True @click.group("anatomy") def main(): pass @main.command() @click.argument("directories", nargs=-1) @click.option("--features-file", default=None, envvar="ZOPS_ANATOMY_FEATURES") @click.option("--templates-dir", default=None, envvar="ZOPS_ANATOMY_TEMPLATES") @click.option("--playbook-file", default=None) @click.option("--recursive", "-r", is_flag=True) @click.pass_context def apply(ctx, directories, features_file, templates_dir, playbook_file, recursive): """ Apply templates. """ from .layers.playbook import AnatomyPlaybook from zerotk.lib.path import find_up for i_directory in directories: project_name = os.path.basename(os.path.abspath(i_directory)) project_playbook_filename = f"anatomy-features/playbooks/{project_name}.yml" project_playbook_filename = find_up(project_playbook_filename, i_directory) if playbook_file is not None: playbook_filenames = [playbook_file] elif os.path.exists(project_playbook_filename): playbook_filenames = [project_playbook_filename] elif recursive: directory = os.path.abspath(i_directory) playbook_filenames = find_all("anatomy-playbook.yml", directory) playbook_filenames = GitIgnored().filter(playbook_filenames) else: playbook_filenames = [i_directory + "/anatomy-playbook.yml"] for i_filename in playbook_filenames: features_file = features_file or _find_features_file(dirname(i_filename)) templates_dir = templates_dir or os.path.join( os.path.dirname(features_file), "templates" ) Console.info(f"Apply {i_filename}") _register_features(features_file, templates_dir) Console.title(i_directory) anatomy_playbook = AnatomyPlaybook.from_file(i_filename) anatomy_playbook.apply(i_directory) def _find_features_file(path): from zerotk.lib.path import find_up SEARCH_FILENAMES = [ "anatomy-features/anatomy-features.yml", "anatomy-features.yml", ] for i_filename in SEARCH_FILENAMES: result = find_up(i_filename, path) if result is not None: break if result is None: Console.error("Can't find features file: anatomy-features.yml.") raise SystemError(1) Console.info("Features filename:", result) return result def _register_features(filename, templates_dir): from .layers.feature import AnatomyFeatureRegistry AnatomyFeatureRegistry.clear() AnatomyFeatureRegistry.register_from_file(filename, templates_dir)
zops.anatomy
/zops.anatomy-3.8.0.tar.gz/zops.anatomy-3.8.0/zops/anatomy/cli.py
cli.py
import os from zerotk.lib.text import dedent from collections import OrderedDict, MutableMapping import distutils.util class UndefinedVariableInTemplate(KeyError): pass class TemplateEngine(object): """ Provide an easy and centralized way to change how we expand templates. """ __singleton = None @classmethod def get(cls): if cls.__singleton is None: cls.__singleton = cls() return cls.__singleton def expand(self, text, variables, alt_expansion=False): from jinja2 import Environment, Template, StrictUndefined if alt_expansion: kwargs = dict( block_start_string="{{%", block_end_string="%}}", variable_start_string="{{{", variable_end_string="}}}", ) else: kwargs = {} env = Environment( trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=True, undefined=StrictUndefined, **kwargs ) def is_empty(text_): return not bool(expandit(text_).strip()) env.tests["empty"] = is_empty def expandit(text_): before = None result = str(text_) while before != result: before = result result = env.from_string(result, template_class=Template).render( **variables ) return result env.filters["expandit"] = expandit def dashcase(text_): result = "" for i, i_char in enumerate(str(text_)): r = i_char.lower() if i > 0 and i_char.isupper(): result += "-" result += r return result env.filters["dashcase"] = dashcase def dmustache(text_): return "{{" + str(text_) + "}}" env.filters["dmustache"] = dmustache def env_var(text_): return "${" + expandit(text_) + "}" env.filters["env_var"] = env_var def to_json(text_): if isinstance(text_, bool): return "true" if text_ else "false" if isinstance(text_, list): return "[" + ", ".join([to_json(i) for i in text_]) + "]" if isinstance(text_, (int, float)): return str(text_) return '"{}"'.format(text_) env.filters["to_json"] = to_json import stringcase env.filters["camelcase"] = stringcase.camelcase env.filters["spinalcase"] = stringcase.spinalcase env.filters["pascalcase"] = stringcase.pascalcase def is_enabled(o): result = o.get("enabled", None) if result is None: return True result = env.from_string(result, template_class=Template).render( **variables ) result = bool(distutils.util.strtobool(result)) return result env.filters["is_enabled"] = is_enabled def combine(*terms, **kwargs): """ NOTE: Copied from ansible. """ import itertools from functools import reduce def merge_hash(a, b): """ Recursively merges hash b into a so that keys from b take precedence over keys from a NOTE: Copied from ansible. """ # if a is empty or equal to b, return b if a == {} or a == b: return b.copy() # if b is empty the below unfolds quickly result = a.copy() # next, iterate over b keys and values for k, v in b.items(): # if there's already such key in a # and that key contains a MutableMapping if ( k in result and isinstance(result[k], MutableMapping) and isinstance(v, MutableMapping) ): # merge those dicts recursively result[k] = merge_hash(result[k], v) else: # otherwise, just copy the value from b to a result[k] = v return result recursive = kwargs.get("recursive", False) if len(kwargs) > 1 or (len(kwargs) == 1 and "recursive" not in kwargs): raise RuntimeError("'recursive' is the only valid keyword argument") dicts = [] for t in terms: if isinstance(t, MutableMapping): dicts.append(t) elif isinstance(t, list): dicts.append(combine(*t, **kwargs)) else: raise RuntimeError("|combine expects dictionaries, got " + repr(t)) if recursive: return reduce(merge_hash, dicts) else: return dict(itertools.chain(*map(lambda x: x.items(), dicts))) env.filters["combine"] = combine def dedup(lst, key): """Remove duplicates from ta list of dictionaries.""" result = OrderedDict() for i_dict in lst: k = i_dict[key] v = result.get(k, {}) v.update(i_dict) result[k] = v result = list(result.values()) return result env.filters["dedup"] = dedup def dfilteredkeys(dct, value): """Filter dictionary list by the value.""" return [i_key for (i_key, i_value) in dct.items() if i_value == value] env.filters["dfilteredkeys"] = dfilteredkeys def dvalues(lst, key): """In a list of dictionaries, for each item returns item["key"].""" return [i.get(key) for i in lst] env.filters["dvalues"] = dvalues result = expandit(text) return result class AnatomyFile(object): """ Implements a file. Usage: f = AnatomyFile('filename.txt', 'first line') f.apply('directory') """ def __init__(self, filename, contents, executable=False): self.__filename = filename self.__content = dedent(contents) self.__executable = executable def apply(self, directory, variables, filename=None): """ Create the file using all registered blocks. Expand variables in all blocks. :param directory: :param variables: :return: """ expand = TemplateEngine.get().expand filename = filename or self.__filename filename = os.path.join(directory, filename) filename = expand(filename, variables) if self.__content.startswith("!"): content_filename = self.__content[1:] template_filename = "{{ ANATOMY.templates_dir }}/{{ ANATOMY.template}}" template_filename = f"{template_filename}/{content_filename}" template_filename = expand(template_filename, variables) content_filename = expand(template_filename, variables) self.__content = open(content_filename).read() # Use alternative variable/block expansion when working with Ansible # file. alt_expansion = filename.endswith("ansible.yml") try: content = expand(self.__content, variables, alt_expansion) except Exception as e: raise RuntimeError("ERROR: {}: {}".format(filename, e)) self._create_file(filename, content) if self.__executable: AnatomyFile.make_executable(filename) def _create_file(self, filename, contents): contents = contents.replace(" \n", "\n") contents = contents.rstrip("\n") contents += "\n" os.makedirs(os.path.dirname(filename), exist_ok=True) try: with open(filename, "w") as oss: oss.write(contents) except Exception as e: raise RuntimeError(e) @staticmethod def make_executable(path): mode = os.stat(path).st_mode mode |= (mode & 0o444) >> 2 # copy R bits to X os.chmod(path, mode) class AnatomySymlink(object): def __init__(self, filename, symlink, executable=False): self.__filename = filename self.__symlink = symlink self.__executable = executable def apply(self, directory, variables, filename=None): """ Create the file using all registered blocks. Expand variables in all blocks. :param directory: :param variables: :return: """ expand = TemplateEngine.get().expand filename = filename or self.__filename filename = os.path.join(directory, filename) filename = expand(filename, variables) symlink = os.path.join(os.path.dirname(filename), self.__symlink) assert os.path.isfile( symlink ), "Can't find symlink destination file: {}".format(symlink) self._create_symlink(filename, symlink) if self.__executable: AnatomyFile.make_executable(filename) @staticmethod def _create_symlink(filename, symlink): os.makedirs(os.path.dirname(filename), exist_ok=True) try: if os.path.isfile(filename) or os.path.islink(filename): os.unlink(filename) # Create a symlink with a relative path (not absolute) path = os.path.normpath(symlink) start = os.path.normpath(os.path.dirname(filename)) symlink = os.path.relpath(path, start) os.symlink(symlink, filename) except Exception as e: raise RuntimeError(e) class AnatomyTree(object): """ A collection of anatomy-files. Usage: tree = AnatomyTree() tree.create_file('gitignore', '.gitignore', '.pyc') tree.apply('directory') """ def __init__(self): self.__variables = OrderedDict() self.__files = {} def get_file(self, filename): """ Returns a AnatomyFile instance associated with the given filename, creating one if there's none registered. :param str filename: :return AnatomyFile: """ return self.__files.setdefault(filename, AnatomyFile(filename)) def apply(self, directory, variables=None): """ Create all registered files. :param str directory: :param dict variables: """ dd = self.__variables.copy() if variables is not None: dd = merge_dict(dd, variables) for i_fileid, i_file in self.__files.items(): try: filename = dd[i_fileid]["filename"] except KeyError: filename = None i_file.apply(directory, variables=dd, filename=filename) def create_file(self, filename, contents, executable=False): """ Create a new file in this tree. :param str filename: :param str contents: """ if filename in self.__files: raise FileExistsError(filename) self.__files[filename] = AnatomyFile(filename, contents, executable=executable) def create_link(self, filename, symlink, executable=False): """ Create a new symlink in this tree. :param str filename: :param str symlink: """ if filename in self.__files: raise FileExistsError(filename) self.__files[filename] = AnatomySymlink( filename, symlink, executable=executable ) def add_variables(self, variables, left_join=True): """ Adds the given variables to this tree variables. :param dict variables: :param bool left_join: If True, the root keys of the new variables (variables parameters) must already exist in the current variables dictionary. """ self.__variables = merge_dict(self.__variables, variables, left_join=left_join) def evaluate(self, text): return eval(text, self.__variables) def merge_dict(d1, d2, left_join=True): """ :param dict d1: :param dict d2: :return: """ return _merge_dict(d1, d2, depth=0, left_join=left_join) def _merge_dict(d1, d2, depth=0, left_join=True): def merge_value(v1, v2, override=False): if v2 is None: return v1 elif override: return v2 elif isinstance(v1, dict): return _merge_dict(v1, v2, depth=depth + 1, left_join=left_join) elif isinstance(v1, (list, tuple)): return v1 + v2 else: return v2 assert isinstance(d1, dict), "Parameter d1 must be a dict, not {}. d1={}".format( d1.__class__, d1 ) assert isinstance(d2, dict), "Parameter d2 must be a dict, not {}. d2={}".format( d2.__class__, d2 ) d2_cleaned = {i.rstrip("!"): j for (i, j) in d2.items()} if left_join and depth < 2: keys = d1.keys() right_keys = set(d2_cleaned.keys()) right_keys = right_keys.difference(set(d1.keys())) if right_keys: raise RuntimeError("Extra keys: {}".format(right_keys)) else: keys = list(d1.keys()) + [i for i in d2_cleaned.keys() if i not in d1] result = OrderedDict() for i_key in keys: try: result[i_key] = merge_value( d1.get(i_key), d2_cleaned.get(i_key), override=i_key + "!" in d2 ) except AssertionError as e: print("While merging value for key {}".format(i_key)) raise return result
zops.anatomy
/zops.anatomy-3.8.0.tar.gz/zops.anatomy-3.8.0/zops/anatomy/layers/tree.py
tree.py
from zops.anatomy.layers.feature import AnatomyFeatureRegistry from zerotk.lib.yaml import yaml_from_file from collections import OrderedDict class AnatomyPlaybook(object): """ Describes features and variables to apply in a project tree. """ def __init__(self, condition=True): self.__features = OrderedDict() self.__variables = {} @classmethod def get_template_name(cls, filename): contents = yaml_from_file(filename) return contents.pop("anatomy-template", "application") @classmethod def from_file(cls, filename): contents = yaml_from_file(filename) result = cls.from_contents(contents) return result @classmethod def from_contents(cls, contents): result = cls() result.__use_feature("ANATOMY", []) contents = contents.pop("anatomy-playbook", contents) use_features = contents.pop("use-features") if not isinstance(use_features, dict): raise TypeError( 'Use-features must be a dict not "{}"'.format(use_features.__class__) ) skip_features = contents.pop("skip-features", []) for i_feature_name, i_variables in use_features.items(): result.__use_feature(i_feature_name, skip_features) i_variables = cls._process_variables(i_variables) result.set_variables(i_feature_name, i_variables) if contents.keys(): raise KeyError(list(contents.keys())) return result @classmethod def _process_variables(cls, variables): return variables def __use_feature(self, feature_name, skipped): feature = AnatomyFeatureRegistry.get(feature_name) feature.using_features(self.__features, skipped) def set_variables(self, feature_name, variables): """ :param str key: :param object value: """ assert feature_name not in self.__variables self.__variables[feature_name] = variables def apply(self, directory): from zops.anatomy.layers.tree import AnatomyTree import os tree = AnatomyTree() if not os.path.isdir(directory): os.makedirs(directory) print("Applying features:") for i_feature_name, i_feature in self.__features.items(): i_feature.apply(tree) print(" * {}".format(i_feature_name)) print("Applying anatomy-tree.") tree.apply(directory, self.__variables)
zops.anatomy
/zops.anatomy-3.8.0.tar.gz/zops.anatomy-3.8.0/zops/anatomy/layers/playbook.py
playbook.py
from zops.anatomy.layers.tree import merge_dict from collections import OrderedDict import types import os from dataclasses import dataclass class FeatureNotFound(KeyError): pass class FeatureAlreadyRegistered(KeyError): pass class AnatomyFeatureRegistry(object): feature_registry = OrderedDict() @classmethod def clear(cls): cls.feature_registry = OrderedDict() @classmethod def get(cls, feature_name): """ Returns a previously registered feature associated with the given feature_name. :param str feature_name: :return AnatomyFeature: """ try: return cls.feature_registry[feature_name] except KeyError: raise FeatureNotFound(feature_name) @classmethod def register(cls, feature_name, feature): """ Registers a feature instance to a name. :param str feature_name: :param AnatomyFeature feature: """ if feature_name in cls.feature_registry: raise FeatureAlreadyRegistered(feature_name) cls.feature_registry[feature_name] = feature @classmethod def register_from_file(cls, filename, templates_dir): from zerotk.lib.yaml import yaml_from_file contents = yaml_from_file(filename) return cls.register_from_contents(contents, templates_dir) @classmethod def register_from_text(cls, text): from zerotk.lib.yaml import yaml_load from zerotk.lib.text import dedent text = dedent(text) contents = yaml_load(text) return cls.register_from_contents(contents) @classmethod def register_from_contents(cls, contents, templates_dir): feature = AnatomyFeature.from_contents( { "name": "ANATOMY", "variables": { "templates_dir": templates_dir, "template": "application", }, }, ) cls.register(feature.name, feature) for i_feature in contents["anatomy-features"]: feature = AnatomyFeature.from_contents(i_feature) cls.register(feature.name, feature) @classmethod def tree(cls): """ Returns all files created by the registered features. This is part of the helper functions for the end-user. Since the user must know all the file-ids in order to add contents to the files we'll need a way to list all files and their IDs. :return 3-tupple(str, str, str): Returns a tuple containing: [0]: Feature name [1]: File-id [2]: Filename """ result = [] for i_name, i_feature in cls.feature_registry.items(): if i_feature.filename: result.append((i_name, i_feature.filename, i_feature.filename)) return result class IAnatomyFeature(object): """ Implements a feature. A feature can add content in many files in its 'apply' method. Usage: tree = AnatomyTree() variables = {} feature = AnatomyFeatureRegistry.get('alpha') feature.apply(tree, variables) tree.apply('directory') """ def __init__(self, name): self.__name = name @property def name(self): return self.__name def apply(self, tree): """ Apply this feature instance in the given anatomy-tree. :param AnatomyTree tree: """ raise NotImplementedError() class AnatomyFeature(IAnatomyFeature): @dataclass class File: filename: str contents: str symlink: str executable: bool def __init__(self, name, variables=None, use_features=None, condition="True"): super().__init__(name) self.__condition = condition self.__variables = OrderedDict() self.__variables[name] = variables or OrderedDict() self.__use_features = use_features or OrderedDict() self.__enabled = True self.__files = [] def is_enabled(self): return self.__enabled @classmethod def from_contents(cls, contents): def optional_pop(dd, key, default): try: return dd.pop(key) except KeyError: return default name = contents.pop("name") condition = contents.pop("condition", "True") variables = contents.pop("variables", OrderedDict()) use_features = contents.pop("use-features", None) result = AnatomyFeature(name, variables, use_features, condition=condition) create_files = contents.pop("create-files", []) create_file = contents.pop("create-file", None) if create_file is not None: create_files.append(create_file) for i_create_file in create_files: symlink = optional_pop(i_create_file, "symlink", None) template = optional_pop(i_create_file, "template", None) filename = i_create_file.pop("filename", template) executable = optional_pop(i_create_file, "executable", False) if symlink is not None: result.create_link(filename, symlink, executable=executable) else: if template is not None: file_contents = f"!{template}" else: file_contents = i_create_file.pop("contents") result.create_file(filename, file_contents, executable=executable) if i_create_file.keys(): raise KeyError(list(i_create_file.keys())) if contents.keys(): raise KeyError(list(contents.keys())) return result @property def filename(self): raise NotImplementedError() def apply(self, tree): """ Implements AnatomyFeature.apply. """ tree.add_variables(self.__use_features, left_join=True) tree.add_variables(self.__variables, left_join=False) result = self.is_enabled() if result and self.__files: for i_file in self.__files: if i_file.contents: tree.create_file( i_file.filename, i_file.contents, executable=i_file.executable ) else: tree.create_link( i_file.filename, i_file.symlink, executable=i_file.executable ) return result def using_features(self, features, skipped): self.__enabled = self.name not in skipped for i_name, i_vars in self.__use_features.items(): feature = AnatomyFeatureRegistry.get(i_name) feature.using_features(features, skipped) # DEBUGGING: print('using anatomy-feature {} ({})'.format(self.name, id(self))) feature = features.get(self.name) if feature is None: features[self.name] = self else: assert id(feature) == id(self) def create_file(self, filename, contents, executable=False): self.__files.append( self.File( filename = filename, contents = contents, symlink = None, executable = executable ) ) def create_link(self, filename, symlink, executable=False): self.__files.append( self.File( filename = filename, contents=None, symlink=symlink, executable=executable ) )
zops.anatomy
/zops.anatomy-3.8.0.tar.gz/zops.anatomy-3.8.0/zops/anatomy/layers/feature.py
feature.py
import itertools import os import re import sys import time from operator import attrgetter, itemgetter from pathlib import Path import boto3 import click from tabulate import tabulate from zops.aws.cluster import Cluster from zops.aws.instance import Instance from zops.aws.image import Image from zops.aws.autoscaling import AutoScalingGroup from zops.aws.utils_click import STRING_LIST from zops.aws.cli_config import load_config @click.command(name="ami.list") @click.argument("clusters", nargs=-1) @click.option("--regions", type=STRING_LIST, default="*") @click.option("--force-regions", is_flag=True) @click.option( "--sort-by", default="creation_date", type=click.Choice( [ "image_id", "name", "tags:Name", "tags:Version", "owner_id", "creation_date", "stage", "profile", "region", ], case_sensitive=True, ), help="Sort list by thie attribute. Default: creation_date", ) def ami_list(clusters, regions, force_regions, sort_by): """ List AMIs in a cluster. List images from all regions associated with that cluster. Examples: \b # List AMI images for tier3's cluster. $ uh aws ami.list tier3 \b # List AMI images. Try to guess the cluster based on the current directory. $ uh aws ami.list """ load_config() clusters = Cluster.clusters_arg(clusters) rows = [[i[1] for i in Image._iter_attrs()]] for i_cluster in clusters: cluster = Cluster.clusters[i_cluster] regions = cluster.regions_arg(regions, force=force_regions) for i_ami in sorted( cluster.list_images(regions=regions), key=attrgetter(sort_by) ): rows.append( [getattr(i_ami, j_name) for j_name, _ in Image._iter_attrs()] ) print(tabulate(rows, headers="firstrow")) @click.command() @click.argument("name") @click.argument("region") @click.argument("credentials") def aws_configure_profile(name, region, credentials): """ Configure AWS profile locally (~/.aws/credentials). Add a new profile in the local credentials file using the given name, region and credentials. The credentials format is the following: access-id,access-secret Example: \b $ uh ami configure-profile tier3 ca-central-1 $AWS_ACCOUNT_KEY_ID,$AWS_SECRET_ACCOUNT_KEY OUTPUT: ~/.aws/credentials file has new values like \b [tier3] aws_access_key_id=<value of $AWS_ACCOUNT_KEY_ID> aws_secret_access_key=<value of $AWS_SECRET_ACCOUNT_KEY> region = ca-central-1 """ load_config() credentials_file = Path("~/.aws/credentials").expanduser() credentials_file.parent.mkdir(parents=True, exist_ok=True) access_id, access_secret = credentials.split(",", 1) with credentials_file.open("a") as oss: oss.write( f""" [{name}] aws_access_key_id={access_id} aws_secret_access_key={access_secret} region = {region} """ ) @click.command("ami.deregister") @click.option("--regions", type=STRING_LIST, default="*") @click.argument("image_names", nargs=-1) @click.option("--yes", is_flag=True) def ami_deregister(image_names, regions, yes): """ Deregister AMIs with the given version. """ load_config() internal_cluster = Cluster.clusters["internal"] regions = ("ca-central-1", "us-east-2") def _items(): """ List items (image) to be deregistered. """ result = [] for i_image in internal_cluster.list_images(regions=regions): if i_image.name in image_names: result.append(i_image) return result for i_image in _items(): i_image.msg("DEREGISTER") i_image.deregister(yes=yes) @click.command("ami.build") @click.argument("version") @click.argument( "cluster_name", ) @click.argument("cluster_names", nargs=-1) @click.option( "--images", "image_names", help="List images to build. By default build all images.", type=STRING_LIST, default=[], ) @click.option( "--regions", help="Region where to build the AMI.\nBy default build on cluster's" "default region.", type=STRING_LIST, default=[], ) @click.option( "--overwrite", is_flag=True, help="Overwrite existing image with the same name.", ) @click.option( "--cleanedb-app_branch", default=None, help="Overrides clean machine application branch. Defaults to the image" "defined on aws_operations.yml configuration file.", ) @click.option("--base-ami-version", default=None) @click.option("--image-os", default="centos7") @click.option("--aws-credentials-env", default="AWS_CREDENTIALS__AMI_BUILD") @click.option("--yes", is_flag=True) def ami_build( version, cluster_name, cluster_names, image_names, regions, overwrite, cleanedb_app_branch, base_ami_version, image_os, aws_credentials_env, yes, ): """ Build AMIs base images. VERSION: The version (semantic) for the new base images. CLUSTER_NAME: Cluster where to build images. CLUSTER_NAMES: Optional list of clusters to share the image with. * This command must be executed on unhaggle/unhaggle-ami repository; * This command must be executed on build-amis directory; Examples: \b # Build version 2.0.10 for all baseimages $ uh aws ami.build 2.0.10 \b # Build version 2.0.10 for all baseimages (explicit) $ uh aws ami.build 2.0.10 unhaggle-ami \b # Build version 2.0.10 for all baseimages and share it with tier3 $ uh aws ami.build 2.0.10 unhaggle-ami tier3 \b # Build version 2.0.10 only for baseimage $ uh aws ami.build --images=baseimage 2.0.10 \b # Build version 2.0.10 for all baseimages on tier3 cluster $ uh aws ami.build 2.0.10 tier3 \b # Build version 2.0.10 of clean image for tier3 $ uh-ami ami.build --images=clean 2.0.10 tier3 """ load_config() cluster = Cluster.clusters[cluster_name] image_names = cluster.image_names_arg(image_names) regions = cluster.regions_arg(regions) cluster_names = set(cluster_names) clusters = [Cluster.clusters[i] for i in cluster_names] ami_regions = { i.regions[0] for i in clusters if i.regions[0] != cluster.regions[0] } ami_users = {str(i.aws_id) for i in clusters} base_ami_version = base_ami_version or version aws_credentials = os.environ[aws_credentials_env] print( f""" # Build AMIs * cluster: {cluster.name} * regions: {', '.join(regions)} * ami_user: {', '.join(ami_users)} * images: {', '.join(image_names)} * version: {version} * aws_credentials: {aws_credentials} * base_ami_version: {base_ami_version} """ ) if ami_regions: print("# Copy AMIs to these regions:") for i_region in ami_regions: print(f" * {i_region}") print("# Share with these AWS accounts:") for i_cluster in clusters: print(f" * {i_cluster.aws_id} ({i_cluster.name})") def _items(): """ List items (image) to be build. * Check if the image already exists; """ result = [] for i_image_name, i_region in itertools.product(image_names, regions): image = cluster.get_image( i_image_name, version, i_region, image_os ) if image.exists: if overwrite: image.msg("WARN: Image already exists: Overwriting.") image.deregister(yes=yes) else: image.msg("SKIP: Image already exists: Skipping") continue result.append(image) return result for i_image in _items(): i_image.msg("BUILD") if cleanedb_app_branch is not None: cluster.app_branch = cleanedb_app_branch r = cluster.build_image( i_image, base_ami_version, ami_regions=ami_regions, ami_users=ami_users, image_os=image_os, aws_credentials=aws_credentials, yes=yes, ) if not r: print( "ERROR: Error while building image. " "Check the logs for more details." ) sys.exit(1) @click.command() @click.argument("clusters", nargs=-1) @click.option("--revision_width", default=80) def deployments_list(clusters, revision_width): """ List AWS deployments. """ load_config() keys = [ "cluster", "region", "app", "group", "status", "create_time", "end_time", "revision", ] sort_by = "create_time" clusters = Cluster.clusters_arg(clusters) deploys = [] for i_cluster in clusters: cluster = Cluster.clusters[i_cluster] deploys += cluster.list_deploy(revision_width=revision_width) rows = [keys] rows += [ [i[j] for j in keys] for i in sorted(deploys, key=itemgetter(sort_by)) ] print(tabulate(rows, headers="firstrow")) @click.command(name="ec2.list") @click.argument("clusters", nargs=-1) @click.option("--sort-by", default="launch_time") @click.option("--volumes", is_flag=True) @click.option("--keys", type=list, default=Instance._ATTRS) def ec2_list(sort_by, volumes, keys, clusters): """ List AWS EC2 instances. """ load_config() clusters = Cluster.clusters_arg(clusters) if volumes: keys += ["encrypted_volumes"] rows = [keys] for i_cluster in clusters: cluster = Cluster.clusters[i_cluster] for i_region in cluster.regions: for j_instance in cluster.list_instances( i_region, sort_by=sort_by ): rows.append(j_instance.as_row(keys)) print(tabulate(rows, headers="firstrow")) @click.command() @click.argument("instance_names", nargs=-1) def ec2_start(instance_names): """ Start AWS EC2 instance. """ load_config() CLUSTER_MAP = { "bp": "buildandprice", "pi": "paymentinsights", "audi": "tier1_audi", } for i_instance_name in instance_names: cluster = i_instance_name.split("-")[0] cluster = CLUSTER_MAP.get(cluster, cluster) cluster = Cluster.clusters[cluster] for j_instance in cluster.get_instance_by_name( i_instance_name, state="stopped" ): print(f"{j_instance}: Starting instance.") j_instance.start() @click.command(name="ec2.shell") @click.argument("instance_seed") @click.option("--index", type=int, default=0) @click.option("--profile", type=str, default=None) @click.option("--region", default="ca-central-1") @click.option("--command", type=str, default=None) @click.option("--sleep", type=int, default=1) def ec2_shell(instance_seed, index, profile, region, command, sleep): """ Start SSM session on AWS EC2 instance. """ import os load_config() cluster, instance_name = Cluster.instances_arg(instance_seed) if cluster is None: instance_id = instance_name else: print(f"Instance name: {instance_name}") profile = profile or cluster.profile print(f"AWS profile: {profile}") if region is not None: cluster.regions = [region] else: region = cluster.regions[0] print(f"AWS region: {region}") instances = cluster.get_instance_by_name( instance_name, state="running" ) if not instances: print( f""" ERROR: No instances found. Check if your AWS credentials work with: aws --profile={profile} ec2 describe-instances """ ) exit(9) instance = instances[index] instance_id = instance.id print(f"Instance id: {instance_id}") if command: ssm_client = boto3.Session(profile_name=profile).client("ssm") response = ssm_client.send_command( InstanceIds=[instance_id], DocumentName="AWS-RunShellScript", Parameters={"commands": [command]}, ) command_id = response["Command"]["CommandId"] for i_retries in range(3): time.sleep(sleep) output = ssm_client.get_command_invocation( CommandId=command_id, InstanceId=instance_id, ) if output["Status"] != "InProgress": break print(output["StandardOutputContent"]) else: cmd = ( f"aws --profile={profile} ssm start-session --target {instance_id}" ) print(f"Command line: {cmd}") os.system(cmd) # nosec B605 print(f"{instance_id}: Finished SSM session.") @click.command(name="asg.list") @click.argument("asg_seed") @click.option("--region", default=None) def asg_list(asg_seed, region): """ List ASGs (Auto Scaling Gropus) that matches the given name. Examples: # Lists all production ASGs for Tier3. uh aws asg.list tier3-prod """ load_config() for i_asg in AutoScalingGroup.list_groups(asg_seed, region): i_asg.print() @click.command() @click.argument("asg_seed") def asg_instance_refresh(asg_seed): """ Executes instance-refresh for ASGs Examples: # Update instances related with Tier3's production ASGs. uh aws asg.instance-refresh tier3-prod-app """ load_config() autoscaling_groups = list_autoscaling_groups(asg_seed) for i_asg in autoscaling_groups: asg_name = i_asg["AutoScalingGroupName"] i_asg.start_instance_refresh() print(f"\n{asg_name} >> SUCCESS: Instance refresh started.") @click.command(name="asg.update") @click.argument("asg_seed") @click.argument("desired_capacity", type=int) @click.option("--region", default=None) def asg_update(asg_seed, desired_capacity, region): """ Updates the desired capacity for ASGs. Examples: # Update the desired capacity of tier3-prod-app to 6. uh aws asg.update tier3-prod-app 6 """ load_config() for i_asg in AutoScalingGroup.list_groups(asg_seed, region): i_asg.print() i_asg.update( desired_capacity=desired_capacity, ) @click.command(name="params.list") @click.argument("cluster") @click.option("--prefix", default="/DJANGO") def params_list(cluster, prefix): """ List parameters from the selected cluster. Examples: uh aws params.list tier3 """ load_config() cluster = Cluster.get_cluster(cluster) result = {} for i_region in cluster.regions: ssm = cluster.ssm_client(i_region) parameters_pages = ssm.get_paginator( "get_parameters_by_path" ).paginate( Path=prefix, Recursive=True, WithDecryption=True, ) for i_page in parameters_pages: for j_parameter in i_page["Parameters"]: result[j_parameter["Name"]] = ( j_parameter.get("Value"), j_parameter.get("Type"), ) for i_name, (i_value, i_type) in sorted(result.items()): type_spec = f":{i_type}" if i_type != "String" else "" print(f"{i_name}{type_spec}={i_value}") @click.command(name="params.put") @click.argument("cluster") @click.argument("filename") @click.option("--region", default=None) def params_put(cluster, filename, region): """ Upload settings from filename into Parameter Store. Examples: uh aws params.put tier3-dev-params.lst """ def parameters(filename): for i_line in open(filename).readlines(): line = i_line.strip("\n ") if not line: continue if line.startswith("#"): continue yield split_name_value(line) load_config() cluster = Cluster.get_cluster(cluster) region = region or cluster.regions[0] ssm = cluster.ssm_resource(region) for i_name, i_type, i_value in parameters(filename): if i_type == "SecureString": value = "..." + i_value[-5:] else: value = i_value # print(f"DEL {i_name}:{i_type}={value}") # print(f"NEW {i_name}:{i_type}={value}") print(f"SET {i_name}:{i_type}={value}") ssm.put_parameter( Name=i_name, Value=i_value, Type=i_type, Overwrite=True ) def split_name_value(name_value): NAME_VALUE_REGEX = re.compile( r"(?P<name>[\/\w]*)(?::(?P<type>\w*))?=(?P<value>.*)$" ) m = NAME_VALUE_REGEX.match(name_value) if m is None: raise RuntimeError(f"Can't regex the line: '{name_value}'") r_name, r_type, r_value = m.groups() r_type = r_type or "String" return r_name, r_type, r_value @click.command(name="params.get") @click.argument("cluster") @click.argument("name") @click.option("--region", default=None) def params_get(cluster, name, region): """ Get the value of a SSM Parameter. Examples: uh aws params.get mi-dev /DJANGO/CREDITAPP_DEV__SLACK_TOKEN """ load_config() cluster = Cluster.get_cluster(cluster) region = region or cluster.regions[0] ssm = cluster.ssm_resource(region) r = ssm.get_parameter(Name=name, WithDecryption=True) print(f"{name}={r['Parameter']['Value']}") @click.command(name="params.set") @click.argument("cluster") @click.argument("name_values", nargs=-1) @click.option("--region", default=None) @click.option("--overwrite", is_flag=True) def params_set(cluster, name_values, region, overwrite): """ Set a SSM Parameter value. Examples: uh aws params.set tier3-dev /DJANGO/TIER3_DEV__SLACK_TOKEN=12345 """ load_config() cluster = Cluster.get_cluster(cluster) region = region or cluster.regions[0] ssm = cluster.ssm_resource(region) for i_name_value in name_values: name, value_type, value = split_name_value(i_name_value) ssm.put_parameter( Name=name, Value=value, Type=value_type, Overwrite=overwrite ) @click.command(name="params.del") @click.argument("cluster") @click.argument("names", nargs=-1) @click.option("--region", default=None) def params_del(cluster, names, region): """ Delete a SSM Parameter. Examples: uh aws params.del tier3-dev /DJANGO/TIER3_DEV__SLACK_TOKEN """ load_config() cluster = Cluster.get_cluster(cluster) region = region or cluster.regions[0] ssm = cluster.ssm_resource(region) ssm.delete_parameters(Names=names) @click.command(name="resources.clean") @click.argument("clusters", nargs=-1) @click.option("--region", default=None) @click.option("--yes", is_flag=True) def resources_clean(clusters, region, yes): SECURITY_GROUP_FILTER = [ { "Name": "description", "Values": ["Temporary group for Packer", "launch-wizard-*"], } ] KEYPAIRS_FILTER = [{"Name": "key-name", "Values": ["packer*"]}] load_config() for i_cluster in clusters: cluster = Cluster.get_cluster(i_cluster) region = region or cluster.regions[0] ec2 = cluster.ec2_resource(region) click.echo("Resources cleanup") click.echo("Security Groups:") security_groups = ec2.security_groups.filter( Filters=SECURITY_GROUP_FILTER ) for i in security_groups: click.echo(f" * {i.group_id}: {i.group_name} - {i.description}") click.echo("Key Pairs:") key_pairs = ec2.key_pairs.filter(Filters=KEYPAIRS_FILTER) for i in key_pairs: click.echo(f" * {i.key_pair_id}: {i.key_name}") click.echo("Instances:") INSTANCES_FILTER = [ { "Name": "instance.group-id", "Values": [i.group_id for i in security_groups], } ] instances = ec2.instances.filter(Filters=INSTANCES_FILTER) for i in instances: name_tag = [j["Value"] for j in i.tags if j["Key"] == "Name"][0] click.echo(f" * {i.id}: {name_tag} - {i.state['Name']}") if yes: click.echo("Terminating instances...") for i in instances: i.terminate() click.echo("Deleting key-pairs...") for i in key_pairs: i.delete() click.echo("Deleting security-groups...") for i in security_groups: try: i.revoke_ingress(IpPermissions=i.ip_permissions) i.delete() except Exception: click.echo(f"*** Failed to delete security group {i.id}") continue @click.command(name="resources.clear_default_vpcs") @click.argument("cluster") @click.option("--regions", multiple=True, default=[]) @click.option( "--skip-regions", multiple=True, default=["ca-central-1", "us-east-2"] ) @click.option("--yes", is_flag=True) def resources_clear_default_vps(cluster, regions, skip_regions, yes): load_config() cluster = Cluster.get_cluster(cluster) client = cluster.ec2() regions = regions or [ i["RegionName"] for i in client.describe_regions()["Regions"] ] regions = [i for i in regions if i not in skip_regions] print(f"Regions: {regions}") for i_region in regions: ec2 = cluster.ec2_resource(i_region) for j_vpc in ec2.vpcs.all(): vpc_name = "?" if j_vpc.tags: tags = {k["Key"]: k["Value"] for k in j_vpc.tags} vpc_name = tags["Name"] if not j_vpc.is_default: print( f"* Skip non-default VPC in region {i_region}: {j_vpc.vpc_id} ({vpc_name})" ) continue print( f"* Deleting default VPC in region {i_region}: {j_vpc.vpc_id} ({vpc_name})" ) _delete_vpc(j_vpc, yes) def _delete_vpc(vpc, yes): for igw in vpc.internet_gateways.all(): print(f" * Detaching and Removing igw: {igw.id}") if yes: igw.detach_from_vpc(VpcId=vpc.vpc_id) igw.delete() for sub in [i for i in vpc.subnets.all() if i.default_for_az]: print(f" * Removing subnet: {sub.id}") if yes: sub.delete() for rtb in vpc.route_tables.all(): if ( rtb.associations_attribute and rtb.associations_attribute[0]["Main"] ): print(f" * Skip main route-table: {rtb.id}") continue print(f"* Removing route-table {rtb.id}") if yes: rtb.delete() for acl in [i for i in vpc.network_acls.all() if not i.is_default]: print(f" * Removing acl: {acl.id}") if yes: acl.delete() for sg in vpc.security_groups.all(): if sg.group_name == "default": print(f" * Skip default security group: {sg.id}") continue print(f" * Removing security-group: {sg.id}") if yes: sg.delete() print(f" * Removing vpc: {vpc.id}") if yes: vpc.delete() @click.command(name="ecr.list") @click.argument("repos", nargs=-1) @click.option("--cluster", default="mi-shared") @click.option("--region", default=None) def ecr_list(repos, cluster, region): load_config() cluster = Cluster.get_cluster(cluster) region = region or cluster.regions[0] ecr = cluster.ecr_client(region) if repos: for i_repo in repos: images = ecr.describe_images(repositoryName=i_repo)["imageDetails"] for i in sorted(images, key=lambda d: d["repositoryName"]): images_tags = "/".join(i.get("imageTags", [""])) image_size = round(i["imageSizeInBytes"] / (1024 * 1024), 2) if images_tags: print( "* {registryId}.dkr.ecr.{region}.amazonaws.com/{repositoryName}:{images_tags} ({image_size}Mb) - {imagePushedAt} ".format( images_tags=images_tags, image_size=image_size, region=region, **i ) ) else: repos = ecr.describe_repositories() for i_repo in sorted(repos["repositories"], key=lambda d: d["repositoryUri"]): print(f"* {i_repo['repositoryUri']}") @click.command(name="rds_snapshot.list") @click.argument("cluster") @click.option("--region", default=None) def rds_snapshot_list(cluster, region): load_config() cluster = Cluster.get_cluster(cluster) region = region or cluster.regions[0] rds = cluster.client("rds", region=region) snapshots = rds.describe_db_snapshots(SnapshotType="automated")[ "DBSnapshots" ] for i in snapshots: print("*", i) @click.command(name="vpc.details") @click.argument("cluster") @click.option("--region", default=None) def vpc_details(cluster, region): import json load_config() cluster = Cluster.get_cluster(cluster) region = region or cluster.regions[0] ec2 = cluster.ec2_resource(region=region) result = {} for i_vpc in ec2.vpcs.all(): subnets = sorted(i_vpc.subnets.all(), key=lambda x: x.availability_zone) result["vpc_id"] = i_vpc.id # result["public_subnets"] = {} # result["private_subnets"] = {} # result["private_route_table_ids"] = {} # result["azs"] = {} result["public_subnets"] = [j.id for j in subnets if j.map_public_ip_on_launch] result["private_subnets"] = [j.id for j in subnets if not j.map_public_ip_on_launch] result["private_route_table_ids"] = [ j.id for j in i_vpc.route_tables.all() if j.associations_attribute[0].get("SubnetId") in result["private_subnets"] ] result["azs"] = list({j.availability_zone for j in subnets}) print(json.dumps(result)) @click.command(name="ecr.login") @click.argument("cluster") @click.option("--region", default=None) def ecr_login(cluster, region): load_config() cluster = Cluster.get_cluster(cluster) region = region or cluster.regions[0] print(f"aws ecr --profile=mi-shared get-login-password --region {region} | docker login --username AWS --password-stdin {cluster.aws_id}.dkr.ecr.{region}.amazonaws.com")
zops.aws
/zops.aws-1.0.0-py3-none-any.whl/zops/aws/cli_commands.py
cli_commands.py
import copy import functools import os import subprocess from operator import attrgetter from typing import Dict import boto3 import click import yaml from .utils import get_resource_attr, format_date from .utils_shell import packer from .image import Image from .instance import Instance class Cluster: """ Group all information about a given cluster. All specifics for each cluster is defined here. The algorithms are the same for all cluster. """ AWS_OWNERS = [] clusters = {} @classmethod def get_cluster(cls, cluster): result = cls.clusters.get(cluster) if result is None: raise click.ClickException(f"Invalid cluster name: '{cluster}'.") return result @classmethod def get_cluster_env(cls, cluster_env): cluster_name, env = cluster_env.split("-", 1) result = Cluster.clusters_arg(cluster_name) result = Cluster.get_cluster(result) return result, env def __init__( self, name, profile, regions, project=None, psql_version=10, python_version="3.6", requires_name="requires.txt", images="app cron tunnel clean".split(), app_branch="master", aws_id=None, newrelic_id=None, sentry_id=None, ): self.name = name self.project = project or name self.profile = profile self.regions = regions[:] self.psql_version = psql_version self.app_branch = app_branch self.python_version = python_version self.requires_name = requires_name self.images = images self.aws_id = aws_id self.newrelic_id = newrelic_id self.sentry_id = sentry_id @classmethod def load_clusters(cls, config_dict: Dict): result = {} for i_name, i_details in config_dict.items(): profile = i_details.pop("profile", i_name) result[i_name] = cls(name=i_name, profile=profile, **i_details) cls.clusters = result return cls.clusters @property def caption(self): return self.name.upper() PROJECT_MAP = {"t3can": "tier3"} CLUSTERS_ARG = [ ("/ami.unhaggle", ["unhaggle-ami"]), ("/audi-cluster", ["tier1_audi"]), ("/bp-cluster", ["buildandprice"]), ("/buildandprice", ["buildandprice"]), ("/creditapp", ["t3can"]), ("/paymentinsights", ["paymentinsights"]), ("/pi-cluster", ["paymentinsights"]), ("/polestar", ["polestar"]), ("/polestar-cluster", ["polestar"]), ("/t3can-cluster", ["t3can"]), ("/t3usa-cluster", ["t3usa"]), ("/tier1_audi", ["tier1_audi"]), ("/tier1", ["tier1"]), ("/tier1-cluster", ["tier1"]), ("/tier3", ["tier3"]), ("/unhaggle", ["unhaggle"]), ("/unhaggle-ami", ["unhaggle-ami"]), ("/unhaggle-cluster", ["unhaggle"]), ("/mi-cluster", ["mi-dev"]), ] CLUSTER_MAP = { "bp": "buildandprice", "pi": "paymentinsights", "audi": "tier1_audi", "intranet": "internal", "nomad": "internal", "sandbox": "mi-sandbox", "dev": "mi-dev", "qa": "mi-qa", "stage": "mi-stage", "intranet": "internal", } @classmethod def clusters_arg(cls, clusters): result = clusters if not result: cwd = os.getcwd() for i_match, i_clusters in cls.CLUSTERS_ARG: if i_match in cwd is not None: result = i_clusters break else: result = ["unhaggle-ami"] return result @classmethod def instances_arg(cls, instance_seed): name_parts = instance_seed.split("-") suffix = "" if instance_seed.startswith("i-"): return None, instance_seed last_part = name_parts.pop(-1) if last_part.isnumeric(): suffix = f"-{last_part}" role = name_parts.pop(-1) else: role = last_part workspace = ( name_parts.pop(-1) if name_parts else cls.terraform_workspace() ) project = cls.clusters_arg([name_parts.pop(-1)] if name_parts else [])[ 0 ] cluster = cls.CLUSTER_MAP.get( workspace, cls.CLUSTER_MAP.get(project, project) ) cluster = cls.clusters[cluster] project = cls.PROJECT_MAP.get(project, project) return cluster, f"{project}-{workspace}-{role}{suffix}" @classmethod def terraform_workspace(cls): return ( subprocess.check_output(["terraform", "workspace", "show"]) .decode("UTF-8") .strip() ) def regions_arg(self, regions, force=False): """ Handles regions argument. """ if "*" in regions: return tuple(self.regions) if not regions: return (self.regions[0],) if isinstance(regions, str): regions = regions.split(",") if not force: invalid_regions = [i for i in regions if i not in self.regions] if invalid_regions: raise RuntimeError( f"Invalid regions: {', '.join(invalid_regions)}. Valid ones {', '.join(self.regions)}" ) return tuple(regions) def image_names_arg(self, images): """ Handles images argument: * If given, check each image name and return it; * If not given, return the complete list of images for this cluster. """ if not images or images == "*": return self.images if isinstance(images, str): images = images.split(",") invalid_images = [i for i in images if i not in self.images] if invalid_images: raise RuntimeError( f"Invalid images: {', '.join(invalid_images)}. Valid images: {', '.join(self.images)}" ) return images @functools.lru_cache() def codedeploy(self, region=None): region = region or self.regions[0] return self._session.client("codedeploy", region_name=region) @functools.lru_cache() def s3(self, region=None): region = region or self.regions[0] return self._session.client("s3", region_name=region) @functools.lru_cache() def ec2(self, region=None): region = region or self.regions[0] return self._session.client("ec2", region_name=region) @functools.lru_cache() def autoscaling(self, region=None): region = region or self.regions[0] return self._session.client("autoscaling", region_name=region) @functools.lru_cache() def ec2_resource(self, region=None): region = region or self.regions[0] return self._session.resource("ec2", region_name=region) @functools.lru_cache() def ecr_client(self, region=None): region = region or self.regions[0] return self._session.client("ecr", region_name=region) @functools.lru_cache() def ssm_client(self, region=None): region = region or self.regions[0] return self._session.client("ssm", region_name=region) @functools.lru_cache() def ssm_resource(self, region=None): region = region or self.regions[0] return self._session.client("ssm", region_name=region) @property @functools.lru_cache() def _session(self): return boto3.Session(profile_name=self.profile) @functools.lru_cache() def list_images(self, regions=None): """ List AMI images for this cluster. Return a list of dictionary with the keys defined in image_keys. """ result = [] regions = regions or self.regions for i_region in regions: for i in self.ec2_resource(i_region).images.filter( Owners=self.AWS_OWNERS ): image = Image.from_aws_ami( i, region=i_region, profile=self.profile ) result.append(image) return result @functools.lru_cache() def list_instances(self, region, sort_by="launch_time"): ec2 = self.ec2_resource(region) return [ Instance(self, region, i) for i in sorted(ec2.instances.filter(), key=attrgetter(sort_by)) ] def get_image(self, image_name, version, region, image_os): for i_image in self.list_images(): try: if i_image.tag_name == "-": tag_name, tag_version = i_image.name.split("-", 3)[-2:] else: tag_name, tag_version = ( i_image.tag_name, i_image.tag_version, ) if ( i_image.region == region and tag_name == image_name and tag_version == version ): return i_image except ValueError: # Ignore images that don't match our format. continue return Image( tag_name=image_name, tag_version=version, profile=self.profile, region=region, image_os=image_os, ) def get_instance_by_name(self, instance_name, state="running"): region = self.regions[0] result = self.ec2_resource(region).instances.filter( Filters=[ {"Name": "tag:Name", "Values": [f"{instance_name}*"]}, {"Name": "instance-state-name", "Values": [state]}, ] ) return list(result) def copy_image(self, source_image, region, yes=False): result = copy.deepcopy(source_image) result.image_id = None result.region = region if not yes: print( f"$ aws ec2 copy-image {source_image.display_name} ==> {result.region}" ) return result response = self.ec2(region).copy_image( Name=source_image.name, SourceImageId=source_image.image_id, SourceRegion=source_image.region, ) result.image_id = response["ImageId"] return result def wait_image_available(self, images, yes=False): """ Wait for the given images to be available. """ if yes: images_by_region = {} for i_image in images: images_by_region.setdefault(i_image.region, []).append(i_image) for i_region, i_images in images_by_region.items(): waiter = self.ec2(i_region).get_waiter("image_available") waiter.wait( ImageIds=[j.image_id for j in i_images], WaiterConfig={"Delay": 6, "MaxAttempts": 100}, ) else: print("$ aws ec2 wait image-available:") for i_image in images: print(f" * {i_image.display_name}") def build_image( self, image, base_ami_version=None, ami_regions=None, ami_users=None, image_os="centos7", aws_credentials=",", yes=False, ): """ Build the image using packer. The configuration files are expected at build-amis/<OS>/NAME/ """ vars = dict( version=image.tag_version, app_branch=self.app_branch, app_name=self.name, aws_profile=self.profile, aws_region=self.regions[0], base_ami_version=base_ami_version or image.tag_version, psql_version=self.psql_version, python_version=self.python_version, requires_name=self.requires_name, # Credentials to download stuff from S3 from the builder EC2 # instance. Couldn't find a way to use the instances permissions # using IAM. aws_access_key=aws_credentials.split(",")[0], aws_secret_key=aws_credentials.split(",")[1], ) filters = { "cluster": [ "version", "aws_profile", "aws_region", ], "base": [ "version", "aws_profile", "aws_region", ], "basedocker": [ "version", "base_ami_version", "aws_profile", "aws_access_key", "aws_secret_key", "aws_region", ], "app": [ "version", "base_ami_version", "aws_profile", "aws_access_key", "aws_secret_key", "aws_region", ], "clean": [ "version", "base_ami_version", "aws_profile", "aws_region", "app_name", "app_branch", "python_version", "requires_name", "psql_version", ], "ftp": [ "version", "base_ami_version", "aws_profile", ], "tunnel": [ "version", "base_ami_version", "aws_profile", ], "nomad": [ "version", "base_ami_version", "aws_profile", "aws_region", ], "redash": [ "version", "base_ami_name" "base_ami_version", "aws_profile", "aws_region", ], } vars = { i_name: i_value for i_name, i_value in vars.items() if i_name in filters[image.tag_name] } if ami_users: vars["ami_users"] = ami_users if ami_regions: vars["ami_regions"] = ami_regions return packer( "build", f"./{image_os}/{image.tag_name}/{image.tag_name}.pkr.hcl", builder="amazon-ebs", on_error="cleanup", vars=vars, yes=yes, ) def list_deploy(self, revision_width=80): result = [] for i_region in self.regions: apps = ( self.codedeploy(i_region) .list_applications() .get("applications", []) ) for j_app in apps: deployment_groups = self.codedeploy( i_region ).list_deployment_groups(applicationName=j_app) for k_group in deployment_groups.get("deploymentGroups", []): deployment_group_info = ( self.codedeploy(i_region) .get_deployment_group( applicationName=j_app, deploymentGroupName=k_group ) .get("deploymentGroupInfo", {}) ) last_deployment = deployment_group_info.get( "lastAttemptedDeployment", {} ) if not last_deployment: continue deployment = self.codedeploy(i_region).get_deployment( deploymentId=last_deployment["deploymentId"] ) deployment_info = deployment["deploymentInfo"] try: revision = deployment_info["revision"]["s3Location"][ "key" ] revision = revision[:revision_width] + "..." except KeyError: revision = "UNKNOWN" result.append( dict( cluster=self.name, region=i_region, app=j_app, group=k_group, status=deployment_info["status"], create_time=format_date( deployment_info["createTime"] ), end_time=format_date( deployment_info.get("endTime", "") ), revision=revision, ) ) return result def list_autoscaling_groups(asg_filter, region="ca-central-1"): """ Returns a list of dictionary representing autoscaling groups with some extra information: * [ImageId]: The AMI id associated with the ASG. * [Instances]: A list of associated EC2 instances. * [InstanceRefreshes]: A list of associated instance refreshes. * start_instance_refresh: A method that starts the instance-refresh. """ class ASG(dict): def __init__(self, *args, **kwargs): result = super().__init__(*args, **kwargs) ec2_client = session.client("ec2") if "LaunchConfigurationName" in self: launch_configurations = ( autoscaling.describe_launch_configurations( LaunchConfigurationNames=[ self["LaunchConfigurationName"] ] )["LaunchConfigurations"] ) image_id = launch_configurations[0]["ImageId"] else: launch_template_id = self["LaunchTemplate"]["LaunchTemplateId"] launch_template = ec2_client.describe_launch_templates( LaunchTemplateIds=[launch_template_id] ) launch_template_version = launch_template["LaunchTemplates"][ 0 ]["LatestVersionNumber"] launch_template_version = ( ec2_client.describe_launch_template_versions( LaunchTemplateId=launch_template_id, Versions=[str(launch_template_version)], ) ) image_id = launch_template_version["LaunchTemplateVersions"][ 0 ]["LaunchTemplateData"]["ImageId"] self["ImageId"] = image_id image_name = ec2_client.describe_images(ImageIds=[image_id]) self["ImageName"] = image_name["Images"][0]["Name"] try: elb_health = { i["Target"]["Id"]: i["TargetHealth"]["State"] for i in elb.describe_target_health( TargetGroupArn=self["TargetGroupARNs"][0] )["TargetHealthDescriptions"] } except IndexError: elb_health = {} instance_ids = [j["InstanceId"] for j in self["Instances"]] if instance_ids: ec2_instances = { j.instance_id: j for j in ec2.instances.filter(InstanceIds=instance_ids) } for j_instance in self["Instances"]: instance_id = j_instance["InstanceId"] j_instance["ec2.ImageId"] = ec2_instances[ instance_id ].image_id j_instance["ec2.State"] = get_resource_attr( ec2_instances[instance_id], "state:Name" ) j_instance["image.name"] = get_resource_attr( ec2_instances[instance_id], "image.name" ) j_instance["elb.HealthStatus"] = elb_health.get( instance_id, "?" ) instance_refreshes = autoscaling.describe_instance_refreshes( AutoScalingGroupName=asg_name ) instance_refreshes = instance_refreshes["InstanceRefreshes"] self["InstanceRefreshes"] = instance_refreshes return result def start_instance_refresh(self): """ Replaces instances using ASG "instance refresh" feature. """ asg_name = self["AutoScalingGroupName"] return autoscaling.start_instance_refresh( AutoScalingGroupName=asg_name, Strategy="Rolling", Preferences={ "MinHealthyPercentage": 50, "InstanceWarmup": 120, # 'CheckpointPercentages': [50,], # 'CheckpointDelay': 60 }, ) def update(self, desired_capacity, max_size): """ Replaces instances using a custom algorithm: * DOUBLE the number of instances; * WAIT for the new instances to take over; * HALVE the number of instances back to normal; """ autoscaling.update_auto_scaling_group( AutoScalingGroupName=self["AutoScalingGroupName"], DesiredCapacity=desired_capacity, MaxSize=max_size, ) PROFILE_MAP = { "sandbox": "mi-sandbox", "dev": "mi-dev", "stage": "mi-stage", "qa": "mi-qa", "peb": "tier3", } profile_name = asg_filter.split("-") profile_name = PROFILE_MAP.get( profile_name[1], PROFILE_MAP.get(profile_name[0], profile_name[0]) ) session = boto3.Session(profile_name=profile_name, region_name=region) autoscaling = session.client("autoscaling") ec2 = session.resource("ec2") elb = session.client("elbv2") result = [] for i_autoscaling_group in autoscaling.describe_auto_scaling_groups()[ "AutoScalingGroups" ]: asg_name = i_autoscaling_group["AutoScalingGroupName"] if not asg_name.startswith(asg_filter): continue autoscaling_group = ASG(i_autoscaling_group) result.append(autoscaling_group) if not result: print( f"WARNING: No autoscaling group matches the given name: {asg_filter}" ) return result def handle_instance_refreshes(asg): """ Handles instace-refreshes associated with the given ASG. Returns True if there's any instance-refresh in progress. """ result = False for j_refresh in asg["InstanceRefreshes"]: if j_refresh["Status"] in ["Pending", "InProgress"]: result = True print( f" >> NOTICE: Instance refresh in progress: {j_refresh.get('StatusReason', '')}" ) elif j_refresh["Status"] == "Successful": # Ignore successful instance refreshes. pass else: raise RuntimeError( f"Instance refresh in an unkonwn state: {j_refresh}" ) return result def handle_autoscaling_instances(asg, image_id_asg): """ Check if any instance associated with the ASG is running with a AMI different from the one specificed on ASG. Returns whether the ASG needs refresh. """ STATUS = { True: "outdated", False: "ok", } result = False for j_instance in asg["Instances"]: outdated = j_instance["ec2.ImageId"] != image_id_asg status = STATUS[outdated] result = result or outdated print( f" - {j_instance['InstanceId']} ({j_instance['image.name']}): {j_instance.get('elb.HealthStatus', '?')} {j_instance['ec2.State']} ==> {status} ", ) return result
zops.aws
/zops.aws-1.0.0-py3-none-any.whl/zops/aws/cluster.py
cluster.py
import copy import datetime import functools import json import os import subprocess import time from operator import attrgetter from pathlib import Path import boto3 import click import dateutil import yaml from .image import Image from .utils import get_resource_attr class AutoScalingGroup: PROFILE_MAP = {} @classmethod def list_groups(cls, asg_seed, region): """ Returns a list of dictionary representing autoscaling groups with some extra information: * [ImageId]: The AMI id associated with the ASG. * [Instances]: A list of associated EC2 instances. * [InstanceRefreshes]: A list of associated instance refreshes. * start_instance_refresh: A method that starts the instance-refresh. """ profile_name = asg_seed.split("-") profile_name = cls.PROFILE_MAP.get( profile_name[1], cls.PROFILE_MAP.get(profile_name[0], profile_name[0]) ) print(f"AWS_PROFILE={profile_name}") print(f"AWS_REGION={region}") session = boto3.Session( profile_name=profile_name, region_name=region ) autoscaling = session.client("autoscaling") result = [] autoscaling_groups = autoscaling.describe_auto_scaling_groups() for i_autoscaling_group in autoscaling_groups["AutoScalingGroups"]: asg_name = i_autoscaling_group["AutoScalingGroupName"] if not asg_name.startswith(asg_seed): continue autoscaling_group = cls(session, i_autoscaling_group) result.append(autoscaling_group) if not result: print( f"WARNING: No autoscaling group matches the given name: {asg_seed}" ) return result def __init__(self, session, asg_dict): self._session = session ec2_resource = self._session.resource("ec2") elbv2_client = self._session.client("elbv2") autoscaling_client = self._session.client("autoscaling") self.name = asg_dict["AutoScalingGroupName"] self.desired_capacity = asg_dict["DesiredCapacity"] self.max_size = asg_dict["MaxSize"] image_id = self._get_image_id_from_launch_data(self._session, asg_dict) self.image = Image.from_image_id(session, image_id) # Create a map from ec2 instance id to their health status in this # autoscaling group. try: elb_health = { i["Target"]["Id"]: i["TargetHealth"]["State"] for i in elbv2_client.describe_target_health( TargetGroupArn=asg_dict["TargetGroupARNs"][0] )["TargetHealthDescriptions"] } except IndexError: elb_health = {} # TODO: Replace these dicts wiht Instance objects. self._instances = asg_dict["Instances"] instance_ids = [i["InstanceId"] for i in self._instances] if instance_ids: ec2_instances = { j.instance_id: j for j in ec2_resource.instances.filter(InstanceIds=instance_ids) } for j_instance in self._instances: instance_id = j_instance["InstanceId"] j_instance["ec2.ImageId"] = ec2_instances[ instance_id ].image_id j_instance["ec2.State"] = get_resource_attr( ec2_instances[instance_id], "state:Name" ) j_instance["image.name"] = get_resource_attr( ec2_instances[instance_id], "image.name" ) j_instance["elb.HealthStatus"] = elb_health.get( instance_id, "?" ) instance_refreshes = autoscaling_client.describe_instance_refreshes( AutoScalingGroupName=self.name ) self._instance_refreshes = instance_refreshes["InstanceRefreshes"] def print(self): """ Check if any instance associated with the ASG is running with a AMI different from the one specificed on ASG. Returns whether the ASG needs refresh. """ STATUS = { True: "outdated", False: "updated", } result = False print( f"\n{self.name} ({self.image.name}) - ({self.desired_capacity} of {self.max_size})" ) for j_instance in self._instances: outdated = j_instance["ec2.ImageId"] != self.image.image_id status = STATUS[outdated] result = result or outdated print( f" - {j_instance['InstanceId']} ({j_instance['image.name']}): {j_instance.get('elb.HealthStatus', '?')} {j_instance['ec2.State']} ==> {status} ", ) return result @classmethod def _get_image_id_from_launch_data(cls, session, asg_dict): autoscaling_client = session.client("autoscaling") ec2_client = session.client("ec2") if "LaunchConfigurationName" in asg_dict: launch_configurations = ( autoscaling_client.describe_launch_configurations( LaunchConfigurationNames=[ asg_dict["LaunchConfigurationName"] ] )["LaunchConfigurations"] ) return launch_configurations[0]["ImageId"] else: launch_template_id = asg_dict["LaunchTemplate"]["LaunchTemplateId"] launch_template = ec2_client.describe_launch_templates( LaunchTemplateIds=[launch_template_id] ) launch_template_version = launch_template["LaunchTemplates"][0]["LatestVersionNumber"] launch_template_version = ( ec2_client.describe_launch_template_versions( LaunchTemplateId=launch_template_id, Versions=[str(launch_template_version)], ) ) return launch_template_version["LaunchTemplateVersions"][0]["LaunchTemplateData"]["ImageId"] def start_instance_refresh(self): """ Replaces instances using ASG "instance refresh" feature. """ asg_name = self["AutoScalingGroupName"] return self._autoscaling_client.start_instance_refresh( AutoScalingGroupName=asg_name, Strategy="Rolling", Preferences={ "MinHealthyPercentage": 50, "InstanceWarmup": 120, # 'CheckpointPercentages': [50,], # 'CheckpointDelay': 60 }, ) def update(self, desired_capacity): """ Replaces instances using a custom algorithm: * DOUBLE the number of instances; * WAIT for the new instances to take over; * HALVE the number of instances back to normal; """ autoscaling_client = self._session.client("autoscaling") autoscaling_client.update_auto_scaling_group( AutoScalingGroupName=self.name, DesiredCapacity=desired_capacity, MaxSize=max(self.max_size, desired_capacity), ) # def handle_instance_refreshes(asg): # """ # Handles instace-refreshes associated with the given ASG. # # Returns True if there's any instance-refresh in progress. # """ # result = False # for j_refresh in asg["InstanceRefreshes"]: # if j_refresh["Status"] in ["Pending", "InProgress"]: # result = True # print( # f" >> NOTICE: Instance refresh in progress: {j_refresh.get('StatusReason', '')}" # ) # elif j_refresh["Status"] == "Successful": # # Ignore successful instance refreshes. # pass # else: # raise RuntimeError( # f"Instance refresh in an unkonwn state: {j_refresh}" # ) # return result # # # def handle_autoscaling_instances(asg, image_id_asg): # """ # Check if any instance associated with the ASG is running with a AMI # different from the one specificed on ASG. # # Returns whether the ASG needs refresh. # """ # # STATUS = { # True: "outdated", # False: "ok", # } # # result = False # for j_instance in asg["Instances"]: # outdated = j_instance["ec2.ImageId"] != image_id_asg # status = STATUS[outdated] # result = result or outdated # print( # f" - {j_instance['InstanceId']} ({j_instance['image.name']}): {j_instance.get('elb.HealthStatus', '?')} {j_instance['ec2.State']} ==> {status} ", # ) # return result
zops.aws
/zops.aws-1.0.0-py3-none-any.whl/zops/aws/autoscaling.py
autoscaling.py
import boto3 from .utils import get_resource_attr class Image: """ Encapsulates a AMI Image object with the following characteristics: * Only holds a subset of boto3's ami object; * This object has two modes: * One, reflects an existing AMI in a AWS cluster (image_id is not None); * The other, it holds information for objects not yet available on AWS. * This object fullfil the following objectives: * List AMI images; * Build, Copy, Tag and Share images. """ _ATTRS = [ "image_id", "image_os", "name", ("tag_name", "tags:Name"), ("tag_version", "tags:Version"), "owner_id", "creation_date", "state", # Meta information "profile", "region", ] def __init__(self, **kwargs): for i_name, i_seed in self._iter_attrs(): setattr(self, i_name, kwargs.get(i_name)) def __str__(self): return f"<Image {self.display_name} profile={self.profile} image_id={self.image_id}>" @classmethod def _iter_attrs(cls): for i_attr in cls._ATTRS: if not isinstance(i_attr, tuple): i_attr = (i_attr, i_attr) yield i_attr @classmethod def from_image_id(cls, session, image_id): return cls.from_aws_ami(session.resource("ec2").Image(image_id)) @classmethod def from_aws_ami(cls, aws_ami, region="INVALID", profile="INVALID"): """ Create an Image instance from a AWS AMI instance. """ d = {} for i_name, i_seed in cls._iter_attrs(): d[i_name] = get_resource_attr(aws_ami, i_seed) d.update( { "region": region, "profile": profile, } ) return cls(**d) def split_name(self): assert self.name is not None result = self.name.split("-")[2:4] if len(result) == 1: result = ["", result[0]] return result @property def exists(self): return self.image_id is not None @property def tagged(self): return self.tag_name is None or self.tag_version is None @property def full_name(self): return ( self.name or f"motoinsight-{self.image_os}-{self.tag_name}-{self.tag_version}" ) @property def display_name(self): return f"{self.full_name} @ {self.profile}:{self.region}" def msg(self, msg): """ Print a message prefixed with this image name and region. """ print(f"* {self.display_name}: {msg}") def share_with(self, aws_id, yes=False): """ Share this image with the target account. """ if not yes: print( f"$ aws ec2 modify-image_attribute {self.full_name} ==> Add UserId={aws_id}" ) return session = boto3.Session( profile_name=self.profile, region_name=self.region ) ec2 = session.client("ec2") ec2.modify_image_attribute( ImageId=self.image_id, LaunchPermission=dict(Add=[dict(UserId=str(aws_id))]), ) def deregister(self, yes=False): if not self.exists: return if not yes: print(f"$ aws ec2 deregister-image --image-id={self.image_id}") return session = boto3.Session( profile_name=self.profile, region_name=self.region ) ec2 = session.client("ec2") ec2.deregister_image(ImageId=self.image_id) def auto_tag(self, yes=False): """ Update 'Name' and 'Version' tags based on image name. """ if not yes: print("$ aws ec2 create-tags...") return if not self.exists: self.msg("ERROR: Image does not exist on AWS Cluster.") return if self.tagged: self.msg("NOTE: Image already tagged.") return self.msg("TAG") session = boto3.Session( profile_name=self.profile, region_name=self.region ) ec2_client = session.client("ec2") tag_name, tag_version = self.full_name.split("-")[2:4] ec2_client.create_tags( Resources=[self.image_id], Tags=[ {"Key": "Name", "Value": tag_name}, {"Key": "Version", "Value": tag_version}, ], )
zops.aws
/zops.aws-1.0.0-py3-none-any.whl/zops/aws/image.py
image.py
# zops.jenkins_jobs Manage the creation of jenkins jobs. Organize your [Jenkins](jenkins.io) jobs right inside your code. A typical projetct usinhg zops.jenkins_jobs directory would look like this: ``` /jenkins-jobs Jenkinsfile branch.yml jenkins-jobs.ini ``` ### branch.yml ```YAML - job: name: zops.jenkins_jobs__{branch} project-type: pipeline pipeline: script-path: jenkins-jobs/Jenkinsfile scm: - git: url: '[email protected]:zerotk/zops.jenkins_jobs' credentials-id: 'XXX-YYY' skip-tag: true wipe-workspace: false branches: - '*/{branch}' ``` * The {setup.name} and {setup.url} variable are obtained from setup.py; * The {git.branch} variable is obtained from the git repository; ``` With the following command line you can create the job in your Jenkins server: ```bash $ zops jobs create ```
zops.code-standards
/zops.code_standards-0.1.0.tar.gz/zops.code_standards-0.1.0/README.md
README.md
# zops.jenkins_jobs Manage the creation of jenkins jobs. Organize your [Jenkins](jenkins.io) jobs right inside your code. A typical projetct usinhg zops.jenkins_jobs directory would look like this: ``` /jenkins-jobs Jenkinsfile branch.yml jenkins-jobs.ini ``` ### branch.yml ```YAML - job: name: zops.jenkins_jobs__{branch} project-type: pipeline pipeline: script-path: jenkins-jobs/Jenkinsfile scm: - git: url: '[email protected]:zerotk/zops.jenkins_jobs' credentials-id: 'XXX-YYY' skip-tag: true wipe-workspace: false branches: - '*/{branch}' ``` * The {setup.name} and {setup.url} variable are obtained from setup.py; * The {git.branch} variable is obtained from the git repository; ``` With the following command line you can create the job in your Jenkins server: ```bash $ zops jobs create ```
zops.jenkins-jobs
/zops.jenkins_jobs-0.5.0.tar.gz/zops.jenkins_jobs-0.5.0/README.md
README.md
# zops.requirements_directory This plugin for [zops](https://github.com/zerotk/zops) adds suport to manage Python requirements in a directory, using [pip-tools](https://github.com/nvie/pip-tools). ## Instalation ```bash $ pip install zops.requirements_directory ``` ## Usage Place your python dependencies files inside the `requirements` directory, using the `.in` exension. Declare the dependencies with minimal version references. ``` /requirements /production.in /development.in ``` Use the `req compile` command to generate the final `.txt` files, with pinned versions: ```bash $ zops req compile /requirements/production.txt (sources: /requirements/production.in) /requirements/development.txt (sources: /requirements/development.in, /requirements/production.in) ``` Use the `--update` option to also update all the dependencies versions. ```bash $ zops req compile --update ``` ## Include directive You can "include" other ".in" files using the include directive as follows: ``` #!INCLUDE production.in ``` # Examples ### requirements/production.in ``` django ``` ### requirements/development.in ``` #!INCLUDE production.in zops.requirements_directory pytest-django ```
zops.requirements-directory
/zops.requirements_directory-1.2.0.tar.gz/zops.requirements_directory-1.2.0/README.md
README.md
import os import click from zerotk.zops import Console from zerotk.lib.path import popd click.disable_unicode_literals_warning = True @click.group('requirements-directory') def main(): pass @main.command() @click.option('--update', is_flag=True, help='Updates all libraries versions.') def compile(update): """ Update requirements """ def _pip_compile(*args): """ Performs pip-compile (from piptools) with a twist. We force editable requirements to use GIT repository (parameter obtain=True) so we have setuptools_scm working on them (axado.runner uses setuptools_scm). """ from contextlib import contextmanager @contextmanager def replaced_argv(args): import sys argv = sys.argv sys.argv = [''] + list(args) yield sys.argv = argv from pip.req.req_install import InstallRequirement try: InstallRequirement.update_editable_ except AttributeError: InstallRequirement.update_editable_ = InstallRequirement.update_editable InstallRequirement.update_editable = lambda s, _o: InstallRequirement.update_editable_(s, True) with replaced_argv(args): from piptools.scripts.compile import cli try: cli() except SystemExit as e: return e.code base_params = ['--no-index', '--no-emit-trusted-host', '-r'] if update: base_params += ['-U'] from glob import glob for i_filename in glob('requirements/*.in'): output_filename = get_output_filename(i_filename) input_filenames = get_input_filenames(i_filename) temporary_dependencies = get_temporary_dependencies(i_filename) Console.info('{}: generating from {}'.format(output_filename, ', '.join(input_filenames))) params = base_params + input_filenames + ['-o', output_filename] Console.execution('pip-compile {}'.format(' '.join(params))) _pip_compile(*params) Console.info('{}: '.format(output_filename)) fixes(output_filename, temporary_dependencies) @main.command() @click.option('--rebuild', is_flag=True, help='Clear any caches upfront, rebuild from scratch.') @click.argument('directories', nargs=-1) @click.pass_context def upgrade(click_context, rebuild, directories): """ New algorithm to upgrade requirements directory. """ from glob import glob # NOTE: Create before the loop to maintain the dependencies-cache. pip_tools = PipTools(click_context) directories = directories or ['.'] for i_directory in directories: for j_filename in glob(os.path.join(i_directory, '**/requirements/*.in'), recursive=True): cwd, filename = j_filename.split('/requirements/') filename = 'requirements/' + filename Console.title(cwd) with popd(cwd): output_filename = get_output_filename(filename) input_filenames = get_input_filenames(filename) temporary_dependencies = get_temporary_dependencies(filename) Console.item(output_filename, ident=1) for k_input_filename in input_filenames: Console.item(k_input_filename, ident=2) pip_tools.compile(output_filename, input_filenames, upgrade=True, rebuild=rebuild) fixes(output_filename, temporary_dependencies) def get_input_filenames(filename): import os result = [] include_lines = [i for i in open(filename, 'r').readlines() if i.startswith('#!INCLUDE')] for i_line in include_lines: included_filename = i_line.split(' ', 1)[-1].strip() included_filename = os.path.join(os.path.dirname(filename), included_filename) result.append(included_filename) result.append(filename) return result def get_temporary_dependencies(filename): """ List all dependencies declared in the input file that must be removed from the generated file (temporary). """ result = [] with open(filename, 'r') as iss: for i_line in iss.readlines(): if '#!TEMPORARY' in i_line: i_line = i_line.rsplit('#')[0] i_line = i_line.strip() result.append(i_line) return result def get_output_filename(filename): import os return os.path.splitext(filename)[0] + '.txt' def fixes(filename, temporary_dependencies): def replace_file_references(line): """ Replaces file:// references by local ones. """ parts = line.split('file://') if len(parts) > 1: ref_path = parts[-1] rel_path = os.path.relpath(ref_path) return '-e {}'.format(rel_path) return line def is_setuptools_dependency(line): """ Remove setuptools dependencies from the generated file. """ return 'via setuptools' in line def is_temporary_dependency(line): """ Remove lines """ for i_temporary_dependency in temporary_dependencies: if i_temporary_dependency in line: return True return False with open(filename, 'r') as iss: lines = iss.readlines() lines = [replace_file_references(i) for i in lines] lines = [i for i in lines if not is_setuptools_dependency(i)] lines = [i for i in lines if not is_temporary_dependency(i)] with open(filename, 'w') as oss: oss.writelines(lines) class PipTools(object): def __init__(self, click_context): from piptools.cache import DependencyCache self.dependency_cache = DependencyCache() # NOTE: Debugging # Show some debugging information. from piptools.logging import log log.verbose = True self.__click_context = click_context def compile(self, dst_file, src_files, upgrade=False, rebuild=False, new_code=False): """ Performs pip-compile (from piptools) with a twist. We force editable requirements to use GIT repository (parameter obtain=True) so we have setuptools_scm working on them (we use setuptools_scm). Not sure this is working with piptools 2.X. """ from pip.req.req_install import InstallRequirement try: InstallRequirement.update_editable_ except AttributeError: InstallRequirement.update_editable_ = InstallRequirement.update_editable InstallRequirement.update_editable = lambda s, _o: InstallRequirement.update_editable_(s, True) from piptools.scripts.compile import cli return self.__click_context.invoke( cli, output_file=dst_file, src_files=src_files, upgrade=upgrade, rebuild=rebuild, emit_trusted_host=False, header=False, index=False, ) if __name__ == '__main__': main()
zops.requirements-directory
/zops.requirements_directory-1.2.0.tar.gz/zops.requirements_directory-1.2.0/zops/requirements_directory/cli.py
cli.py
Produce & Publish Authoring Environment ======================================= The Produce & Publish Authoring Environment is a Plone-based solution for generating high-quality PDF documents from Plone content and office content supporting - managing editorial content - conversion assets - conversion configuration - conversion and publication under one hood. Requirements ------------ - Plone 4.1, 4.2 (untested with Plone 4.3) - installation of the Produce & Publish server (see documentation) - currently supports the commercial PDFreactor and PrinceXML as external PDF converter - support for free PDF generation using PhantomJS upcoming) .. note:: With ``zopyx.authoring`` Version 2.4 or higher you will need to upgrade your Produce & Publish Server to the new ``pp.server`` implementation. Documentation ------------- See http://pythonhosted.org/zopyx.authoring Source code: ------------ - https://bitbucket.org/ajung/zopyx.authoring/src/master/src/zopyx.authoring Issue tracker: -------------- - https://bitbucket.org/ajung/zopyx.authoring/issues License ------- ``Product & Publish Authoring Environment`` is published under the GNU Public License V2 (GPL 2). Contact ------- | ZOPYX Limited | Hundskapfklinge 33 | D-72074 Tuebingen, Germany | [email protected] | www.zopyx.com | www.produce-and-publish.info
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/README.txt
README.txt
.. Produce & Publish Authoring Environment documentation master file, created by sphinx-quickstart on Tue Apr 12 15:26:21 2011. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Welcome to the Produce & Publish documentation. Produce & Publish is a set of components for generating high-quality office-documents, PDF documents or e-books. Produce & Publish Authoring Environment ======================================= .. toctree:: :maxdepth: 3 authoring/installation.rst authoring/manage_content.rst authoring/conversions_center.rst authoring/conversions.rst authoring/supplementary.rst How-Tos ======= .. toctree:: :maxdepth: 1 howto/walkthrough.rst howto/paste_from_word.rst howto/edit_authors.rst howto/s5-customization.rst howto/index-listing.rst Copyright & Credits =================== .. toctree:: :maxdepth: 1 misc/copyright.rst misc/credits.rst
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/docs/source/index.rst
index.rst
!function($){"use strict";$(function(){$.support.transition=function(){var transitionEnd=function(){var name,el=document.createElement("bootstrap"),transEndEventNames={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(name in transEndEventNames)if(void 0!==el.style[name])return transEndEventNames[name]}();return transitionEnd&&{end:transitionEnd}}()})}(window.jQuery),!function($){"use strict";var dismiss='[data-dismiss="alert"]',Alert=function(el){$(el).on("click",dismiss,this.close)};Alert.prototype.close=function(e){function removeElement(){$parent.trigger("closed").remove()}var $parent,$this=$(this),selector=$this.attr("data-target");selector||(selector=$this.attr("href"),selector=selector&&selector.replace(/.*(?=#[^\s]*$)/,"")),$parent=$(selector),e&&e.preventDefault(),$parent.length||($parent=$this.hasClass("alert")?$this:$this.parent()),$parent.trigger(e=$.Event("close")),e.isDefaultPrevented()||($parent.removeClass("in"),$.support.transition&&$parent.hasClass("fade")?$parent.on($.support.transition.end,removeElement):removeElement())};var old=$.fn.alert;$.fn.alert=function(option){return this.each(function(){var $this=$(this),data=$this.data("alert");data||$this.data("alert",data=new Alert(this)),"string"==typeof option&&data[option].call($this)})},$.fn.alert.Constructor=Alert,$.fn.alert.noConflict=function(){return $.fn.alert=old,this},$(document).on("click.alert.data-api",dismiss,Alert.prototype.close)}(window.jQuery),!function($){"use strict";var Button=function(element,options){this.$element=$(element),this.options=$.extend({},$.fn.button.defaults,options)};Button.prototype.setState=function(state){var d="disabled",$el=this.$element,data=$el.data(),val=$el.is("input")?"val":"html";state+="Text",data.resetText||$el.data("resetText",$el[val]()),$el[val](data[state]||this.options[state]),setTimeout(function(){"loadingText"==state?$el.addClass(d).attr(d,d):$el.removeClass(d).removeAttr(d)},0)},Button.prototype.toggle=function(){var $parent=this.$element.closest('[data-toggle="buttons-radio"]');$parent&&$parent.find(".active").removeClass("active"),this.$element.toggleClass("active")};var old=$.fn.button;$.fn.button=function(option){return this.each(function(){var $this=$(this),data=$this.data("button"),options="object"==typeof option&&option;data||$this.data("button",data=new Button(this,options)),"toggle"==option?data.toggle():option&&data.setState(option)})},$.fn.button.defaults={loadingText:"loading..."},$.fn.button.Constructor=Button,$.fn.button.noConflict=function(){return $.fn.button=old,this},$(document).on("click.button.data-api","[data-toggle^=button]",function(e){var $btn=$(e.target);$btn.hasClass("btn")||($btn=$btn.closest(".btn")),$btn.button("toggle")})}(window.jQuery),!function($){"use strict";var Carousel=function(element,options){this.$element=$(element),this.options=options,"hover"==this.options.pause&&this.$element.on("mouseenter",$.proxy(this.pause,this)).on("mouseleave",$.proxy(this.cycle,this))};Carousel.prototype={cycle:function(e){return e||(this.paused=!1),this.options.interval&&!this.paused&&(this.interval=setInterval($.proxy(this.next,this),this.options.interval)),this},to:function(pos){var $active=this.$element.find(".item.active"),children=$active.parent().children(),activePos=children.index($active),that=this;if(!(pos>children.length-1||0>pos))return this.sliding?this.$element.one("slid",function(){that.to(pos)}):activePos==pos?this.pause().cycle():this.slide(pos>activePos?"next":"prev",$(children[pos]))},pause:function(e){return e||(this.paused=!0),this.$element.find(".next, .prev").length&&$.support.transition.end&&(this.$element.trigger($.support.transition.end),this.cycle()),clearInterval(this.interval),this.interval=null,this},next:function(){return this.sliding?void 0:this.slide("next")},prev:function(){return this.sliding?void 0:this.slide("prev")},slide:function(type,next){var e,$active=this.$element.find(".item.active"),$next=next||$active[type](),isCycling=this.interval,direction="next"==type?"left":"right",fallback="next"==type?"first":"last",that=this;if(this.sliding=!0,isCycling&&this.pause(),$next=$next.length?$next:this.$element.find(".item")[fallback](),e=$.Event("slide",{relatedTarget:$next[0]}),!$next.hasClass("active")){if($.support.transition&&this.$element.hasClass("slide")){if(this.$element.trigger(e),e.isDefaultPrevented())return;$next.addClass(type),$next[0].offsetWidth,$active.addClass(direction),$next.addClass(direction),this.$element.one($.support.transition.end,function(){$next.removeClass([type,direction].join(" ")).addClass("active"),$active.removeClass(["active",direction].join(" ")),that.sliding=!1,setTimeout(function(){that.$element.trigger("slid")},0)})}else{if(this.$element.trigger(e),e.isDefaultPrevented())return;$active.removeClass("active"),$next.addClass("active"),this.sliding=!1,this.$element.trigger("slid")}return isCycling&&this.cycle(),this}}};var old=$.fn.carousel;$.fn.carousel=function(option){return this.each(function(){var $this=$(this),data=$this.data("carousel"),options=$.extend({},$.fn.carousel.defaults,"object"==typeof option&&option),action="string"==typeof option?option:options.slide;data||$this.data("carousel",data=new Carousel(this,options)),"number"==typeof option?data.to(option):action?data[action]():options.interval&&data.cycle()})},$.fn.carousel.defaults={interval:5e3,pause:"hover"},$.fn.carousel.Constructor=Carousel,$.fn.carousel.noConflict=function(){return $.fn.carousel=old,this},$(document).on("click.carousel.data-api","[data-slide]",function(e){var href,$this=$(this),$target=$($this.attr("data-target")||(href=$this.attr("href"))&&href.replace(/.*(?=#[^\s]+$)/,"")),options=$.extend({},$target.data(),$this.data());$target.carousel(options),e.preventDefault()})}(window.jQuery),!function($){"use strict";var Collapse=function(element,options){this.$element=$(element),this.options=$.extend({},$.fn.collapse.defaults,options),this.options.parent&&(this.$parent=$(this.options.parent)),this.options.toggle&&this.toggle()};Collapse.prototype={constructor:Collapse,dimension:function(){var hasWidth=this.$element.hasClass("width");return hasWidth?"width":"height"},show:function(){var dimension,scroll,actives,hasData;if(!this.transitioning){if(dimension=this.dimension(),scroll=$.camelCase(["scroll",dimension].join("-")),actives=this.$parent&&this.$parent.find("> .accordion-group > .in"),actives&&actives.length){if(hasData=actives.data("collapse"),hasData&&hasData.transitioning)return;actives.collapse("hide"),hasData||actives.data("collapse",null)}this.$element[dimension](0),this.transition("addClass",$.Event("show"),"shown"),$.support.transition&&this.$element[dimension](this.$element[0][scroll])}},hide:function(){var dimension;this.transitioning||(dimension=this.dimension(),this.reset(this.$element[dimension]()),this.transition("removeClass",$.Event("hide"),"hidden"),this.$element[dimension](0))},reset:function(size){var dimension=this.dimension();return this.$element.removeClass("collapse")[dimension](size||"auto")[0].offsetWidth,this.$element[null!==size?"addClass":"removeClass"]("collapse"),this},transition:function(method,startEvent,completeEvent){var that=this,complete=function(){"show"==startEvent.type&&that.reset(),that.transitioning=0,that.$element.trigger(completeEvent)};this.$element.trigger(startEvent),startEvent.isDefaultPrevented()||(this.transitioning=1,this.$element[method]("in"),$.support.transition&&this.$element.hasClass("collapse")?this.$element.one($.support.transition.end,complete):complete())},toggle:function(){this[this.$element.hasClass("in")?"hide":"show"]()}};var old=$.fn.collapse;$.fn.collapse=function(option){return this.each(function(){var $this=$(this),data=$this.data("collapse"),options="object"==typeof option&&option;data||$this.data("collapse",data=new Collapse(this,options)),"string"==typeof option&&data[option]()})},$.fn.collapse.defaults={toggle:!0},$.fn.collapse.Constructor=Collapse,$.fn.collapse.noConflict=function(){return $.fn.collapse=old,this},$(document).on("click.collapse.data-api","[data-toggle=collapse]",function(e){var href,$this=$(this),target=$this.attr("data-target")||e.preventDefault()||(href=$this.attr("href"))&&href.replace(/.*(?=#[^\s]+$)/,""),option=$(target).data("collapse")?"toggle":$this.data();$this[$(target).hasClass("in")?"addClass":"removeClass"]("collapsed"),$(target).collapse(option)})}(window.jQuery),!function($){"use strict";function clearMenus(){$(toggle).each(function(){getParent($(this)).removeClass("open")})}function getParent($this){var $parent,selector=$this.attr("data-target");return selector||(selector=$this.attr("href"),selector=selector&&/#/.test(selector)&&selector.replace(/.*(?=#[^\s]*$)/,"")),$parent=$(selector),$parent.length||($parent=$this.parent()),$parent}var toggle="[data-toggle=dropdown]",Dropdown=function(element){var $el=$(element).on("click.dropdown.data-api",this.toggle);$("html").on("click.dropdown.data-api",function(){$el.parent().removeClass("open")})};Dropdown.prototype={constructor:Dropdown,toggle:function(){var $parent,isActive,$this=$(this);if(!$this.is(".disabled, :disabled"))return $parent=getParent($this),isActive=$parent.hasClass("open"),clearMenus(),isActive||$parent.toggleClass("open"),$this.focus(),!1},keydown:function(e){var $this,$items,$parent,isActive,index;if(/(38|40|27)/.test(e.keyCode)&&($this=$(this),e.preventDefault(),e.stopPropagation(),!$this.is(".disabled, :disabled"))){if($parent=getParent($this),isActive=$parent.hasClass("open"),!isActive||isActive&&27==e.keyCode)return $this.click();$items=$("[role=menu] li:not(.divider):visible a",$parent),$items.length&&(index=$items.index($items.filter(":focus")),38==e.keyCode&&index>0&&index--,40==e.keyCode&&$items.length-1>index&&index++,~index||(index=0),$items.eq(index).focus())}}};var old=$.fn.dropdown;$.fn.dropdown=function(option){return this.each(function(){var $this=$(this),data=$this.data("dropdown");data||$this.data("dropdown",data=new Dropdown(this)),"string"==typeof option&&data[option].call($this)})},$.fn.dropdown.Constructor=Dropdown,$.fn.dropdown.noConflict=function(){return $.fn.dropdown=old,this},$(document).on("click.dropdown.data-api touchstart.dropdown.data-api",clearMenus).on("click.dropdown touchstart.dropdown.data-api",".dropdown form",function(e){e.stopPropagation()}).on("touchstart.dropdown.data-api",".dropdown-menu",function(e){e.stopPropagation()}).on("click.dropdown.data-api touchstart.dropdown.data-api",toggle,Dropdown.prototype.toggle).on("keydown.dropdown.data-api touchstart.dropdown.data-api",toggle+", [role=menu]",Dropdown.prototype.keydown)}(window.jQuery),!function($){"use strict";var Modal=function(element,options){this.options=options,this.$element=$(element).delegate('[data-dismiss="modal"]',"click.dismiss.modal",$.proxy(this.hide,this)),this.options.remote&&this.$element.find(".modal-body").load(this.options.remote)};Modal.prototype={constructor:Modal,toggle:function(){return this[this.isShown?"hide":"show"]()},show:function(){var that=this,e=$.Event("show");this.$element.trigger(e),this.isShown||e.isDefaultPrevented()||(this.isShown=!0,this.escape(),this.backdrop(function(){var transition=$.support.transition&&that.$element.hasClass("fade");that.$element.parent().length||that.$element.appendTo(document.body),that.$element.show(),transition&&that.$element[0].offsetWidth,that.$element.addClass("in").attr("aria-hidden",!1),that.enforceFocus(),transition?that.$element.one($.support.transition.end,function(){that.$element.focus().trigger("shown")}):that.$element.focus().trigger("shown")}))},hide:function(e){e&&e.preventDefault(),e=$.Event("hide"),this.$element.trigger(e),this.isShown&&!e.isDefaultPrevented()&&(this.isShown=!1,this.escape(),$(document).off("focusin.modal"),this.$element.removeClass("in").attr("aria-hidden",!0),$.support.transition&&this.$element.hasClass("fade")?this.hideWithTransition():this.hideModal())},enforceFocus:function(){var that=this;$(document).on("focusin.modal",function(e){that.$element[0]===e.target||that.$element.has(e.target).length||that.$element.focus()})},escape:function(){var that=this;this.isShown&&this.options.keyboard?this.$element.on("keyup.dismiss.modal",function(e){27==e.which&&that.hide()}):this.isShown||this.$element.off("keyup.dismiss.modal")},hideWithTransition:function(){var that=this,timeout=setTimeout(function(){that.$element.off($.support.transition.end),that.hideModal()},500);this.$element.one($.support.transition.end,function(){clearTimeout(timeout),that.hideModal()})},hideModal:function(){this.$element.hide().trigger("hidden"),this.backdrop()},removeBackdrop:function(){this.$backdrop.remove(),this.$backdrop=null},backdrop:function(callback){var animate=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var doAnimate=$.support.transition&&animate;this.$backdrop=$('<div class="modal-backdrop '+animate+'" />').appendTo(document.body),this.$backdrop.click("static"==this.options.backdrop?$.proxy(this.$element[0].focus,this.$element[0]):$.proxy(this.hide,this)),doAnimate&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),doAnimate?this.$backdrop.one($.support.transition.end,callback):callback()}else!this.isShown&&this.$backdrop?(this.$backdrop.removeClass("in"),$.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one($.support.transition.end,$.proxy(this.removeBackdrop,this)):this.removeBackdrop()):callback&&callback()}};var old=$.fn.modal;$.fn.modal=function(option){return this.each(function(){var $this=$(this),data=$this.data("modal"),options=$.extend({},$.fn.modal.defaults,$this.data(),"object"==typeof option&&option);data||$this.data("modal",data=new Modal(this,options)),"string"==typeof option?data[option]():options.show&&data.show()})},$.fn.modal.defaults={backdrop:!0,keyboard:!0,show:!0},$.fn.modal.Constructor=Modal,$.fn.modal.noConflict=function(){return $.fn.modal=old,this},$(document).on("click.modal.data-api",'[data-toggle="modal"]',function(e){var $this=$(this),href=$this.attr("href"),$target=$($this.attr("data-target")||href&&href.replace(/.*(?=#[^\s]+$)/,"")),option=$target.data("modal")?"toggle":$.extend({remote:!/#/.test(href)&&href},$target.data(),$this.data());e.preventDefault(),$target.modal(option).one("hide",function(){$this.focus()})})}(window.jQuery),!function($){"use strict";var Tooltip=function(element,options){this.init("tooltip",element,options)};Tooltip.prototype={constructor:Tooltip,init:function(type,element,options){var eventIn,eventOut;this.type=type,this.$element=$(element),this.options=this.getOptions(options),this.enabled=!0,"click"==this.options.trigger?this.$element.on("click."+this.type,this.options.selector,$.proxy(this.toggle,this)):"manual"!=this.options.trigger&&(eventIn="hover"==this.options.trigger?"mouseenter":"focus",eventOut="hover"==this.options.trigger?"mouseleave":"blur",this.$element.on(eventIn+"."+this.type,this.options.selector,$.proxy(this.enter,this)),this.$element.on(eventOut+"."+this.type,this.options.selector,$.proxy(this.leave,this))),this.options.selector?this._options=$.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},getOptions:function(options){return options=$.extend({},$.fn[this.type].defaults,options,this.$element.data()),options.delay&&"number"==typeof options.delay&&(options.delay={show:options.delay,hide:options.delay}),options},enter:function(e){var self=$(e.currentTarget)[this.type](this._options).data(this.type);return self.options.delay&&self.options.delay.show?(clearTimeout(this.timeout),self.hoverState="in",this.timeout=setTimeout(function(){"in"==self.hoverState&&self.show()},self.options.delay.show),void 0):self.show()},leave:function(e){var self=$(e.currentTarget)[this.type](this._options).data(this.type);return this.timeout&&clearTimeout(this.timeout),self.options.delay&&self.options.delay.hide?(self.hoverState="out",this.timeout=setTimeout(function(){"out"==self.hoverState&&self.hide()},self.options.delay.hide),void 0):self.hide()},show:function(){var $tip,inside,pos,actualWidth,actualHeight,placement,tp;if(this.hasContent()&&this.enabled){switch($tip=this.tip(),this.setContent(),this.options.animation&&$tip.addClass("fade"),placement="function"==typeof this.options.placement?this.options.placement.call(this,$tip[0],this.$element[0]):this.options.placement,inside=/in/.test(placement),$tip.detach().css({top:0,left:0,display:"block"}).insertAfter(this.$element),pos=this.getPosition(inside),actualWidth=$tip[0].offsetWidth,actualHeight=$tip[0].offsetHeight,inside?placement.split(" ")[1]:placement){case"bottom":tp={top:pos.top+pos.height,left:pos.left+pos.width/2-actualWidth/2};break;case"top":tp={top:pos.top-actualHeight,left:pos.left+pos.width/2-actualWidth/2};break;case"left":tp={top:pos.top+pos.height/2-actualHeight/2,left:pos.left-actualWidth};break;case"right":tp={top:pos.top+pos.height/2-actualHeight/2,left:pos.left+pos.width}}$tip.offset(tp).addClass(placement).addClass("in")}},setContent:function(){var $tip=this.tip(),title=this.getTitle();$tip.find(".tooltip-inner")[this.options.html?"html":"text"](title),$tip.removeClass("fade in top bottom left right")},hide:function(){function removeWithAnimation(){var timeout=setTimeout(function(){$tip.off($.support.transition.end).detach()},500);$tip.one($.support.transition.end,function(){clearTimeout(timeout),$tip.detach()})}var $tip=this.tip();return $tip.removeClass("in"),$.support.transition&&this.$tip.hasClass("fade")?removeWithAnimation():$tip.detach(),this},fixTitle:function(){var $e=this.$element;($e.attr("title")||"string"!=typeof $e.attr("data-original-title"))&&$e.attr("data-original-title",$e.attr("title")||"").removeAttr("title")},hasContent:function(){return this.getTitle()},getPosition:function(inside){return $.extend({},inside?{top:0,left:0}:this.$element.offset(),{width:this.$element[0].offsetWidth,height:this.$element[0].offsetHeight})},getTitle:function(){var title,$e=this.$element,o=this.options;return title=$e.attr("data-original-title")||("function"==typeof o.title?o.title.call($e[0]):o.title)},tip:function(){return this.$tip=this.$tip||$(this.options.template)},validate:function(){this.$element[0].parentNode||(this.hide(),this.$element=null,this.options=null)},enable:function(){this.enabled=!0},disable:function(){this.enabled=!1},toggleEnabled:function(){this.enabled=!this.enabled},toggle:function(e){var self=$(e.currentTarget)[this.type](this._options).data(this.type);self[self.tip().hasClass("in")?"hide":"show"]()},destroy:function(){this.hide().$element.off("."+this.type).removeData(this.type)}};var old=$.fn.tooltip;$.fn.tooltip=function(option){return this.each(function(){var $this=$(this),data=$this.data("tooltip"),options="object"==typeof option&&option;data||$this.data("tooltip",data=new Tooltip(this,options)),"string"==typeof option&&data[option]()})},$.fn.tooltip.Constructor=Tooltip,$.fn.tooltip.defaults={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover",title:"",delay:0,html:!1},$.fn.tooltip.noConflict=function(){return $.fn.tooltip=old,this}}(window.jQuery),!function($){"use strict";var Popover=function(element,options){this.init("popover",element,options)};Popover.prototype=$.extend({},$.fn.tooltip.Constructor.prototype,{constructor:Popover,setContent:function(){var $tip=this.tip(),title=this.getTitle(),content=this.getContent();$tip.find(".popover-title")[this.options.html?"html":"text"](title),$tip.find(".popover-content")[this.options.html?"html":"text"](content),$tip.removeClass("fade top bottom left right in")},hasContent:function(){return this.getTitle()||this.getContent()},getContent:function(){var content,$e=this.$element,o=this.options;return content=$e.attr("data-content")||("function"==typeof o.content?o.content.call($e[0]):o.content)},tip:function(){return this.$tip||(this.$tip=$(this.options.template)),this.$tip},destroy:function(){this.hide().$element.off("."+this.type).removeData(this.type)}});var old=$.fn.popover;$.fn.popover=function(option){return this.each(function(){var $this=$(this),data=$this.data("popover"),options="object"==typeof option&&option;data||$this.data("popover",data=new Popover(this,options)),"string"==typeof option&&data[option]()})},$.fn.popover.Constructor=Popover,$.fn.popover.defaults=$.extend({},$.fn.tooltip.defaults,{placement:"right",trigger:"click",content:"",template:'<div class="popover"><div class="arrow"></div><div class="popover-inner"><h3 class="popover-title"></h3><div class="popover-content"></div></div></div>'}),$.fn.popover.noConflict=function(){return $.fn.popover=old,this}}(window.jQuery),!function($){"use strict";function ScrollSpy(element,options){var href,process=$.proxy(this.process,this),$element=$(element).is("body")?$(window):$(element);this.options=$.extend({},$.fn.scrollspy.defaults,options),this.$scrollElement=$element.on("scroll.scroll-spy.data-api",process),this.selector=(this.options.target||(href=$(element).attr("href"))&&href.replace(/.*(?=#[^\s]+$)/,"")||"")+" .nav li > a",this.$body=$("body"),this.refresh(),this.process()}ScrollSpy.prototype={constructor:ScrollSpy,refresh:function(){var $targets,self=this;this.offsets=$([]),this.targets=$([]),$targets=this.$body.find(this.selector).map(function(){var $el=$(this),href=$el.data("target")||$el.attr("href"),$href=/^#\w/.test(href)&&$(href);return $href&&$href.length&&[[$href.position().top+self.$scrollElement.scrollTop(),href]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){self.offsets.push(this[0]),self.targets.push(this[1])})},process:function(){var i,scrollTop=this.$scrollElement.scrollTop()+this.options.offset,scrollHeight=this.$scrollElement[0].scrollHeight||this.$body[0].scrollHeight,maxScroll=scrollHeight-this.$scrollElement.height(),offsets=this.offsets,targets=this.targets,activeTarget=this.activeTarget;if(scrollTop>=maxScroll)return activeTarget!=(i=targets.last()[0])&&this.activate(i);for(i=offsets.length;i--;)activeTarget!=targets[i]&&scrollTop>=offsets[i]&&(!offsets[i+1]||offsets[i+1]>=scrollTop)&&this.activate(targets[i])},activate:function(target){var active,selector;this.activeTarget=target,$(this.selector).parent(".active").removeClass("active"),selector=this.selector+'[data-target="'+target+'"],'+this.selector+'[href="'+target+'"]',active=$(selector).parent("li").addClass("active"),active.parent(".dropdown-menu").length&&(active=active.closest("li.dropdown").addClass("active")),active.trigger("activate")}};var old=$.fn.scrollspy;$.fn.scrollspy=function(option){return this.each(function(){var $this=$(this),data=$this.data("scrollspy"),options="object"==typeof option&&option;data||$this.data("scrollspy",data=new ScrollSpy(this,options)),"string"==typeof option&&data[option]()})},$.fn.scrollspy.Constructor=ScrollSpy,$.fn.scrollspy.defaults={offset:10},$.fn.scrollspy.noConflict=function(){return $.fn.scrollspy=old,this},$(window).on("load",function(){$('[data-spy="scroll"]').each(function(){var $spy=$(this);$spy.scrollspy($spy.data())})})}(window.jQuery),!function($){"use strict";var Tab=function(element){this.element=$(element)};Tab.prototype={constructor:Tab,show:function(){var previous,$target,e,$this=this.element,$ul=$this.closest("ul:not(.dropdown-menu)"),selector=$this.attr("data-target");selector||(selector=$this.attr("href"),selector=selector&&selector.replace(/.*(?=#[^\s]*$)/,"")),$this.parent("li").hasClass("active")||(previous=$ul.find(".active:last a")[0],e=$.Event("show",{relatedTarget:previous}),$this.trigger(e),e.isDefaultPrevented()||($target=$(selector),this.activate($this.parent("li"),$ul),this.activate($target,$target.parent(),function(){$this.trigger({type:"shown",relatedTarget:previous})})))},activate:function(element,container,callback){function next(){$active.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"),element.addClass("active"),transition?(element[0].offsetWidth,element.addClass("in")):element.removeClass("fade"),element.parent(".dropdown-menu")&&element.closest("li.dropdown").addClass("active"),callback&&callback()}var $active=container.find("> .active"),transition=callback&&$.support.transition&&$active.hasClass("fade");transition?$active.one($.support.transition.end,next):next(),$active.removeClass("in")}};var old=$.fn.tab;$.fn.tab=function(option){return this.each(function(){var $this=$(this),data=$this.data("tab");data||$this.data("tab",data=new Tab(this)),"string"==typeof option&&data[option]()})},$.fn.tab.Constructor=Tab,$.fn.tab.noConflict=function(){return $.fn.tab=old,this},$(document).on("click.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"]',function(e){e.preventDefault(),$(this).tab("show")})}(window.jQuery),!function($){"use strict";var Typeahead=function(element,options){this.$element=$(element),this.options=$.extend({},$.fn.typeahead.defaults,options),this.matcher=this.options.matcher||this.matcher,this.sorter=this.options.sorter||this.sorter,this.highlighter=this.options.highlighter||this.highlighter,this.updater=this.options.updater||this.updater,this.source=this.options.source,this.$menu=$(this.options.menu),this.shown=!1,this.listen()};Typeahead.prototype={constructor:Typeahead,select:function(){var val=this.$menu.find(".active").attr("data-value");return this.$element.val(this.updater(val)).change(),this.hide()},updater:function(item){return item},show:function(){var pos=$.extend({},this.$element.position(),{height:this.$element[0].offsetHeight});return this.$menu.insertAfter(this.$element).css({top:pos.top+pos.height,left:pos.left}).show(),this.shown=!0,this},hide:function(){return this.$menu.hide(),this.shown=!1,this},lookup:function(){var items;return this.query=this.$element.val(),!this.query||this.query.length<this.options.minLength?this.shown?this.hide():this:(items=$.isFunction(this.source)?this.source(this.query,$.proxy(this.process,this)):this.source,items?this.process(items):this)},process:function(items){var that=this;return items=$.grep(items,function(item){return that.matcher(item)}),items=this.sorter(items),items.length?this.render(items.slice(0,this.options.items)).show():this.shown?this.hide():this},matcher:function(item){return~item.toLowerCase().indexOf(this.query.toLowerCase())},sorter:function(items){for(var item,beginswith=[],caseSensitive=[],caseInsensitive=[];item=items.shift();)item.toLowerCase().indexOf(this.query.toLowerCase())?~item.indexOf(this.query)?caseSensitive.push(item):caseInsensitive.push(item):beginswith.push(item);return beginswith.concat(caseSensitive,caseInsensitive)},highlighter:function(item){var query=this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&");return item.replace(RegExp("("+query+")","ig"),function($1,match){return"<strong>"+match+"</strong>"})},render:function(items){var that=this;return items=$(items).map(function(i,item){return i=$(that.options.item).attr("data-value",item),i.find("a").html(that.highlighter(item)),i[0]}),items.first().addClass("active"),this.$menu.html(items),this},next:function(){var active=this.$menu.find(".active").removeClass("active"),next=active.next();next.length||(next=$(this.$menu.find("li")[0])),next.addClass("active")},prev:function(){var active=this.$menu.find(".active").removeClass("active"),prev=active.prev();prev.length||(prev=this.$menu.find("li").last()),prev.addClass("active")},listen:function(){this.$element.on("blur",$.proxy(this.blur,this)).on("keypress",$.proxy(this.keypress,this)).on("keyup",$.proxy(this.keyup,this)),this.eventSupported("keydown")&&this.$element.on("keydown",$.proxy(this.keydown,this)),this.$menu.on("click",$.proxy(this.click,this)).on("mouseenter","li",$.proxy(this.mouseenter,this))},eventSupported:function(eventName){var isSupported=eventName in this.$element;return isSupported||(this.$element.setAttribute(eventName,"return;"),isSupported="function"==typeof this.$element[eventName]),isSupported},move:function(e){if(this.shown){switch(e.keyCode){case 9:case 13:case 27:e.preventDefault();break;case 38:e.preventDefault(),this.prev();break;case 40:e.preventDefault(),this.next()}e.stopPropagation()}},keydown:function(e){this.suppressKeyPressRepeat=~$.inArray(e.keyCode,[40,38,9,13,27]),this.move(e)},keypress:function(e){this.suppressKeyPressRepeat||this.move(e)},keyup:function(e){switch(e.keyCode){case 40:case 38:case 16:case 17:case 18:break;case 9:case 13:if(!this.shown)return;this.select();break;case 27:if(!this.shown)return;this.hide();break;default:this.lookup()}e.stopPropagation(),e.preventDefault()},blur:function(){var that=this;setTimeout(function(){that.hide()},150)},click:function(e){e.stopPropagation(),e.preventDefault(),this.select()},mouseenter:function(e){this.$menu.find(".active").removeClass("active"),$(e.currentTarget).addClass("active")}};var old=$.fn.typeahead;$.fn.typeahead=function(option){return this.each(function(){var $this=$(this),data=$this.data("typeahead"),options="object"==typeof option&&option;data||$this.data("typeahead",data=new Typeahead(this,options)),"string"==typeof option&&data[option]()})},$.fn.typeahead.defaults={source:[],items:8,menu:'<ul class="typeahead dropdown-menu"></ul>',item:'<li><a href="#"></a></li>',minLength:1},$.fn.typeahead.Constructor=Typeahead,$.fn.typeahead.noConflict=function(){return $.fn.typeahead=old,this},$(document).on("focus.typeahead.data-api",'[data-provide="typeahead"]',function(e){var $this=$(this);$this.data("typeahead")||(e.preventDefault(),$this.typeahead($this.data()))})}(window.jQuery),!function($){"use strict";var Affix=function(element,options){this.options=$.extend({},$.fn.affix.defaults,options),this.$window=$(window).on("scroll.affix.data-api",$.proxy(this.checkPosition,this)).on("click.affix.data-api",$.proxy(function(){setTimeout($.proxy(this.checkPosition,this),1)},this)),this.$element=$(element),this.checkPosition()};Affix.prototype.checkPosition=function(){if(this.$element.is(":visible")){var affix,scrollHeight=$(document).height(),scrollTop=this.$window.scrollTop(),position=this.$element.offset(),offset=this.options.offset,offsetBottom=offset.bottom,offsetTop=offset.top,reset="affix affix-top affix-bottom";"object"!=typeof offset&&(offsetBottom=offsetTop=offset),"function"==typeof offsetTop&&(offsetTop=offset.top()),"function"==typeof offsetBottom&&(offsetBottom=offset.bottom()),affix=null!=this.unpin&&scrollTop+this.unpin<=position.top?!1:null!=offsetBottom&&position.top+this.$element.height()>=scrollHeight-offsetBottom?"bottom":null!=offsetTop&&offsetTop>=scrollTop?"top":!1,this.affixed!==affix&&(this.affixed=affix,this.unpin="bottom"==affix?position.top-scrollTop:null,this.$element.removeClass(reset).addClass("affix"+(affix?"-"+affix:"")))}};var old=$.fn.affix;$.fn.affix=function(option){return this.each(function(){var $this=$(this),data=$this.data("affix"),options="object"==typeof option&&option;data||$this.data("affix",data=new Affix(this,options)),"string"==typeof option&&data[option]()})},$.fn.affix.Constructor=Affix,$.fn.affix.defaults={offset:0},$.fn.affix.noConflict=function(){return $.fn.affix=old,this},$(window).on("load",function(){$('[data-spy="affix"]').each(function(){var $spy=$(this),data=$spy.data();data.offset=data.offset||{},data.offsetBottom&&(data.offset.bottom=data.offsetBottom),data.offsetTop&&(data.offset.top=data.offsetTop),$spy.affix(data)})})}(window.jQuery);
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/docs/source/_themes/bootstrap/static/bootstrap.min.js
bootstrap.min.js
Conversion control center ========================= The Conversion Control Center is where you manage all your work. .. image:: images/cc_view.png The links behind the **Contents folder** give you access to your configured contents folder. The eye icon will give you view access to the content folder while the pencil icon will open the first content object in edit mode. .. image:: images/cc_content_folder.png Inspectors ---------- The Conversion Control Center comes with several inspectors that allow you to check several aspects of your authoring project for consistency. Image inspector +++++++++++++++ The image inspectors displays all referenced images (in thumbnail size) together with all conversion related parameters. The most common problem are images without a description. The description is used for the caption of an image and therefore must be filled out. An image with a missing description will be marked with an exclamation mark. .. image:: images/cc_inspector_image.png Anchor inspector ++++++++++++++++ The anchor inspector shows all internal cross-references. Stale references will be marked with an exclamation mark or a green check sign as shown in the picture. .. image:: images/cc_inspector_anchors.png Document structure inspector ++++++++++++++++++++++++++++ The document structure inspector checks your document for logical errors. E.g. a ``H1`` heading can not be followed by a ``H3`` heading. .. image:: images/cc_inspector_document_structure.png Links inspector +++++++++++++++ For inspection completeness the Links inspector will list all links to external pages including their link text. .. image:: images/cc_inspector_links.png Conversion workflow ------------------- Every conversion output (PDF, EPUB etc.) will be stored in a dedicated ``Drafts`` folder that you can see at the bottom of the conversions center view. .. image:: images/drafts_published.png All entries are sorted by creation date (newest first). By clicking on conversion result you can either download the generated file or view them within a browser (HTML + PDF conversion). Additional information about size, creation date and creator is provided. If you are fine with conversion result then you can click on ``publish/rename`` and the conversion result will be moved into the configured ``Publications`` folder. The workflow state of all content will be automatically changed to state ``published``.
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/docs/source/authoring/conversions_center.rst
conversions_center.rst
Installation ============ This documentation assumes that your installation of Plone/Zope is based on zc.buildout. - edit your *buildout.cfg* - add ``zopyx.authoring`` to the ``zcml`` option of your buildout.cfg:: eggs = ... zopyx.authoring - re-run:: bin/buildout - restart Zope/Plone - now either create a new Plone 4 site through the ZMI and select the ``Authoring Environment`` profile from the list of available extension profiles or .. image:: images/ae_install_zmi.png visit the add-ons control panel within the Plone UI and add ``Produce & Publish Authoring Environment`` to the list of installed add-ons .. image:: images/ae_install_plone.png .. note:: The Produce & Publish Authoring Environment requires an installation of ``pp.server`` Produce & Publish server. An installation of the older``zopyx.smartprintng.server`` Produce & Publish server will not work.
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/docs/source/authoring/installation.rst
installation.rst
Supplementary information ========================= Screencasts ----------- The following screencasts demonstrate some of the outstanding features of the Produce & Publish Authoring Environment (produced using Authoring Environment Version 1.X). - `A quick walk-through <http://www.youtube.com/zopyxfilter#p/u/6/RFlRJviA5bE>`_. - `Using footnotes <http://www.youtube.com/zopyxfilter#p/u/2/yLyR6pJuQX4>`_. - `Generating a 300 page PDF from Plone content <http://www.youtube.com/zopyxfilter#p/u/0/b_GZ7yWnis8>`_. - `Consolidated HTML + chapter-wise PDF generation <http://www.youtube.com/zopyxfilter#p/u/1/EJq4Qwst_yw>`_.
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/docs/source/authoring/supplementary.rst
supplementary.rst
Managing and organizing your content ==================================== Your content can be organized as hierarchial set of folders, pages and images. The folder structure determines the later structure of your document. Inside the root authoring content folder you can add the following content types. AuthoringContentFolder ---------------------- A standard Plone folder holding other folders and pages AuthoringContentImage --------------------- A standard image content type holding one image. The authoring environment keeps the original size/resolution of the image. The original and full resolution of the images will always be used for generating PDF documents. The authoring environment does support generating a PDF document with a reduced size. However this conversion happens as a dedicated post-processing step after generating the PDF with the full-size image. The Image type provides several additional settings that are related to the PDF conversion. .. image:: images/add-image.png Scale for PDF production ++++++++++++++++++++++++ This parameters determines the horizontal width in percent of the image inside the generated PDF document. Adjust this parameter in case an image would use too much space or cause an unwanted page break. Exclude from image enumeration ++++++++++++++++++++++++++++++ By default, all images will be enumerated. This checkbox can be used to exclude an image from the enumeration. Create image link to full scale in HTML view ++++++++++++++++++++++++++++++++++++++++++++ The authoring environment will not generate a link to the full view of an image if you decide to generate a HTML version of your content. However by checking the checkbox you can enable this option. Display image inline ++++++++++++++++++++ By default, images are displayed as a block without text floating around them. In cases when you need to include an image as part of a paragraph (e.g. icon images used inside a legend of a table or an image) you may choose to display this particular image inline. Inline images will not be enumerated. Caption position ++++++++++++++++ The authoring environment will generated image captions for each image (if it is not inlined). The image caption is taken from the ``description`` metadata of the image. So make sure that the description metadata is maintained properly - otherwise you may encounter a warning in the generated documents. The position of the image caption can be below or above the image. AuthoringContentAggregator -------------------------- A content aggregator can be used to reference existing content inside other content folders. The basic purpose is to re-use existing content in order to avoid redundancies. .. image:: images/add-aggregator.png By adding an aggregator you have the option to reference either another content folder or an existing content page. The aggregator acts as a transparent proxy for the referenced object. The conversion engine of Produce & Publish will replace an aggregator during the conversion with the content of the referenced content page or content folder. The detail view of a content aggregator object will show additional information about the referenced object. .. image:: images/view-aggregator.png LinkTool -------- The Authoring Environment allows you to create links to other content pieces without creating the _traditional_ HTML anchors yourself. The Authoring Environment will insert automatically internal **ID** attributes for the following elements in order to make them directly linkable: * tables * headings (H1, H2, H3, ...) * list items * images The Authoring Environment provides a new TinyMCE plugin: the **LinkTool**. You can use the **LinkTool** selecting a text within TinyMCE and clicking on the **LinkTool** icon of the TinyMCE toolbar. .. image:: images/linktool_start.png The **LinkTool** displays all linkable content items grouped by documents. Linking to headings +++++++++++++++++++ .. image:: images/linktool_headings.png Linking to tables +++++++++++++++++ Tables are represented by their caption or summary. So ensure that your table contains a proper caption or summary. .. image:: images/linktool_tables.png Linking to images +++++++++++++++++ All linkable images are represented by their thumbnail images. .. image:: images/linktool_images.png Linking to list items +++++++++++++++++++++ You can create links to arbitrary list items ((un)ordered list and definition lists are supported). The typical usecase is e.g. a literature list represented as a list. Inside the content you are then able to reference those list item entries. .. image:: images/linktool_listitems.png Working with tables ------------------- Produce & Publish does not provide any extra functionality for editing tables using the TinyMCE editor of Plone 4 or higher. It provides only two additional CSS classes ``Grid + Landscape`` and ``No grid + Landscape``. The landscape mode will render a table in the PDF output in landscape mode on a dedicated page. This can be used for table with an excessive width.
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/docs/source/authoring/manage_content.rst
manage_content.rst
Customizing S5 templates and styles (Authoring Environment) =========================================================== There are two files relevant to the S5 conversion. The rendering template is defined in ``zopyx.authoring/zopyx/authoring/browser/s5_presentation_template.pt`` and ``zopyx.authoring/zopyx/authoring/skins/zopyx_authoring/pp-s5-pretty.css``. If you need to customize your files then you have basically two options inside your own policy/theme package: - provide your own versions of the files through the overrides mechanism of ZCML for overriding the presentation template and your own skins directory for overriding the CSS file or - using ``z3c.jbot`` for overriding both the presentation template and the stylesheet through one customization mechanism (recommended)
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/docs/source/howto/s5-customization.rst
s5-customization.rst
Pasting content from Microsoft Office (Word) into Plone ======================================================== It seems to be a common approach to edit content within Word on Windows and then to insert the content using copy & paste into Plone The problem ------------ The content copied from Word contains a lot of additional and partly improper HTML markup which may cause trouble in Plone - both from the visual and functionality point of view. So in general it is **forbidden** to paste Word content directly into the editor window of Plone. The solution ------------ Click on the the ``Paste from Word`` icon inside the toolbar of the editor and paste the Word content into the textarea inside the popup window and then just click on ``Insert``. This will remove most of the Word markup crap often causing problems. .. image:: images/paste_from_word.png
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/docs/source/howto/paste_from_word.rst
paste_from_word.rst
How to create an index list with index terms ============================================ Produce & Publish provides a simple build-in mechanism for generating a list of index terms with their occurrence (page-numbers). Prequisites ----------- All index terms must be marked using:: <span class="index-term">some index term</span> This can either be accomplished by generating the related markup through the content-type specific browser views/templates that are registered as ``@@asHTML`` view (Produce & Publish Plone Client Connector) or you highlight a term inside TinyMCE and apply the style ``Index term`` from the styles dropdown menu (Produce & Publish Authoring Environment). Generating an index through the Plone Client Connector ------------------------------------------------------ The standard ``@@asPlainPDF`` view of the Plone Client Connector will automatically create an index listing at the end of the document. The underlaying transformation ``addIndexList`` is called automatically (see ``pdf.py`` file within the client connector sources) Generating an index through the Authoring Environment ----------------------------------------------------- Inside the Authoring Environment have the option to create individual listings including an index listing by checking the related checkbox from the ``PDF`` tab of your conversions page. Custom location of the indexes listing inside your template ----------------------------------------------------------- By default the index listing will be added to the end of the document. However you can control the place through a custom PDF rendering template (e.g. inside your own resources directory). You may place the following markup e.g. in front or after the body text:: <div id="indexes-list"> index listing will be inserted here </div>
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/docs/source/howto/index-listing.rst
index-listing.rst
Manage authors for coverpage PDF ================================ The PDF coverpage contains some optional space for the authors of the document. .. image:: images/coverpage.png :scale: 50 % First visit the content folder of the related conversion folder .. image:: images/edit-authors-2.png and then click on its ``Edit`` tab. .. image:: images/edit-authors-3.png A list of author names can be entered (one per line) into the ``Creators`` text field. .. image:: images/edit-authors-4.png
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/docs/source/howto/edit_authors.rst
edit_authors.rst
A quick walk-through ================================ Create a new conversion for a new content project ------------------------------------------------- .. image:: images/create-1.png Switch to content folder of the project --------------------------------------- .. image:: images/create-2.png Create a new aggregator to reference existing content ----------------------------------------------------- .. image:: images/create-3.png Generate the PDF document ------------------------- .. image:: images/create-5.png
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/docs/source/howto/walkthrough.rst
walkthrough.rst
Credits ======= Parts of the Produce & Publish development have been made possible by substantial financial support of the following companies and organizations: * Distributed European Infrastructure for Supercomputing Applications (http://www.deisa.eu) * Deutsche Gesellschaft für Hämatologie und Onkologie (http://www.dgho.de) * TQM - Totally Quality Management (http://www.tqm.com) Thanks to my fantastic Produce & Publish team: * Ida Ebkes * Veit Schiele * Carsten Raddatz * Stefania Trabucchi
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/docs/source/misc/credits.rst
credits.rst
import os PROJECTNAME = 'zopyx.authoring' ADD_PERMISSIONS = { # -*- extra stuff goes here -*- 'AuthoringCalibreProfile': 'zopyx.authoring: Add AuthoringCalibreProfile', 'AuthoringContentAggregator': 'zopyx.authoring: Add AuthoringContentAggregator', 'AuthoringPublishedDocument': 'zopyx.authoring: Add AuthoringPublishedDocument', 'AuthoringConversionsCollection': 'zopyx.authoring: Add AuthoringConversionsCollection', 'AuthoringCoverPage': 'zopyx.authoring: Add AuthoringCoverPage', 'AuthoringContentPage': 'zopyx.authoring: Add AuthoringContentPage', 'AuthoringConversionFolder': 'zopyx.authoring: Add AuthoringConversionFolder', 'AuthoringContentsFolder': 'zopyx.authoring: Add AuthoringContentsFolder', 'AuthoringTemplate': 'zopyx.authoring: Add AuthoringTemplate', 'AuthoringTemplatesFolder': 'zopyx.authoring: Add AuthoringTemplatesFolder', 'AuthoringImageResource': 'zopyx.authoring: Add AuthoringImageResource', 'AuthoringStylesheet': 'zopyx.authoring: Add AuthoringStylesheet', 'AuthoringBinaryResource': 'zopyx.authoring: Add AuthoringBinaryResource', 'AuthoringMasterTemplate': 'zopyx.authoring: Add AuthoringMasterTemplate', 'AuthoringContentFolder': 'zopyx.authoring: Add AuthoringContentFolder', 'AuthoringProject': 'zopyx.authoring: Add AuthoringProject', } DEPENDENCIES = [ 'Products.DataGridField', # 'Products.ImageEditor', ] PUBLISHED_DOCUMENT_CSS = """ #content { counter-reset: c1 %(chapter_number)d table-counter %(table_counter)d image-counter %(image_counter)d; } """ CALIBRE_DEFAULT_OPTIONS = [ dict(name='--level1-toc', value="//*[name()='h1']"), dict(name='--level2-toc', value="//*[name()='h2']"), dict(name='--level3-toc', value="//*[name()='h3']"), dict(name='--page-breaks-before', value="//*[name()='h1' or name()='h2']"), dict(name='--title', value='%(title)s'), dict(name='--authors', value='%(authors)s') ] CONVERSION_SERVER_URL = os.environ.get('PP_SERVER_URL', 'http://localhost:6543')
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/zopyx/authoring/config.py
config.py
from zope.i18nmessageid import MessageFactory from zopyx.authoring import config from Products.Archetypes import atapi from Products.CMFCore import utils from Products.CMFCore.permissions import setDefaultRoles # Define a message factory for when this product is internationalised. # This will be imported with the special name "_" in most modules. Strings # like _(u"message") will then be extracted by i18n tools for translation. authoringMessageFactory = MessageFactory('producepublish') def initialize(context): """Initializer called when used as a Zope 2 product. This is referenced from configure.zcml. Regstrations as a "Zope 2 product" is necessary for GenericSetup profiles to work, for example. Here, we call the Archetypes machinery to register our content types with Zope and the CMF. """ # Retrieve the content types that have been registered with Archetypes # This happens when the content type is imported and the registerType() # call in the content type's module is invoked. Actually, this happens # during ZCML processing, but we do it here again to be explicit. Of # course, even if we import the module several times, it is only run # once. content_types, constructors, ftis = atapi.process_types( atapi.listTypes(config.PROJECTNAME), config.PROJECTNAME) # Now initialize all these content types. The initialization process takes # care of registering low-level Zope 2 factories, including the relevant # add-permission. These are listed in config.py. We use different # permissions for each content type to allow maximum flexibility of who # can add which content types, where. The roles are set up in rolemap.xml # in the GenericSetup profile. for atype, constructor in zip(content_types, constructors): utils.ContentInit('%s: %s' % (config.PROJECTNAME, atype.portal_type), content_types = (atype,), permission = config.ADD_PERMISSIONS[atype.portal_type], extra_constructors = (constructor,), ).initialize(context) for id, permission in config.ADD_PERMISSIONS.items(): setDefaultRoles(permission, ('Manager', 'Owner')) # activate monkey patches import patches # check if ghostscript is installed import util from logger import LOG if util.checkCommand('gs'): HAVE_GHOSTSCRIPT = True LOG.info('Ghostscript is installed - good!') else: HAVE_GHOSTSCRIPT = False LOG.warn('Ghostscript is not installed - bad (needed for PDF optimization)') if util.checkCommand('tidy'): HAVE_TIDY = True LOG.info('Tidy is installed - good!') else: HAVE_TIDY = False LOG.warn('Tidy is not installed - bad (needed for DOC(X) import)') if util.checkCommand('curl'): HAVE_CURL = True LOG.info('Curl is installed - good!') else: HAVE_CURL = False LOG.warn('CURL is not installed - bad (needed for DOC(X) import)') from config import CONVERSION_SERVER_URL LOG.info('Using conversion server at %s' % CONVERSION_SERVER_URL)
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/zopyx/authoring/__init__.py
__init__.py
tinyMCEPopup.requireLangPack(); var action, orgTableWidth, orgTableHeight, dom = tinyMCEPopup.editor.dom; function insertTable() { console.log('zopyx.authoring custom table pluging'); var formObj = document.forms[0]; var inst = tinyMCEPopup.editor, dom = inst.dom; var cols = 2, rows = 2, border = 0, cellpadding = -1, cellspacing = -1, align, width, height, className, caption, frame, rules, overlay; var html = '', capEl, elm; var cellLimit, rowLimit, colLimit; if (tinyMCEPopup.getParam('table_firstline_th')) { line_tag = "th"; } else { line_tag = "td"; } tinyMCEPopup.restoreSelection(); if (!AutoValidator.validate(formObj)) { tinyMCEPopup.alert(inst.getLang('invalid_data')); return false; } elm = dom.getParent(inst.selection.getNode(), 'table'); // Get form data cols = formObj.elements['cols'].value; rows = formObj.elements['rows'].value; border = formObj.elements['border'].value != "" ? formObj.elements['border'].value : 0; cellpadding = formObj.elements['cellpadding'].value != "" ? formObj.elements['cellpadding'].value : ""; cellspacing = formObj.elements['cellspacing'].value != "" ? formObj.elements['cellspacing'].value : ""; align = getSelectValue(formObj, "align"); frame = getSelectValue(formObj, "tframe"); rules = getSelectValue(formObj, "rules"); width = formObj.elements['width'].value; height = formObj.elements['height'].value; bordercolor = formObj.elements['bordercolor'].value; bgcolor = formObj.elements['bgcolor'].value; className = getSelectValue(formObj, "class"); id = formObj.elements['id'].value; summary = formObj.elements['summary'].value; style = formObj.elements['style'].value; dir = formObj.elements['dir'].value; lang = formObj.elements['lang'].value; background = formObj.elements['backgroundimage'].value; caption = formObj.elements['caption'].checked; overlay = formObj.elements['overlay'].checked; cellLimit = tinyMCEPopup.getParam('table_cell_limit', false); rowLimit = tinyMCEPopup.getParam('table_row_limit', false); colLimit = tinyMCEPopup.getParam('table_col_limit', false); if (overlay) className = className + ' display-overlay'; // Validate table size if (colLimit && cols > colLimit) { tinyMCEPopup.alert(inst.getLang('table_dlg.col_limit').replace(/\{\$cols\}/g, colLimit)); return false; } else if (rowLimit && rows > rowLimit) { tinyMCEPopup.alert(inst.getLang('table_dlg.row_limit').replace(/\{\$rows\}/g, rowLimit)); return false; } else if (cellLimit && cols * rows > cellLimit) { tinyMCEPopup.alert(inst.getLang('table_dlg.cell_limit').replace(/\{\$cells\}/g, cellLimit)); return false; } // Update table if (action == "update") { inst.execCommand('mceBeginUndoLevel'); dom.setAttrib(elm, 'cellPadding', cellpadding, true); dom.setAttrib(elm, 'cellSpacing', cellspacing, true); dom.setAttrib(elm, 'border', border); dom.setAttrib(elm, 'align', align); dom.setAttrib(elm, 'tframe', frame); dom.setAttrib(elm, 'rules', rules); dom.setAttrib(elm, 'class', className); dom.setAttrib(elm, 'style', style); dom.setAttrib(elm, 'id', id); dom.setAttrib(elm, 'summary', summary); dom.setAttrib(elm, 'dir', dir); dom.setAttrib(elm, 'lang', lang); capEl = inst.dom.select('caption', elm)[0]; if (capEl && !caption) capEl.parentNode.removeChild(capEl); if (!capEl && caption) { capEl = elm.ownerDocument.createElement('caption'); if (!tinymce.isIE) capEl.innerHTML = '<br mce_bogus="1"/>'; elm.insertBefore(capEl, elm.firstChild); } if (width && inst.settings.inline_styles) { dom.setStyle(elm, 'width', width); dom.setAttrib(elm, 'width', ''); } else { dom.setAttrib(elm, 'width', width, true); dom.setStyle(elm, 'width', ''); } // Remove these since they are not valid XHTML dom.setAttrib(elm, 'borderColor', ''); dom.setAttrib(elm, 'bgColor', ''); dom.setAttrib(elm, 'background', ''); if (height && inst.settings.inline_styles) { dom.setStyle(elm, 'height', height); dom.setAttrib(elm, 'height', ''); } else { dom.setAttrib(elm, 'height', height, true); dom.setStyle(elm, 'height', ''); } if (background != '') elm.style.backgroundImage = "url('" + background + "')"; else elm.style.backgroundImage = ''; /* if (tinyMCEPopup.getParam("inline_styles")) { if (width != '') elm.style.width = getCSSSize(width); }*/ if (bordercolor != "") { elm.style.borderColor = bordercolor; elm.style.borderStyle = elm.style.borderStyle == "" ? "solid" : elm.style.borderStyle; elm.style.borderWidth = border == "" ? "1px" : border; } else elm.style.borderColor = ''; elm.style.backgroundColor = bgcolor; elm.style.height = getCSSSize(height); inst.addVisual(); // Fix for stange MSIE align bug //elm.outerHTML = elm.outerHTML; inst.nodeChanged(); inst.execCommand('mceEndUndoLevel'); // Repaint if dimensions changed if (formObj.width.value != orgTableWidth || formObj.height.value != orgTableHeight) inst.execCommand('mceRepaint'); tinyMCEPopup.close(); return true; } // Create new table html += '<table'; html += makeAttrib('id', id); html += makeAttrib('border', border); html += makeAttrib('cellpadding', cellpadding); html += makeAttrib('cellspacing', cellspacing); if (width && inst.settings.inline_styles) { if (style) style += '; '; // Force px if (/^[0-9\.]+$/.test(width)) width += 'px'; style += 'width: ' + width; } else html += makeAttrib('width', width); /* if (height) { if (style) style += '; '; style += 'height: ' + height; }*/ //html += makeAttrib('height', height); //html += makeAttrib('bordercolor', bordercolor); //html += makeAttrib('bgcolor', bgcolor); html += makeAttrib('align', align); html += makeAttrib('frame', frame); html += makeAttrib('rules', rules); html += makeAttrib('class', className); html += makeAttrib('style', style); html += makeAttrib('summary', summary); html += makeAttrib('dir', dir); html += makeAttrib('lang', lang); html += '>'; if (caption) { if (!tinymce.isIE) html += '<caption><br mce_bogus="1"/></caption>'; else html += '<caption></caption>'; } for (var y=0; y<rows; y++) { html += "<tr>"; for (var x=0; x<cols; x++) { if (!tinymce.isIE) html += '<'+line_tag+'><br mce_bogus="1"/></'+line_tag+'>'; else html += '<'+line_tag+'></'+line_tag+'>'; } line_tag = "td"; html += "</tr>"; } html += "</table>"; inst.execCommand('mceBeginUndoLevel'); // Move table if (inst.settings.fix_table_elements) { var bm = inst.selection.getBookmark(), patt = ''; inst.execCommand('mceInsertContent', false, '<br class="_mce_marker" />'); tinymce.each('h1,h2,h3,h4,h5,h6,p'.split(','), function(n) { if (patt) patt += ','; patt += n + ' ._mce_marker'; }); tinymce.each(inst.dom.select(patt), function(n) { inst.dom.split(inst.dom.getParent(n, 'h1,h2,h3,h4,h5,h6,p'), n); }); dom.setOuterHTML(dom.select('._mce_marker')[0], html); inst.selection.moveToBookmark(bm); } else inst.execCommand('mceInsertContent', false, html); inst.addVisual(); inst.execCommand('mceEndUndoLevel'); tinyMCEPopup.close(); } function makeAttrib(attrib, value) { var formObj = document.forms[0]; var valueElm = formObj.elements[attrib]; if (typeof(value) == "undefined" || value == null) { value = ""; if (valueElm) value = valueElm.value; } if (value == "") return ""; // XML encode it value = value.replace(/&/g, '&amp;'); value = value.replace(/\"/g, '&quot;'); value = value.replace(/</g, '&lt;'); value = value.replace(/>/g, '&gt;'); return ' ' + attrib + '="' + value + '"'; } function init() { tinyMCEPopup.resizeToInnerSize(); document.getElementById('backgroundimagebrowsercontainer').innerHTML = getBrowserHTML('backgroundimagebrowser','backgroundimage','image','table'); document.getElementById('backgroundimagebrowsercontainer').innerHTML = getBrowserHTML('backgroundimagebrowser','backgroundimage','image','table'); document.getElementById('bordercolor_pickcontainer').innerHTML = getColorPickerHTML('bordercolor_pick','bordercolor'); document.getElementById('bgcolor_pickcontainer').innerHTML = getColorPickerHTML('bgcolor_pick','bgcolor'); var cols = 2, rows = 2, border = tinyMCEPopup.getParam('table_default_border', '0'), cellpadding = tinyMCEPopup.getParam('table_default_cellpadding', ''), cellspacing = tinyMCEPopup.getParam('table_default_cellspacing', ''); var align = "", width = "", height = "", bordercolor = "", bgcolor = "", className = ""; var id = "", summary = "", style = "", dir = "", lang = "", background = "", bgcolor = "", bordercolor = "", rules, frame; var inst = tinyMCEPopup.editor, dom = inst.dom; var formObj = document.forms[0]; var elm = dom.getParent(inst.selection.getNode(), "table"); action = tinyMCEPopup.getWindowArg('action'); if (!action) action = elm ? "update" : "insert"; if (elm && action != "insert") { var rowsAr = elm.rows; var cols = 0; for (var i=0; i<rowsAr.length; i++) if (rowsAr[i].cells.length > cols) cols = rowsAr[i].cells.length; cols = cols; rows = rowsAr.length; st = dom.parseStyle(dom.getAttrib(elm, "style")); border = trimSize(getStyle(elm, 'border', 'borderWidth')); cellpadding = dom.getAttrib(elm, 'cellpadding', ""); cellspacing = dom.getAttrib(elm, 'cellspacing', ""); width = trimSize(getStyle(elm, 'width', 'width')); height = trimSize(getStyle(elm, 'height', 'height')); bordercolor = convertRGBToHex(getStyle(elm, 'bordercolor', 'borderLeftColor')); bgcolor = convertRGBToHex(getStyle(elm, 'bgcolor', 'backgroundColor')); align = dom.getAttrib(elm, 'align', align); frame = dom.getAttrib(elm, 'frame'); rules = dom.getAttrib(elm, 'rules'); className = tinymce.trim(dom.getAttrib(elm, 'class').replace(/mceItem.+/g, '')); overlay = className.indexOf('display-overlay') != -1 ? '1' : ''; className = className.replace(/display-overlay/g, ''); id = dom.getAttrib(elm, 'id'); summary = dom.getAttrib(elm, 'summary'); style = dom.serializeStyle(st); dir = dom.getAttrib(elm, 'dir'); lang = dom.getAttrib(elm, 'lang'); background = getStyle(elm, 'background', 'backgroundImage').replace(new RegExp("url\\('?([^']*)'?\\)", 'gi'), "$1"); formObj.caption.checked = elm.getElementsByTagName('caption').length > 0; formObj.overlay.checked = overlay; orgTableWidth = width; orgTableHeight = height; action = "update"; formObj.insert.value = inst.getLang('update'); } addClassesToList('class', "table_styles"); TinyMCE_EditableSelects.init(); // Update form selectByValue(formObj, 'align', align); selectByValue(formObj, 'frame', frame); selectByValue(formObj, 'rules', rules); selectByValue(formObj, 'class', className, true, true); formObj.cols.value = cols; formObj.rows.value = rows; formObj.border.value = border; formObj.cellpadding.value = cellpadding; formObj.cellspacing.value = cellspacing; formObj.width.value = width; formObj.height.value = height; formObj.bordercolor.value = bordercolor; formObj.bgcolor.value = bgcolor; formObj.id.value = id; formObj.summary.value = summary; formObj.style.value = style; formObj.dir.value = dir; formObj.lang.value = lang; formObj.backgroundimage.value = background; updateColor('bordercolor_pick', 'bordercolor'); updateColor('bgcolor_pick', 'bgcolor'); // Resize some elements if (isVisible('backgroundimagebrowser')) document.getElementById('backgroundimage').style.width = '180px'; // Disable some fields in update mode if (action == "update") { formObj.cols.disabled = true; formObj.rows.disabled = true; } } function changedSize() { var formObj = document.forms[0]; var st = dom.parseStyle(formObj.style.value); /* var width = formObj.width.value; if (width != "") st['width'] = tinyMCEPopup.getParam("inline_styles") ? getCSSSize(width) : ""; else st['width'] = "";*/ var height = formObj.height.value; if (height != "") st['height'] = getCSSSize(height); else st['height'] = ""; formObj.style.value = dom.serializeStyle(st); } function changedBackgroundImage() { var formObj = document.forms[0]; var st = dom.parseStyle(formObj.style.value); st['background-image'] = "url('" + formObj.backgroundimage.value + "')"; formObj.style.value = dom.serializeStyle(st); } function changedBorder() { var formObj = document.forms[0]; var st = dom.parseStyle(formObj.style.value); // Update border width if the element has a color if (formObj.border.value != "" && formObj.bordercolor.value != "") st['border-width'] = formObj.border.value + "px"; formObj.style.value = dom.serializeStyle(st); } function changedColor() { var formObj = document.forms[0]; var st = dom.parseStyle(formObj.style.value); st['background-color'] = formObj.bgcolor.value; if (formObj.bordercolor.value != "") { st['border-color'] = formObj.bordercolor.value; // Add border-width if it's missing if (!st['border-width']) st['border-width'] = formObj.border.value == "" ? "1px" : formObj.border.value + "px"; } formObj.style.value = dom.serializeStyle(st); } function changedStyle() { var formObj = document.forms[0]; var st = dom.parseStyle(formObj.style.value); if (st['background-image']) formObj.backgroundimage.value = st['background-image'].replace(new RegExp("url\\('?([^']*)'?\\)", 'gi'), "$1"); else formObj.backgroundimage.value = ''; if (st['width']) formObj.width.value = trimSize(st['width']); if (st['height']) formObj.height.value = trimSize(st['height']); if (st['background-color']) { formObj.bgcolor.value = st['background-color']; updateColor('bgcolor_pick','bgcolor'); } if (st['border-color']) { formObj.bordercolor.value = st['border-color']; updateColor('bordercolor_pick','bordercolor'); } } tinyMCEPopup.onInit.add(init);
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/zopyx/authoring/overrides/Products.TinyMCE.skins.tinymce.plugins.table.js.table.js
Products.TinyMCE.skins.tinymce.plugins.table.js.table.js
import lxml.html from urlparse import urlparse from Products.Five.browser import BrowserView from Products.CMFCore.utils import getToolByName from zopyx.authoring import authoringMessageFactory as _ from zopyx.smartprintng.plone import xpath_query from zopyx.smartprintng.plone.browser.images import resolveImage, existsExternalImageUrl from image import getImageValue class DebugView(BrowserView): _soup = None @property def soup(self): view = self.context.getContentFolder().restrictedTraverse('@@asHTML') return lxml.html.fromstring(view()) def _allRootDocuments(self): """ Returns an iterator for all root documents. The iterator returns a tuple (document_root_in_zodb, Beautifulsoup node of this document) """ ref_catalog = getToolByName(self.context, 'reference_catalog') for div in self.soup.xpath('//div'): if 'level-0' in div.get('class', ''): div_obj = ref_catalog.lookupObject(div.get('uid')) yield div_obj, div def debugLevels(self): """ return the used Hx level tags """ result = list() for obj, soup in self._allRootDocuments(): last_level = 1 headings = [] for node in soup.xpath(xpath_query(('h1', 'h2', 'h3', 'h4', 'h5', 'h6'))): level = int(node.tag[-1]) error = level > last_level and level-last_level > 1 headings.append(dict(tag=node.tag, level=level, error=error, text=node.text_content())) last_level = level result.append(dict(id=obj.getId(), title=obj.Title(), description=obj.Description(), url=obj.absolute_url(), heading=headings)) return result def debugLinks(self): """ Return a list of links found in the contents document """ links = [] for document, div in self._allRootDocuments(): links_in_doc = list() for link in div.xpath('//a'): href = link.get('href') if not href: continue parts = urlparse(href) if parts.scheme in ('http', 'https', 'ftp'): css_class = link.get('class', '') if not 'editlink' in css_class: links_in_doc.append(dict(text=link.text_content(), css_class=css_class, href=href)) if links_in_doc: links.append(dict(id=document.getId(), title=document.Title(), href=href, description=document.Description(), url=document.absolute_url(), links=links_in_doc)) return links def debugAnchors(self): """ Return a list of anchors found in the contents document """ # find all internal linkable objects first (having an 'id' attribute) link_ids = [node.get('id') for node in self.soup.xpath('//*') if node.get('id')] links = [] # now check all internal links if they are resolvable or not for document, div in self._allRootDocuments(): links_in_doc = list() for link in div.xpath('//a'): href = link.get('href') if not href: continue ref_id = None if href.startswith('resolveuid') and '#' in href: ref_id = href.rsplit('#')[-1] elif href.startswith('#'): ref_id = href[1:] # chop of leading '#' if ref_id: if ref_id in link_ids: links_in_doc.append(dict(text=link.text_content(), found=True)) else: links_in_doc.append(dict(text=link.text_content(), found=False)) links.append(dict(id=document.getId(), title=document.Title(), href=href, description=document.Description(), url=document.absolute_url(), links=links_in_doc)) return links def debugImages(self): """ Return a list of image data for all images inside a content folder """ result = list() images_seen = list() for document, document_node in self._allRootDocuments(): for img in document_node.xpath('//img'): src = str(img.get('src')) img_obj = resolveImage(document, src) if src in images_seen: continue images_seen.append(src) if img_obj: result.append(dict(id=img_obj.getId(), obj=img_obj, title=img_obj.Title(), uid=img_obj.UID(), description=img_obj.Description(), href=img_obj.absolute_url(), image_src=src, external_image=False, pdfScale=getImageValue(img_obj, 'pdfScale'), excludeFromEnumeration=getImageValue(img_obj, 'excludeFromImageEnumeration'), linkToFullScale=getImageValue(img_obj, 'linkToFullScale'), displayInline=getImageValue(img_obj, 'displayInline'), captionPosition=getImageValue(img_obj, 'captionPosition'), )) else: image_exists = existsExternalImageUrl(src) result.append(dict(id=None, obj=None, title=None, image_exists=image_exists, uid=None, description=None, href=None, image_src=src, external_image=True, pdfScale=None, excludeFromEnumeration=None, linkToFullScale=None, displayInline=None, captionPosition=None, )) return result def updateImages(self): """ Update image properties for given set of images by their UID """ params = self.request.form sync_title_description = self.request.form.get('sync_title_description') ref_catalog = getToolByName(self.context, 'reference_catalog') for uid in params.get('uids', []): img = ref_catalog.lookupObject(uid) for k,v in params.items(): field = img.getField(k) if field and v != '': img.getField(k).set(img, v) if sync_title_description: img.setDescription(img.Title()) img.reindexObject() self.context.plone_utils.addPortalMessage(_(u'Image properties updated')) return self.request.response.redirect(self.context.absolute_url() + '/@@debug-images') def preflightResults(self): """ Run an PDF export in preflight mode """ view = self.context.restrictedTraverse('@@generate_pdf') transformations = ['makeImagesLocal'] return view(transformations=transformations, preflight_only=True)
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/zopyx/authoring/browser/debug.py
debug.py
import os import hashlib import zipfile import tempfile from Products.Five.browser import BrowserView from zopyx.smartprintng.plone.resources import resources_registry from zopyx.authoring.logger import LOG EXT2TYPE = { '.pt' : 'AuthoringMasterTemplate', '.cover' : 'AuthoringCoverPage', '.styles' : 'AuthoringStylesheet', '.css': 'AuthoringStylesheet', '.jpg' : 'AuthoringImageResource', '.png' : 'AuthoringImageResource', '.gif' : 'AuthoringImageResource', '.hyp' : 'AuthoringBinaryResource', '.otf' : 'AuthoringBinaryResource', '.ttf' : 'AuthoringBinaryResource', '.calibre' : 'AuthoringCalibreProfile', } class AuthoringTemplateView(BrowserView): def __init__(self, context, request): self.request = request self.context = context def available_resources(self): """ Return all registred resources from SmartPrintNG """ return sorted(resources_registry.keys()) def export_resource(self): """ Export all data belong to a template as ZIP """ zip_filename = tempfile.mktemp() ZIP = zipfile.ZipFile(zip_filename, 'w') for obj in self.context.getFolderContents(): obj = obj.getObject() ZIP.writestr(obj.getId(), obj.get_data()) ZIP.close() data = file(zip_filename).read() os.unlink(zip_filename) R = self.request.RESPONSE R.setHeader('content-type', 'application/zip') R.setHeader('content-length', len(data)) R.setHeader('content-disposition', 'attachment; filename="%s.zip"' % self.context.getId()) R.write(data) def import_resource(self, resource, import_mode=''): """ Import a SmartPrintNG resource into the AuthoringTemplate """ if import_mode == 'clear': self.context.manage_delObjects(self.context.objectIds()) for dirname, dirnames, filenames in os.walk(resources_registry[resource]): if '.svn' in dirname: continue for filename in filenames: fullname = os.path.join(dirname, filename) if not os.path.isfile(fullname): continue basename, ext = os.path.splitext(fullname) # skip unsupported extensions if not ext in EXT2TYPE.keys(): LOG.warn('Ignored during resource import: %s' % fullname) continue if import_mode == 'incremental' and filename in self.context.objectIds(): self.context.manage_delObjects(filename) portal_type = EXT2TYPE.get(ext) self.context.invokeFactory(portal_type, id=filename, title=filename) self.context[filename].update_data(file(fullname).read()) self.context.plone_utils.addPortalMessage(u'Resource %s imported' % resource) self.request.response.redirect(self.context.absolute_url()) def sync(self, redirect=True): """ Sync filesystem-based resource directory with AuthoringTemplate in Plone (always sync from filesystem -> Plone) """ resource = self.context.getResourceOnFilesystem() if not resource: if redirect: self.context.plone_utils.addPortalMessage(u'Nothing to be synced') self.request.response.redirect(self.context.absolute_url()) return filenames_used = set() resource_dir = resources_registry.get(resource) if not resource_dir: raise RuntimeError('No configured resource "%s" found' % resource) for dirname, dirnames, filenames in os.walk(resource_dir): if '.svn' in dirname: continue for filename in filenames: fullname = os.path.join(dirname, filename) if not os.path.isfile(fullname): continue basename, ext = os.path.splitext(fullname) # skip unsupported extensions if not ext in EXT2TYPE.keys(): LOG.warn('Ignored during resource import: %s' % fullname) continue # compare md5 hashes if filename in self.context.objectIds(): obj = self.context[filename] fs_digest = hashlib.md5(file(fullname, 'rb').read()).hexdigest() data = obj.get_data() data_digest = hashlib.md5(data).hexdigest() # hashes are the same -> nothing to do if data_digest == fs_digest: filenames_used.add(filename) continue # object does not exist or hashes are different -> reimport/recreate LOG.info('Syncing %s:%s' % (resource, basename)) filenames_used.add(filename) if filename in self.context.objectIds(): self.context.manage_delObjects(filename) portal_type = EXT2TYPE.get(ext) self.context.invokeFactory(portal_type, id=filename, title=filename) self.context[filename].update_data(file(fullname).read()) # remove obsolete stuff existing_ids = set(self.context.contentIds()) obsolete_ids = existing_ids - filenames_used self.context.manage_delObjects(list(obsolete_ids)) if redirect: self.context.plone_utils.addPortalMessage(u'Synced %s from filesystem into template' % resource) self.request.response.redirect(self.context.absolute_url())
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/zopyx/authoring/browser/authoringtemplate.py
authoringtemplate.py
import os import time import hashlib import tempfile import cssutils from zipfile import ZipFile, is_zipfile import zope.event from zope.interface import directlyProvides, directlyProvidedBy from Products.Five.browser import BrowserView from Products.CMFCore.utils import getToolByName from DateTime.DateTime import DateTime from plone.i18n.normalizer.interfaces import IUserPreferredURLNormalizer from zopyx.smartprintng.plone import Transformer from zopyx.smartprintng.plone.interfaces import IArchiveFolder from .. import authoringMessageFactory as _ from .. import HAVE_TIDY, HAVE_CURL from ..logger import LOG from ..subscribers.events import AfterOfficeImport import util import word_util def cleanup_html(html): """ cleanup HTML generated by OpenOffice """ if not HAVE_TIDY: raise RuntimeError('Tidy is not available') filename = tempfile.mktemp() filename_out = filename + '.out' file(filename, 'wb').write(html) cmd = 'tidy -utf8 -c %s >%s' % (filename, filename_out) LOG.info('Running %s' % cmd) status = os.system(cmd) LOG.info('tidy exit code: %d' % status) if not os.path.exists(filename_out) or os.path.getsize(filename_out) == 0: raise RuntimeError('Running "tidy" failed (cmd: %s)' % cmd) # Perform some transformations html = file(filename_out).read() transformations = ['shiftHeadings', 'cleanupEmptyElements', 'removeEmptyNodesFromWord', 'mergeSingleSpanIntoParagraph', 'convertWordFootnotes', 'convertWordFootnotes2', 'convertWordEndnotes', 'fixHeadingsAfterOfficeImport', 'cleanupTables', 'adjustImagesAfterOfficeImport', 'addUUIDsToAllTags', ] T = Transformer(transformations) result_html = T(html, input_encoding='utf-8', return_body=True) os.unlink(filename) os.unlink(filename_out) return result_html ignored_styles = ( 'font-family', 'orphans', 'direction', 'widows', 'border', 'border-top', 'border-bottom', 'border-left', 'border-right', 'padding', 'padding-top', 'padding-bottom', 'padding-left', 'padding-right', 'margin', 'margin-top', 'margin-bottom', 'margin-left', 'margin-right', 'so-language', 'page-break-before', 'page-break-after', 'font-size', 'text-indent', 'line-height', ) def cleanup_css(css): sheet = cssutils.parseString(css) cssutils.ser.prefs.indent = ' ' for i, rule in enumerate(sheet): if isinstance(rule, cssutils.css.CSSStyleRule): remove_props = list() remove_props = [prop.name for prop in rule.style if prop.name.lower() in ignored_styles] for name in remove_props: rule.style.removeProperty(name) for i, rule in enumerate(sheet): if isinstance(rule, cssutils.css.CSSPageRule): sheet.deleteRule(rule) continue return sheet.cssText class OfficeUpload(BrowserView): """ This view accepts an uploaded office document (.docx, .docx) and sends it to an external hosted conversion service at fafalter.de. The result is returned as ZIP archive containing a HTML and the extracted images (both will be reimported into Plone). """ def __call__(self): if not HAVE_CURL: raise RuntimeError('curl is not available') # url and credentials are stored on the property sheet pp = getToolByName(self.context, 'portal_properties') zp = getToolByName(pp, 'zopyxauthoring_properties') if self.request.get('do_archive'): ids = self.context.objectIds() if ids: archive_id = 'archive-%s' %DateTime().strftime('%Y%m%dT%H%M%S') self.context.invokeFactory('AuthoringContentFolder', id=archive_id, title=archive_id) archive_folder = self.context[archive_id] directlyProvides(archive_folder, directlyProvidedBy(archive_folder), IArchiveFolder) cb = self.context.manage_copyObjects(ids) archive_folder.manage_pasteObjects(cb) # Tabula-Rasa first if requested clear_options = self.request.get('clear_options') if clear_options == 'clear_all': self.context.manage_delObjects([o.getId() for o in self.context.contentValues() if o.portal_type not in ('AuthoringContentFolder',)]) elif clear_options == 'keep_images': self.context.manage_delObjects([o.getId() for o in self.context.contentValues() if o.portal_type not in ('Image', 'AuthoringContentFolder')]) # store uploaded file first on the filesystem if not 'doc' in self.request.form: self.context.plone_utils.addPortalMessage(_(u'label_no_file_uploaded', u'No uploaded file found')) return self.request.response.redirect(self.context.absolute_url() + '/@@import-office-document-form') doc_filename = self.request['doc'].filename if not doc_filename.lower().endswith('docx'): self.context.plone_utils.addPortalMessage(_(u'label_upload_is_not_a_docx_file', u'Uploaded file must be a .DOCX file'), 'error') return self.request.response.redirect(self.context.absolute_url() + '/@@folder_contents') data = self.request['doc'].read() if not data: self.context.plone_utils.addPortalMessage(_(u'label_no_file_given', u'No file given'), 'error') return self.request.response.redirect(self.context.absolute_url() + '/@@import-office-document-form') doc_filename = os.path.basename(self.request['doc'].filename) doc_filename, doc_ext = os.path.splitext(doc_filename) doc_filename = unicode(doc_filename, 'utf-8') dest_id = IUserPreferredURLNormalizer(self.request).normalize(doc_filename) if doc_ext.lower() != '.docx': self.context.plone_utils.addPortalMessage(_(u'label_only_docx_files', u'Imported file must be a DOCX file'), 'error') return self.request.response.redirect(self.context.absolute_url() + '/@@import-office-document-form') input_fn= tempfile.mktemp(prefix='%s-%s-' %(dest_id, DateTime().strftime('%Y%m%dT%H%M%S'))) zip_fn = input_fn + '.zip' file(input_fn, 'wb').write(data) LOG.info('Received office document (%d bytes), stored as %s' % (len(data), input_fn)) hash2image = dict() image_original_dir = None if doc_ext.lower() == '.zip': # Upload of a ZIP file containing the result of a local OO conversion zip_fn = input_fn else: # First perform a replacement of all hires images into lo-res image # replaceImages() will return a minimized version of the original DOCX # document. 'hash2image' will be used later to replace the minimized images # with the original images for import into Plone. The matching is based on # the md5 hash of the thumnail images docx_filename, hash2image, image_original_dir = word_util.replaceImages(input_fn) # POST file to Fafalter server and trigger conversion ts = time.time() cmd = 'curl -s -u "%s:%s" --form "doc=@%s" -o "%s" "%s"' % \ (zp.oo_server_username, zp.oo_server_password, docx_filename, zip_fn, zp.oo_server_url) LOG.info('Running %s' % cmd) status = os.system(cmd) LOG.info('curl exit code: %d, duration=%2.2f seconds' % (status, time.time() - ts)) if not is_zipfile(zip_fn): msg = 'File returned from external conversion is not a ZIP file' LOG.error(msg) LOG.error('Curl output:\n%s\n' % file(zip_fn).read()) raise RuntimeError(msg) content_folder_title = self.context.getContentFolder().Title() # import converted files (html + images) from ZIP file # back into Plone ZF = ZipFile(zip_fn) LOG.info('ZIP contents: %s' % ZF.namelist()) image_counter = 1 office_styles = '' for name in ZF.namelist(): basename, ext = os.path.splitext(name) if ext == '.html': self.context.invokeFactory('AuthoringContentPage', id=dest_id, title=content_folder_title) LOG.info('Added Document %s' % dest_id) doc = self.context[dest_id] html = ZF.read(name) html = cleanup_html(html) doc.setText(html) doc.setContentType('text/html') doc.getField('text').setContentType(doc, 'text/html') doc.reindexObject() elif ext in ('.jpg', '.gif', '.png'): # img_id = '%s-%d.%s' % (dest_id, image_counter, ext) title = '%s (Image %d)' % (dest_id, image_counter) self.context.invokeFactory('Image', id=name, title=title) image_counter += 1 LOG.info('Added Image %s' % name) img = self.context[name] # Check if the image is a thumbnail (as replaced through replaceImages()) img_data = ZF.read(name) img_data_hash = hashlib.md5(img_data).hexdigest() # Img/thumbnail hash matches a former replacment? If yes # then restore the original image content into Plone real_image = hash2image.get(img_data_hash) if real_image: img_data = file(real_image, 'rb').read() img.setImage(img_data) img.reindexObject() elif ext in('.css'): office_styles = cleanup_css(ZF.read(name)) # attach stylesheet self.context[dest_id].setOfficeStyles(office_styles) # house-keeping ZF.close() util.safe_unlink(zip_fn) util.safe_unlink(input_fn) util.safe_unlink(image_original_dir) zope.event.notify(AfterOfficeImport(self.context)) self.context.plone_utils.addPortalMessage(_(u'label_upload_and_conversion_completed', u'Upload and conversion completed')) return self.request.response.redirect(self.context.absolute_url() + '/@@folder_contents') def usage(self): """ Return back references """
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/zopyx/authoring/browser/contentfolder.py
contentfolder.py
from ordereddict import OrderedDict from Products.Five.browser import BrowserView from Products.CMFCore.utils import getToolByName from zopyx.smartprintng.plone import xpath_query import util import lxml.html class MetaInformation(BrowserView): """ This view returns informations about tables, images and headings for the aggregated HTML of the root content folder as JSON data. """ def getMetaInformation(self): ref_catalog = getToolByName(self.context, 'reference_catalog') # get hold of the root content folder try: content_folder = self.context.getContentFolder() except AttributeError: return dict(documents={}) # and render the aggregated HTML html = content_folder.restrictedTraverse('@@asHTML')() root = lxml.html.fromstring(html) documents = OrderedDict() for div in root.xpath('//div'): if not 'level-0' in div.get('class', ''): continue uid = div.get('uid') # of root node root_node = ref_catalog.lookupObject(uid) documents[uid] = dict(metadata={}, tables=[], images=[], headings=[]) documents[uid]['metadata']['path'] = div.get('path') documents[uid]['metadata']['id'] = div.get('document_id') documents[uid]['metadata']['title'] = root_node.Title() documents[uid]['metadata']['description'] = root_node.Description() documents[uid]['metadata']['url'] = root_node.absolute_url() for node in div.xpath(xpath_query(('h1', 'h2', 'h3', 'h4', 'h5'))): id = node.get('id') level = int(node.tag[1:]) url = 'resolveuid/%s/#%s' % (uid, id) if id: d = dict(id=id, target_url=url, name=node.tag, level=level, text=node.text_content()) documents[uid]['headings'].append(d) # process images for node in div.xpath('//img'): id = node.get('id') src = node.get('src') if not src: continue src_parts = src.split('/') if src_parts[-1].startswith('image_'): src = '/'.join(src_parts[:-1]) elif '@@images' in src: src = '/'.join(src_parts[:src_parts.index('@@images')]) url = 'resolveuid/%s/#%s' % (uid, id) image_url = '%s/%s/image_thumb' % (content_folder.absolute_url(), src) if id: d = dict(id=id, target_url=url, image_url=image_url, name=node.tag) documents[uid]['images'].append(d) # process tables for node in div.xpath('//table'): id = node.get('id') if not id: continue # caption + caption summary = node.get('summary') or '(table without caption or summary)' caption = summary if node.xpath('//caption'): caption = node.xpath('//caption')[0].text_content() url = 'resolveuid/%s/#%s' % (uid, id) d = dict(id=id, target_url=url, name=node.tag, caption=caption) documents[uid]['tables'].append(d) # process lists documents[uid]['lists'] = [] for list_node in div.xpath(xpath_query(('ol', 'ul', 'dl'))): list_items = list() for item in list_node.xpath(xpath_query(('li', 'dt'))): item_id = item.get('id') if item_id: url = 'resolveuid/%s/#%s' % (uid, item_id) list_items.append(dict(id=item_id, target_url=url, text=item.text_content())) documents[uid]['lists'].append(list_items) return dict(documents=documents) class TableHandler(BrowserView): """ Table folding - return a rendered HTML table by its ID """ def show_table(self, id): """ Return the HTML code of a table given by its id """ return util.extract_table(self.context.getText(), id)
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/zopyx/authoring/browser/ippcontent.py
ippcontent.py
import os from Products.Five.browser import BrowserView from Products.CMFCore.utils import getToolByName from DateTime.DateTime import DateTime from plone.app.layout.navigation.root import getNavigationRootObject from plone.i18n.normalizer.de import Normalizer from .. import authoringMessageFactory as _ package_home = os.path.dirname(__file__) class AuthoringProject(BrowserView): def add_authoringproject(self, title): """ Prepare AuthoringEnvironment for a new project """ putils = getToolByName(self.context, 'plone_utils') project_id = Normalizer().normalize(unicode(title, 'utf-8').lower()) project_id = putils.normalizeString(project_id) if not 'contents' in self.context.objectIds(): self.context.invokeFactory('AuthoringContentsFolder', id='contents', title='Contents') self.context['contents'].reindexObject() if not 'templates' in self.context.objectIds(): self.context.invokeFactory('AuthoringTemplatesFolder', id='templates', title='Templates') self.context['templates'].reindexObject() # setup demo template folder templates = self.context['templates'] templates.invokeFactory('AuthoringTemplate', id='template', title='Template') demo_template = templates['template'] demo_template.restrictedTraverse('@@import_resource')('pp-default', import_mode='clear') if not 'conversions' in self.context.objectIds(): self.context.invokeFactory('AuthoringConversionsCollection', id='conversions', title='Conversions') self.context['conversions'].reindexObject() # setup demo content contents = self.context['contents'] if project_id in contents.objectIds(): self.context.plone_utils.addPortalMessage(_(u'label_project_exists', u'Project already exists - choose a different name'), 'error') return self.request.response.redirect(self.context.absolute_url()) contents.invokeFactory('AuthoringContentFolder', id=project_id) demo = contents[project_id] demo.setTitle(title) demo.reindexObject() demo.invokeFactory('AuthoringContentPage', 'page1', title='Page1') page1 = demo['page1'] page1.setTitle(u'Page1') page1.setDescription(u'Test document') page1.setText(file(os.path.join(package_home, 'default.txt')).read()) page1.setFormat('text/html') page1.setContentType('text/html') page1.reindexObject() # prepare conversions folder conversions_collection = self.context['conversions'] conversions_collection.invokeFactory('AuthoringConversionFolder', id=project_id) conversion = conversions_collection[project_id] conversion.setTitle(title) conversion.reindexObject() conversion.setContentFolderPath('/'.join(demo.getPhysicalPath())) templates = self.context['templates'] demo_template = templates['template'] conversion.setConversionTemplatePath('/'.join(demo_template.getPhysicalPath())) conversion.setPublicationsFolder(conversion['published']) conversion.setMasterTemplate('pdf_template.pt') conversion.setEbookMasterTemplate('ebook_template.pt') conversion.setCalibreProfile('calibre_profile.calibre') conversion.setStyles([ 'styles_standalone.css', 'single_aggregated_bookmarks.css', 'single_aggregated_toc.css', 'page_numbers.css', 'hyphenation.css', 'footnotes.css', 'images.css', 'tables.css', 'crossreferences.css', 'indexes.css', ]), self.context.plone_utils.addPortalMessage(_(u'label_project_created', u'Project created')) self.request.response.redirect(conversion.absolute_url()) def cleanup_project(self, drafts_older_than=0): """ Remove drafts older than N days """ ct = getToolByName(self.context, 'portal_catalog') now = DateTime() path = '/'.join(self.context.getPhysicalPath()) for brain in ct(portal_type='AuthoringConversionFolder', path=path): conv = brain.getObject() del_ids = [ob.getId for ob in conv.drafts.getFolderContents() if now - ob.modified > drafts_older_than] conv.drafts.manage_delObjects(del_ids) self.context.plone_utils.addPortalMessage(_(u'label_project_cleanup_down', u'Cleanup done')) self.request.response.redirect(self.context.absolute_url())
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/zopyx/authoring/browser/authoringproject.py
authoringproject.py
import os import lxml.html from zopyx.smartprintng.plone import xpath_query def _cleanupHtml(html): return lxml.html.tostring(lxml.html.fromstring(html.strip()), encoding=unicode) def splitHTMLIntoSlides(source_html): root = lxml.html.fromstring(source_html) body = root.xpath('//div[@id="main-content"]')[0] # h1 tags are obsolete in S5 since we promote all H2 tags to H1 tags below for heading in body.xpath('//h1'): heading.getparent().remove(heading) # Each slide in S5 starts with a H1 tag. Each slide in HTML (aggregated or not) # is represented by a H2 tag and the markup until the next H2 tag. So we # need to shift all H2 tags to H1 etc. In addition we need to split the # HTML documents at H1 tags (formerlly H2 tags). # h2->h1, h3->h2, ... for heading in body.xpath(xpath_query(('h2', 'h3', 'h4', 'h5'))): heading.text = heading.text_content() level = int(heading.tag[1:]) heading.tag= 'h%d' % (level - 1) # now split the page into chunks at each H1 tag which is the marker for a # new slide current_doc = list() slides = list() html2 = lxml.html.tostring(body, encoding=unicode) for line in html2.split('\n'): line = line.rstrip() if '<h1' in line.lower() and current_doc: html = u' '.join(current_doc) # add only slides if they have a h1 tag in it (ignoring # trailing HTML junk) if '<h1' in html: slides.append(_cleanupHtml(html)) current_doc = [line] else: current_doc.append(line) html = u' '.join(current_doc) slides.append(_cleanupHtml(html)) return slides def html2s5(context, html_filename): html = file(html_filename).read() slides = splitHTMLIntoSlides(html) # retrieve presentation helper view s5view = context.restrictedTraverse('@@s5_presentation_template') # get hold of metadata for rendering the S5 view content_folder = context.getContentFolder() conversion_folder = context.getConversionFolder() # parameter dict params = dict(s5line1=conversion_folder.getS5Line1(), s5line2=conversion_folder.getS5Line2(), s5line3=conversion_folder.getS5Line3(), s5line4=conversion_folder.getS5Line4() ) for field in content_folder.Schema().fields(): params[field.getName()] = field.get(content_folder) # now render s5 html = s5view(slides=slides, **params) s5_filename = os.path.join(os.path.dirname(html_filename), 'index_s5.html') file(s5_filename, 'wb').write(html.encode('utf-8')) return s5_filename
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/zopyx/authoring/browser/s5.py
s5.py
import os import shutil import subprocess import time import tempfile import zipfile import json import unicodedata from ConfigParser import ConfigParser import lxml.html from DateTime import DateTime from OFS.DTMLDocument import addDTMLDocument from DateTime.DateTime import DateTime from Products.Five.browser import BrowserView from Products.CMFCore.WorkflowCore import WorkflowException from Products.ATContentTypes.interface.folder import IATFolder from Products.ATContentTypes.interface.image import IATImage from Products.ATContentTypes.interface.document import IATDocument from Products.ATContentTypes.lib import constraintypes from simpledropbox import SimpleDropbox from zopyx.authoring import authoringMessageFactory as _ from zopyx.authoring.subscribers.events import BeforePublishing, AfterPublishing from zopyx.smartprintng.plone.browser import util from plone.i18n.normalizer.interfaces import IUserPreferredURLNormalizer from plone.memoize import ram import zope.event import zope.component from zope.interface import directlyProvides from zope.contenttype import guess_content_type try: from zope.pagetemplate.pagetemplatefile import PageTemplateFile except ImportError: from zope.app.pagetemplate.viewpagetemplatefile import ViewPageTemplateFile as PageTemplateFile from zopyx.smartprintng.plone.browser.splitter import split_html import pp.client.python.pdf as pdf_client from .. import HAVE_GHOSTSCRIPT from ..logger import LOG from ..config import PUBLISHED_DOCUMENT_CSS, CONVERSION_SERVER_URL from ..interfaces import IConversionView from zopyx.smartprintng.plone import Transformer, hasTransformations, availableTransformations from util import safe_invokeFactory, preflight import s5 # server host/port of the SmartPrintNG server KEEP_OUTPUT = 'KEEP_OUTPUT' in os.environ def fix_links(html, nodeid2filename): """ fix_links() is called for every splitted HTML document and will walk over all links referencing linkable components as given through href='resolveuid/<UID>#<id-or-anchor>'. It will lookup the referenced filename from the nodeid2filename dictionary and replace the href with a relative link to the real html file. """ if not isinstance(html, unicode): html = unicode(html, 'utf-8') root = lxml.html.fromstring(html) for link in root.xpath('//*[name()="a"]'): href = link.attrib.get('href') if not href: continue ref_id = None if href.startswith('resolveuid') and '#' in href: ref_id = href.rsplit('#')[-1] elif href.startswith('#'): ref_id = href[1:] # chop of leading '#' if ref_id: ref_filename = nodeid2filename.get(ref_id) if ref_filename: link.attrib['href'] = '%s#%s' % (nodeid2filename[ref_id], ref_id) else: LOG.warn('No reference for %s found' % ref_id) link.attrib['class'] = link.attrib.get('class', '') + ' unresolved-link' return lxml.html.tostring(root, encoding=unicode) class ConversionsFolderView(BrowserView): def __init__(self, context, request): self.request = request self.context = context self.export_run = False def redirect_edit_view(self): """ Redirect to edit view of the first document """ content_folder = self.context.getContentFolder() brains = content_folder.getFolderContents({'portal_type' : 'AuthoringContentPage'}) if len(brains) > 1: self.context.plone_utils.addPortalMessage(_(u'label_more_than_one_document_found', u'More than one editable document found. Please select a document from the content folder view.'), 'error') return self.request.response.redirect(self.context.absolute_url()) elif len(brains) == 0: self.context.plone_utils.addPortalMessage(_(u'label_no_document_found', u'No document found'), 'error') return self.request.response.redirect(self.context.absolute_url()) return self.request.response.redirect(brains[0].getURL() + '/edit') def _generate_pdf(self, **params): # merge request and method parameters LOG.info('generate_pdf() -> %r' % params) root_document = params.get('root_document', self.context.getContentFolder()) transformations = params.get('transformations', [])[::] converter = params.get('converter', 'princexml') export_result = self.export_template_resources(params) LOG.info(' Export directory: %s' % export_result['workdir']) # get HTML body as snippet view = root_document.restrictedTraverse('@@asHTML') body = view(published_only=params.get('published-only'), filter_uids=params.get('filter_uids', [])) # the PDF rendering template is always exported as pdf_template.pt template_name = params.get('converter') == 'calibre' and 'ebook_template.pt' or 'pdf_template.pt' template_filename = os.path.join(export_result['workdir'], template_name) # now render the template html = PageTemplateFile(template_filename)(self.context, context=self.context, request=self.request, content_root=root_document, coverfront=export_result['coverfront'], coverback=export_result['coverback'], body=body) # apply transformations transformations.insert(0, 'ignoreHeadingsForStructure') transformations.append('adjustAnchorsToLinkables') transformations.append('fixAmpersand') LOG.info('Using new transformation engine (%s)' % transformations) T = Transformer(transformations, context=self.context, destdir=export_result['workdir']) html = T(html) # normalize to UTF (fixing issues with COMBINING DIAERESIS) html = unicodedata.normalize('NFC', html).encode('utf-8') html = html.replace(chr(11), ' ') # remove 0x0b crap chars html_output_filename = os.path.join(export_result['workdir'], 'index.html') file(html_output_filename, 'wb').write(html) errors = preflight(export_result['workdir']) for error in errors: LOG.warn('PREFLIGHT: %s' % error) if 'preflight_only' in params: return errors if 'no_conversion' in params: return export_result['workdir'] # converter command line options if 'converter_commandline_options' in params: cmd_filename = os.path.join(export_result['workdir'], 'commandlineoptions.txt') file(cmd_filename, 'w').write(params['converter_commandline_options']) # run the conversion ts = time.time() LOG.info('Output written to %s' % export_result['workdir']) result = pdf_client.pdf(export_result['workdir'], server_url=CONVERSION_SERVER_URL, converter=params['converter']) if result['status'] != 'OK': raise RuntimeError('Conversion failed: {}'.format(result['output'])) output_file = result['output_filename'] LOG.info('Output filename: {}'.format(output_file)) LOG.info('Output filesize: {} bytes'.format(os.path.getsize(output_file))) # reduce PDF size (if != 'default') by piping the pdf file through ghostscript pdf_quality = params.get('pdf_quality', 'default') if pdf_quality != 'default': dirname, basename = os.path.split(output_file) pdf_optimized = os.path.join(dirname, 'out_' + basename) cmd = 'gs -dCompatibilityLevel=1.4 -dPDFSETTINGS=/%s -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile="%s" "%s"' % (pdf_quality, pdf_optimized, output_file) LOG.info('Optimizing PDF (%s)' % cmd) p = subprocess.Popen(cmd, shell=True) status = os.waitpid(p.pid, 0)[1] if status != 0: msg = u'PDF optimization failed with status %d' % status LOG.error(msg) raise RuntimeError(msg) result['output_filename'] = pdf_optimized LOG.info('Conversion time: %3.1f seconds' % (time.time() -ts)) return result['output_filename'] def _calibre_cmdline_options(self): """ Return Calibre conversion commandline options """ cf = self.context.getContentFolder() params = {'title' : cf.Title().encode('utf-8'), 'authors' : u' & '.join(self.context.getEbookAuthors()), 'cover' : 'ebook-cover-image', } return params def _calibre_additional_options(self): """ Inject additional Calibre options """ options = list() options.append('--extra-css "%(WORKDIR)s/ebook.css"') if self.context.getEbookCoverpageImage(): options.append('--cover "%(WORKDIR)s/ebook-cover-image"') if self.context.Subject(): options.append('--tags "%s"' % u','.join(list(self.context.Subject()))) if self.context.Language(): options.append('--language %s' % self.context.Language()) options.append('--book-producer "ZOPYX Produce and Publish AuthoringEnvironment"') return u' ' + u' '.join(options) def generate_epub(self, **kw): """ Browser view called directly from the P&P UI for generating an EPUB file. """ params = self.request.form params.update(kw) calibre_profile = self.context.getCalibreProfileObject() if calibre_profile is None: self.context.plone_utils.addPortalMessage(_(u'label_no_calibre_profile_configured', u'No Calibre file configured - unable to convert to EPUB'), 'error') return self.request.response.redirect(self.context.absolute_url() + '?show_latest_draft=1') transformations = ['makeImagesLocal', 'cleanupForEPUB'] params['converter'] = 'calibre' params['transformations'] = transformations params['converter_commandline_options'] = calibre_profile.getCommandlineOptions() % \ self._calibre_cmdline_options() params['converter_commandline_options'] += self._calibre_additional_options() return self.generate_pdf(**params) def generate_pdf(self, **kw): """ Browser view called directly from the P&P UI for generating a PDF file from the content in the configured content folder. The result will be stored inside the 'drafts' folder. """ # merge request and keyword parameters params = self.request.form params.update(kw) # call the PDF wrapper (returns PDF filename) output_file = self._generate_pdf(**params) if 'preflight_only' in params: return output_file # (which is actually 'errors') workdir = os.path.dirname(output_file) # optional ZIP conversion if params.has_key('store-zip'): zip_filename = tempfile.mktemp('.zip') ZF = zipfile.ZipFile(zip_filename, 'w') # add generated output file if output_file: ZF.write(output_file, os.path.basename(output_file)) for filename in os.listdir(workdir): ZF.write(os.path.join(workdir, filename), filename) ZF.close() output_file = zip_filename # guess content-type (ensure that this code will later also work with # other output formats) mime_type, enc = guess_content_type(output_file) basename, ext = os.path.splitext(os.path.basename(output_file)) # store output file in local 'drafts' folder (hard-coded) dest_folder = self.context.drafts # limit name to 30 spaces since normalizeString() returns only 50 chars # and we need space for the date-time string root_document = self.context.getContentFolder() dest_id = root_document.Title()[:30] + ' ' + DateTime().strftime('%Y-%m-%d-%H:%M:%S') dest_id = unicode(dest_id, 'utf-8') dest_id = IUserPreferredURLNormalizer(self.request).normalize(dest_id) + ext dest_folder.invokeFactory('File', id=dest_id, title=dest_id) dest_file = dest_folder[dest_id] dest_file.setFile(file(output_file, 'rb').read()) dest_file.setContentType(mime_type) dest_file.reindexObject() # store conversion parameters as property (JSON) params_json = json.dumps(params) dest_file.manage_addProperty('conversionparameters', params_json, 'string') # store form parameters in session if hasattr(self.request, 'SESSION'): self.request.SESSION.set('zopyx_authoring', self.request.form.copy()) if KEEP_OUTPUT: LOG.info('Workdir: %s' % workdir) LOG.info('Outputfile: %s' % output_file) else: os.unlink(output_file) if not 'no_redirect' in kw: self.context.plone_utils.addPortalMessage(_(u'Output file generated')) self.request.response.redirect(self.context.absolute_url() + '?show_latest_draft=1') def generate_html_pdf(self, **kw): """ Browser view called directly from the P&P UI for generating HTML and optional PDF. """ # merge request and keyword parameters params = self.request.form params.update(kw) html_mode = params.get('html_mode', 'complete') target = params.get('target', 'drafts') content_folder = self.context.getContentFolder() # prepare destination if target == 'publications': # trigger archiving by sending an event# if 'do_archive' in params: zope.event.notify(BeforePublishing(self.context)) dest_folder = self.context.getPublicationsFolder() for brain in dest_folder.getFolderContents(): obj = brain.getObject() obj.unindexObject() dest_folder.manage_delObjects(obj.getId()) else: dest_id = content_folder.Title()[:30] + ' ' + DateTime().strftime('%Y-%m-%d-%H:%M:%S') dest_id = IUserPreferredURLNormalizer(self.request).normalize(dest_id) self.context.drafts.invokeFactory('Folder', id=dest_id, title=dest_id) dest_folder = self.context.drafts[dest_id] # store conversion parameters as property (JSON) params_json = json.dumps(params) if dest_folder.hasProperty('conversionparameters'): dest_folder._updateProperty('conversionparameters', params_json) else: dest_folder.manage_addProperty('conversionparameters', params_json, 'string') # export HTML + resource to the filesystem (but no conversion) workdir = self._generate_pdf(no_conversion=True, transformations=['makeImagesLocal', 'cleanupHtml', 'footnotesForHtml', 'rescaleImagesToOriginalScale', 'addAnchorsToHeadings', 'removeTableOfContents', ]) html_filename = os.path.join(workdir, 'index.html') # Post-transformation using new transformation API. Although the H2..H5 # already carry id=".." attribute there are not attribute sets for the H1 nodes # since the H1 is usually taken from the document titles. The id attributes are only # added automatically by the ippcontent subscriber for the document body (having H2..H5 # nodes) T = Transformer(['addUUIDs']) html = T(file(html_filename).read(), input_encoding='utf-8') file(html_filename, 'w').write(html.encode('utf-8')) # split always since we also need meta information from the main document split_html(html_filename) # There is always a documents.ini file generated by split_html() CP = ConfigParser()# CP.read(os.path.join(workdir, 'documents.ini')) # After calling split_html() the generated documents.ini will contain # information about all linkable objects inside each document. Each section of # document.ini will contain a list of 'node_ids' nodeid2filename = dict() for section in CP.sections(): node_ids = [nid.strip() for nid in CP.get(section, 'node_ids').split()] # determine of filename for current section if html_mode == 'complete': filename = 'index.html' # all-in-one else: title = CP.get(section, 'title') filename = IUserPreferredURLNormalizer(self.request).normalize(unicode(title, 'utf-8')) for node_id in node_ids: nodeid2filename[node_id] = filename ################################################################ # Store the (splitted) HTML inside drafts/publication folder ################################################################ # import HTML files injected_styles = dict() countersStartWith = params.get('counter_start', 'h1') if html_mode == 'complete': # a single aggregated document is stored under 'index.html' id = 'index.html' CP.read(os.path.join(workdir, 'documents.ini')) title = CP.get('0', 'title') # first document of split set html_filename = os.path.join(workdir, 'index.html') text = fix_links(file(html_filename).read(), nodeid2filename) dest_folder.invokeFactory('AuthoringPublishedDocument', id=id) page = dest_folder[id] page.setTitle(title) page.setCountersStartWith(countersStartWith) page.setText(text) page.setContentType('text/html') page.getField('text').setContentType(page, 'text/html') page.reindexObject() dest_folder.setDefaultPage(id) # inject office styles # retrieve the content document/page authoring_pages = content_folder.objectValues('AuthoringContentPage') if authoring_pages: page.setOfficeStyles(authoring_pages[0].getOfficeStyles()) # now import splitted documents elif html_mode == 'split': # for splitted documents we generate the HTML filename based # on the 'filename' option from the related sections table_counter = 0 image_counter = 0 sections = CP.sections() sections.sort(lambda x,y: cmp(int(x), int(y))) for i, section in enumerate(sections): filename = CP.get(section, 'filename') title = CP.get(section, 'title') id = IUserPreferredURLNormalizer(self.request).normalize(unicode(title, 'utf-8')) number_tables = CP.getint(section, 'number_tables') number_images = CP.getint(section, 'number_images') # inject split document specific counters if params.get('reset_counters'): styles = '' else: styles = PUBLISHED_DOCUMENT_CSS % dict(chapter_number=i, image_counter=image_counter, table_counter=table_counter) injected_styles[id] = styles.replace('#content', '#main-content') table_counter += number_tables image_counter += number_images text = fix_links(file(filename).read(), nodeid2filename) new_id = safe_invokeFactory(dest_folder, 'AuthoringPublishedDocument', id=id, title=title, text=text, styles=styles, countersStartWith=countersStartWith, ) dest_folder[new_id].setContentType('text/html') dest_folder[new_id].getField('text').setContentType(dest_folder[new_id], 'text/html') dest_folder[new_id].reindexObject() if i == 0: dest_folder.setDefaultPage(new_id) ########################################################################### # Export presentation mode (making only sense with html_mode=complete) ########################################################################### if 'generate_s5' in params: id = 'index_s5.html' title = CP.get('0', 'title') # first document of split set html_filename = os.path.join(workdir, 'index.html') s5_filename = s5.html2s5(self.context, html_filename) dest_folder.addDTMLDocument(id, id, file(s5_filename)) ########################################################################### # import images (from $workdir/images.ini) ########################################################################### if os.path.exists(os.path.join(workdir, 'images.ini')): IMAGE_CP = ConfigParser()# IMAGE_CP.read(os.path.join(workdir, 'images.ini')) for section in IMAGE_CP.sections(): filename = IMAGE_CP.get(section, 'filename') id = section description = title = u'' if IMAGE_CP.has_option(section, 'title'): title = IMAGE_CP.get(section, 'title') if IMAGE_CP.has_option(section, 'description'): description = IMAGE_CP.get(section, 'description') if IMAGE_CP.has_option(section, 'id'): id = IMAGE_CP.get(section, 'id') new_id = safe_invokeFactory(dest_folder, 'Image', id=id, title=title, description=description, image=file(filename).read(), excludeFromNav=True) dest_folder[new_id].reindexObject() ########################################################################### # store aggregated HTML ########################################################################### id = 'index_aggregated.html' title = CP.get('0', 'title') # first document of split set html_filename = os.path.join(workdir, 'index.html') dest_folder.invokeFactory('Document', id=id) page = dest_folder[id] page.setTitle(title) page.setText(file(html_filename).read()) page.setExcludeFromNav(True) page.reindexObject() ########################################################################### # now PDF generation ########################################################################### if 'generate_pdf' in params: # the published HTML already contains image captions other stuff # that we want remove first before running the PDF conversion. # In particular we need to export the images and re-created the captions transformations = ['removeListings', # also removes image-captions 'removeProcessedFlags', 'makeImagesLocal', 'addTableOfContents', 'addTableList', 'addImageList', ] if html_mode == 'complete': output_filename = self._generate_pdf(root_document=dest_folder['index.html'], reset_counters=1, pdf_quality=params.get('pdf_quality', 'default'), transformations=transformations) pdf_name = content_folder.Title() pdf_name = IUserPreferredURLNormalizer(self.request).normalize(pdf_name) + '.pdf' dest_folder.invokeFactory('File', id=pdf_name, title=pdf_name, file=file(output_filename).read()) dest_folder[pdf_name].setFilename(pdf_name) dest_folder[pdf_name].setTitle(pdf_name) dest_folder[pdf_name].setFile(file(output_filename).read()) elif html_mode == 'split': for brain in dest_folder.getFolderContents({'portal_type' : ('AuthoringPublishedDocument',)}): transformations.append('replaceUnresolvedLinks') root_document = brain.getObject() output_filename = self._generate_pdf(root_document=root_document, transformations=transformations, reset_counters=1, # no need over carrying counters forward!? pdf_quality=params.get('pdf_quality', 'default'), # supplementary_stylesheet=styles_inject, ) pdf_name = os.path.splitext(root_document.getId())[0] + '.pdf' dest_folder.invokeFactory('File', id=pdf_name, title=pdf_name, file=file(output_filename).read()) dest_folder[pdf_name].setFilename(pdf_name) ########################################################################### # generate EPub ########################################################################### if 'generate_epub' in params: transformations = ['removeListings', 'removeProcessedFlags', 'makeImagesLocal', 'cleanupForEPUB'] params = dict() calibre_profile = self.context.getCalibreProfileObject() params['converter_commandline_options'] = '' if calibre_profile: params['converter_commandline_options'] = calibre_profile.getCommandlineOptions() % \ self._calibre_cmdline_options() params['converter_commandline_options'] += self._calibre_additional_options() params['root_document'] = dest_folder['index.html'] params['converter'] = 'calibre' params['transformations'] = transformations params['reset_counters'] = 1 output_filename = self._generate_pdf(**params) epub_source_html = os.path.join(os.path.dirname(output_filename), 'index.html') dest_folder.addDTMLDocument('index_epub.html', 'index_epub.html', file(epub_source_html)) epub_name = 'index.epub' dest_folder.invokeFactory('File', id=epub_name, title=epub_name, file=file(output_filename).read()) dest_folder[epub_name].setFilename(epub_name) dest_folder[epub_name].reindexObject() # AfterPublication hook (triggering) post-generation actions if target == 'publications': zope.event.notify(AfterPublishing(self.context)) self.context.plone_utils.addPortalMessage(_(u'label_output_generated', u'Output file generated')) self.request.response.redirect(self.context.absolute_url() + '?show_latest_draft=1') if 'return_destination' in params: return dest_folder def export_template_resources(self, params): """ Export template resources to the filesystem (workdir) """ template_folder = self.context.getConversionTemplate() template_folder.restrictedTraverse('@@sync')(redirect=False) content_folder = self.context.getContentFolder() prefix = '%s-%s-' % (self.context.getContentFolder().getId(), DateTime().ISO()) workdir = tempfile.mkdtemp(prefix=prefix) # export template folder template_filename = None for obj in template_folder.getFolderContents(): obj = obj.getObject() if obj.portal_type in ('AuthoringCoverPage', 'AuthoringCalibreProfile'): continue dest_filename = os.path.join(workdir, obj.getId()) if obj.getId() == self.context.getMasterTemplate(): # id-by-reference dest_filename = template_filename = os.path.join(workdir, 'pdf_template.pt') if obj.getId() == self.context.getEbookMasterTemplate(): # id-by-reference dest_filename = template_filename = os.path.join(workdir, 'ebook_template.pt') # get_data() is a common API to all files under templates file(dest_filename, 'wb').write(obj.get_data()) if template_filename is None: raise ValueError('No template "%s" found' % self.context.getMasterTemplate()) # coverpage handling coverfront = coverback = None if params.get('use_front_cover_page') and self.context.getFrontCoverPage(): cover_html = self.context.getFrontCoverPage().getHtml() tmp1 = tempfile.mktemp() file(tmp1, 'wb').write(cover_html) coverfront = PageTemplateFile(tmp1)(self.context, context=self.context, request=self.request, content_root=content_folder) os.unlink(tmp1) if params.get('use_back_cover_page') and self.context.getBackCoverPage(): cover_html = self.context.getBackCoverPage().getHtml() tmp2 = tempfile.mktemp() file(tmp2, 'wb').write(cover_html) coverback = PageTemplateFile(tmp2)(self.context, context=self.context, request=self.request, content_root=content_folder) os.unlink(tmp2) # Ebook coverpage if self.context.getEbookCoverpageImage(): file(os.path.join(workdir, 'ebook-cover-image'), 'wb').write(str(self.context.getEbookCoverpageImage().data)) # supplementary stylesheet passed as text suppl_styles = params.get('supplementary_stylesheet', '') file(os.path.join(workdir, 'injected_counters.css'), 'w').write(suppl_styles) # inject office styles authoring_pages = [o for o in content_folder.contentValues() if o.portal_type == 'AuthoringContentPage'] if authoring_pages: office_styles = authoring_pages[0].getOfficeStyles() file(os.path.join(workdir, 'injected_office_styles.css'), 'w').write(office_styles) return dict(workdir=workdir, coverfront=coverfront, coverback=coverback) def publishPublicationFolder(self): """ Publish all content in the configured publication folder """ def publishWalker(obj): try: wf_tool.doActionFor(obj, 'publish') obj.reindexObject(idxs=['review_state']) except WorkflowException: pass if IATFolder.providedBy(obj): for brain in obj.getFolderContents(): publishWalker(brain.getObject()) wf_tool = self.context.portal_workflow publication_folder = self.context.getPublicationsFolder() publishWalker(publication_folder) def publishDropbox(self, uid, rename=False): """ move a draft by UID to Dropbox """ obj = self.context.portal_catalog(UID=uid)[0].getObject() username = self.context.getDropboxUsername() password = self.context.getDropboxPassword() directory = self.context.getDropboxDirectory() sdb = SimpleDropbox(username, password) sdb.login() if IATFolder.providedBy(obj): dest_path = unicode(directory + '/' + obj.getId() + '.zip') export_view = obj.restrictedTraverse('@@download_all') data = export_view(download=True) sdb.put(dest_path, data) else: dest_path = unicode(directory + '/' + obj.getId()) sdb.put(dest_path, str(obj.getFile().data)) self.context.plone_utils.addPortalMessage(_(u'Draft copied to Dropbox (%s@%s)' % (username, dest_path))) self.request.response.redirect(self.context.absolute_url() + '?show_latest_publication=1') def publishDraft(self, uid, rename=False): """ move a draft by UID from drafts to published folder """ obj = self.context.portal_catalog(UID=uid)[0].getObject() cb = obj.aq_parent.manage_cutObjects([obj.getId()]) dest = self.context.getPublicationsFolder() dest.manage_pasteObjects(cb) new_obj = dest[obj.getId()] new_id = new_obj.getId() if rename: basename, ext = os.path.splitext(new_id) dest_id = IUserPreferredURLNormalizer(self.request).normalize(self.context.getContentFolder().Title()) + ext if dest_id in dest.objectIds(): dest.manage_delObjects(dest_id) dest.manage_renameObject(new_id, dest_id) new_obj = dest[dest_id] new_obj.setTitle(self.context.getContentFolder().Title()) new_obj.reindexObject() if new_obj.portal_type == 'File': new_obj.setFilename(new_id) # try to publish try: self.context.portal_workflow.doActionFor(new_obj, 'publish') except WorkflowException: LOG.warn('Unable to change wfstate to publish for draft (%s)' % (new_obj.absolute_url(1))) self.context.plone_utils.addPortalMessage(_(u'Draft published')) self.request.response.redirect(self.context.absolute_url() + '?show_latest_publication=1') def cleanDrafts(self): """ remove all drafts """ self.context.drafts.manage_delObjects(self.context.drafts.objectIds()) self.context.plone_utils.addPortalMessage(_(u'Drafts folder cleaned')) self.request.response.redirect(self.context.absolute_url()) def availableTransformations(self): """ return all available transformations """ return availableTransformations() def relativePath(self, obj): """ return relative path of object within Plone site """ obj_path = '/'.join(obj.getPhysicalPath()) plone_path = '/'.join(self.context.portal_url.getPortalObject().getPhysicalPath()) + '/' return obj_path.replace(plone_path, '') def getSupplementaryConversionViews(self): result = list() for name, util in zope.component.getUtilitiesFor(IConversionView): d = util() d['name'] = name result.append(d) return result def getCalibreProfiles(self): """ Return calibre profiles from authoring project parent """ return () def haveGhostscript(self): """ Ghostscript installed? """ return HAVE_GHOSTSCRIPT def getContentFolderContents(self): """ Return content of the content folder """ content_folder = self.context.getContentFolder() return content_folder.getFolderContents({'portal_type' : ('Document', 'AuthoringContentPage')})
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/zopyx/authoring/browser/conversionsfolder.py
conversionsfolder.py
import os import tempfile import zipfile from Products.Five.browser import BrowserView from zopyx.authoring import authoringMessageFactory as _ HTML = """ <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" href="publisheddocument.css" type="text/css" /> <link rel="stylesheet" href="publisheddocument_counters_h1.css" type="text/css" /> <style type="text/css"> %(styles)s </style> </head> <body> <div id="content"> %(html)s </div> </body> </html> """ package_home = os.path.dirname(__file__) published_css = file(os.path.join(package_home, 'resources', 'publisheddocument.css')).read() published_h1_css = file(os.path.join(package_home, 'resources', 'publisheddocument_counters_h1.css')).read() published_h2_css = file(os.path.join(package_home, 'resources', 'publisheddocument_counters_h2.css')).read() class DownloadAll(BrowserView): """ Download all content of folder as ZIP """ def __call__(self, download=False): try: self.context.getAuthoringProject() except AttributeError: self.request.response.setStatus(404) return have_s5 = 'index_s5.html' in self.context.objectIds() have_epub = 'index.epub' in self.context.objectIds() # Write ZIP archive zip_filename = tempfile.mktemp() ZIP = zipfile.ZipFile(zip_filename, 'w') # CSS first ZIP.writestr('html/publisheddocument.css', published_css) ZIP.writestr('html/publisheddocument_counters_h1.css', published_h1_css) ZIP.writestr('html/publisheddocument_counters_h2.css', published_h2_css) html_filenames = list() for obj in self.context.getFolderContents(): obj = obj.getObject() obj_id = obj.getId() if obj.portal_type in ('AuthoringPublishedDocument',): styles = obj.getStyles() html = obj.getText() html = html.replace('/image_preview', '') html = HTML % dict(html=html, styles=styles) id = 'html/' + obj_id if not id.endswith('.html'): id += '.html' ZIP.writestr(id, html) html_filenames.append(id) elif obj.portal_type in ('Document',): # S5 if obj_id == 'index_aggregated.html': html = obj.getText() html = html.replace('/image_preview', '') html = HTML % dict(html=html, styles='') ZIP.writestr('html/index_aggregated.html', html) elif obj.portal_type == 'Image': # export only preview scale img = obj.Schema().getField('image').getScale(obj, scale='preview') if img is not None: # TQM workaround ZIP.writestr('html/' + obj_id, str(img.data)) ZIP.writestr('presentation/%s/image_preview' % obj_id, str(img.data)) if have_epub: ZIP.writestr('epub/preview_%s' % obj_id, str(img.data)) elif obj.portal_type == 'File': if obj.getId().endswith('.pdf'): ZIP.writestr('pdf/' + obj.getId(), str(obj.getFile().data)) elif obj.getId().endswith('.epub'): ZIP.writestr('epub/' + obj_id, str(obj.getFile().data)) if html_filenames: ZIP.writestr('html/all-files.txt', '\n'.join(html_filenames)) # Further EPUB stuff if have_epub: obj = self.context['index_epub.html'] ZIP.writestr('epub/index_epub.html', obj.document_src()) # S5 export # The S5 HTML document is stored as a DTML Document. All other resources are # located in the skins folder and are acquired here using acquisition if have_s5: obj = self.context['index_s5.html'] ZIP.writestr('presentation/index.html', obj.document_src()) # S5 Resources for name in ('pp-s5-core.css', 'pp-s5-framing.css', 'pp-s5-opera.css', 'pp-s5-outline.css', 'pp-s5-pretty.css', 'pp-s5-print.css', 'pp-s5-pretty.css', 'pp-s5-slides.css', 'pp-s5-slides.js'): resource = getattr(self.context, name) ZIP.writestr('presentation/%s' % name, str(resource)) # custom immages for name in ('logo.png', 'custom-logo.png', 'title.png'): img = getattr(self.context, name, None) if img: ZIP.writestr('presentation/%s' % name, str(img._data)) ZIP.close() data = file(zip_filename).read() if download: return data os.unlink(zip_filename) R = self.request.RESPONSE R.setHeader('content-type', 'application/zip') R.setHeader('content-length', len(data)) R.setHeader('content-disposition', 'attachment; filename="%s.zip"' % self.context.getId()) return R.write(data) class SortFolderView(BrowserView): """ Sort folder alphabatically """ def __call__(self): docs = list(self.context.getFolderContents()) docs.sort(lambda x,y: cmp(x.Title, y.Title)) for i, brain in enumerate(docs): self.context.moveObjectToPosition(brain.getId, i) self.context[brain.getId].reindexObject() self.context.plone_utils.addPortalMessage(_(u'label_folder_sorted', u'Folder sorted')) self.request.response.redirect(self.context.absolute_url())
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/zopyx/authoring/browser/folder.py
folder.py
import os import tempfile import hashlib import zipfile import shutil import util import PIL.Image def replaceImages(docx_filename): """ This method creates a new DOCX file containing minimized versions of the original images (at least for images larger than 128x128px. """ # temporary directory for holding the original (large-scale) images image_original_dir = tempfile.mkdtemp() # unzip DOCX file first tmpdir = tempfile.mkdtemp() ZF = zipfile.ZipFile(docx_filename) files_in_zip = ZF.namelist()[::] for name in ZF.namelist(): basedir = os.path.dirname(name) destdir = os.path.join(tmpdir, basedir) destpath = os.path.join(tmpdir, name) if not os.path.exists(destdir): os.makedirs(destdir) file(destpath, 'wb').write(ZF.read(name)) ZF.close() # process images hash2image= dict() imgdir = os.path.join(tmpdir, 'word', 'media') if os.path.exists(imgdir): for imgname in os.listdir(imgdir): fullimgname = os.path.join(imgdir, imgname) ext = os.path.splitext(fullimgname)[1].lower() if not ext in ('.png', '.jpg', '.gif'): print 'Can not handle %s files (%s) - REMOVED' % (ext, imgname) files_in_zip.remove(fullimgname.replace(tmpdir + '/', '')) os.unlink(fullimgname) continue pil_img = PIL.Image.open(fullimgname) if pil_img.size[0] < 128 and pil_img.size[1] < 128: continue # preserve original image shutil.copy(fullimgname, image_original_dir) # rescale image pil_img.thumbnail((100,100)) # and replace original image with thumbnail os.unlink(fullimgname) pil_img.save(fullimgname, quality=25) # store hash of thumbnail image with a reference to the original image md5 = hashlib.md5(file(fullimgname, 'rb').read()).hexdigest() hash2image[md5] = os.path.join(image_original_dir, imgname) # Create new .docx file with minimized images docx_zip_name = tempfile.mktemp(suffix='.docx') docx_zip = zipfile.ZipFile(docx_zip_name, 'w') for name in files_in_zip: docx_zip.writestr(name, file(os.path.join(tmpdir, name), 'rb').read()) docx_zip.close() util.safe_unlink(tmpdir) return docx_zip_name, hash2image, image_original_dir
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/zopyx/authoring/browser/word_util.py
word_util.py
from DateTime import DateTime from Products.CMFCore.utils import getToolByName def archiver(event): """ Archiver """ conversion = event.conversion wf_tool = getToolByName(conversion, 'portal_workflow') archive_folder = conversion.getArchiveFolder() if archive_folder is None: return # nothing to do # items to be archived? publication_folder = conversion.getPublicationsFolder() ids = publication_folder.objectIds() if not ids: return # determine presets for archive folder content_folder = conversion.restrictedTraverse(conversion.getContentFolderPath()) content_folder_id = content_folder.getId() content_folder_title = content_folder.Title() if not content_folder_id in archive_folder.objectIds(): archive_folder.invokeFactory('Folder', id=content_folder_id, title=content_folder_title) wf_tool.doActionFor(archive_folder[content_folder_id] , 'publish') archive_folder[content_folder_id].reindexObject() # create a new folder with timestamp as ID content_archive_folder = archive_folder[content_folder_id] now = DateTime() dest_id= now.strftime('%Y%m%dT%H%M%S') dest_title = 'Version (%s)' % now.strftime('%d.%m.%Y-%H:%Mh') content_archive_folder.invokeFactory('Folder', id=dest_id, title=dest_title) wf_tool.doActionFor(content_archive_folder[dest_id] , 'publish') content_archive_folder[dest_id].reindexObject() # move new folder to the top content_archive_folder.moveObjectToPosition(dest_id, 0) # cut/paste from publication folder to archive folder dest_folder = content_archive_folder[dest_id] dest_folder.manage_pasteObjects(publication_folder.manage_cutObjects(ids)) # add (Version: XXXX) to archived image content for id in dest_folder.objectIds(): ob = dest_folder[id] if ob.portal_type in ('Image',): ob.setTitle('%s (%s)' % (ob.Title(), dest_title)) ob.reindexObject()
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/zopyx/authoring/subscribers/archiver.py
archiver.py
(function() { tinymce.PluginManager.requireLangPack('linktool'); tinymce.create('tinymce.plugins.linktoolPlugin', { init : function(ed, url) { // Register commands ed.addCommand('mcelinktoolPopup', function() { var e = ed.selection.getNode(); // Internal image object like a flash placeholder if (ed.dom.getAttrib(e, 'class').indexOf('mceItem') != -1) return; ed.windowManager.open({ file : url + '/popup.html', width : 800, height : 650, inline : 1 }, { plugin_url : url }); }); // Register buttons //tinyMCE.getButtonHTML(cn, 'lang_linktool_desc', '{$pluginurl}/images/tinymce_button.gif', 'mcelinktoolPopup'); ed.addButton('linktool', { title : 'LinkTool', cmd : 'mcelinktoolPopup', image : url + '/images/tinymce_button.gif' }); ed.onNodeChange.add(function(ed, cm, n, co) { cm.setDisabled('linktool', co && n.nodeName != 'A'); cm.setActive('linktool', n.nodeName == 'A' && !n.name); }); }, getInfo : function() { return { longname : 'Image Map Editor', author : 'Adam Maschek, John Ericksen', authorurl : 'http://linktool.googlecode.com', infourl : 'http://linktool.googlecode.com', version : "2.0" }; } }); // Register plugin tinymce.PluginManager.add('linktool', tinymce.plugins.linktoolPlugin); })(); var TinyMCE_linktoolPlugin = { execCommand : function(editor_id, element, command, user_interface, value) { switch (command) { case "mcelinktoolPopup": var template = new Array(); template['file'] = '../../plugins/linktool/popup.html'; template['width'] = 700; template['height'] = 670; var inst = tinyMCE.getInstanceById(editor_id); var elm = inst.getFocusElement(); if (elm != null && tinyMCE.getAttrib(elm, 'class').indexOf('mceItem') != -1) return true; tinyMCE.openWindow(template, {editor_id : editor_id, scrollbars : "yes", resizable: "yes"}); return true; } return false; }, handleNodeChange : function(editor_id, node, undo_index, undo_levels, visual_aid, any_selection) { if (node == null) return; //check parents //if image parent already has imagemap, toggle selected state, if simple image, use normal state do { //console.log(node.nodeName); if (node.nodeName == "IMG" && tinyMCE.getAttrib(node, 'class').indexOf('mceItem') == -1) { if (tinyMCE.getAttrib(node, 'usemap') != '') { tinyMCE.switchClass(editor_id + '_linktool', 'mceButtonSelected'); } else { tinyMCE.switchClass(editor_id + '_linktool', 'mceButtonNormal'); } return true; } } while ((node = node.parentNode)); //button disabled by default tinyMCE.switchClass(editor_id + '_linktool', 'mceButtonDisabled'); return true; } }; //tinyMCE.addPlugin("linktool", TinyMCE_linktoolPlugin); //tinymce.PluginManager.add("linktool", tinymce.plugins.linktoolPlugin);
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/zopyx/authoring/skins/zopyx_linktool/linktool/editor_plugin.js
editor_plugin.js
(function() { tinymce.PluginManager.requireLangPack('imgmap'); tinymce.create('tinymce.plugins.imgmapPlugin', { init : function(ed, url) { // Register commands ed.addCommand('mceimgmapPopup', function() { var e = ed.selection.getNode(); // Internal image object like a flash placeholder if (ed.dom.getAttrib(e, 'class').indexOf('mceItem') != -1) return; ed.windowManager.open({ file : url + '/popup.html', width : 700, height : 560, inline : 1 }, { plugin_url : url }); }); // Register buttons //tinyMCE.getButtonHTML(cn, 'lang_imgmap_desc', '{$pluginurl}/images/tinymce_button.gif', 'mceimgmapPopup'); ed.addButton('imgmap', { title : 'imgmap.desc', cmd : 'mceimgmapPopup', image : url + '/images/tinymce_button.gif' }); // Add a node change handler, selects the button in the UI when a image is selected ed.onNodeChange.add(function(ed, cm, node) { if (node == null) return; //check parents //if image parent already has imagemap, toggle selected state, if simple image, use normal state do { //console.log(node.nodeName); if (node.nodeName == "IMG" && ed.dom.getAttrib(node, 'class').indexOf('mceItem') == -1) { if (ed.dom.getAttrib(node, 'usemap') != '') { cm.setDisabled('imgmap', false); cm.setActive('imgmap', true); } else { cm.setDisabled('imgmap', false); cm.setActive('imgmap', false); } return true; } } while ((node = node.parentNode)); //button disabled by default cm.setDisabled('imgmap', true); cm.setActive('imgmap', false); return true; }); }, getInfo : function() { return { longname : 'Image Map Editor', author : 'Adam Maschek, John Ericksen', authorurl : 'http://imgmap.googlecode.com', infourl : 'http://imgmap.googlecode.com', version : "2.0" }; } }); // Register plugin tinymce.PluginManager.add('imgmap', tinymce.plugins.imgmapPlugin); })(); var TinyMCE_imgmapPlugin = { execCommand : function(editor_id, element, command, user_interface, value) { switch (command) { case "mceimgmapPopup": var template = new Array(); template['file'] = '../../plugins/imgmap/popup.html'; template['width'] = 700; template['height'] = 670; var inst = tinyMCE.getInstanceById(editor_id); var elm = inst.getFocusElement(); if (elm != null && tinyMCE.getAttrib(elm, 'class').indexOf('mceItem') != -1) return true; tinyMCE.openWindow(template, {editor_id : editor_id, scrollbars : "yes", resizable: "yes"}); return true; } return false; }, handleNodeChange : function(editor_id, node, undo_index, undo_levels, visual_aid, any_selection) { if (node == null) return; //check parents //if image parent already has imagemap, toggle selected state, if simple image, use normal state do { //console.log(node.nodeName); if (node.nodeName == "IMG" && tinyMCE.getAttrib(node, 'class').indexOf('mceItem') == -1) { if (tinyMCE.getAttrib(node, 'usemap') != '') { tinyMCE.switchClass(editor_id + '_imgmap', 'mceButtonSelected'); } else { tinyMCE.switchClass(editor_id + '_imgmap', 'mceButtonNormal'); } return true; } } while ((node = node.parentNode)); //button disabled by default tinyMCE.switchClass(editor_id + '_imgmap', 'mceButtonDisabled'); return true; } }; //tinyMCE.addPlugin("imgmap", TinyMCE_imgmapPlugin); //tinymce.PluginManager.add("imgmap", tinymce.plugins.imgmapPlugin);
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/zopyx/authoring/skins/zopyx_linktool/linktool/editor_plugin_src.js
editor_plugin_src.js
var editor = null; var img_obj = null; var map_obj = null; //array of form elements var props = []; function init() { tinyMCEPopup.resizeToInnerSize(); //tinyMCE.setWindowArg('mce_windowresize', true);//i guess we dont need this editor = tinyMCEPopup.editor; var _parent = editor.contentWindow.parent.location.href; selected_node = editor.selection.getNode(); var content = document.getElementById('content'); content.innerHTML = loadMetaInformation(_parent + '/../@@metaInformation'); } function loadMetaInformation(url) { // load anchors from view @@getAnchors view var request = new XMLHttpRequest(); request.open('get', url, false); request.send(null); if (request.status == 200) return request.responseText; else return 'An error occurred'; } function cancelAction() { tinyMCEPopup.close(); } function addLink(url, linktype, id) { var inst = tinyMCEPopup.editor; var elm, elementArray, i; elm = inst.selection.getNode(); elm = inst.dom.getParent(elm, "A"); tinyMCEPopup.execCommand("mceBeginUndoLevel"); // Create new anchor elements if (elm == null) { inst.getDoc().execCommand("unlink", false, null); tinyMCEPopup.execCommand("CreateLink", false, url, {skip_undo : 1}); elementArray = tinymce.grep(inst.dom.select("a"), function(n) {return inst.dom.getAttrib(n, 'href') == url;}); for (i=0; i<elementArray.length; i++) setAllAttribs(elm = elementArray[i], linktype, id); } // Don't move caret if selection was image if (elm && (elm.childNodes.length != 1 || elm.firstChild.nodeName != 'IMG')) { inst.focus(); inst.selection.select(elm); inst.selection.collapse(0); tinyMCEPopup.storeSelection(); } tinyMCEPopup.execCommand("mceEndUndoLevel"); tinyMCEPopup.close(); } function setAllAttribs(elm, linktype, id) { var dom = tinyMCEPopup.editor.dom; dom.addClass(elm, 'reference-' + linktype); // does not work // dom.setAttrib(elm, 'destid', id); }
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/zopyx/authoring/skins/zopyx_linktool/linktool/jscripts/functions.js
functions.js
* @fileoverview * Online Image Map Editor - main script file. * This is the main script file of the Online Image Map Editor. * * TODO: * -scriptload race condition fix * -destroy/cleanup function ? * -testing highlighter * -cursor area_mousemove in opera not refreshing quite well - bug reported * -get rid of memo array * -highlight which control point is edited in html or form mode * -more comments, especially on config vars * -make function names more logical * - dumpconfig * -prepare for bad input /poly not properly closed? * -prepare for % values in coords * -prepare for default shape http://www.w3.org/TR/html4/struct/objects.html#edef-AREA * * @date 26-02-2007 2:24:50 * @author Adam Maschek (adam.maschek(at)gmail.com) * @copyright * @version 2.2 * */ /*jslint browser: true, newcap: false, white: false, onevar: false, plusplus: false, eqeqeq: false, nomen: false */ /*global imgmapStrings:true, window:false, G_vmlCanvasManager:false, air:false, imgmap_spawnObjects:true */ /** * @author Adam Maschek * @constructor * @param config The config object. */ function imgmap(config) { /** Version string of imgmap */ this.version = "2.2"; /** Build date of imgmap */ this.buildDate = "2009/07/26 16:29"; /** Sequential build number of imgmap */ this.buildNumber = "108"; /** Config object of the imgmap instance */ this.config = {}; /** Status flag to indicate current drawing mode */ this.is_drawing = 0; /** Array to hold language strings */ this.strings = []; /** Helper array for some drawing operations */ this.memory = []; /** Array to hold reference to all areas (canvases) */ this.areas = []; /** Array to hold last log entries */ this.logStore = []; /** Associative array to hold bound event handlers */ this.eventHandlers = {}; this.currentid = 0; this.draggedId = null; this.selectedId = null; this.nextShape = 'rect'; /** possible values: 0 - edit, 1 - preview */ this.viewmode = 0; /** array of dynamically loaded javascripts */ this.loadedScripts = []; this.isLoaded = false; this.cntReloads = 0; /** holds the name of the actively edited map, use getMapName to read it */ this.mapname = ''; /** holds the id of the actively edited map, use getMapIdto read it */ this.mapid = ''; /** watermark to attach to output */ this.waterMark = '<!-- Created by Online Image Map Editor (http://www.maschek.hu/imagemap/index) -->'; /** global scale of areas (1-normal, 2-doubled, 0.5-half, etc.) */ this.globalscale = 1; /** is_drawing draw mode constant */ this.DM_RECTANGLE_DRAW = 1; /** is_drawing draw mode constant */ this.DM_RECTANGLE_MOVE = 11; /** is_drawing draw mode constant */ this.DM_RECTANGLE_RESIZE_TOP = 12; /** is_drawing draw mode constant */ this.DM_RECTANGLE_RESIZE_RIGHT = 13; /** is_drawing draw mode constant */ this.DM_RECTANGLE_RESIZE_BOTTOM = 14; /** is_drawing draw mode constant */ this.DM_RECTANGLE_RESIZE_LEFT = 15; /** is_drawing draw mode constant */ this.DM_SQUARE_DRAW = 2; /** is_drawing draw mode constant */ this.DM_SQUARE_MOVE = 21; /** is_drawing draw mode constant */ this.DM_SQUARE_RESIZE_TOP = 22; /** is_drawing draw mode constant */ this.DM_SQUARE_RESIZE_RIGHT = 23; /** is_drawing draw mode constant */ this.DM_SQUARE_RESIZE_BOTTOM = 24; /** is_drawing draw mode constant */ this.DM_SQUARE_RESIZE_LEFT = 25; /** is_drawing draw mode constant */ this.DM_POLYGON_DRAW = 3; /** is_drawing draw mode constant */ this.DM_POLYGON_LASTDRAW = 30; /** is_drawing draw mode constant */ this.DM_POLYGON_MOVE = 31; /** is_drawing draw mode constant */ this.DM_BEZIER_DRAW = 4; /** is_drawing draw mode constant */ this.DM_BEZIER_LASTDRAW = 40; /** is_drawing draw mode constant */ this.DM_BEZIER_MOVE = 41; //set some config defaults below /** * Mode of operation * possible values: * editor - classical editor, * editor2 - dreamweaver style editor, * highlighter - map highlighter, will spawn imgmap instances for each map found in the current page * highlighter_spawn - internal mode after spawning imgmap objects */ this.config.mode = "editor"; this.config.baseroot = ''; this.config.lang = ''; this.config.defaultLang = 'en'; this.config.loglevel = 0; this.config.custom_callbacks = {};//possible values: see below! /** Callback events that you can handle in your GUI. */ this.event_types = [ 'onModeChanged', 'onHtmlChanged', 'onAddArea', 'onRemoveArea', 'onDrawArea', 'onResizeArea', 'onRelaxArea', 'onFocusArea', 'onBlurArea', 'onMoveArea', 'onSelectRow', 'onLoadImage', 'onSetMap', 'onGetMap', 'onSelectArea', 'onDblClickArea', 'onStatusMessage', 'onAreaChanged']; //default color values this.config.CL_DRAW_BOX = '#E32636'; this.config.CL_DRAW_SHAPE = '#d00'; this.config.CL_DRAW_BG = '#fff'; this.config.CL_NORM_BOX = '#E32636'; this.config.CL_NORM_SHAPE = '#d00'; this.config.CL_NORM_BG = '#fff'; this.config.CL_HIGHLIGHT_BOX = '#E32636'; this.config.CL_HIGHLIGHT_SHAPE = '#d00'; this.config.CL_HIGHLIGHT_BG = '#fff'; this.config.CL_KNOB = '#555'; this.config.bounding_box = true; this.config.label = '%n'; //the format string of the area labels - possible values: %n - number, %c - coords, %h - href, %a - alt, %t - title this.config.label_class = 'imgmap_label'; //the css class to apply on labels this.config.label_style = 'font: bold 10px Arial'; //this.config.label_style = 'font-weight: bold; font-size: 10px; font-family: Arial; color: #964'; //the css style(s) to apply on labels this.config.hint = '#%n %h'; //the format string of the area mouseover hints - possible values: %n - number, %c - coords, %h - href, %a - alt, %t - title this.config.draw_opacity = '35'; //the opacity value of the area while drawing, moving or resizing - possible values 0 - 100 or range "(x)-y" this.config.norm_opacity = '50'; //the opacity value of the area while relaxed - possible values 0 - 100 or range "(x)-y" this.config.highlight_opacity = '70'; //the opacity value of the area while highlighted - possible values 0 - 100 or range "(x)-y" this.config.cursor_default = 'crosshair'; //auto/pointer //the css cursor while hovering over the image //browser sniff var ua = navigator.userAgent; this.isMSIE = (navigator.appName == "Microsoft Internet Explorer"); this.isMSIE5 = this.isMSIE && (ua.indexOf('MSIE 5') != -1); this.isMSIE5_0 = this.isMSIE && (ua.indexOf('MSIE 5.0') != -1); this.isMSIE7 = this.isMSIE && (ua.indexOf('MSIE 7') != -1); this.isGecko = ua.indexOf('Gecko') != -1; this.isSafari = ua.indexOf('Safari') != -1; this.isOpera = (typeof window.opera != 'undefined'); this.setup(config); } /** * Return an object given by id or object itself. * @date 22-02-2007 0:14:50 * @author Adam Maschek (adam.maschek(at)gmail.com) * @param objorid A DOM object, or id of a DOM object. * @return The identified DOM object or null on error. */ imgmap.prototype.assignOID = function(objorid) { try { if (typeof objorid == 'undefined') { this.log("Undefined object passed to assignOID.");// Called from: " + arguments.callee.caller, 1); return null; } else if (typeof objorid == 'object') { return objorid; } else if (typeof objorid == 'string') { return document.getElementById(objorid); } } catch (err) { this.log("Error in assignOID", 1); } return null; }; /** * Main setup function. * Can be called manually or constructor will call it. * @date 22-02-2007 0:15:42 * @author Adam Maschek (adam.maschek(at)gmail.com) * @param config config object * @return True if all went ok. */ imgmap.prototype.setup = function(config) { //this.log('setup'); //copy non-default config parameters to this.config for (var i in config) { if (config.hasOwnProperty(i)) { this.config[i] = config[i]; } } //set document event hooks this.addEvent(document, 'keydown', this.eventHandlers.doc_keydown = this.doc_keydown.bind(this)); this.addEvent(document, 'keyup', this.eventHandlers.doc_keyup = this.doc_keyup.bind(this)); this.addEvent(document, 'mousedown', this.eventHandlers.doc_mousedown = this.doc_mousedown.bind(this)); //set pic_container element - supposedly it already exists in the DOM if (config && config.pic_container) { this.pic_container = this.assignOID(config.pic_container); this.disableSelection(this.pic_container); } if (!this.config.baseroot) { //search for a base - theoretically there can only be one, but lets search //for the first non-empty var bases = document.getElementsByTagName('base'); var base = ''; for (i=0; i<bases.length; i++) {//i declared earlier if (bases[i].href) { base = bases[i].href; //append slash if missing if (base.charAt(base.length-1) != '/') { base+= '/'; } break; } } //search for scripts var scripts = document.getElementsByTagName('script'); for (i=0; i<scripts.length; i++) {//i declared earlier if (scripts[i].src && scripts[i].src.match(/imgmap\w*\.js(\?.*?)?$/)) { var src = scripts[i].src; //cut filename part, leave last slash src = src.substring(0, src.lastIndexOf('/') + 1); //set final baseroot path if (base && src.indexOf('://') == -1) { this.config.baseroot = base + src; } else { this.config.baseroot = src; } //exit loop break; } } } //load excanvas js - as soon as possible if (this.isMSIE && typeof window.CanvasRenderingContext2D == 'undefined' && typeof G_vmlCanvasManager == 'undefined') { this.loadScript(this.config.baseroot + 'excanvas.js'); //alert('loadcanvas'); } //alert(this.config.baseroot); //load language js - as soon as possible if (!this.config.lang) { this.config.lang = this.detectLanguage(); } if (typeof imgmapStrings == 'undefined') { //language file might have already been loaded (ex highlighter mode) this.loadScript(this.config.baseroot + 'lang_' + this.config.lang + '.js'); } //check event hooks var found, j, le; for (i in this.config.custom_callbacks) { if (this.config.custom_callbacks.hasOwnProperty(i)) { found = false; for (j = 0, le = this.event_types.length; j < le; j++) { if (i == this.event_types[j]) { found = true; break; } } if (!found) { this.log("Unknown custom callback: " + i, 1); } } } //hook onload event - as late as possible this.addEvent(window, 'load', this.onLoad.bind(this)); return true; }; /** * currently unused * @ignore */ imgmap.prototype.retryDelayed = function(fn, delay, tries) { if (typeof fn.tries == 'undefined') {fn.tries = 0;} //alert(fn.tries+1); if (fn.tries++ < tries) { //alert('ss'); window.setTimeout(function() { fn.apply(this); }, delay); } }; /** * EVENT HANDLER: Handle event when the page with scripts is loaded. * @date 22-02-2007 0:16:22 * @author Adam Maschek (adam.maschek(at)gmail.com) * @param e The event object. */ imgmap.prototype.onLoad = function(e) { if (this.isLoaded) {return true;} var _this = this; //this.log('readystate: ' + document.readyState); if (typeof imgmapStrings == 'undefined') { if (this.cntReloads++ < 5) { //this.retryDelayed(_this.onLoad(), 1000, 3); window.setTimeout(function () {_this.onLoad(e);} ,1200); this.log('Delaying onload (language ' + this.config.lang + ' not loaded, try: ' + this.cntReloads + ')'); return false; } else if (this.config.lang != this.config.defaultLang && this.config.defaultLang != 'en') { this.log('Falling back to default language: ' + this.config.defaultLang); this.cntReloads = 0; this.config.lang = this.config.defaultLang; this.loadScript(this.config.baseroot + 'lang_' + this.config.lang + '.js'); window.setTimeout(function () {_this.onLoad(e);} ,1200); return false; } else if (this.config.lang != 'en') { this.log('Falling back to english language'); this.cntReloads = 0; this.config.lang = 'en'; this.loadScript(this.config.baseroot + 'lang_' + this.config.lang + '.js'); window.setTimeout(function () {_this.onLoad(e);} ,1200); return false; } } //else try { this.loadStrings(imgmapStrings); } catch (err) { this.log("Unable to load language strings", 1); } //check if ExplorerCanvas correctly loaded - detect if browser supports canvas //alert(typeof G_vmlCanvasManager + this.isMSIE + typeof window.CanvasRenderingContext2D); if (this.isMSIE) { //alert('cccc'); //alert(typeof G_vmlCanvasManager); if (typeof window.CanvasRenderingContext2D == 'undefined' && typeof G_vmlCanvasManager == 'undefined') { //alert('bbb'); /* if (this.cntReloads++ < 5) { var _this = this; //this.retryDelayed(_this.onLoad(), 1000, 3); window.setTimeout(function () { _this.onLoad(e); } ,1000 ); //alert('aaa'); this.log('Delaying onload (excanvas not loaded, try: ' + this.cntReloads + ')'); return false; } */ this.log(this.strings.ERR_EXCANVAS_LOAD, 2);//critical error } } if (this.config.mode == 'highlighter') { //call global scope function imgmap_spawnObjects(this.config); } this.isLoaded = true; return true; }; /** * Attach new 'evt' event handler 'callback' to 'obj' * @date 24-02-2007 21:16:20 * @param obj The object on which the handler is defined. * @param evt The name of the event, like mousedown. * @param callback The callback function (named if you want it to be removed). */ imgmap.prototype.addEvent = function(obj, evt, callback) { if (obj.attachEvent) { //Microsoft style registration model return obj.attachEvent("on" + evt, callback); } else if (obj.addEventListener) { //W3C style model obj.addEventListener(evt, callback, false); return true; } else { obj['on' + evt] = callback; } }; /** * Detach 'evt' event handled by 'callback' from 'obj' object. * Callback must be a non anonymous function, see eventHandlers. * @see #eventHandlers * Example: myimgmap.removeEvent(myimgmap.pic, 'mousedown', myimgmap.eventHandlers.img_mousedown); * @date 24-11-2007 15:22:17 * @param obj The object on which the handler is defined. * @param evt The name of the event, like mousedown. * @param callback The named callback function. */ imgmap.prototype.removeEvent = function(obj, evt, callback) { if (obj.detachEvent) { //Microsoft style detach model return obj.detachEvent("on" + evt, callback); } else if (obj.removeEventListener) { //W3C style model obj.removeEventListener(evt, callback, false); return true; } else { obj['on' + evt] = null; } }; /** * We need this because load events for scripts function slightly differently. * @link http://dean.edwards.name/weblog/2006/06/again/ * @author Adam Maschek (adam.maschek(at)gmail.com) * @date 24-03-2007 11:02:21 */ imgmap.prototype.addLoadEvent = function(obj, callback) { if (obj.attachEvent) { //Microsoft style registration model return obj.attachEvent("onreadystatechange", callback); } else if (obj.addEventListener) { //W3C style registration model obj.addEventListener('load', callback, false); return true; } else { obj.onload = callback; } }; /** * Include another js script into the current document. * @date 22-02-2007 0:17:04 * @author Adam Maschek (adam.maschek(at)gmail.com) * @param url The url of the script we want to load. * @see #script_load * @see #addLoadEvent */ imgmap.prototype.loadScript = function(url) { if (url === '') {return false;} if (this.loadedScripts[url] == 1) {return true;}//script already loaded this.log('Loading script: ' + url); //we might need this someday for safari? //var temp = '<script language="javascript" type="text/javascript" src="' + url + '"></script>'; //document.write(temp); try { var head = document.getElementsByTagName('head')[0]; var temp = document.createElement('SCRIPT'); temp.setAttribute('language', 'javascript'); temp.setAttribute('type', 'text/javascript'); temp.setAttribute('src', url); //temp.setAttribute('defer', true); head.appendChild(temp); this.addLoadEvent(temp, this.script_load.bind(this)); } catch (err) { this.log('Error loading script: ' + url); } return true; }; /** * EVENT HANDLER: Event handler of external script loaded. * @param e The event object. */ imgmap.prototype.script_load = function(e) { var obj = (this.isMSIE) ? window.event.srcElement : e.currentTarget; var url = obj.src; var complete = false; //alert(url); if (typeof obj.readyState != 'undefined') { //explorer if (obj.readyState == 'complete') { complete = true; } } else { //other browsers? complete = true; } if (complete) { this.loadedScripts[url] = 1; this.log('Loaded script: ' + url); return true; } }; /** * Load strings from a key:value object to the prototype strings array. * @author adam * @date 2007 * @param obj Javascript object that holds key:value pairs. */ imgmap.prototype.loadStrings = function(obj) { for (var key in obj) { if (obj.hasOwnProperty(key)) { this.strings[key] = obj[key]; } } }; /** * This function is to load a given img url to the pic_container. * * Loading an image will clear all current maps. * @see #useImage * @param img The imageurl or object to load (if object, function will get url, and do a recall) * @param imgw The width we want to force on the image (optional) * @param imgh The height we want to force on the image (optional) * @returns True on success */ imgmap.prototype.loadImage = function(img, imgw, imgh) { //test for container if (typeof this.pic_container == 'undefined') { this.log('You must have pic_container defined to use loadImage!', 2); return false; } //wipe all this.removeAllAreas(); //reset scale this.globalscale = 1; this.fireEvent('onHtmlChanged', '');//empty if (!this._getLastArea()) { //init with one new area if there was none editable if (this.config.mode != "editor2") {this.addNewArea();} } if (typeof img == 'string') { //there is an image given with url to load if (typeof this.pic == 'undefined') { this.pic = document.createElement('IMG'); this.pic_container.appendChild(this.pic); //event handler hooking - only at the first load this.addEvent(this.pic, 'mousedown', this.eventHandlers.img_mousedown = this.img_mousedown.bind(this)); this.addEvent(this.pic, 'mouseup', this.eventHandlers.img_mouseup = this.img_mouseup.bind(this)); this.addEvent(this.pic, 'mousemove', this.eventHandlers.img_mousemove = this.img_mousemove.bind(this)); this.pic.style.cursor = this.config.cursor_default; } //img ='../../'+img; this.log('Loading image: ' + img, 0); //calculate timestamp to bypass browser cache mechanism var q = '?'; if (img.indexOf('?') > -1) { q = '&'; } this.pic.src = img + q + (new Date().getTime()); if (imgw && imgw > 0) {this.pic.setAttribute('width', imgw);} if (imgh && imgh > 0) {this.pic.setAttribute('height', imgh);} this.fireEvent('onLoadImage', this.pic); return true; } else if (typeof img == 'object') { //we have to use the src of the image object var src = img.src; //img.getAttribute('src'); if (src === '' && img.getAttribute('mce_src') !== '') { //if it is a tinymce object, it has no src but mce_src attribute! src = img.getAttribute('mce_src'); } else if (src === '' && img.getAttribute('_fcksavedurl') !== '') { //if it is an fck object, it might have only _fcksavedurl attribute! src = img.getAttribute('_fcksavedurl'); } // Get the displayed dimensions of the image if (!imgw) { imgw = img.clientWidth; } if (!imgh) { imgh = img.clientHeight; } //recurse, this time with the url string return this.loadImage(src, imgw, imgh); } }; /** * We use this when there is an existing image object we want to handle with imgmap. * Mainly used in highlighter mode. * @author adam * @see #loadImage * @see #imgmap_spawnObjects * @date 2007 * @param img DOM object or id of image we want to use. */ imgmap.prototype.useImage = function(img) { //wipe all this.removeAllAreas(); if (!this._getLastArea()) { //init with one new area if there was none editable if (this.config.mode != "editor2") {this.addNewArea();} } img = this.assignOID(img); if (typeof img == 'object') { if (typeof this.pic != 'undefined') { //remove previous handlers this.removeEvent(this.pic, 'mousedown', this.eventHandlers.img_mousedown); this.removeEvent(this.pic, 'mouseup', this.eventHandlers.img_mouseup); this.removeEvent(this.pic, 'mousemove', this.eventHandlers.img_mousemove); this.pic.style.cursor = ''; } this.pic = img; //hook event handlers this.addEvent(this.pic, 'mousedown', this.eventHandlers.img_mousedown = this.img_mousedown.bind(this)); this.addEvent(this.pic, 'mouseup', this.eventHandlers.img_mouseup = this.img_mouseup.bind(this)); this.addEvent(this.pic, 'mousemove', this.eventHandlers.img_mousemove = this.img_mousemove.bind(this)); this.pic.style.cursor = this.config.cursor_default; if (this.pic.parentNode.className == 'pic_container') { //use existing container this.pic_container = this.pic.parentNode; } else { //dynamically create container this.pic_container = document.createElement("div"); this.pic_container.className = 'pic_container'; this.pic.parentNode.insertBefore(this.pic_container, this.pic); //ref: If the node already exists it is removed from current parent node, then added to new parent node. this.pic_container.appendChild(this.pic); } this.fireEvent('onLoadImage', this.pic); return true; } }; /** * Fires custom hook onStatusMessage, passing the status string. * Use this to update your GUI. * @author Adam Maschek (adam.maschek(at)gmail.com) * @date 26-07-2008 13:22:54 * @param str The status string */ imgmap.prototype.statusMessage = function(str) { this.fireEvent('onStatusMessage', str); }; /** * Adds basic logging functionality using firebug console object if available. * Also tries to use AIR introspector if available. * @date 20-02-2007 17:55:18 * @author Adam Maschek (adam.maschek(at)gmail.com) * @param obj The object or string you want to debug/echo. * @level level The log level, 0 being the smallest issue. */ imgmap.prototype.log = function(obj, level) { if (level === '' || typeof level == 'undefined') {level = 0;} if (this.config.loglevel != -1 && level >= this.config.loglevel) { this.logStore.push({level: level, obj: obj}); } if (typeof console == 'object') { console.log(obj); } else if (this.isOpera) { opera.postError(level + ': ' + obj); } else if (typeof air == 'object') { //we are inside AIR if (typeof air.Introspector == 'object') { air.Introspector.Console.log(obj); } else { air.trace(obj); } } else { if (level > 1) { //alert(level + ': ' + obj); //dump with all pevious errors: var msg = ''; for (var i=0, le = this.logStore.length; i<le; i++) { msg+= this.logStore[i].level + ': ' + this.logStore[i].obj + "\n"; } alert(msg); } else { window.defaultStatus = (level + ': ' + obj); } } }; /** * Produces the image map HTML output with the defined areas. * Invokes getMapInnerHTML. * @author Adam Maschek (adam.maschek(at)gmail.com) * @date 2006-06-06 15:10:27 * @param flags Currently ony 'noscale' used to prevent scaling of coordinates in preview mode. * @return The generated html code. */ imgmap.prototype.getMapHTML = function(flags) { var html = '<map id="'+this.getMapId()+'" name="'+this.getMapName()+'">' + this.getMapInnerHTML(flags) + this.waterMark + '</map>'; this.fireEvent('onGetMap', html); //alert(html); return html; }; /** * Get the map areas part only of the current imagemap. * @see #getMapHTML * @author adam * @param flags Currently ony 'noscale' used to prevent scaling of coordinates in preview mode. * @return The generated map code without the map wrapper. */ imgmap.prototype.getMapInnerHTML = function(flags) { var html, coords; html = ''; //foreach area properties for (var i=0, le = this.areas.length; i<le; i++) { if (this.areas[i]) { if (this.areas[i].shape && this.areas[i].shape != 'undefined') { coords = this.areas[i].lastInput; if (flags && flags.match(/noscale/)) { //for preview use real coordinates, not scaled var cs = coords.split(','); for (var j=0, le2 = cs.length; j<le2; j++) { cs[j] = Math.round(cs[j] * this.globalscale); } coords = cs.join(','); } html+= '<area shape="' + this.areas[i].shape + '"' + ' alt="' + this.areas[i].aalt + '"' + ' title="' + this.areas[i].atitle + '"' + ' coords="' + coords + '"' + ' href="' + this.areas[i].ahref + '"' + ' target="' + this.areas[i].atarget + '" />'; } } } //alert(html); return html; }; /** * Get the map name of the current imagemap. * If doesnt exist, nor map id, generate a new name based on timestamp. * The most portable solution is to use the same value for id and name. * This also conforms the HTML 5 specification, that says: * "If the id attribute is also specified, both attributes must have the same value." * @link http://www.w3.org/html/wg/html5/#the-map-element * @author adam * @see #getMapId * @return The name of the map. */ imgmap.prototype.getMapName = function() { if (this.mapname === '') { if (this.mapid !== '') {return this.mapid;} var now = new Date(); this.mapname = 'imgmap' + now.getFullYear() + (now.getMonth()+1) + now.getDate() + now.getHours() + now.getMinutes() + now.getSeconds(); } return this.mapname; }; /** * Get the map id of the current imagemap. * If doesnt exist, use map name. * @author adam * @see #getMapName * @return The id of the map. */ imgmap.prototype.getMapId = function() { if (this.mapid === '') { this.mapid = this.getMapName(); } return this.mapid; }; /** * Convert wild shape names to normal ones. * @date 25-12-2008 19:27:06 * @param shape The name of the shape to convert. * @return The normalized shape name, rect as default. */ imgmap.prototype._normShape = function(shape) { if (!shape) {return 'rect';} shape = this.trim(shape).toLowerCase(); if (shape.substring(0, 4) == 'rect') {return 'rect';} if (shape.substring(0, 4) == 'circ') {return 'circle';} if (shape.substring(0, 4) == 'poly') {return 'poly';} return 'rect'; }; /** * Try to normalize coordinates that came from: * 1. html textarea * 2. user input in the active area's input field * 3. from the html source in case of plugins or highlighter * Example of inputs that need to be handled: * 035,035 075,062 * 150,217, 190,257, 150,297,110,257 * @author adam * @param coords The coordinates in a string. * @param shape The shape of the object (rect, circle, poly, bezier1). * @param flag Flags that modify the operation. (fromcircle, frompoly, fromrect, preserve) * @returns The normalized coordinates. */ imgmap.prototype._normCoords = function(coords, shape, flag) { //function level var declarations var i;//generic cycle counter var sx;//smallest x var sy;//smallest y var gx;//greatest x var gy;//greatest y var temp, le; //console.log('normcoords: ' + coords + ' - ' + shape + ' - ' + flag); coords = this.trim(coords); if (coords === '') {return '';} var oldcoords = coords; //replace some general junk coords = coords.replace(/(\d)(\D)+(\d)/g, "$1,$3"); coords = coords.replace(/,\D+(\d)/g, ",$1");//cut leading junk coords = coords.replace(/,0+(\d)/g, ",$1");//cut leading zeros coords = coords.replace(/(\d)(\D)+,/g, "$1,"); coords = coords.replace(/^\D+(\d)/g, "$1");//cut leading junk coords = coords.replace(/^0+(\d)/g, "$1");//cut leading zeros coords = coords.replace(/(\d)(\D)+$/g, "$1");//cut trailing junk //console.log('>'+coords + ' - ' + shape + ' - ' + flag); //now fix other issues var parts = coords.split(','); if (shape == 'rect') { if (flag == 'fromcircle') { var r = parts[2]; parts[0] = parts[0] - r; parts[1] = parts[1] - r; parts[2] = parseInt(parts[0], 10) + 2 * r; parts[3] = parseInt(parts[1], 10) + 2 * r; } else if (flag == 'frompoly') { sx = parseInt(parts[0], 10); gx = parseInt(parts[0], 10); sy = parseInt(parts[1], 10); gy = parseInt(parts[1], 10); for (i=0, le = parts.length; i<le; i++) { if (i % 2 === 0 && parseInt(parts[i], 10) < sx) { sx = parseInt(parts[i], 10);} if (i % 2 === 1 && parseInt(parts[i], 10) < sy) { sy = parseInt(parts[i], 10);} if (i % 2 === 0 && parseInt(parts[i], 10) > gx) { gx = parseInt(parts[i], 10);} if (i % 2 === 1 && parseInt(parts[i], 10) > gy) { gy = parseInt(parts[i], 10);} //console.log(sx+","+sy+","+gx+","+gy); } parts[0] = sx; parts[1] = sy; parts[2] = gx; parts[3] = gy; } if (!(parseInt(parts[1], 10) >= 0)) {parts[1] = parts[0];} if (!(parseInt(parts[2], 10) >= 0)) {parts[2] = parseInt(parts[0], 10) + 10;} if (!(parseInt(parts[3], 10) >= 0)) {parts[3] = parseInt(parts[1], 10) + 10;} if (parseInt(parts[0], 10) > parseInt(parts[2], 10)) { temp = parts[0]; parts[0] = parts[2]; parts[2] = temp; } if (parseInt(parts[1], 10) > parseInt(parts[3], 10)) { temp = parts[1]; parts[1] = parts[3]; parts[3] = temp; } coords = parts[0]+","+parts[1]+","+parts[2]+","+parts[3]; //console.log(coords); } else if (shape == 'circle') { if (flag == 'fromrect') { sx = parseInt(parts[0], 10); gx = parseInt(parts[2], 10); sy = parseInt(parts[1], 10); gy = parseInt(parts[3], 10); //use smaller side parts[2] = (gx - sx < gy - sy) ? gx - sx : gy - sy; parts[2] = Math.floor(parts[2] / 2);//radius parts[0] = sx + parts[2]; parts[1] = sy + parts[2]; } else if (flag == 'frompoly') { sx = parseInt(parts[0], 10); gx = parseInt(parts[0], 10); sy = parseInt(parts[1], 10); gy = parseInt(parts[1], 10); for (i=0, le = parts.length; i<le; i++) { if (i % 2 === 0 && parseInt(parts[i], 10) < sx) { sx = parseInt(parts[i], 10);} if (i % 2 === 1 && parseInt(parts[i], 10) < sy) { sy = parseInt(parts[i], 10);} if (i % 2 === 0 && parseInt(parts[i], 10) > gx) { gx = parseInt(parts[i], 10);} if (i % 2 === 1 && parseInt(parts[i], 10) > gy) { gy = parseInt(parts[i], 10);} //console.log(sx+","+sy+","+gx+","+gy); } //use smaller side parts[2] = (gx - sx < gy - sy) ? gx - sx : gy - sy; parts[2] = Math.floor(parts[2] / 2);//radius parts[0] = sx + parts[2]; parts[1] = sy + parts[2]; } if (!(parseInt(parts[1], 10) > 0)) {parts[1] = parts[0];} if (!(parseInt(parts[2], 10) > 0)) {parts[2] = 10;} coords = parts[0]+","+parts[1]+","+parts[2]; } else if (shape == 'poly') { if (flag == 'fromrect') { parts[4] = parts[2]; parts[5] = parts[3]; parts[2] = parts[0]; parts[6] = parts[4]; parts[7] = parts[1]; } else if (flag == 'fromcircle') { //@url http://www.pixelwit.com/blog/2007/06/29/basic-circle-drawing-actionscript/ var centerX = parseInt(parts[0], 10); var centerY = parseInt(parts[1], 10); var radius = parseInt(parts[2], 10); var j = 0; parts[j++] = centerX + radius; parts[j++] = centerY; var sides = 60;//constant = sides the fake circle will have for (i=0; i<=sides; i++) { var pointRatio = i/sides; var xSteps = Math.cos(pointRatio*2*Math.PI); var ySteps = Math.sin(pointRatio*2*Math.PI); var pointX = centerX + xSteps * radius; var pointY = centerY + ySteps * radius; parts[j++] = Math.round(pointX); parts[j++] = Math.round(pointY); } //console.log(parts); } coords = parts.join(','); } else if (shape == 'bezier1') { coords = parts.join(','); } if (flag == 'preserve' && oldcoords != coords) { //return original and throw error //throw "invalid coords"; return oldcoords; } return coords; }; /** * Sets the coordinates according to the given HTML map code or DOM object. * @author Adam Maschek (adam.maschek(at)gmail.com) * @date 2006-06-07 11:47:16 * @param map DOM object or string of a map you want to apply. * @return True on success */ imgmap.prototype.setMapHTML = function(map) { if (this.viewmode === 1) {return;}//exit if preview mode this.fireEvent('onSetMap', map); //this.log(map); //remove all areas this.removeAllAreas(); //console.log(this.areas); var oMap; if (typeof map == 'string') { var oHolder = document.createElement('DIV'); oHolder.innerHTML = map; oMap = oHolder.firstChild; } else if (typeof map == 'object') { oMap = map; } if (!oMap || oMap.nodeName.toLowerCase() !== 'map') {return false;} this.mapname = oMap.name; this.mapid = oMap.id; var newareas = oMap.getElementsByTagName('area'); var shape, coords, href, alt, title, target, id; for (var i=0, le = newareas.length; i<le; i++) { shape = coords = href = alt = title = target = ''; id = this.addNewArea();//btw id == this.currentid, just this form is a bit clearer shape = this._normShape(newareas[i].getAttribute('shape', 2)); this.initArea(id, shape); if (newareas[i].getAttribute('coords', 2)) { //normalize coords coords = this._normCoords(newareas[i].getAttribute('coords', 2), shape); this.areas[id].lastInput = coords; //for area this one will be set in recalculate } href = newareas[i].getAttribute('href', 2); // FCKeditor stored url to prevent mangling from the browser. var sSavedUrl = newareas[i].getAttribute( '_fcksavedurl' ); if (sSavedUrl) { href = sSavedUrl; } if (href) { this.areas[id].ahref = href; } alt = newareas[i].getAttribute('alt'); if (alt) { this.areas[id].aalt = alt; } title = newareas[i].getAttribute('title'); if (!title) {title = alt;} if (title) { this.areas[id].atitle = title; } target = newareas[i].getAttribute('target'); if (target) {target = target.toLowerCase();} // if (target == '') target = '_self'; this.areas[id].atarget = target; this._recalculate(id, coords);//contains repaint this.relaxArea(id); this.fireEvent('onAreaChanged', this.areas[id]); }//end for areas this.fireEvent('onHtmlChanged', this.getMapHTML()); return true; }; /** * Preview image with imagemap applied. * @author Adam Maschek (adam.maschek(at)gmail.com) * @date 2006-06-06 14:51:01 * @url http://www.quirksmode.org/bugreports/archives/2005/03/Usemap_attribute_wrongly_case_sensitive.html * @return False on error, 0 when switched to edit mode, 1 when switched to preview mode */ imgmap.prototype.togglePreview = function() { var i, le;//generic cycle counter if (!this.pic) {return false;}//exit if pic is undefined //dynamically create preview container if (!this.preview) { this.preview = document.createElement('DIV'); this.preview.style.display = 'none'; this.pic_container.appendChild(this.preview); } if (this.viewmode === 0) { //hide canvas elements and labels for (i = 0, le = this.areas.length; i < le; i++) { if (this.areas[i]) { this.areas[i].style.display = 'none'; if (this.areas[i].label) {this.areas[i].label.style.display = 'none';} } } //activate image map this.preview.innerHTML = this.getMapHTML('noscale'); this.pic.setAttribute('border', '0', 0); this.pic.setAttribute('usemap', '#' + this.mapname, 0); this.pic.style.cursor = 'auto'; this.viewmode = 1; this.statusMessage(this.strings.PREVIEW_MODE); } else { //show canvas elements for (i = 0, le = this.areas.length; i < le; i++) { if (this.areas[i]) { this.areas[i].style.display = ''; if (this.areas[i].label && this.config.label) {this.areas[i].label.style.display = '';} } } //clear image map this.preview.innerHTML = ''; this.pic.style.cursor = this.config.cursor_default; this.pic.removeAttribute('usemap', 0); this.viewmode = 0; this.statusMessage(this.strings.DESIGN_MODE); this.is_drawing = 0; } this.fireEvent('onModeChanged', this.viewmode); return this.viewmode; }; /** * Adds a new area. It will later become a canvas. * GUI should use the onAddArea callback to act accordingly. * @author Adam Maschek (adam.maschek(at)gmail.com) * @date 2006-06-06 16:49:25 * @see #initArea */ imgmap.prototype.addNewArea = function() { if (this.viewmode === 1) {return;}//exit if preview mode var lastarea = this._getLastArea(); var id = (lastarea) ? lastarea.aid + 1 : 0; //alert(id); //insert new possibly? unknown area (will be initialized at mousedown) this.areas[id] = document.createElement('DIV'); this.areas[id].id = this.mapname + 'area' + id; this.areas[id].aid = id; this.areas[id].shape = "undefined"; this.currentid = id; this.fireEvent('onAddArea', id); return id; }; /** * Initialize a new area. * Create the canvas, initialize it. * Reset area parameters. * @param id The id of the area (already existing with undefined shape) * @param shape The shape the area will have (rect, circle, poly, bezier1) */ imgmap.prototype.initArea = function(id, shape) { if (!this.areas[id]) {return false;}//if all was erased, return //remove preinited dummy div or already placed canvas if (this.areas[id].parentNode) {this.areas[id].parentNode.removeChild(this.areas[id]);} if (this.areas[id].label) {this.areas[id].label.parentNode.removeChild(this.areas[id].label);} this.areas[id] = null; //create CANVAS node this.areas[id] = document.createElement('CANVAS'); this.pic_container.appendChild(this.areas[id]); this.pic_container.style.position = 'relative'; //alert('init' + typeof G_vmlCanvasManager); if (typeof G_vmlCanvasManager != "undefined") { //override CANVAS with VML object this.areas[id] = G_vmlCanvasManager.initElement(this.areas[id]); //this.areas[id] = this.pic.parentNode.lastChild; } this.areas[id].id = this.mapname + 'area' + id; this.areas[id].aid = id; this.areas[id].shape = shape; this.areas[id].ahref = ''; this.areas[id].atitle = ''; this.areas[id].aalt = ''; this.areas[id].atarget = ''; // '_self'; this.areas[id].style.position = 'absolute'; this.areas[id].style.top = this.pic.offsetTop + 'px'; this.areas[id].style.left = this.pic.offsetLeft + 'px'; this._setopacity(this.areas[id], this.config.CL_DRAW_BG, this.config.draw_opacity); //hook event handlers this.areas[id].ondblclick = this.area_dblclick.bind(this); this.areas[id].onmousedown = this.area_mousedown.bind(this); this.areas[id].onmouseup = this.area_mouseup.bind(this); this.areas[id].onmousemove = this.area_mousemove.bind(this); this.areas[id].onmouseover = this.area_mouseover.bind(this); this.areas[id].onmouseout = this.area_mouseout.bind(this); //initialize memory object this.memory[id] = {}; this.memory[id].downx = 0; this.memory[id].downy = 0; this.memory[id].left = 0; this.memory[id].top = 0; this.memory[id].width = 0; this.memory[id].height = 0; this.memory[id].xpoints = []; this.memory[id].ypoints = []; //create label node this.areas[id].label = document.createElement('DIV'); this.pic_container.appendChild(this.areas[id].label); this.areas[id].label.className = this.config.label_class; this.assignCSS(this.areas[id].label, this.config.label_style); this.areas[id].label.style.position = 'absolute'; }; /** * Resets area border and opacity to a normal state after drawing. * @author Adam Maschek (adam.maschek(at)gmail.com) * @date 15-02-2007 22:07:28 * @param id The id of the area. * @see #relaxAllAreas */ imgmap.prototype.relaxArea = function(id) { if (!this.areas[id]) {return;} this.fireEvent('onRelaxArea', id); this._setBorder(id, 'NORM'); this._setopacity(this.areas[id], this.config.CL_NORM_BG, this.config.norm_opacity); }; /** * Resets area border and opacity of all areas. * Calls relaxArea on each of them. * @author Adam Maschek (adam.maschek(at)gmail.com) * @date 23-04-2007 23:31:09 * @see #relaxArea */ imgmap.prototype.relaxAllAreas = function() { for (var i=0, le = this.areas.length; i<le; i++) { if (this.areas[i]) { this.relaxArea(i); } } }; /** * Set border of a given area according to style flag. * Possible values of style: NORM, HIGHLIGHT, DRAW. * Non-rectangle shapes wont get a border if config.bounding_box is false. * @date 26-12-2008 22:34:41 * @param id The id of the area to set the border on. * @param style Coloring style (NORM, HIGHLIGHT, DRAW), see relevant colors in config. * @since 2.1 */ imgmap.prototype._setBorder = function(id, style) { if (this.areas[id].shape == 'rect' || this.config.bounding_box) { this.areas[id].style.borderWidth = '1px'; this.areas[id].style.borderStyle = (style == 'DRAW' ? 'dotted' : 'solid'); this.areas[id].style.borderColor = this.config['CL_' + style + '_' + (this.areas[id].shape == 'rect' ? 'SHAPE' : 'BOX')]; } else { //clear border this.areas[id].style.border = ''; } }; /** * Set opacity of area to the given percentage, as well as set the background color. * If percentage contains a dash(-), the setting of the opacity will be gradual. * @param area The area object. * @param bgcolor New background color * @param pct Percentage of the opacity. */ imgmap.prototype._setopacity = function(area, bgcolor, pct) { if (bgcolor) {area.style.backgroundColor = bgcolor;} if (pct && typeof pct == 'string' && pct.match(/^\d*\-\d+$/)) { //gradual fade var parts = pct.split('-'); if (typeof parts[0] != 'undefined') { //set initial opacity parts[0] = parseInt(parts[0], 10); this._setopacity(area, bgcolor, parts[0]); } if (typeof parts[1] != 'undefined') { parts[1] = parseInt(parts[1], 10); var curr = this._getopacity(area); //this.log('curr: '+curr); var _this = this; var diff = Math.round(parts[1] - curr); if (diff > 5) { window.setTimeout(function () {_this._setopacity(area, null, '-'+parts[1]);}, 20); pct = 1*curr + 5; } else if (diff < -3) { window.setTimeout(function () {_this._setopacity(area, null, '-'+parts[1]);}, 20); pct = 1*curr - 3; } else { //final set pct = parts[1]; } } } if (!isNaN(pct)) { pct = Math.round(parseInt(pct, 10)); //this.log('set ('+area.aid+'): ' + pct, 1); area.style.opacity = pct / 100; area.style.filter = 'alpha(opacity='+pct+')'; } }; /** * Get the currently set opacity of a given area. * @author adam * @param area The area (canvas) you want to get opacity info from. * @return Opacity value in a range of 0-100. */ imgmap.prototype._getopacity = function(area) { if (area.style.opacity <= 1) { return area.style.opacity * 100; } if (area.style.filter) { //alpha(opacity=NaN) return parseInt(area.style.filter.replace(/alpha\(opacity\=([^\)]*)\)/ig, "$1"), 10); } return 100;//default opacity }; /** * Removes the area marked by id. * removeAllAreas will indicate a mass flag so that the output HTML will only be updated at * the end of the operation. * Callback will call the GUI code to remove GUI elements. * @author Adam Maschek (adam.maschek(at)gmail.com) * @date 11-02-2007 20:40:58 * @param id The id of the area to remove. * @param mass Flag to indicate skipping the call of onHtmlChanged callback * @see #removeAllAreas */ imgmap.prototype.removeArea = function(id, mass) { if (this.viewmode === 1) {return;}//exit if preview mode if (id === null || typeof id == "undefined") {return;}//exit if no id given try { //remove area and label //explicitly set some values to null to avoid IE circular reference memleak this.areas[id].label.parentNode.removeChild(this.areas[id].label); this.areas[id].parentNode.removeChild(this.areas[id]); this.areas[id].label.className = null; //this.areas[id].label.style = null; //console.log(this.areas[id].label); this.areas[id].label = null; this.areas[id].onmouseover = null; this.areas[id].onmouseout = null; this.areas[id].onmouseup = null; this.areas[id].onmousedown = null; this.areas[id].onmousemove = null; // console.log(this.areas[id].label); } catch (err) { //alert('noparent'); } this.areas[id] = null; this.fireEvent('onRemoveArea', id); //update grand html if (!mass) {this.fireEvent('onHtmlChanged', this.getMapHTML());} }; /** * Removes all areas. * Will call removeArea on all areas. * @author Adam Maschek (adam.maschek(at)gmail.com) * @date 2006-06-07 11:55:34 * @see #removeArea */ imgmap.prototype.removeAllAreas = function() { for (var i = 0, le = this.areas.length; i < le; i++) { if (this.areas[i]) { this.removeArea(i, true); } } //only call this at the end, use mass param above to avoid calling it in process this.fireEvent('onHtmlChanged', this.getMapHTML()); }; /** * Scales all areas. * Will store scale parameter in globalscale property. * This is needed to know how to draw new areas on an already scaled canvas. * @author adam * @date 02-11-2008 14:13:14 * @param scale Scale factor (1-original, 0.5-half, 2-double, etc.) */ imgmap.prototype.scaleAllAreas = function(scale) { var rscale = 1;//relative scale try { rscale = scale / this.globalscale; } catch (err) { this.log("Invalid (global)scale", 1); } //console.log('gscale: '+this.globalscale); //console.log('scale: '+scale); //console.log('rscale: '+rscale); this.globalscale = scale; for (var i = 0, le = this.areas.length; i < le; i++) { if (this.areas[i] && this.areas[i].shape != 'undefined') { this.scaleArea(i, rscale); } } }; /** * Scales one area. * @author adam * @date 02-11-2008 14:13:14 * @param rscale Relative scale factor (1-keep, 0.5-half, 2-double, etc.) */ imgmap.prototype.scaleArea = function(id, rscale) { //set position and new dimensions this.areas[id].style.top = parseInt(this.areas[id].style.top, 10) * rscale + 'px'; this.areas[id].style.left = parseInt(this.areas[id].style.left, 10) * rscale + 'px'; this.setAreaSize(id, this.areas[id].width * rscale, this.areas[id].height * rscale); //handle polygon/bezier coordinates scaling if (this.areas[id].shape == 'poly' || this.areas[id].shape == 'bezier1') { for (var i=0, le = this.areas[id].xpoints.length; i<le; i++) { this.areas[id].xpoints[i]*= rscale; this.areas[id].ypoints[i]*= rscale; } } this._repaint(this.areas[id], this.config.CL_NORM_SHAPE); this._updatecoords(id); }; /** * Put label in the top left corner according to label config. * By default it will contain the number of the area (area.aid) * @param id The id of the area to add label to. */ imgmap.prototype._putlabel = function(id) { if (this.viewmode === 1) {return;}//exit if preview mode if (!this.areas[id].label) {return;}//not yet inited try { if (!this.config.label) { this.areas[id].label.innerHTML = ''; this.areas[id].label.style.display = 'none'; } else { this.areas[id].label.style.display = ''; var label = this.config.label; label = label.replace(/%n/g, String(id)); label = label.replace(/%c/g, String(this.areas[id].lastInput)); label = label.replace(/%h/g, String(this.areas[id].ahref)); label = label.replace(/%a/g, String(this.areas[id].aalt)); label = label.replace(/%t/g, String(this.areas[id].atitle)); this.areas[id].label.innerHTML = label; } //align to the top left corner this.areas[id].label.style.top = this.areas[id].style.top; this.areas[id].label.style.left = this.areas[id].style.left; } catch (err) { this.log("Error putting label", 1); } }; /** * Set area title and alt (for IE) according to the hint configuration. * This will show up in the usual yellow box when you hover over with the mouse. * @param id The id of the area to set hint at. */ imgmap.prototype._puthint = function(id) { try { if (!this.config.hint) { this.areas[id].title = ''; this.areas[id].alt = ''; } else { var hint = this.config.hint; hint = hint.replace(/%n/g, String(id)); hint = hint.replace(/%c/g, String(this.areas[id].lastInput)); hint = hint.replace(/%h/g, String(this.areas[id].ahref)); hint = hint.replace(/%a/g, String(this.areas[id].aalt)); hint = hint.replace(/%t/g, String(this.areas[id].atitle)); this.areas[id].title = hint; this.areas[id].alt = hint; } } catch (err) { this.log("Error putting hint", 1); } }; /** * Will call repaint on all areas. * Useful when you change labeling or hint config on the GUI. * @see #_repaint */ imgmap.prototype._repaintAll = function() { for (var i=0, le = this.areas.length; i<le; i++) { if (this.areas[i]) { this._repaint(this.areas[i], this.config.CL_NORM_SHAPE); } } }; /** * Repaints the actual canvas content. * This is the only canvas drawing magic that is happening. * In fact rectangles will not have any canvas content, just a normal css border. * After repainting the canvas, it will call putlabel and puthint methods. * @param area The area object. * @param color Color of the line to draw on the canvas. * @param x Only used for polygons/beziers as the newest control point x. * @param y Only used for polygons/beziers as the newest control point y. */ imgmap.prototype._repaint = function(area, color, x, y) { var ctx;//canvas context var width, height, left, top;//canvas properties var i, le;//loop counter if (area.shape == 'circle') { width = parseInt(area.style.width, 10); var radius = Math.floor(width/2) - 1; //get canvas context //alert(area.tagName); ctx = area.getContext("2d"); //clear canvas ctx.clearRect(0, 0, width, width); //draw circle ctx.beginPath(); ctx.strokeStyle = color; ctx.arc(radius, radius, radius, 0, Math.PI*2, 0); ctx.stroke(); ctx.closePath(); //draw center ctx.strokeStyle = this.config.CL_KNOB; ctx.strokeRect(radius, radius, 1, 1); //put label this._putlabel(area.aid); this._puthint(area.aid); } else if (area.shape == 'rect') { //put label this._putlabel(area.aid); this._puthint(area.aid); } else if (area.shape == 'poly') { width = parseInt(area.style.width, 10); height = parseInt(area.style.height, 10); left = parseInt(area.style.left, 10); top = parseInt(area.style.top, 10); if (area.xpoints) { //get canvas context ctx = area.getContext("2d"); //clear canvas ctx.clearRect(0, 0, width, height); //draw polygon ctx.beginPath(); ctx.strokeStyle = color; ctx.moveTo(area.xpoints[0] - left, area.ypoints[0] - top); for (i = 1, le = area.xpoints.length; i < le; i++) { ctx.lineTo(area.xpoints[i] - left , area.ypoints[i] - top); } if (this.is_drawing == this.DM_POLYGON_DRAW || this.is_drawing == this.DM_POLYGON_LASTDRAW) { //only draw to the current position if not moving ctx.lineTo(x - left - 5 , y - top - 5); } ctx.lineTo(area.xpoints[0] - left , area.ypoints[0] - top); ctx.stroke(); ctx.closePath(); } //put label this._putlabel(area.aid); this._puthint(area.aid); } else if (area.shape == 'bezier1') { width = parseInt(area.style.width, 10); height = parseInt(area.style.height, 10); left = parseInt(area.style.left, 10); top = parseInt(area.style.top, 10); if (area.xpoints) { //get canvas context ctx = area.getContext("2d"); //clear canvas ctx.clearRect(0, 0, width, height); //draw bezier1 (every second point is control point) ctx.beginPath(); ctx.strokeStyle = color; //move to the beginning position ctx.moveTo(area.xpoints[0] - left, area.ypoints[0] - top); //draw previous points - use every second point only for (i = 2, le = area.xpoints.length; i < le; i+= 2) { ctx.quadraticCurveTo(area.xpoints[i-1] - left, area.ypoints[i-1] - top, area.xpoints[i] - left, area.ypoints[i] - top); } if (this.is_drawing == this.DM_BEZIER_DRAW || this.is_drawing == this.DM_BEZIER_LASTDRAW) { //only draw to the current position if not moving if (area.xpoints.length % 2 === 0 && area.xpoints.length > 1) { //drawing point - draw a curve to it using the previous control point ctx.quadraticCurveTo(area.xpoints[area.xpoints.length - 1] - left - 5 , area.ypoints[area.ypoints.length - 1] - top - 5, x - left - 5 , y - top - 5); } else { //control point - simply draw a line to it ctx.lineTo(x - left - 5 , y - top - 5); } } //close area by drawing a line to the first point ctx.lineTo(area.xpoints[0] - left , area.ypoints[0] - top); ctx.stroke(); ctx.closePath(); } //put label this._putlabel(area.aid); this._puthint(area.aid); } }; /** * Updates Area coordinates. * Called when needed, eg. on mousemove, mousedown. * Also updates html container value (thru hook). * Calls callback onAreaChanged and onHtmlChanged so that GUI can follow. * This is an important hook to your GUI. * Uses globalscale to scale real coordinates to area coordinates. * @date 2006.10.24. 22:39:27 * @author Adam Maschek (adam.maschek(at)gmail.com) * @param id The id of the area. */ imgmap.prototype._updatecoords = function(id) { var left = Math.round(parseInt(this.areas[id].style.left, 10) / this.globalscale); var top = Math.round(parseInt(this.areas[id].style.top, 10) / this.globalscale); var height = Math.round(parseInt(this.areas[id].style.height, 10) / this.globalscale); var width = Math.round(parseInt(this.areas[id].style.width, 10) / this.globalscale); var value = ''; if (this.areas[id].shape == 'rect') { value = left + ',' + top + ',' + (left + width) + ',' + (top + height); this.areas[id].lastInput = value; } else if (this.areas[id].shape == 'circle') { var radius = Math.floor(width/2) - 1; value = (left + radius) + ',' + (top + radius) + ',' + radius; this.areas[id].lastInput = value; } else if (this.areas[id].shape == 'poly' || this.areas[id].shape == 'bezier1') { if (this.areas[id].xpoints) { for (var i=0, le = this.areas[id].xpoints.length; i<le; i++) { value+= Math.round(this.areas[id].xpoints[i] / this.globalscale) + ',' + Math.round(this.areas[id].ypoints[i] / this.globalscale) + ','; } value = value.substring(0, value.length - 1); } this.areas[id].lastInput = value; } this.fireEvent('onAreaChanged', this.areas[id]); this.fireEvent('onHtmlChanged', this.getMapHTML()); }; /** * Updates the visual representation of the area with the given id according * to the new coordinates that typically come from an input on the GUI. * Uses globalscale to scale area coordinates to real coordinates. * @date 2006.10.24. 22:46:55 * @author Adam Maschek (adam.maschek(at)gmail.com) * @param id The id of the area. * @param coords The new coords, they will be normalized. */ imgmap.prototype._recalculate = function(id, coords) { try { if (coords) { coords = this._normCoords(coords, this.areas[id].shape, 'preserve'); } else { coords = this.areas[id].lastInput || '' ; } var parts = coords.split(','); if (this.areas[id].shape == 'rect') { if (parts.length != 4 || parseInt(parts[0], 10) > parseInt(parts[2], 10) || parseInt(parts[1], 10) > parseInt(parts[3], 10)) {throw "invalid coords";} this.areas[id].style.left = this.globalscale * (this.pic.offsetLeft + parseInt(parts[0], 10)) + 'px'; this.areas[id].style.top = this.globalscale * (this.pic.offsetTop + parseInt(parts[1], 10)) + 'px'; this.setAreaSize(id, this.globalscale * (parts[2] - parts[0]), this.globalscale * (parts[3] - parts[1])); this._repaint(this.areas[id], this.config.CL_NORM_SHAPE); } else if (this.areas[id].shape == 'circle') { if (parts.length != 3 || parseInt(parts[2], 10) < 0) {throw "invalid coords";} var width = 2 * (parts[2]); //alert(parts[2]); //alert(width); this.setAreaSize(id, this.globalscale * width, this.globalscale * width); this.areas[id].style.left = this.globalscale * (this.pic.offsetLeft + parseInt(parts[0], 10) - width/2) + 'px'; this.areas[id].style.top = this.globalscale * (this.pic.offsetTop + parseInt(parts[1], 10) - width/2) + 'px'; this._repaint(this.areas[id], this.config.CL_NORM_SHAPE); } else if (this.areas[id].shape == 'poly' || this.areas[id].shape == 'bezier1') { if (parts.length < 2) {throw "invalid coords";} this.areas[id].xpoints = []; this.areas[id].ypoints = []; for (var i=0, le = parts.length; i<le; i+=2) { this.areas[id].xpoints[this.areas[id].xpoints.length] = this.globalscale * (this.pic.offsetLeft + parseInt(parts[i], 10)); this.areas[id].ypoints[this.areas[id].ypoints.length] = this.globalscale * (this.pic.offsetTop + parseInt(parts[i+1], 10)); this._polygongrow(this.areas[id], this.globalscale * parts[i], this.globalscale * parts[i+1]); } this._polygonshrink(this.areas[id]);//includes repaint } } catch (err) { var msg = (err.message) ? err.message : 'error calculating coordinates'; this.log(msg, 1); this.statusMessage(this.strings.ERR_INVALID_COORDS); if (this.areas[id].lastInput) { this.fireEvent('onAreaChanged', this.areas[id]); } this._repaint(this.areas[id], this.config.CL_NORM_SHAPE); return; } //on success update lastInput this.areas[id].lastInput = coords; }; /** * Grow polygon area to be able to contain the given new coordinates. * @author adam * @param area The area to grow. * @param newx The new coordinate x. * @param newy The new coordinate y. * @see #_polygonshrink */ imgmap.prototype._polygongrow = function(area, newx, newy) { //this.log('pgrow'); var xdiff = newx - parseInt(area.style.left, 10); var ydiff = newy - parseInt(area.style.top , 10); var pad = 0;//padding on the edges var pad2 = 0;//twice the padding if (newx < parseInt(area.style.left, 10)) { area.style.left = (newx - pad) + 'px'; this.setAreaSize(area.aid, parseInt(area.style.width, 10) + Math.abs(xdiff) + pad2, null); } else if (newx > parseInt(area.style.left, 10) + parseInt(area.style.width, 10)) { this.setAreaSize(area.aid, newx - parseInt(area.style.left, 10) + pad2, null); } if (newy < parseInt(area.style.top, 10)) { area.style.top = (newy - pad) + 'px'; this.setAreaSize(area.aid, null, parseInt(area.style.height, 10) + Math.abs(ydiff) + pad2); } else if (newy > parseInt(area.style.top, 10) + parseInt(area.style.height, 10)) { this.setAreaSize(area.aid, null, newy - parseInt(area.style.top, 10) + pad2); } }; /** * Shrink the polygon bounding area to the necessary size, by first reducing it * to the minimum, and then gradually growing it. * We need this because while we were drawing the polygon, it might have expanded * the canvas more than needed. * Will repaint the area. * @author adam * @param area The area to shrink. * @see #_polygongrow */ imgmap.prototype._polygonshrink = function(area) { //this.log('pshrink'); area.style.left = (area.xpoints[0]) + 'px'; area.style.top = (area.ypoints[0]) + 'px'; this.setAreaSize(area.aid, 0, 0); for (var i=0, le = area.xpoints.length; i<le; i++) { this._polygongrow(area, area.xpoints[i], area.ypoints[i]); } this._repaint(area, this.config.CL_NORM_SHAPE); }; /** * EVENT HANDLER: Handles mousemove on the image. * This is the main drawing routine. * Depending on the current shape, will draw the rect/circle/poly to the new position. * @param e The event object. */ imgmap.prototype.img_mousemove = function(e) { //function level var declarations var x; var y; var xdiff; var ydiff; var diff; if (this.viewmode === 1) {return;}//exit if preview mode //event.x is relative to parent element, but page.x is NOT //pos coordinates are the same absolute coords, offset coords are relative to parent var pos = this._getPos(this.pic); x = (this.isMSIE) ? (window.event.x - this.pic.offsetLeft) : (e.pageX - pos.x); y = (this.isMSIE) ? (window.event.y - this.pic.offsetTop) : (e.pageY - pos.y); x = x + this.pic_container.scrollLeft; y = y + this.pic_container.scrollTop; //this.log(x + ' - ' + y + ': ' + this.memory[this.currentid].downx + ' - ' +this.memory[this.currentid].downy); //exit if outside image if (x<0 || y<0 || x>this.pic.width || y>this.pic.height) {return;} //old dimensions that need to be updated in this function if (this.memory[this.currentid]) { var top = this.memory[this.currentid].top; var left = this.memory[this.currentid].left; var height = this.memory[this.currentid].height; var width = this.memory[this.currentid].width; } // Handle shift state for Safari // Safari doesn't generate keyboard events for modifiers: http://bugs.webkit.org/show_bug.cgi?id=11696 if (this.isSafari) { if (e.shiftKey) { if (this.is_drawing == this.DM_RECTANGLE_DRAW) { this.is_drawing = this.DM_SQUARE_DRAW; this.statusMessage(this.strings.SQUARE2_DRAW); } } else { if (this.is_drawing == this.DM_SQUARE_DRAW && this.areas[this.currentid].shape == 'rect') { //not for circle! this.is_drawing = this.DM_RECTANGLE_DRAW; this.statusMessage(this.strings.RECTANGLE_DRAW); } } } if (this.is_drawing == this.DM_RECTANGLE_DRAW) { //rectangle mode this.fireEvent('onDrawArea', this.currentid); xdiff = x - this.memory[this.currentid].downx; ydiff = y - this.memory[this.currentid].downy; //alert(xdiff); this.setAreaSize(this.currentid, Math.abs(xdiff), Math.abs(ydiff)); if (xdiff < 0) { this.areas[this.currentid].style.left = (x + 1) + 'px'; } if (ydiff < 0) { this.areas[this.currentid].style.top = (y + 1) + 'px'; } } else if (this.is_drawing == this.DM_SQUARE_DRAW) { //square mode - align to shorter side this.fireEvent('onDrawArea', this.currentid); xdiff = x - this.memory[this.currentid].downx; ydiff = y - this.memory[this.currentid].downy; if (Math.abs(xdiff) < Math.abs(ydiff)) { diff = Math.abs(parseInt(xdiff, 10)); } else { diff = Math.abs(parseInt(ydiff, 10)); } //alert(xdiff); this.setAreaSize(this.currentid, diff, diff); if (xdiff < 0) { this.areas[this.currentid].style.left = (this.memory[this.currentid].downx + diff*-1) + 'px'; } if (ydiff < 0) { this.areas[this.currentid].style.top = (this.memory[this.currentid].downy + diff*-1 + 1) + 'px'; } } else if (this.is_drawing == this.DM_POLYGON_DRAW || this.is_drawing == this.DM_BEZIER_DRAW) { //polygon or bezier mode this.fireEvent('onDrawArea', this.currentid); this._polygongrow(this.areas[this.currentid], x, y); } else if (this.is_drawing == this.DM_RECTANGLE_MOVE || this.is_drawing == this.DM_SQUARE_MOVE) { this.fireEvent('onMoveArea', this.currentid); x = x - this.memory[this.currentid].rdownx; y = y - this.memory[this.currentid].rdowny; if (x + width > this.pic.width || y + height > this.pic.height) {return;} if (x < 0 || y < 0) {return;} //this.log(x + ' - '+width+ '+'+this.memory[this.currentid].rdownx +'='+xdiff ); this.areas[this.currentid].style.left = x + 1 + 'px'; this.areas[this.currentid].style.top = y + 1 + 'px'; } else if (this.is_drawing == this.DM_POLYGON_MOVE || this.is_drawing == this.DM_BEZIER_MOVE) { this.fireEvent('onMoveArea', this.currentid); x = x - this.memory[this.currentid].rdownx; y = y - this.memory[this.currentid].rdowny; if (x + width > this.pic.width || y + height > this.pic.height) {return;} if (x < 0 || y < 0) {return;} xdiff = x - left; ydiff = y - top; if (this.areas[this.currentid].xpoints) { for (var i=0, le = this.areas[this.currentid].xpoints.length; i<le; i++) { this.areas[this.currentid].xpoints[i] = this.memory[this.currentid].xpoints[i] + xdiff; this.areas[this.currentid].ypoints[i] = this.memory[this.currentid].ypoints[i] + ydiff; } } this.areas[this.currentid].style.left = x + 'px'; this.areas[this.currentid].style.top = y + 'px'; } else if (this.is_drawing == this.DM_SQUARE_RESIZE_LEFT) { this.fireEvent('onResizeArea', this.currentid); diff = x - left; //alert(diff); if ((width + (-1 * diff)) > 0) { //real resize left this.areas[this.currentid].style.left = x + 1 + 'px'; this.areas[this.currentid].style.top = (top + (diff/2)) + 'px'; this.setAreaSize(this.currentid, parseInt(width + (-1 * diff), 10), parseInt(height + (-1 * diff), 10)); } else { //jump to another state this.memory[this.currentid].width = 0; this.memory[this.currentid].height = 0; this.memory[this.currentid].left = x; this.memory[this.currentid].top = y; this.is_drawing = this.DM_SQUARE_RESIZE_RIGHT; } } else if (this.is_drawing == this.DM_SQUARE_RESIZE_RIGHT) { this.fireEvent('onResizeArea', this.currentid); diff = x - left - width; if ((width + (diff)) - 1 > 0) { //real resize right this.areas[this.currentid].style.top = (top + (-1* diff/2)) + 'px'; this.setAreaSize(this.currentid, (width + (diff)) - 1, (height + (diff))); } else { //jump to another state this.memory[this.currentid].width = 0; this.memory[this.currentid].height = 0; this.memory[this.currentid].left = x; this.memory[this.currentid].top = y; this.is_drawing = this.DM_SQUARE_RESIZE_LEFT; } } else if (this.is_drawing == this.DM_SQUARE_RESIZE_TOP) { this.fireEvent('onResizeArea', this.currentid); diff = y - top; if ((width + (-1 * diff)) > 0) { //real resize top this.areas[this.currentid].style.top = y + 1 + 'px'; this.areas[this.currentid].style.left = (left + (diff/2)) + 'px'; this.setAreaSize(this.currentid, (width + (-1 * diff)), (height + (-1 * diff))); } else { //jump to another state this.memory[this.currentid].width = 0; this.memory[this.currentid].height = 0; this.memory[this.currentid].left = x; this.memory[this.currentid].top = y; this.is_drawing = this.DM_SQUARE_RESIZE_BOTTOM; } } else if (this.is_drawing == this.DM_SQUARE_RESIZE_BOTTOM) { this.fireEvent('onResizeArea', this.currentid); diff = y - top - height; if ((width + (diff)) - 1 > 0) { //real resize bottom this.areas[this.currentid].style.left = (left + (-1* diff/2)) + 'px'; this.setAreaSize(this.currentid, (width + (diff)) - 1 , (height + (diff)) - 1); } else { //jump to another state this.memory[this.currentid].width = 0; this.memory[this.currentid].height = 0; this.memory[this.currentid].left = x; this.memory[this.currentid].top = y; this.is_drawing = this.DM_SQUARE_RESIZE_TOP; } } else if (this.is_drawing == this.DM_RECTANGLE_RESIZE_LEFT) { this.fireEvent('onResizeArea', this.currentid); xdiff = x - left; if (width + (-1 * xdiff) > 0) { //real resize left this.areas[this.currentid].style.left = x + 1 + 'px'; this.setAreaSize(this.currentid, width + (-1 * xdiff), null); } else { //jump to another state this.memory[this.currentid].width = 0; this.memory[this.currentid].left = x; this.is_drawing = this.DM_RECTANGLE_RESIZE_RIGHT; } } else if (this.is_drawing == this.DM_RECTANGLE_RESIZE_RIGHT) { this.fireEvent('onResizeArea', this.currentid); xdiff = x - left - width; if ((width + (xdiff)) - 1 > 0) { //real resize right this.setAreaSize(this.currentid, (width + (xdiff)) - 1, null); } else { //jump to another state this.memory[this.currentid].width = 0; this.memory[this.currentid].left = x; this.is_drawing = this.DM_RECTANGLE_RESIZE_LEFT; } } else if (this.is_drawing == this.DM_RECTANGLE_RESIZE_TOP) { this.fireEvent('onResizeArea', this.currentid); ydiff = y - top; if ((height + (-1 * ydiff)) > 0) { //real resize top this.areas[this.currentid].style.top = y + 1 + 'px'; this.setAreaSize(this.currentid, null, (height + (-1 * ydiff))); } else { //jump to another state this.memory[this.currentid].height = 0; this.memory[this.currentid].top = y; this.is_drawing = this.DM_RECTANGLE_RESIZE_BOTTOM; } } else if (this.is_drawing == this.DM_RECTANGLE_RESIZE_BOTTOM) { this.fireEvent('onResizeArea', this.currentid); ydiff = y - top - height; if ((height + (ydiff)) - 1 > 0) { //real resize bottom this.setAreaSize(this.currentid, null, (height + (ydiff)) - 1); } else { //jump to another state this.memory[this.currentid].height = 0; this.memory[this.currentid].top = y; this.is_drawing = this.DM_RECTANGLE_RESIZE_TOP; } } //repaint canvas elements if (this.is_drawing) { this._repaint(this.areas[this.currentid], this.config.CL_DRAW_SHAPE, x, y); this._updatecoords(this.currentid); } }; /** * EVENT HANDLER: Handles mouseup on the image. * Handles dragging and resizing. * @param e The event object. */ imgmap.prototype.img_mouseup = function(e) { if (this.viewmode === 1) {return;}//exit if preview mode //console.log('img_mouseup'); //if (!this.props[this.currentid]) return; var pos = this._getPos(this.pic); var x = (this.isMSIE) ? (window.event.x - this.pic.offsetLeft) : (e.pageX - pos.x); var y = (this.isMSIE) ? (window.event.y - this.pic.offsetTop) : (e.pageY - pos.y); x = x + this.pic_container.scrollLeft; y = y + this.pic_container.scrollTop; //for everything that is move or resize if (this.is_drawing != this.DM_RECTANGLE_DRAW && this.is_drawing != this.DM_SQUARE_DRAW && this.is_drawing != this.DM_POLYGON_DRAW && this.is_drawing != this.DM_POLYGON_LASTDRAW && this.is_drawing != this.DM_BEZIER_DRAW && this.is_drawing != this.DM_BEZIER_LASTDRAW) { //end dragging this.draggedId = null; //finish state this.is_drawing = 0; this.statusMessage(this.strings.READY); this.relaxArea(this.currentid); if (this.areas[this.currentid] == this._getLastArea()) { //if (this.config.mode != "editor2") this.addNewArea(); return; } this.memory[this.currentid].downx = x; this.memory[this.currentid].downy = y; } }; /** * EVENT HANDLER: Handles mousedown on the image. * Handles beggining or end of draw, or polygon/bezier point set. * @param e The event object. */ imgmap.prototype.img_mousedown = function(e) { if (this.viewmode === 1) {return;}//exit if preview mode if (!this.areas[this.currentid] && this.config.mode != "editor2") {return;} //console.log('img_mousedown'); var pos = this._getPos(this.pic); var x = (this.isMSIE) ? (window.event.x - this.pic.offsetLeft) : (e.pageX - pos.x); var y = (this.isMSIE) ? (window.event.y - this.pic.offsetTop) : (e.pageY - pos.y); x = x + this.pic_container.scrollLeft; y = y + this.pic_container.scrollTop; // Handle the Shift state if (!e) { e = window.event; } if (e.shiftKey) { if (this.is_drawing == this.DM_POLYGON_DRAW) { this.is_drawing = this.DM_POLYGON_LASTDRAW; } else if (this.is_drawing == this.DM_BEZIER_DRAW) { this.is_drawing = this.DM_BEZIER_LASTDRAW; } } //console.log(this.is_drawing); //this.statusMessage(x + ' - ' + y + ': ' + this.props[this.currentid].getElementsByTagName('select')[0].value); if (this.is_drawing == this.DM_POLYGON_DRAW || this.is_drawing == this.DM_BEZIER_DRAW) { //its not finish state yet this.areas[this.currentid].xpoints[this.areas[this.currentid].xpoints.length] = x - 5; this.areas[this.currentid].ypoints[this.areas[this.currentid].ypoints.length] = y - 5; this.memory[this.currentid].downx = x; this.memory[this.currentid].downy = y; return; } else if (this.is_drawing && this.is_drawing != this.DM_POLYGON_DRAW && this.is_drawing != this.DM_BEZIER_DRAW) { //finish any other state if (this.is_drawing == this.DM_POLYGON_LASTDRAW || this.is_drawing == this.DM_BEZIER_LASTDRAW) { //add last controlpoint and update coords this.areas[this.currentid].xpoints[this.areas[this.currentid].xpoints.length] = x - 5; this.areas[this.currentid].ypoints[this.areas[this.currentid].ypoints.length] = y - 5; this._updatecoords(this.currentid); this.is_drawing = 0; this._polygonshrink(this.areas[this.currentid]); } this.is_drawing = 0; this.statusMessage(this.strings.READY); this.relaxArea(this.currentid); if (this.areas[this.currentid] == this._getLastArea()) { //editor mode adds next area automatically if (this.config.mode != "editor2") {this.addNewArea();} return; } return; } if (this.config.mode == "editor2") { if (!this.nextShape) {return;} this.addNewArea(); //console.log("init: " + this.nextShape); this.initArea(this.currentid, this.nextShape); } else if (this.areas[this.currentid].shape == 'undefined' || this.areas[this.currentid].shape == 'poly') { //var shape = (this.props[this.currentid]) ? this.props[this.currentid].getElementsByTagName('select')[0].value : this.nextShape; var shape = this.nextShape; if (!shape) {shape = 'rect';} //console.log("init: " + shape); this.initArea(this.currentid, shape); } if (this.areas[this.currentid].shape == 'poly') { this.is_drawing = this.DM_POLYGON_DRAW; this.statusMessage(this.strings.POLYGON_DRAW); this.areas[this.currentid].style.left = x + 'px'; this.areas[this.currentid].style.top = y + 'px'; this.areas[this.currentid].style.width = 0; this.areas[this.currentid].style.height = 0; this.areas[this.currentid].xpoints = []; this.areas[this.currentid].ypoints = []; this.areas[this.currentid].xpoints[0] = x; this.areas[this.currentid].ypoints[0] = y; } else if (this.areas[this.currentid].shape == 'bezier1') { this.is_drawing = this.DM_BEZIER_DRAW; this.statusMessage(this.strings.BEZIER_DRAW); this.areas[this.currentid].style.left = x + 'px'; this.areas[this.currentid].style.top = y + 'px'; this.areas[this.currentid].style.width = 0; this.areas[this.currentid].style.height = 0; this.areas[this.currentid].xpoints = []; this.areas[this.currentid].ypoints = []; this.areas[this.currentid].xpoints[0] = x; this.areas[this.currentid].ypoints[0] = y; } else if (this.areas[this.currentid].shape == 'rect') { this.is_drawing = this.DM_RECTANGLE_DRAW; this.statusMessage(this.strings.RECTANGLE_DRAW); this.areas[this.currentid].style.left = x + 'px'; this.areas[this.currentid].style.top = y + 'px'; this.areas[this.currentid].style.width = 0; this.areas[this.currentid].style.height = 0; } else if (this.areas[this.currentid].shape == 'circle') { this.is_drawing = this.DM_SQUARE_DRAW; this.statusMessage(this.strings.SQUARE_DRAW); this.areas[this.currentid].style.left = x + 'px'; this.areas[this.currentid].style.top = y + 'px'; this.areas[this.currentid].style.width = 0; this.areas[this.currentid].style.height = 0; } this._setBorder(this.currentid, 'DRAW'); this.memory[this.currentid].downx = x; this.memory[this.currentid].downy = y; }; /** * Highlights a given area. * Sets opacity and repaints. * @date 2007.12.28. 18:23:00 * @param id The id of the area to blur. * @param flag Modifier, possible values: grad - for gradual fade in */ imgmap.prototype.highlightArea = function(id, flag) { if (this.is_drawing) {return;}//exit if in drawing state if (this.areas[id] && this.areas[id].shape != 'undefined') { //area exists - highlight it this.fireEvent('onFocusArea', this.areas[id]); this._setBorder(id, 'HIGHLIGHT'); var opacity = this.config.highlight_opacity; if (flag == 'grad') { //apply gradient opacity opacity = '-' + opacity; } this._setopacity(this.areas[id], this.config.CL_HIGHLIGHT_BG, opacity); this._repaint(this.areas[id], this.config.CL_HIGHLIGHT_SHAPE); } }; /** * Blurs a given area. * Sets opacity and repaints. * @date 2007.12.28. 18:23:26 * @param id The id of the area to blur. * @param flag Modifier, possible values: grad - for gradual fade out */ imgmap.prototype.blurArea = function(id, flag) { if (this.is_drawing) {return;}//exit if in drawing state if (this.areas[id] && this.areas[id].shape != 'undefined') { //area exists - fade it back this.fireEvent('onBlurArea', this.areas[id]); this._setBorder(id, 'NORM'); var opacity = this.config.norm_opacity; if (flag == 'grad') { //apply gradient opacity opacity = '-' + opacity; } this._setopacity(this.areas[id], this.config.CL_NORM_BG, opacity); this._repaint(this.areas[id], this.config.CL_NORM_SHAPE); } }; /** * EVENT HANDLER: Handles event of mousemove on imgmap areas. * - changes cursor depending where we are inside the area (buggy in opera) * - handles area resize * - handles area move * @url http://evolt.org/article/Mission_Impossible_mouse_position/17/23335/index.html * @url http://my.opera.com/community/forums/topic.dml?id=239498&t=1217158015&page=1 * @author adam * @param e The event object. */ imgmap.prototype.area_mousemove = function(e) { if (this.viewmode === 1) {return;}//exit if preview mode if (!this.is_drawing) { var obj = (this.isMSIE) ? window.event.srcElement : e.currentTarget; if (obj.tagName == 'DIV') { //do this because of label obj = obj.parentNode; } if (obj.tagName == 'image' || obj.tagName == 'group' || obj.tagName == 'shape' || obj.tagName == 'stroke') { //do this because of excanvas obj = obj.parentNode.parentNode; } //opera fix - adam - 04-12-2007 23:14:05 if (this.isOpera) { e.layerX = e.offsetX; e.layerY = e.offsetY; } var xdiff = (this.isMSIE) ? (window.event.offsetX) : (e.layerX); var ydiff = (this.isMSIE) ? (window.event.offsetY) : (e.layerY); //this.log(obj.aid + ' : ' + xdiff + ',' + ydiff); var resizable = (obj.shape == 'rect' || obj.shape == 'circle'); if (resizable && xdiff < 6 && ydiff > 6) { //move left obj.style.cursor = 'w-resize'; } else if (resizable && xdiff > parseInt(obj.style.width, 10) - 6 && ydiff > 6) { //move right obj.style.cursor = 'e-resize'; } else if (resizable && xdiff > 6 && ydiff < 6) { //move top obj.style.cursor = 'n-resize'; } else if (resizable && ydiff > parseInt(obj.style.height, 10) - 6 && xdiff > 6) { //move bottom obj.style.cursor = 's-resize'; } else { //move all obj.style.cursor = 'move'; } if (obj.aid != this.draggedId) { //not dragged or different if (obj.style.cursor == 'move') {obj.style.cursor = 'default';} return; } //moved here from mousedown if (xdiff < 6 && ydiff > 6) { //move left if (this.areas[this.currentid].shape == 'circle') { this.is_drawing = this.DM_SQUARE_RESIZE_LEFT; this.statusMessage(this.strings.SQUARE_RESIZE_LEFT); } else if (this.areas[this.currentid].shape == 'rect') { this.is_drawing = this.DM_RECTANGLE_RESIZE_LEFT; this.statusMessage(this.strings.RECTANGLE_RESIZE_LEFT); } } else if (xdiff > parseInt(this.areas[this.currentid].style.width, 10) - 6 && ydiff > 6) { //move right if (this.areas[this.currentid].shape == 'circle') { this.is_drawing = this.DM_SQUARE_RESIZE_RIGHT; this.statusMessage(this.strings.SQUARE_RESIZE_RIGHT); } else if (this.areas[this.currentid].shape == 'rect') { this.is_drawing = this.DM_RECTANGLE_RESIZE_RIGHT; this.statusMessage(this.strings.RECTANGLE_RESIZE_RIGHT); } } else if (xdiff > 6 && ydiff < 6) { //move top if (this.areas[this.currentid].shape == 'circle') { this.is_drawing = this.DM_SQUARE_RESIZE_TOP; this.statusMessage(this.strings.SQUARE_RESIZE_TOP); } else if (this.areas[this.currentid].shape == 'rect') { this.is_drawing = this.DM_RECTANGLE_RESIZE_TOP; this.statusMessage(this.strings.RECTANGLE_RESIZE_TOP); } } else if (ydiff > parseInt(this.areas[this.currentid].style.height, 10) - 6 && xdiff > 6) { //move bottom if (this.areas[this.currentid].shape == 'circle') { this.is_drawing = this.DM_SQUARE_RESIZE_BOTTOM; this.statusMessage(this.strings.SQUARE_RESIZE_BOTTOM); } else if (this.areas[this.currentid].shape == 'rect') { this.is_drawing = this.DM_RECTANGLE_RESIZE_BOTTOM; this.statusMessage(this.strings.RECTANGLE_RESIZE_BOTTOM); } } else/*if (xdiff < 10 && ydiff < 10 ) */{ //move all if (this.areas[this.currentid].shape == 'circle') { this.is_drawing = this.DM_SQUARE_MOVE; this.statusMessage(this.strings.SQUARE_MOVE); this.memory[this.currentid].rdownx = xdiff; this.memory[this.currentid].rdowny = ydiff; } else if (this.areas[this.currentid].shape == 'rect') { this.is_drawing = this.DM_RECTANGLE_MOVE; this.statusMessage(this.strings.RECTANGLE_MOVE); this.memory[this.currentid].rdownx = xdiff; this.memory[this.currentid].rdowny = ydiff; } else if (this.areas[this.currentid].shape == 'poly' || this.areas[this.currentid].shape == 'bezier1') { if (this.areas[this.currentid].xpoints) { for (var i=0, le = this.areas[this.currentid].xpoints.length; i<le; i++) { this.memory[this.currentid].xpoints[i] = this.areas[this.currentid].xpoints[i]; this.memory[this.currentid].ypoints[i] = this.areas[this.currentid].ypoints[i]; } } if (this.areas[this.currentid].shape == 'poly') { this.is_drawing = this.DM_POLYGON_MOVE; this.statusMessage(this.strings.POLYGON_MOVE); } else if (this.areas[this.currentid].shape == 'bezier1') { this.is_drawing = this.DM_BEZIER_MOVE; this.statusMessage(this.strings.BEZIER_MOVE); } this.memory[this.currentid].rdownx = xdiff; this.memory[this.currentid].rdowny = ydiff; } } //common memory settings (preparing to move or resize) this.memory[this.currentid].width = parseInt(this.areas[this.currentid].style.width, 10); this.memory[this.currentid].height = parseInt(this.areas[this.currentid].style.height, 10); this.memory[this.currentid].top = parseInt(this.areas[this.currentid].style.top, 10); this.memory[this.currentid].left = parseInt(this.areas[this.currentid].style.left, 10); this._setBorder(this.currentid, 'DRAW'); this._setopacity(this.areas[this.currentid], this.config.CL_DRAW_BG, this.config.draw_opacity); } else { //if drawing and not ie, have to propagate to image event this.img_mousemove(e); } }; /** * EVENT HANDLER: Handles event of mouseup on imgmap areas. * Basically clears draggedId. * @author adam * @param e The event object */ imgmap.prototype.area_mouseup = function(e) { if (this.viewmode === 1) {return;}//exit if preview mode //console.log('area_mouseup'); if (!this.is_drawing) { var obj = (this.isMSIE) ? window.event.srcElement : e.currentTarget; if (obj.tagName == 'DIV') { //do this because of label obj = obj.parentNode; } if (obj.tagName == 'image' || obj.tagName == 'group' || obj.tagName == 'shape' || obj.tagName == 'stroke') { //do this because of excanvas obj = obj.parentNode.parentNode; } if (this.areas[this.currentid] != obj) { //trying to draw on a different canvas,switch to this one if (typeof obj.aid == 'undefined') { this.log('Cannot identify target area', 1); return; } //this.form_selectRow(obj.aid, true); //this.currentid = obj.aid; } this.draggedId = null; } else { //if drawing and not ie, have to propagate to image event //console.log('propup'); this.img_mouseup(e); } }; /** * EVENT HANDLER: Handles event of mouseover on imgmap areas. * Calls gradual highlight on the given area. * @author adam * @param e The event object */ imgmap.prototype.area_mouseover = function(e) { if (this.viewmode === 1 && this.config.mode !== 'highlighter_spawn') {return;}//exit if preview mode if (!this.is_drawing) { //this.log('area_mouseover'); //identify source object var obj = (this.isMSIE) ? window.event.srcElement : e.currentTarget; if (obj.tagName == 'DIV') { //do this because of label obj = obj.parentNode; } if (obj.tagName == 'image' || obj.tagName == 'group' || obj.tagName == 'shape' || obj.tagName == 'stroke') { //do this because of excanvas obj = obj.parentNode.parentNode; } /* //switch to hovered area if (this.areas[this.currentid] != obj) { //trying to draw on a different canvas, switch to this one if (typeof obj.aid == 'undefined') { this.log('Cannot identify target area', 1); return; } this.form_selectRow(obj.aid, true); this.currentid = obj.aid; } */ this.highlightArea(obj.aid, 'grad'); } }; /** * EVENT HANDLER: Handles event of mouseout on imgmap areas. * Calls gradient blur on the given area. * @author adam * @param e The event object */ imgmap.prototype.area_mouseout = function(e) { if (this.viewmode === 1 && this.config.mode !== 'highlighter_spawn') {return;}//exit if preview mode if (!this.is_drawing) { //this.log('area_mouseout'); //identify source object var obj = (this.isMSIE) ? window.event.srcElement : e.currentTarget; if (obj.tagName == 'DIV') { //do this because of label obj = obj.parentNode; } if (obj.tagName == 'image' || obj.tagName == 'group' || obj.tagName == 'shape' || obj.tagName == 'stroke') { //do this because of excanvas obj = obj.parentNode.parentNode; } this.blurArea(obj.aid, 'grad'); } }; /** * EVENT HANDLER: Handles event of double click on imgmap areas. * Basically only fires the custom callback. * @author Colin Bell * @param e The event object */ imgmap.prototype.area_dblclick = function(e) { if (this.viewmode === 1) {return;}//exit if preview mode //console.log('area_dblclick'); if (!this.is_drawing) { var obj = (this.isMSIE) ? window.event.srcElement : e.currentTarget; if (obj.tagName == 'DIV') { //do this because of label obj = obj.parentNode; } if (obj.tagName == 'image' || obj.tagName == 'group' || obj.tagName == 'shape' || obj.tagName == 'stroke') { //do this because of excanvas obj = obj.parentNode.parentNode; } if (this.areas[this.currentid] != obj) { //trying to draw on a different canvas, switch to this one if (typeof obj.aid == 'undefined') { this.log('Cannot identify target area', 1); return; } this.currentid = obj.aid; } this.fireEvent('onDblClickArea', this.areas[this.currentid]); //stop event propagation to document level if (this.isMSIE) { window.event.cancelBubble = true; } else { e.stopPropagation(); } } }; /** * EVENT HANDLER: Handles event of mousedown on imgmap areas. * Sets the variables draggedid, selectedid and currentid to the given area. * @author adam * @param e The event object */ imgmap.prototype.area_mousedown = function(e) { if (this.viewmode === 1 && this.config.mode !== 'highlighter_spawn') {return;}//exit if preview mode //console.log('area_mousedown'); if (!this.is_drawing) { var obj = (this.isMSIE) ? window.event.srcElement : e.currentTarget; if (obj.tagName == 'DIV') { //do this because of label obj = obj.parentNode; } if (obj.tagName == 'image' || obj.tagName == 'group' || obj.tagName == 'shape' || obj.tagName == 'stroke') { //do this because of excanvas obj = obj.parentNode.parentNode; } if (this.areas[this.currentid] != obj) { //trying to draw on a different canvas, switch to this one if (typeof obj.aid == 'undefined') { this.log('Cannot identify target area', 1); return; } this.currentid = obj.aid; } //this.log('selected = '+this.currentid); this.draggedId = this.currentid; this.selectedId = this.currentid; this.fireEvent('onSelectArea', this.areas[this.currentid]); //stop event propagation to document level if (this.isMSIE) { window.event.cancelBubble = true; } else { e.stopPropagation(); } } else { //if drawing and not ie, have to propagate to image event //console.log('propdown'); this.img_mousedown(e); } }; /** * EVENT HANDLER: Handles event 'keydown' on document. * Handles SHIFT hold while drawing. * Note: Safari doesn't generate keyboard events for modifiers: * @url http://bugs.webkit.org/show_bug.cgi?id=11696 * @author adam * @param e The event object */ imgmap.prototype.doc_keydown = function(e) { if (this.viewmode === 1) {return;}//exit if preview mode var key = (this.isMSIE) ? event.keyCode : e.keyCode; //console.log(key); if (key == 46) { //delete key pressed if (this.selectedId !== null && !this.is_drawing) {this.removeArea(this.selectedId);} } else if (key == 16) { //shift key pressed if (this.is_drawing == this.DM_RECTANGLE_DRAW) { this.is_drawing = this.DM_SQUARE_DRAW; this.statusMessage(this.strings.SQUARE2_DRAW); } } }; /** * EVENT HANDLER: Handles event 'keyup' on document. * Handles SHIFT release while drawing. * @author adam * @param e The event object */ imgmap.prototype.doc_keyup = function(e) { var key = (this.isMSIE) ? event.keyCode : e.keyCode; //alert(key); if (key == 16) { //shift key released if (this.is_drawing == this.DM_SQUARE_DRAW && this.areas[this.currentid].shape == 'rect') { //not for circle! this.is_drawing = this.DM_RECTANGLE_DRAW; this.statusMessage(this.strings.RECTANGLE_DRAW); } } }; /** * EVENT HANDLER: Handles event 'mousedown' on document. * @author adam * @param e The event object */ imgmap.prototype.doc_mousedown = function(e) { if (this.viewmode === 1) {return;}//exit if preview mode if (!this.is_drawing) { this.selectedId = null; } }; /** * Get the real position of the element. * Deal with browser differences when trying to get the position of an area. * @param element The element you want the position of. * @return An object with x and y members. */ imgmap.prototype._getPos = function(element) { var xpos = 0; var ypos = 0; if (element) { var elementOffsetParent = element.offsetParent; // If the element has an offset parent if (elementOffsetParent) { // While there is an offset parent while ((elementOffsetParent = element.offsetParent)) { //offset might give negative in opera when the image is scrolled if (element.offsetLeft > 0) {xpos += element.offsetLeft;} if (element.offsetTop > 0) {ypos += element.offsetTop;} element = elementOffsetParent; } } else { xpos = element.offsetLeft; ypos = element.offsetTop; } } return {x: xpos, y: ypos}; }; /** * Gets the last (visible and editable) area. * @author Adam Maschek (adam.maschek(at)gmail.com) * @date 2006-06-15 16:34:51 * @returns The last area object or null. */ imgmap.prototype._getLastArea = function() { for (var i = this.areas.length-1; i>=0; i--) { if (this.areas[i]) { return this.areas[i]; } } return null; }; /** * Parses cssText to single style declarations. * @author adam * @date 25-09-2007 18:19:51 * @param obj The DOM object to apply styles on. * @param cssText The css declarations to apply. */ imgmap.prototype.assignCSS = function(obj, cssText) { var parts = cssText.split(';'); for (var i = 0; i < parts.length; i++) { var p = parts[i].split(':'); //we need to camelcase by - signs var pp = this.trim(p[0]).split('-'); var prop = pp[0]; for (var j = 1; j < pp.length; j++) { //replace first letters to uppercase prop+= pp[j].replace(/^\w/, pp[j].substring(0,1).toUpperCase()); } obj.style[this.trim(prop)] = this.trim(p[1]); } }; /** * To fire callback hooks on custom events, passing them the object of the event. * @author adam * @date 13-10-2007 15:24:49 * @param evt The type of event * @param obj The object of the event. (can be an id, a string, an object, whatever is most relevant) */ imgmap.prototype.fireEvent = function(evt, obj) { //this.log("Firing event: " + evt); if (typeof this.config.custom_callbacks[evt] == 'function') { return this.config.custom_callbacks[evt](obj); } }; /** * To set area dimensions. * This is needed to achieve the same result in all browsers. * @author adam * @date 10-12-2007 22:29:41 * @param id The id of the area (canvas) to resize. * @param w The desired width in pixels. * @param h The desired height in pixels. */ imgmap.prototype.setAreaSize = function(id, w, h) { if (id === null) {id = this.currentid;} if (w !== null) { this.areas[id].width = w; this.areas[id].style.width = (w) + 'px'; this.areas[id].setAttribute('width', w); } if (h !== null) { this.areas[id].height = h; this.areas[id].style.height = (h) + 'px'; this.areas[id].setAttribute('height', h); } }; /** * Tries to detect preferred language of user. * @date 2007.12.28. 15:43:46 * @return The two byte language code. (We dont care now for pt-br, etc.) */ imgmap.prototype.detectLanguage = function() { var lang; if (navigator.userLanguage) { lang = navigator.userLanguage.toLowerCase(); } else if (navigator.language) { lang = navigator.language.toLowerCase(); } else { return this.config.defaultLang; } //this.log(lang, 2); if (lang.length >= 2) { lang = lang.substring(0,2); return lang; } return this.config.defaultLang; }; /** * Disable selection on a given object. * This is especially useful in Safari, where dragging around areas * keeps selecting all sorts of things. * @author Bret Taylor * @url http://ajaxcookbook.org/disable-text-selection/ * @date 27-07-2008 1:57:45 * @param element The DOM element on which you want to disable selection. */ imgmap.prototype.disableSelection = function(element) { if (typeof element == 'undefined' || !element) {return false;} if (typeof element.onselectstart != "undefined") { element.onselectstart = function() { return false; }; } if (typeof element.unselectable != "undefined") { element.unselectable = "on"; } if (typeof element.style.MozUserSelect != "undefined") { element.style.MozUserSelect = "none"; } }; /** * @date 11-02-2007 19:57:05 * @url http://www.deepwood.net/writing/method-references.html.utf8 * @author Daniel Brockman * @addon */ Function.prototype.bind = function(object) { var method = this; return function () { return method.apply(object, arguments); }; }; /** * Trims a string. * Changed not to extend String but use own function for better compatibility. * @param str The string to trim. */ imgmap.prototype.trim = function(str) { return str.replace(/^\s+|\s+$/g, ''); }; /** * Spawn an imgmap object for each imagemap found in the document. * This is used for highlighter mode only. * @param config An imgmap config object */ function imgmap_spawnObjects(config) { //console.log('spawnobjects'); var maps = document.getElementsByTagName('map'); var imgs = document.getElementsByTagName('img'); var imaps = []; var imapn; //console.log(maps.length); for (var i=0, le=maps.length; i<le; i++) { for (var j=0, le2=imgs.length; j<le2; j++) { //console.log(i); // console.log(maps[i].name); // console.log(imgs[j].getAttribute('usemap')); if ('#' + maps[i].name == imgs[j].getAttribute('usemap')) { //we found one matching pair // console.log(maps[i]); config.mode = 'highlighter_spawn'; imapn = new imgmap(config); //imapn.setup(config); imapn.useImage(imgs[j]); imapn.setMapHTML(maps[i]); imapn.viewmode = 1; imaps.push(imapn); } } } } //global instance? //imgmap_spawnObjects();?
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/zopyx/authoring/skins/zopyx_linktool/linktool/jscripts/imgmap.js
imgmap.js
function imgmap(_1){this.version="2.2";this.buildDate="2009/07/26 16:02";this.buildNumber="106";this.config={};this.is_drawing=0;this.strings=[];this.memory=[];this.areas=[];this.logStore=[];this.eventHandlers={};this.currentid=0;this.draggedId=null;this.selectedId=null;this.nextShape="rect";this.viewmode=0;this.loadedScripts=[];this.isLoaded=false;this.cntReloads=0;this.mapname="";this.mapid="";this.waterMark="<!-- Created by Online Image Map Editor (http://www.maschek.hu/imagemap/index) -->";this.globalscale=1;this.DM_RECTANGLE_DRAW=1;this.DM_RECTANGLE_MOVE=11;this.DM_RECTANGLE_RESIZE_TOP=12;this.DM_RECTANGLE_RESIZE_RIGHT=13;this.DM_RECTANGLE_RESIZE_BOTTOM=14;this.DM_RECTANGLE_RESIZE_LEFT=15;this.DM_SQUARE_DRAW=2;this.DM_SQUARE_MOVE=21;this.DM_SQUARE_RESIZE_TOP=22;this.DM_SQUARE_RESIZE_RIGHT=23;this.DM_SQUARE_RESIZE_BOTTOM=24;this.DM_SQUARE_RESIZE_LEFT=25;this.DM_POLYGON_DRAW=3;this.DM_POLYGON_LASTDRAW=30;this.DM_POLYGON_MOVE=31;this.DM_BEZIER_DRAW=4;this.DM_BEZIER_LASTDRAW=40;this.DM_BEZIER_MOVE=41;this.config.mode="editor";this.config.baseroot="";this.config.lang="";this.config.defaultLang="en";this.config.loglevel=0;this.config.custom_callbacks={};this.event_types=["onModeChanged","onHtmlChanged","onAddArea","onRemoveArea","onDrawArea","onResizeArea","onRelaxArea","onFocusArea","onBlurArea","onMoveArea","onSelectRow","onLoadImage","onSetMap","onGetMap","onSelectArea","onDblClickArea","onStatusMessage","onAreaChanged"];this.config.CL_DRAW_BOX="#E32636";this.config.CL_DRAW_SHAPE="#d00";this.config.CL_DRAW_BG="#fff";this.config.CL_NORM_BOX="#E32636";this.config.CL_NORM_SHAPE="#d00";this.config.CL_NORM_BG="#fff";this.config.CL_HIGHLIGHT_BOX="#E32636";this.config.CL_HIGHLIGHT_SHAPE="#d00";this.config.CL_HIGHLIGHT_BG="#fff";this.config.CL_KNOB="#555";this.config.bounding_box=true;this.config.label="%n";this.config.label_class="imgmap_label";this.config.label_style="font: bold 10px Arial";this.config.hint="#%n %h";this.config.draw_opacity="35";this.config.norm_opacity="50";this.config.highlight_opacity="70";this.config.cursor_default="crosshair";var ua=navigator.userAgent;this.isMSIE=(navigator.appName=="Microsoft Internet Explorer");this.isMSIE5=this.isMSIE&&(ua.indexOf("MSIE 5")!=-1);this.isMSIE5_0=this.isMSIE&&(ua.indexOf("MSIE 5.0")!=-1);this.isMSIE7=this.isMSIE&&(ua.indexOf("MSIE 7")!=-1);this.isGecko=ua.indexOf("Gecko")!=-1;this.isSafari=ua.indexOf("Safari")!=-1;this.isOpera=(typeof window.opera!="undefined");this.setup(_1);} imgmap.prototype.assignOID=function(_3){try{if(typeof _3=="undefined"){this.log("Undefined object passed to assignOID.");return null;}else{if(typeof _3=="object"){return _3;}else{if(typeof _3=="string"){return document.getElementById(_3);}}}} catch(err){this.log("Error in assignOID",1);} return null;};imgmap.prototype.setup=function(_4){for(var i in _4){if(_4.hasOwnProperty(i)){this.config[i]=_4[i];}} this.addEvent(document,"keydown",this.eventHandlers.doc_keydown=this.doc_keydown.bind(this));this.addEvent(document,"keyup",this.eventHandlers.doc_keyup=this.doc_keyup.bind(this));this.addEvent(document,"mousedown",this.eventHandlers.doc_mousedown=this.doc_mousedown.bind(this));if(_4&&_4.pic_container){this.pic_container=this.assignOID(_4.pic_container);this.disableSelection(this.pic_container);} if(!this.config.baseroot){var _6=document.getElementsByTagName("base");var _7="";for(i=0;i<_6.length;i++){if(_6[i].href){_7=_6[i].href;if(_7.charAt(_7.length-1)!="/"){_7+="/";} break;}} var _8=document.getElementsByTagName("script");for(i=0;i<_8.length;i++){if(_8[i].src&&_8[i].src.match(/imgmap\w*\.js(\?.*?)?$/)){var _9=_8[i].src;_9=_9.substring(0,_9.lastIndexOf("/")+1);if(_7&&_9.indexOf("://")==-1){this.config.baseroot=_7+_9;}else{this.config.baseroot=_9;} break;}}} if(this.isMSIE&&typeof window.CanvasRenderingContext2D=="undefined"&&typeof G_vmlCanvasManager=="undefined"){this.loadScript(this.config.baseroot+"excanvas.js");} if(!this.config.lang){this.config.lang=this.detectLanguage();} if(typeof imgmapStrings=="undefined"){this.loadScript(this.config.baseroot+"lang_"+this.config.lang+".js");} var _a,j,le;for(i in this.config.custom_callbacks){if(this.config.custom_callbacks.hasOwnProperty(i)){_a=false;for(j=0,le=this.event_types.length;j<le;j++){if(i==this.event_types[j]){_a=true;break;}} if(!_a){this.log("Unknown custom callback: "+i,1);}}} this.addEvent(window,"load",this.onLoad.bind(this));return true;};imgmap.prototype.retryDelayed=function(fn,_e,_f){if(typeof fn.tries=="undefined"){fn.tries=0;} if(fn.tries++<_f){window.setTimeout(function(){fn.apply(this);},_e);}};imgmap.prototype.onLoad=function(e){if(this.isLoaded){return true;} var _11=this;if(typeof imgmapStrings=="undefined"){if(this.cntReloads++<5){window.setTimeout(function(){_11.onLoad(e);},1200);this.log("Delaying onload (language "+this.config.lang+" not loaded, try: "+this.cntReloads+")");return false;}else{if(this.config.lang!=this.config.defaultLang&&this.config.defaultLang!="en"){this.log("Falling back to default language: "+this.config.defaultLang);this.cntReloads=0;this.config.lang=this.config.defaultLang;this.loadScript(this.config.baseroot+"lang_"+this.config.lang+".js");window.setTimeout(function(){_11.onLoad(e);},1200);return false;}else{if(this.config.lang!="en"){this.log("Falling back to english language");this.cntReloads=0;this.config.lang="en";this.loadScript(this.config.baseroot+"lang_"+this.config.lang+".js");window.setTimeout(function(){_11.onLoad(e);},1200);return false;}}}} try{this.loadStrings(imgmapStrings);} catch(err){this.log("Unable to load language strings",1);} if(this.isMSIE){if(typeof window.CanvasRenderingContext2D=="undefined"&&typeof G_vmlCanvasManager=="undefined"){this.log(this.strings.ERR_EXCANVAS_LOAD,2);}} if(this.config.mode=="highlighter"){imgmap_spawnObjects(this.config);} this.isLoaded=true;return true;};imgmap.prototype.addEvent=function(obj,evt,_14){if(obj.attachEvent){return obj.attachEvent("on"+evt,_14);}else{if(obj.addEventListener){obj.addEventListener(evt,_14,false);return true;}else{obj["on"+evt]=_14;}}};imgmap.prototype.removeEvent=function(obj,evt,_17){if(obj.detachEvent){return obj.detachEvent("on"+evt,_17);}else{if(obj.removeEventListener){obj.removeEventListener(evt,_17,false);return true;}else{obj["on"+evt]=null;}}};imgmap.prototype.addLoadEvent=function(obj,_19){if(obj.attachEvent){return obj.attachEvent("onreadystatechange",_19);}else{if(obj.addEventListener){obj.addEventListener("load",_19,false);return true;}else{obj.onload=_19;}}};imgmap.prototype.loadScript=function(url){if(url===""){return false;} if(this.loadedScripts[url]==1){return true;} this.log("Loading script: "+url);try{var _1b=document.getElementsByTagName("head")[0];var _1c=document.createElement("SCRIPT");_1c.setAttribute("language","javascript");_1c.setAttribute("type","text/javascript");_1c.setAttribute("src",url);_1b.appendChild(_1c);this.addLoadEvent(_1c,this.script_load.bind(this));} catch(err){this.log("Error loading script: "+url);} return true;};imgmap.prototype.script_load=function(e){var obj=(this.isMSIE)?window.event.srcElement:e.currentTarget;var url=obj.src;var _20=false;if(typeof obj.readyState!="undefined"){if(obj.readyState=="complete"){_20=true;}}else{_20=true;} if(_20){this.loadedScripts[url]=1;this.log("Loaded script: "+url);return true;}};imgmap.prototype.loadStrings=function(obj){for(var key in obj){if(obj.hasOwnProperty(key)){this.strings[key]=obj[key];}}};imgmap.prototype.loadImage=function(img,_24,_25){if(typeof this.pic_container=="undefined"){this.log("You must have pic_container defined to use loadImage!",2);return false;} this.removeAllAreas();this.globalscale=1;this.fireEvent("onHtmlChanged","");if(!this._getLastArea()){if(this.config.mode!="editor2"){this.addNewArea();}} if(typeof img=="string"){if(typeof this.pic=="undefined"){this.pic=document.createElement("IMG");this.pic_container.appendChild(this.pic);this.addEvent(this.pic,"mousedown",this.eventHandlers.img_mousedown=this.img_mousedown.bind(this));this.addEvent(this.pic,"mouseup",this.eventHandlers.img_mouseup=this.img_mouseup.bind(this));this.addEvent(this.pic,"mousemove",this.eventHandlers.img_mousemove=this.img_mousemove.bind(this));this.pic.style.cursor=this.config.cursor_default;} this.log("Loading image: "+img,0);var q="?";if(img.indexOf("?")>-1){q="&";} this.pic.src=img+q+(new Date().getTime());if(_24&&_24>0){this.pic.setAttribute("width",_24);} if(_25&&_25>0){this.pic.setAttribute("height",_25);} this.fireEvent("onLoadImage",this.pic);return true;}else{if(typeof img=="object"){var src=img.src;if(src===""&&img.getAttribute("mce_src")!==""){src=img.getAttribute("mce_src");}else{if(src===""&&img.getAttribute("_fcksavedurl")!==""){src=img.getAttribute("_fcksavedurl");}} if(!_24){_24=img.clientWidth;} if(!_25){_25=img.clientHeight;} return this.loadImage(src,_24,_25);}}};imgmap.prototype.useImage=function(img){this.removeAllAreas();if(!this._getLastArea()){if(this.config.mode!="editor2"){this.addNewArea();}} img=this.assignOID(img);if(typeof img=="object"){if(typeof this.pic!="undefined"){this.removeEvent(this.pic,"mousedown",this.eventHandlers.img_mousedown);this.removeEvent(this.pic,"mouseup",this.eventHandlers.img_mouseup);this.removeEvent(this.pic,"mousemove",this.eventHandlers.img_mousemove);this.pic.style.cursor="";} this.pic=img;this.addEvent(this.pic,"mousedown",this.eventHandlers.img_mousedown=this.img_mousedown.bind(this));this.addEvent(this.pic,"mouseup",this.eventHandlers.img_mouseup=this.img_mouseup.bind(this));this.addEvent(this.pic,"mousemove",this.eventHandlers.img_mousemove=this.img_mousemove.bind(this));this.pic.style.cursor=this.config.cursor_default;if(this.pic.parentNode.className=="pic_container"){this.pic_container=this.pic.parentNode;}else{this.pic_container=document.createElement("div");this.pic_container.className="pic_container";this.pic.parentNode.insertBefore(this.pic_container,this.pic);this.pic_container.appendChild(this.pic);} this.fireEvent("onLoadImage",this.pic);return true;}};imgmap.prototype.statusMessage=function(str){this.fireEvent("onStatusMessage",str);};imgmap.prototype.log=function(obj,_2b){if(_2b===""||typeof _2b=="undefined"){_2b=0;} if(this.config.loglevel!=-1&&_2b>=this.config.loglevel){this.logStore.push({level:_2b,obj:obj});} if(typeof console=="object"){console.log(obj);}else{if(this.isOpera){opera.postError(_2b+": "+obj);}else{if(typeof air=="object"){if(typeof air.Introspector=="object"){air.Introspector.Console.log(obj);}else{air.trace(obj);}}else{if(_2b>1){var msg="";for(var i=0,le=this.logStore.length;i<le;i++){msg+=this.logStore[i].level+": "+this.logStore[i].obj+"\n";} alert(msg);}else{window.defaultStatus=(_2b+": "+obj);}}}}};imgmap.prototype.getMapHTML=function(_2f){var _30="<map id=\""+this.getMapId()+"\" name=\""+this.getMapName()+"\">"+this.getMapInnerHTML(_2f)+this.waterMark+"</map>";this.fireEvent("onGetMap",_30);return _30;};imgmap.prototype.getMapInnerHTML=function(_31){var _32,_33;_32="";for(var i=0,le=this.areas.length;i<le;i++){if(this.areas[i]){if(this.areas[i].shape&&this.areas[i].shape!="undefined"){_33=this.areas[i].lastInput;if(_31&&_31.match(/noscale/)){var cs=_33.split(",");for(var j=0,le2=cs.length;j<le2;j++){cs[j]=Math.round(cs[j]*this.globalscale);} _33=cs.join(",");} _32+="<area shape=\""+this.areas[i].shape+"\""+" alt=\""+this.areas[i].aalt+"\""+" title=\""+this.areas[i].atitle+"\""+" coords=\""+_33+"\""+" href=\""+this.areas[i].ahref+"\""+" target=\""+this.areas[i].atarget+"\" />";}}} return _32;};imgmap.prototype.getMapName=function(){if(this.mapname===""){if(this.mapid!==""){return this.mapid;} var now=new Date();this.mapname="imgmap"+now.getFullYear()+(now.getMonth()+1)+now.getDate()+now.getHours()+now.getMinutes()+now.getSeconds();} return this.mapname;};imgmap.prototype.getMapId=function(){if(this.mapid===""){this.mapid=this.getMapName();} return this.mapid;};imgmap.prototype._normShape=function(_3a){if(!_3a){return"rect";} _3a=this.trim(_3a).toLowerCase();if(_3a.substring(0,4)=="rect"){return"rect";} if(_3a.substring(0,4)=="circ"){return"circle";} if(_3a.substring(0,4)=="poly"){return"poly";} return"rect";};imgmap.prototype._normCoords=function(_3b,_3c,_3d){var i;var sx;var sy;var gx;var gy;var _43,le;_3b=this.trim(_3b);if(_3b===""){return"";} var _45=_3b;_3b=_3b.replace(/(\d)(\D)+(\d)/g,"$1,$3");_3b=_3b.replace(/,\D+(\d)/g,",$1");_3b=_3b.replace(/,0+(\d)/g,",$1");_3b=_3b.replace(/(\d)(\D)+,/g,"$1,");_3b=_3b.replace(/^\D+(\d)/g,"$1");_3b=_3b.replace(/^0+(\d)/g,"$1");_3b=_3b.replace(/(\d)(\D)+$/g,"$1");var _46=_3b.split(",");if(_3c=="rect"){if(_3d=="fromcircle"){var r=_46[2];_46[0]=_46[0]-r;_46[1]=_46[1]-r;_46[2]=parseInt(_46[0],10)+2*r;_46[3]=parseInt(_46[1],10)+2*r;}else{if(_3d=="frompoly"){sx=parseInt(_46[0],10);gx=parseInt(_46[0],10);sy=parseInt(_46[1],10);gy=parseInt(_46[1],10);for(i=0,le=_46.length;i<le;i++){if(i%2===0&&parseInt(_46[i],10)<sx){sx=parseInt(_46[i],10);} if(i%2===1&&parseInt(_46[i],10)<sy){sy=parseInt(_46[i],10);} if(i%2===0&&parseInt(_46[i],10)>gx){gx=parseInt(_46[i],10);} if(i%2===1&&parseInt(_46[i],10)>gy){gy=parseInt(_46[i],10);}} _46[0]=sx;_46[1]=sy;_46[2]=gx;_46[3]=gy;}} if(!(parseInt(_46[1],10)>=0)){_46[1]=_46[0];} if(!(parseInt(_46[2],10)>=0)){_46[2]=parseInt(_46[0],10)+10;} if(!(parseInt(_46[3],10)>=0)){_46[3]=parseInt(_46[1],10)+10;} if(parseInt(_46[0],10)>parseInt(_46[2],10)){_43=_46[0];_46[0]=_46[2];_46[2]=_43;} if(parseInt(_46[1],10)>parseInt(_46[3],10)){_43=_46[1];_46[1]=_46[3];_46[3]=_43;} _3b=_46[0]+","+_46[1]+","+_46[2]+","+_46[3];}else{if(_3c=="circle"){if(_3d=="fromrect"){sx=parseInt(_46[0],10);gx=parseInt(_46[2],10);sy=parseInt(_46[1],10);gy=parseInt(_46[3],10);_46[2]=(gx-sx<gy-sy)?gx-sx:gy-sy;_46[2]=Math.floor(_46[2]/2);_46[0]=sx+_46[2];_46[1]=sy+_46[2];}else{if(_3d=="frompoly"){sx=parseInt(_46[0],10);gx=parseInt(_46[0],10);sy=parseInt(_46[1],10);gy=parseInt(_46[1],10);for(i=0,le=_46.length;i<le;i++){if(i%2===0&&parseInt(_46[i],10)<sx){sx=parseInt(_46[i],10);} if(i%2===1&&parseInt(_46[i],10)<sy){sy=parseInt(_46[i],10);} if(i%2===0&&parseInt(_46[i],10)>gx){gx=parseInt(_46[i],10);} if(i%2===1&&parseInt(_46[i],10)>gy){gy=parseInt(_46[i],10);}} _46[2]=(gx-sx<gy-sy)?gx-sx:gy-sy;_46[2]=Math.floor(_46[2]/2);_46[0]=sx+_46[2];_46[1]=sy+_46[2];}} if(!(parseInt(_46[1],10)>0)){_46[1]=_46[0];} if(!(parseInt(_46[2],10)>0)){_46[2]=10;} _3b=_46[0]+","+_46[1]+","+_46[2];}else{if(_3c=="poly"){if(_3d=="fromrect"){_46[4]=_46[2];_46[5]=_46[3];_46[2]=_46[0];_46[6]=_46[4];_46[7]=_46[1];}else{if(_3d=="fromcircle"){var _48=parseInt(_46[0],10);var _49=parseInt(_46[1],10);var _4a=parseInt(_46[2],10);var j=0;_46[j++]=_48+_4a;_46[j++]=_49;var _4c=60;for(i=0;i<=_4c;i++){var _4d=i/_4c;var _4e=Math.cos(_4d*2*Math.PI);var _4f=Math.sin(_4d*2*Math.PI);var _50=_48+_4e*_4a;var _51=_49+_4f*_4a;_46[j++]=Math.round(_50);_46[j++]=Math.round(_51);}}} _3b=_46.join(",");}else{if(_3c=="bezier1"){_3b=_46.join(",");}}}} if(_3d=="preserve"&&_45!=_3b){return _45;} return _3b;};imgmap.prototype.setMapHTML=function(map){if(this.viewmode===1){return;} this.fireEvent("onSetMap",map);this.removeAllAreas();var _53;if(typeof map=="string"){var _54=document.createElement("DIV");_54.innerHTML=map;_53=_54.firstChild;}else{if(typeof map=="object"){_53=map;}} if(!_53||_53.nodeName.toLowerCase()!=="map"){return false;} this.mapname=_53.name;this.mapid=_53.id;var _55=_53.getElementsByTagName("area");var _56,_57,_58,alt,_5a,_5b,id;for(var i=0,le=_55.length;i<le;i++){_56=_57=_58=alt=_5a=_5b="";id=this.addNewArea();_56=this._normShape(_55[i].getAttribute("shape",2));this.initArea(id,_56);if(_55[i].getAttribute("coords",2)){_57=this._normCoords(_55[i].getAttribute("coords",2),_56);this.areas[id].lastInput=_57;} _58=_55[i].getAttribute("href",2);var _5f=_55[i].getAttribute("_fcksavedurl");if(_5f){_58=_5f;} if(_58){this.areas[id].ahref=_58;} alt=_55[i].getAttribute("alt");if(alt){this.areas[id].aalt=alt;} _5a=_55[i].getAttribute("title");if(!_5a){_5a=alt;} if(_5a){this.areas[id].atitle=_5a;} _5b=_55[i].getAttribute("target");if(_5b){_5b=_5b.toLowerCase();} this.areas[id].atarget=_5b;this._recalculate(id,_57);this.relaxArea(id);this.fireEvent("onAreaChanged",this.areas[id]);} this.fireEvent("onHtmlChanged",this.getMapHTML());return true;};imgmap.prototype.togglePreview=function(){var i,le;if(!this.pic){return false;} if(!this.preview){this.preview=document.createElement("DIV");this.preview.style.display="none";this.pic_container.appendChild(this.preview);} if(this.viewmode===0){for(i=0,le=this.areas.length;i<le;i++){if(this.areas[i]){this.areas[i].style.display="none";if(this.areas[i].label){this.areas[i].label.style.display="none";}}} this.preview.innerHTML=this.getMapHTML("noscale");this.pic.setAttribute("border","0",0);this.pic.setAttribute("usemap","#"+this.mapname,0);this.pic.style.cursor="auto";this.viewmode=1;this.statusMessage(this.strings.PREVIEW_MODE);}else{for(i=0,le=this.areas.length;i<le;i++){if(this.areas[i]){this.areas[i].style.display="";if(this.areas[i].label&&this.config.label){this.areas[i].label.style.display="";}}} this.preview.innerHTML="";this.pic.style.cursor=this.config.cursor_default;this.pic.removeAttribute("usemap",0);this.viewmode=0;this.statusMessage(this.strings.DESIGN_MODE);this.is_drawing=0;} this.fireEvent("onModeChanged",this.viewmode);return this.viewmode;};imgmap.prototype.addNewArea=function(){if(this.viewmode===1){return;} var _62=this._getLastArea();var id=(_62)?_62.aid+1:0;this.areas[id]=document.createElement("DIV");this.areas[id].id=this.mapname+"area"+id;this.areas[id].aid=id;this.areas[id].shape="undefined";this.currentid=id;this.fireEvent("onAddArea",id);return id;};imgmap.prototype.initArea=function(id,_65){if(!this.areas[id]){return false;} if(this.areas[id].parentNode){this.areas[id].parentNode.removeChild(this.areas[id]);} if(this.areas[id].label){this.areas[id].label.parentNode.removeChild(this.areas[id].label);} this.areas[id]=null;this.areas[id]=document.createElement("CANVAS");this.pic_container.appendChild(this.areas[id]);this.pic_container.style.position="relative";if(typeof G_vmlCanvasManager!="undefined"){this.areas[id]=G_vmlCanvasManager.initElement(this.areas[id]);} this.areas[id].id=this.mapname+"area"+id;this.areas[id].aid=id;this.areas[id].shape=_65;this.areas[id].ahref="";this.areas[id].atitle="";this.areas[id].aalt="";this.areas[id].atarget="";this.areas[id].style.position="absolute";this.areas[id].style.top=this.pic.offsetTop+"px";this.areas[id].style.left=this.pic.offsetLeft+"px";this._setopacity(this.areas[id],this.config.CL_DRAW_BG,this.config.draw_opacity);this.areas[id].ondblclick=this.area_dblclick.bind(this);this.areas[id].onmousedown=this.area_mousedown.bind(this);this.areas[id].onmouseup=this.area_mouseup.bind(this);this.areas[id].onmousemove=this.area_mousemove.bind(this);this.areas[id].onmouseover=this.area_mouseover.bind(this);this.areas[id].onmouseout=this.area_mouseout.bind(this);this.memory[id]={};this.memory[id].downx=0;this.memory[id].downy=0;this.memory[id].left=0;this.memory[id].top=0;this.memory[id].width=0;this.memory[id].height=0;this.memory[id].xpoints=[];this.memory[id].ypoints=[];this.areas[id].label=document.createElement("DIV");this.pic_container.appendChild(this.areas[id].label);this.areas[id].label.className=this.config.label_class;this.assignCSS(this.areas[id].label,this.config.label_style);this.areas[id].label.style.position="absolute";};imgmap.prototype.relaxArea=function(id){if(!this.areas[id]){return;} this.fireEvent("onRelaxArea",id);this._setBorder(id,"NORM");this._setopacity(this.areas[id],this.config.CL_NORM_BG,this.config.norm_opacity);};imgmap.prototype.relaxAllAreas=function(){for(var i=0,le=this.areas.length;i<le;i++){if(this.areas[i]){this.relaxArea(i);}}};imgmap.prototype._setBorder=function(id,_6a){if(this.areas[id].shape=="rect"||this.config.bounding_box){this.areas[id].style.borderWidth="1px";this.areas[id].style.borderStyle=(_6a=="DRAW"?"dotted":"solid");this.areas[id].style.borderColor=this.config["CL_"+_6a+"_"+(this.areas[id].shape=="rect"?"SHAPE":"BOX")];}else{this.areas[id].style.border="";}};imgmap.prototype._setopacity=function(_6b,_6c,pct){if(_6c){_6b.style.backgroundColor=_6c;} if(pct&&typeof pct=="string"&&pct.match(/^\d*\-\d+$/)){var _6e=pct.split("-");if(typeof _6e[0]!="undefined"){_6e[0]=parseInt(_6e[0],10);this._setopacity(_6b,_6c,_6e[0]);} if(typeof _6e[1]!="undefined"){_6e[1]=parseInt(_6e[1],10);var _6f=this._getopacity(_6b);var _70=this;var _71=Math.round(_6e[1]-_6f);if(_71>5){window.setTimeout(function(){_70._setopacity(_6b,null,"-"+_6e[1]);},20);pct=1*_6f+5;}else{if(_71<-3){window.setTimeout(function(){_70._setopacity(_6b,null,"-"+_6e[1]);},20);pct=1*_6f-3;}else{pct=_6e[1];}}}} if(!isNaN(pct)){pct=Math.round(parseInt(pct,10));_6b.style.opacity=pct/100;_6b.style.filter="alpha(opacity="+pct+")";}};imgmap.prototype._getopacity=function(_72){if(_72.style.opacity<=1){return _72.style.opacity*100;} if(_72.style.filter){return parseInt(_72.style.filter.replace(/alpha\(opacity\=([^\)]*)\)/ig,"$1"),10);} return 100;};imgmap.prototype.removeArea=function(id,_74){if(this.viewmode===1){return;} if(id===null||typeof id=="undefined"){return;} try{this.areas[id].label.parentNode.removeChild(this.areas[id].label);this.areas[id].parentNode.removeChild(this.areas[id]);this.areas[id].label.className=null;this.areas[id].label=null;this.areas[id].onmouseover=null;this.areas[id].onmouseout=null;this.areas[id].onmouseup=null;this.areas[id].onmousedown=null;this.areas[id].onmousemove=null;} catch(err){} this.areas[id]=null;this.fireEvent("onRemoveArea",id);if(!_74){this.fireEvent("onHtmlChanged",this.getMapHTML());}};imgmap.prototype.removeAllAreas=function(){for(var i=0,le=this.areas.length;i<le;i++){if(this.areas[i]){this.removeArea(i,true);}} this.fireEvent("onHtmlChanged",this.getMapHTML());};imgmap.prototype.scaleAllAreas=function(_77){var _78=1;try{_78=_77/this.globalscale;} catch(err){this.log("Invalid (global)scale",1);} this.globalscale=_77;for(var i=0,le=this.areas.length;i<le;i++){if(this.areas[i]&&this.areas[i].shape!="undefined"){this.scaleArea(i,_78);}}};imgmap.prototype.scaleArea=function(id,_7c){this.areas[id].style.top=parseInt(this.areas[id].style.top,10)*_7c+"px";this.areas[id].style.left=parseInt(this.areas[id].style.left,10)*_7c+"px";this.setAreaSize(id,this.areas[id].width*_7c,this.areas[id].height*_7c);if(this.areas[id].shape=="poly"||this.areas[id].shape=="bezier1"){for(var i=0,le=this.areas[id].xpoints.length;i<le;i++){this.areas[id].xpoints[i]*=_7c;this.areas[id].ypoints[i]*=_7c;}} this._repaint(this.areas[id],this.config.CL_NORM_SHAPE);this._updatecoords(id);};imgmap.prototype._putlabel=function(id){if(this.viewmode===1){return;} if(!this.areas[id].label){return;} try{if(!this.config.label){this.areas[id].label.innerHTML="";this.areas[id].label.style.display="none";}else{this.areas[id].label.style.display="";var _80=this.config.label;_80=_80.replace(/%n/g,String(id));_80=_80.replace(/%c/g,String(this.areas[id].lastInput));_80=_80.replace(/%h/g,String(this.areas[id].ahref));_80=_80.replace(/%a/g,String(this.areas[id].aalt));_80=_80.replace(/%t/g,String(this.areas[id].atitle));this.areas[id].label.innerHTML=_80;} this.areas[id].label.style.top=this.areas[id].style.top;this.areas[id].label.style.left=this.areas[id].style.left;} catch(err){this.log("Error putting label",1);}};imgmap.prototype._puthint=function(id){try{if(!this.config.hint){this.areas[id].title="";this.areas[id].alt="";}else{var _82=this.config.hint;_82=_82.replace(/%n/g,String(id));_82=_82.replace(/%c/g,String(this.areas[id].lastInput));_82=_82.replace(/%h/g,String(this.areas[id].ahref));_82=_82.replace(/%a/g,String(this.areas[id].aalt));_82=_82.replace(/%t/g,String(this.areas[id].atitle));this.areas[id].title=_82;this.areas[id].alt=_82;}} catch(err){this.log("Error putting hint",1);}};imgmap.prototype._repaintAll=function(){for(var i=0,le=this.areas.length;i<le;i++){if(this.areas[i]){this._repaint(this.areas[i],this.config.CL_NORM_SHAPE);}}};imgmap.prototype._repaint=function(_85,_86,x,y){var ctx;var _8a,_8b,_8c,top;var i,le;if(_85.shape=="circle"){_8a=parseInt(_85.style.width,10);var _90=Math.floor(_8a/2)-1;ctx=_85.getContext("2d");ctx.clearRect(0,0,_8a,_8a);ctx.beginPath();ctx.strokeStyle=_86;ctx.arc(_90,_90,_90,0,Math.PI*2,0);ctx.stroke();ctx.closePath();ctx.strokeStyle=this.config.CL_KNOB;ctx.strokeRect(_90,_90,1,1);this._putlabel(_85.aid);this._puthint(_85.aid);}else{if(_85.shape=="rect"){this._putlabel(_85.aid);this._puthint(_85.aid);}else{if(_85.shape=="poly"){_8a=parseInt(_85.style.width,10);_8b=parseInt(_85.style.height,10);_8c=parseInt(_85.style.left,10);top=parseInt(_85.style.top,10);if(_85.xpoints){ctx=_85.getContext("2d");ctx.clearRect(0,0,_8a,_8b);ctx.beginPath();ctx.strokeStyle=_86;ctx.moveTo(_85.xpoints[0]-_8c,_85.ypoints[0]-top);for(i=1,le=_85.xpoints.length;i<le;i++){ctx.lineTo(_85.xpoints[i]-_8c,_85.ypoints[i]-top);} if(this.is_drawing==this.DM_POLYGON_DRAW||this.is_drawing==this.DM_POLYGON_LASTDRAW){ctx.lineTo(x-_8c-5,y-top-5);} ctx.lineTo(_85.xpoints[0]-_8c,_85.ypoints[0]-top);ctx.stroke();ctx.closePath();} this._putlabel(_85.aid);this._puthint(_85.aid);}else{if(_85.shape=="bezier1"){_8a=parseInt(_85.style.width,10);_8b=parseInt(_85.style.height,10);_8c=parseInt(_85.style.left,10);top=parseInt(_85.style.top,10);if(_85.xpoints){ctx=_85.getContext("2d");ctx.clearRect(0,0,_8a,_8b);ctx.beginPath();ctx.strokeStyle=_86;ctx.moveTo(_85.xpoints[0]-_8c,_85.ypoints[0]-top);for(i=2,le=_85.xpoints.length;i<le;i+=2){ctx.quadraticCurveTo(_85.xpoints[i-1]-_8c,_85.ypoints[i-1]-top,_85.xpoints[i]-_8c,_85.ypoints[i]-top);} if(this.is_drawing==this.DM_BEZIER_DRAW||this.is_drawing==this.DM_BEZIER_LASTDRAW){if(_85.xpoints.length%2===0&&_85.xpoints.length>1){ctx.quadraticCurveTo(_85.xpoints[_85.xpoints.length-1]-_8c-5,_85.ypoints[_85.ypoints.length-1]-top-5,x-_8c-5,y-top-5);}else{ctx.lineTo(x-_8c-5,y-top-5);}} ctx.lineTo(_85.xpoints[0]-_8c,_85.ypoints[0]-top);ctx.stroke();ctx.closePath();} this._putlabel(_85.aid);this._puthint(_85.aid);}}}}};imgmap.prototype._updatecoords=function(id){var _92=Math.round(parseInt(this.areas[id].style.left,10)/this.globalscale);var top=Math.round(parseInt(this.areas[id].style.top,10)/this.globalscale);var _94=Math.round(parseInt(this.areas[id].style.height,10)/this.globalscale);var _95=Math.round(parseInt(this.areas[id].style.width,10)/this.globalscale);var _96="";if(this.areas[id].shape=="rect"){_96=_92+","+top+","+(_92+_95)+","+(top+_94);this.areas[id].lastInput=_96;}else{if(this.areas[id].shape=="circle"){var _97=Math.floor(_95/2)-1;_96=(_92+_97)+","+(top+_97)+","+_97;this.areas[id].lastInput=_96;}else{if(this.areas[id].shape=="poly"||this.areas[id].shape=="bezier1"){if(this.areas[id].xpoints){for(var i=0,le=this.areas[id].xpoints.length;i<le;i++){_96+=Math.round(this.areas[id].xpoints[i]/this.globalscale)+","+Math.round(this.areas[id].ypoints[i]/this.globalscale)+",";} _96=_96.substring(0,_96.length-1);} this.areas[id].lastInput=_96;}}} this.fireEvent("onAreaChanged",this.areas[id]);this.fireEvent("onHtmlChanged",this.getMapHTML());};imgmap.prototype._recalculate=function(id,_9b){try{if(_9b){_9b=this._normCoords(_9b,this.areas[id].shape,"preserve");}else{_9b=this.areas[id].lastInput||"";} var _9c=_9b.split(",");if(this.areas[id].shape=="rect"){if(_9c.length!=4||parseInt(_9c[0],10)>parseInt(_9c[2],10)||parseInt(_9c[1],10)>parseInt(_9c[3],10)){throw"invalid coords";} this.areas[id].style.left=this.globalscale*(this.pic.offsetLeft+parseInt(_9c[0],10))+"px";this.areas[id].style.top=this.globalscale*(this.pic.offsetTop+parseInt(_9c[1],10))+"px";this.setAreaSize(id,this.globalscale*(_9c[2]-_9c[0]),this.globalscale*(_9c[3]-_9c[1]));this._repaint(this.areas[id],this.config.CL_NORM_SHAPE);}else{if(this.areas[id].shape=="circle"){if(_9c.length!=3||parseInt(_9c[2],10)<0){throw"invalid coords";} var _9d=2*(_9c[2]);this.setAreaSize(id,this.globalscale*_9d,this.globalscale*_9d);this.areas[id].style.left=this.globalscale*(this.pic.offsetLeft+parseInt(_9c[0],10)-_9d/2)+"px";this.areas[id].style.top=this.globalscale*(this.pic.offsetTop+parseInt(_9c[1],10)-_9d/2)+"px";this._repaint(this.areas[id],this.config.CL_NORM_SHAPE);}else{if(this.areas[id].shape=="poly"||this.areas[id].shape=="bezier1"){if(_9c.length<2){throw"invalid coords";} this.areas[id].xpoints=[];this.areas[id].ypoints=[];for(var i=0,le=_9c.length;i<le;i+=2){this.areas[id].xpoints[this.areas[id].xpoints.length]=this.globalscale*(this.pic.offsetLeft+parseInt(_9c[i],10));this.areas[id].ypoints[this.areas[id].ypoints.length]=this.globalscale*(this.pic.offsetTop+parseInt(_9c[i+1],10));this._polygongrow(this.areas[id],this.globalscale*_9c[i],this.globalscale*_9c[i+1]);} this._polygonshrink(this.areas[id]);}}}} catch(err){var msg=(err.message)?err.message:"error calculating coordinates";this.log(msg,1);this.statusMessage(this.strings.ERR_INVALID_COORDS);if(this.areas[id].lastInput){this.fireEvent("onAreaChanged",this.areas[id]);} this._repaint(this.areas[id],this.config.CL_NORM_SHAPE);return;} this.areas[id].lastInput=_9b;};imgmap.prototype._polygongrow=function(_a1,_a2,_a3){var _a4=_a2-parseInt(_a1.style.left,10);var _a5=_a3-parseInt(_a1.style.top,10);var pad=0;var _a7=0;if(_a2<parseInt(_a1.style.left,10)){_a1.style.left=(_a2-pad)+"px";this.setAreaSize(_a1.aid,parseInt(_a1.style.width,10)+Math.abs(_a4)+_a7,null);}else{if(_a2>parseInt(_a1.style.left,10)+parseInt(_a1.style.width,10)){this.setAreaSize(_a1.aid,_a2-parseInt(_a1.style.left,10)+_a7,null);}} if(_a3<parseInt(_a1.style.top,10)){_a1.style.top=(_a3-pad)+"px";this.setAreaSize(_a1.aid,null,parseInt(_a1.style.height,10)+Math.abs(_a5)+_a7);}else{if(_a3>parseInt(_a1.style.top,10)+parseInt(_a1.style.height,10)){this.setAreaSize(_a1.aid,null,_a3-parseInt(_a1.style.top,10)+_a7);}}};imgmap.prototype._polygonshrink=function(_a8){_a8.style.left=(_a8.xpoints[0])+"px";_a8.style.top=(_a8.ypoints[0])+"px";this.setAreaSize(_a8.aid,0,0);for(var i=0,le=_a8.xpoints.length;i<le;i++){this._polygongrow(_a8,_a8.xpoints[i],_a8.ypoints[i]);} this._repaint(_a8,this.config.CL_NORM_SHAPE);};imgmap.prototype.img_mousemove=function(e){var x;var y;var _ae;var _af;var _b0;if(this.viewmode===1){return;} var pos=this._getPos(this.pic);x=(this.isMSIE)?(window.event.x-this.pic.offsetLeft):(e.pageX-pos.x);y=(this.isMSIE)?(window.event.y-this.pic.offsetTop):(e.pageY-pos.y);x=x+this.pic_container.scrollLeft;y=y+this.pic_container.scrollTop;if(x<0||y<0||x>this.pic.width||y>this.pic.height){return;} if(this.memory[this.currentid]){var top=this.memory[this.currentid].top;var _b3=this.memory[this.currentid].left;var _b4=this.memory[this.currentid].height;var _b5=this.memory[this.currentid].width;} if(this.isSafari){if(e.shiftKey){if(this.is_drawing==this.DM_RECTANGLE_DRAW){this.is_drawing=this.DM_SQUARE_DRAW;this.statusMessage(this.strings.SQUARE2_DRAW);}}else{if(this.is_drawing==this.DM_SQUARE_DRAW&&this.areas[this.currentid].shape=="rect"){this.is_drawing=this.DM_RECTANGLE_DRAW;this.statusMessage(this.strings.RECTANGLE_DRAW);}}} if(this.is_drawing==this.DM_RECTANGLE_DRAW){this.fireEvent("onDrawArea",this.currentid);_ae=x-this.memory[this.currentid].downx;_af=y-this.memory[this.currentid].downy;this.setAreaSize(this.currentid,Math.abs(_ae),Math.abs(_af));if(_ae<0){this.areas[this.currentid].style.left=(x+1)+"px";} if(_af<0){this.areas[this.currentid].style.top=(y+1)+"px";}}else{if(this.is_drawing==this.DM_SQUARE_DRAW){this.fireEvent("onDrawArea",this.currentid);_ae=x-this.memory[this.currentid].downx;_af=y-this.memory[this.currentid].downy;if(Math.abs(_ae)<Math.abs(_af)){_b0=Math.abs(parseInt(_ae,10));}else{_b0=Math.abs(parseInt(_af,10));} this.setAreaSize(this.currentid,_b0,_b0);if(_ae<0){this.areas[this.currentid].style.left=(this.memory[this.currentid].downx+_b0*-1)+"px";} if(_af<0){this.areas[this.currentid].style.top=(this.memory[this.currentid].downy+_b0*-1+1)+"px";}}else{if(this.is_drawing==this.DM_POLYGON_DRAW||this.is_drawing==this.DM_BEZIER_DRAW){this.fireEvent("onDrawArea",this.currentid);this._polygongrow(this.areas[this.currentid],x,y);}else{if(this.is_drawing==this.DM_RECTANGLE_MOVE||this.is_drawing==this.DM_SQUARE_MOVE){this.fireEvent("onMoveArea",this.currentid);x=x-this.memory[this.currentid].rdownx;y=y-this.memory[this.currentid].rdowny;if(x+_b5>this.pic.width||y+_b4>this.pic.height){return;} if(x<0||y<0){return;} this.areas[this.currentid].style.left=x+1+"px";this.areas[this.currentid].style.top=y+1+"px";}else{if(this.is_drawing==this.DM_POLYGON_MOVE||this.is_drawing==this.DM_BEZIER_MOVE){this.fireEvent("onMoveArea",this.currentid);x=x-this.memory[this.currentid].rdownx;y=y-this.memory[this.currentid].rdowny;if(x+_b5>this.pic.width||y+_b4>this.pic.height){return;} if(x<0||y<0){return;} _ae=x-_b3;_af=y-top;if(this.areas[this.currentid].xpoints){for(var i=0,le=this.areas[this.currentid].xpoints.length;i<le;i++){this.areas[this.currentid].xpoints[i]=this.memory[this.currentid].xpoints[i]+_ae;this.areas[this.currentid].ypoints[i]=this.memory[this.currentid].ypoints[i]+_af;}} this.areas[this.currentid].style.left=x+"px";this.areas[this.currentid].style.top=y+"px";}else{if(this.is_drawing==this.DM_SQUARE_RESIZE_LEFT){this.fireEvent("onResizeArea",this.currentid);_b0=x-_b3;if((_b5+(-1*_b0))>0){this.areas[this.currentid].style.left=x+1+"px";this.areas[this.currentid].style.top=(top+(_b0/2))+"px";this.setAreaSize(this.currentid,parseInt(_b5+(-1*_b0),10),parseInt(_b4+(-1*_b0),10));}else{this.memory[this.currentid].width=0;this.memory[this.currentid].height=0;this.memory[this.currentid].left=x;this.memory[this.currentid].top=y;this.is_drawing=this.DM_SQUARE_RESIZE_RIGHT;}}else{if(this.is_drawing==this.DM_SQUARE_RESIZE_RIGHT){this.fireEvent("onResizeArea",this.currentid);_b0=x-_b3-_b5;if((_b5+(_b0))-1>0){this.areas[this.currentid].style.top=(top+(-1*_b0/2))+"px";this.setAreaSize(this.currentid,(_b5+(_b0))-1,(_b4+(_b0)));}else{this.memory[this.currentid].width=0;this.memory[this.currentid].height=0;this.memory[this.currentid].left=x;this.memory[this.currentid].top=y;this.is_drawing=this.DM_SQUARE_RESIZE_LEFT;}}else{if(this.is_drawing==this.DM_SQUARE_RESIZE_TOP){this.fireEvent("onResizeArea",this.currentid);_b0=y-top;if((_b5+(-1*_b0))>0){this.areas[this.currentid].style.top=y+1+"px";this.areas[this.currentid].style.left=(_b3+(_b0/2))+"px";this.setAreaSize(this.currentid,(_b5+(-1*_b0)),(_b4+(-1*_b0)));}else{this.memory[this.currentid].width=0;this.memory[this.currentid].height=0;this.memory[this.currentid].left=x;this.memory[this.currentid].top=y;this.is_drawing=this.DM_SQUARE_RESIZE_BOTTOM;}}else{if(this.is_drawing==this.DM_SQUARE_RESIZE_BOTTOM){this.fireEvent("onResizeArea",this.currentid);_b0=y-top-_b4;if((_b5+(_b0))-1>0){this.areas[this.currentid].style.left=(_b3+(-1*_b0/2))+"px";this.setAreaSize(this.currentid,(_b5+(_b0))-1,(_b4+(_b0))-1);}else{this.memory[this.currentid].width=0;this.memory[this.currentid].height=0;this.memory[this.currentid].left=x;this.memory[this.currentid].top=y;this.is_drawing=this.DM_SQUARE_RESIZE_TOP;}}else{if(this.is_drawing==this.DM_RECTANGLE_RESIZE_LEFT){this.fireEvent("onResizeArea",this.currentid);_ae=x-_b3;if(_b5+(-1*_ae)>0){this.areas[this.currentid].style.left=x+1+"px";this.setAreaSize(this.currentid,_b5+(-1*_ae),null);}else{this.memory[this.currentid].width=0;this.memory[this.currentid].left=x;this.is_drawing=this.DM_RECTANGLE_RESIZE_RIGHT;}}else{if(this.is_drawing==this.DM_RECTANGLE_RESIZE_RIGHT){this.fireEvent("onResizeArea",this.currentid);_ae=x-_b3-_b5;if((_b5+(_ae))-1>0){this.setAreaSize(this.currentid,(_b5+(_ae))-1,null);}else{this.memory[this.currentid].width=0;this.memory[this.currentid].left=x;this.is_drawing=this.DM_RECTANGLE_RESIZE_LEFT;}}else{if(this.is_drawing==this.DM_RECTANGLE_RESIZE_TOP){this.fireEvent("onResizeArea",this.currentid);_af=y-top;if((_b4+(-1*_af))>0){this.areas[this.currentid].style.top=y+1+"px";this.setAreaSize(this.currentid,null,(_b4+(-1*_af)));}else{this.memory[this.currentid].height=0;this.memory[this.currentid].top=y;this.is_drawing=this.DM_RECTANGLE_RESIZE_BOTTOM;}}else{if(this.is_drawing==this.DM_RECTANGLE_RESIZE_BOTTOM){this.fireEvent("onResizeArea",this.currentid);_af=y-top-_b4;if((_b4+(_af))-1>0){this.setAreaSize(this.currentid,null,(_b4+(_af))-1);}else{this.memory[this.currentid].height=0;this.memory[this.currentid].top=y;this.is_drawing=this.DM_RECTANGLE_RESIZE_TOP;}}}}}}}}}}}}}} if(this.is_drawing){this._repaint(this.areas[this.currentid],this.config.CL_DRAW_SHAPE,x,y);this._updatecoords(this.currentid);}};imgmap.prototype.img_mouseup=function(e){if(this.viewmode===1){return;} var pos=this._getPos(this.pic);var x=(this.isMSIE)?(window.event.x-this.pic.offsetLeft):(e.pageX-pos.x);var y=(this.isMSIE)?(window.event.y-this.pic.offsetTop):(e.pageY-pos.y);x=x+this.pic_container.scrollLeft;y=y+this.pic_container.scrollTop;if(this.is_drawing!=this.DM_RECTANGLE_DRAW&&this.is_drawing!=this.DM_SQUARE_DRAW&&this.is_drawing!=this.DM_POLYGON_DRAW&&this.is_drawing!=this.DM_POLYGON_LASTDRAW&&this.is_drawing!=this.DM_BEZIER_DRAW&&this.is_drawing!=this.DM_BEZIER_LASTDRAW){this.draggedId=null;this.is_drawing=0;this.statusMessage(this.strings.READY);this.relaxArea(this.currentid);if(this.areas[this.currentid]==this._getLastArea()){return;} this.memory[this.currentid].downx=x;this.memory[this.currentid].downy=y;}};imgmap.prototype.img_mousedown=function(e){if(this.viewmode===1){return;} if(!this.areas[this.currentid]&&this.config.mode!="editor2"){return;} var pos=this._getPos(this.pic);var x=(this.isMSIE)?(window.event.x-this.pic.offsetLeft):(e.pageX-pos.x);var y=(this.isMSIE)?(window.event.y-this.pic.offsetTop):(e.pageY-pos.y);x=x+this.pic_container.scrollLeft;y=y+this.pic_container.scrollTop;if(!e){e=window.event;} if(e.shiftKey){if(this.is_drawing==this.DM_POLYGON_DRAW){this.is_drawing=this.DM_POLYGON_LASTDRAW;}else{if(this.is_drawing==this.DM_BEZIER_DRAW){this.is_drawing=this.DM_BEZIER_LASTDRAW;}}} if(this.is_drawing==this.DM_POLYGON_DRAW||this.is_drawing==this.DM_BEZIER_DRAW){this.areas[this.currentid].xpoints[this.areas[this.currentid].xpoints.length]=x-5;this.areas[this.currentid].ypoints[this.areas[this.currentid].ypoints.length]=y-5;this.memory[this.currentid].downx=x;this.memory[this.currentid].downy=y;return;}else{if(this.is_drawing&&this.is_drawing!=this.DM_POLYGON_DRAW&&this.is_drawing!=this.DM_BEZIER_DRAW){if(this.is_drawing==this.DM_POLYGON_LASTDRAW||this.is_drawing==this.DM_BEZIER_LASTDRAW){this.areas[this.currentid].xpoints[this.areas[this.currentid].xpoints.length]=x-5;this.areas[this.currentid].ypoints[this.areas[this.currentid].ypoints.length]=y-5;this._updatecoords(this.currentid);this.is_drawing=0;this._polygonshrink(this.areas[this.currentid]);} this.is_drawing=0;this.statusMessage(this.strings.READY);this.relaxArea(this.currentid);if(this.areas[this.currentid]==this._getLastArea()){if(this.config.mode!="editor2"){this.addNewArea();} return;} return;}} if(this.config.mode=="editor2"){if(!this.nextShape){return;} this.addNewArea();this.initArea(this.currentid,this.nextShape);}else{if(this.areas[this.currentid].shape=="undefined"||this.areas[this.currentid].shape=="poly"){var _c0=this.nextShape;if(!_c0){_c0="rect";} this.initArea(this.currentid,_c0);}} if(this.areas[this.currentid].shape=="poly"){this.is_drawing=this.DM_POLYGON_DRAW;this.statusMessage(this.strings.POLYGON_DRAW);this.areas[this.currentid].style.left=x+"px";this.areas[this.currentid].style.top=y+"px";this.areas[this.currentid].style.width=0;this.areas[this.currentid].style.height=0;this.areas[this.currentid].xpoints=[];this.areas[this.currentid].ypoints=[];this.areas[this.currentid].xpoints[0]=x;this.areas[this.currentid].ypoints[0]=y;}else{if(this.areas[this.currentid].shape=="bezier1"){this.is_drawing=this.DM_BEZIER_DRAW;this.statusMessage(this.strings.BEZIER_DRAW);this.areas[this.currentid].style.left=x+"px";this.areas[this.currentid].style.top=y+"px";this.areas[this.currentid].style.width=0;this.areas[this.currentid].style.height=0;this.areas[this.currentid].xpoints=[];this.areas[this.currentid].ypoints=[];this.areas[this.currentid].xpoints[0]=x;this.areas[this.currentid].ypoints[0]=y;}else{if(this.areas[this.currentid].shape=="rect"){this.is_drawing=this.DM_RECTANGLE_DRAW;this.statusMessage(this.strings.RECTANGLE_DRAW);this.areas[this.currentid].style.left=x+"px";this.areas[this.currentid].style.top=y+"px";this.areas[this.currentid].style.width=0;this.areas[this.currentid].style.height=0;}else{if(this.areas[this.currentid].shape=="circle"){this.is_drawing=this.DM_SQUARE_DRAW;this.statusMessage(this.strings.SQUARE_DRAW);this.areas[this.currentid].style.left=x+"px";this.areas[this.currentid].style.top=y+"px";this.areas[this.currentid].style.width=0;this.areas[this.currentid].style.height=0;}}}} this._setBorder(this.currentid,"DRAW");this.memory[this.currentid].downx=x;this.memory[this.currentid].downy=y;};imgmap.prototype.highlightArea=function(id,_c2){if(this.is_drawing){return;} if(this.areas[id]&&this.areas[id].shape!="undefined"){this.fireEvent("onFocusArea",this.areas[id]);this._setBorder(id,"HIGHLIGHT");var _c3=this.config.highlight_opacity;if(_c2=="grad"){_c3="-"+_c3;} this._setopacity(this.areas[id],this.config.CL_HIGHLIGHT_BG,_c3);this._repaint(this.areas[id],this.config.CL_HIGHLIGHT_SHAPE);}};imgmap.prototype.blurArea=function(id,_c5){if(this.is_drawing){return;} if(this.areas[id]&&this.areas[id].shape!="undefined"){this.fireEvent("onBlurArea",this.areas[id]);this._setBorder(id,"NORM");var _c6=this.config.norm_opacity;if(_c5=="grad"){_c6="-"+_c6;} this._setopacity(this.areas[id],this.config.CL_NORM_BG,_c6);this._repaint(this.areas[id],this.config.CL_NORM_SHAPE);}};imgmap.prototype.area_mousemove=function(e){if(this.viewmode===1){return;} if(!this.is_drawing){var obj=(this.isMSIE)?window.event.srcElement:e.currentTarget;if(obj.tagName=="DIV"){obj=obj.parentNode;} if(obj.tagName=="image"||obj.tagName=="group"||obj.tagName=="shape"||obj.tagName=="stroke"){obj=obj.parentNode.parentNode;} if(this.isOpera){e.layerX=e.offsetX;e.layerY=e.offsetY;} var _c9=(this.isMSIE)?(window.event.offsetX):(e.layerX);var _ca=(this.isMSIE)?(window.event.offsetY):(e.layerY);var _cb=(obj.shape=="rect"||obj.shape=="circle");if(_cb&&_c9<6&&_ca>6){obj.style.cursor="w-resize";}else{if(_cb&&_c9>parseInt(obj.style.width,10)-6&&_ca>6){obj.style.cursor="e-resize";}else{if(_cb&&_c9>6&&_ca<6){obj.style.cursor="n-resize";}else{if(_cb&&_ca>parseInt(obj.style.height,10)-6&&_c9>6){obj.style.cursor="s-resize";}else{obj.style.cursor="move";}}}} if(obj.aid!=this.draggedId){if(obj.style.cursor=="move"){obj.style.cursor="default";} return;} if(_c9<6&&_ca>6){if(this.areas[this.currentid].shape=="circle"){this.is_drawing=this.DM_SQUARE_RESIZE_LEFT;this.statusMessage(this.strings.SQUARE_RESIZE_LEFT);}else{if(this.areas[this.currentid].shape=="rect"){this.is_drawing=this.DM_RECTANGLE_RESIZE_LEFT;this.statusMessage(this.strings.RECTANGLE_RESIZE_LEFT);}}}else{if(_c9>parseInt(this.areas[this.currentid].style.width,10)-6&&_ca>6){if(this.areas[this.currentid].shape=="circle"){this.is_drawing=this.DM_SQUARE_RESIZE_RIGHT;this.statusMessage(this.strings.SQUARE_RESIZE_RIGHT);}else{if(this.areas[this.currentid].shape=="rect"){this.is_drawing=this.DM_RECTANGLE_RESIZE_RIGHT;this.statusMessage(this.strings.RECTANGLE_RESIZE_RIGHT);}}}else{if(_c9>6&&_ca<6){if(this.areas[this.currentid].shape=="circle"){this.is_drawing=this.DM_SQUARE_RESIZE_TOP;this.statusMessage(this.strings.SQUARE_RESIZE_TOP);}else{if(this.areas[this.currentid].shape=="rect"){this.is_drawing=this.DM_RECTANGLE_RESIZE_TOP;this.statusMessage(this.strings.RECTANGLE_RESIZE_TOP);}}}else{if(_ca>parseInt(this.areas[this.currentid].style.height,10)-6&&_c9>6){if(this.areas[this.currentid].shape=="circle"){this.is_drawing=this.DM_SQUARE_RESIZE_BOTTOM;this.statusMessage(this.strings.SQUARE_RESIZE_BOTTOM);}else{if(this.areas[this.currentid].shape=="rect"){this.is_drawing=this.DM_RECTANGLE_RESIZE_BOTTOM;this.statusMessage(this.strings.RECTANGLE_RESIZE_BOTTOM);}}}else{if(this.areas[this.currentid].shape=="circle"){this.is_drawing=this.DM_SQUARE_MOVE;this.statusMessage(this.strings.SQUARE_MOVE);this.memory[this.currentid].rdownx=_c9;this.memory[this.currentid].rdowny=_ca;}else{if(this.areas[this.currentid].shape=="rect"){this.is_drawing=this.DM_RECTANGLE_MOVE;this.statusMessage(this.strings.RECTANGLE_MOVE);this.memory[this.currentid].rdownx=_c9;this.memory[this.currentid].rdowny=_ca;}else{if(this.areas[this.currentid].shape=="poly"||this.areas[this.currentid].shape=="bezier1"){if(this.areas[this.currentid].xpoints){for(var i=0,le=this.areas[this.currentid].xpoints.length;i<le;i++){this.memory[this.currentid].xpoints[i]=this.areas[this.currentid].xpoints[i];this.memory[this.currentid].ypoints[i]=this.areas[this.currentid].ypoints[i];}} if(this.areas[this.currentid].shape=="poly"){this.is_drawing=this.DM_POLYGON_MOVE;this.statusMessage(this.strings.POLYGON_MOVE);}else{if(this.areas[this.currentid].shape=="bezier1"){this.is_drawing=this.DM_BEZIER_MOVE;this.statusMessage(this.strings.BEZIER_MOVE);}} this.memory[this.currentid].rdownx=_c9;this.memory[this.currentid].rdowny=_ca;}}}}}}} this.memory[this.currentid].width=parseInt(this.areas[this.currentid].style.width,10);this.memory[this.currentid].height=parseInt(this.areas[this.currentid].style.height,10);this.memory[this.currentid].top=parseInt(this.areas[this.currentid].style.top,10);this.memory[this.currentid].left=parseInt(this.areas[this.currentid].style.left,10);this._setBorder(this.currentid,"DRAW");this._setopacity(this.areas[this.currentid],this.config.CL_DRAW_BG,this.config.draw_opacity);}else{this.img_mousemove(e);}};imgmap.prototype.area_mouseup=function(e){if(this.viewmode===1){return;} if(!this.is_drawing){var obj=(this.isMSIE)?window.event.srcElement:e.currentTarget;if(obj.tagName=="DIV"){obj=obj.parentNode;} if(obj.tagName=="image"||obj.tagName=="group"||obj.tagName=="shape"||obj.tagName=="stroke"){obj=obj.parentNode.parentNode;} if(this.areas[this.currentid]!=obj){if(typeof obj.aid=="undefined"){this.log("Cannot identify target area",1);return;}} this.draggedId=null;}else{this.img_mouseup(e);}};imgmap.prototype.area_mouseover=function(e){if(this.viewmode===1&&this.config.mode!=="highlighter_spawn"){return;} if(!this.is_drawing){var obj=(this.isMSIE)?window.event.srcElement:e.currentTarget;if(obj.tagName=="DIV"){obj=obj.parentNode;} if(obj.tagName=="image"||obj.tagName=="group"||obj.tagName=="shape"||obj.tagName=="stroke"){obj=obj.parentNode.parentNode;} this.highlightArea(obj.aid,"grad");}};imgmap.prototype.area_mouseout=function(e){if(this.viewmode===1&&this.config.mode!=="highlighter_spawn"){return;} if(!this.is_drawing){var obj=(this.isMSIE)?window.event.srcElement:e.currentTarget;if(obj.tagName=="DIV"){obj=obj.parentNode;} if(obj.tagName=="image"||obj.tagName=="group"||obj.tagName=="shape"||obj.tagName=="stroke"){obj=obj.parentNode.parentNode;} this.blurArea(obj.aid,"grad");}};imgmap.prototype.area_dblclick=function(e){if(this.viewmode===1){return;} if(!this.is_drawing){var obj=(this.isMSIE)?window.event.srcElement:e.currentTarget;if(obj.tagName=="DIV"){obj=obj.parentNode;} if(obj.tagName=="image"||obj.tagName=="group"||obj.tagName=="shape"||obj.tagName=="stroke"){obj=obj.parentNode.parentNode;} if(this.areas[this.currentid]!=obj){if(typeof obj.aid=="undefined"){this.log("Cannot identify target area",1);return;} this.currentid=obj.aid;} this.fireEvent("onDblClickArea",this.areas[this.currentid]);if(this.isMSIE){window.event.cancelBubble=true;}else{e.stopPropagation();}}};imgmap.prototype.area_mousedown=function(e){if(this.viewmode===1&&this.config.mode!=="highlighter_spawn"){return;} if(!this.is_drawing){var obj=(this.isMSIE)?window.event.srcElement:e.currentTarget;if(obj.tagName=="DIV"){obj=obj.parentNode;} if(obj.tagName=="image"||obj.tagName=="group"||obj.tagName=="shape"||obj.tagName=="stroke"){obj=obj.parentNode.parentNode;} if(this.areas[this.currentid]!=obj){if(typeof obj.aid=="undefined"){this.log("Cannot identify target area",1);return;} this.currentid=obj.aid;} this.draggedId=this.currentid;this.selectedId=this.currentid;this.fireEvent("onSelectArea",this.areas[this.currentid]);if(this.isMSIE){window.event.cancelBubble=true;}else{e.stopPropagation();}}else{this.img_mousedown(e);}};imgmap.prototype.doc_keydown=function(e){if(this.viewmode===1){return;} var key=(this.isMSIE)?event.keyCode:e.keyCode;if(key==46){if(this.selectedId!==null&&!this.is_drawing){this.removeArea(this.selectedId);}}else{if(key==16){if(this.is_drawing==this.DM_RECTANGLE_DRAW){this.is_drawing=this.DM_SQUARE_DRAW;this.statusMessage(this.strings.SQUARE2_DRAW);}}}};imgmap.prototype.doc_keyup=function(e){var key=(this.isMSIE)?event.keyCode:e.keyCode;if(key==16){if(this.is_drawing==this.DM_SQUARE_DRAW&&this.areas[this.currentid].shape=="rect"){this.is_drawing=this.DM_RECTANGLE_DRAW;this.statusMessage(this.strings.RECTANGLE_DRAW);}}};imgmap.prototype.doc_mousedown=function(e){if(this.viewmode===1){return;} if(!this.is_drawing){this.selectedId=null;}};imgmap.prototype._getPos=function(_dd){var _de=0;var _df=0;if(_dd){var _e0=_dd.offsetParent;if(_e0){while((_e0=_dd.offsetParent)){if(_dd.offsetLeft>0){_de+=_dd.offsetLeft;} if(_dd.offsetTop>0){_df+=_dd.offsetTop;} _dd=_e0;}}else{_de=_dd.offsetLeft;_df=_dd.offsetTop;}} return{x:_de,y:_df};};imgmap.prototype._getLastArea=function(){for(var i=this.areas.length-1;i>=0;i--){if(this.areas[i]){return this.areas[i];}} return null;};imgmap.prototype.assignCSS=function(obj,_e3){var _e4=_e3.split(";");for(var i=0;i<_e4.length;i++){var p=_e4[i].split(":");var pp=this.trim(p[0]).split("-");var _e8=pp[0];for(var j=1;j<pp.length;j++){_e8+=pp[j].replace(/^\w/,pp[j].substring(0,1).toUpperCase());} obj.style[this.trim(_e8)]=this.trim(p[1]);}};imgmap.prototype.fireEvent=function(evt,obj){if(typeof this.config.custom_callbacks[evt]=="function"){return this.config.custom_callbacks[evt](obj);}};imgmap.prototype.setAreaSize=function(id,w,h){if(id===null){id=this.currentid;} if(w!==null){this.areas[id].width=w;this.areas[id].style.width=(w)+"px";this.areas[id].setAttribute("width",w);} if(h!==null){this.areas[id].height=h;this.areas[id].style.height=(h)+"px";this.areas[id].setAttribute("height",h);}};imgmap.prototype.detectLanguage=function(){var _ef;if(navigator.userLanguage){_ef=navigator.userLanguage.toLowerCase();}else{if(navigator.language){_ef=navigator.language.toLowerCase();}else{return this.config.defaultLang;}} if(_ef.length>=2){_ef=_ef.substring(0,2);return _ef;} return this.config.defaultLang;};imgmap.prototype.disableSelection=function(_f0){if(typeof _f0=="undefined"||!_f0){return false;} if(typeof _f0.onselectstart!="undefined"){_f0.onselectstart=function(){return false;};} if(typeof _f0.unselectable!="undefined"){_f0.unselectable="on";} if(typeof _f0.style.MozUserSelect!="undefined"){_f0.style.MozUserSelect="none";}};Function.prototype.bind=function(_f1){var _f2=this;return function(){return _f2.apply(_f1,arguments);};};imgmap.prototype.trim=function(str){return str.replace(/^\s+|\s+$/g,"");};function imgmap_spawnObjects(_f4){var _f5=document.getElementsByTagName("map");var _f6=document.getElementsByTagName("img");var _f7=[];var _f8;for(var i=0,le=_f5.length;i<le;i++){for(var j=0,le2=_f6.length;j<le2;j++){if("#"+_f5[i].name==_f6[j].getAttribute("usemap")){_f4.mode="highlighter_spawn";_f8=new imgmap(_f4);_f8.useImage(_f6[j]);_f8.setMapHTML(_f5[i]);_f8.viewmode=1;_f7.push(_f8);}}}}
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/zopyx/authoring/skins/zopyx_linktool/linktool/jscripts/imgmap_packed.js
imgmap_packed.js
document.createElement("canvas").getContext||(function(){var s=Math,j=s.round,F=s.sin,G=s.cos,V=s.abs,W=s.sqrt,k=10,v=k/2;function X(){return this.context_||(this.context_=new H(this))}var L=Array.prototype.slice;function Y(b,a){var c=L.call(arguments,2);return function(){return b.apply(a,c.concat(L.call(arguments)))}}var M={init:function(b){if(/MSIE/.test(navigator.userAgent)&&!window.opera){var a=b||document;a.createElement("canvas");a.attachEvent("onreadystatechange",Y(this.init_,this,a))}},init_:function(b){b.namespaces.g_vml_|| b.namespaces.add("g_vml_","urn:schemas-microsoft-com:vml","#default#VML");b.namespaces.g_o_||b.namespaces.add("g_o_","urn:schemas-microsoft-com:office:office","#default#VML");if(!b.styleSheets.ex_canvas_){var a=b.createStyleSheet();a.owningElement.id="ex_canvas_";a.cssText="canvas{display:inline-block;overflow:hidden;text-align:left;width:300px;height:150px}g_vml_\\:*{behavior:url(#default#VML)}g_o_\\:*{behavior:url(#default#VML)}"}var c=b.getElementsByTagName("canvas"),d=0;for(;d<c.length;d++)this.initElement(c[d])}, initElement:function(b){if(!b.getContext){b.getContext=X;b.innerHTML="";b.attachEvent("onpropertychange",Z);b.attachEvent("onresize",$);var a=b.attributes;if(a.width&&a.width.specified)b.style.width=a.width.nodeValue+"px";else b.width=b.clientWidth;if(a.height&&a.height.specified)b.style.height=a.height.nodeValue+"px";else b.height=b.clientHeight}return b}};function Z(b){var a=b.srcElement;switch(b.propertyName){case "width":a.style.width=a.attributes.width.nodeValue+"px";a.getContext().clearRect(); break;case "height":a.style.height=a.attributes.height.nodeValue+"px";a.getContext().clearRect();break}}function $(b){var a=b.srcElement;if(a.firstChild){a.firstChild.style.width=a.clientWidth+"px";a.firstChild.style.height=a.clientHeight+"px"}}M.init();var N=[],B=0;for(;B<16;B++){var C=0;for(;C<16;C++)N[B*16+C]=B.toString(16)+C.toString(16)}function I(){return[[1,0,0],[0,1,0],[0,0,1]]}function y(b,a){var c=I(),d=0;for(;d<3;d++){var f=0;for(;f<3;f++){var h=0,g=0;for(;g<3;g++)h+=b[d][g]*a[g][f];c[d][f]= h}}return c}function O(b,a){a.fillStyle=b.fillStyle;a.lineCap=b.lineCap;a.lineJoin=b.lineJoin;a.lineWidth=b.lineWidth;a.miterLimit=b.miterLimit;a.shadowBlur=b.shadowBlur;a.shadowColor=b.shadowColor;a.shadowOffsetX=b.shadowOffsetX;a.shadowOffsetY=b.shadowOffsetY;a.strokeStyle=b.strokeStyle;a.globalAlpha=b.globalAlpha;a.arcScaleX_=b.arcScaleX_;a.arcScaleY_=b.arcScaleY_;a.lineScale_=b.lineScale_}function P(b){var a,c=1;b=String(b);if(b.substring(0,3)=="rgb"){var d=b.indexOf("(",3),f=b.indexOf(")",d+ 1),h=b.substring(d+1,f).split(",");a="#";var g=0;for(;g<3;g++)a+=N[Number(h[g])];if(h.length==4&&b.substr(3,1)=="a")c=h[3]}else a=b;return{color:a,alpha:c}}function aa(b){switch(b){case "butt":return"flat";case "round":return"round";case "square":default:return"square"}}function H(b){this.m_=I();this.mStack_=[];this.aStack_=[];this.currentPath_=[];this.fillStyle=this.strokeStyle="#000";this.lineWidth=1;this.lineJoin="miter";this.lineCap="butt";this.miterLimit=k*1;this.globalAlpha=1;this.canvas=b; var a=b.ownerDocument.createElement("div");a.style.width=b.clientWidth+"px";a.style.height=b.clientHeight+"px";a.style.overflow="hidden";a.style.position="absolute";b.appendChild(a);this.element_=a;this.lineScale_=this.arcScaleY_=this.arcScaleX_=1}var i=H.prototype;i.clearRect=function(){this.element_.innerHTML=""};i.beginPath=function(){this.currentPath_=[]};i.moveTo=function(b,a){var c=this.getCoords_(b,a);this.currentPath_.push({type:"moveTo",x:c.x,y:c.y});this.currentX_=c.x;this.currentY_=c.y}; i.lineTo=function(b,a){var c=this.getCoords_(b,a);this.currentPath_.push({type:"lineTo",x:c.x,y:c.y});this.currentX_=c.x;this.currentY_=c.y};i.bezierCurveTo=function(b,a,c,d,f,h){var g=this.getCoords_(f,h),l=this.getCoords_(b,a),e=this.getCoords_(c,d);Q(this,l,e,g)};function Q(b,a,c,d){b.currentPath_.push({type:"bezierCurveTo",cp1x:a.x,cp1y:a.y,cp2x:c.x,cp2y:c.y,x:d.x,y:d.y});b.currentX_=d.x;b.currentY_=d.y}i.quadraticCurveTo=function(b,a,c,d){var f=this.getCoords_(b,a),h=this.getCoords_(c,d),g={x:this.currentX_+ 0.6666666666666666*(f.x-this.currentX_),y:this.currentY_+0.6666666666666666*(f.y-this.currentY_)};Q(this,g,{x:g.x+(h.x-this.currentX_)/3,y:g.y+(h.y-this.currentY_)/3},h)};i.arc=function(b,a,c,d,f,h){c*=k;var g=h?"at":"wa",l=b+G(d)*c-v,e=a+F(d)*c-v,m=b+G(f)*c-v,r=a+F(f)*c-v;if(l==m&&!h)l+=0.125;var n=this.getCoords_(b,a),o=this.getCoords_(l,e),q=this.getCoords_(m,r);this.currentPath_.push({type:g,x:n.x,y:n.y,radius:c,xStart:o.x,yStart:o.y,xEnd:q.x,yEnd:q.y})};i.rect=function(b,a,c,d){this.moveTo(b, a);this.lineTo(b+c,a);this.lineTo(b+c,a+d);this.lineTo(b,a+d);this.closePath()};i.strokeRect=function(b,a,c,d){var f=this.currentPath_;this.beginPath();this.moveTo(b,a);this.lineTo(b+c,a);this.lineTo(b+c,a+d);this.lineTo(b,a+d);this.closePath();this.stroke();this.currentPath_=f};i.fillRect=function(b,a,c,d){var f=this.currentPath_;this.beginPath();this.moveTo(b,a);this.lineTo(b+c,a);this.lineTo(b+c,a+d);this.lineTo(b,a+d);this.closePath();this.fill();this.currentPath_=f};i.createLinearGradient=function(b, a,c,d){var f=new D("gradient");f.x0_=b;f.y0_=a;f.x1_=c;f.y1_=d;return f};i.createRadialGradient=function(b,a,c,d,f,h){var g=new D("gradientradial");g.x0_=b;g.y0_=a;g.r0_=c;g.x1_=d;g.y1_=f;g.r1_=h;return g};i.drawImage=function(b){var a,c,d,f,h,g,l,e,m=b.runtimeStyle.width,r=b.runtimeStyle.height;b.runtimeStyle.width="auto";b.runtimeStyle.height="auto";var n=b.width,o=b.height;b.runtimeStyle.width=m;b.runtimeStyle.height=r;if(arguments.length==3){a=arguments[1];c=arguments[2];h=g=0;l=d=n;e=f=o}else if(arguments.length== 5){a=arguments[1];c=arguments[2];d=arguments[3];f=arguments[4];h=g=0;l=n;e=o}else if(arguments.length==9){h=arguments[1];g=arguments[2];l=arguments[3];e=arguments[4];a=arguments[5];c=arguments[6];d=arguments[7];f=arguments[8]}else throw Error("Invalid number of arguments");var q=this.getCoords_(a,c),t=[];t.push(" <g_vml_:group",' coordsize="',k*10,",",k*10,'"',' coordorigin="0,0"',' style="width:',10,"px;height:",10,"px;position:absolute;");if(this.m_[0][0]!=1||this.m_[0][1]){var E=[];E.push("M11=", this.m_[0][0],",","M12=",this.m_[1][0],",","M21=",this.m_[0][1],",","M22=",this.m_[1][1],",","Dx=",j(q.x/k),",","Dy=",j(q.y/k),"");var p=q,z=this.getCoords_(a+d,c),w=this.getCoords_(a,c+f),x=this.getCoords_(a+d,c+f);p.x=s.max(p.x,z.x,w.x,x.x);p.y=s.max(p.y,z.y,w.y,x.y);t.push("padding:0 ",j(p.x/k),"px ",j(p.y/k),"px 0;filter:progid:DXImageTransform.Microsoft.Matrix(",E.join(""),", sizingmethod='clip');")}else t.push("top:",j(q.y/k),"px;left:",j(q.x/k),"px;");t.push(' ">','<g_vml_:image src="',b.src, '"',' style="width:',k*d,"px;"," height:",k*f,'px;"',' cropleft="',h/n,'"',' croptop="',g/o,'"',' cropright="',(n-h-l)/n,'"',' cropbottom="',(o-g-e)/o,'"'," />","</g_vml_:group>");this.element_.insertAdjacentHTML("BeforeEnd",t.join(""))};i.stroke=function(b){var a=[],c=P(b?this.fillStyle:this.strokeStyle),d=c.color,f=c.alpha*this.globalAlpha;a.push("<g_vml_:shape",' filled="',!!b,'"',' style="position:absolute;width:',10,"px;height:",10,'px;"',' coordorigin="0 0" coordsize="',k*10," ",k*10,'"',' stroked="', !b,'"',' path="');var h={x:null,y:null},g={x:null,y:null},l=0;for(;l<this.currentPath_.length;l++){var e=this.currentPath_[l];switch(e.type){case "moveTo":a.push(" m ",j(e.x),",",j(e.y));break;case "lineTo":a.push(" l ",j(e.x),",",j(e.y));break;case "close":a.push(" x ");e=null;break;case "bezierCurveTo":a.push(" c ",j(e.cp1x),",",j(e.cp1y),",",j(e.cp2x),",",j(e.cp2y),",",j(e.x),",",j(e.y));break;case "at":case "wa":a.push(" ",e.type," ",j(e.x-this.arcScaleX_*e.radius),",",j(e.y-this.arcScaleY_*e.radius), " ",j(e.x+this.arcScaleX_*e.radius),",",j(e.y+this.arcScaleY_*e.radius)," ",j(e.xStart),",",j(e.yStart)," ",j(e.xEnd),",",j(e.yEnd));break}if(e){if(h.x==null||e.x<h.x)h.x=e.x;if(g.x==null||e.x>g.x)g.x=e.x;if(h.y==null||e.y<h.y)h.y=e.y;if(g.y==null||e.y>g.y)g.y=e.y}}a.push(' ">');if(b)if(typeof this.fillStyle=="object"){var m=this.fillStyle,r=0,n={x:0,y:0},o=0,q=1;if(m.type_=="gradient"){var t=m.x1_/this.arcScaleX_,E=m.y1_/this.arcScaleY_,p=this.getCoords_(m.x0_/this.arcScaleX_,m.y0_/this.arcScaleY_), z=this.getCoords_(t,E);r=Math.atan2(z.x-p.x,z.y-p.y)*180/Math.PI;if(r<0)r+=360;if(r<1.0E-6)r=0}else{var p=this.getCoords_(m.x0_,m.y0_),w=g.x-h.x,x=g.y-h.y;n={x:(p.x-h.x)/w,y:(p.y-h.y)/x};w/=this.arcScaleX_*k;x/=this.arcScaleY_*k;var R=s.max(w,x);o=2*m.r0_/R;q=2*m.r1_/R-o}var u=m.colors_;u.sort(function(ba,ca){return ba.offset-ca.offset});var J=u.length,da=u[0].color,ea=u[J-1].color,fa=u[0].alpha*this.globalAlpha,ga=u[J-1].alpha*this.globalAlpha,S=[],l=0;for(;l<J;l++){var T=u[l];S.push(T.offset*q+ o+" "+T.color)}a.push('<g_vml_:fill type="',m.type_,'"',' method="none" focus="100%"',' color="',da,'"',' color2="',ea,'"',' colors="',S.join(","),'"',' opacity="',ga,'"',' g_o_:opacity2="',fa,'"',' angle="',r,'"',' focusposition="',n.x,",",n.y,'" />')}else a.push('<g_vml_:fill color="',d,'" opacity="',f,'" />');else{var K=this.lineScale_*this.lineWidth;if(K<1)f*=K;a.push("<g_vml_:stroke",' opacity="',f,'"',' joinstyle="',this.lineJoin,'"',' miterlimit="',this.miterLimit,'"',' endcap="',aa(this.lineCap), '"',' weight="',K,'px"',' color="',d,'" />')}a.push("</g_vml_:shape>");this.element_.insertAdjacentHTML("beforeEnd",a.join(""))};i.fill=function(){this.stroke(true)};i.closePath=function(){this.currentPath_.push({type:"close"})};i.getCoords_=function(b,a){var c=this.m_;return{x:k*(b*c[0][0]+a*c[1][0]+c[2][0])-v,y:k*(b*c[0][1]+a*c[1][1]+c[2][1])-v}};i.save=function(){var b={};O(this,b);this.aStack_.push(b);this.mStack_.push(this.m_);this.m_=y(I(),this.m_)};i.restore=function(){O(this.aStack_.pop(), this);this.m_=this.mStack_.pop()};function ha(b){var a=0;for(;a<3;a++){var c=0;for(;c<2;c++)if(!isFinite(b[a][c])||isNaN(b[a][c]))return false}return true}function A(b,a,c){if(!!ha(a)){b.m_=a;if(c)b.lineScale_=W(V(a[0][0]*a[1][1]-a[0][1]*a[1][0]))}}i.translate=function(b,a){A(this,y([[1,0,0],[0,1,0],[b,a,1]],this.m_),false)};i.rotate=function(b){var a=G(b),c=F(b);A(this,y([[a,c,0],[-c,a,0],[0,0,1]],this.m_),false)};i.scale=function(b,a){this.arcScaleX_*=b;this.arcScaleY_*=a;A(this,y([[b,0,0],[0,a, 0],[0,0,1]],this.m_),true)};i.transform=function(b,a,c,d,f,h){A(this,y([[b,a,0],[c,d,0],[f,h,1]],this.m_),true)};i.setTransform=function(b,a,c,d,f,h){A(this,[[b,a,0],[c,d,0],[f,h,1]],true)};i.clip=function(){};i.arcTo=function(){};i.createPattern=function(){return new U};function D(b){this.type_=b;this.r1_=this.y1_=this.x1_=this.r0_=this.y0_=this.x0_=0;this.colors_=[]}D.prototype.addColorStop=function(b,a){a=P(a);this.colors_.push({offset:b,color:a.color,alpha:a.alpha})};function U(){}G_vmlCanvasManager= M;CanvasRenderingContext2D=H;CanvasGradient=D;CanvasPattern=U})();
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/zopyx/authoring/skins/zopyx_linktool/linktool/jscripts/excanvas.js
excanvas.js
var undef; var slideCSS = ''; var snum = 0; var smax = 1; var incpos = 0; var number = undef; var s5mode = true; var defaultView = 'slideshow'; var controlVis = 'visible'; var isIE = navigator.appName == 'Microsoft Internet Explorer' && navigator.userAgent.indexOf('Opera') < 1 ? 1 : 0; var isOp = navigator.userAgent.indexOf('Opera') > -1 ? 1 : 0; var isGe = navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('Safari') < 1 ? 1 : 0; function hasClass(object, className) { if (!object.className) return false; return (object.className.search('(^|\\s)' + className + '(\\s|$)') != -1); } function hasValue(object, value) { if (!object) return false; return (object.search('(^|\\s)' + value + '(\\s|$)') != -1); } function removeClass(object,className) { if (!object) return; object.className = object.className.replace(new RegExp('(^|\\s)'+className+'(\\s|$)'), RegExp.$1+RegExp.$2); } function addClass(object,className) { if (!object || hasClass(object, className)) return; if (object.className) { object.className += ' '+className; } else { object.className = className; } } function GetElementsWithClassName(elementName,className) { var allElements = document.getElementsByTagName(elementName); var elemColl = new Array(); for (var i = 0; i< allElements.length; i++) { if (hasClass(allElements[i], className)) { elemColl[elemColl.length] = allElements[i]; } } return elemColl; } function isParentOrSelf(element, id) { if (element == null || element.nodeName=='BODY') return false; else if (element.id == id) return true; else return isParentOrSelf(element.parentNode, id); } function nodeValue(node) { var result = ""; if (node.nodeType == 1) { var children = node.childNodes; for (var i = 0; i < children.length; ++i) { result += nodeValue(children[i]); } } else if (node.nodeType == 3) { result = node.nodeValue; } return(result); } function slideLabel() { var slideColl = GetElementsWithClassName('*','slide'); var list = document.getElementById('jumplist'); smax = slideColl.length; for (var n = 0; n < smax; n++) { var obj = slideColl[n]; var did = 'slide' + n.toString(); obj.setAttribute('id',did); if (isOp) continue; var otext = ''; var menu = obj.firstChild; if (!menu) continue; // to cope with empty slides while (menu && menu.nodeType == 3) { menu = menu.nextSibling; } if (!menu) continue; // to cope with slides with only text nodes var menunodes = menu.childNodes; for (var o = 0; o < menunodes.length; o++) { otext += nodeValue(menunodes[o]); } var nodes = obj.getElementsByTagName('h1'); if (nodes.length > 0) { otext = nodes[0].innerHTML; list.options[list.length] = new Option(n + ' : ' + otext, n); } } } function currentSlide() { var cs; if (document.getElementById) { cs = document.getElementById('currentSlide'); } else { cs = document.currentSlide; } cs.innerHTML = '<span id="csHere">' + snum + '<\/span> ' + '<span id="csSep">\/<\/span> ' + '<span id="csTotal">' + (smax-1) + '<\/span>'; if (snum == 0) { cs.style.visibility = 'hidden'; } else { cs.style.visibility = 'visible'; } } function go(step) { if (document.getElementById('slideProj').disabled || step == 0) return; var jl = document.getElementById('jumplist'); var cid = 'slide' + snum; var ce = document.getElementById(cid); if (incrementals[snum].length > 0) { for (var i = 0; i < incrementals[snum].length; i++) { removeClass(incrementals[snum][i], 'current'); removeClass(incrementals[snum][i], 'incremental'); } } if (step != 'j') { snum += step; lmax = smax - 1; if (snum > lmax) snum = lmax; if (snum < 0) snum = 0; } else snum = parseInt(jl.value); var nid = 'slide' + snum; var ne = document.getElementById(nid); if (!ne) { ne = document.getElementById('slide0'); snum = 0; } if (step < 0) {incpos = incrementals[snum].length} else {incpos = 0;} if (incrementals[snum].length > 0 && incpos == 0) { for (var i = 0; i < incrementals[snum].length; i++) { if (hasClass(incrementals[snum][i], 'current')) incpos = i + 1; else addClass(incrementals[snum][i], 'incremental'); } } if (incrementals[snum].length > 0 && incpos > 0) addClass(incrementals[snum][incpos - 1], 'current'); ce.style.visibility = 'hidden'; ne.style.visibility = 'visible'; jl.selectedIndex = snum; currentSlide(); number = 0; } function goTo(target) { if (target >= smax || target == snum) return; go(target - snum); } function subgo(step) { if (step > 0) { removeClass(incrementals[snum][incpos - 1],'current'); removeClass(incrementals[snum][incpos], 'incremental'); addClass(incrementals[snum][incpos],'current'); incpos++; } else { incpos--; removeClass(incrementals[snum][incpos],'current'); addClass(incrementals[snum][incpos], 'incremental'); addClass(incrementals[snum][incpos - 1],'current'); } } function toggle() { var slideColl = GetElementsWithClassName('*','slide'); var slides = document.getElementById('slideProj'); var outline = document.getElementById('outlineStyle'); if (!slides.disabled) { slides.disabled = true; outline.disabled = false; s5mode = false; fontSize('1em'); for (var n = 0; n < smax; n++) { var slide = slideColl[n]; slide.style.visibility = 'visible'; } } else { slides.disabled = false; outline.disabled = true; s5mode = true; fontScale(); for (var n = 0; n < smax; n++) { var slide = slideColl[n]; slide.style.visibility = 'hidden'; } slideColl[snum].style.visibility = 'visible'; } } function showHide(action) { var obj = GetElementsWithClassName('*','hideme')[0]; switch (action) { case 's': obj.style.visibility = 'visible'; break; case 'h': obj.style.visibility = 'hidden'; break; case 'k': if (obj.style.visibility != 'visible') { obj.style.visibility = 'visible'; } else { obj.style.visibility = 'hidden'; } break; } } // 'keys' code adapted from MozPoint (http://mozpoint.mozdev.org/) function keys(key) { if (!key) { key = event; key.which = key.keyCode; } if (key.which == 84) { toggle(); return; } if (s5mode) { switch (key.which) { case 10: // return case 13: // enter if (window.event && isParentOrSelf(window.event.srcElement, 'controls')) return; if (key.target && isParentOrSelf(key.target, 'controls')) return; if(number != undef) { goTo(number); break; } case 32: // spacebar case 34: // page down case 39: // rightkey case 40: // downkey if(number != undef) { go(number); } else if (!incrementals[snum] || incpos >= incrementals[snum].length) { go(1); } else { subgo(1); } break; case 33: // page up case 37: // leftkey case 38: // upkey if(number != undef) { go(-1 * number); } else if (!incrementals[snum] || incpos <= 0) { go(-1); } else { subgo(-1); } break; case 36: // home goTo(0); break; case 35: // end goTo(smax-1); break; case 67: // c showHide('k'); break; } if (key.which < 48 || key.which > 57) { number = undef; } else { if (window.event && isParentOrSelf(window.event.srcElement, 'controls')) return; if (key.target && isParentOrSelf(key.target, 'controls')) return; number = (((number != undef) ? number : 0) * 10) + (key.which - 48); } } return false; } function clicker(e) { number = undef; var target; if (window.event) { target = window.event.srcElement; e = window.event; } else target = e.target; if (target.getAttribute('href') != null || hasValue(target.rel, 'external') || isParentOrSelf(target, 'controls') || isParentOrSelf(target,'embed') || isParentOrSelf(target,'object')) return true; if (!e.which || e.which == 1) { if (!incrementals[snum] || incpos >= incrementals[snum].length) { go(1); } else { subgo(1); } } } function findSlide(hash) { var target = null; var slides = GetElementsWithClassName('*','slide'); for (var i = 0; i < slides.length; i++) { var targetSlide = slides[i]; if ( (targetSlide.name && targetSlide.name == hash) || (targetSlide.id && targetSlide.id == hash) ) { target = targetSlide; break; } } while(target != null && target.nodeName != 'BODY') { if (hasClass(target, 'slide')) { return parseInt(target.id.slice(5)); } target = target.parentNode; } return null; } function slideJump() { if (window.location.hash == null) return; var sregex = /^#slide(\d+)$/; var matches = sregex.exec(window.location.hash); var dest = null; if (matches != null) { dest = parseInt(matches[1]); } else { dest = findSlide(window.location.hash.slice(1)); } if (dest != null) go(dest - snum); } function fixLinks() { var thisUri = window.location.href; thisUri = thisUri.slice(0, thisUri.length - window.location.hash.length); var aelements = document.getElementsByTagName('A'); for (var i = 0; i < aelements.length; i++) { var a = aelements[i].href; var slideID = a.match('\#slide[0-9]{1,2}'); if ((slideID) && (slideID[0].slice(0,1) == '#')) { var dest = findSlide(slideID[0].slice(1)); if (dest != null) { if (aelements[i].addEventListener) { aelements[i].addEventListener("click", new Function("e", "if (document.getElementById('slideProj').disabled) return;" + "go("+dest+" - snum); " + "if (e.preventDefault) e.preventDefault();"), true); } else if (aelements[i].attachEvent) { aelements[i].attachEvent("onclick", new Function("", "if (document.getElementById('slideProj').disabled) return;" + "go("+dest+" - snum); " + "event.returnValue = false;")); } } } } } function externalLinks() { if (!document.getElementsByTagName) return; var anchors = document.getElementsByTagName('a'); for (var i=0; i<anchors.length; i++) { var anchor = anchors[i]; if (anchor.getAttribute('href') && hasValue(anchor.rel, 'external')) { anchor.target = '_blank'; addClass(anchor,'external'); } } } function createControls() { var controlsDiv = document.getElementById("controls"); if (!controlsDiv) return; var hider = ' onmouseover="showHide(\'s\');" onmouseout="showHide(\'h\');"'; var hideDiv, hideList = ''; if (controlVis == 'hidden') { hideDiv = hider; } else { hideList = hider; } controlsDiv.innerHTML = '<form action="#" id="controlForm"' + hideDiv + '>' + '<div id="navLinks">' + '<a accesskey="t" id="toggle" href="javascript:toggle();">&#216;<\/a>' + '<a accesskey="z" id="prev" href="javascript:go(-1);">&laquo;<\/a>' + '<a accesskey="x" id="next" href="javascript:go(1);">&raquo;<\/a>' + '<div id="navList"' + hideList + '><select id="jumplist" onchange="go(\'j\');"><\/select><\/div>' + '<\/div><\/form>'; if (controlVis == 'hidden') { var hidden = document.getElementById('navLinks'); } else { var hidden = document.getElementById('jumplist'); } addClass(hidden,'hideme'); } function fontScale() { // causes layout problems in FireFox that get fixed if browser's Reload is used; same may be true of other Gecko-based browsers if (!s5mode) return false; var vScale = 22; // both yield 32 (after rounding) at 1024x768 var hScale = 32; // perhaps should auto-calculate based on theme's declared value? if (window.innerHeight) { var vSize = window.innerHeight; var hSize = window.innerWidth; } else if (document.documentElement.clientHeight) { var vSize = document.documentElement.clientHeight; var hSize = document.documentElement.clientWidth; } else if (document.body.clientHeight) { var vSize = document.body.clientHeight; var hSize = document.body.clientWidth; } else { var vSize = 700; // assuming 1024x768, minus chrome and such var hSize = 1024; // these do not account for kiosk mode or Opera Show } var newSize = Math.min(Math.round(vSize/vScale),Math.round(hSize/hScale)); fontSize(newSize + 'px'); if (isGe) { // hack to counter incremental reflow bugs var obj = document.getElementsByTagName('body')[0]; obj.style.display = 'none'; obj.style.display = 'block'; } } function fontSize(value) { if (!(s5ss = document.getElementById('s5ss'))) { if (!isIE) { document.getElementsByTagName('head')[0].appendChild(s5ss = document.createElement('style')); s5ss.setAttribute('media','screen, projection'); s5ss.setAttribute('id','s5ss'); } else { document.createStyleSheet(); document.s5ss = document.styleSheets[document.styleSheets.length - 1]; } } if (!isIE) { while (s5ss.lastChild) s5ss.removeChild(s5ss.lastChild); s5ss.appendChild(document.createTextNode('body {font-size: ' + value + ' !important;}')); } else { document.s5ss.addRule('body','font-size: ' + value + ' !important;'); } } function notOperaFix() { slideCSS = document.getElementById('slideProj').href; var slides = document.getElementById('slideProj'); var outline = document.getElementById('outlineStyle'); slides.setAttribute('media','screen'); outline.disabled = true; if (isGe) { slides.setAttribute('href','null'); // Gecko fix slides.setAttribute('href',slideCSS); // Gecko fix } if (isIE && document.styleSheets && document.styleSheets[0]) { document.styleSheets[0].addRule('img', 'behavior: url(ui/default/iepngfix.htc)'); document.styleSheets[0].addRule('div', 'behavior: url(ui/default/iepngfix.htc)'); document.styleSheets[0].addRule('.slide', 'behavior: url(ui/default/iepngfix.htc)'); } } function getIncrementals(obj) { var incrementals = new Array(); if (!obj) return incrementals; var children = obj.childNodes; for (var i = 0; i < children.length; i++) { var child = children[i]; if (hasClass(child, 'incremental')) { if (child.nodeName == 'OL' || child.nodeName == 'UL') { removeClass(child, 'incremental'); for (var j = 0; j < child.childNodes.length; j++) { if (child.childNodes[j].nodeType == 1) { addClass(child.childNodes[j], 'incremental'); } } } else { incrementals[incrementals.length] = child; removeClass(child,'incremental'); } } if (hasClass(child, 'show-first')) { if (child.nodeName == 'OL' || child.nodeName == 'UL') { removeClass(child, 'show-first'); if (child.childNodes[isGe].nodeType == 1) { removeClass(child.childNodes[isGe], 'incremental'); } } else { incrementals[incrementals.length] = child; } } incrementals = incrementals.concat(getIncrementals(child)); } return incrementals; } function createIncrementals() { var incrementals = new Array(); for (var i = 0; i < smax; i++) { incrementals[i] = getIncrementals(document.getElementById('slide'+i)); } return incrementals; } function defaultCheck() { var allMetas = document.getElementsByTagName('meta'); for (var i = 0; i< allMetas.length; i++) { if (allMetas[i].name == 'defaultView') { defaultView = allMetas[i].content; } if (allMetas[i].name == 'controlVis') { controlVis = allMetas[i].content; } } } // Key trap fix, new function body for trap() function trap(e) { if (!e) { e = event; e.which = e.keyCode; } try { modifierKey = e.ctrlKey || e.altKey || e.metaKey; } catch(e) { modifierKey = false; } return modifierKey || e.which == 0; } function startup() { defaultCheck(); if (!isOp) createControls(); slideLabel(); fixLinks(); externalLinks(); fontScale(); if (!isOp) { notOperaFix(); incrementals = createIncrementals(); slideJump(); if (defaultView == 'outline') { toggle(); } document.onkeyup = keys; document.onkeypress = trap; document.onclick = clicker; } } window.onload = startup; window.onresize = function(){setTimeout('fontScale()', 50);}
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/zopyx/authoring/skins/zopyx_authoring/pp-s5-slides.js
pp-s5-slides.js
import lxml.html from zope.interface import Interface from zope.interface import implements from plone.app.portlets.portlets import base from plone.portlets.interfaces import IPortletDataProvider from plone.memoize import instance from zope import schema from zope.formlib import form from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile from Acquisition import aq_inner, aq_parent from zopyx.authoring import authoringMessageFactory as _ from zopyx.smartprintng.plone import xpath_query from zope.i18nmessageid import MessageFactory __ = MessageFactory("plone") class IPublishedContentPortlet(IPortletDataProvider): """A portlet It inherits from IPortletDataProvider because for this portlet, the data that is being rendered and the portlet assignment itself are the same. """ # some_field = schema.TextLine(title=_(u"Some field"), # description=_(u"A field to use"), # required=True) class Assignment(base.Assignment): """Portlet assignment. This is what is actually managed through the portlets UI and associated with columns. """ implements(IPublishedContentPortlet) # TODO: Set default values for the configurable parameters here # some_field = u"" # TODO: Add keyword parameters for configurable parameters here # def __init__(self, some_field=u''): # self.some_field = some_field def __init__(self): pass @property def title(self): """This property is used to give the title of the portlet in the "manage portlets" screen. """ return __(u"PublishedContentPortlet") class Renderer(base.Renderer): """Portlet renderer. This is registered in configure.zcml. The referenced page template is rendered, and the implicit variable 'view' will refer to an instance of this class. Other methods can be added and referenced in the template. """ render = ViewPageTemplateFile('publishedcontentportlet.pt') @instance.memoize def getPdfFiles(self): return [b for b in aq_parent(aq_inner(self.context)).getFolderContents() if b.getId.endswith('.pdf')] @instance.memoize def haveEPUB(self): parent = aq_parent(aq_inner(self.context)) return [b for b in parent.getFolderContents() if b.getId == 'index.epub'] @instance.memoize def haveS5(self): parent = aq_parent(aq_inner(self.context)) return 'index_s5.html' in parent.objectIds() def folderURL(self): """ Return URL of parent folder """ parent = aq_parent(aq_inner(self.context)) return parent.absolute_url() def getObjSize(self, id): parent = aq_parent(aq_inner(self.context)) return parent[id].getObjSize() @instance.memoize def getTableOfContents(self): actual_url = self.request.ACTUAL_URL parent = aq_parent(aq_inner(self.context)) result = list() brains = parent.getFolderContents({'portal_type' : 'AuthoringPublishedDocument', 'sort_on' : 'getObjPositionInParent'}) if len(brains) == 1: h_tags = ('h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8') else: h_tags = ('h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8') for brain in brains: obj = brain.getObject() links = list() if obj.getId() == self.context.getId(): html = unicode(obj.getText(), 'utf-8') root = lxml.html.fromstring(html) for i, tag in enumerate(root.xpath(xpath_query(h_tags))): text = tag.text_content() level = int(tag.tag[-1]) id = tag.get('id') links.append(dict(level=level, href='%s#%s' % (actual_url, id), index=i, text=text)) css_classes = obj.getId()==self.context.getId() and 'toc-table toc-table-active' or 'toc-table' result.append(dict(id=obj.getId(), title=obj.Title(), url=obj.absolute_url(), css_classes=css_classes, links=links)) return result class AddForm(base.AddForm): """Portlet add form. This is registered in configure.zcml. The form_fields variable tells zope.formlib which fields to display. The create() method actually constructs the assignment that is being added. """ form_fields = form.Fields(IPublishedContentPortlet) def create(self, data): return Assignment(**data) # NOTE: IF this portlet does not have any configurable parameters, you can # remove this class definition and delete the editview attribute from the # <plone:portlet /> registration in configure.zcml class EditForm(base.EditForm): """Portlet edit form. This is registered with configure.zcml. The form_fields variable tells zope.formlib which fields to display. """ form_fields = form.Fields(IPublishedContentPortlet)
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/zopyx/authoring/portlets/publishedcontentportlet.py
publishedcontentportlet.py
from zope.interface import Interface from zope.interface import implements from plone.app.portlets.portlets import base from plone.portlets.interfaces import IPortletDataProvider from zope import schema from zope.formlib import form from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile from Products.CMFCore.utils import getToolByName from AccessControl import getSecurityManager from zopyx.authoring import authoringMessageFactory as _ class IMyAuthoringProjects(IPortletDataProvider): """A portlet It inherits from IPortletDataProvider because for this portlet, the data that is being rendered and the portlet assignment itself are the same. """ # TODO: Add any zope.schema fields here to capture portlet configuration # information. Alternatively, if there are no settings, leave this as an # empty interface - see also notes around the add form and edit form # below. # some_field = schema.TextLine(title=_(u"Some field"), # description=_(u"A field to use"), # required=True) class Assignment(base.Assignment): """Portlet assignment. This is what is actually managed through the portlets UI and associated with columns. """ implements(IMyAuthoringProjects) # TODO: Set default values for the configurable parameters here # some_field = u"" # TODO: Add keyword parameters for configurable parameters here # def __init__(self, some_field=u''): # self.some_field = some_field def __init__(self): pass @property def title(self): """This property is used to give the title of the portlet in the "manage portlets" screen. """ return _(u"My Authoring Projects") class Renderer(base.Renderer): """Portlet renderer. This is registered in configure.zcml. The referenced page template is rendered, and the implicit variable 'view' will refer to an instance of this class. Other methods can be added and referenced in the template. """ render = ViewPageTemplateFile('myauthoringprojects.pt') def myProjects(self): me = getSecurityManager().getUser().getUserName() projects = list() catalog = getToolByName(self.context, 'portal_catalog') for brain in catalog(portal_type='AuthoringConversionFolder', Creator=me, sort_on='sortable_title'): projects.append(dict(url=brain.getURL, title=brain.Title)) return projects # NOTE: If this portlet does not have any configurable parameters, you can # inherit from NullAddForm and remove the form_fields variable. class AddForm(base.NullAddForm): """Portlet add form. This is registered in configure.zcml. The form_fields variable tells zope.formlib which fields to display. The create() method actually constructs the assignment that is being added. """ def create(self): return Assignment() # NOTE: IF this portlet does not have any configurable parameters, you can # remove this class definition and delete the editview attribute from the # <plone:portlet /> registration in configure.zcml class EditForm(base.EditForm): """Portlet edit form. This is registered with configure.zcml. The form_fields variable tells zope.formlib which fields to display. """ form_fields = form.Fields(IMyAuthoringProjects)
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/zopyx/authoring/portlets/myauthoringprojects.py
myauthoringprojects.py
from zope.interface import Interface from zope.interface import implements from plone.app.portlets.portlets import base from plone.portlets.interfaces import IPortletDataProvider from zope import schema from zope.formlib import form from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile from zopyx.authoring import authoringMessageFactory as _ class IAuthoringEnvironment(IPortletDataProvider): """A portlet It inherits from IPortletDataProvider because for this portlet, the data that is being rendered and the portlet assignment itself are the same. """ # TODO: Add any zope.schema fields here to capture portlet configuration # information. Alternatively, if there are no settings, leave this as an # empty interface - see also notes around the add form and edit form # below. conversion = schema.TextLine(title=_(u"Conversion"), description=_(u"Conversion to be triggered"), required=True) class Assignment(base.Assignment): """Portlet assignment. This is what is actually managed through the portlets UI and associated with columns. """ implements(IAuthoringEnvironment) # TODO: Set default values for the configurable parameters here conversion = u"" # TODO: Add keyword parameters for configurable parameters here def __init__(self, conversion=u''): self.conversion = conversion @property def title(self): """This property is used to give the title of the portlet in the "manage portlets" screen. """ return _(u"Authoring Environment") class Renderer(base.Renderer): """Portlet renderer. This is registered in configure.zcml. The referenced page template is rendered, and the implicit variable 'view' will refer to an instance of this class. Other methods can be added and referenced in the template. """ render = ViewPageTemplateFile('authoringenvironment.pt') def getConversion(self): return self.data.conversion # NOTE: If this portlet does not have any configurable parameters, you can # inherit from NullAddForm and remove the form_fields variable. class AddForm(base.AddForm): """Portlet add form. This is registered in configure.zcml. The form_fields variable tells zope.formlib which fields to display. The create() method actually constructs the assignment that is being added. """ form_fields = form.Fields(IAuthoringEnvironment) def create(self, data): return Assignment(**data) # NOTE: IF this portlet does not have any configurable parameters, you can # remove this class definition and delete the editview attribute from the # <plone:portlet /> registration in configure.zcml class EditForm(base.EditForm): """Portlet edit form. This is registered with configure.zcml. The form_fields variable tells zope.formlib which fields to display. """ form_fields = form.Fields(IAuthoringEnvironment)
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/zopyx/authoring/portlets/authoringenvironment.py
authoringenvironment.py
from zope.interface import implements, directlyProvides from Products.Archetypes import atapi from Products.ATContentTypes.content import folder from Products.ATContentTypes.content import schemata from zopyx.authoring import authoringMessageFactory as _ from zopyx.authoring.interfaces import IAuthoringTemplate from zopyx.authoring.config import PROJECTNAME from Products.CMFCore.ContentTypeRegistry import manage_addRegistry from zopyx.smartprintng.plone.resources import resources_registry AuthoringTemplateSchema = folder.ATFolderSchema.copy() + atapi.Schema(( # -*- Your Archetypes field definitions here ... -*- atapi.StringField('resourceOnFilesystem', vocabulary='getResourcesOnFilesystem', widget=atapi.SelectionWidget(label=_('label_resource_on_filesystem', default='Resources on filesystem'), format='select', ), ), )) # Set storage on fields copied from ATFolderSchema, making sure # they work well with the python bridge properties. AuthoringTemplateSchema['title'].storage = atapi.AnnotationStorage() AuthoringTemplateSchema['description'].storage = atapi.AnnotationStorage() schemata.finalizeATCTSchema( AuthoringTemplateSchema, folderish=True, moveDiscussion=False ) class predicate(object): """ Used for content type registry """ def __init__(self, id, extensions): self.extensions = extensions self.id = id class AuthoringTemplate(folder.ATFolder): """Authoring Template""" implements(IAuthoringTemplate) meta_type = "AuthoringTemplate" schema = AuthoringTemplateSchema title = atapi.ATFieldProperty('title') description = atapi.ATFieldProperty('description') # -*- Your ATSchema to Python Property Bridges Here ... -*- def at_post_create_script(self, ): # content-type registry manage_addRegistry(self) registry = self['content_type_registry'] registry.addPredicate('images', 'extension') registry.addPredicate('templates', 'extension') registry.addPredicate('stylesheet', 'extension') registry.addPredicate('files', 'extension') registry.doUpdatePredicate('images', predicate('images', 'jpg jpeg png gif JPG JPEG PNG GIF'), 'AuthoringImageResource', self.REQUEST) registry.doUpdatePredicate('stylesheet', predicate('stylesheet', 'css CSS styles STYLES'), 'AuthoringStylesheet', self.REQUEST) registry.doUpdatePredicate('templates', predicate('templates', 'pt PT template TEMPLATE'), 'AuthoringMasterTemplate', self.REQUEST) registry.doUpdatePredicate('files', predicate('files', 'ttf TTF otf OTF dic DIC'), 'AuthoringBinaryResource', self.REQUEST) def getResourcesOnFilesystem(self): result = atapi.DisplayList() result.add('', _(u'label_no_edit_resource_ttw', u'No, I edit my resources through the web')) for r in resources_registry.keys(): result.add(r, _(u'Use resource') + ':' + r) return result atapi.registerType(AuthoringTemplate, PROJECTNAME)
zopyx.authoring
/zopyx.authoring-2.4.0.zip/zopyx.authoring-2.4.0/zopyx/authoring/content/authoringtemplate.py
authoringtemplate.py