repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
jayphelps/ember.js
tests/node/app-boot-test.js
8176
/*globals global,__dirname*/ var path = require('path'); var distPath = path.join(__dirname, '../../dist'); var emberPath = path.join(distPath, 'ember.debug.cjs'); var templateCompilerPath = path.join(distPath, 'ember-template-compiler'); var defeatureifyConfig = require(path.join(__dirname, '../../features.json')); var canUseInstanceInitializers = true; var canUseApplicationVisit; if (defeatureifyConfig.features['ember-application-visit'] !== false) { canUseApplicationVisit = true; } var features = {}; for (var feature in defeatureifyConfig.features) { features[feature] = defeatureifyConfig.features[feature]; } features['ember-application-visit'] =true; /*jshint -W079 */ global.EmberENV = { FEATURES: features }; var Ember, compile, domHelper, run, DOMHelper, app; var SimpleDOM = require('simple-dom'); var URL = require('url'); function createApplication() { var App = Ember.Application.extend().create({ autoboot: false }); App.Router = Ember.Router.extend({ location: 'none' }); return App; } function createDOMHelper() { var document = new SimpleDOM.Document(); var domHelper = new DOMHelper(document); domHelper.protocolForURL = function(url) { var protocol = URL.parse(url).protocol; return (protocol == null) ? ':' : protocol; }; domHelper.setMorphHTML = function(morph, html) { var section = this.document.createRawHTMLSection(html); morph.setNode(section); }; return domHelper; } function registerDOMHelper(app) { app.instanceInitializer({ name: 'register-dom-helper', initialize: function(app) { app.register('renderer:-dom', { create: function() { return new Ember._Renderer(domHelper, false); } }); } }); } function registerTemplates(app, templates) { app.instanceInitializer({ name: 'register-application-template', initialize: function(app) { for (var key in templates) { app.register('template:' + key, compile(templates[key])); } } }); } function registerControllers(app, controllers) { app.instanceInitializer({ name: 'register-application-controllers', initialize: function(app) { for (var key in controllers) { app.register('controller:' + key, controllers[key]); } } }); } function renderToElement(instance) { var element; run(function() { element = instance.view.renderToElement(); }); return element; } function assertHTMLMatches(assert, actualElement, expectedHTML) { var serializer = new SimpleDOM.HTMLSerializer(SimpleDOM.voidMap); var serialized = serializer.serialize(actualElement); assert.ok(serialized.match(expectedHTML), serialized + " matches " + expectedHTML); } QUnit.module("App boot", { setup: function() { Ember = require(emberPath); compile = require(templateCompilerPath).compile; Ember.testing = true; DOMHelper = Ember.HTMLBars.DOMHelper; domHelper = createDOMHelper(); run = Ember.run; }, teardown: function() { Ember.run(app, 'destroy'); delete global.Ember; // clear the previously cached version of this module delete require.cache[emberPath + '.js']; delete require.cache[templateCompilerPath + '.js']; } }); if (canUseInstanceInitializers && canUseApplicationVisit) { QUnit.test("App is created without throwing an exception", function(assert) { run(function() { app = createApplication(); registerDOMHelper(app); app.visit('/'); }); assert.ok(app); }); QUnit.test("It is possible to render a view in Node", function(assert) { var View = Ember.Component.extend({ renderer: new Ember._Renderer(new DOMHelper(new SimpleDOM.Document())), layout: compile("<h1>Hello</h1>") }); var view = View.create({ _domHelper: new DOMHelper(new SimpleDOM.Document()), }); run(view, view.createElement); var serializer = new SimpleDOM.HTMLSerializer(SimpleDOM.voidMap); assert.ok(serializer.serialize(view.element).match(/<h1>Hello<\/h1>/)); }); QUnit.test("It is possible to render a view with curlies in Node", function(assert) { var View = Ember.Component.extend({ renderer: new Ember._Renderer(new DOMHelper(new SimpleDOM.Document())), layout: compile("<h1>Hello {{location}}</h1>"), location: "World" }); var view = View.create({ _domHelper: new DOMHelper(new SimpleDOM.Document()) }); run(view, view.createElement); var serializer = new SimpleDOM.HTMLSerializer(SimpleDOM.voidMap); assert.ok(serializer.serialize(view.element).match(/<h1>Hello World<\/h1>/)); }); QUnit.test("It is possible to render a view with a nested {{component}} helper in Node", function(assert) { var registry = new Ember.Application.buildRegistry({ get: function(path) { return Ember.get(this, path); } }); registry.register('component-lookup:main', Ember.ComponentLookup); var container = registry.container(); var View = Ember.Component.extend({ container: container, renderer: new Ember._Renderer(new DOMHelper(new SimpleDOM.Document())), layout: compile("<h1>Hello {{#if hasExistence}}{{location}}{{/if}}</h1> <div>{{component 'foo-bar'}}</div>"), location: "World", hasExistence: true }); registry.register('component:foo-bar', Ember.Component.extend({ layout: compile("<p>The files are *inside* the computer?!</p>") })); var view = View.create(); run(view, function() { view.createElement(); }); var serializer = new SimpleDOM.HTMLSerializer(SimpleDOM.voidMap); assert.ok(serializer.serialize(view.element).match(/<h1>Hello World<\/h1> <div><div id="(.*)" class="ember-view"><p>The files are \*inside\* the computer\?\!<\/p><\/div><\/div>/)); }); QUnit.test("It is possible to render a view with {{link-to}} in Node", function(assert) { run(function() { app = createApplication(); app.Router.map(function() { this.route('photos'); }); registerDOMHelper(app); registerTemplates(app, { application: "<h1>{{#link-to 'photos'}}Go to photos{{/link-to}}</h1>" }); }); return app.visit('/').then(function(instance) { var element = renderToElement(instance); assertHTMLMatches(assert, element.firstChild, /^<div id="ember\d+" class="ember-view"><h1><a id="ember\d+" href="\/photos" class="ember-view">Go to photos<\/a><\/h1><\/div>$/); }); }); QUnit.test("It is possible to render non-escaped content", function(assert) { debugger; run(function() { app = createApplication(); app.Router.map(function() { this.route('photos'); }); registerDOMHelper(app); registerTemplates(app, { application: "<h1>{{{title}}}</h1>" }); registerControllers(app, { application: Ember.Controller.extend({ title: "<b>Hello world</b>" }) }); }); return app.visit('/').then(function(instance) { var element = renderToElement(instance); assertHTMLMatches(assert, element.firstChild, /^<div id="ember\d+" class="ember-view"><h1><b>Hello world<\/b><\/h1><\/div>$/); }); }); QUnit.test("It is possible to render outlets in Node", function(assert) { run(function() { app = createApplication(); app.Router.map(function() { this.route('photos'); }); registerDOMHelper(app); registerTemplates(app, { application: "<p>{{outlet}}</p>", index: "<span>index</span>", photos: "<em>photos</em>" }); }); var visits = []; visits.push(app.visit('/').then(function(instance) { var element = renderToElement(instance); assertHTMLMatches(assert, element.firstChild, /<div id="ember(.*)" class="ember-view"><p><span>index<\/span><\/p><\/div>/); })); visits.push(app.visit('/photos').then(function(instance) { var element = renderToElement(instance); assertHTMLMatches(assert, element.firstChild, /<div id="ember(.*)" class="ember-view"><p><em>photos<\/em><\/p><\/div>/); })); return Ember.RSVP.Promise.all(visits); }); }
mit
jueyang/almostatlas
js/reveal.js
129623
/*! * reveal.js * http://lab.hakim.se/reveal-js * MIT licensed * * Copyright (C) 2015 Hakim El Hattab, http://hakim.se */ (function( root, factory ) { if( typeof define === 'function' && define.amd ) { // AMD. Register as an anonymous module. define( function() { root.Reveal = factory(); return root.Reveal; } ); } else if( typeof exports === 'object' ) { // Node. Does not work with strict CommonJS. module.exports = factory(); } else { // Browser globals. root.Reveal = factory(); } }( this, function() { 'use strict'; var Reveal; var SLIDES_SELECTOR = '.slides section', HORIZONTAL_SLIDES_SELECTOR = '.slides>section', VERTICAL_SLIDES_SELECTOR = '.slides>section.present>section', HOME_SLIDE_SELECTOR = '.slides>section:first-of-type', // Configuration defaults, can be overridden at initialization time config = { // The "normal" size of the presentation, aspect ratio will be preserved // when the presentation is scaled to fit different resolutions width: 960, height: 700, // Factor of the display size that should remain empty around the content margin: 0.1, // Bounds for smallest/largest possible scale to apply to content minScale: 0.2, maxScale: 1.5, // Display controls in the bottom right corner controls: true, // Display a presentation progress bar progress: true, // Display the page number of the current slide slideNumber: false, // Push each slide change to the browser history history: false, // Enable keyboard shortcuts for navigation keyboard: true, // Optional function that blocks keyboard events when retuning false keyboardCondition: null, // Enable the slide overview mode overview: true, // Vertical centering of slides center: true, // Enables touch navigation on devices with touch input touch: true, // Loop the presentation loop: false, // Change the presentation direction to be RTL rtl: false, // Turns fragments on and off globally fragments: true, // Flags if the presentation is running in an embedded mode, // i.e. contained within a limited portion of the screen embedded: false, // Flags if we should show a help overlay when the questionmark // key is pressed help: true, // Flags if it should be possible to pause the presentation (blackout) pause: true, // Flags if speaker notes should be visible to all viewers showNotes: false, // Number of milliseconds between automatically proceeding to the // next slide, disabled when set to 0, this value can be overwritten // by using a data-autoslide attribute on your slides autoSlide: 0, // Stop auto-sliding after user input autoSlideStoppable: true, // Enable slide navigation via mouse wheel mouseWheel: false, // Apply a 3D roll to links on hover rollingLinks: false, // Hides the address bar on mobile devices hideAddressBar: true, // Opens links in an iframe preview overlay previewLinks: false, // Exposes the reveal.js API through window.postMessage postMessage: true, // Dispatches all reveal.js events to the parent window through postMessage postMessageEvents: false, // Focuses body when page changes visiblity to ensure keyboard shortcuts work focusBodyOnPageVisibilityChange: true, // Transition style transition: 'slide', // none/fade/slide/convex/concave/zoom // Transition speed transitionSpeed: 'default', // default/fast/slow // Transition style for full page slide backgrounds backgroundTransition: 'fade', // none/fade/slide/convex/concave/zoom // Parallax background image parallaxBackgroundImage: '', // CSS syntax, e.g. "a.jpg" // Parallax background size parallaxBackgroundSize: '', // CSS syntax, e.g. "3000px 2000px" // Amount of pixels to move the parallax background per slide step parallaxBackgroundHorizontal: null, parallaxBackgroundVertical: null, // Number of slides away from the current that are visible viewDistance: 3, // Script dependencies to load dependencies: [] }, // Flags if reveal.js is loaded (has dispatched the 'ready' event) loaded = false, // Flags if the overview mode is currently active overview = false, // The horizontal and vertical index of the currently active slide indexh, indexv, // The previous and current slide HTML elements previousSlide, currentSlide, previousBackground, // Slides may hold a data-state attribute which we pick up and apply // as a class to the body. This list contains the combined state of // all current slides. state = [], // The current scale of the presentation (see width/height config) scale = 1, // CSS transform that is currently applied to the slides container, // split into two groups slidesTransform = { layout: '', overview: '' }, // Cached references to DOM elements dom = {}, // Features supported by the browser, see #checkCapabilities() features = {}, // Client is a mobile device, see #checkCapabilities() isMobileDevice, // Throttles mouse wheel navigation lastMouseWheelStep = 0, // Delays updates to the URL due to a Chrome thumbnailer bug writeURLTimeout = 0, // Flags if the interaction event listeners are bound eventsAreBound = false, // The current auto-slide duration autoSlide = 0, // Auto slide properties autoSlidePlayer, autoSlideTimeout = 0, autoSlideStartTime = -1, autoSlidePaused = false, // Holds information about the currently ongoing touch input touch = { startX: 0, startY: 0, startSpan: 0, startCount: 0, captured: false, threshold: 40 }, // Holds information about the keyboard shortcuts keyboardShortcuts = { 'N , SPACE': 'Next slide', 'P': 'Previous slide', '&#8592; , H': 'Navigate left', '&#8594; , L': 'Navigate right', '&#8593; , K': 'Navigate up', '&#8595; , J': 'Navigate down', 'Home': 'First slide', 'End': 'Last slide', 'B , .': 'Pause', 'F': 'Fullscreen', 'ESC, O': 'Slide overview' }; /** * Starts up the presentation if the client is capable. */ function initialize( options ) { checkCapabilities(); if( !features.transforms2d && !features.transforms3d ) { document.body.setAttribute( 'class', 'no-transforms' ); // Since JS won't be running any further, we load all lazy // loading elements upfront var images = toArray( document.getElementsByTagName( 'img' ) ), iframes = toArray( document.getElementsByTagName( 'iframe' ) ); var lazyLoadable = images.concat( iframes ); for( var i = 0, len = lazyLoadable.length; i < len; i++ ) { var element = lazyLoadable[i]; if( element.getAttribute( 'data-src' ) ) { element.setAttribute( 'src', element.getAttribute( 'data-src' ) ); element.removeAttribute( 'data-src' ); } } // If the browser doesn't support core features we won't be // using JavaScript to control the presentation return; } // Cache references to key DOM elements dom.wrapper = document.querySelector( '.reveal' ); dom.slides = document.querySelector( '.reveal .slides' ); // Force a layout when the whole page, incl fonts, has loaded window.addEventListener( 'load', layout, false ); var query = Reveal.getQueryHash(); // Do not accept new dependencies via query config to avoid // the potential of malicious script injection if( typeof query['dependencies'] !== 'undefined' ) delete query['dependencies']; // Copy options over to our config object extend( config, options ); extend( config, query ); // Hide the address bar in mobile browsers hideAddressBar(); // Loads the dependencies and continues to #start() once done load(); } /** * Inspect the client to see what it's capable of, this * should only happens once per runtime. */ function checkCapabilities() { features.transforms3d = 'WebkitPerspective' in document.body.style || 'MozPerspective' in document.body.style || 'msPerspective' in document.body.style || 'OPerspective' in document.body.style || 'perspective' in document.body.style; features.transforms2d = 'WebkitTransform' in document.body.style || 'MozTransform' in document.body.style || 'msTransform' in document.body.style || 'OTransform' in document.body.style || 'transform' in document.body.style; features.requestAnimationFrameMethod = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame; features.requestAnimationFrame = typeof features.requestAnimationFrameMethod === 'function'; features.canvas = !!document.createElement( 'canvas' ).getContext; features.touch = !!( 'ontouchstart' in window ); // Transitions in the overview are disabled in desktop and // mobile Safari due to lag features.overviewTransitions = !/Version\/[\d\.]+.*Safari/.test( navigator.userAgent ); isMobileDevice = /(iphone|ipod|ipad|android)/gi.test( navigator.userAgent ); } /** * Loads the dependencies of reveal.js. Dependencies are * defined via the configuration option 'dependencies' * and will be loaded prior to starting/binding reveal.js. * Some dependencies may have an 'async' flag, if so they * will load after reveal.js has been started up. */ function load() { var scripts = [], scriptsAsync = [], scriptsToPreload = 0; // Called once synchronous scripts finish loading function proceed() { if( scriptsAsync.length ) { // Load asynchronous scripts head.js.apply( null, scriptsAsync ); } start(); } function loadScript( s ) { head.ready( s.src.match( /([\w\d_\-]*)\.?js$|[^\\\/]*$/i )[0], function() { // Extension may contain callback functions if( typeof s.callback === 'function' ) { s.callback.apply( this ); } if( --scriptsToPreload === 0 ) { proceed(); } }); } for( var i = 0, len = config.dependencies.length; i < len; i++ ) { var s = config.dependencies[i]; // Load if there's no condition or the condition is truthy if( !s.condition || s.condition() ) { if( s.async ) { scriptsAsync.push( s.src ); } else { scripts.push( s.src ); } loadScript( s ); } } if( scripts.length ) { scriptsToPreload = scripts.length; // Load synchronous scripts head.js.apply( null, scripts ); } else { proceed(); } } /** * Starts up reveal.js by binding input events and navigating * to the current URL deeplink if there is one. */ function start() { // Make sure we've got all the DOM elements we need setupDOM(); // Listen to messages posted to this window setupPostMessage(); // Prevent iframes from scrolling the slides out of view setupIframeScrollPrevention(); // Resets all vertical slides so that only the first is visible resetVerticalSlides(); // Updates the presentation to match the current configuration values configure(); // Read the initial hash readURL(); // Update all backgrounds updateBackground( true ); // Notify listeners that the presentation is ready but use a 1ms // timeout to ensure it's not fired synchronously after #initialize() setTimeout( function() { // Enable transitions now that we're loaded dom.slides.classList.remove( 'no-transition' ); loaded = true; dispatchEvent( 'ready', { 'indexh': indexh, 'indexv': indexv, 'currentSlide': currentSlide } ); }, 1 ); // Special setup and config is required when printing to PDF if( isPrintingPDF() ) { removeEventListeners(); // The document needs to have loaded for the PDF layout // measurements to be accurate if( document.readyState === 'complete' ) { setupPDF(); } else { window.addEventListener( 'load', setupPDF ); } } } /** * Finds and stores references to DOM elements which are * required by the presentation. If a required element is * not found, it is created. */ function setupDOM() { // Prevent transitions while we're loading dom.slides.classList.add( 'no-transition' ); // Background element dom.background = createSingletonNode( dom.wrapper, 'div', 'backgrounds', null ); // Progress bar dom.progress = createSingletonNode( dom.wrapper, 'div', 'progress', '<span></span>' ); dom.progressbar = dom.progress.querySelector( 'span' ); // Arrow controls createSingletonNode( dom.wrapper, 'aside', 'controls', '<button class="navigate-left" aria-label="previous slide"></button>' + '<button class="navigate-right" aria-label="next slide"></button>' + '<button class="navigate-up" aria-label="above slide"></button>' + '<button class="navigate-down" aria-label="below slide"></button>' ); // Slide number dom.slideNumber = createSingletonNode( dom.wrapper, 'div', 'slide-number', '' ); // Element containing notes that are visible to the audience dom.speakerNotes = createSingletonNode( dom.wrapper, 'div', 'speaker-notes', null ); dom.speakerNotes.setAttribute( 'data-prevent-swipe', '' ); // Overlay graphic which is displayed during the paused mode createSingletonNode( dom.wrapper, 'div', 'pause-overlay', null ); // Cache references to elements dom.controls = document.querySelector( '.reveal .controls' ); dom.theme = document.querySelector( '#theme' ); dom.wrapper.setAttribute( 'role', 'application' ); // There can be multiple instances of controls throughout the page dom.controlsLeft = toArray( document.querySelectorAll( '.navigate-left' ) ); dom.controlsRight = toArray( document.querySelectorAll( '.navigate-right' ) ); dom.controlsUp = toArray( document.querySelectorAll( '.navigate-up' ) ); dom.controlsDown = toArray( document.querySelectorAll( '.navigate-down' ) ); dom.controlsPrev = toArray( document.querySelectorAll( '.navigate-prev' ) ); dom.controlsNext = toArray( document.querySelectorAll( '.navigate-next' ) ); dom.statusDiv = createStatusDiv(); } /** * Creates a hidden div with role aria-live to announce the * current slide content. Hide the div off-screen to make it * available only to Assistive Technologies. */ function createStatusDiv() { var statusDiv = document.getElementById( 'aria-status-div' ); if( !statusDiv ) { statusDiv = document.createElement( 'div' ); statusDiv.style.position = 'absolute'; statusDiv.style.height = '1px'; statusDiv.style.width = '1px'; statusDiv.style.overflow ='hidden'; statusDiv.style.clip = 'rect( 1px, 1px, 1px, 1px )'; statusDiv.setAttribute( 'id', 'aria-status-div' ); statusDiv.setAttribute( 'aria-live', 'polite' ); statusDiv.setAttribute( 'aria-atomic','true' ); dom.wrapper.appendChild( statusDiv ); } return statusDiv; } /** * Configures the presentation for printing to a static * PDF. */ function setupPDF() { var slideSize = getComputedSlideSize( window.innerWidth, window.innerHeight ); // Dimensions of the PDF pages var pageWidth = Math.floor( slideSize.width * ( 1 + config.margin ) ), pageHeight = Math.floor( slideSize.height * ( 1 + config.margin ) ); // Dimensions of slides within the pages var slideWidth = slideSize.width, slideHeight = slideSize.height; // Let the browser know what page size we want to print injectStyleSheet( '@page{size:'+ pageWidth +'px '+ pageHeight +'px; margin: 0;}' ); // Limit the size of certain elements to the dimensions of the slide injectStyleSheet( '.reveal section>img, .reveal section>video, .reveal section>iframe{max-width: '+ slideWidth +'px; max-height:'+ slideHeight +'px}' ); document.body.classList.add( 'print-pdf' ); document.body.style.width = pageWidth + 'px'; document.body.style.height = pageHeight + 'px'; // Add each slide's index as attributes on itself, we need these // indices to generate slide numbers below toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( hslide, h ) { hslide.setAttribute( 'data-index-h', h ); if( hslide.classList.contains( 'stack' ) ) { toArray( hslide.querySelectorAll( 'section' ) ).forEach( function( vslide, v ) { vslide.setAttribute( 'data-index-h', h ); vslide.setAttribute( 'data-index-v', v ); } ); } } ); // Slide and slide background layout toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) { // Vertical stacks are not centred since their section // children will be if( slide.classList.contains( 'stack' ) === false ) { // Center the slide inside of the page, giving the slide some margin var left = ( pageWidth - slideWidth ) / 2, top = ( pageHeight - slideHeight ) / 2; var contentHeight = getAbsoluteHeight( slide ); var numberOfPages = Math.max( Math.ceil( contentHeight / pageHeight ), 1 ); // Center slides vertically if( numberOfPages === 1 && config.center || slide.classList.contains( 'center' ) ) { top = Math.max( ( pageHeight - contentHeight ) / 2, 0 ); } // Position the slide inside of the page slide.style.left = left + 'px'; slide.style.top = top + 'px'; slide.style.width = slideWidth + 'px'; // TODO Backgrounds need to be multiplied when the slide // stretches over multiple pages var background = slide.querySelector( '.slide-background' ); if( background ) { background.style.width = pageWidth + 'px'; background.style.height = ( pageHeight * numberOfPages ) + 'px'; background.style.top = -top + 'px'; background.style.left = -left + 'px'; } // Inject notes if `showNotes` is enabled if( config.showNotes ) { var notes = getSlideNotes( slide ); if( notes ) { var notesSpacing = 8; var notesElement = document.createElement( 'div' ); notesElement.classList.add( 'speaker-notes' ); notesElement.classList.add( 'speaker-notes-pdf' ); notesElement.innerHTML = notes; notesElement.style.left = ( notesSpacing - left ) + 'px'; notesElement.style.bottom = ( notesSpacing - top ) + 'px'; notesElement.style.width = ( pageWidth - notesSpacing*2 ) + 'px'; slide.appendChild( notesElement ); } } // Inject slide numbers if `slideNumbers` are enabled if( config.slideNumber ) { var slideNumberH = parseInt( slide.getAttribute( 'data-index-h' ), 10 ) + 1, slideNumberV = parseInt( slide.getAttribute( 'data-index-v' ), 10 ) + 1; var numberElement = document.createElement( 'div' ); numberElement.classList.add( 'slide-number' ); numberElement.classList.add( 'slide-number-pdf' ); numberElement.innerHTML = formatSlideNumber( slideNumberH, '.', slideNumberV ); background.appendChild( numberElement ); } } } ); // Show all fragments toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ' .fragment' ) ).forEach( function( fragment ) { fragment.classList.add( 'visible' ); } ); } /** * This is an unfortunate necessity. Iframes can trigger the * parent window to scroll, for example by focusing an input. * This scrolling can not be prevented by hiding overflow in * CSS so we have to resort to repeatedly checking if the * browser has decided to offset our slides :( */ function setupIframeScrollPrevention() { if( dom.slides.querySelector( 'iframe' ) ) { setInterval( function() { if( dom.wrapper.scrollTop !== 0 || dom.wrapper.scrollLeft !== 0 ) { dom.wrapper.scrollTop = 0; dom.wrapper.scrollLeft = 0; } }, 500 ); } } /** * Creates an HTML element and returns a reference to it. * If the element already exists the existing instance will * be returned. */ function createSingletonNode( container, tagname, classname, innerHTML ) { // Find all nodes matching the description var nodes = container.querySelectorAll( '.' + classname ); // Check all matches to find one which is a direct child of // the specified container for( var i = 0; i < nodes.length; i++ ) { var testNode = nodes[i]; if( testNode.parentNode === container ) { return testNode; } } // If no node was found, create it now var node = document.createElement( tagname ); node.classList.add( classname ); if( typeof innerHTML === 'string' ) { node.innerHTML = innerHTML; } container.appendChild( node ); return node; } /** * Creates the slide background elements and appends them * to the background container. One element is created per * slide no matter if the given slide has visible background. */ function createBackgrounds() { var printMode = isPrintingPDF(); // Clear prior backgrounds dom.background.innerHTML = ''; dom.background.classList.add( 'no-transition' ); // Iterate over all horizontal slides toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( slideh ) { var backgroundStack; if( printMode ) { backgroundStack = createBackground( slideh, slideh ); } else { backgroundStack = createBackground( slideh, dom.background ); } // Iterate over all vertical slides toArray( slideh.querySelectorAll( 'section' ) ).forEach( function( slidev ) { if( printMode ) { createBackground( slidev, slidev ); } else { createBackground( slidev, backgroundStack ); } backgroundStack.classList.add( 'stack' ); } ); } ); // Add parallax background if specified if( config.parallaxBackgroundImage ) { dom.background.style.backgroundImage = 'url("' + config.parallaxBackgroundImage + '")'; dom.background.style.backgroundSize = config.parallaxBackgroundSize; // Make sure the below properties are set on the element - these properties are // needed for proper transitions to be set on the element via CSS. To remove // annoying background slide-in effect when the presentation starts, apply // these properties after short time delay setTimeout( function() { dom.wrapper.classList.add( 'has-parallax-background' ); }, 1 ); } else { dom.background.style.backgroundImage = ''; dom.wrapper.classList.remove( 'has-parallax-background' ); } } /** * Creates a background for the given slide. * * @param {HTMLElement} slide * @param {HTMLElement} container The element that the background * should be appended to */ function createBackground( slide, container ) { var data = { background: slide.getAttribute( 'data-background' ), backgroundSize: slide.getAttribute( 'data-background-size' ), backgroundImage: slide.getAttribute( 'data-background-image' ), backgroundVideo: slide.getAttribute( 'data-background-video' ), backgroundIframe: slide.getAttribute( 'data-background-iframe' ), backgroundColor: slide.getAttribute( 'data-background-color' ), backgroundRepeat: slide.getAttribute( 'data-background-repeat' ), backgroundPosition: slide.getAttribute( 'data-background-position' ), backgroundTransition: slide.getAttribute( 'data-background-transition' ) }; var element = document.createElement( 'div' ); // Carry over custom classes from the slide to the background element.className = 'slide-background ' + slide.className.replace( /present|past|future/, '' ); if( data.background ) { // Auto-wrap image urls in url(...) if( /^(http|file|\/\/)/gi.test( data.background ) || /\.(svg|png|jpg|jpeg|gif|bmp)$/gi.test( data.background ) ) { slide.setAttribute( 'data-background-image', data.background ); } else { element.style.background = data.background; } } // Create a hash for this combination of background settings. // This is used to determine when two slide backgrounds are // the same. if( data.background || data.backgroundColor || data.backgroundImage || data.backgroundVideo || data.backgroundIframe ) { element.setAttribute( 'data-background-hash', data.background + data.backgroundSize + data.backgroundImage + data.backgroundVideo + data.backgroundIframe + data.backgroundColor + data.backgroundRepeat + data.backgroundPosition + data.backgroundTransition ); } // Additional and optional background properties if( data.backgroundSize ) element.style.backgroundSize = data.backgroundSize; if( data.backgroundColor ) element.style.backgroundColor = data.backgroundColor; if( data.backgroundRepeat ) element.style.backgroundRepeat = data.backgroundRepeat; if( data.backgroundPosition ) element.style.backgroundPosition = data.backgroundPosition; if( data.backgroundTransition ) element.setAttribute( 'data-background-transition', data.backgroundTransition ); container.appendChild( element ); // If backgrounds are being recreated, clear old classes slide.classList.remove( 'has-dark-background' ); slide.classList.remove( 'has-light-background' ); // If this slide has a background color, add a class that // signals if it is light or dark. If the slide has no background // color, no class will be set var computedBackgroundColor = window.getComputedStyle( element ).backgroundColor; if( computedBackgroundColor ) { var rgb = colorToRgb( computedBackgroundColor ); // Ignore fully transparent backgrounds. Some browsers return // rgba(0,0,0,0) when reading the computed background color of // an element with no background if( rgb && rgb.a !== 0 ) { if( colorBrightness( computedBackgroundColor ) < 128 ) { slide.classList.add( 'has-dark-background' ); } else { slide.classList.add( 'has-light-background' ); } } } return element; } /** * Registers a listener to postMessage events, this makes it * possible to call all reveal.js API methods from another * window. For example: * * revealWindow.postMessage( JSON.stringify({ * method: 'slide', * args: [ 2 ] * }), '*' ); */ function setupPostMessage() { if( config.postMessage ) { window.addEventListener( 'message', function ( event ) { var data = event.data; // Make sure we're dealing with JSON if( typeof data === 'string' && data.charAt( 0 ) === '{' && data.charAt( data.length - 1 ) === '}' ) { data = JSON.parse( data ); // Check if the requested method can be found if( data.method && typeof Reveal[data.method] === 'function' ) { Reveal[data.method].apply( Reveal, data.args ); } } }, false ); } } /** * Applies the configuration settings from the config * object. May be called multiple times. */ function configure( options ) { var numberOfSlides = dom.wrapper.querySelectorAll( SLIDES_SELECTOR ).length; dom.wrapper.classList.remove( config.transition ); // New config options may be passed when this method // is invoked through the API after initialization if( typeof options === 'object' ) extend( config, options ); // Force linear transition based on browser capabilities if( features.transforms3d === false ) config.transition = 'linear'; dom.wrapper.classList.add( config.transition ); dom.wrapper.setAttribute( 'data-transition-speed', config.transitionSpeed ); dom.wrapper.setAttribute( 'data-background-transition', config.backgroundTransition ); dom.controls.style.display = config.controls ? 'block' : 'none'; dom.progress.style.display = config.progress ? 'block' : 'none'; dom.slideNumber.style.display = config.slideNumber && !isPrintingPDF() ? 'block' : 'none'; if( config.rtl ) { dom.wrapper.classList.add( 'rtl' ); } else { dom.wrapper.classList.remove( 'rtl' ); } if( config.center ) { dom.wrapper.classList.add( 'center' ); } else { dom.wrapper.classList.remove( 'center' ); } // Exit the paused mode if it was configured off if( config.pause === false ) { resume(); } if( config.showNotes ) { dom.speakerNotes.classList.add( 'visible' ); } else { dom.speakerNotes.classList.remove( 'visible' ); } if( config.mouseWheel ) { document.addEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF document.addEventListener( 'mousewheel', onDocumentMouseScroll, false ); } else { document.removeEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF document.removeEventListener( 'mousewheel', onDocumentMouseScroll, false ); } // Rolling 3D links if( config.rollingLinks ) { enableRollingLinks(); } else { disableRollingLinks(); } // Iframe link previews if( config.previewLinks ) { enablePreviewLinks(); } else { disablePreviewLinks(); enablePreviewLinks( '[data-preview-link]' ); } // Remove existing auto-slide controls if( autoSlidePlayer ) { autoSlidePlayer.destroy(); autoSlidePlayer = null; } // Generate auto-slide controls if needed if( numberOfSlides > 1 && config.autoSlide && config.autoSlideStoppable && features.canvas && features.requestAnimationFrame ) { autoSlidePlayer = new Playback( dom.wrapper, function() { return Math.min( Math.max( ( Date.now() - autoSlideStartTime ) / autoSlide, 0 ), 1 ); } ); autoSlidePlayer.on( 'click', onAutoSlidePlayerClick ); autoSlidePaused = false; } // When fragments are turned off they should be visible if( config.fragments === false ) { toArray( dom.slides.querySelectorAll( '.fragment' ) ).forEach( function( element ) { element.classList.add( 'visible' ); element.classList.remove( 'current-fragment' ); } ); } sync(); } /** * Binds all event listeners. */ function addEventListeners() { eventsAreBound = true; window.addEventListener( 'hashchange', onWindowHashChange, false ); window.addEventListener( 'resize', onWindowResize, false ); if( config.touch ) { dom.wrapper.addEventListener( 'touchstart', onTouchStart, false ); dom.wrapper.addEventListener( 'touchmove', onTouchMove, false ); dom.wrapper.addEventListener( 'touchend', onTouchEnd, false ); // Support pointer-style touch interaction as well if( window.navigator.pointerEnabled ) { // IE 11 uses un-prefixed version of pointer events dom.wrapper.addEventListener( 'pointerdown', onPointerDown, false ); dom.wrapper.addEventListener( 'pointermove', onPointerMove, false ); dom.wrapper.addEventListener( 'pointerup', onPointerUp, false ); } else if( window.navigator.msPointerEnabled ) { // IE 10 uses prefixed version of pointer events dom.wrapper.addEventListener( 'MSPointerDown', onPointerDown, false ); dom.wrapper.addEventListener( 'MSPointerMove', onPointerMove, false ); dom.wrapper.addEventListener( 'MSPointerUp', onPointerUp, false ); } } if( config.keyboard ) { document.addEventListener( 'keydown', onDocumentKeyDown, false ); document.addEventListener( 'keypress', onDocumentKeyPress, false ); } if( config.progress && dom.progress ) { dom.progress.addEventListener( 'click', onProgressClicked, false ); } if( config.focusBodyOnPageVisibilityChange ) { var visibilityChange; if( 'hidden' in document ) { visibilityChange = 'visibilitychange'; } else if( 'msHidden' in document ) { visibilityChange = 'msvisibilitychange'; } else if( 'webkitHidden' in document ) { visibilityChange = 'webkitvisibilitychange'; } if( visibilityChange ) { document.addEventListener( visibilityChange, onPageVisibilityChange, false ); } } // Listen to both touch and click events, in case the device // supports both var pointerEvents = [ 'touchstart', 'click' ]; // Only support touch for Android, fixes double navigations in // stock browser if( navigator.userAgent.match( /android/gi ) ) { pointerEvents = [ 'touchstart' ]; } pointerEvents.forEach( function( eventName ) { dom.controlsLeft.forEach( function( el ) { el.addEventListener( eventName, onNavigateLeftClicked, false ); } ); dom.controlsRight.forEach( function( el ) { el.addEventListener( eventName, onNavigateRightClicked, false ); } ); dom.controlsUp.forEach( function( el ) { el.addEventListener( eventName, onNavigateUpClicked, false ); } ); dom.controlsDown.forEach( function( el ) { el.addEventListener( eventName, onNavigateDownClicked, false ); } ); dom.controlsPrev.forEach( function( el ) { el.addEventListener( eventName, onNavigatePrevClicked, false ); } ); dom.controlsNext.forEach( function( el ) { el.addEventListener( eventName, onNavigateNextClicked, false ); } ); } ); } /** * Unbinds all event listeners. */ function removeEventListeners() { eventsAreBound = false; document.removeEventListener( 'keydown', onDocumentKeyDown, false ); document.removeEventListener( 'keypress', onDocumentKeyPress, false ); window.removeEventListener( 'hashchange', onWindowHashChange, false ); window.removeEventListener( 'resize', onWindowResize, false ); dom.wrapper.removeEventListener( 'touchstart', onTouchStart, false ); dom.wrapper.removeEventListener( 'touchmove', onTouchMove, false ); dom.wrapper.removeEventListener( 'touchend', onTouchEnd, false ); // IE11 if( window.navigator.pointerEnabled ) { dom.wrapper.removeEventListener( 'pointerdown', onPointerDown, false ); dom.wrapper.removeEventListener( 'pointermove', onPointerMove, false ); dom.wrapper.removeEventListener( 'pointerup', onPointerUp, false ); } // IE10 else if( window.navigator.msPointerEnabled ) { dom.wrapper.removeEventListener( 'MSPointerDown', onPointerDown, false ); dom.wrapper.removeEventListener( 'MSPointerMove', onPointerMove, false ); dom.wrapper.removeEventListener( 'MSPointerUp', onPointerUp, false ); } if ( config.progress && dom.progress ) { dom.progress.removeEventListener( 'click', onProgressClicked, false ); } [ 'touchstart', 'click' ].forEach( function( eventName ) { dom.controlsLeft.forEach( function( el ) { el.removeEventListener( eventName, onNavigateLeftClicked, false ); } ); dom.controlsRight.forEach( function( el ) { el.removeEventListener( eventName, onNavigateRightClicked, false ); } ); dom.controlsUp.forEach( function( el ) { el.removeEventListener( eventName, onNavigateUpClicked, false ); } ); dom.controlsDown.forEach( function( el ) { el.removeEventListener( eventName, onNavigateDownClicked, false ); } ); dom.controlsPrev.forEach( function( el ) { el.removeEventListener( eventName, onNavigatePrevClicked, false ); } ); dom.controlsNext.forEach( function( el ) { el.removeEventListener( eventName, onNavigateNextClicked, false ); } ); } ); } /** * Extend object a with the properties of object b. * If there's a conflict, object b takes precedence. */ function extend( a, b ) { for( var i in b ) { a[ i ] = b[ i ]; } } /** * Converts the target object to an array. */ function toArray( o ) { return Array.prototype.slice.call( o ); } /** * Utility for deserializing a value. */ function deserialize( value ) { if( typeof value === 'string' ) { if( value === 'null' ) return null; else if( value === 'true' ) return true; else if( value === 'false' ) return false; else if( value.match( /^\d+$/ ) ) return parseFloat( value ); } return value; } /** * Measures the distance in pixels between point a * and point b. * * @param {Object} a point with x/y properties * @param {Object} b point with x/y properties */ function distanceBetween( a, b ) { var dx = a.x - b.x, dy = a.y - b.y; return Math.sqrt( dx*dx + dy*dy ); } /** * Applies a CSS transform to the target element. */ function transformElement( element, transform ) { element.style.WebkitTransform = transform; element.style.MozTransform = transform; element.style.msTransform = transform; element.style.transform = transform; } /** * Applies CSS transforms to the slides container. The container * is transformed from two separate sources: layout and the overview * mode. */ function transformSlides( transforms ) { // Pick up new transforms from arguments if( typeof transforms.layout === 'string' ) slidesTransform.layout = transforms.layout; if( typeof transforms.overview === 'string' ) slidesTransform.overview = transforms.overview; // Apply the transforms to the slides container if( slidesTransform.layout ) { transformElement( dom.slides, slidesTransform.layout + ' ' + slidesTransform.overview ); } else { transformElement( dom.slides, slidesTransform.overview ); } } /** * Injects the given CSS styles into the DOM. */ function injectStyleSheet( value ) { var tag = document.createElement( 'style' ); tag.type = 'text/css'; if( tag.styleSheet ) { tag.styleSheet.cssText = value; } else { tag.appendChild( document.createTextNode( value ) ); } document.getElementsByTagName( 'head' )[0].appendChild( tag ); } /** * Converts various color input formats to an {r:0,g:0,b:0} object. * * @param {String} color The string representation of a color, * the following formats are supported: * - #000 * - #000000 * - rgb(0,0,0) */ function colorToRgb( color ) { var hex3 = color.match( /^#([0-9a-f]{3})$/i ); if( hex3 && hex3[1] ) { hex3 = hex3[1]; return { r: parseInt( hex3.charAt( 0 ), 16 ) * 0x11, g: parseInt( hex3.charAt( 1 ), 16 ) * 0x11, b: parseInt( hex3.charAt( 2 ), 16 ) * 0x11 }; } var hex6 = color.match( /^#([0-9a-f]{6})$/i ); if( hex6 && hex6[1] ) { hex6 = hex6[1]; return { r: parseInt( hex6.substr( 0, 2 ), 16 ), g: parseInt( hex6.substr( 2, 2 ), 16 ), b: parseInt( hex6.substr( 4, 2 ), 16 ) }; } var rgb = color.match( /^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i ); if( rgb ) { return { r: parseInt( rgb[1], 10 ), g: parseInt( rgb[2], 10 ), b: parseInt( rgb[3], 10 ) }; } var rgba = color.match( /^rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\,\s*([\d]+|[\d]*.[\d]+)\s*\)$/i ); if( rgba ) { return { r: parseInt( rgba[1], 10 ), g: parseInt( rgba[2], 10 ), b: parseInt( rgba[3], 10 ), a: parseFloat( rgba[4] ) }; } return null; } /** * Calculates brightness on a scale of 0-255. * * @param color See colorStringToRgb for supported formats. */ function colorBrightness( color ) { if( typeof color === 'string' ) color = colorToRgb( color ); if( color ) { return ( color.r * 299 + color.g * 587 + color.b * 114 ) / 1000; } return null; } /** * Retrieves the height of the given element by looking * at the position and height of its immediate children. */ function getAbsoluteHeight( element ) { var height = 0; if( element ) { var absoluteChildren = 0; toArray( element.childNodes ).forEach( function( child ) { if( typeof child.offsetTop === 'number' && child.style ) { // Count # of abs children if( window.getComputedStyle( child ).position === 'absolute' ) { absoluteChildren += 1; } height = Math.max( height, child.offsetTop + child.offsetHeight ); } } ); // If there are no absolute children, use offsetHeight if( absoluteChildren === 0 ) { height = element.offsetHeight; } } return height; } /** * Returns the remaining height within the parent of the * target element. * * remaining height = [ configured parent height ] - [ current parent height ] */ function getRemainingHeight( element, height ) { height = height || 0; if( element ) { var newHeight, oldHeight = element.style.height; // Change the .stretch element height to 0 in order find the height of all // the other elements element.style.height = '0px'; newHeight = height - element.parentNode.offsetHeight; // Restore the old height, just in case element.style.height = oldHeight + 'px'; return newHeight; } return height; } /** * Checks if this instance is being used to print a PDF. */ function isPrintingPDF() { return ( /print-pdf/gi ).test( window.location.search ); } /** * Hides the address bar if we're on a mobile device. */ function hideAddressBar() { if( config.hideAddressBar && isMobileDevice ) { // Events that should trigger the address bar to hide window.addEventListener( 'load', removeAddressBar, false ); window.addEventListener( 'orientationchange', removeAddressBar, false ); } } /** * Causes the address bar to hide on mobile devices, * more vertical space ftw. */ function removeAddressBar() { setTimeout( function() { window.scrollTo( 0, 1 ); }, 10 ); } /** * Dispatches an event of the specified type from the * reveal DOM element. */ function dispatchEvent( type, args ) { var event = document.createEvent( 'HTMLEvents', 1, 2 ); event.initEvent( type, true, true ); extend( event, args ); dom.wrapper.dispatchEvent( event ); // If we're in an iframe, post each reveal.js event to the // parent window. Used by the notes plugin if( config.postMessageEvents && window.parent !== window.self ) { window.parent.postMessage( JSON.stringify({ namespace: 'reveal', eventName: type, state: getState() }), '*' ); } } /** * Wrap all links in 3D goodness. */ function enableRollingLinks() { if( features.transforms3d && !( 'msPerspective' in document.body.style ) ) { var anchors = dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ' a' ); for( var i = 0, len = anchors.length; i < len; i++ ) { var anchor = anchors[i]; if( anchor.textContent && !anchor.querySelector( '*' ) && ( !anchor.className || !anchor.classList.contains( anchor, 'roll' ) ) ) { var span = document.createElement('span'); span.setAttribute('data-title', anchor.text); span.innerHTML = anchor.innerHTML; anchor.classList.add( 'roll' ); anchor.innerHTML = ''; anchor.appendChild(span); } } } } /** * Unwrap all 3D links. */ function disableRollingLinks() { var anchors = dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ' a.roll' ); for( var i = 0, len = anchors.length; i < len; i++ ) { var anchor = anchors[i]; var span = anchor.querySelector( 'span' ); if( span ) { anchor.classList.remove( 'roll' ); anchor.innerHTML = span.innerHTML; } } } /** * Bind preview frame links. */ function enablePreviewLinks( selector ) { var anchors = toArray( document.querySelectorAll( selector ? selector : 'a' ) ); anchors.forEach( function( element ) { if( /^(http|www)/gi.test( element.getAttribute( 'href' ) ) ) { element.addEventListener( 'click', onPreviewLinkClicked, false ); } } ); } /** * Unbind preview frame links. */ function disablePreviewLinks() { var anchors = toArray( document.querySelectorAll( 'a' ) ); anchors.forEach( function( element ) { if( /^(http|www)/gi.test( element.getAttribute( 'href' ) ) ) { element.removeEventListener( 'click', onPreviewLinkClicked, false ); } } ); } /** * Opens a preview window for the target URL. */ function showPreview( url ) { closeOverlay(); dom.overlay = document.createElement( 'div' ); dom.overlay.classList.add( 'overlay' ); dom.overlay.classList.add( 'overlay-preview' ); dom.wrapper.appendChild( dom.overlay ); dom.overlay.innerHTML = [ '<header>', '<a class="close" href="#"><span class="icon"></span></a>', '<a class="external" href="'+ url +'" target="_blank"><span class="icon"></span></a>', '</header>', '<div class="spinner"></div>', '<div class="viewport">', '<iframe src="'+ url +'"></iframe>', '</div>' ].join(''); dom.overlay.querySelector( 'iframe' ).addEventListener( 'load', function( event ) { dom.overlay.classList.add( 'loaded' ); }, false ); dom.overlay.querySelector( '.close' ).addEventListener( 'click', function( event ) { closeOverlay(); event.preventDefault(); }, false ); dom.overlay.querySelector( '.external' ).addEventListener( 'click', function( event ) { closeOverlay(); }, false ); setTimeout( function() { dom.overlay.classList.add( 'visible' ); }, 1 ); } /** * Opens a overlay window with help material. */ function showHelp() { if( config.help ) { closeOverlay(); dom.overlay = document.createElement( 'div' ); dom.overlay.classList.add( 'overlay' ); dom.overlay.classList.add( 'overlay-help' ); dom.wrapper.appendChild( dom.overlay ); var html = '<p class="title">Keyboard Shortcuts</p><br/>'; html += '<table><th>KEY</th><th>ACTION</th>'; for( var key in keyboardShortcuts ) { html += '<tr><td>' + key + '</td><td>' + keyboardShortcuts[ key ] + '</td></tr>'; } html += '</table>'; dom.overlay.innerHTML = [ '<header>', '<a class="close" href="#"><span class="icon"></span></a>', '</header>', '<div class="viewport">', '<div class="viewport-inner">'+ html +'</div>', '</div>' ].join(''); dom.overlay.querySelector( '.close' ).addEventListener( 'click', function( event ) { closeOverlay(); event.preventDefault(); }, false ); setTimeout( function() { dom.overlay.classList.add( 'visible' ); }, 1 ); } } /** * Closes any currently open overlay. */ function closeOverlay() { if( dom.overlay ) { dom.overlay.parentNode.removeChild( dom.overlay ); dom.overlay = null; } } /** * Applies JavaScript-controlled layout rules to the * presentation. */ function layout() { if( dom.wrapper && !isPrintingPDF() ) { var size = getComputedSlideSize(); var slidePadding = 20; // TODO Dig this out of DOM // Layout the contents of the slides layoutSlideContents( config.width, config.height, slidePadding ); dom.slides.style.width = size.width + 'px'; dom.slides.style.height = size.height + 'px'; // Determine scale of content to fit within available space scale = Math.min( size.presentationWidth / size.width, size.presentationHeight / size.height ); // Respect max/min scale settings scale = Math.max( scale, config.minScale ); scale = Math.min( scale, config.maxScale ); // Don't apply any scaling styles if scale is 1 if( scale === 1 ) { dom.slides.style.zoom = ''; dom.slides.style.left = ''; dom.slides.style.top = ''; dom.slides.style.bottom = ''; dom.slides.style.right = ''; transformSlides( { layout: '' } ); } else { // Use zoom to scale up in desktop Chrome so that content // remains crisp. We don't use zoom to scale down since that // can lead to shifts in text layout/line breaks. if( scale > 1 && !isMobileDevice && /chrome/i.test( navigator.userAgent ) && typeof dom.slides.style.zoom !== 'undefined' ) { dom.slides.style.zoom = scale; dom.slides.style.left = ''; dom.slides.style.top = ''; dom.slides.style.bottom = ''; dom.slides.style.right = ''; transformSlides( { layout: '' } ); } // Apply scale transform as a fallback else { dom.slides.style.zoom = ''; dom.slides.style.left = '50%'; dom.slides.style.top = '50%'; dom.slides.style.bottom = 'auto'; dom.slides.style.right = 'auto'; transformSlides( { layout: 'translate(-50%, -50%) scale('+ scale +')' } ); } } // Select all slides, vertical and horizontal var slides = toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ); for( var i = 0, len = slides.length; i < len; i++ ) { var slide = slides[ i ]; // Don't bother updating invisible slides if( slide.style.display === 'none' ) { continue; } if( config.center || slide.classList.contains( 'center' ) ) { // Vertical stacks are not centred since their section // children will be if( slide.classList.contains( 'stack' ) ) { slide.style.top = 0; } else { slide.style.top = Math.max( ( ( size.height - getAbsoluteHeight( slide ) ) / 2 ) - slidePadding, 0 ) + 'px'; } } else { slide.style.top = ''; } } updateProgress(); updateParallax(); } } /** * Applies layout logic to the contents of all slides in * the presentation. */ function layoutSlideContents( width, height, padding ) { // Handle sizing of elements with the 'stretch' class toArray( dom.slides.querySelectorAll( 'section > .stretch' ) ).forEach( function( element ) { // Determine how much vertical space we can use var remainingHeight = getRemainingHeight( element, height ); // Consider the aspect ratio of media elements if( /(img|video)/gi.test( element.nodeName ) ) { var nw = element.naturalWidth || element.videoWidth, nh = element.naturalHeight || element.videoHeight; var es = Math.min( width / nw, remainingHeight / nh ); element.style.width = ( nw * es ) + 'px'; element.style.height = ( nh * es ) + 'px'; } else { element.style.width = width + 'px'; element.style.height = remainingHeight + 'px'; } } ); } /** * Calculates the computed pixel size of our slides. These * values are based on the width and height configuration * options. */ function getComputedSlideSize( presentationWidth, presentationHeight ) { var size = { // Slide size width: config.width, height: config.height, // Presentation size presentationWidth: presentationWidth || dom.wrapper.offsetWidth, presentationHeight: presentationHeight || dom.wrapper.offsetHeight }; // Reduce available space by margin size.presentationWidth -= ( size.presentationWidth * config.margin ); size.presentationHeight -= ( size.presentationHeight * config.margin ); // Slide width may be a percentage of available width if( typeof size.width === 'string' && /%$/.test( size.width ) ) { size.width = parseInt( size.width, 10 ) / 100 * size.presentationWidth; } // Slide height may be a percentage of available height if( typeof size.height === 'string' && /%$/.test( size.height ) ) { size.height = parseInt( size.height, 10 ) / 100 * size.presentationHeight; } return size; } /** * Stores the vertical index of a stack so that the same * vertical slide can be selected when navigating to and * from the stack. * * @param {HTMLElement} stack The vertical stack element * @param {int} v Index to memorize */ function setPreviousVerticalIndex( stack, v ) { if( typeof stack === 'object' && typeof stack.setAttribute === 'function' ) { stack.setAttribute( 'data-previous-indexv', v || 0 ); } } /** * Retrieves the vertical index which was stored using * #setPreviousVerticalIndex() or 0 if no previous index * exists. * * @param {HTMLElement} stack The vertical stack element */ function getPreviousVerticalIndex( stack ) { if( typeof stack === 'object' && typeof stack.setAttribute === 'function' && stack.classList.contains( 'stack' ) ) { // Prefer manually defined start-indexv var attributeName = stack.hasAttribute( 'data-start-indexv' ) ? 'data-start-indexv' : 'data-previous-indexv'; return parseInt( stack.getAttribute( attributeName ) || 0, 10 ); } return 0; } /** * Displays the overview of slides (quick nav) by scaling * down and arranging all slide elements. */ function activateOverview() { // Only proceed if enabled in config if( config.overview && !isOverview() ) { overview = true; dom.wrapper.classList.add( 'overview' ); dom.wrapper.classList.remove( 'overview-deactivating' ); if( features.overviewTransitions ) { setTimeout( function() { dom.wrapper.classList.add( 'overview-animated' ); }, 1 ); } // Don't auto-slide while in overview mode cancelAutoSlide(); // Move the backgrounds element into the slide container to // that the same scaling is applied dom.slides.appendChild( dom.background ); // Clicking on an overview slide navigates to it toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) { if( !slide.classList.contains( 'stack' ) ) { slide.addEventListener( 'click', onOverviewSlideClicked, true ); } } ); updateSlidesVisibility(); layoutOverview(); updateOverview(); layout(); // Notify observers of the overview showing dispatchEvent( 'overviewshown', { 'indexh': indexh, 'indexv': indexv, 'currentSlide': currentSlide } ); } } /** * Uses CSS transforms to position all slides in a grid for * display inside of the overview mode. */ function layoutOverview() { var margin = 70; var slideWidth = config.width + margin, slideHeight = config.height + margin; // Reverse in RTL mode if( config.rtl ) { slideWidth = -slideWidth; } // Layout slides toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( hslide, h ) { hslide.setAttribute( 'data-index-h', h ); transformElement( hslide, 'translate3d(' + ( h * slideWidth ) + 'px, 0, 0)' ); if( hslide.classList.contains( 'stack' ) ) { toArray( hslide.querySelectorAll( 'section' ) ).forEach( function( vslide, v ) { vslide.setAttribute( 'data-index-h', h ); vslide.setAttribute( 'data-index-v', v ); transformElement( vslide, 'translate3d(0, ' + ( v * slideHeight ) + 'px, 0)' ); } ); } } ); // Layout slide backgrounds toArray( dom.background.childNodes ).forEach( function( hbackground, h ) { transformElement( hbackground, 'translate3d(' + ( h * slideWidth ) + 'px, 0, 0)' ); toArray( hbackground.querySelectorAll( '.slide-background' ) ).forEach( function( vbackground, v ) { transformElement( vbackground, 'translate3d(0, ' + ( v * slideHeight ) + 'px, 0)' ); } ); } ); } /** * Moves the overview viewport to the current slides. * Called each time the current slide changes. */ function updateOverview() { var margin = 70; var slideWidth = config.width + margin, slideHeight = config.height + margin; // Reverse in RTL mode if( config.rtl ) { slideWidth = -slideWidth; } transformSlides( { overview: [ 'translateX('+ ( -indexh * slideWidth ) +'px)', 'translateY('+ ( -indexv * slideHeight ) +'px)', 'translateZ('+ ( window.innerWidth < 400 ? -1000 : -2500 ) +'px)' ].join( ' ' ) } ); } /** * Exits the slide overview and enters the currently * active slide. */ function deactivateOverview() { // Only proceed if enabled in config if( config.overview ) { overview = false; dom.wrapper.classList.remove( 'overview' ); dom.wrapper.classList.remove( 'overview-animated' ); // Temporarily add a class so that transitions can do different things // depending on whether they are exiting/entering overview, or just // moving from slide to slide dom.wrapper.classList.add( 'overview-deactivating' ); setTimeout( function () { dom.wrapper.classList.remove( 'overview-deactivating' ); }, 1 ); // Move the background element back out dom.wrapper.appendChild( dom.background ); // Clean up changes made to slides toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) { transformElement( slide, '' ); slide.removeEventListener( 'click', onOverviewSlideClicked, true ); } ); // Clean up changes made to backgrounds toArray( dom.background.querySelectorAll( '.slide-background' ) ).forEach( function( background ) { transformElement( background, '' ); } ); transformSlides( { overview: '' } ); slide( indexh, indexv ); layout(); cueAutoSlide(); // Notify observers of the overview hiding dispatchEvent( 'overviewhidden', { 'indexh': indexh, 'indexv': indexv, 'currentSlide': currentSlide } ); } } /** * Toggles the slide overview mode on and off. * * @param {Boolean} override Optional flag which overrides the * toggle logic and forcibly sets the desired state. True means * overview is open, false means it's closed. */ function toggleOverview( override ) { if( typeof override === 'boolean' ) { override ? activateOverview() : deactivateOverview(); } else { isOverview() ? deactivateOverview() : activateOverview(); } } /** * Checks if the overview is currently active. * * @return {Boolean} true if the overview is active, * false otherwise */ function isOverview() { return overview; } /** * Checks if the current or specified slide is vertical * (nested within another slide). * * @param {HTMLElement} slide [optional] The slide to check * orientation of */ function isVerticalSlide( slide ) { // Prefer slide argument, otherwise use current slide slide = slide ? slide : currentSlide; return slide && slide.parentNode && !!slide.parentNode.nodeName.match( /section/i ); } /** * Handling the fullscreen functionality via the fullscreen API * * @see http://fullscreen.spec.whatwg.org/ * @see https://developer.mozilla.org/en-US/docs/DOM/Using_fullscreen_mode */ function enterFullscreen() { var element = document.body; // Check which implementation is available var requestMethod = element.requestFullScreen || element.webkitRequestFullscreen || element.webkitRequestFullScreen || element.mozRequestFullScreen || element.msRequestFullscreen; if( requestMethod ) { requestMethod.apply( element ); } } /** * Enters the paused mode which fades everything on screen to * black. */ function pause() { if( config.pause ) { var wasPaused = dom.wrapper.classList.contains( 'paused' ); cancelAutoSlide(); dom.wrapper.classList.add( 'paused' ); if( wasPaused === false ) { dispatchEvent( 'paused' ); } } } /** * Exits from the paused mode. */ function resume() { var wasPaused = dom.wrapper.classList.contains( 'paused' ); dom.wrapper.classList.remove( 'paused' ); cueAutoSlide(); if( wasPaused ) { dispatchEvent( 'resumed' ); } } /** * Toggles the paused mode on and off. */ function togglePause( override ) { if( typeof override === 'boolean' ) { override ? pause() : resume(); } else { isPaused() ? resume() : pause(); } } /** * Checks if we are currently in the paused mode. */ function isPaused() { return dom.wrapper.classList.contains( 'paused' ); } /** * Toggles the auto slide mode on and off. * * @param {Boolean} override Optional flag which sets the desired state. * True means autoplay starts, false means it stops. */ function toggleAutoSlide( override ) { if( typeof override === 'boolean' ) { override ? resumeAutoSlide() : pauseAutoSlide(); } else { autoSlidePaused ? resumeAutoSlide() : pauseAutoSlide(); } } /** * Checks if the auto slide mode is currently on. */ function isAutoSliding() { return !!( autoSlide && !autoSlidePaused ); } /** * Steps from the current point in the presentation to the * slide which matches the specified horizontal and vertical * indices. * * @param {int} h Horizontal index of the target slide * @param {int} v Vertical index of the target slide * @param {int} f Optional index of a fragment within the * target slide to activate * @param {int} o Optional origin for use in multimaster environments */ function slide( h, v, f, o ) { // Remember where we were at before previousSlide = currentSlide; // Query all horizontal slides in the deck var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ); // If no vertical index is specified and the upcoming slide is a // stack, resume at its previous vertical index if( v === undefined && !isOverview() ) { v = getPreviousVerticalIndex( horizontalSlides[ h ] ); } // If we were on a vertical stack, remember what vertical index // it was on so we can resume at the same position when returning if( previousSlide && previousSlide.parentNode && previousSlide.parentNode.classList.contains( 'stack' ) ) { setPreviousVerticalIndex( previousSlide.parentNode, indexv ); } // Remember the state before this slide var stateBefore = state.concat(); // Reset the state array state.length = 0; var indexhBefore = indexh || 0, indexvBefore = indexv || 0; // Activate and transition to the new slide indexh = updateSlides( HORIZONTAL_SLIDES_SELECTOR, h === undefined ? indexh : h ); indexv = updateSlides( VERTICAL_SLIDES_SELECTOR, v === undefined ? indexv : v ); // Update the visibility of slides now that the indices have changed updateSlidesVisibility(); layout(); // Apply the new state stateLoop: for( var i = 0, len = state.length; i < len; i++ ) { // Check if this state existed on the previous slide. If it // did, we will avoid adding it repeatedly for( var j = 0; j < stateBefore.length; j++ ) { if( stateBefore[j] === state[i] ) { stateBefore.splice( j, 1 ); continue stateLoop; } } document.documentElement.classList.add( state[i] ); // Dispatch custom event matching the state's name dispatchEvent( state[i] ); } // Clean up the remains of the previous state while( stateBefore.length ) { document.documentElement.classList.remove( stateBefore.pop() ); } // Update the overview if it's currently active if( isOverview() ) { updateOverview(); } // Find the current horizontal slide and any possible vertical slides // within it var currentHorizontalSlide = horizontalSlides[ indexh ], currentVerticalSlides = currentHorizontalSlide.querySelectorAll( 'section' ); // Store references to the previous and current slides currentSlide = currentVerticalSlides[ indexv ] || currentHorizontalSlide; // Show fragment, if specified if( typeof f !== 'undefined' ) { navigateFragment( f ); } // Dispatch an event if the slide changed var slideChanged = ( indexh !== indexhBefore || indexv !== indexvBefore ); if( slideChanged ) { dispatchEvent( 'slidechanged', { 'indexh': indexh, 'indexv': indexv, 'previousSlide': previousSlide, 'currentSlide': currentSlide, 'origin': o } ); } else { // Ensure that the previous slide is never the same as the current previousSlide = null; } // Solves an edge case where the previous slide maintains the // 'present' class when navigating between adjacent vertical // stacks if( previousSlide ) { previousSlide.classList.remove( 'present' ); previousSlide.setAttribute( 'aria-hidden', 'true' ); // Reset all slides upon navigate to home // Issue: #285 if ( dom.wrapper.querySelector( HOME_SLIDE_SELECTOR ).classList.contains( 'present' ) ) { // Launch async task setTimeout( function () { var slides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.stack') ), i; for( i in slides ) { if( slides[i] ) { // Reset stack setPreviousVerticalIndex( slides[i], 0 ); } } }, 0 ); } } // Handle embedded content if( slideChanged || !previousSlide ) { stopEmbeddedContent( previousSlide ); startEmbeddedContent( currentSlide ); } // Announce the current slide contents, for screen readers dom.statusDiv.textContent = currentSlide.textContent; updateControls(); updateProgress(); updateBackground(); updateParallax(); updateSlideNumber(); updateNotes(); // Update the URL hash writeURL(); cueAutoSlide(); } /** * Syncs the presentation with the current DOM. Useful * when new slides or control elements are added or when * the configuration has changed. */ function sync() { // Subscribe to input removeEventListeners(); addEventListeners(); // Force a layout to make sure the current config is accounted for layout(); // Reflect the current autoSlide value autoSlide = config.autoSlide; // Start auto-sliding if it's enabled cueAutoSlide(); // Re-create the slide backgrounds createBackgrounds(); // Write the current hash to the URL writeURL(); sortAllFragments(); updateControls(); updateProgress(); updateBackground( true ); updateSlideNumber(); updateSlidesVisibility(); updateNotes(); formatEmbeddedContent(); startEmbeddedContent( currentSlide ); if( isOverview() ) { layoutOverview(); } } /** * Resets all vertical slides so that only the first * is visible. */ function resetVerticalSlides() { var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ); horizontalSlides.forEach( function( horizontalSlide ) { var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) ); verticalSlides.forEach( function( verticalSlide, y ) { if( y > 0 ) { verticalSlide.classList.remove( 'present' ); verticalSlide.classList.remove( 'past' ); verticalSlide.classList.add( 'future' ); verticalSlide.setAttribute( 'aria-hidden', 'true' ); } } ); } ); } /** * Sorts and formats all of fragments in the * presentation. */ function sortAllFragments() { var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ); horizontalSlides.forEach( function( horizontalSlide ) { var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) ); verticalSlides.forEach( function( verticalSlide, y ) { sortFragments( verticalSlide.querySelectorAll( '.fragment' ) ); } ); if( verticalSlides.length === 0 ) sortFragments( horizontalSlide.querySelectorAll( '.fragment' ) ); } ); } /** * Updates one dimension of slides by showing the slide * with the specified index. * * @param {String} selector A CSS selector that will fetch * the group of slides we are working with * @param {Number} index The index of the slide that should be * shown * * @return {Number} The index of the slide that is now shown, * might differ from the passed in index if it was out of * bounds. */ function updateSlides( selector, index ) { // Select all slides and convert the NodeList result to // an array var slides = toArray( dom.wrapper.querySelectorAll( selector ) ), slidesLength = slides.length; var printMode = isPrintingPDF(); if( slidesLength ) { // Should the index loop? if( config.loop ) { index %= slidesLength; if( index < 0 ) { index = slidesLength + index; } } // Enforce max and minimum index bounds index = Math.max( Math.min( index, slidesLength - 1 ), 0 ); for( var i = 0; i < slidesLength; i++ ) { var element = slides[i]; var reverse = config.rtl && !isVerticalSlide( element ); element.classList.remove( 'past' ); element.classList.remove( 'present' ); element.classList.remove( 'future' ); // http://www.w3.org/html/wg/drafts/html/master/editing.html#the-hidden-attribute element.setAttribute( 'hidden', '' ); element.setAttribute( 'aria-hidden', 'true' ); // If this element contains vertical slides if( element.querySelector( 'section' ) ) { element.classList.add( 'stack' ); } // If we're printing static slides, all slides are "present" if( printMode ) { element.classList.add( 'present' ); continue; } if( i < index ) { // Any element previous to index is given the 'past' class element.classList.add( reverse ? 'future' : 'past' ); if( config.fragments ) { var pastFragments = toArray( element.querySelectorAll( '.fragment' ) ); // Show all fragments on prior slides while( pastFragments.length ) { var pastFragment = pastFragments.pop(); pastFragment.classList.add( 'visible' ); pastFragment.classList.remove( 'current-fragment' ); } } } else if( i > index ) { // Any element subsequent to index is given the 'future' class element.classList.add( reverse ? 'past' : 'future' ); if( config.fragments ) { var futureFragments = toArray( element.querySelectorAll( '.fragment.visible' ) ); // No fragments in future slides should be visible ahead of time while( futureFragments.length ) { var futureFragment = futureFragments.pop(); futureFragment.classList.remove( 'visible' ); futureFragment.classList.remove( 'current-fragment' ); } } } } // Mark the current slide as present slides[index].classList.add( 'present' ); slides[index].removeAttribute( 'hidden' ); slides[index].removeAttribute( 'aria-hidden' ); // If this slide has a state associated with it, add it // onto the current state of the deck var slideState = slides[index].getAttribute( 'data-state' ); if( slideState ) { state = state.concat( slideState.split( ' ' ) ); } } else { // Since there are no slides we can't be anywhere beyond the // zeroth index index = 0; } return index; } /** * Optimization method; hide all slides that are far away * from the present slide. */ function updateSlidesVisibility() { // Select all slides and convert the NodeList result to // an array var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ), horizontalSlidesLength = horizontalSlides.length, distanceX, distanceY; if( horizontalSlidesLength && typeof indexh !== 'undefined' ) { // The number of steps away from the present slide that will // be visible var viewDistance = isOverview() ? 10 : config.viewDistance; // Limit view distance on weaker devices if( isMobileDevice ) { viewDistance = isOverview() ? 6 : 2; } // All slides need to be visible when exporting to PDF if( isPrintingPDF() ) { viewDistance = Number.MAX_VALUE; } for( var x = 0; x < horizontalSlidesLength; x++ ) { var horizontalSlide = horizontalSlides[x]; var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) ), verticalSlidesLength = verticalSlides.length; // Determine how far away this slide is from the present distanceX = Math.abs( ( indexh || 0 ) - x ) || 0; // If the presentation is looped, distance should measure // 1 between the first and last slides if( config.loop ) { distanceX = Math.abs( ( ( indexh || 0 ) - x ) % ( horizontalSlidesLength - viewDistance ) ) || 0; } // Show the horizontal slide if it's within the view distance if( distanceX < viewDistance ) { showSlide( horizontalSlide ); } else { hideSlide( horizontalSlide ); } if( verticalSlidesLength ) { var oy = getPreviousVerticalIndex( horizontalSlide ); for( var y = 0; y < verticalSlidesLength; y++ ) { var verticalSlide = verticalSlides[y]; distanceY = x === ( indexh || 0 ) ? Math.abs( ( indexv || 0 ) - y ) : Math.abs( y - oy ); if( distanceX + distanceY < viewDistance ) { showSlide( verticalSlide ); } else { hideSlide( verticalSlide ); } } } } } } /** * Pick up notes from the current slide and display tham * to the viewer. * * @see `showNotes` config value */ function updateNotes() { if( config.showNotes && dom.speakerNotes && currentSlide && !isPrintingPDF() ) { dom.speakerNotes.innerHTML = getSlideNotes() || ''; } } /** * Updates the progress bar to reflect the current slide. */ function updateProgress() { // Update progress if enabled if( config.progress && dom.progressbar ) { dom.progressbar.style.width = getProgress() * dom.wrapper.offsetWidth + 'px'; } } /** * Updates the slide number div to reflect the current slide. * * The following slide number formats are available: * "h.v": horizontal . vertical slide number (default) * "h/v": horizontal / vertical slide number * "c": flattened slide number * "c/t": flattened slide number / total slides */ function updateSlideNumber() { // Update slide number if enabled if( config.slideNumber && dom.slideNumber ) { var value = []; var format = 'h.v'; // Check if a custom number format is available if( typeof config.slideNumber === 'string' ) { format = config.slideNumber; } switch( format ) { case 'c': value.push( getSlidePastCount() + 1 ); break; case 'c/t': value.push( getSlidePastCount() + 1, '/', getTotalSlides() ); break; case 'h/v': value.push( indexh + 1 ); if( isVerticalSlide() ) value.push( '/', indexv + 1 ); break; default: value.push( indexh + 1 ); if( isVerticalSlide() ) value.push( '.', indexv + 1 ); } dom.slideNumber.innerHTML = formatSlideNumber( value[0], value[1], value[2] ); } } /** * Applies HTML formatting to a slide number before it's * written to the DOM. */ function formatSlideNumber( a, delimiter, b ) { if( typeof b === 'number' && !isNaN( b ) ) { return '<span class="slide-number-a">'+ a +'</span>' + '<span class="slide-number-delimiter">'+ delimiter +'</span>' + '<span class="slide-number-b">'+ b +'</span>'; } else { return '<span class="slide-number-a">'+ a +'</span>'; } } /** * Updates the state of all control/navigation arrows. */ function updateControls() { var routes = availableRoutes(); var fragments = availableFragments(); // Remove the 'enabled' class from all directions dom.controlsLeft.concat( dom.controlsRight ) .concat( dom.controlsUp ) .concat( dom.controlsDown ) .concat( dom.controlsPrev ) .concat( dom.controlsNext ).forEach( function( node ) { node.classList.remove( 'enabled' ); node.classList.remove( 'fragmented' ); } ); // Add the 'enabled' class to the available routes if( routes.left ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'enabled' ); } ); if( routes.right ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'enabled' ); } ); if( routes.up ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'enabled' ); } ); if( routes.down ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'enabled' ); } ); // Prev/next buttons if( routes.left || routes.up ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'enabled' ); } ); if( routes.right || routes.down ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'enabled' ); } ); // Highlight fragment directions if( currentSlide ) { // Always apply fragment decorator to prev/next buttons if( fragments.prev ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } ); if( fragments.next ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } ); // Apply fragment decorators to directional buttons based on // what slide axis they are in if( isVerticalSlide( currentSlide ) ) { if( fragments.prev ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } ); if( fragments.next ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } ); } else { if( fragments.prev ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } ); if( fragments.next ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } ); } } } /** * Updates the background elements to reflect the current * slide. * * @param {Boolean} includeAll If true, the backgrounds of * all vertical slides (not just the present) will be updated. */ function updateBackground( includeAll ) { var currentBackground = null; // Reverse past/future classes when in RTL mode var horizontalPast = config.rtl ? 'future' : 'past', horizontalFuture = config.rtl ? 'past' : 'future'; // Update the classes of all backgrounds to match the // states of their slides (past/present/future) toArray( dom.background.childNodes ).forEach( function( backgroundh, h ) { backgroundh.classList.remove( 'past' ); backgroundh.classList.remove( 'present' ); backgroundh.classList.remove( 'future' ); if( h < indexh ) { backgroundh.classList.add( horizontalPast ); } else if ( h > indexh ) { backgroundh.classList.add( horizontalFuture ); } else { backgroundh.classList.add( 'present' ); // Store a reference to the current background element currentBackground = backgroundh; } if( includeAll || h === indexh ) { toArray( backgroundh.querySelectorAll( '.slide-background' ) ).forEach( function( backgroundv, v ) { backgroundv.classList.remove( 'past' ); backgroundv.classList.remove( 'present' ); backgroundv.classList.remove( 'future' ); if( v < indexv ) { backgroundv.classList.add( 'past' ); } else if ( v > indexv ) { backgroundv.classList.add( 'future' ); } else { backgroundv.classList.add( 'present' ); // Only if this is the present horizontal and vertical slide if( h === indexh ) currentBackground = backgroundv; } } ); } } ); // Stop any currently playing video background if( previousBackground ) { var previousVideo = previousBackground.querySelector( 'video' ); if( previousVideo ) previousVideo.pause(); } if( currentBackground ) { // Start video playback var currentVideo = currentBackground.querySelector( 'video' ); if( currentVideo ) { if( currentVideo.currentTime > 0 ) currentVideo.currentTime = 0; currentVideo.play(); } var backgroundImageURL = currentBackground.style.backgroundImage || ''; // Restart GIFs (doesn't work in Firefox) if( /\.gif/i.test( backgroundImageURL ) ) { currentBackground.style.backgroundImage = ''; window.getComputedStyle( currentBackground ).opacity; currentBackground.style.backgroundImage = backgroundImageURL; } // Don't transition between identical backgrounds. This // prevents unwanted flicker. var previousBackgroundHash = previousBackground ? previousBackground.getAttribute( 'data-background-hash' ) : null; var currentBackgroundHash = currentBackground.getAttribute( 'data-background-hash' ); if( currentBackgroundHash && currentBackgroundHash === previousBackgroundHash && currentBackground !== previousBackground ) { dom.background.classList.add( 'no-transition' ); } previousBackground = currentBackground; } // If there's a background brightness flag for this slide, // bubble it to the .reveal container if( currentSlide ) { [ 'has-light-background', 'has-dark-background' ].forEach( function( classToBubble ) { if( currentSlide.classList.contains( classToBubble ) ) { dom.wrapper.classList.add( classToBubble ); } else { dom.wrapper.classList.remove( classToBubble ); } } ); } // Allow the first background to apply without transition setTimeout( function() { dom.background.classList.remove( 'no-transition' ); }, 1 ); } /** * Updates the position of the parallax background based * on the current slide index. */ function updateParallax() { if( config.parallaxBackgroundImage ) { var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ), verticalSlides = dom.wrapper.querySelectorAll( VERTICAL_SLIDES_SELECTOR ); var backgroundSize = dom.background.style.backgroundSize.split( ' ' ), backgroundWidth, backgroundHeight; if( backgroundSize.length === 1 ) { backgroundWidth = backgroundHeight = parseInt( backgroundSize[0], 10 ); } else { backgroundWidth = parseInt( backgroundSize[0], 10 ); backgroundHeight = parseInt( backgroundSize[1], 10 ); } var slideWidth = dom.background.offsetWidth, horizontalSlideCount = horizontalSlides.length, horizontalOffsetMultiplier, horizontalOffset; if( typeof config.parallaxBackgroundHorizontal === 'number' ) { horizontalOffsetMultiplier = config.parallaxBackgroundHorizontal; } else { horizontalOffsetMultiplier = ( backgroundWidth - slideWidth ) / ( horizontalSlideCount-1 ); } horizontalOffset = horizontalOffsetMultiplier * indexh * -1; var slideHeight = dom.background.offsetHeight, verticalSlideCount = verticalSlides.length, verticalOffsetMultiplier, verticalOffset; if( typeof config.parallaxBackgroundVertical === 'number' ) { verticalOffsetMultiplier = config.parallaxBackgroundVertical; } else { verticalOffsetMultiplier = ( backgroundHeight - slideHeight ) / ( verticalSlideCount-1 ); } verticalOffset = verticalSlideCount > 0 ? verticalOffsetMultiplier * indexv * 1 : 0; dom.background.style.backgroundPosition = horizontalOffset + 'px ' + -verticalOffset + 'px'; } } /** * Called when the given slide is within the configured view * distance. Shows the slide element and loads any content * that is set to load lazily (data-src). */ function showSlide( slide ) { // Show the slide element slide.style.display = 'block'; // Media elements with data-src attributes toArray( slide.querySelectorAll( 'img[data-src], video[data-src], audio[data-src]' ) ).forEach( function( element ) { element.setAttribute( 'src', element.getAttribute( 'data-src' ) ); element.removeAttribute( 'data-src' ); } ); // Media elements with <source> children toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( media ) { var sources = 0; toArray( media.querySelectorAll( 'source[data-src]' ) ).forEach( function( source ) { source.setAttribute( 'src', source.getAttribute( 'data-src' ) ); source.removeAttribute( 'data-src' ); sources += 1; } ); // If we rewrote sources for this video/audio element, we need // to manually tell it to load from its new origin if( sources > 0 ) { media.load(); } } ); // Show the corresponding background element var indices = getIndices( slide ); var background = getSlideBackground( indices.h, indices.v ); if( background ) { background.style.display = 'block'; // If the background contains media, load it if( background.hasAttribute( 'data-loaded' ) === false ) { background.setAttribute( 'data-loaded', 'true' ); var backgroundImage = slide.getAttribute( 'data-background-image' ), backgroundVideo = slide.getAttribute( 'data-background-video' ), backgroundVideoLoop = slide.hasAttribute( 'data-background-video-loop' ), backgroundIframe = slide.getAttribute( 'data-background-iframe' ); // Images if( backgroundImage ) { background.style.backgroundImage = 'url('+ backgroundImage +')'; } // Videos else if ( backgroundVideo && !isSpeakerNotes() ) { var video = document.createElement( 'video' ); if( backgroundVideoLoop ) { video.setAttribute( 'loop', '' ); } // Support comma separated lists of video sources backgroundVideo.split( ',' ).forEach( function( source ) { video.innerHTML += '<source src="'+ source +'">'; } ); background.appendChild( video ); } // Iframes else if( backgroundIframe ) { var iframe = document.createElement( 'iframe' ); iframe.setAttribute( 'src', backgroundIframe ); iframe.style.width = '100%'; iframe.style.height = '100%'; iframe.style.maxHeight = '100%'; iframe.style.maxWidth = '100%'; background.appendChild( iframe ); } } } } /** * Called when the given slide is moved outside of the * configured view distance. */ function hideSlide( slide ) { // Hide the slide element slide.style.display = 'none'; // Hide the corresponding background element var indices = getIndices( slide ); var background = getSlideBackground( indices.h, indices.v ); if( background ) { background.style.display = 'none'; } } /** * Determine what available routes there are for navigation. * * @return {Object} containing four booleans: left/right/up/down */ function availableRoutes() { var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ), verticalSlides = dom.wrapper.querySelectorAll( VERTICAL_SLIDES_SELECTOR ); var routes = { left: indexh > 0 || config.loop, right: indexh < horizontalSlides.length - 1 || config.loop, up: indexv > 0, down: indexv < verticalSlides.length - 1 }; // reverse horizontal controls for rtl if( config.rtl ) { var left = routes.left; routes.left = routes.right; routes.right = left; } return routes; } /** * Returns an object describing the available fragment * directions. * * @return {Object} two boolean properties: prev/next */ function availableFragments() { if( currentSlide && config.fragments ) { var fragments = currentSlide.querySelectorAll( '.fragment' ); var hiddenFragments = currentSlide.querySelectorAll( '.fragment:not(.visible)' ); return { prev: fragments.length - hiddenFragments.length > 0, next: !!hiddenFragments.length }; } else { return { prev: false, next: false }; } } /** * Enforces origin-specific format rules for embedded media. */ function formatEmbeddedContent() { var _appendParamToIframeSource = function( sourceAttribute, sourceURL, param ) { toArray( dom.slides.querySelectorAll( 'iframe['+ sourceAttribute +'*="'+ sourceURL +'"]' ) ).forEach( function( el ) { var src = el.getAttribute( sourceAttribute ); if( src && src.indexOf( param ) === -1 ) { el.setAttribute( sourceAttribute, src + ( !/\?/.test( src ) ? '?' : '&' ) + param ); } }); }; // YouTube frames must include "?enablejsapi=1" _appendParamToIframeSource( 'src', 'youtube.com/embed/', 'enablejsapi=1' ); _appendParamToIframeSource( 'data-src', 'youtube.com/embed/', 'enablejsapi=1' ); // Vimeo frames must include "?api=1" _appendParamToIframeSource( 'src', 'player.vimeo.com/', 'api=1' ); _appendParamToIframeSource( 'data-src', 'player.vimeo.com/', 'api=1' ); } /** * Start playback of any embedded content inside of * the targeted slide. */ function startEmbeddedContent( slide ) { if( slide && !isSpeakerNotes() ) { // Restart GIFs toArray( slide.querySelectorAll( 'img[src$=".gif"]' ) ).forEach( function( el ) { // Setting the same unchanged source like this was confirmed // to work in Chrome, FF & Safari el.setAttribute( 'src', el.getAttribute( 'src' ) ); } ); // HTML5 media elements toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) { if( el.hasAttribute( 'data-autoplay' ) && typeof el.play === 'function' ) { el.play(); } } ); // Normal iframes toArray( slide.querySelectorAll( 'iframe[src]' ) ).forEach( function( el ) { startEmbeddedIframe( { target: el } ); } ); // Lazy loading iframes toArray( slide.querySelectorAll( 'iframe[data-src]' ) ).forEach( function( el ) { if( el.getAttribute( 'src' ) !== el.getAttribute( 'data-src' ) ) { el.removeEventListener( 'load', startEmbeddedIframe ); // remove first to avoid dupes el.addEventListener( 'load', startEmbeddedIframe ); el.setAttribute( 'src', el.getAttribute( 'data-src' ) ); } } ); } } /** * "Starts" the content of an embedded iframe using the * postmessage API. */ function startEmbeddedIframe( event ) { var iframe = event.target; // YouTube postMessage API if( /youtube\.com\/embed\//.test( iframe.getAttribute( 'src' ) ) && iframe.hasAttribute( 'data-autoplay' ) ) { iframe.contentWindow.postMessage( '{"event":"command","func":"playVideo","args":""}', '*' ); } // Vimeo postMessage API else if( /player\.vimeo\.com\//.test( iframe.getAttribute( 'src' ) ) && iframe.hasAttribute( 'data-autoplay' ) ) { iframe.contentWindow.postMessage( '{"method":"play"}', '*' ); } // Generic postMessage API else { iframe.contentWindow.postMessage( 'slide:start', '*' ); } } /** * Stop playback of any embedded content inside of * the targeted slide. */ function stopEmbeddedContent( slide ) { if( slide && slide.parentNode ) { // HTML5 media elements toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) { if( !el.hasAttribute( 'data-ignore' ) && typeof el.pause === 'function' ) { el.pause(); } } ); // Generic postMessage API for non-lazy loaded iframes toArray( slide.querySelectorAll( 'iframe' ) ).forEach( function( el ) { el.contentWindow.postMessage( 'slide:stop', '*' ); el.removeEventListener( 'load', startEmbeddedIframe ); }); // YouTube postMessage API toArray( slide.querySelectorAll( 'iframe[src*="youtube.com/embed/"]' ) ).forEach( function( el ) { if( !el.hasAttribute( 'data-ignore' ) && typeof el.contentWindow.postMessage === 'function' ) { el.contentWindow.postMessage( '{"event":"command","func":"pauseVideo","args":""}', '*' ); } }); // Vimeo postMessage API toArray( slide.querySelectorAll( 'iframe[src*="player.vimeo.com/"]' ) ).forEach( function( el ) { if( !el.hasAttribute( 'data-ignore' ) && typeof el.contentWindow.postMessage === 'function' ) { el.contentWindow.postMessage( '{"method":"pause"}', '*' ); } }); // Lazy loading iframes toArray( slide.querySelectorAll( 'iframe[data-src]' ) ).forEach( function( el ) { // Only removing the src doesn't actually unload the frame // in all browsers (Firefox) so we set it to blank first el.setAttribute( 'src', 'about:blank' ); el.removeAttribute( 'src' ); } ); } } /** * Returns the number of past slides. This can be used as a global * flattened index for slides. */ function getSlidePastCount() { var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ); // The number of past slides var pastCount = 0; // Step through all slides and count the past ones mainLoop: for( var i = 0; i < horizontalSlides.length; i++ ) { var horizontalSlide = horizontalSlides[i]; var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) ); for( var j = 0; j < verticalSlides.length; j++ ) { // Stop as soon as we arrive at the present if( verticalSlides[j].classList.contains( 'present' ) ) { break mainLoop; } pastCount++; } // Stop as soon as we arrive at the present if( horizontalSlide.classList.contains( 'present' ) ) { break; } // Don't count the wrapping section for vertical slides if( horizontalSlide.classList.contains( 'stack' ) === false ) { pastCount++; } } return pastCount; } /** * Returns a value ranging from 0-1 that represents * how far into the presentation we have navigated. */ function getProgress() { // The number of past and total slides var totalCount = getTotalSlides(); var pastCount = getSlidePastCount(); if( currentSlide ) { var allFragments = currentSlide.querySelectorAll( '.fragment' ); // If there are fragments in the current slide those should be // accounted for in the progress. if( allFragments.length > 0 ) { var visibleFragments = currentSlide.querySelectorAll( '.fragment.visible' ); // This value represents how big a portion of the slide progress // that is made up by its fragments (0-1) var fragmentWeight = 0.9; // Add fragment progress to the past slide count pastCount += ( visibleFragments.length / allFragments.length ) * fragmentWeight; } } return pastCount / ( totalCount - 1 ); } /** * Checks if this presentation is running inside of the * speaker notes window. */ function isSpeakerNotes() { return !!window.location.search.match( /receiver/gi ); } /** * Reads the current URL (hash) and navigates accordingly. */ function readURL() { var hash = window.location.hash; // Attempt to parse the hash as either an index or name var bits = hash.slice( 2 ).split( '/' ), name = hash.replace( /#|\//gi, '' ); // If the first bit is invalid and there is a name we can // assume that this is a named link if( isNaN( parseInt( bits[0], 10 ) ) && name.length ) { var element; // Ensure the named link is a valid HTML ID attribute if( /^[a-zA-Z][\w:.-]*$/.test( name ) ) { // Find the slide with the specified ID element = document.getElementById( name ); } if( element ) { // Find the position of the named slide and navigate to it var indices = Reveal.getIndices( element ); slide( indices.h, indices.v ); } // If the slide doesn't exist, navigate to the current slide else { slide( indexh || 0, indexv || 0 ); } } else { // Read the index components of the hash var h = parseInt( bits[0], 10 ) || 0, v = parseInt( bits[1], 10 ) || 0; if( h !== indexh || v !== indexv ) { slide( h, v ); } } } /** * Updates the page URL (hash) to reflect the current * state. * * @param {Number} delay The time in ms to wait before * writing the hash */ function writeURL( delay ) { if( config.history ) { // Make sure there's never more than one timeout running clearTimeout( writeURLTimeout ); // If a delay is specified, timeout this call if( typeof delay === 'number' ) { writeURLTimeout = setTimeout( writeURL, delay ); } else if( currentSlide ) { var url = '/'; // Attempt to create a named link based on the slide's ID var id = currentSlide.getAttribute( 'id' ); if( id ) { id = id.replace( /[^a-zA-Z0-9\-\_\:\.]/g, '' ); } // If the current slide has an ID, use that as a named link if( typeof id === 'string' && id.length ) { url = '/' + id; } // Otherwise use the /h/v index else { if( indexh > 0 || indexv > 0 ) url += indexh; if( indexv > 0 ) url += '/' + indexv; } window.location.hash = url; } } } /** * Retrieves the h/v location of the current, or specified, * slide. * * @param {HTMLElement} slide If specified, the returned * index will be for this slide rather than the currently * active one * * @return {Object} { h: <int>, v: <int>, f: <int> } */ function getIndices( slide ) { // By default, return the current indices var h = indexh, v = indexv, f; // If a slide is specified, return the indices of that slide if( slide ) { var isVertical = isVerticalSlide( slide ); var slideh = isVertical ? slide.parentNode : slide; // Select all horizontal slides var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ); // Now that we know which the horizontal slide is, get its index h = Math.max( horizontalSlides.indexOf( slideh ), 0 ); // Assume we're not vertical v = undefined; // If this is a vertical slide, grab the vertical index if( isVertical ) { v = Math.max( toArray( slide.parentNode.querySelectorAll( 'section' ) ).indexOf( slide ), 0 ); } } if( !slide && currentSlide ) { var hasFragments = currentSlide.querySelectorAll( '.fragment' ).length > 0; if( hasFragments ) { var currentFragment = currentSlide.querySelector( '.current-fragment' ); if( currentFragment && currentFragment.hasAttribute( 'data-fragment-index' ) ) { f = parseInt( currentFragment.getAttribute( 'data-fragment-index' ), 10 ); } else { f = currentSlide.querySelectorAll( '.fragment.visible' ).length - 1; } } } return { h: h, v: v, f: f }; } /** * Retrieves the total number of slides in this presentation. */ function getTotalSlides() { return dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ':not(.stack)' ).length; } /** * Returns the slide element matching the specified index. */ function getSlide( x, y ) { var horizontalSlide = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR )[ x ]; var verticalSlides = horizontalSlide && horizontalSlide.querySelectorAll( 'section' ); if( verticalSlides && verticalSlides.length && typeof y === 'number' ) { return verticalSlides ? verticalSlides[ y ] : undefined; } return horizontalSlide; } /** * Returns the background element for the given slide. * All slides, even the ones with no background properties * defined, have a background element so as long as the * index is valid an element will be returned. */ function getSlideBackground( x, y ) { // When printing to PDF the slide backgrounds are nested // inside of the slides if( isPrintingPDF() ) { var slide = getSlide( x, y ); if( slide ) { var background = slide.querySelector( '.slide-background' ); if( background && background.parentNode === slide ) { return background; } } return undefined; } var horizontalBackground = dom.wrapper.querySelectorAll( '.backgrounds>.slide-background' )[ x ]; var verticalBackgrounds = horizontalBackground && horizontalBackground.querySelectorAll( '.slide-background' ); if( verticalBackgrounds && verticalBackgrounds.length && typeof y === 'number' ) { return verticalBackgrounds ? verticalBackgrounds[ y ] : undefined; } return horizontalBackground; } /** * Retrieves the speaker notes from a slide. Notes can be * defined in two ways: * 1. As a data-notes attribute on the slide <section> * 2. As an <aside class="notes"> inside of the slide */ function getSlideNotes( slide ) { // Default to the current slide slide = slide || currentSlide; // Notes can be specified via the data-notes attribute... if( slide.hasAttribute( 'data-notes' ) ) { return slide.getAttribute( 'data-notes' ); } // ... or using an <aside class="notes"> element var notesElement = slide.querySelector( 'aside.notes' ); if( notesElement ) { return notesElement.innerHTML; } return null; } /** * Retrieves the current state of the presentation as * an object. This state can then be restored at any * time. */ function getState() { var indices = getIndices(); return { indexh: indices.h, indexv: indices.v, indexf: indices.f, paused: isPaused(), overview: isOverview() }; } /** * Restores the presentation to the given state. * * @param {Object} state As generated by getState() */ function setState( state ) { if( typeof state === 'object' ) { slide( deserialize( state.indexh ), deserialize( state.indexv ), deserialize( state.indexf ) ); var pausedFlag = deserialize( state.paused ), overviewFlag = deserialize( state.overview ); if( typeof pausedFlag === 'boolean' && pausedFlag !== isPaused() ) { togglePause( pausedFlag ); } if( typeof overviewFlag === 'boolean' && overviewFlag !== isOverview() ) { toggleOverview( overviewFlag ); } } } /** * Return a sorted fragments list, ordered by an increasing * "data-fragment-index" attribute. * * Fragments will be revealed in the order that they are returned by * this function, so you can use the index attributes to control the * order of fragment appearance. * * To maintain a sensible default fragment order, fragments are presumed * to be passed in document order. This function adds a "fragment-index" * attribute to each node if such an attribute is not already present, * and sets that attribute to an integer value which is the position of * the fragment within the fragments list. */ function sortFragments( fragments ) { fragments = toArray( fragments ); var ordered = [], unordered = [], sorted = []; // Group ordered and unordered elements fragments.forEach( function( fragment, i ) { if( fragment.hasAttribute( 'data-fragment-index' ) ) { var index = parseInt( fragment.getAttribute( 'data-fragment-index' ), 10 ); if( !ordered[index] ) { ordered[index] = []; } ordered[index].push( fragment ); } else { unordered.push( [ fragment ] ); } } ); // Append fragments without explicit indices in their // DOM order ordered = ordered.concat( unordered ); // Manually count the index up per group to ensure there // are no gaps var index = 0; // Push all fragments in their sorted order to an array, // this flattens the groups ordered.forEach( function( group ) { group.forEach( function( fragment ) { sorted.push( fragment ); fragment.setAttribute( 'data-fragment-index', index ); } ); index ++; } ); return sorted; } /** * Navigate to the specified slide fragment. * * @param {Number} index The index of the fragment that * should be shown, -1 means all are invisible * @param {Number} offset Integer offset to apply to the * fragment index * * @return {Boolean} true if a change was made in any * fragments visibility as part of this call */ function navigateFragment( index, offset ) { if( currentSlide && config.fragments ) { var fragments = sortFragments( currentSlide.querySelectorAll( '.fragment' ) ); if( fragments.length ) { // If no index is specified, find the current if( typeof index !== 'number' ) { var lastVisibleFragment = sortFragments( currentSlide.querySelectorAll( '.fragment.visible' ) ).pop(); if( lastVisibleFragment ) { index = parseInt( lastVisibleFragment.getAttribute( 'data-fragment-index' ) || 0, 10 ); } else { index = -1; } } // If an offset is specified, apply it to the index if( typeof offset === 'number' ) { index += offset; } var fragmentsShown = [], fragmentsHidden = []; toArray( fragments ).forEach( function( element, i ) { if( element.hasAttribute( 'data-fragment-index' ) ) { i = parseInt( element.getAttribute( 'data-fragment-index' ), 10 ); } // Visible fragments if( i <= index ) { if( !element.classList.contains( 'visible' ) ) fragmentsShown.push( element ); element.classList.add( 'visible' ); element.classList.remove( 'current-fragment' ); // Announce the fragments one by one to the Screen Reader dom.statusDiv.textContent = element.textContent; if( i === index ) { element.classList.add( 'current-fragment' ); } } // Hidden fragments else { if( element.classList.contains( 'visible' ) ) fragmentsHidden.push( element ); element.classList.remove( 'visible' ); element.classList.remove( 'current-fragment' ); } } ); if( fragmentsHidden.length ) { dispatchEvent( 'fragmenthidden', { fragment: fragmentsHidden[0], fragments: fragmentsHidden } ); } if( fragmentsShown.length ) { dispatchEvent( 'fragmentshown', { fragment: fragmentsShown[0], fragments: fragmentsShown } ); } updateControls(); updateProgress(); return !!( fragmentsShown.length || fragmentsHidden.length ); } } return false; } /** * Navigate to the next slide fragment. * * @return {Boolean} true if there was a next fragment, * false otherwise */ function nextFragment() { return navigateFragment( null, 1 ); } /** * Navigate to the previous slide fragment. * * @return {Boolean} true if there was a previous fragment, * false otherwise */ function previousFragment() { return navigateFragment( null, -1 ); } /** * Cues a new automated slide if enabled in the config. */ function cueAutoSlide() { cancelAutoSlide(); if( currentSlide ) { var currentFragment = currentSlide.querySelector( '.current-fragment' ); var fragmentAutoSlide = currentFragment ? currentFragment.getAttribute( 'data-autoslide' ) : null; var parentAutoSlide = currentSlide.parentNode ? currentSlide.parentNode.getAttribute( 'data-autoslide' ) : null; var slideAutoSlide = currentSlide.getAttribute( 'data-autoslide' ); // Pick value in the following priority order: // 1. Current fragment's data-autoslide // 2. Current slide's data-autoslide // 3. Parent slide's data-autoslide // 4. Global autoSlide setting if( fragmentAutoSlide ) { autoSlide = parseInt( fragmentAutoSlide, 10 ); } else if( slideAutoSlide ) { autoSlide = parseInt( slideAutoSlide, 10 ); } else if( parentAutoSlide ) { autoSlide = parseInt( parentAutoSlide, 10 ); } else { autoSlide = config.autoSlide; } // If there are media elements with data-autoplay, // automatically set the autoSlide duration to the // length of that media. Not applicable if the slide // is divided up into fragments. if( currentSlide.querySelectorAll( '.fragment' ).length === 0 ) { toArray( currentSlide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) { if( el.hasAttribute( 'data-autoplay' ) ) { if( autoSlide && el.duration * 1000 > autoSlide ) { autoSlide = ( el.duration * 1000 ) + 1000; } } } ); } // Cue the next auto-slide if: // - There is an autoSlide value // - Auto-sliding isn't paused by the user // - The presentation isn't paused // - The overview isn't active // - The presentation isn't over if( autoSlide && !autoSlidePaused && !isPaused() && !isOverview() && ( !Reveal.isLastSlide() || availableFragments().next || config.loop === true ) ) { autoSlideTimeout = setTimeout( navigateNext, autoSlide ); autoSlideStartTime = Date.now(); } if( autoSlidePlayer ) { autoSlidePlayer.setPlaying( autoSlideTimeout !== -1 ); } } } /** * Cancels any ongoing request to auto-slide. */ function cancelAutoSlide() { clearTimeout( autoSlideTimeout ); autoSlideTimeout = -1; } function pauseAutoSlide() { if( autoSlide && !autoSlidePaused ) { autoSlidePaused = true; dispatchEvent( 'autoslidepaused' ); clearTimeout( autoSlideTimeout ); if( autoSlidePlayer ) { autoSlidePlayer.setPlaying( false ); } } } function resumeAutoSlide() { if( autoSlide && autoSlidePaused ) { autoSlidePaused = false; dispatchEvent( 'autoslideresumed' ); cueAutoSlide(); } } function navigateLeft() { // Reverse for RTL if( config.rtl ) { if( ( isOverview() || nextFragment() === false ) && availableRoutes().left ) { slide( indexh + 1 ); } } // Normal navigation else if( ( isOverview() || previousFragment() === false ) && availableRoutes().left ) { slide( indexh - 1 ); } } function navigateRight() { // Reverse for RTL if( config.rtl ) { if( ( isOverview() || previousFragment() === false ) && availableRoutes().right ) { slide( indexh - 1 ); } } // Normal navigation else if( ( isOverview() || nextFragment() === false ) && availableRoutes().right ) { slide( indexh + 1 ); } } function navigateUp() { // Prioritize hiding fragments if( ( isOverview() || previousFragment() === false ) && availableRoutes().up ) { slide( indexh, indexv - 1 ); } } function navigateDown() { // Prioritize revealing fragments if( ( isOverview() || nextFragment() === false ) && availableRoutes().down ) { slide( indexh, indexv + 1 ); } } /** * Navigates backwards, prioritized in the following order: * 1) Previous fragment * 2) Previous vertical slide * 3) Previous horizontal slide */ function navigatePrev() { // Prioritize revealing fragments if( previousFragment() === false ) { if( availableRoutes().up ) { navigateUp(); } else { // Fetch the previous horizontal slide, if there is one var previousSlide; if( config.rtl ) { previousSlide = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.future' ) ).pop(); } else { previousSlide = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.past' ) ).pop(); } if( previousSlide ) { var v = ( previousSlide.querySelectorAll( 'section' ).length - 1 ) || undefined; var h = indexh - 1; slide( h, v ); } } } } /** * The reverse of #navigatePrev(). */ function navigateNext() { // Prioritize revealing fragments if( nextFragment() === false ) { if( availableRoutes().down ) { navigateDown(); } else if( config.rtl ) { navigateLeft(); } else { navigateRight(); } } // If auto-sliding is enabled we need to cue up // another timeout cueAutoSlide(); } /** * Checks if the target element prevents the triggering of * swipe navigation. */ function isSwipePrevented( target ) { while( target && typeof target.hasAttribute === 'function' ) { if( target.hasAttribute( 'data-prevent-swipe' ) ) return true; target = target.parentNode; } return false; } // --------------------------------------------------------------------// // ----------------------------- EVENTS -------------------------------// // --------------------------------------------------------------------// /** * Called by all event handlers that are based on user * input. */ function onUserInput( event ) { if( config.autoSlideStoppable ) { pauseAutoSlide(); } } /** * Handler for the document level 'keypress' event. */ function onDocumentKeyPress( event ) { // Check if the pressed key is question mark if( event.shiftKey && event.charCode === 63 ) { if( dom.overlay ) { closeOverlay(); } else { showHelp( true ); } } } /** * Handler for the document level 'keydown' event. */ function onDocumentKeyDown( event ) { // If there's a condition specified and it returns false, // ignore this event if( typeof config.keyboardCondition === 'function' && config.keyboardCondition() === false ) { return true; } // Remember if auto-sliding was paused so we can toggle it var autoSlideWasPaused = autoSlidePaused; onUserInput( event ); // Check if there's a focused element that could be using // the keyboard var activeElementIsCE = document.activeElement && document.activeElement.contentEditable !== 'inherit'; var activeElementIsInput = document.activeElement && document.activeElement.tagName && /input|textarea/i.test( document.activeElement.tagName ); // Disregard the event if there's a focused element or a // keyboard modifier key is present if( activeElementIsCE || activeElementIsInput || (event.shiftKey && event.keyCode !== 32) || event.altKey || event.ctrlKey || event.metaKey ) return; // While paused only allow resume keyboard events; 'b', '.'' var resumeKeyCodes = [66,190,191]; var key; // Custom key bindings for togglePause should be able to resume if( typeof config.keyboard === 'object' ) { for( key in config.keyboard ) { if( config.keyboard[key] === 'togglePause' ) { resumeKeyCodes.push( parseInt( key, 10 ) ); } } } if( isPaused() && resumeKeyCodes.indexOf( event.keyCode ) === -1 ) { return false; } var triggered = false; // 1. User defined key bindings if( typeof config.keyboard === 'object' ) { for( key in config.keyboard ) { // Check if this binding matches the pressed key if( parseInt( key, 10 ) === event.keyCode ) { var value = config.keyboard[ key ]; // Callback function if( typeof value === 'function' ) { value.apply( null, [ event ] ); } // String shortcuts to reveal.js API else if( typeof value === 'string' && typeof Reveal[ value ] === 'function' ) { Reveal[ value ].call(); } triggered = true; } } } // 2. System defined key bindings if( triggered === false ) { // Assume true and try to prove false triggered = true; switch( event.keyCode ) { // p, page up case 80: case 33: navigatePrev(); break; // n, page down case 78: case 34: navigateNext(); break; // h, left case 72: case 37: navigateLeft(); break; // l, right case 76: case 39: navigateRight(); break; // k, up //case 75: case 38: navigateUp(); break; case 75: navigateUp(); break; // j, down //case 74: case 40: navigateDown(); break; case 74: navigateDown(); break; // home case 36: slide( 0 ); break; // end case 35: slide( Number.MAX_VALUE ); break; // space case 32: isOverview() ? deactivateOverview() : event.shiftKey ? navigatePrev() : navigateNext(); break; // return case 13: isOverview() ? deactivateOverview() : triggered = false; break; // two-spot, semicolon, b, period, Logitech presenter tools "black screen" button case 58: case 59: case 66: case 190: case 191: togglePause(); break; // f case 70: enterFullscreen(); break; // a case 65: if ( config.autoSlideStoppable ) toggleAutoSlide( autoSlideWasPaused ); break; default: triggered = false; } } // If the input resulted in a triggered action we should prevent // the browsers default behavior if( triggered ) { event.preventDefault && event.preventDefault(); } // ESC or O key else if ( ( event.keyCode === 27 || event.keyCode === 79 ) && features.transforms3d ) { if( dom.overlay ) { closeOverlay(); } else { toggleOverview(); } event.preventDefault && event.preventDefault(); } // If auto-sliding is enabled we need to cue up // another timeout cueAutoSlide(); } /** * Handler for the 'touchstart' event, enables support for * swipe and pinch gestures. */ function onTouchStart( event ) { if( isSwipePrevented( event.target ) ) return true; touch.startX = event.touches[0].clientX; touch.startY = event.touches[0].clientY; touch.startCount = event.touches.length; // If there's two touches we need to memorize the distance // between those two points to detect pinching if( event.touches.length === 2 && config.overview ) { touch.startSpan = distanceBetween( { x: event.touches[1].clientX, y: event.touches[1].clientY }, { x: touch.startX, y: touch.startY } ); } } /** * Handler for the 'touchmove' event. */ function onTouchMove( event ) { if( isSwipePrevented( event.target ) ) return true; // Each touch should only trigger one action if( !touch.captured ) { onUserInput( event ); var currentX = event.touches[0].clientX; var currentY = event.touches[0].clientY; // If the touch started with two points and still has // two active touches; test for the pinch gesture if( event.touches.length === 2 && touch.startCount === 2 && config.overview ) { // The current distance in pixels between the two touch points var currentSpan = distanceBetween( { x: event.touches[1].clientX, y: event.touches[1].clientY }, { x: touch.startX, y: touch.startY } ); // If the span is larger than the desire amount we've got // ourselves a pinch if( Math.abs( touch.startSpan - currentSpan ) > touch.threshold ) { touch.captured = true; if( currentSpan < touch.startSpan ) { activateOverview(); } else { deactivateOverview(); } } event.preventDefault(); } // There was only one touch point, look for a swipe else if( event.touches.length === 1 && touch.startCount !== 2 ) { var deltaX = currentX - touch.startX, deltaY = currentY - touch.startY; if( deltaX > touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) { touch.captured = true; navigateLeft(); } else if( deltaX < -touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) { touch.captured = true; navigateRight(); } else if( deltaY > touch.threshold ) { touch.captured = true; navigateUp(); } else if( deltaY < -touch.threshold ) { touch.captured = true; navigateDown(); } // If we're embedded, only block touch events if they have // triggered an action if( config.embedded ) { if( touch.captured || isVerticalSlide( currentSlide ) ) { event.preventDefault(); } } // Not embedded? Block them all to avoid needless tossing // around of the viewport in iOS else { event.preventDefault(); } } } // There's a bug with swiping on some Android devices unless // the default action is always prevented else if( navigator.userAgent.match( /android/gi ) ) { event.preventDefault(); } } /** * Handler for the 'touchend' event. */ function onTouchEnd( event ) { touch.captured = false; } /** * Convert pointer down to touch start. */ function onPointerDown( event ) { if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) { event.touches = [{ clientX: event.clientX, clientY: event.clientY }]; onTouchStart( event ); } } /** * Convert pointer move to touch move. */ function onPointerMove( event ) { if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) { event.touches = [{ clientX: event.clientX, clientY: event.clientY }]; onTouchMove( event ); } } /** * Convert pointer up to touch end. */ function onPointerUp( event ) { if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) { event.touches = [{ clientX: event.clientX, clientY: event.clientY }]; onTouchEnd( event ); } } /** * Handles mouse wheel scrolling, throttled to avoid skipping * multiple slides. */ function onDocumentMouseScroll( event ) { if( Date.now() - lastMouseWheelStep > 600 ) { lastMouseWheelStep = Date.now(); var delta = event.detail || -event.wheelDelta; if( delta > 0 ) { navigateNext(); } else { navigatePrev(); } } } /** * Clicking on the progress bar results in a navigation to the * closest approximate horizontal slide using this equation: * * ( clickX / presentationWidth ) * numberOfSlides */ function onProgressClicked( event ) { onUserInput( event ); event.preventDefault(); var slidesTotal = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).length; var slideIndex = Math.floor( ( event.clientX / dom.wrapper.offsetWidth ) * slidesTotal ); if( config.rtl ) { slideIndex = slidesTotal - slideIndex; } slide( slideIndex ); } /** * Event handler for navigation control buttons. */ function onNavigateLeftClicked( event ) { event.preventDefault(); onUserInput(); navigateLeft(); } function onNavigateRightClicked( event ) { event.preventDefault(); onUserInput(); navigateRight(); } function onNavigateUpClicked( event ) { event.preventDefault(); onUserInput(); navigateUp(); } function onNavigateDownClicked( event ) { event.preventDefault(); onUserInput(); navigateDown(); } function onNavigatePrevClicked( event ) { event.preventDefault(); onUserInput(); navigatePrev(); } function onNavigateNextClicked( event ) { event.preventDefault(); onUserInput(); navigateNext(); } /** * Handler for the window level 'hashchange' event. */ function onWindowHashChange( event ) { readURL(); } /** * Handler for the window level 'resize' event. */ function onWindowResize( event ) { layout(); } /** * Handle for the window level 'visibilitychange' event. */ function onPageVisibilityChange( event ) { var isHidden = document.webkitHidden || document.msHidden || document.hidden; // If, after clicking a link or similar and we're coming back, // focus the document.body to ensure we can use keyboard shortcuts if( isHidden === false && document.activeElement !== document.body ) { // Not all elements support .blur() - SVGs among them. if( typeof document.activeElement.blur === 'function' ) { document.activeElement.blur(); } document.body.focus(); } } /** * Invoked when a slide is and we're in the overview. */ function onOverviewSlideClicked( event ) { // TODO There's a bug here where the event listeners are not // removed after deactivating the overview. if( eventsAreBound && isOverview() ) { event.preventDefault(); var element = event.target; while( element && !element.nodeName.match( /section/gi ) ) { element = element.parentNode; } if( element && !element.classList.contains( 'disabled' ) ) { deactivateOverview(); if( element.nodeName.match( /section/gi ) ) { var h = parseInt( element.getAttribute( 'data-index-h' ), 10 ), v = parseInt( element.getAttribute( 'data-index-v' ), 10 ); slide( h, v ); } } } } /** * Handles clicks on links that are set to preview in the * iframe overlay. */ function onPreviewLinkClicked( event ) { if( event.currentTarget && event.currentTarget.hasAttribute( 'href' ) ) { var url = event.currentTarget.getAttribute( 'href' ); if( url ) { showPreview( url ); event.preventDefault(); } } } /** * Handles click on the auto-sliding controls element. */ function onAutoSlidePlayerClick( event ) { // Replay if( Reveal.isLastSlide() && config.loop === false ) { slide( 0, 0 ); resumeAutoSlide(); } // Resume else if( autoSlidePaused ) { resumeAutoSlide(); } // Pause else { pauseAutoSlide(); } } // --------------------------------------------------------------------// // ------------------------ PLAYBACK COMPONENT ------------------------// // --------------------------------------------------------------------// /** * Constructor for the playback component, which displays * play/pause/progress controls. * * @param {HTMLElement} container The component will append * itself to this * @param {Function} progressCheck A method which will be * called frequently to get the current progress on a range * of 0-1 */ function Playback( container, progressCheck ) { // Cosmetics this.diameter = 50; this.thickness = 3; // Flags if we are currently playing this.playing = false; // Current progress on a 0-1 range this.progress = 0; // Used to loop the animation smoothly this.progressOffset = 1; this.container = container; this.progressCheck = progressCheck; this.canvas = document.createElement( 'canvas' ); this.canvas.className = 'playback'; this.canvas.width = this.diameter; this.canvas.height = this.diameter; this.context = this.canvas.getContext( '2d' ); this.container.appendChild( this.canvas ); this.render(); } Playback.prototype.setPlaying = function( value ) { var wasPlaying = this.playing; this.playing = value; // Start repainting if we weren't already if( !wasPlaying && this.playing ) { this.animate(); } else { this.render(); } }; Playback.prototype.animate = function() { var progressBefore = this.progress; this.progress = this.progressCheck(); // When we loop, offset the progress so that it eases // smoothly rather than immediately resetting if( progressBefore > 0.8 && this.progress < 0.2 ) { this.progressOffset = this.progress; } this.render(); if( this.playing ) { features.requestAnimationFrameMethod.call( window, this.animate.bind( this ) ); } }; /** * Renders the current progress and playback state. */ Playback.prototype.render = function() { var progress = this.playing ? this.progress : 0, radius = ( this.diameter / 2 ) - this.thickness, x = this.diameter / 2, y = this.diameter / 2, iconSize = 14; // Ease towards 1 this.progressOffset += ( 1 - this.progressOffset ) * 0.1; var endAngle = ( - Math.PI / 2 ) + ( progress * ( Math.PI * 2 ) ); var startAngle = ( - Math.PI / 2 ) + ( this.progressOffset * ( Math.PI * 2 ) ); this.context.save(); this.context.clearRect( 0, 0, this.diameter, this.diameter ); // Solid background color this.context.beginPath(); this.context.arc( x, y, radius + 2, 0, Math.PI * 2, false ); this.context.fillStyle = 'rgba( 0, 0, 0, 0.4 )'; this.context.fill(); // Draw progress track this.context.beginPath(); this.context.arc( x, y, radius, 0, Math.PI * 2, false ); this.context.lineWidth = this.thickness; this.context.strokeStyle = '#666'; this.context.stroke(); if( this.playing ) { // Draw progress on top of track this.context.beginPath(); this.context.arc( x, y, radius, startAngle, endAngle, false ); this.context.lineWidth = this.thickness; this.context.strokeStyle = '#fff'; this.context.stroke(); } this.context.translate( x - ( iconSize / 2 ), y - ( iconSize / 2 ) ); // Draw play/pause icons if( this.playing ) { this.context.fillStyle = '#fff'; this.context.fillRect( 0, 0, iconSize / 2 - 2, iconSize ); this.context.fillRect( iconSize / 2 + 2, 0, iconSize / 2 - 2, iconSize ); } else { this.context.beginPath(); this.context.translate( 2, 0 ); this.context.moveTo( 0, 0 ); this.context.lineTo( iconSize - 2, iconSize / 2 ); this.context.lineTo( 0, iconSize ); this.context.fillStyle = '#fff'; this.context.fill(); } this.context.restore(); }; Playback.prototype.on = function( type, listener ) { this.canvas.addEventListener( type, listener, false ); }; Playback.prototype.off = function( type, listener ) { this.canvas.removeEventListener( type, listener, false ); }; Playback.prototype.destroy = function() { this.playing = false; if( this.canvas.parentNode ) { this.container.removeChild( this.canvas ); } }; // --------------------------------------------------------------------// // ------------------------------- API --------------------------------// // --------------------------------------------------------------------// Reveal = { initialize: initialize, configure: configure, sync: sync, // Navigation methods slide: slide, left: navigateLeft, right: navigateRight, up: navigateUp, down: navigateDown, prev: navigatePrev, next: navigateNext, // Fragment methods navigateFragment: navigateFragment, prevFragment: previousFragment, nextFragment: nextFragment, // Deprecated aliases navigateTo: slide, navigateLeft: navigateLeft, navigateRight: navigateRight, navigateUp: navigateUp, navigateDown: navigateDown, navigatePrev: navigatePrev, navigateNext: navigateNext, // Forces an update in slide layout layout: layout, // Returns an object with the available routes as booleans (left/right/top/bottom) availableRoutes: availableRoutes, // Returns an object with the available fragments as booleans (prev/next) availableFragments: availableFragments, // Toggles the overview mode on/off toggleOverview: toggleOverview, // Toggles the "black screen" mode on/off togglePause: togglePause, // Toggles the auto slide mode on/off toggleAutoSlide: toggleAutoSlide, // State checks isOverview: isOverview, isPaused: isPaused, isAutoSliding: isAutoSliding, // Adds or removes all internal event listeners (such as keyboard) addEventListeners: addEventListeners, removeEventListeners: removeEventListeners, // Facility for persisting and restoring the presentation state getState: getState, setState: setState, // Presentation progress on range of 0-1 getProgress: getProgress, // Returns the indices of the current, or specified, slide getIndices: getIndices, getTotalSlides: getTotalSlides, // Returns the slide element at the specified index getSlide: getSlide, // Returns the slide background element at the specified index getSlideBackground: getSlideBackground, // Returns the speaker notes string for a slide, or null getSlideNotes: getSlideNotes, // Returns the previous slide element, may be null getPreviousSlide: function() { return previousSlide; }, // Returns the current slide element getCurrentSlide: function() { return currentSlide; }, // Returns the current scale of the presentation content getScale: function() { return scale; }, // Returns the current configuration object getConfig: function() { return config; }, // Helper method, retrieves query string as a key/value hash getQueryHash: function() { var query = {}; location.search.replace( /[A-Z0-9]+?=([\w\.%-]*)/gi, function(a) { query[ a.split( '=' ).shift() ] = a.split( '=' ).pop(); } ); // Basic deserialization for( var i in query ) { var value = query[ i ]; query[ i ] = deserialize( unescape( value ) ); } return query; }, // Returns true if we're currently on the first slide isFirstSlide: function() { return ( indexh === 0 && indexv === 0 ); }, // Returns true if we're currently on the last slide isLastSlide: function() { if( currentSlide ) { // Does this slide has next a sibling? if( currentSlide.nextElementSibling ) return false; // If it's vertical, does its parent have a next sibling? if( isVerticalSlide( currentSlide ) && currentSlide.parentNode.nextElementSibling ) return false; return true; } return false; }, // Checks if reveal.js has been loaded and is ready for use isReady: function() { return loaded; }, // Forward event binding to the reveal DOM element addEventListener: function( type, listener, useCapture ) { if( 'addEventListener' in window ) { ( dom.wrapper || document.querySelector( '.reveal' ) ).addEventListener( type, listener, useCapture ); } }, removeEventListener: function( type, listener, useCapture ) { if( 'addEventListener' in window ) { ( dom.wrapper || document.querySelector( '.reveal' ) ).removeEventListener( type, listener, useCapture ); } }, // Programatically triggers a keyboard event triggerKey: function( keyCode ) { onDocumentKeyDown( { keyCode: keyCode } ); } }; return Reveal; }));
mit
digimatic/ogre
RenderSystems/GL/src/GLSL/src/OgreGLSLProgram.cpp
21209
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreGpuProgram.h" #include "OgreRoot.h" #include "OgreRenderSystem.h" #include "OgreRenderSystemCapabilities.h" #include "OgreStringConverter.h" #include "OgreGpuProgramManager.h" #include "OgreHighLevelGpuProgramManager.h" #include "OgreLogManager.h" #include "OgreGLSLProgram.h" #include "OgreGLSLGpuProgram.h" #include "OgreGLSLExtSupport.h" #include "OgreGLSLLinkProgramManager.h" #include "OgreGLSLPreprocessor.h" namespace Ogre { namespace GLSL { //----------------------------------------------------------------------- GLSLProgram::CmdPreprocessorDefines GLSLProgram::msCmdPreprocessorDefines; GLSLProgram::CmdAttach GLSLProgram::msCmdAttach; GLSLProgram::CmdColumnMajorMatrices GLSLProgram::msCmdColumnMajorMatrices; GLSLProgram::CmdInputOperationType GLSLProgram::msInputOperationTypeCmd; GLSLProgram::CmdOutputOperationType GLSLProgram::msOutputOperationTypeCmd; GLSLProgram::CmdMaxOutputVertices GLSLProgram::msMaxOutputVerticesCmd; //----------------------------------------------------------------------- //--------------------------------------------------------------------------- GLSLProgram::~GLSLProgram() { // Have to call this here rather than in Resource destructor // since calling virtual methods in base destructors causes crash if (isLoaded()) { unload(); } else { unloadHighLevel(); } } //----------------------------------------------------------------------- void GLSLProgram::loadFromSource(void) { // Preprocess the GLSL shader in order to get a clean source CPreprocessor cpp; // Pass all user-defined macros to preprocessor if (!mPreprocessorDefines.empty ()) { String::size_type pos = 0; while (pos != String::npos) { // Find delims String::size_type endPos = mPreprocessorDefines.find_first_of(";,=", pos); if (endPos != String::npos) { String::size_type macro_name_start = pos; size_t macro_name_len = endPos - pos; pos = endPos; // Check definition part if (mPreprocessorDefines[pos] == '=') { // set up a definition, skip delim ++pos; String::size_type macro_val_start = pos; size_t macro_val_len; endPos = mPreprocessorDefines.find_first_of(";,", pos); if (endPos == String::npos) { macro_val_len = mPreprocessorDefines.size () - pos; pos = endPos; } else { macro_val_len = endPos - pos; pos = endPos+1; } cpp.Define ( mPreprocessorDefines.c_str () + macro_name_start, macro_name_len, mPreprocessorDefines.c_str () + macro_val_start, macro_val_len); } else { // No definition part, define as "1" ++pos; cpp.Define ( mPreprocessorDefines.c_str () + macro_name_start, macro_name_len, 1); } } else pos = endPos; } } size_t out_size = 0; const char *src = mSource.c_str (); size_t src_len = mSource.size (); char *out = cpp.Parse (src, src_len, out_size); if (!out || !out_size) // Failed to preprocess, break out OGRE_EXCEPT (Exception::ERR_RENDERINGAPI_ERROR, "Failed to preprocess shader " + mName, __FUNCTION__); mSource = String (out, out_size); if (out < src || out > src + src_len) free (out); } //--------------------------------------------------------------------------- bool GLSLProgram::compile(const bool checkErrors) { if (mCompiled == 1) { return true; } // only create a shader object if glsl is supported if (isSupported()) { // create shader object GLenum shaderType = 0x0000; switch (mType) { case GPT_VERTEX_PROGRAM: shaderType = GL_VERTEX_SHADER_ARB; break; case GPT_FRAGMENT_PROGRAM: shaderType = GL_FRAGMENT_SHADER_ARB; break; case GPT_GEOMETRY_PROGRAM: shaderType = GL_GEOMETRY_SHADER_EXT; break; case GPT_COMPUTE_PROGRAM: case GPT_DOMAIN_PROGRAM: case GPT_HULL_PROGRAM: break; } mGLHandle = glCreateShaderObjectARB(shaderType); } // Add preprocessor extras and main source if (!mSource.empty()) { const char *source = mSource.c_str(); glShaderSourceARB(mGLHandle, 1, &source, NULL); } if (checkErrors) { logObjectInfo("GLSL compiling: " + mName, mGLHandle); } glCompileShaderARB(mGLHandle); // check for compile errors glGetObjectParameterivARB(mGLHandle, GL_OBJECT_COMPILE_STATUS_ARB, &mCompiled); if(checkErrors) { logObjectInfo(mCompiled ? "GLSL compiled: " : "GLSL compile log: " + mName, mGLHandle); } return (mCompiled == 1); } //----------------------------------------------------------------------- void GLSLProgram::createLowLevelImpl(void) { mAssemblerProgram = GpuProgramPtr(OGRE_NEW GLSLGpuProgram( this )); // Shader params need to be forwarded to low level implementation mAssemblerProgram->setAdjacencyInfoRequired(isAdjacencyInfoRequired()); } //--------------------------------------------------------------------------- void GLSLProgram::unloadImpl() { // We didn't create mAssemblerProgram through a manager, so override this // implementation so that we don't try to remove it from one. Since getCreator() // is used, it might target a different matching handle! mAssemblerProgram.setNull(); unloadHighLevel(); } //----------------------------------------------------------------------- void GLSLProgram::unloadHighLevelImpl(void) { if (isSupported()) { glDeleteObjectARB(mGLHandle); mCompiled = 0; mGLHandle = 0; } } //----------------------------------------------------------------------- void GLSLProgram::populateParameterNames(GpuProgramParametersSharedPtr params) { getConstantDefinitions(); params->_setNamedConstants(mConstantDefs); // Don't set logical / physical maps here, as we can't access parameters by logical index in GLHL. } //----------------------------------------------------------------------- void GLSLProgram::buildConstantDefinitions() const { // We need an accurate list of all the uniforms in the shader, but we // can't get at them until we link all the shaders into a program object. // Therefore instead, parse the source code manually and extract the uniforms createParameterMappingStructures(true); GLSLLinkProgramManager::getSingleton().extractConstantDefs( mSource, *mConstantDefs.get(), mName); // Also parse any attached sources for (GLSLProgramContainer::const_iterator i = mAttachedGLSLPrograms.begin(); i != mAttachedGLSLPrograms.end(); ++i) { GLSLProgram* childShader = *i; GLSLLinkProgramManager::getSingleton().extractConstantDefs( childShader->getSource(), *mConstantDefs.get(), childShader->getName()); } } //----------------------------------------------------------------------- GLSLProgram::GLSLProgram(ResourceManager* creator, const String& name, ResourceHandle handle, const String& group, bool isManual, ManualResourceLoader* loader) : HighLevelGpuProgram(creator, name, handle, group, isManual, loader) , mGLHandle(0) , mCompiled(0) , mInputOperationType(RenderOperation::OT_TRIANGLE_LIST) , mOutputOperationType(RenderOperation::OT_TRIANGLE_LIST) , mMaxOutputVertices(3) , mColumnMajorMatrices(true) { // add parameter command "attach" to the material serializer dictionary if (createParamDictionary("GLSLProgram")) { setupBaseParamDictionary(); ParamDictionary* dict = getParamDictionary(); dict->addParameter(ParameterDef("preprocessor_defines", "Preprocessor defines use to compile the program.", PT_STRING),&msCmdPreprocessorDefines); dict->addParameter(ParameterDef("attach", "name of another GLSL program needed by this program", PT_STRING),&msCmdAttach); dict->addParameter(ParameterDef("column_major_matrices", "Whether matrix packing in column-major order.", PT_BOOL),&msCmdColumnMajorMatrices); dict->addParameter( ParameterDef("input_operation_type", "The input operation type for this geometry program. \ Can be 'point_list', 'line_list', 'line_strip', 'triangle_list', \ 'triangle_strip' or 'triangle_fan'", PT_STRING), &msInputOperationTypeCmd); dict->addParameter( ParameterDef("output_operation_type", "The input operation type for this geometry program. \ Can be 'point_list', 'line_strip' or 'triangle_strip'", PT_STRING), &msOutputOperationTypeCmd); dict->addParameter( ParameterDef("max_output_vertices", "The maximum number of vertices a single run of this geometry program can output", PT_INT),&msMaxOutputVerticesCmd); } // Manually assign language now since we use it immediately mSyntaxCode = "glsl"; } //--------------------------------------------------------------------- bool GLSLProgram::getPassSurfaceAndLightStates(void) const { // scenemanager should pass on light & material state to the rendersystem return true; } //--------------------------------------------------------------------- bool GLSLProgram::getPassTransformStates(void) const { // scenemanager should pass on transform state to the rendersystem return true; } //----------------------------------------------------------------------- String GLSLProgram::CmdAttach::doGet(const void *target) const { return (static_cast<const GLSLProgram*>(target))->getAttachedShaderNames(); } //----------------------------------------------------------------------- void GLSLProgram::CmdAttach::doSet(void *target, const String& shaderNames) { //get all the shader program names: there could be more than one StringVector vecShaderNames = StringUtil::split(shaderNames, " \t", 0); size_t programNameCount = vecShaderNames.size(); for ( size_t i = 0; i < programNameCount; ++i ) { static_cast<GLSLProgram*>(target)->attachChildShader(vecShaderNames[i]); } } //----------------------------------------------------------------------- String GLSLProgram::CmdPreprocessorDefines::doGet(const void *target) const { return static_cast<const GLSLProgram*>(target)->getPreprocessorDefines(); } void GLSLProgram::CmdPreprocessorDefines::doSet(void *target, const String& val) { static_cast<GLSLProgram*>(target)->setPreprocessorDefines(val); } //----------------------------------------------------------------------- void GLSLProgram::attachChildShader(const String& name) { // is the name valid and already loaded? // check with the high level program manager to see if it was loaded HighLevelGpuProgramPtr hlProgram = HighLevelGpuProgramManager::getSingleton().getByName(name); if (!hlProgram.isNull()) { if (hlProgram->getSyntaxCode() == "glsl") { // make sure attached program source gets loaded and compiled // don't need a low level implementation for attached shader objects // loadHighLevelImpl will only load the source and compile once // so don't worry about calling it several times GLSLProgram* childShader = static_cast<GLSLProgram*>(hlProgram.getPointer()); // load the source and attach the child shader only if supported if (isSupported()) { childShader->loadHighLevelImpl(); // add to the container mAttachedGLSLPrograms.push_back( childShader ); mAttachedShaderNames += name + " "; } } } } //----------------------------------------------------------------------- void GLSLProgram::attachToProgramObject( const GLhandleARB programObject ) { // attach child objects GLSLProgramContainerIterator childprogramcurrent = mAttachedGLSLPrograms.begin(); GLSLProgramContainerIterator childprogramend = mAttachedGLSLPrograms.end(); while (childprogramcurrent != childprogramend) { GLSLProgram* childShader = *childprogramcurrent; // bug in ATI GLSL linker : modules without main function must be recompiled each time // they are linked to a different program object // don't check for compile errors since there won't be any // *** minor inconvenience until ATI fixes there driver childShader->compile(false); childShader->attachToProgramObject( programObject ); ++childprogramcurrent; } glAttachObjectARB( programObject, mGLHandle ); GLenum glErr = glGetError(); if(glErr != GL_NO_ERROR) { reportGLSLError( glErr, "GLSLProgram::attachToProgramObject", "Error attaching " + mName + " shader object to GLSL Program Object", programObject ); } } //----------------------------------------------------------------------- void GLSLProgram::detachFromProgramObject( const GLhandleARB programObject ) { glDetachObjectARB(programObject, mGLHandle); GLenum glErr = glGetError(); if(glErr != GL_NO_ERROR) { reportGLSLError( glErr, "GLSLProgram::detachFromProgramObject", "Error detaching " + mName + " shader object from GLSL Program Object", programObject ); } // attach child objects GLSLProgramContainerIterator childprogramcurrent = mAttachedGLSLPrograms.begin(); GLSLProgramContainerIterator childprogramend = mAttachedGLSLPrograms.end(); while (childprogramcurrent != childprogramend) { GLSLProgram* childShader = *childprogramcurrent; childShader->detachFromProgramObject( programObject ); ++childprogramcurrent; } } //----------------------------------------------------------------------- const String& GLSLProgram::getLanguage(void) const { static const String language = "glsl"; return language; } //----------------------------------------------------------------------- RenderOperation::OperationType parseOperationType(const String& val) { if (val == "point_list") { return RenderOperation::OT_POINT_LIST; } else if (val == "line_list") { return RenderOperation::OT_LINE_LIST; } else if (val == "line_strip") { return RenderOperation::OT_LINE_STRIP; } else if (val == "triangle_strip") { return RenderOperation::OT_TRIANGLE_STRIP; } else if (val == "triangle_fan") { return RenderOperation::OT_TRIANGLE_FAN; } else { //Triangle list is the default fallback. Keep it this way? return RenderOperation::OT_TRIANGLE_LIST; } } //----------------------------------------------------------------------- String operationTypeToString(RenderOperation::OperationType val) { switch (val) { case RenderOperation::OT_POINT_LIST: return "point_list"; break; case RenderOperation::OT_LINE_LIST: return "line_list"; break; case RenderOperation::OT_LINE_STRIP: return "line_strip"; break; case RenderOperation::OT_TRIANGLE_STRIP: return "triangle_strip"; break; case RenderOperation::OT_TRIANGLE_FAN: return "triangle_fan"; break; case RenderOperation::OT_TRIANGLE_LIST: default: return "triangle_list"; break; } } //----------------------------------------------------------------------- String GLSLProgram::CmdColumnMajorMatrices::doGet(const void *target) const { return StringConverter::toString(static_cast<const GLSLProgram*>(target)->getColumnMajorMatrices()); } void GLSLProgram::CmdColumnMajorMatrices::doSet(void *target, const String& val) { static_cast<GLSLProgram*>(target)->setColumnMajorMatrices(StringConverter::parseBool(val)); } //----------------------------------------------------------------------- String GLSLProgram::CmdInputOperationType::doGet(const void* target) const { const GLSLProgram* t = static_cast<const GLSLProgram*>(target); return operationTypeToString(t->getInputOperationType()); } void GLSLProgram::CmdInputOperationType::doSet(void* target, const String& val) { GLSLProgram* t = static_cast<GLSLProgram*>(target); t->setInputOperationType(parseOperationType(val)); } //----------------------------------------------------------------------- String GLSLProgram::CmdOutputOperationType::doGet(const void* target) const { const GLSLProgram* t = static_cast<const GLSLProgram*>(target); return operationTypeToString(t->getOutputOperationType()); } void GLSLProgram::CmdOutputOperationType::doSet(void* target, const String& val) { GLSLProgram* t = static_cast<GLSLProgram*>(target); t->setOutputOperationType(parseOperationType(val)); } //----------------------------------------------------------------------- String GLSLProgram::CmdMaxOutputVertices::doGet(const void* target) const { const GLSLProgram* t = static_cast<const GLSLProgram*>(target); return StringConverter::toString(t->getMaxOutputVertices()); } void GLSLProgram::CmdMaxOutputVertices::doSet(void* target, const String& val) { GLSLProgram* t = static_cast<GLSLProgram*>(target); t->setMaxOutputVertices(StringConverter::parseInt(val)); } } }
mit
yomolify/cc-server
node_modules/react-gmaps/dist/components/infoWindow.js
424
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _entity = require('./entity'); var _entity2 = _interopRequireDefault(_entity); var _events = require('./events'); exports['default'] = (0, _entity2['default'])('InfoWindow', _events.InfoWindowEvents); module.exports = exports['default'];
mit
Discordius/Lesswrong2
packages/lesswrong/components/async/editor-plugins/markdown-shortcuts-plugin/modifiers/handleImage.js
577
import insertImage from './insertImage'; const handleImage = (editorState, character) => { const re = /!\[([^\]]*)]\(([^)"]+)(?: "([^"]+)")?\)/g; const key = editorState.getSelection().getStartKey(); const text = editorState.getCurrentContent().getBlockForKey(key).getText(); const line = `${text}${character}`; let newEditorState = editorState; let matchArr; do { matchArr = re.exec(line); if (matchArr) { newEditorState = insertImage(newEditorState, matchArr); } } while (matchArr); return newEditorState; }; export default handleImage;
mit
ReplayMod/MCProtocolLib
src/main/java/com/github/steveice10/mc/protocol/data/game/entity/player/InteractAction.java
142
package com.github.steveice10.mc.protocol.data.game.entity.player; public enum InteractAction { INTERACT, ATTACK, INTERACT_AT; }
mit
jordannick/SymfonyTest
web/js/jquery-autosave/src/jquery.autosave.js
19237
/** * @fileOverview jQuery.autosave * * @author Kyle Florence * @website https://github.com/kflorence/jquery-autosave * @version 1.2-pre * * Inspired by the jQuery.autosave plugin written by Raymond Julin, * Mads Erik Forberg and Simen Graaten. * * Dual licensed under the MIT and BSD Licenses. */ ;(function($, window, document, undefined) { // Figure out if html5 "input" event is available var inputSupported = (function() { var tmp = document.createElement("input"); if ('oninput' in tmp) return true; // also try workaround for older versions of Firefox tmp.setAttribute("oninput", "return;"); return typeof tmp["oninput"] === "function"; }()); /** * Attempts to find a callback from a list of callbacks. * * @param {String|Object|function} callback * The callback to get. Can be a string or object that represents one of * the built in callback methods, or a custom function to use instead. * * @param {Object} callbacks * An object containing the callbacks to search in. * * @returns {Object} * The callback object. This will be an empty object if the callback * could not be found. If it was found, this object will contain at the * very least a "method" property and potentially an "options" property. */ var _findCallback = function(callback, callbacks) { var cb = { options: {} }, callbackType = typeof callback; if (callbackType === "function") { // Custom function with no options cb.method = callback; } else if (callbackType === "string" && callbacks[callback]) { // Built in method, use default options cb.method = callbacks[callback].method; } else if (callbackType === "object") { callbackType = typeof callback.method; if (callbackType === "function") { // Custom function cb.method = callback.method; } else if (callbackType === "string" && callbacks[callback.method]) { // Built in method cb.method = callbacks[callback.method].method; cb.options = $.extend(true, cb.options, callbacks[callback.method].options, callback.options); } } return cb; }; $.autosave = { timer: 0, $queues: $({}), states: { changed: "changed", modified: "modified" }, options: { namespace: "autosave", callbacks: { trigger: "change", scope: null, data: "serialize", condition: null, save: "ajax" }, events: { save: "save", saved: "saved", changed: "changed", modified: "modified" } }, /** * Initializes the plugin. * * @param {jQuery} $elements * The elements passed to the plugin. * * @param {Object} [options] * The user-defined options to merge with the defaults. * * @returns {jQuery} $elements * The elements passed to the plugin to maintain chainability. */ initialize: function($elements, options) { var self = this; this.$elements = $elements; this.options = $.extend(true, {}, this.options, options); // If length == 0, we have no forms or inputs if (this.elements().length) { var validCallbacks, $forms = this.forms(), $inputs = this.inputs(); // Only attach to forms $forms.data(this.options.namespace, this); $.each(this.options.events, function(name, eventName) { self.options.events[name] = [eventName, self.options.namespace].join("."); }); // Parse callback options into an array of callback objects $.each(this.options.callbacks, function(key, value) { validCallbacks = []; if (value) { $.each($.isArray(value) ? value : [value], function(i, callback) { callback = _findCallback(callback, self.callbacks[key]); // If callback has a valid method, we can use it if ($.isFunction(callback.method)) { validCallbacks.push(callback); } }); } self.options.callbacks[key] = validCallbacks; }); // Attempt to save when "save" is triggered on a form $forms.bind([this.options.events.save, this.options.namespace].join("."), function(e, inputs) { self.save(inputs, e.type); }); // Listen for changes on all inputs $inputs.bind(["change", this.options.namespace].join("."), function(e) { $(this).data([self.options.namespace, self.states.changed].join("."), true); $(this.form).triggerHandler(self.options.events.changed, [this]); }); // Listen for modifications on all inputs // Use html5 "input" event is available. Otherwise, use "keyup". var modifyTriggerEvent = inputSupported ? "input" : "keyup"; $inputs.bind([modifyTriggerEvent, this.options.namespace].join("."), function(e) { $(this).data([self.options.namespace, self.states.modified].join("."), true); $(this.form).triggerHandler(self.options.events.modified, [this]); }); // Set up triggers $.each(this.options.callbacks.trigger, function(i, trigger) { trigger.method.call(self, trigger.options); }); } return $elements; }, /** * Returns the forms and inputs within a specific context. * * @param {jQuery|Element|Element[]} [elements] * The elements to search within. Uses the pass elements by default. * * @return {jQuery} * A jQuery object containing any matched form and input elements. */ elements: function(elements) { if (!elements) { elements = this.$elements; } return $(elements).filter(function() { return (this.elements || this.form); }); }, /** * Returns the forms found within elements. * * @param {jQuery|Element|Element[]} [elements] * The elements to search within. Uses all of the currently found * forms and form inputs by default. * * @returns {jQuery} * A jQuery object containing any matched form elements. */ forms: function(elements) { return $($.unique(this.elements(elements).map(function() { return this.elements ? this : this.form; }).get())); }, /** * Returns the inputs found within elements. * * @param {jQuery|Element|Element[]} elements * The elements to search within. Uses all of the currently found * forms and form inputs by default. * * @returns {jQuery} * A jQuery object containing any matched input elements. */ inputs: function(elements) { return this.elements(elements).map(function() { return this.elements ? $.makeArray($(this).find(":input")) : this; }); }, /** * Returns the inputs from a set of inputs that are considered valid. * * @param {jQuery|Element|Element[]} [inputs] * The set of inputs to search within. Uses all of the currently found * inputs by default. * * @returns {jQuery} * A jQuery object containing any matched input elements. */ validInputs: function(inputs) { return this.inputs(inputs); }, /** * Get all of the inputs whose value has changed since the last save. * * @param {jQuery|Element|Element[]} [inputs] * The set of inputs to search within. Uses all of the currently found * inputs by default. * * @returns {jQuery} * A jQuery object containing any matched input elements. */ changedInputs: function(inputs) { var self = this; return this.inputs(inputs).filter(function() { return $(this).data([self.options.namespace, self.states.changed].join(".")); }); }, /** * Get all of the inputs whose value has been modified since the last save. * * @param {jQuery|Element|Element[]} [inputs] * The set of inputs to search within. Uses all of the currently found * inputs by default. * * @returns {jQuery} * A jQuery object containing any matched input elements. */ modifiedInputs: function(inputs) { var self = this; return this.inputs(inputs).filter(function() { return $(this).data([self.options.namespace, self.states.modified].join(".")); }); }, /** * Starts an autosave interval loop, stopping the current one if needed. * * @param {number} interval * An integer value representing the time between intervals in * milliseconds. */ startInterval: function(interval) { var self = this; interval = interval || this.interval; if (this.timer) { this.stopInterval(); } if (!isNaN(parseInt(interval))) { this.timer = setTimeout(function() { self.save(false, self.timer); }, interval); } }, /** * Stops an autosave interval loop. */ stopInterval: function() { clearTimeout(this.timer); this.timer = null; }, /** * Attemps to save form data. * * @param {jQuery|Element|Element[]} [inputs] * The inputs to extract data from. Can be of type jQuery, a DOM * element, or an array of DOM elements. If no inputs are passed, all * of the currently available inputs will be used. * * @param {mixed} [caller] * Used to denote who called this function. If passed, it is typically * the ID of the current interval timer and may be used to check if the * timer called this function. */ save: function(inputs, caller) { var self = this, saved = false, $inputs = this.validInputs(inputs); // If there are no save methods defined, we can't save if (this.options.callbacks.save.length) { // Continue filtering the scope of inputs $.each(this.options.callbacks.scope, function(i, scope) { $inputs = scope.method.call(self, scope.options, $inputs); }); if ($inputs.length) { var formData, passes = true; // Manipulate form data $.each(this.options.callbacks.data, function(i, data) { formData = data.method.call(self, data.options, $inputs, formData); }); // Loop through pre-save conditions and proceed only if they pass $.each(this.options.callbacks.condition, function(i, condition) { return (passes = condition.method.call( self, condition.options, $inputs, formData, caller )) !== false; }); if (passes) { // Add all of our save methods to the queue $.each(this.options.callbacks.save, function(i, save) { self.$queues.queue("save", function() { if (save.method.call(self, save.options, formData) === false) { // Methods that return false should handle the call to next() // we call resetFields manually here (immediately) before the async // save fires, because the callback will call next without 'true'. // and we want to reset the fields when the async save *starts*. self.resetFields(); } else { self.next("save", true); } }); }); // We were able to save saved = true; } } } // Start the dequeue process this.next("save", saved); }, /** * Maintains the queue; calls the next function in line, or performs * necessary cleanup when the queue is empty. * * @param {String} name * The name of the queue. * * @param {Boolean} [resetChanged] * Whether or not to reset which elements were changed/modified before saving. * Defaults to false. */ next: function(name, resetChanged) { var queue = this.$queues.queue(name); // Dequeue the next function if queue is not empty if (queue && queue.length) { this.$queues.dequeue(name); } // Queue is empty or does not exist else { this.finished(queue, name, resetChanged); } }, /** * Reset which elements where changed/modified before saving. */ resetFields: function() { this.inputs().data([this.options.namespace, this.states.changed].join("."), false); this.inputs().data([this.options.namespace, this.states.modified].join("."), false); }, /** * Called whenever a queue finishes processing, usually to perform some * type of cleanup. * * @param {Array} queue * The queue that has finished processing. * * @param {Boolean} [resetChanged] * Whether or not to reset which elements were changed/modified before saving. * Defaults to false */ finished: function(queue, name, resetChanged) { if (name === "save") { if (queue) { this.forms().triggerHandler(this.options.events.saved); } if (resetChanged) { this.resetFields(); } // If there is a timer running, start the next interval if (this.timer) { this.startInterval(); } } } }; var callbacks = $.autosave.callbacks = {}; $.each($.autosave.options.callbacks, function(key) { callbacks[key] = {}; }); $.extend(callbacks.trigger, { /** * Attempt to save any time an input value changes. */ change: { method: function() { var self = this; this.forms().bind([this.options.events.changed, this.options.namespace].join("."), function(e, input) { self.save(input, e.type); }); } }, /** * Attempt to save any time an input value is modified. */ modify: { method: function() { var self = this; this.forms().bind([this.options.events.modified, this.options.namespace].join("."), function(e, input) { self.save(input, e.type); }); } }, /** * Creates an interval loop that will attempt to save periodically. */ interval: { method: function(options) { if (!isNaN(parseInt(options.interval))) { this.startInterval(this.interval = options.interval); } }, options: { interval: 30000 } } }); $.extend(callbacks.scope, { /** * Use all inputs */ all: { method: function() { return this.validInputs(); } }, /** * Only use the inputs with values that have changed since the last save. */ changed: { method: function() { return this.changedInputs(); } }, /** * Only use the inputs with values that have been modified since the last save. */ modified: { method: function() { return this.modifiedInputs(); } } }); $.extend(callbacks.data, { /** * See: http://api.jquery.com/serialize/ * * @returns {String} * Standard URL-encoded string of form values. */ serialize: { method: function(options, $inputs) { return $inputs.serialize(); } }, /** * See: http://api.jquery.com/serializeArray/ * * @returns {Array} * An array of objects containing name/value pairs. */ serializeArray: { method: function(options, $inputs) { return $inputs.serializeArray(); } }, /** * Whereas .serializeArray() serializes a form into an array, * .serializeObject() serializes a form into an object. * * jQuery serializeObject - v0.2 - 1/20/2010 * http://benalman.com/projects/jquery-misc-plugins/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ * * @returns {Object} * The resulting object of form values. */ serializeObject: { method: function(options, $inputs) { var obj = {}; $.each($inputs.serializeArray(), function(i, o) { var n = o.name, v = o.value; obj[n] = obj[n] === undefined ? v : $.isArray(obj[n]) ? obj[n].concat(v) : [obj[n], v]; }); return obj; } } }); $.extend(callbacks.condition, { /** * Only save if the interval called the save method. */ interval: { method: function(options, $inputs, data, caller) { return (!this.timer || this.timer === caller); } }, /** * Only save if at least one of the input values has changed. */ changed: { method: function() { return this.changedInputs().length > 0; } }, /** * Only save if at least one of the input values has been modified. */ modified: { method: function() { return this.modifiedInputs().length > 0; } } }); $.extend(callbacks.save, { /** * Saves form data using a jQuery.ajax call. */ ajax: { method: function(options, formData) { var self = this, o = $.extend({}, options); // Wrap the complete method with our own o.complete = function(xhr, status) { if ($.isFunction(options.complete)) { options.complete.apply(self, arguments); } self.next("save"); }; // Allow for dynamically generated data if ($.isFunction(o.data)) { o.data = o.data.call(self, formData); } var formDataType = $.type(formData), optionsDataType = $.type(o.data); // No options data given, use form data if (optionsDataType == "undefined") { o.data = formData; // Data types must match in order to merge } else if (formDataType == optionsDataType) { switch(formDataType) { case "array": { o.data = $.merge(formData, o.data); } break; case "object": { o.data = $.extend(formData, o.data); } break; case "string": { o.data = formData + (formData.length ? "&" : "") + o.data; } break; } } else { throw "Cannot merge form data with options data, must be of same type."; } $.ajax(o); return false; }, options: { url: window.location.href } } }); /** * Attaches an autosave class instance to the form elements associated with * the elements passed into the plugin. * * @param {Object} [options] * User supplied options to override the defaults within the plugin. * * @returns {jQuery} * The elements that invoked this function. */ $.fn.autosave = function(options) { return $.extend({}, $.autosave).initialize(this, options); }; })(jQuery, window, document);
mit
rodrigoamaral/django-fullcalendar
fullcalendar/tests.py
2430
from django.test import TestCase from .util import snake_to_camel_case, convert_field_names, calendar_options class CamelCaseTest(TestCase): def test_one_word_variable(self): s = 'one' self.assertEqual(snake_to_camel_case(s), 'one') def test_two_word_variable(self): s = 'two_word' self.assertEqual(snake_to_camel_case(s), 'twoWord') def test_three_word_variable(self): s = 'three_word_variable' self.assertEqual(snake_to_camel_case(s), 'threeWordVariable') def test_startswith_one_underscore(self): s = '_one_under' self.assertEqual(snake_to_camel_case(s), '_oneUnder') def test_startswith_two_underscores(self): s = '__two_under' self.assertEqual(snake_to_camel_case(s), '__twoUnder') def test_starts_ends_with_one_underscore(self): s = '_one_under_' self.assertEqual(snake_to_camel_case(s), '_oneUnder_') def test_starts_ends_with_two_underscores(self): s = '__two_under__' self.assertEqual(snake_to_camel_case(s), '__twoUnder__') class ConvertFieldNames(TestCase): def test_conversion(self): l = [{'start': '2013-11-27', 'end': '2013-11-29', 'all_day': 'true', '__size__': 1, '__to_string__': 'false'}] self.assertEqual(convert_field_names(l), [{'start': '2013-11-27', 'end': '2013-11-29', 'allDay': 'true', '__size__': 1, '__toString__': 'false'}]) class CalendarOptions(TestCase): def test_options_string(self): s = '{timeFormat: "H:mm", header: {left: "prev,next today", center: "title", right: "month,agendaWeek,agendaDay",}' self.assertEqual(calendar_options('all_events/',s), '{events: "all_events/", timeFormat: "H:mm", header: {left: "prev,next today", center: "title", right: "month,agendaWeek,agendaDay",}') def test_options_string_with_whitespaces(self): s = ' {timeFormat: "H:mm", header: {left: "prev,next today", center: "title", right: "month,agendaWeek,agendaDay",} ' self.assertEqual(calendar_options('all_events/',s), '{events: "all_events/", timeFormat: "H:mm", header: {left: "prev,next today", center: "title", right: "month,agendaWeek,agendaDay",}') def test_options_empty_string(self): s = '' self.assertEqual(calendar_options('all_events/',s), '{events: "all_events/"}')
mit
Remak-kickstart/remark-kickstart
extensions/imagecropper/assets/jquery-ui-1.8.9.custom.min.js
20654
/*! * jQuery UI 1.8.9 * * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI */ (function(c,j){function k(a){return!c(a).parents().andSelf().filter(function(){return c.curCSS(this,"visibility")==="hidden"||c.expr.filters.hidden(this)}).length}c.ui=c.ui||{};if(!c.ui.version){c.extend(c.ui,{version:"1.8.9",keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106, NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91}});c.fn.extend({_focus:c.fn.focus,focus:function(a,b){return typeof a==="number"?this.each(function(){var d=this;setTimeout(function(){c(d).focus();b&&b.call(d)},a)}):this._focus.apply(this,arguments)},scrollParent:function(){var a;a=c.browser.msie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(c.curCSS(this, "position",1))&&/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0);return/fixed/.test(this.css("position"))||!a.length?c(document):a},zIndex:function(a){if(a!==j)return this.css("zIndex",a);if(this.length){a=c(this[0]);for(var b;a.length&&a[0]!==document;){b=a.css("position"); if(b==="absolute"||b==="relative"||b==="fixed"){b=parseInt(a.css("zIndex"),10);if(!isNaN(b)&&b!==0)return b}a=a.parent()}}return 0},disableSelection:function(){return this.bind((c.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(a){a.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}});c.each(["Width","Height"],function(a,b){function d(f,g,l,m){c.each(e,function(){g-=parseFloat(c.curCSS(f,"padding"+this,true))||0;if(l)g-=parseFloat(c.curCSS(f, "border"+this+"Width",true))||0;if(m)g-=parseFloat(c.curCSS(f,"margin"+this,true))||0});return g}var e=b==="Width"?["Left","Right"]:["Top","Bottom"],h=b.toLowerCase(),i={innerWidth:c.fn.innerWidth,innerHeight:c.fn.innerHeight,outerWidth:c.fn.outerWidth,outerHeight:c.fn.outerHeight};c.fn["inner"+b]=function(f){if(f===j)return i["inner"+b].call(this);return this.each(function(){c(this).css(h,d(this,f)+"px")})};c.fn["outer"+b]=function(f,g){if(typeof f!=="number")return i["outer"+b].call(this,f);return this.each(function(){c(this).css(h, d(this,f,true,g)+"px")})}});c.extend(c.expr[":"],{data:function(a,b,d){return!!c.data(a,d[3])},focusable:function(a){var b=a.nodeName.toLowerCase(),d=c.attr(a,"tabindex");if("area"===b){b=a.parentNode;d=b.name;if(!a.href||!d||b.nodeName.toLowerCase()!=="map")return false;a=c("img[usemap=#"+d+"]")[0];return!!a&&k(a)}return(/input|select|textarea|button|object/.test(b)?!a.disabled:"a"==b?a.href||!isNaN(d):!isNaN(d))&&k(a)},tabbable:function(a){var b=c.attr(a,"tabindex");return(isNaN(b)||b>=0)&&c(a).is(":focusable")}}); c(function(){var a=document.body,b=a.appendChild(b=document.createElement("div"));c.extend(b.style,{minHeight:"100px",height:"auto",padding:0,borderWidth:0});c.support.minHeight=b.offsetHeight===100;c.support.selectstart="onselectstart"in b;a.removeChild(b).style.display="none"});c.extend(c.ui,{plugin:{add:function(a,b,d){a=c.ui[a].prototype;for(var e in d){a.plugins[e]=a.plugins[e]||[];a.plugins[e].push([b,d[e]])}},call:function(a,b,d){if((b=a.plugins[b])&&a.element[0].parentNode)for(var e=0;e<b.length;e++)a.options[b[e][0]]&& b[e][1].apply(a.element,d)}},contains:function(a,b){return document.compareDocumentPosition?a.compareDocumentPosition(b)&16:a!==b&&a.contains(b)},hasScroll:function(a,b){if(c(a).css("overflow")==="hidden")return false;b=b&&b==="left"?"scrollLeft":"scrollTop";var d=false;if(a[b]>0)return true;a[b]=1;d=a[b]>0;a[b]=0;return d},isOverAxis:function(a,b,d){return a>b&&a<b+d},isOver:function(a,b,d,e,h,i){return c.ui.isOverAxis(a,d,h)&&c.ui.isOverAxis(b,e,i)}})}})(jQuery); ;/*! * jQuery UI Widget 1.8.9 * * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Widget */ (function(b,j){if(b.cleanData){var k=b.cleanData;b.cleanData=function(a){for(var c=0,d;(d=a[c])!=null;c++)b(d).triggerHandler("remove");k(a)}}else{var l=b.fn.remove;b.fn.remove=function(a,c){return this.each(function(){if(!c)if(!a||b.filter(a,[this]).length)b("*",this).add([this]).each(function(){b(this).triggerHandler("remove")});return l.call(b(this),a,c)})}}b.widget=function(a,c,d){var e=a.split(".")[0],f;a=a.split(".")[1];f=e+"-"+a;if(!d){d=c;c=b.Widget}b.expr[":"][f]=function(h){return!!b.data(h, a)};b[e]=b[e]||{};b[e][a]=function(h,g){arguments.length&&this._createWidget(h,g)};c=new c;c.options=b.extend(true,{},c.options);b[e][a].prototype=b.extend(true,c,{namespace:e,widgetName:a,widgetEventPrefix:b[e][a].prototype.widgetEventPrefix||a,widgetBaseClass:f},d);b.widget.bridge(a,b[e][a])};b.widget.bridge=function(a,c){b.fn[a]=function(d){var e=typeof d==="string",f=Array.prototype.slice.call(arguments,1),h=this;d=!e&&f.length?b.extend.apply(null,[true,d].concat(f)):d;if(e&&d.charAt(0)==="_")return h; e?this.each(function(){var g=b.data(this,a),i=g&&b.isFunction(g[d])?g[d].apply(g,f):g;if(i!==g&&i!==j){h=i;return false}}):this.each(function(){var g=b.data(this,a);g?g.option(d||{})._init():b.data(this,a,new c(d,this))});return h}};b.Widget=function(a,c){arguments.length&&this._createWidget(a,c)};b.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:false},_createWidget:function(a,c){b.data(c,this.widgetName,this);this.element=b(c);this.options=b.extend(true,{},this.options, this._getCreateOptions(),a);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy()});this._create();this._trigger("create");this._init()},_getCreateOptions:function(){return b.metadata&&b.metadata.get(this.element[0])[this.widgetName]},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName);this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled")}, widget:function(){return this.element},option:function(a,c){var d=a;if(arguments.length===0)return b.extend({},this.options);if(typeof a==="string"){if(c===j)return this.options[a];d={};d[a]=c}this._setOptions(d);return this},_setOptions:function(a){var c=this;b.each(a,function(d,e){c._setOption(d,e)});return this},_setOption:function(a,c){this.options[a]=c;if(a==="disabled")this.widget()[c?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",c);return this}, enable:function(){return this._setOption("disabled",false)},disable:function(){return this._setOption("disabled",true)},_trigger:function(a,c,d){var e=this.options[a];c=b.Event(c);c.type=(a===this.widgetEventPrefix?a:this.widgetEventPrefix+a).toLowerCase();d=d||{};if(c.originalEvent){a=b.event.props.length;for(var f;a;){f=b.event.props[--a];c[f]=c.originalEvent[f]}}this.element.trigger(c,d);return!(b.isFunction(e)&&e.call(this.element[0],c,d)===false||c.isDefaultPrevented())}}})(jQuery); ;/*! * jQuery UI Mouse 1.8.9 * * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Mouse * * Depends: * jquery.ui.widget.js */ (function(c){c.widget("ui.mouse",{options:{cancel:":input,option",distance:1,delay:0},_mouseInit:function(){var a=this;this.element.bind("mousedown."+this.widgetName,function(b){return a._mouseDown(b)}).bind("click."+this.widgetName,function(b){if(true===c.data(b.target,a.widgetName+".preventClickEvent")){c.removeData(b.target,a.widgetName+".preventClickEvent");b.stopImmediatePropagation();return false}});this.started=false},_mouseDestroy:function(){this.element.unbind("."+this.widgetName)},_mouseDown:function(a){a.originalEvent= a.originalEvent||{};if(!a.originalEvent.mouseHandled){this._mouseStarted&&this._mouseUp(a);this._mouseDownEvent=a;var b=this,e=a.which==1,f=typeof this.options.cancel=="string"?c(a.target).parents().add(a.target).filter(this.options.cancel).length:false;if(!e||f||!this._mouseCapture(a))return true;this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet)this._mouseDelayTimer=setTimeout(function(){b.mouseDelayMet=true},this.options.delay);if(this._mouseDistanceMet(a)&&this._mouseDelayMet(a)){this._mouseStarted= this._mouseStart(a)!==false;if(!this._mouseStarted){a.preventDefault();return true}}this._mouseMoveDelegate=function(d){return b._mouseMove(d)};this._mouseUpDelegate=function(d){return b._mouseUp(d)};c(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);a.preventDefault();return a.originalEvent.mouseHandled=true}},_mouseMove:function(a){if(c.browser.msie&&!(document.documentMode>=9)&&!a.button)return this._mouseUp(a);if(this._mouseStarted){this._mouseDrag(a); return a.preventDefault()}if(this._mouseDistanceMet(a)&&this._mouseDelayMet(a))(this._mouseStarted=this._mouseStart(this._mouseDownEvent,a)!==false)?this._mouseDrag(a):this._mouseUp(a);return!this._mouseStarted},_mouseUp:function(a){c(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;a.target==this._mouseDownEvent.target&&c.data(a.target,this.widgetName+".preventClickEvent", true);this._mouseStop(a)}return false},_mouseDistanceMet:function(a){return Math.max(Math.abs(this._mouseDownEvent.pageX-a.pageX),Math.abs(this._mouseDownEvent.pageY-a.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return true}})})(jQuery); ;/* * jQuery UI Slider 1.8.9 * * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Slider * * Depends: * jquery.ui.core.js * jquery.ui.mouse.js * jquery.ui.widget.js */ (function(d){d.widget("ui.slider",d.ui.mouse,{widgetEventPrefix:"slide",options:{animate:false,distance:0,max:100,min:0,orientation:"horizontal",range:false,step:1,value:0,values:null},_create:function(){var b=this,a=this.options;this._mouseSliding=this._keySliding=false;this._animateOff=true;this._handleIndex=null;this._detectOrientation();this._mouseInit();this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget ui-widget-content ui-corner-all");a.disabled&&this.element.addClass("ui-slider-disabled ui-disabled"); this.range=d([]);if(a.range){if(a.range===true){this.range=d("<div></div>");if(!a.values)a.values=[this._valueMin(),this._valueMin()];if(a.values.length&&a.values.length!==2)a.values=[a.values[0],a.values[0]]}else this.range=d("<div></div>");this.range.appendTo(this.element).addClass("ui-slider-range");if(a.range==="min"||a.range==="max")this.range.addClass("ui-slider-range-"+a.range);this.range.addClass("ui-widget-header")}d(".ui-slider-handle",this.element).length===0&&d("<a href='#'></a>").appendTo(this.element).addClass("ui-slider-handle"); if(a.values&&a.values.length)for(;d(".ui-slider-handle",this.element).length<a.values.length;)d("<a href='#'></a>").appendTo(this.element).addClass("ui-slider-handle");this.handles=d(".ui-slider-handle",this.element).addClass("ui-state-default ui-corner-all");this.handle=this.handles.eq(0);this.handles.add(this.range).filter("a").click(function(c){c.preventDefault()}).hover(function(){a.disabled||d(this).addClass("ui-state-hover")},function(){d(this).removeClass("ui-state-hover")}).focus(function(){if(a.disabled)d(this).blur(); else{d(".ui-slider .ui-state-focus").removeClass("ui-state-focus");d(this).addClass("ui-state-focus")}}).blur(function(){d(this).removeClass("ui-state-focus")});this.handles.each(function(c){d(this).data("index.ui-slider-handle",c)});this.handles.keydown(function(c){var e=true,f=d(this).data("index.ui-slider-handle"),h,g,i;if(!b.options.disabled){switch(c.keyCode){case d.ui.keyCode.HOME:case d.ui.keyCode.END:case d.ui.keyCode.PAGE_UP:case d.ui.keyCode.PAGE_DOWN:case d.ui.keyCode.UP:case d.ui.keyCode.RIGHT:case d.ui.keyCode.DOWN:case d.ui.keyCode.LEFT:e= false;if(!b._keySliding){b._keySliding=true;d(this).addClass("ui-state-active");h=b._start(c,f);if(h===false)return}break}i=b.options.step;h=b.options.values&&b.options.values.length?(g=b.values(f)):(g=b.value());switch(c.keyCode){case d.ui.keyCode.HOME:g=b._valueMin();break;case d.ui.keyCode.END:g=b._valueMax();break;case d.ui.keyCode.PAGE_UP:g=b._trimAlignValue(h+(b._valueMax()-b._valueMin())/5);break;case d.ui.keyCode.PAGE_DOWN:g=b._trimAlignValue(h-(b._valueMax()-b._valueMin())/5);break;case d.ui.keyCode.UP:case d.ui.keyCode.RIGHT:if(h=== b._valueMax())return;g=b._trimAlignValue(h+i);break;case d.ui.keyCode.DOWN:case d.ui.keyCode.LEFT:if(h===b._valueMin())return;g=b._trimAlignValue(h-i);break}b._slide(c,f,g);return e}}).keyup(function(c){var e=d(this).data("index.ui-slider-handle");if(b._keySliding){b._keySliding=false;b._stop(c,e);b._change(c,e);d(this).removeClass("ui-state-active")}});this._refreshValue();this._animateOff=false},destroy:function(){this.handles.remove();this.range.remove();this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-slider-disabled ui-widget ui-widget-content ui-corner-all").removeData("slider").unbind(".slider"); this._mouseDestroy();return this},_mouseCapture:function(b){var a=this.options,c,e,f,h,g;if(a.disabled)return false;this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()};this.elementOffset=this.element.offset();c=this._normValueFromMouse({x:b.pageX,y:b.pageY});e=this._valueMax()-this._valueMin()+1;h=this;this.handles.each(function(i){var j=Math.abs(c-h.values(i));if(e>j){e=j;f=d(this);g=i}});if(a.range===true&&this.values(1)===a.min){g+=1;f=d(this.handles[g])}if(this._start(b, g)===false)return false;this._mouseSliding=true;h._handleIndex=g;f.addClass("ui-state-active").focus();a=f.offset();this._clickOffset=!d(b.target).parents().andSelf().is(".ui-slider-handle")?{left:0,top:0}:{left:b.pageX-a.left-f.width()/2,top:b.pageY-a.top-f.height()/2-(parseInt(f.css("borderTopWidth"),10)||0)-(parseInt(f.css("borderBottomWidth"),10)||0)+(parseInt(f.css("marginTop"),10)||0)};this.handles.hasClass("ui-state-hover")||this._slide(b,g,c);return this._animateOff=true},_mouseStart:function(){return true}, _mouseDrag:function(b){var a=this._normValueFromMouse({x:b.pageX,y:b.pageY});this._slide(b,this._handleIndex,a);return false},_mouseStop:function(b){this.handles.removeClass("ui-state-active");this._mouseSliding=false;this._stop(b,this._handleIndex);this._change(b,this._handleIndex);this._clickOffset=this._handleIndex=null;return this._animateOff=false},_detectOrientation:function(){this.orientation=this.options.orientation==="vertical"?"vertical":"horizontal"},_normValueFromMouse:function(b){var a; if(this.orientation==="horizontal"){a=this.elementSize.width;b=b.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)}else{a=this.elementSize.height;b=b.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)}a=b/a;if(a>1)a=1;if(a<0)a=0;if(this.orientation==="vertical")a=1-a;b=this._valueMax()-this._valueMin();return this._trimAlignValue(this._valueMin()+a*b)},_start:function(b,a){var c={handle:this.handles[a],value:this.value()};if(this.options.values&&this.options.values.length){c.value= this.values(a);c.values=this.values()}return this._trigger("start",b,c)},_slide:function(b,a,c){var e;if(this.options.values&&this.options.values.length){e=this.values(a?0:1);if(this.options.values.length===2&&this.options.range===true&&(a===0&&c>e||a===1&&c<e))c=e;if(c!==this.values(a)){e=this.values();e[a]=c;b=this._trigger("slide",b,{handle:this.handles[a],value:c,values:e});this.values(a?0:1);b!==false&&this.values(a,c,true)}}else if(c!==this.value()){b=this._trigger("slide",b,{handle:this.handles[a], value:c});b!==false&&this.value(c)}},_stop:function(b,a){var c={handle:this.handles[a],value:this.value()};if(this.options.values&&this.options.values.length){c.value=this.values(a);c.values=this.values()}this._trigger("stop",b,c)},_change:function(b,a){if(!this._keySliding&&!this._mouseSliding){var c={handle:this.handles[a],value:this.value()};if(this.options.values&&this.options.values.length){c.value=this.values(a);c.values=this.values()}this._trigger("change",b,c)}},value:function(b){if(arguments.length){this.options.value= this._trimAlignValue(b);this._refreshValue();this._change(null,0)}return this._value()},values:function(b,a){var c,e,f;if(arguments.length>1){this.options.values[b]=this._trimAlignValue(a);this._refreshValue();this._change(null,b)}if(arguments.length)if(d.isArray(arguments[0])){c=this.options.values;e=arguments[0];for(f=0;f<c.length;f+=1){c[f]=this._trimAlignValue(e[f]);this._change(null,f)}this._refreshValue()}else return this.options.values&&this.options.values.length?this._values(b):this.value(); else return this._values()},_setOption:function(b,a){var c,e=0;if(d.isArray(this.options.values))e=this.options.values.length;d.Widget.prototype._setOption.apply(this,arguments);switch(b){case "disabled":if(a){this.handles.filter(".ui-state-focus").blur();this.handles.removeClass("ui-state-hover");this.handles.attr("disabled","disabled");this.element.addClass("ui-disabled")}else{this.handles.removeAttr("disabled");this.element.removeClass("ui-disabled")}break;case "orientation":this._detectOrientation(); this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation);this._refreshValue();break;case "value":this._animateOff=true;this._refreshValue();this._change(null,0);this._animateOff=false;break;case "values":this._animateOff=true;this._refreshValue();for(c=0;c<e;c+=1)this._change(null,c);this._animateOff=false;break}},_value:function(){var b=this.options.value;return b=this._trimAlignValue(b)},_values:function(b){var a,c;if(arguments.length){a=this.options.values[b]; return a=this._trimAlignValue(a)}else{a=this.options.values.slice();for(c=0;c<a.length;c+=1)a[c]=this._trimAlignValue(a[c]);return a}},_trimAlignValue:function(b){if(b<=this._valueMin())return this._valueMin();if(b>=this._valueMax())return this._valueMax();var a=this.options.step>0?this.options.step:1,c=(b-this._valueMin())%a;alignValue=b-c;if(Math.abs(c)*2>=a)alignValue+=c>0?a:-a;return parseFloat(alignValue.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max}, _refreshValue:function(){var b=this.options.range,a=this.options,c=this,e=!this._animateOff?a.animate:false,f,h={},g,i,j,l;if(this.options.values&&this.options.values.length)this.handles.each(function(k){f=(c.values(k)-c._valueMin())/(c._valueMax()-c._valueMin())*100;h[c.orientation==="horizontal"?"left":"bottom"]=f+"%";d(this).stop(1,1)[e?"animate":"css"](h,a.animate);if(c.options.range===true)if(c.orientation==="horizontal"){if(k===0)c.range.stop(1,1)[e?"animate":"css"]({left:f+"%"},a.animate); if(k===1)c.range[e?"animate":"css"]({width:f-g+"%"},{queue:false,duration:a.animate})}else{if(k===0)c.range.stop(1,1)[e?"animate":"css"]({bottom:f+"%"},a.animate);if(k===1)c.range[e?"animate":"css"]({height:f-g+"%"},{queue:false,duration:a.animate})}g=f});else{i=this.value();j=this._valueMin();l=this._valueMax();f=l!==j?(i-j)/(l-j)*100:0;h[c.orientation==="horizontal"?"left":"bottom"]=f+"%";this.handle.stop(1,1)[e?"animate":"css"](h,a.animate);if(b==="min"&&this.orientation==="horizontal")this.range.stop(1, 1)[e?"animate":"css"]({width:f+"%"},a.animate);if(b==="max"&&this.orientation==="horizontal")this.range[e?"animate":"css"]({width:100-f+"%"},{queue:false,duration:a.animate});if(b==="min"&&this.orientation==="vertical")this.range.stop(1,1)[e?"animate":"css"]({height:f+"%"},a.animate);if(b==="max"&&this.orientation==="vertical")this.range[e?"animate":"css"]({height:100-f+"%"},{queue:false,duration:a.animate})}}});d.extend(d.ui.slider,{version:"1.8.9"})})(jQuery); ;
mit
jonnybee/csla
Samples/NET/cs/ExtendableWcfPortalForDotNet/Rolodex.WPF/Views/PleaseWaitView.xaml.cs
636
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Rolodex.Silverlight.Views { /// <summary> /// Interaction logic for PleaseWaitView.xaml /// </summary> public partial class PleaseWaitView : UserControl { public PleaseWaitView() { InitializeComponent(); } } }
mit
kbond/symfony
src/Symfony/Component/Cache/DependencyInjection/CachePoolPass.php
11025
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Cache\DependencyInjection; use Symfony\Component\Cache\Adapter\AbstractAdapter; use Symfony\Component\Cache\Adapter\ArrayAdapter; use Symfony\Component\Cache\Adapter\ChainAdapter; use Symfony\Component\Cache\Adapter\ParameterNormalizer; use Symfony\Component\Cache\Messenger\EarlyExpirationDispatcher; use Symfony\Component\DependencyInjection\ChildDefinition; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Reference; /** * @author Nicolas Grekas <p@tchwork.com> */ class CachePoolPass implements CompilerPassInterface { private $cachePoolTag; private $kernelResetTag; private $cacheClearerId; private $cachePoolClearerTag; private $cacheSystemClearerId; private $cacheSystemClearerTag; private $reverseContainerId; private $reversibleTag; private $messageHandlerId; public function __construct(string $cachePoolTag = 'cache.pool', string $kernelResetTag = 'kernel.reset', string $cacheClearerId = 'cache.global_clearer', string $cachePoolClearerTag = 'cache.pool.clearer', string $cacheSystemClearerId = 'cache.system_clearer', string $cacheSystemClearerTag = 'kernel.cache_clearer', string $reverseContainerId = 'reverse_container', string $reversibleTag = 'container.reversible', string $messageHandlerId = 'cache.early_expiration_handler') { $this->cachePoolTag = $cachePoolTag; $this->kernelResetTag = $kernelResetTag; $this->cacheClearerId = $cacheClearerId; $this->cachePoolClearerTag = $cachePoolClearerTag; $this->cacheSystemClearerId = $cacheSystemClearerId; $this->cacheSystemClearerTag = $cacheSystemClearerTag; $this->reverseContainerId = $reverseContainerId; $this->reversibleTag = $reversibleTag; $this->messageHandlerId = $messageHandlerId; } /** * {@inheritdoc} */ public function process(ContainerBuilder $container) { if ($container->hasParameter('cache.prefix.seed')) { $seed = $container->getParameterBag()->resolveValue($container->getParameter('cache.prefix.seed')); } else { $seed = '_'.$container->getParameter('kernel.project_dir'); $seed .= '.'.$container->getParameter('kernel.container_class'); } $needsMessageHandler = false; $allPools = []; $clearers = []; $attributes = [ 'provider', 'name', 'namespace', 'default_lifetime', 'early_expiration_message_bus', 'reset', ]; foreach ($container->findTaggedServiceIds($this->cachePoolTag) as $id => $tags) { $adapter = $pool = $container->getDefinition($id); if ($pool->isAbstract()) { continue; } $class = $adapter->getClass(); while ($adapter instanceof ChildDefinition) { $adapter = $container->findDefinition($adapter->getParent()); $class = $class ?: $adapter->getClass(); if ($t = $adapter->getTag($this->cachePoolTag)) { $tags[0] += $t[0]; } } $name = $tags[0]['name'] ?? $id; if (!isset($tags[0]['namespace'])) { $namespaceSeed = $seed; if (null !== $class) { $namespaceSeed .= '.'.$class; } $tags[0]['namespace'] = $this->getNamespace($namespaceSeed, $name); } if (isset($tags[0]['clearer'])) { $clearer = $tags[0]['clearer']; while ($container->hasAlias($clearer)) { $clearer = (string) $container->getAlias($clearer); } } else { $clearer = null; } unset($tags[0]['clearer'], $tags[0]['name']); if (isset($tags[0]['provider'])) { $tags[0]['provider'] = new Reference(static::getServiceProvider($container, $tags[0]['provider'])); } if (ChainAdapter::class === $class) { $adapters = []; foreach ($adapter->getArgument(0) as $provider => $adapter) { if ($adapter instanceof ChildDefinition) { $chainedPool = $adapter; } else { $chainedPool = $adapter = new ChildDefinition($adapter); } $chainedTags = [\is_int($provider) ? [] : ['provider' => $provider]]; $chainedClass = ''; while ($adapter instanceof ChildDefinition) { $adapter = $container->findDefinition($adapter->getParent()); $chainedClass = $chainedClass ?: $adapter->getClass(); if ($t = $adapter->getTag($this->cachePoolTag)) { $chainedTags[0] += $t[0]; } } if (ChainAdapter::class === $chainedClass) { throw new InvalidArgumentException(sprintf('Invalid service "%s": chain of adapters cannot reference another chain, found "%s".', $id, $chainedPool->getParent())); } $i = 0; if (isset($chainedTags[0]['provider'])) { $chainedPool->replaceArgument($i++, new Reference(static::getServiceProvider($container, $chainedTags[0]['provider']))); } if (isset($tags[0]['namespace']) && ArrayAdapter::class !== $adapter->getClass()) { $chainedPool->replaceArgument($i++, $tags[0]['namespace']); } if (isset($tags[0]['default_lifetime'])) { $chainedPool->replaceArgument($i++, $tags[0]['default_lifetime']); } $adapters[] = $chainedPool; } $pool->replaceArgument(0, $adapters); unset($tags[0]['provider'], $tags[0]['namespace']); $i = 1; } else { $i = 0; } foreach ($attributes as $attr) { if (!isset($tags[0][$attr])) { // no-op } elseif ('reset' === $attr) { if ($tags[0][$attr]) { $pool->addTag($this->kernelResetTag, ['method' => $tags[0][$attr]]); } } elseif ('early_expiration_message_bus' === $attr) { $needsMessageHandler = true; $pool->addMethodCall('setCallbackWrapper', [(new Definition(EarlyExpirationDispatcher::class)) ->addArgument(new Reference($tags[0]['early_expiration_message_bus'])) ->addArgument(new Reference($this->reverseContainerId)) ->addArgument((new Definition('callable')) ->setFactory([new Reference($id), 'setCallbackWrapper']) ->addArgument(null) ), ]); $pool->addTag($this->reversibleTag); } elseif ('namespace' !== $attr || ArrayAdapter::class !== $class) { $argument = $tags[0][$attr]; if ('default_lifetime' === $attr && !is_numeric($argument)) { $argument = (new Definition('int', [$argument])) ->setFactory([ParameterNormalizer::class, 'normalizeDuration']); } $pool->replaceArgument($i++, $argument); } unset($tags[0][$attr]); } if (!empty($tags[0])) { throw new InvalidArgumentException(sprintf('Invalid "%s" tag for service "%s": accepted attributes are "clearer", "provider", "name", "namespace", "default_lifetime", "early_expiration_message_bus" and "reset", found "%s".', $this->cachePoolTag, $id, implode('", "', array_keys($tags[0])))); } if (null !== $clearer) { $clearers[$clearer][$name] = new Reference($id, $container::IGNORE_ON_UNINITIALIZED_REFERENCE); } $allPools[$name] = new Reference($id, $container::IGNORE_ON_UNINITIALIZED_REFERENCE); } if (!$needsMessageHandler) { $container->removeDefinition($this->messageHandlerId); } $notAliasedCacheClearerId = $this->cacheClearerId; while ($container->hasAlias($this->cacheClearerId)) { $this->cacheClearerId = (string) $container->getAlias($this->cacheClearerId); } if ($container->hasDefinition($this->cacheClearerId)) { $clearers[$notAliasedCacheClearerId] = $allPools; } foreach ($clearers as $id => $pools) { $clearer = $container->getDefinition($id); if ($clearer instanceof ChildDefinition) { $clearer->replaceArgument(0, $pools); } else { $clearer->setArgument(0, $pools); } $clearer->addTag($this->cachePoolClearerTag); if ($this->cacheSystemClearerId === $id) { $clearer->addTag($this->cacheSystemClearerTag); } } if ($container->hasDefinition('console.command.cache_pool_list')) { $container->getDefinition('console.command.cache_pool_list')->replaceArgument(0, array_keys($allPools)); } } private function getNamespace(string $seed, string $id) { return substr(str_replace('/', '-', base64_encode(hash('sha256', $id.$seed, true))), 0, 10); } /** * @internal */ public static function getServiceProvider(ContainerBuilder $container, $name) { $container->resolveEnvPlaceholders($name, null, $usedEnvs); if ($usedEnvs || preg_match('#^[a-z]++:#', $name)) { $dsn = $name; if (!$container->hasDefinition($name = '.cache_connection.'.ContainerBuilder::hash($dsn))) { $definition = new Definition(AbstractAdapter::class); $definition->setPublic(false); $definition->setFactory([AbstractAdapter::class, 'createConnection']); $definition->setArguments([$dsn, ['lazy' => true]]); $container->setDefinition($name, $definition); } } return $name; } }
mit
next-l/enju_flower
spec/dummy/db/migrate/059_create_libraries.rb
892
class CreateLibraries < ActiveRecord::Migration def change create_table :libraries do |t| t.string :name, :null => false t.text :display_name t.string :short_display_name, :null => false t.string :zip_code t.text :street t.text :locality t.text :region t.string :telephone_number_1 t.string :telephone_number_2 t.string :fax_number t.text :note t.integer :call_number_rows, :default => 1, :null => false t.string :call_number_delimiter, :default => "|", :null => false t.integer :library_group_id, :default => 1, :null => false t.integer :users_count, :default => 0, :null => false t.integer :position t.integer :country_id t.timestamps t.datetime :deleted_at end add_index :libraries, :library_group_id add_index :libraries, :name, :unique => true end end
mit
anditto/bitcoin
src/rpc/mining.cpp
58575
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <amount.h> #include <chain.h> #include <chainparams.h> #include <consensus/consensus.h> #include <consensus/params.h> #include <consensus/validation.h> #include <core_io.h> #include <deploymentinfo.h> #include <deploymentstatus.h> #include <key_io.h> #include <miner.h> #include <net.h> #include <node/context.h> #include <policy/fees.h> #include <pow.h> #include <rpc/blockchain.h> #include <rpc/mining.h> #include <rpc/net.h> #include <rpc/server.h> #include <rpc/util.h> #include <script/descriptor.h> #include <script/script.h> #include <script/signingprovider.h> #include <shutdown.h> #include <txmempool.h> #include <univalue.h> #include <util/fees.h> #include <util/strencodings.h> #include <util/string.h> #include <util/system.h> #include <util/translation.h> #include <validation.h> #include <validationinterface.h> #include <warnings.h> #include <memory> #include <stdint.h> /** * Return average network hashes per second based on the last 'lookup' blocks, * or from the last difficulty change if 'lookup' is nonpositive. * If 'height' is nonnegative, compute the estimate at the time when a given block was found. */ static UniValue GetNetworkHashPS(int lookup, int height, const CChain& active_chain) { const CBlockIndex* pb = active_chain.Tip(); if (height >= 0 && height < active_chain.Height()) { pb = active_chain[height]; } if (pb == nullptr || !pb->nHeight) return 0; // If lookup is -1, then use blocks since last difficulty change. if (lookup <= 0) lookup = pb->nHeight % Params().GetConsensus().DifficultyAdjustmentInterval() + 1; // If lookup is larger than chain, then set it to chain length. if (lookup > pb->nHeight) lookup = pb->nHeight; const CBlockIndex* pb0 = pb; int64_t minTime = pb0->GetBlockTime(); int64_t maxTime = minTime; for (int i = 0; i < lookup; i++) { pb0 = pb0->pprev; int64_t time = pb0->GetBlockTime(); minTime = std::min(time, minTime); maxTime = std::max(time, maxTime); } // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception. if (minTime == maxTime) return 0; arith_uint256 workDiff = pb->nChainWork - pb0->nChainWork; int64_t timeDiff = maxTime - minTime; return workDiff.getdouble() / timeDiff; } static RPCHelpMan getnetworkhashps() { return RPCHelpMan{"getnetworkhashps", "\nReturns the estimated network hashes per second based on the last n blocks.\n" "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n" "Pass in [height] to estimate the network speed at the time when a certain block was found.\n", { {"nblocks", RPCArg::Type::NUM, RPCArg::Default{120}, "The number of blocks, or -1 for blocks since last difficulty change."}, {"height", RPCArg::Type::NUM, RPCArg::Default{-1}, "To estimate at the time of the given height."}, }, RPCResult{ RPCResult::Type::NUM, "", "Hashes per second estimated"}, RPCExamples{ HelpExampleCli("getnetworkhashps", "") + HelpExampleRpc("getnetworkhashps", "") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { ChainstateManager& chainman = EnsureAnyChainman(request.context); LOCK(cs_main); return GetNetworkHashPS(!request.params[0].isNull() ? request.params[0].get_int() : 120, !request.params[1].isNull() ? request.params[1].get_int() : -1, chainman.ActiveChain()); }, }; } static bool GenerateBlock(ChainstateManager& chainman, CBlock& block, uint64_t& max_tries, unsigned int& extra_nonce, uint256& block_hash) { block_hash.SetNull(); { LOCK(cs_main); IncrementExtraNonce(&block, chainman.ActiveChain().Tip(), extra_nonce); } CChainParams chainparams(Params()); while (max_tries > 0 && block.nNonce < std::numeric_limits<uint32_t>::max() && !CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus()) && !ShutdownRequested()) { ++block.nNonce; --max_tries; } if (max_tries == 0 || ShutdownRequested()) { return false; } if (block.nNonce == std::numeric_limits<uint32_t>::max()) { return true; } std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(block); if (!chainman.ProcessNewBlock(chainparams, shared_pblock, true, nullptr)) { throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted"); } block_hash = block.GetHash(); return true; } static UniValue generateBlocks(ChainstateManager& chainman, const CTxMemPool& mempool, const CScript& coinbase_script, int nGenerate, uint64_t nMaxTries) { int nHeightEnd = 0; int nHeight = 0; { // Don't keep cs_main locked LOCK(cs_main); nHeight = chainman.ActiveChain().Height(); nHeightEnd = nHeight+nGenerate; } unsigned int nExtraNonce = 0; UniValue blockHashes(UniValue::VARR); while (nHeight < nHeightEnd && !ShutdownRequested()) { std::unique_ptr<CBlockTemplate> pblocktemplate(BlockAssembler(chainman.ActiveChainstate(), mempool, Params()).CreateNewBlock(coinbase_script)); if (!pblocktemplate.get()) throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block"); CBlock *pblock = &pblocktemplate->block; uint256 block_hash; if (!GenerateBlock(chainman, *pblock, nMaxTries, nExtraNonce, block_hash)) { break; } if (!block_hash.IsNull()) { ++nHeight; blockHashes.push_back(block_hash.GetHex()); } } return blockHashes; } static bool getScriptFromDescriptor(const std::string& descriptor, CScript& script, std::string& error) { FlatSigningProvider key_provider; const auto desc = Parse(descriptor, key_provider, error, /* require_checksum = */ false); if (desc) { if (desc->IsRange()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Ranged descriptor not accepted. Maybe pass through deriveaddresses first?"); } FlatSigningProvider provider; std::vector<CScript> scripts; if (!desc->Expand(0, key_provider, scripts, provider)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Cannot derive script without private keys")); } // Combo descriptors can have 2 or 4 scripts, so we can't just check scripts.size() == 1 CHECK_NONFATAL(scripts.size() > 0 && scripts.size() <= 4); if (scripts.size() == 1) { script = scripts.at(0); } else if (scripts.size() == 4) { // For uncompressed keys, take the 3rd script, since it is p2wpkh script = scripts.at(2); } else { // Else take the 2nd script, since it is p2pkh script = scripts.at(1); } return true; } else { return false; } } static RPCHelpMan generatetodescriptor() { return RPCHelpMan{ "generatetodescriptor", "\nMine blocks immediately to a specified descriptor (before the RPC call returns)\n", { {"num_blocks", RPCArg::Type::NUM, RPCArg::Optional::NO, "How many blocks are generated immediately."}, {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor to send the newly generated bitcoin to."}, {"maxtries", RPCArg::Type::NUM, RPCArg::Default{DEFAULT_MAX_TRIES}, "How many iterations to try."}, }, RPCResult{ RPCResult::Type::ARR, "", "hashes of blocks generated", { {RPCResult::Type::STR_HEX, "", "blockhash"}, } }, RPCExamples{ "\nGenerate 11 blocks to mydesc\n" + HelpExampleCli("generatetodescriptor", "11 \"mydesc\"")}, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const int num_blocks{request.params[0].get_int()}; const uint64_t max_tries{request.params[2].isNull() ? DEFAULT_MAX_TRIES : request.params[2].get_int()}; CScript coinbase_script; std::string error; if (!getScriptFromDescriptor(request.params[1].get_str(), coinbase_script, error)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error); } NodeContext& node = EnsureAnyNodeContext(request.context); const CTxMemPool& mempool = EnsureMemPool(node); ChainstateManager& chainman = EnsureChainman(node); return generateBlocks(chainman, mempool, coinbase_script, num_blocks, max_tries); }, }; } static RPCHelpMan generate() { return RPCHelpMan{"generate", "has been replaced by the -generate cli option. Refer to -help for more information.", {}, {}, RPCExamples{""}, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { throw JSONRPCError(RPC_METHOD_NOT_FOUND, self.ToString()); }}; } static RPCHelpMan generatetoaddress() { return RPCHelpMan{"generatetoaddress", "\nMine blocks immediately to a specified address (before the RPC call returns)\n", { {"nblocks", RPCArg::Type::NUM, RPCArg::Optional::NO, "How many blocks are generated immediately."}, {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The address to send the newly generated bitcoin to."}, {"maxtries", RPCArg::Type::NUM, RPCArg::Default{DEFAULT_MAX_TRIES}, "How many iterations to try."}, }, RPCResult{ RPCResult::Type::ARR, "", "hashes of blocks generated", { {RPCResult::Type::STR_HEX, "", "blockhash"}, }}, RPCExamples{ "\nGenerate 11 blocks to myaddress\n" + HelpExampleCli("generatetoaddress", "11 \"myaddress\"") + "If you are using the " PACKAGE_NAME " wallet, you can get a new address to send the newly generated bitcoin to with:\n" + HelpExampleCli("getnewaddress", "") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const int num_blocks{request.params[0].get_int()}; const uint64_t max_tries{request.params[2].isNull() ? DEFAULT_MAX_TRIES : request.params[2].get_int()}; CTxDestination destination = DecodeDestination(request.params[1].get_str()); if (!IsValidDestination(destination)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address"); } NodeContext& node = EnsureAnyNodeContext(request.context); const CTxMemPool& mempool = EnsureMemPool(node); ChainstateManager& chainman = EnsureChainman(node); CScript coinbase_script = GetScriptForDestination(destination); return generateBlocks(chainman, mempool, coinbase_script, num_blocks, max_tries); }, }; } static RPCHelpMan generateblock() { return RPCHelpMan{"generateblock", "\nMine a block with a set of ordered transactions immediately to a specified address or descriptor (before the RPC call returns)\n", { {"output", RPCArg::Type::STR, RPCArg::Optional::NO, "The address or descriptor to send the newly generated bitcoin to."}, {"transactions", RPCArg::Type::ARR, RPCArg::Optional::NO, "An array of hex strings which are either txids or raw transactions.\n" "Txids must reference transactions currently in the mempool.\n" "All transactions must be valid and in valid order, otherwise the block will be rejected.", { {"rawtx/txid", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, ""}, }, }, }, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR_HEX, "hash", "hash of generated block"}, } }, RPCExamples{ "\nGenerate a block to myaddress, with txs rawtx and mempool_txid\n" + HelpExampleCli("generateblock", R"("myaddress" '["rawtx", "mempool_txid"]')") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const auto address_or_descriptor = request.params[0].get_str(); CScript coinbase_script; std::string error; if (!getScriptFromDescriptor(address_or_descriptor, coinbase_script, error)) { const auto destination = DecodeDestination(address_or_descriptor); if (!IsValidDestination(destination)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address or descriptor"); } coinbase_script = GetScriptForDestination(destination); } NodeContext& node = EnsureAnyNodeContext(request.context); const CTxMemPool& mempool = EnsureMemPool(node); std::vector<CTransactionRef> txs; const auto raw_txs_or_txids = request.params[1].get_array(); for (size_t i = 0; i < raw_txs_or_txids.size(); i++) { const auto str(raw_txs_or_txids[i].get_str()); uint256 hash; CMutableTransaction mtx; if (ParseHashStr(str, hash)) { const auto tx = mempool.get(hash); if (!tx) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Transaction %s not in mempool.", str)); } txs.emplace_back(tx); } else if (DecodeHexTx(mtx, str)) { txs.push_back(MakeTransactionRef(std::move(mtx))); } else { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("Transaction decode failed for %s. Make sure the tx has at least one input.", str)); } } CChainParams chainparams(Params()); CBlock block; ChainstateManager& chainman = EnsureChainman(node); { LOCK(cs_main); CTxMemPool empty_mempool; std::unique_ptr<CBlockTemplate> blocktemplate(BlockAssembler(chainman.ActiveChainstate(), empty_mempool, chainparams).CreateNewBlock(coinbase_script)); if (!blocktemplate) { throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block"); } block = blocktemplate->block; } CHECK_NONFATAL(block.vtx.size() == 1); // Add transactions block.vtx.insert(block.vtx.end(), txs.begin(), txs.end()); RegenerateCommitments(block, chainman); { LOCK(cs_main); BlockValidationState state; if (!TestBlockValidity(state, chainparams, chainman.ActiveChainstate(), block, chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock), false, false)) { throw JSONRPCError(RPC_VERIFY_ERROR, strprintf("TestBlockValidity failed: %s", state.ToString())); } } uint256 block_hash; uint64_t max_tries{DEFAULT_MAX_TRIES}; unsigned int extra_nonce{0}; if (!GenerateBlock(chainman, block, max_tries, extra_nonce, block_hash) || block_hash.IsNull()) { throw JSONRPCError(RPC_MISC_ERROR, "Failed to make block."); } UniValue obj(UniValue::VOBJ); obj.pushKV("hash", block_hash.GetHex()); return obj; }, }; } static RPCHelpMan getmininginfo() { return RPCHelpMan{"getmininginfo", "\nReturns a json object containing mining-related information.", {}, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::NUM, "blocks", "The current block"}, {RPCResult::Type::NUM, "currentblockweight", /* optional */ true, "The block weight of the last assembled block (only present if a block was ever assembled)"}, {RPCResult::Type::NUM, "currentblocktx", /* optional */ true, "The number of block transactions of the last assembled block (only present if a block was ever assembled)"}, {RPCResult::Type::NUM, "difficulty", "The current difficulty"}, {RPCResult::Type::NUM, "networkhashps", "The network hashes per second"}, {RPCResult::Type::NUM, "pooledtx", "The size of the mempool"}, {RPCResult::Type::STR, "chain", "current network name (main, test, signet, regtest)"}, {RPCResult::Type::STR, "warnings", "any network and blockchain warnings"}, }}, RPCExamples{ HelpExampleCli("getmininginfo", "") + HelpExampleRpc("getmininginfo", "") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { NodeContext& node = EnsureAnyNodeContext(request.context); const CTxMemPool& mempool = EnsureMemPool(node); ChainstateManager& chainman = EnsureChainman(node); LOCK(cs_main); const CChain& active_chain = chainman.ActiveChain(); UniValue obj(UniValue::VOBJ); obj.pushKV("blocks", active_chain.Height()); if (BlockAssembler::m_last_block_weight) obj.pushKV("currentblockweight", *BlockAssembler::m_last_block_weight); if (BlockAssembler::m_last_block_num_txs) obj.pushKV("currentblocktx", *BlockAssembler::m_last_block_num_txs); obj.pushKV("difficulty", (double)GetDifficulty(active_chain.Tip())); obj.pushKV("networkhashps", getnetworkhashps().HandleRequest(request)); obj.pushKV("pooledtx", (uint64_t)mempool.size()); obj.pushKV("chain", Params().NetworkIDString()); obj.pushKV("warnings", GetWarnings(false).original); return obj; }, }; } // NOTE: Unlike wallet RPC (which use BTC values), mining RPCs follow GBT (BIP 22) in using satoshi amounts static RPCHelpMan prioritisetransaction() { return RPCHelpMan{"prioritisetransaction", "Accepts the transaction into mined blocks at a higher (or lower) priority\n", { {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id."}, {"dummy", RPCArg::Type::NUM, RPCArg::Optional::OMITTED_NAMED_ARG, "API-Compatibility for previous API. Must be zero or null.\n" " DEPRECATED. For forward compatibility use named arguments and omit this parameter."}, {"fee_delta", RPCArg::Type::NUM, RPCArg::Optional::NO, "The fee value (in satoshis) to add (or subtract, if negative).\n" " Note, that this value is not a fee rate. It is a value to modify absolute fee of the TX.\n" " The fee is not actually paid, only the algorithm for selecting transactions into a block\n" " considers the transaction as it would have paid a higher (or lower) fee."}, }, RPCResult{ RPCResult::Type::BOOL, "", "Returns true"}, RPCExamples{ HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000") + HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { LOCK(cs_main); uint256 hash(ParseHashV(request.params[0], "txid")); CAmount nAmount = request.params[2].get_int64(); if (!(request.params[1].isNull() || request.params[1].get_real() == 0)) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Priority is no longer supported, dummy argument to prioritisetransaction must be 0."); } EnsureAnyMemPool(request.context).PrioritiseTransaction(hash, nAmount); return true; }, }; } // NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller static UniValue BIP22ValidationResult(const BlockValidationState& state) { if (state.IsValid()) return NullUniValue; if (state.IsError()) throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString()); if (state.IsInvalid()) { std::string strRejectReason = state.GetRejectReason(); if (strRejectReason.empty()) return "rejected"; return strRejectReason; } // Should be impossible return "valid?"; } static std::string gbt_vb_name(const Consensus::DeploymentPos pos) { const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos]; std::string s = vbinfo.name; if (!vbinfo.gbt_force) { s.insert(s.begin(), '!'); } return s; } static RPCHelpMan getblocktemplate() { return RPCHelpMan{"getblocktemplate", "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n" "It returns data needed to construct a block to work on.\n" "For full specification, see BIPs 22, 23, 9, and 145:\n" " https://github.com/bitcoin/bips/blob/master/bip-0022.mediawiki\n" " https://github.com/bitcoin/bips/blob/master/bip-0023.mediawiki\n" " https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki#getblocktemplate_changes\n" " https://github.com/bitcoin/bips/blob/master/bip-0145.mediawiki\n", { {"template_request", RPCArg::Type::OBJ, RPCArg::Default{UniValue::VOBJ}, "Format of the template", { {"mode", RPCArg::Type::STR, /* treat as named arg */ RPCArg::Optional::OMITTED_NAMED_ARG, "This must be set to \"template\", \"proposal\" (see BIP 23), or omitted"}, {"capabilities", RPCArg::Type::ARR, /* treat as named arg */ RPCArg::Optional::OMITTED_NAMED_ARG, "A list of strings", { {"str", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "client side supported feature, 'longpoll', 'coinbasevalue', 'proposal', 'serverlist', 'workid'"}, }}, {"rules", RPCArg::Type::ARR, RPCArg::Optional::NO, "A list of strings", { {"segwit", RPCArg::Type::STR, RPCArg::Optional::NO, "(literal) indicates client side segwit support"}, {"str", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "other client side supported softfork deployment"}, }}, }, "\"template_request\""}, }, { RPCResult{"If the proposal was accepted with mode=='proposal'", RPCResult::Type::NONE, "", ""}, RPCResult{"If the proposal was not accepted with mode=='proposal'", RPCResult::Type::STR, "", "According to BIP22"}, RPCResult{"Otherwise", RPCResult::Type::OBJ, "", "", { {RPCResult::Type::NUM, "version", "The preferred block version"}, {RPCResult::Type::ARR, "rules", "specific block rules that are to be enforced", { {RPCResult::Type::STR, "", "name of a rule the client must understand to some extent; see BIP 9 for format"}, }}, {RPCResult::Type::OBJ_DYN, "vbavailable", "set of pending, supported versionbit (BIP 9) softfork deployments", { {RPCResult::Type::NUM, "rulename", "identifies the bit number as indicating acceptance and readiness for the named softfork rule"}, }}, {RPCResult::Type::NUM, "vbrequired", "bit mask of versionbits the server requires set in submissions"}, {RPCResult::Type::STR, "previousblockhash", "The hash of current highest block"}, {RPCResult::Type::ARR, "transactions", "contents of non-coinbase transactions that should be included in the next block", { {RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR_HEX, "data", "transaction data encoded in hexadecimal (byte-for-byte)"}, {RPCResult::Type::STR_HEX, "txid", "transaction id encoded in little-endian hexadecimal"}, {RPCResult::Type::STR_HEX, "hash", "hash encoded in little-endian hexadecimal (including witness data)"}, {RPCResult::Type::ARR, "depends", "array of numbers", { {RPCResult::Type::NUM, "", "transactions before this one (by 1-based index in 'transactions' list) that must be present in the final block if this one is"}, }}, {RPCResult::Type::NUM, "fee", "difference in value between transaction inputs and outputs (in satoshis); for coinbase transactions, this is a negative Number of the total collected block fees (ie, not including the block subsidy); if key is not present, fee is unknown and clients MUST NOT assume there isn't one"}, {RPCResult::Type::NUM, "sigops", "total SigOps cost, as counted for purposes of block limits; if key is not present, sigop cost is unknown and clients MUST NOT assume it is zero"}, {RPCResult::Type::NUM, "weight", "total transaction weight, as counted for purposes of block limits"}, }}, }}, {RPCResult::Type::OBJ_DYN, "coinbaseaux", "data that should be included in the coinbase's scriptSig content", { {RPCResult::Type::STR_HEX, "key", "values must be in the coinbase (keys may be ignored)"}, }}, {RPCResult::Type::NUM, "coinbasevalue", "maximum allowable input to coinbase transaction, including the generation award and transaction fees (in satoshis)"}, {RPCResult::Type::STR, "longpollid", "an id to include with a request to longpoll on an update to this template"}, {RPCResult::Type::STR, "target", "The hash target"}, {RPCResult::Type::NUM_TIME, "mintime", "The minimum timestamp appropriate for the next block time, expressed in " + UNIX_EPOCH_TIME}, {RPCResult::Type::ARR, "mutable", "list of ways the block template may be changed", { {RPCResult::Type::STR, "value", "A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'"}, }}, {RPCResult::Type::STR_HEX, "noncerange", "A range of valid nonces"}, {RPCResult::Type::NUM, "sigoplimit", "limit of sigops in blocks"}, {RPCResult::Type::NUM, "sizelimit", "limit of block size"}, {RPCResult::Type::NUM, "weightlimit", "limit of block weight"}, {RPCResult::Type::NUM_TIME, "curtime", "current timestamp in " + UNIX_EPOCH_TIME}, {RPCResult::Type::STR, "bits", "compressed target of next block"}, {RPCResult::Type::NUM, "height", "The height of the next block"}, {RPCResult::Type::STR, "default_witness_commitment", /* optional */ true, "a valid witness commitment for the unmodified block template"}, }}, }, RPCExamples{ HelpExampleCli("getblocktemplate", "'{\"rules\": [\"segwit\"]}'") + HelpExampleRpc("getblocktemplate", "{\"rules\": [\"segwit\"]}") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { NodeContext& node = EnsureAnyNodeContext(request.context); ChainstateManager& chainman = EnsureChainman(node); LOCK(cs_main); std::string strMode = "template"; UniValue lpval = NullUniValue; std::set<std::string> setClientRules; int64_t nMaxVersionPreVB = -1; CChainState& active_chainstate = chainman.ActiveChainstate(); CChain& active_chain = active_chainstate.m_chain; if (!request.params[0].isNull()) { const UniValue& oparam = request.params[0].get_obj(); const UniValue& modeval = find_value(oparam, "mode"); if (modeval.isStr()) strMode = modeval.get_str(); else if (modeval.isNull()) { /* Do nothing */ } else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); lpval = find_value(oparam, "longpollid"); if (strMode == "proposal") { const UniValue& dataval = find_value(oparam, "data"); if (!dataval.isStr()) throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal"); CBlock block; if (!DecodeHexBlk(block, dataval.get_str())) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed"); uint256 hash = block.GetHash(); const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(hash); if (pindex) { if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) return "duplicate"; if (pindex->nStatus & BLOCK_FAILED_MASK) return "duplicate-invalid"; return "duplicate-inconclusive"; } CBlockIndex* const pindexPrev = active_chain.Tip(); // TestBlockValidity only supports blocks built on the current Tip if (block.hashPrevBlock != pindexPrev->GetBlockHash()) return "inconclusive-not-best-prevblk"; BlockValidationState state; TestBlockValidity(state, Params(), active_chainstate, block, pindexPrev, false, true); return BIP22ValidationResult(state); } const UniValue& aClientRules = find_value(oparam, "rules"); if (aClientRules.isArray()) { for (unsigned int i = 0; i < aClientRules.size(); ++i) { const UniValue& v = aClientRules[i]; setClientRules.insert(v.get_str()); } } else { // NOTE: It is important that this NOT be read if versionbits is supported const UniValue& uvMaxVersion = find_value(oparam, "maxversion"); if (uvMaxVersion.isNum()) { nMaxVersionPreVB = uvMaxVersion.get_int64(); } } } if (strMode != "template") throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); if (!Params().IsTestChain()) { const CConnman& connman = EnsureConnman(node); if (connman.GetNodeCount(ConnectionDirection::Both) == 0) { throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, PACKAGE_NAME " is not connected!"); } if (active_chainstate.IsInitialBlockDownload()) { throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, PACKAGE_NAME " is in initial sync and waiting for blocks..."); } } static unsigned int nTransactionsUpdatedLast; const CTxMemPool& mempool = EnsureMemPool(node); if (!lpval.isNull()) { // Wait to respond until either the best block changes, OR a minute has passed and there are more transactions uint256 hashWatchedChain; std::chrono::steady_clock::time_point checktxtime; unsigned int nTransactionsUpdatedLastLP; if (lpval.isStr()) { // Format: <hashBestChain><nTransactionsUpdatedLast> std::string lpstr = lpval.get_str(); hashWatchedChain = ParseHashV(lpstr.substr(0, 64), "longpollid"); nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64)); } else { // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier hashWatchedChain = active_chain.Tip()->GetBlockHash(); nTransactionsUpdatedLastLP = nTransactionsUpdatedLast; } // Release lock while waiting LEAVE_CRITICAL_SECTION(cs_main); { checktxtime = std::chrono::steady_clock::now() + std::chrono::minutes(1); WAIT_LOCK(g_best_block_mutex, lock); while (g_best_block == hashWatchedChain && IsRPCRunning()) { if (g_best_block_cv.wait_until(lock, checktxtime) == std::cv_status::timeout) { // Timeout: Check transactions for update // without holding the mempool lock to avoid deadlocks if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP) break; checktxtime += std::chrono::seconds(10); } } } ENTER_CRITICAL_SECTION(cs_main); if (!IsRPCRunning()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down"); // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners? } const Consensus::Params& consensusParams = Params().GetConsensus(); // GBT must be called with 'signet' set in the rules for signet chains if (consensusParams.signet_blocks && setClientRules.count("signet") != 1) { throw JSONRPCError(RPC_INVALID_PARAMETER, "getblocktemplate must be called with the signet rule set (call with {\"rules\": [\"segwit\", \"signet\"]})"); } // GBT must be called with 'segwit' set in the rules if (setClientRules.count("segwit") != 1) { throw JSONRPCError(RPC_INVALID_PARAMETER, "getblocktemplate must be called with the segwit rule set (call with {\"rules\": [\"segwit\"]})"); } // Update block static CBlockIndex* pindexPrev; static int64_t nStart; static std::unique_ptr<CBlockTemplate> pblocktemplate; if (pindexPrev != active_chain.Tip() || (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5)) { // Clear pindexPrev so future calls make a new block, despite any failures from here on pindexPrev = nullptr; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); CBlockIndex* pindexPrevNew = active_chain.Tip(); nStart = GetTime(); // Create new block CScript scriptDummy = CScript() << OP_TRUE; pblocktemplate = BlockAssembler(active_chainstate, mempool, Params()).CreateNewBlock(scriptDummy); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } CHECK_NONFATAL(pindexPrev); CBlock* pblock = &pblocktemplate->block; // pointer for convenience // Update nTime UpdateTime(pblock, consensusParams, pindexPrev); pblock->nNonce = 0; // NOTE: If at some point we support pre-segwit miners post-segwit-activation, this needs to take segwit support into consideration const bool fPreSegWit = !DeploymentActiveAfter(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT); UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal"); UniValue transactions(UniValue::VARR); std::map<uint256, int64_t> setTxIndex; int i = 0; for (const auto& it : pblock->vtx) { const CTransaction& tx = *it; uint256 txHash = tx.GetHash(); setTxIndex[txHash] = i++; if (tx.IsCoinBase()) continue; UniValue entry(UniValue::VOBJ); entry.pushKV("data", EncodeHexTx(tx)); entry.pushKV("txid", txHash.GetHex()); entry.pushKV("hash", tx.GetWitnessHash().GetHex()); UniValue deps(UniValue::VARR); for (const CTxIn &in : tx.vin) { if (setTxIndex.count(in.prevout.hash)) deps.push_back(setTxIndex[in.prevout.hash]); } entry.pushKV("depends", deps); int index_in_template = i - 1; entry.pushKV("fee", pblocktemplate->vTxFees[index_in_template]); int64_t nTxSigOps = pblocktemplate->vTxSigOpsCost[index_in_template]; if (fPreSegWit) { CHECK_NONFATAL(nTxSigOps % WITNESS_SCALE_FACTOR == 0); nTxSigOps /= WITNESS_SCALE_FACTOR; } entry.pushKV("sigops", nTxSigOps); entry.pushKV("weight", GetTransactionWeight(tx)); transactions.push_back(entry); } UniValue aux(UniValue::VOBJ); arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits); UniValue aMutable(UniValue::VARR); aMutable.push_back("time"); aMutable.push_back("transactions"); aMutable.push_back("prevblock"); UniValue result(UniValue::VOBJ); result.pushKV("capabilities", aCaps); UniValue aRules(UniValue::VARR); aRules.push_back("csv"); if (!fPreSegWit) aRules.push_back("!segwit"); if (consensusParams.signet_blocks) { // indicate to miner that they must understand signet rules // when attempting to mine with this template aRules.push_back("!signet"); } UniValue vbavailable(UniValue::VOBJ); for (int j = 0; j < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j) { Consensus::DeploymentPos pos = Consensus::DeploymentPos(j); ThresholdState state = g_versionbitscache.State(pindexPrev, consensusParams, pos); switch (state) { case ThresholdState::DEFINED: case ThresholdState::FAILED: // Not exposed to GBT at all break; case ThresholdState::LOCKED_IN: // Ensure bit is set in block version pblock->nVersion |= g_versionbitscache.Mask(consensusParams, pos); [[fallthrough]]; case ThresholdState::STARTED: { const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos]; vbavailable.pushKV(gbt_vb_name(pos), consensusParams.vDeployments[pos].bit); if (setClientRules.find(vbinfo.name) == setClientRules.end()) { if (!vbinfo.gbt_force) { // If the client doesn't support this, don't indicate it in the [default] version pblock->nVersion &= ~g_versionbitscache.Mask(consensusParams, pos); } } break; } case ThresholdState::ACTIVE: { // Add to rules only const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos]; aRules.push_back(gbt_vb_name(pos)); if (setClientRules.find(vbinfo.name) == setClientRules.end()) { // Not supported by the client; make sure it's safe to proceed if (!vbinfo.gbt_force) { // If we do anything other than throw an exception here, be sure version/force isn't sent to old clients throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Support for '%s' rule requires explicit client support", vbinfo.name)); } } break; } } } result.pushKV("version", pblock->nVersion); result.pushKV("rules", aRules); result.pushKV("vbavailable", vbavailable); result.pushKV("vbrequired", int(0)); if (nMaxVersionPreVB >= 2) { // If VB is supported by the client, nMaxVersionPreVB is -1, so we won't get here // Because BIP 34 changed how the generation transaction is serialized, we can only use version/force back to v2 blocks // This is safe to do [otherwise-]unconditionally only because we are throwing an exception above if a non-force deployment gets activated // Note that this can probably also be removed entirely after the first BIP9 non-force deployment (ie, probably segwit) gets activated aMutable.push_back("version/force"); } result.pushKV("previousblockhash", pblock->hashPrevBlock.GetHex()); result.pushKV("transactions", transactions); result.pushKV("coinbaseaux", aux); result.pushKV("coinbasevalue", (int64_t)pblock->vtx[0]->vout[0].nValue); result.pushKV("longpollid", active_chain.Tip()->GetBlockHash().GetHex() + ToString(nTransactionsUpdatedLast)); result.pushKV("target", hashTarget.GetHex()); result.pushKV("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1); result.pushKV("mutable", aMutable); result.pushKV("noncerange", "00000000ffffffff"); int64_t nSigOpLimit = MAX_BLOCK_SIGOPS_COST; int64_t nSizeLimit = MAX_BLOCK_SERIALIZED_SIZE; if (fPreSegWit) { CHECK_NONFATAL(nSigOpLimit % WITNESS_SCALE_FACTOR == 0); nSigOpLimit /= WITNESS_SCALE_FACTOR; CHECK_NONFATAL(nSizeLimit % WITNESS_SCALE_FACTOR == 0); nSizeLimit /= WITNESS_SCALE_FACTOR; } result.pushKV("sigoplimit", nSigOpLimit); result.pushKV("sizelimit", nSizeLimit); if (!fPreSegWit) { result.pushKV("weightlimit", (int64_t)MAX_BLOCK_WEIGHT); } result.pushKV("curtime", pblock->GetBlockTime()); result.pushKV("bits", strprintf("%08x", pblock->nBits)); result.pushKV("height", (int64_t)(pindexPrev->nHeight+1)); if (consensusParams.signet_blocks) { result.pushKV("signet_challenge", HexStr(consensusParams.signet_challenge)); } if (!pblocktemplate->vchCoinbaseCommitment.empty()) { result.pushKV("default_witness_commitment", HexStr(pblocktemplate->vchCoinbaseCommitment)); } return result; }, }; } class submitblock_StateCatcher final : public CValidationInterface { public: uint256 hash; bool found; BlockValidationState state; explicit submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), found(false), state() {} protected: void BlockChecked(const CBlock& block, const BlockValidationState& stateIn) override { if (block.GetHash() != hash) return; found = true; state = stateIn; } }; static RPCHelpMan submitblock() { // We allow 2 arguments for compliance with BIP22. Argument 2 is ignored. return RPCHelpMan{"submitblock", "\nAttempts to submit new block to network.\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n", { {"hexdata", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hex-encoded block data to submit"}, {"dummy", RPCArg::Type::STR, RPCArg::DefaultHint{"ignored"}, "dummy value, for compatibility with BIP22. This value is ignored."}, }, { RPCResult{"If the block was accepted", RPCResult::Type::NONE, "", ""}, RPCResult{"Otherwise", RPCResult::Type::STR, "", "According to BIP22"}, }, RPCExamples{ HelpExampleCli("submitblock", "\"mydata\"") + HelpExampleRpc("submitblock", "\"mydata\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>(); CBlock& block = *blockptr; if (!DecodeHexBlk(block, request.params[0].get_str())) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed"); } if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block does not start with a coinbase"); } ChainstateManager& chainman = EnsureAnyChainman(request.context); uint256 hash = block.GetHash(); { LOCK(cs_main); const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(hash); if (pindex) { if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) { return "duplicate"; } if (pindex->nStatus & BLOCK_FAILED_MASK) { return "duplicate-invalid"; } } } { LOCK(cs_main); const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock); if (pindex) { UpdateUncommittedBlockStructures(block, pindex, Params().GetConsensus()); } } bool new_block; auto sc = std::make_shared<submitblock_StateCatcher>(block.GetHash()); RegisterSharedValidationInterface(sc); bool accepted = chainman.ProcessNewBlock(Params(), blockptr, /* fForceProcessing */ true, /* fNewBlock */ &new_block); UnregisterSharedValidationInterface(sc); if (!new_block && accepted) { return "duplicate"; } if (!sc->found) { return "inconclusive"; } return BIP22ValidationResult(sc->state); }, }; } static RPCHelpMan submitheader() { return RPCHelpMan{"submitheader", "\nDecode the given hexdata as a header and submit it as a candidate chain tip if valid." "\nThrows when the header is invalid.\n", { {"hexdata", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hex-encoded block header data"}, }, RPCResult{ RPCResult::Type::NONE, "", "None"}, RPCExamples{ HelpExampleCli("submitheader", "\"aabbcc\"") + HelpExampleRpc("submitheader", "\"aabbcc\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { CBlockHeader h; if (!DecodeHexBlockHeader(h, request.params[0].get_str())) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block header decode failed"); } ChainstateManager& chainman = EnsureAnyChainman(request.context); { LOCK(cs_main); if (!chainman.m_blockman.LookupBlockIndex(h.hashPrevBlock)) { throw JSONRPCError(RPC_VERIFY_ERROR, "Must submit previous header (" + h.hashPrevBlock.GetHex() + ") first"); } } BlockValidationState state; chainman.ProcessNewBlockHeaders({h}, state, Params()); if (state.IsValid()) return NullUniValue; if (state.IsError()) { throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString()); } throw JSONRPCError(RPC_VERIFY_ERROR, state.GetRejectReason()); }, }; } static RPCHelpMan estimatesmartfee() { return RPCHelpMan{"estimatesmartfee", "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n" "confirmation within conf_target blocks if possible and return the number of blocks\n" "for which the estimate is valid. Uses virtual transaction size as defined\n" "in BIP 141 (witness data is discounted).\n", { {"conf_target", RPCArg::Type::NUM, RPCArg::Optional::NO, "Confirmation target in blocks (1 - 1008)"}, {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"conservative"}, "The fee estimate mode.\n" " Whether to return a more conservative estimate which also satisfies\n" " a longer history. A conservative estimate potentially returns a\n" " higher feerate and is more likely to be sufficient for the desired\n" " target, but is not as responsive to short term drops in the\n" " prevailing fee market. Must be one of (case insensitive):\n" "\"" + FeeModes("\"\n\"") + "\""}, }, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::NUM, "feerate", /* optional */ true, "estimate fee rate in " + CURRENCY_UNIT + "/kvB (only present if no errors were encountered)"}, {RPCResult::Type::ARR, "errors", /* optional */ true, "Errors encountered during processing (if there are any)", { {RPCResult::Type::STR, "", "error"}, }}, {RPCResult::Type::NUM, "blocks", "block number where estimate was found\n" "The request target will be clamped between 2 and the highest target\n" "fee estimation is able to return based on how long it has been running.\n" "An error is returned if not enough transactions and blocks\n" "have been observed to make an estimate for any number of blocks."}, }}, RPCExamples{ HelpExampleCli("estimatesmartfee", "6") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { RPCTypeCheck(request.params, {UniValue::VNUM, UniValue::VSTR}); RPCTypeCheckArgument(request.params[0], UniValue::VNUM); CBlockPolicyEstimator& fee_estimator = EnsureAnyFeeEstimator(request.context); unsigned int max_target = fee_estimator.HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE); unsigned int conf_target = ParseConfirmTarget(request.params[0], max_target); bool conservative = true; if (!request.params[1].isNull()) { FeeEstimateMode fee_mode; if (!FeeModeFromString(request.params[1].get_str(), fee_mode)) { throw JSONRPCError(RPC_INVALID_PARAMETER, InvalidEstimateModeErrorMessage()); } if (fee_mode == FeeEstimateMode::ECONOMICAL) conservative = false; } UniValue result(UniValue::VOBJ); UniValue errors(UniValue::VARR); FeeCalculation feeCalc; CFeeRate feeRate = fee_estimator.estimateSmartFee(conf_target, &feeCalc, conservative); if (feeRate != CFeeRate(0)) { result.pushKV("feerate", ValueFromAmount(feeRate.GetFeePerK())); } else { errors.push_back("Insufficient data or no feerate found"); result.pushKV("errors", errors); } result.pushKV("blocks", feeCalc.returnedTarget); return result; }, }; } static RPCHelpMan estimaterawfee() { return RPCHelpMan{"estimaterawfee", "\nWARNING: This interface is unstable and may disappear or change!\n" "\nWARNING: This is an advanced API call that is tightly coupled to the specific\n" " implementation of fee estimation. The parameters it can be called with\n" " and the results it returns will change if the internal implementation changes.\n" "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n" "confirmation within conf_target blocks if possible. Uses virtual transaction size as\n" "defined in BIP 141 (witness data is discounted).\n", { {"conf_target", RPCArg::Type::NUM, RPCArg::Optional::NO, "Confirmation target in blocks (1 - 1008)"}, {"threshold", RPCArg::Type::NUM, RPCArg::Default{0.95}, "The proportion of transactions in a given feerate range that must have been\n" " confirmed within conf_target in order to consider those feerates as high enough and proceed to check\n" " lower buckets."}, }, RPCResult{ RPCResult::Type::OBJ, "", "Results are returned for any horizon which tracks blocks up to the confirmation target", { {RPCResult::Type::OBJ, "short", /* optional */ true, "estimate for short time horizon", { {RPCResult::Type::NUM, "feerate", /* optional */ true, "estimate fee rate in " + CURRENCY_UNIT + "/kvB"}, {RPCResult::Type::NUM, "decay", "exponential decay (per block) for historical moving average of confirmation data"}, {RPCResult::Type::NUM, "scale", "The resolution of confirmation targets at this time horizon"}, {RPCResult::Type::OBJ, "pass", /* optional */ true, "information about the lowest range of feerates to succeed in meeting the threshold", { {RPCResult::Type::NUM, "startrange", "start of feerate range"}, {RPCResult::Type::NUM, "endrange", "end of feerate range"}, {RPCResult::Type::NUM, "withintarget", "number of txs over history horizon in the feerate range that were confirmed within target"}, {RPCResult::Type::NUM, "totalconfirmed", "number of txs over history horizon in the feerate range that were confirmed at any point"}, {RPCResult::Type::NUM, "inmempool", "current number of txs in mempool in the feerate range unconfirmed for at least target blocks"}, {RPCResult::Type::NUM, "leftmempool", "number of txs over history horizon in the feerate range that left mempool unconfirmed after target"}, }}, {RPCResult::Type::OBJ, "fail", /* optional */ true, "information about the highest range of feerates to fail to meet the threshold", { {RPCResult::Type::ELISION, "", ""}, }}, {RPCResult::Type::ARR, "errors", /* optional */ true, "Errors encountered during processing (if there are any)", { {RPCResult::Type::STR, "error", ""}, }}, }}, {RPCResult::Type::OBJ, "medium", /* optional */ true, "estimate for medium time horizon", { {RPCResult::Type::ELISION, "", ""}, }}, {RPCResult::Type::OBJ, "long", /* optional */ true, "estimate for long time horizon", { {RPCResult::Type::ELISION, "", ""}, }}, }}, RPCExamples{ HelpExampleCli("estimaterawfee", "6 0.9") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { RPCTypeCheck(request.params, {UniValue::VNUM, UniValue::VNUM}, true); RPCTypeCheckArgument(request.params[0], UniValue::VNUM); CBlockPolicyEstimator& fee_estimator = EnsureAnyFeeEstimator(request.context); unsigned int max_target = fee_estimator.HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE); unsigned int conf_target = ParseConfirmTarget(request.params[0], max_target); double threshold = 0.95; if (!request.params[1].isNull()) { threshold = request.params[1].get_real(); } if (threshold < 0 || threshold > 1) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid threshold"); } UniValue result(UniValue::VOBJ); for (const FeeEstimateHorizon horizon : ALL_FEE_ESTIMATE_HORIZONS) { CFeeRate feeRate; EstimationResult buckets; // Only output results for horizons which track the target if (conf_target > fee_estimator.HighestTargetTracked(horizon)) continue; feeRate = fee_estimator.estimateRawFee(conf_target, threshold, horizon, &buckets); UniValue horizon_result(UniValue::VOBJ); UniValue errors(UniValue::VARR); UniValue passbucket(UniValue::VOBJ); passbucket.pushKV("startrange", round(buckets.pass.start)); passbucket.pushKV("endrange", round(buckets.pass.end)); passbucket.pushKV("withintarget", round(buckets.pass.withinTarget * 100.0) / 100.0); passbucket.pushKV("totalconfirmed", round(buckets.pass.totalConfirmed * 100.0) / 100.0); passbucket.pushKV("inmempool", round(buckets.pass.inMempool * 100.0) / 100.0); passbucket.pushKV("leftmempool", round(buckets.pass.leftMempool * 100.0) / 100.0); UniValue failbucket(UniValue::VOBJ); failbucket.pushKV("startrange", round(buckets.fail.start)); failbucket.pushKV("endrange", round(buckets.fail.end)); failbucket.pushKV("withintarget", round(buckets.fail.withinTarget * 100.0) / 100.0); failbucket.pushKV("totalconfirmed", round(buckets.fail.totalConfirmed * 100.0) / 100.0); failbucket.pushKV("inmempool", round(buckets.fail.inMempool * 100.0) / 100.0); failbucket.pushKV("leftmempool", round(buckets.fail.leftMempool * 100.0) / 100.0); // CFeeRate(0) is used to indicate error as a return value from estimateRawFee if (feeRate != CFeeRate(0)) { horizon_result.pushKV("feerate", ValueFromAmount(feeRate.GetFeePerK())); horizon_result.pushKV("decay", buckets.decay); horizon_result.pushKV("scale", (int)buckets.scale); horizon_result.pushKV("pass", passbucket); // buckets.fail.start == -1 indicates that all buckets passed, there is no fail bucket to output if (buckets.fail.start != -1) horizon_result.pushKV("fail", failbucket); } else { // Output only information that is still meaningful in the event of error horizon_result.pushKV("decay", buckets.decay); horizon_result.pushKV("scale", (int)buckets.scale); horizon_result.pushKV("fail", failbucket); errors.push_back("Insufficient data or no feerate found which meets threshold"); horizon_result.pushKV("errors",errors); } result.pushKV(StringForFeeEstimateHorizon(horizon), horizon_result); } return result; }, }; } void RegisterMiningRPCCommands(CRPCTable &t) { // clang-format off static const CRPCCommand commands[] = { // category actor (function) // --------------------- ----------------------- { "mining", &getnetworkhashps, }, { "mining", &getmininginfo, }, { "mining", &prioritisetransaction, }, { "mining", &getblocktemplate, }, { "mining", &submitblock, }, { "mining", &submitheader, }, { "generating", &generatetoaddress, }, { "generating", &generatetodescriptor, }, { "generating", &generateblock, }, { "util", &estimatesmartfee, }, { "hidden", &estimaterawfee, }, { "hidden", &generate, }, }; // clang-format on for (const auto& c : commands) { t.appendCommand(c.name, &c); } }
mit
whoisjake/thoughts
vendor/sequel/spec/extensions/string_date_time_spec.rb
3213
require File.join(File.dirname(__FILE__), 'spec_helper') context "String#to_time" do specify "should convert the string into a Time object" do "2007-07-11".to_time.should == Time.parse("2007-07-11") "06:30".to_time.should == Time.parse("06:30") end specify "should raise InvalidValue for an invalid time" do proc {'0000-00-00'.to_time}.should raise_error(Sequel::InvalidValue) end end context "String#to_date" do after do Sequel.convert_two_digit_years = true end specify "should convert the string into a Date object" do "2007-07-11".to_date.should == Date.parse("2007-07-11") end specify "should convert 2 digit years by default" do "July 11, 07".to_date.should == Date.parse("2007-07-11") end specify "should not convert 2 digit years if set not to" do Sequel.convert_two_digit_years = false "July 11, 07".to_date.should == Date.parse("0007-07-11") end specify "should raise InvalidValue for an invalid date" do proc {'0000-00-00'.to_date}.should raise_error(Sequel::InvalidValue) end end context "String#to_datetime" do after do Sequel.convert_two_digit_years = true end specify "should convert the string into a DateTime object" do "2007-07-11 10:11:12a".to_datetime.should == DateTime.parse("2007-07-11 10:11:12a") end specify "should convert 2 digit years by default" do "July 11, 07 10:11:12a".to_datetime.should == DateTime.parse("2007-07-11 10:11:12a") end specify "should not convert 2 digit years if set not to" do Sequel.convert_two_digit_years = false "July 11, 07 10:11:12a".to_datetime.should == DateTime.parse("0007-07-11 10:11:12a") end specify "should raise InvalidValue for an invalid date" do proc {'0000-00-00'.to_datetime}.should raise_error(Sequel::InvalidValue) end end context "String#to_sequel_time" do after do Sequel.datetime_class = Time Sequel.convert_two_digit_years = true end specify "should convert the string into a Time object by default" do "2007-07-11 10:11:12a".to_sequel_time.class.should == Time "2007-07-11 10:11:12a".to_sequel_time.should == Time.parse("2007-07-11 10:11:12a") end specify "should convert the string into a DateTime object if that is set" do Sequel.datetime_class = DateTime "2007-07-11 10:11:12a".to_sequel_time.class.should == DateTime "2007-07-11 10:11:12a".to_sequel_time.should == DateTime.parse("2007-07-11 10:11:12a") end specify "should convert 2 digit years by default if using DateTime class" do Sequel.datetime_class = DateTime "July 11, 07 10:11:12a".to_sequel_time.should == DateTime.parse("2007-07-11 10:11:12a") end specify "should not convert 2 digit years if set not to when using DateTime class" do Sequel.datetime_class = DateTime Sequel.convert_two_digit_years = false "July 11, 07 10:11:12a".to_sequel_time.should == DateTime.parse("0007-07-11 10:11:12a") end specify "should raise InvalidValue for an invalid time" do proc {'0000-00-00'.to_sequel_time}.should raise_error(Sequel::InvalidValue) Sequel.datetime_class = DateTime proc {'0000-00-00'.to_sequel_time}.should raise_error(Sequel::InvalidValue) end end
mit
crcn/nofactor.js
test/custom-test.js
746
var expect = require("expect.js"), nofactor = require(".."), custom = require("../lib/custom"), string = require("../lib/string"); describe("custom#", function () { var c = custom(string); it("can register a custom element", function () { c.registerElement("br", string.Element.extend({ toString: function () { return "<" + this._name + " />"; } })); }); it("can create and stringify the registered element", function () { expect(c.createElement("br").toString()).to.be("<br />"); }); it("can properly stringify the custom element when it's part of a div", function () { var div = c.createElement("div"); div.appendChild(c.createElement("br")); expect(div.toString()).to.be("<div><br /></div>") }) });
mit
nrc/rustc-perf
collector/benchmarks/cranelift-codegen/cranelift-codegen/src/isa/riscv/settings.rs
1711
//! RISC-V Settings. use crate::settings::{self, detail, Builder}; use core::fmt; // Include code generated by `cranelift-codegen/meta-python/gen_settings.py`. This file contains a public // `Flags` struct with an impl for all of the settings defined in // `cranelift-codegen/meta-python/isa/riscv/settings.py`. include!(concat!(env!("OUT_DIR"), "/settings-riscv.rs")); #[cfg(test)] mod tests { use super::{builder, Flags}; use crate::settings::{self, Configurable}; use std::string::ToString; #[test] fn display_default() { let shared = settings::Flags::new(settings::builder()); let b = builder(); let f = Flags::new(&shared, b); assert_eq!( f.to_string(), "[riscv]\n\ supports_m = false\n\ supports_a = false\n\ supports_f = false\n\ supports_d = false\n\ enable_m = true\n\ enable_e = false\n" ); // Predicates are not part of the Display output. assert_eq!(f.full_float(), false); } #[test] fn predicates() { let shared = settings::Flags::new(settings::builder()); let mut b = builder(); b.enable("supports_f").unwrap(); b.enable("supports_d").unwrap(); let f = Flags::new(&shared, b); assert_eq!(f.full_float(), true); let mut sb = settings::builder(); sb.set("enable_simd", "false").unwrap(); let shared = settings::Flags::new(sb); let mut b = builder(); b.enable("supports_f").unwrap(); b.enable("supports_d").unwrap(); let f = Flags::new(&shared, b); assert_eq!(f.full_float(), false); } }
mit
jackmagic313/azure-sdk-for-net
sdk/compute/Microsoft.Azure.Management.Compute/src/Generated/GalleryImagesOperationsExtensions.cs
23533
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Compute { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for GalleryImagesOperations. /// </summary> public static partial class GalleryImagesOperationsExtensions { /// <summary> /// Create or update a gallery image definition. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='galleryName'> /// The name of the Shared Image Gallery in which the Image Definition is to be /// created. /// </param> /// <param name='galleryImageName'> /// The name of the gallery image definition to be created or updated. The /// allowed characters are alphabets and numbers with dots, dashes, and periods /// allowed in the middle. The maximum length is 80 characters. /// </param> /// <param name='galleryImage'> /// Parameters supplied to the create or update gallery image operation. /// </param> public static GalleryImage CreateOrUpdate(this IGalleryImagesOperations operations, string resourceGroupName, string galleryName, string galleryImageName, GalleryImage galleryImage) { return operations.CreateOrUpdateAsync(resourceGroupName, galleryName, galleryImageName, galleryImage).GetAwaiter().GetResult(); } /// <summary> /// Create or update a gallery image definition. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='galleryName'> /// The name of the Shared Image Gallery in which the Image Definition is to be /// created. /// </param> /// <param name='galleryImageName'> /// The name of the gallery image definition to be created or updated. The /// allowed characters are alphabets and numbers with dots, dashes, and periods /// allowed in the middle. The maximum length is 80 characters. /// </param> /// <param name='galleryImage'> /// Parameters supplied to the create or update gallery image operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<GalleryImage> CreateOrUpdateAsync(this IGalleryImagesOperations operations, string resourceGroupName, string galleryName, string galleryImageName, GalleryImage galleryImage, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, galleryName, galleryImageName, galleryImage, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Update a gallery image definition. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='galleryName'> /// The name of the Shared Image Gallery in which the Image Definition is to be /// updated. /// </param> /// <param name='galleryImageName'> /// The name of the gallery image definition to be updated. The allowed /// characters are alphabets and numbers with dots, dashes, and periods allowed /// in the middle. The maximum length is 80 characters. /// </param> /// <param name='galleryImage'> /// Parameters supplied to the update gallery image operation. /// </param> public static GalleryImage Update(this IGalleryImagesOperations operations, string resourceGroupName, string galleryName, string galleryImageName, GalleryImageUpdate galleryImage) { return operations.UpdateAsync(resourceGroupName, galleryName, galleryImageName, galleryImage).GetAwaiter().GetResult(); } /// <summary> /// Update a gallery image definition. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='galleryName'> /// The name of the Shared Image Gallery in which the Image Definition is to be /// updated. /// </param> /// <param name='galleryImageName'> /// The name of the gallery image definition to be updated. The allowed /// characters are alphabets and numbers with dots, dashes, and periods allowed /// in the middle. The maximum length is 80 characters. /// </param> /// <param name='galleryImage'> /// Parameters supplied to the update gallery image operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<GalleryImage> UpdateAsync(this IGalleryImagesOperations operations, string resourceGroupName, string galleryName, string galleryImageName, GalleryImageUpdate galleryImage, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, galleryName, galleryImageName, galleryImage, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Retrieves information about a gallery image definition. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='galleryName'> /// The name of the Shared Image Gallery from which the Image Definitions are /// to be retrieved. /// </param> /// <param name='galleryImageName'> /// The name of the gallery image definition to be retrieved. /// </param> public static GalleryImage Get(this IGalleryImagesOperations operations, string resourceGroupName, string galleryName, string galleryImageName) { return operations.GetAsync(resourceGroupName, galleryName, galleryImageName).GetAwaiter().GetResult(); } /// <summary> /// Retrieves information about a gallery image definition. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='galleryName'> /// The name of the Shared Image Gallery from which the Image Definitions are /// to be retrieved. /// </param> /// <param name='galleryImageName'> /// The name of the gallery image definition to be retrieved. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<GalleryImage> GetAsync(this IGalleryImagesOperations operations, string resourceGroupName, string galleryName, string galleryImageName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, galleryName, galleryImageName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Delete a gallery image. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='galleryName'> /// The name of the Shared Image Gallery in which the Image Definition is to be /// deleted. /// </param> /// <param name='galleryImageName'> /// The name of the gallery image definition to be deleted. /// </param> public static void Delete(this IGalleryImagesOperations operations, string resourceGroupName, string galleryName, string galleryImageName) { operations.DeleteAsync(resourceGroupName, galleryName, galleryImageName).GetAwaiter().GetResult(); } /// <summary> /// Delete a gallery image. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='galleryName'> /// The name of the Shared Image Gallery in which the Image Definition is to be /// deleted. /// </param> /// <param name='galleryImageName'> /// The name of the gallery image definition to be deleted. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IGalleryImagesOperations operations, string resourceGroupName, string galleryName, string galleryImageName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, galleryName, galleryImageName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// List gallery image definitions in a gallery. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='galleryName'> /// The name of the Shared Image Gallery from which Image Definitions are to be /// listed. /// </param> public static IPage<GalleryImage> ListByGallery(this IGalleryImagesOperations operations, string resourceGroupName, string galleryName) { return operations.ListByGalleryAsync(resourceGroupName, galleryName).GetAwaiter().GetResult(); } /// <summary> /// List gallery image definitions in a gallery. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='galleryName'> /// The name of the Shared Image Gallery from which Image Definitions are to be /// listed. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<GalleryImage>> ListByGalleryAsync(this IGalleryImagesOperations operations, string resourceGroupName, string galleryName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByGalleryWithHttpMessagesAsync(resourceGroupName, galleryName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Create or update a gallery image definition. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='galleryName'> /// The name of the Shared Image Gallery in which the Image Definition is to be /// created. /// </param> /// <param name='galleryImageName'> /// The name of the gallery image definition to be created or updated. The /// allowed characters are alphabets and numbers with dots, dashes, and periods /// allowed in the middle. The maximum length is 80 characters. /// </param> /// <param name='galleryImage'> /// Parameters supplied to the create or update gallery image operation. /// </param> public static GalleryImage BeginCreateOrUpdate(this IGalleryImagesOperations operations, string resourceGroupName, string galleryName, string galleryImageName, GalleryImage galleryImage) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, galleryName, galleryImageName, galleryImage).GetAwaiter().GetResult(); } /// <summary> /// Create or update a gallery image definition. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='galleryName'> /// The name of the Shared Image Gallery in which the Image Definition is to be /// created. /// </param> /// <param name='galleryImageName'> /// The name of the gallery image definition to be created or updated. The /// allowed characters are alphabets and numbers with dots, dashes, and periods /// allowed in the middle. The maximum length is 80 characters. /// </param> /// <param name='galleryImage'> /// Parameters supplied to the create or update gallery image operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<GalleryImage> BeginCreateOrUpdateAsync(this IGalleryImagesOperations operations, string resourceGroupName, string galleryName, string galleryImageName, GalleryImage galleryImage, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, galleryName, galleryImageName, galleryImage, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Update a gallery image definition. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='galleryName'> /// The name of the Shared Image Gallery in which the Image Definition is to be /// updated. /// </param> /// <param name='galleryImageName'> /// The name of the gallery image definition to be updated. The allowed /// characters are alphabets and numbers with dots, dashes, and periods allowed /// in the middle. The maximum length is 80 characters. /// </param> /// <param name='galleryImage'> /// Parameters supplied to the update gallery image operation. /// </param> public static GalleryImage BeginUpdate(this IGalleryImagesOperations operations, string resourceGroupName, string galleryName, string galleryImageName, GalleryImageUpdate galleryImage) { return operations.BeginUpdateAsync(resourceGroupName, galleryName, galleryImageName, galleryImage).GetAwaiter().GetResult(); } /// <summary> /// Update a gallery image definition. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='galleryName'> /// The name of the Shared Image Gallery in which the Image Definition is to be /// updated. /// </param> /// <param name='galleryImageName'> /// The name of the gallery image definition to be updated. The allowed /// characters are alphabets and numbers with dots, dashes, and periods allowed /// in the middle. The maximum length is 80 characters. /// </param> /// <param name='galleryImage'> /// Parameters supplied to the update gallery image operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<GalleryImage> BeginUpdateAsync(this IGalleryImagesOperations operations, string resourceGroupName, string galleryName, string galleryImageName, GalleryImageUpdate galleryImage, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, galleryName, galleryImageName, galleryImage, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Delete a gallery image. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='galleryName'> /// The name of the Shared Image Gallery in which the Image Definition is to be /// deleted. /// </param> /// <param name='galleryImageName'> /// The name of the gallery image definition to be deleted. /// </param> public static void BeginDelete(this IGalleryImagesOperations operations, string resourceGroupName, string galleryName, string galleryImageName) { operations.BeginDeleteAsync(resourceGroupName, galleryName, galleryImageName).GetAwaiter().GetResult(); } /// <summary> /// Delete a gallery image. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='galleryName'> /// The name of the Shared Image Gallery in which the Image Definition is to be /// deleted. /// </param> /// <param name='galleryImageName'> /// The name of the gallery image definition to be deleted. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IGalleryImagesOperations operations, string resourceGroupName, string galleryName, string galleryImageName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, galleryName, galleryImageName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// List gallery image definitions in a gallery. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<GalleryImage> ListByGalleryNext(this IGalleryImagesOperations operations, string nextPageLink) { return operations.ListByGalleryNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// List gallery image definitions in a gallery. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<GalleryImage>> ListByGalleryNextAsync(this IGalleryImagesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByGalleryNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
mit
chainer/chainercv
chainercv/utils/download.py
4987
from __future__ import division from __future__ import print_function from distutils.util import strtobool import hashlib import os import shutil import tarfile import tempfile import zipfile import filelock from six.moves.urllib import request import sys import time from chainer.dataset.download import get_dataset_directory from chainer.dataset.download import get_dataset_root def _reporthook(count, block_size, total_size): global start_time if count == 0: start_time = time.time() print(' % Total Recv Speed Time left') return duration = time.time() - start_time progress_size = count * block_size try: speed = progress_size / duration except ZeroDivisionError: speed = float('inf') percent = progress_size / total_size * 100 eta = int((total_size - progress_size) / speed) sys.stdout.write( '\r{:3.0f} {:4.0f}MiB {:4.0f}MiB {:6.0f}KiB/s {:4d}:{:02d}:{:02d}' .format( percent, total_size / (1 << 20), progress_size / (1 << 20), speed / (1 << 10), eta // 60 // 60, (eta // 60) % 60, eta % 60)) sys.stdout.flush() def cached_download(url): """Downloads a file and caches it. This is different from the original :func:`~chainer.dataset.cached_download` in that the download progress is reported. Note that this progress report can be disabled by setting the environment variable `CHAINERCV_DOWNLOAD_REPORT` to `'OFF'`. It downloads a file from the URL if there is no corresponding cache. After the download, this function stores a cache to the directory under the dataset root (see :func:`set_dataset_root`). If there is already a cache for the given URL, it just returns the path to the cache without downloading the same file. Args: url (string): URL to download from. Returns: string: Path to the downloaded file. """ cache_root = os.path.join(get_dataset_root(), '_dl_cache') try: os.makedirs(cache_root) except OSError: if not os.path.exists(cache_root): raise lock_path = os.path.join(cache_root, '_dl_lock') urlhash = hashlib.md5(url.encode('utf-8')).hexdigest() cache_path = os.path.join(cache_root, urlhash) with filelock.FileLock(lock_path): if os.path.exists(cache_path): return cache_path temp_root = tempfile.mkdtemp(dir=cache_root) try: temp_path = os.path.join(temp_root, 'dl') if strtobool(os.getenv('CHAINERCV_DOWNLOAD_REPORT', 'ON')): print('Downloading ...') print('From: {:s}'.format(url)) print('To: {:s}'.format(cache_path)) request.urlretrieve(url, temp_path, _reporthook) else: request.urlretrieve(url, temp_path) with filelock.FileLock(lock_path): shutil.move(temp_path, cache_path) finally: shutil.rmtree(temp_root) return cache_path def download_model(url): """Downloads a model file and puts it under model directory. It downloads a file from the URL and puts it under model directory. For exmaple, if :obj:`url` is `http://example.com/subdir/model.npz`, the pretrained weights file will be saved to `$CHAINER_DATASET_ROOT/pfnet/chainercv/models/model.npz`. If there is already a file at the destination path, it just returns the path without downloading the same file. Args: url (string): URL to download from. Returns: string: Path to the downloaded file. """ # To support ChainerMN, the target directory should be locked. with filelock.FileLock(os.path.join( get_dataset_directory(os.path.join('pfnet', 'chainercv', '.lock')), 'models.lock')): root = get_dataset_directory( os.path.join('pfnet', 'chainercv', 'models')) basename = os.path.basename(url) path = os.path.join(root, basename) if not os.path.exists(path): cache_path = cached_download(url) os.rename(cache_path, path) return path def extractall(file_path, destination, ext): """Extracts an archive file. This function extracts an archive file to a destination. Args: file_path (string): The path of a file to be extracted. destination (string): A directory path. The archive file will be extracted under this directory. ext (string): An extension suffix of the archive file. This function supports :obj:`'.zip'`, :obj:`'.tar'`, :obj:`'.gz'` and :obj:`'.tgz'`. """ if ext == '.zip': with zipfile.ZipFile(file_path, 'r') as z: z.extractall(destination) elif ext == '.tar': with tarfile.TarFile(file_path, 'r') as t: t.extractall(destination) elif ext == '.gz' or ext == '.tgz': with tarfile.open(file_path, 'r:gz') as t: t.extractall(destination)
mit
timshannon/rollup-166
src/js/lib/lodash/collection/size.js
750
import getLength from '../internal/getLength'; import isLength from '../internal/isLength'; import keys from '../object/keys'; /** * Gets the size of `collection` by returning its length for array-like * values or the number of own enumerable properties for objects. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @returns {number} Returns the size of `collection`. * @example * * _.size([1, 2, 3]); * // => 3 * * _.size({ 'a': 1, 'b': 2 }); * // => 2 * * _.size('pebbles'); * // => 7 */ function size(collection) { var length = collection ? getLength(collection) : 0; return isLength(length) ? length : keys(collection).length; } export default size;
mit
pragkent/aliyun-disk
vendor/github.com/denverdino/aliyungo/opensearch/search.go
920
package opensearch import "net/http" type SearchArgs struct { //搜索主体 Query string `ArgName:"query"` //要查询的应用名 Index_name string `ArgName:"index_name"` //[可以通过此参数获取本次查询需要的字段内容] Fetch_fields string `ArgName:"fetch_fields"` //[指定要使用的查询分析规则] Qp string `ArgName:"qp"` //[关闭已生效的查询分析功能] Disable string `ArgName:"disable"` //[设置粗排表达式名字] First_formula_name string `ArgName:"first_formula_name"` //[设置精排表达式名字] Formula_name string `ArgName:"formula_name"` //[动态摘要的配置] Summary string `ArgName:"summary"` } //搜索 //系统提供了丰富的搜索语法以满足用户各种场景下的搜索需求 func (this *Client) Search(args SearchArgs, resp interface{}) error { return this.InvokeByAnyMethod(http.MethodGet, "", "/search", args, resp) }
mit
gruberro/Sylius
src/Sylius/Bundle/PromotionBundle/Controller/PromotionCouponController.php
2637
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Bundle\PromotionBundle\Controller; use FOS\RestBundle\View\View; use Sylius\Bundle\PromotionBundle\Form\Type\PromotionCouponGeneratorInstructionType; use Sylius\Bundle\ResourceBundle\Controller\ResourceController; use Sylius\Component\Promotion\Generator\PromotionCouponGeneratorInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** * @author Paweł Jędrzejewski <pawel@sylius.org> */ class PromotionCouponController extends ResourceController { /** * @param Request $request * * @return Response * * @throws NotFoundHttpException */ public function generateAction(Request $request) { $configuration = $this->requestConfigurationFactory->create($this->metadata, $request); if (null === $promotionId = $request->attributes->get('promotionId')) { throw new NotFoundHttpException('No promotion id given.'); } if (null === $promotion = $this->container->get('sylius.repository.promotion')->find($promotionId)) { throw new NotFoundHttpException('Promotion not found.'); } $form = $this->container->get('form.factory')->create(PromotionCouponGeneratorInstructionType::class); if ($form->handleRequest($request)->isValid()) { $this->getGenerator()->generate($promotion, $form->getData()); $this->flashHelper->addSuccessFlash($configuration, 'generate'); return $this->redirectHandler->redirectToResource($configuration, $promotion); } if (!$configuration->isHtmlRequest()) { return $this->viewHandler->handle($configuration, View::create($form)); } $view = View::create() ->setTemplate($configuration->getTemplate('generate.html')) ->setData([ 'configuration' => $configuration, 'metadata' => $this->metadata, 'promotion' => $promotion, 'form' => $form->createView(), ]) ; return $this->viewHandler->handle($configuration, $view); } /** * @return PromotionCouponGeneratorInterface */ protected function getGenerator() { return $this->container->get('sylius.promotion_coupon_generator'); } }
mit
OfficeDev/PnP-Transformation
Transformation Tool - CSOM/Transformation.PowerShell/WebPart/TransformWebPartByWeb.cs
1644
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Management.Automation; using Transformation.PowerShell.Base; namespace Transformation.PowerShell.WebPart { [Cmdlet(VerbsCommon.Set, "TargetWebPartEnd2EndByUsageCSV")] public class TransformWebPartByUsageCSV : TrasnformationPowerShellCmdlet { [Parameter(Mandatory = true, Position = 0)] public string WebPartUsageFilePath; [Parameter(Mandatory = true, Position = 1)] public string SourceWebPartType; [Parameter(Mandatory = true, Position = 2)] public string TargetWebPartFileName; [Parameter(Mandatory = true, Position = 3)] public string TargetWebPartXmlFilePath; [Parameter(Mandatory = true, Position = 4)] public string OutPutDirectory; [Parameter(Mandatory = true, Position = 5)] public string SharePointOnline_OR_OnPremise; [Parameter(Mandatory = true, Position = 6)] public string UserName; [Parameter(Mandatory = true, Position = 7)] public string Password; [Parameter(Mandatory = true, Position = 8)] public string Domain; protected override void ProcessRecord() { WebPartTransformationHelper webPartTransformationHelper = new WebPartTransformationHelper(); webPartTransformationHelper.TransformWebPart_UsingCSV(WebPartUsageFilePath, SourceWebPartType, TargetWebPartFileName, TargetWebPartXmlFilePath, OutPutDirectory, SharePointOnline_OR_OnPremise, UserName, Password, Domain); } } }
mit
rofrischmann/react-look
packages/react-look-native/test/beforeEach.js
236
import StyleContainer from '../modules/api/StyleContainer' export function clearStyleContainer() { StyleContainer.selectors.clear() StyleContainer.dynamics.clear() StyleContainer._selector = 0 } beforeEach(clearStyleContainer)
mit
billba/botchat
samples/07.advanced-web-chat-apps/b.sso-for-enterprise/app/src/microsoftGraphProfile/Context.js
145
import { createContext } from 'react'; // We will create an empty context here and fill it out via Composer.js. export default createContext();
mit
gubaojian/trylearn
WebLayoutCore/Source/WebCore/platform/glib/KeyedEncoderGlib.cpp
5296
/* * Copyright (C) 2015 Igalia S.L. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "KeyedEncoderGlib.h" #include "SharedBuffer.h" #include <wtf/text/CString.h> namespace WebCore { std::unique_ptr<KeyedEncoder> KeyedEncoder::encoder() { return std::make_unique<KeyedEncoderGlib>(); } KeyedEncoderGlib::KeyedEncoderGlib() { g_variant_builder_init(&m_variantBuilder, G_VARIANT_TYPE("a{sv}")); m_variantBuilderStack.append(&m_variantBuilder); } KeyedEncoderGlib::~KeyedEncoderGlib() { ASSERT(m_variantBuilderStack.size() == 1); ASSERT(m_variantBuilderStack.last() == &m_variantBuilder); ASSERT(m_arrayStack.isEmpty()); ASSERT(m_objectStack.isEmpty()); } void KeyedEncoderGlib::encodeBytes(const String& key, const uint8_t* bytes, size_t size) { GRefPtr<GBytes> gBytes = adoptGRef(g_bytes_new_static(bytes, size)); g_variant_builder_add(m_variantBuilderStack.last(), "{sv}", key.utf8().data(), g_variant_new_from_bytes(G_VARIANT_TYPE("ay"), gBytes.get(), TRUE)); } void KeyedEncoderGlib::encodeBool(const String& key, bool value) { g_variant_builder_add(m_variantBuilderStack.last(), "{sv}", key.utf8().data(), g_variant_new_boolean(value)); } void KeyedEncoderGlib::encodeUInt32(const String& key, uint32_t value) { g_variant_builder_add(m_variantBuilderStack.last(), "{sv}", key.utf8().data(), g_variant_new_uint32(value)); } void KeyedEncoderGlib::encodeInt32(const String& key, int32_t value) { g_variant_builder_add(m_variantBuilderStack.last(), "{sv}", key.utf8().data(), g_variant_new_int32(value)); } void KeyedEncoderGlib::encodeInt64(const String& key, int64_t value) { g_variant_builder_add(m_variantBuilderStack.last(), "{sv}", key.utf8().data(), g_variant_new_int64(value)); } void KeyedEncoderGlib::encodeFloat(const String& key, float value) { encodeDouble(key, value); } void KeyedEncoderGlib::encodeDouble(const String& key, double value) { g_variant_builder_add(m_variantBuilderStack.last(), "{sv}", key.utf8().data(), g_variant_new_double(value)); } void KeyedEncoderGlib::encodeString(const String& key, const String& value) { g_variant_builder_add(m_variantBuilderStack.last(), "{sv}", key.utf8().data(), g_variant_new_string(value.utf8().data())); } void KeyedEncoderGlib::beginObject(const String& key) { GRefPtr<GVariantBuilder> builder = adoptGRef(g_variant_builder_new(G_VARIANT_TYPE("aa{sv}"))); m_objectStack.append(std::make_pair(key, builder)); m_variantBuilderStack.append(builder.get()); } void KeyedEncoderGlib::endObject() { GVariantBuilder* builder = m_variantBuilderStack.takeLast(); g_variant_builder_add(m_variantBuilderStack.last(), "{sv}", m_objectStack.last().first.utf8().data(), g_variant_builder_end(builder)); m_objectStack.removeLast(); } void KeyedEncoderGlib::beginArray(const String& key) { m_arrayStack.append(std::make_pair(key, adoptGRef(g_variant_builder_new(G_VARIANT_TYPE("aa{sv}"))))); } void KeyedEncoderGlib::beginArrayElement() { m_variantBuilderStack.append(g_variant_builder_new(G_VARIANT_TYPE("a{sv}"))); } void KeyedEncoderGlib::endArrayElement() { GRefPtr<GVariantBuilder> variantBuilder = adoptGRef(m_variantBuilderStack.takeLast()); g_variant_builder_add_value(m_arrayStack.last().second.get(), g_variant_builder_end(variantBuilder.get())); } void KeyedEncoderGlib::endArray() { g_variant_builder_add(m_variantBuilderStack.last(), "{sv}", m_arrayStack.last().first.utf8().data(), g_variant_builder_end(m_arrayStack.last().second.get())); m_arrayStack.removeLast(); } RefPtr<SharedBuffer> KeyedEncoderGlib::finishEncoding() { g_assert(m_variantBuilderStack.last() == &m_variantBuilder); GRefPtr<GVariant> variant = g_variant_builder_end(&m_variantBuilder); GRefPtr<GBytes> data = g_variant_get_data_as_bytes(variant.get()); return SharedBuffer::create(static_cast<const unsigned char*>(g_bytes_get_data(data.get(), nullptr)), static_cast<unsigned>(g_bytes_get_size(data.get()))); } } // namespace WebCore
mit
liammagee/fierce-planet-node
public/javascripts/fp-core-old/libs/one-color/slides/CPHJS-Oct2011/colorcat/js/colorcat.js
4218
window.onload = function () { var backgrounds = [ 'background-color', 'background-image' ]; var directions = [ 'top', 'right', 'bottom', 'left' ]; var colorElements = []; var traverse = function (el, fn) { fn(el); for (var i = 0; i < el.childNodes.length; i += 1) { if (el.childNodes[i].nodeType === 1) { traverse(el.childNodes[i], fn); } } }; var registerColor = function (el) { var cs = getComputedStyle(el), styles = [], match = false; var color = cs.getPropertyCSSValue('color').cssText; if (color !== 'rgb(255, 255, 255)') { styles.push({ property: 'color', value: one.color.parse(color) }); } backgrounds.forEach(function (prop) { var val = cs.getPropertyCSSValue(prop).cssText; if (val !== 'none' && val !== 'rgba(0, 0, 0, 0)') { var color = one.color.parse(val); if (color) { styles.push({ property: prop, value: one.color.parse(val) }); } else { var colorStrings = val.match(/rgba?\([^\(]+?\)/g), colors = colorStrings.map(function (rgbaStr) { return one.color.parse(rgbaStr); }); for (var i = 0; i < colorStrings.length; i+=1) { val = val.replace(colorStrings[i], '[' + i + ']'); } styles.push({ property: prop, value: { tpl: val, colors: colors } }); } } }); directions.forEach(function (dir) { var val = cs.getPropertyCSSValue('border-' + dir + '-width').cssText; if (val !== '0px') { styles.push({ property: 'border-' + dir + '-color', value: one.color.parse(cs.getPropertyCSSValue('border-' + dir + '-color').cssText) }); } }); if (styles.length) { colorElements.push({ el: el, styles: styles }); } }; var colorize = function (fn) { colorElements.forEach(function (item) { item.styles.forEach(function (style) { if (style.value.isColor) { item.el.style[style.property] = fn(style.value).toCSSWithAlpha(); } else if (style.value.colors) { var val = style.value.tpl; style.value.colors.forEach(function (color, idx) { val = val.replace('[' + idx + ']', fn(color).toCSSWithAlpha()); }); item.el.style[style.property] = val; } }); }); }; traverse(document.getElementById('mainContainer'), registerColor); colorElements.forEach(function (item) { item.styles.map(function (style) { style.property = style.property.replace(/-(\w)/g, function (str, p1) { return p1.toUpperCase(); }); return style; }); }); var channels = [ 'Red', 'Green', 'Blue', 'Hue', 'Saturation', 'Value', 'Cyan', 'Magenta', 'Yellow', 'Black', 'Alpha' ]; var handler = function (e) { colorize(function (color) { inputs.forEach(function (input) { var val = parseFloat(input.value); color = color[(input.name === 'Alpha' ? 'set' : 'adjust') + input.name](val); }); return color; }); }; var inputs = channels.map(function (channel) { var input = document.getElementById(channel); input.onchange = handler; return input; }); };
mit
jjimenezg93/ai-state_machines
moai/src/uslscore/USZip.cpp
5185
// Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved. // http://getmoai.com // based on zpipe.c Version 1.2 as provided to the public domain 9 November 2004 by Mark Adler #include "pch.h" #include <stdio.h> #include <string.h> #include <assert.h> #include <zlib.h> #include <uslscore/USByteStream.h> #include <uslscore/USMemStream.h> #include <uslscore/USStream.h> #include <uslscore/USZip.h> //----------------------------------------------------------------// int USZip::Deflate ( const void* buffer, size_t size, USLeanArray < u8 >& result, int level ) { USMemStream outStream; USByteStream inStream; inStream.SetBuffer (( void* )buffer, size ); inStream.SetLength ( size ); int r = USZip::Deflate ( inStream, outStream, level ); if ( r == Z_OK ) { result.Init ( outStream.GetLength ()); outStream.Seek ( 0, SEEK_SET ); outStream.ReadBytes ( result.Data (), result.Size () ); } return r; } //----------------------------------------------------------------// int USZip::Deflate ( USStream& source, USStream& dest, int level ) { int ret, flush; unsigned have; z_stream strm; char in [ CHUNKSIZE ]; char out [ CHUNKSIZE ]; /* allocate deflate state */ //strm.zalloc = Z_NULL; //strm.zfree = Z_NULL; //strm.opaque = Z_NULL; memset ( &strm, 0, sizeof ( strm )); strm.next_in = ( Bytef* )in; strm.avail_in = CHUNKSIZE; strm.next_out = ( Bytef* )out; strm.avail_out = CHUNKSIZE; ret = deflateInit2 ( &strm, level, Z_DEFLATED, -MAX_WBITS, 7, Z_DEFAULT_STRATEGY ); if ( ret != Z_OK ) return ret; // compress until end of file do { strm.avail_in = source.ReadBytes ( in, CHUNKSIZE ); strm.next_in = ( Bytef* )in; flush = source.IsAtEnd () ? Z_FINISH : Z_NO_FLUSH; /* run deflate() on input until output buffer not full, finish compression if all of source has been read in */ do { strm.avail_out = CHUNKSIZE; strm.next_out = ( Bytef* )out; ret = deflate ( &strm, flush ); /* no bad return value */ assert ( ret != Z_STREAM_ERROR ); /* state not clobbered */ have = CHUNKSIZE - strm.avail_out; if ( dest.WriteBytes ( out, have ) != have ) { ( void )deflateEnd ( &strm ); return Z_ERRNO; } } while ( strm.avail_out == 0 ); assert ( strm.avail_in == 0 ); /* all input will be used */ /* done when last data in file processed */ } while ( flush != Z_FINISH ); assert ( ret == Z_STREAM_END ); /* stream will be complete */ /* clean up and return */ ( void )deflateEnd ( &strm ); return Z_OK; } //----------------------------------------------------------------// cc8* USZip::GetErrMsg ( int code ) { fputs ( "zpipe: ", stderr ); switch ( code ) { case Z_ERRNO: if ( ferror ( stdin )) return "zpipe: error reading stdin"; if ( ferror ( stdout )) return "zpipe: error writing stdout"; break; case Z_STREAM_ERROR: return "zpipe: invalid compression level"; break; case Z_DATA_ERROR: return "zpipe: invalid or incomplete deflate data"; break; case Z_MEM_ERROR: return "zpipe: out of memory"; break; case Z_VERSION_ERROR: return "zpipe: zlib version mismatch!"; } return "zpipe: ok"; } //----------------------------------------------------------------// int USZip::Inflate ( const void* buffer, size_t size, USLeanArray < u8 >& result ) { USMemStream outStream; USByteStream inStream; inStream.SetBuffer (( void* )buffer, size ); inStream.SetLength ( size ); int r = USZip::Inflate ( inStream, outStream ); if ( r == Z_OK ) { result.Init ( outStream.GetLength ()); outStream.Seek ( 0, SEEK_SET ); outStream.ReadBytes ( result.Data (), result.Size () ); } return r; } //----------------------------------------------------------------// int USZip::Inflate ( USStream& source, USStream& dest ) { int ret; unsigned have; z_stream strm; char in [ CHUNKSIZE ]; char out [ CHUNKSIZE ]; memset ( &strm, 0, sizeof ( strm )); strm.next_in = ( Bytef* )in; strm.avail_in = CHUNKSIZE; strm.next_out = ( Bytef* )out; strm.avail_out = CHUNKSIZE; ret = inflateInit2 ( &strm, -MAX_WBITS ); if ( ret != Z_OK ) return ret; /* decompress until deflate stream ends or end of file */ do { strm.avail_in = source.ReadBytes ( in, CHUNKSIZE ); strm.next_in = ( Bytef* )in; if ( strm.avail_in == 0 ) break; /* run inflate() on input until output buffer not full */ do { strm.avail_out = CHUNKSIZE; strm.next_out = ( Bytef* )out; ret = inflate ( &strm, Z_NO_FLUSH ); assert( ret != Z_STREAM_ERROR ); /* state not clobbered */ switch ( ret ) { case Z_NEED_DICT: ret = Z_DATA_ERROR; /* and fall through */ case Z_DATA_ERROR: case Z_MEM_ERROR: ( void )inflateEnd ( &strm ); return ret; } have = CHUNKSIZE - strm.avail_out; if ( dest.WriteBytes ( out, have ) != have ) { ( void )inflateEnd ( &strm ); return Z_ERRNO; } } while ( strm.avail_out == 0 ); /* done when inflate() says it's done */ } while ( ret != Z_STREAM_END ); /* clean up and return */ ( void )inflateEnd ( &strm ); return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR; }
mit
mdsolver/WurmAssistant3
src/Apps/WurmAssistant/WurmAssistant3/Areas/Calendar/CalendarForm.Designer.cs
22368
using AldursLab.WurmAssistant3.Utils.WinForms; namespace AldursLab.WurmAssistant3.Areas.Calendar { partial class CalendarForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.groupBox1 = new System.Windows.Forms.GroupBox(); this.radioButtonRealTime = new System.Windows.Forms.RadioButton(); this.radioButtonWurmTime = new System.Windows.Forms.RadioButton(); this.checkBoxSoundWarning = new System.Windows.Forms.CheckBox(); this.checkBoxPopupWarning = new System.Windows.Forms.CheckBox(); this.buttonChooseSeasons = new System.Windows.Forms.Button(); this.buttonClearSound = new System.Windows.Forms.Button(); this.buttonChooseSound = new System.Windows.Forms.Button(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.textBoxChosenSeasons = new System.Windows.Forms.TextBox(); this.textBoxChosenSound = new System.Windows.Forms.TextBox(); this.listViewNFSeasons = new AldursLab.WurmAssistant3.Utils.WinForms.ListViewNf(); this.columnHeader4 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader5 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader6 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.label1 = new System.Windows.Forms.Label(); this.comboBoxChooseServer = new System.Windows.Forms.ComboBox(); this.textBoxWurmDate = new System.Windows.Forms.TextBox(); this.panelOptions = new System.Windows.Forms.Panel(); this.buttonModSeasonList = new System.Windows.Forms.Button(); this.buttonConfigure = new System.Windows.Forms.Button(); this.labelDisplayTimeMode = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.groupBox3.SuspendLayout(); this.panelOptions.SuspendLayout(); this.SuspendLayout(); // // groupBox1 // this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.groupBox1.Controls.Add(this.radioButtonRealTime); this.groupBox1.Controls.Add(this.radioButtonWurmTime); this.groupBox1.Location = new System.Drawing.Point(299, 1); this.groupBox1.Margin = new System.Windows.Forms.Padding(2); this.groupBox1.Name = "groupBox1"; this.groupBox1.Padding = new System.Windows.Forms.Padding(2); this.groupBox1.Size = new System.Drawing.Size(128, 72); this.groupBox1.TabIndex = 1; this.groupBox1.TabStop = false; this.groupBox1.Text = "Display time as..."; // // radioButtonRealTime // this.radioButtonRealTime.AutoSize = true; this.radioButtonRealTime.Location = new System.Drawing.Point(4, 39); this.radioButtonRealTime.Margin = new System.Windows.Forms.Padding(2); this.radioButtonRealTime.Name = "radioButtonRealTime"; this.radioButtonRealTime.Size = new System.Drawing.Size(73, 17); this.radioButtonRealTime.TabIndex = 1; this.radioButtonRealTime.TabStop = true; this.radioButtonRealTime.Text = "Real Time"; this.radioButtonRealTime.UseVisualStyleBackColor = true; this.radioButtonRealTime.CheckedChanged += new System.EventHandler(this.radioButtonRealTime_CheckedChanged); // // radioButtonWurmTime // this.radioButtonWurmTime.AutoSize = true; this.radioButtonWurmTime.Location = new System.Drawing.Point(4, 17); this.radioButtonWurmTime.Margin = new System.Windows.Forms.Padding(2); this.radioButtonWurmTime.Name = "radioButtonWurmTime"; this.radioButtonWurmTime.Size = new System.Drawing.Size(79, 17); this.radioButtonWurmTime.TabIndex = 0; this.radioButtonWurmTime.TabStop = true; this.radioButtonWurmTime.Text = "Wurm Time"; this.radioButtonWurmTime.UseVisualStyleBackColor = true; this.radioButtonWurmTime.CheckedChanged += new System.EventHandler(this.radioButtonWurmTime_CheckedChanged); // // checkBoxSoundWarning // this.checkBoxSoundWarning.AutoSize = true; this.checkBoxSoundWarning.Location = new System.Drawing.Point(4, 46); this.checkBoxSoundWarning.Margin = new System.Windows.Forms.Padding(2); this.checkBoxSoundWarning.Name = "checkBoxSoundWarning"; this.checkBoxSoundWarning.Size = new System.Drawing.Size(57, 17); this.checkBoxSoundWarning.TabIndex = 2; this.checkBoxSoundWarning.Text = "Sound"; this.checkBoxSoundWarning.UseVisualStyleBackColor = true; this.checkBoxSoundWarning.CheckedChanged += new System.EventHandler(this.checkBoxSoundWarning_CheckedChanged); // // checkBoxPopupWarning // this.checkBoxPopupWarning.AutoSize = true; this.checkBoxPopupWarning.Location = new System.Drawing.Point(4, 24); this.checkBoxPopupWarning.Margin = new System.Windows.Forms.Padding(2); this.checkBoxPopupWarning.Name = "checkBoxPopupWarning"; this.checkBoxPopupWarning.Size = new System.Drawing.Size(186, 17); this.checkBoxPopupWarning.TabIndex = 3; this.checkBoxPopupWarning.Text = "Popup (bottom right of the screen)"; this.checkBoxPopupWarning.UseVisualStyleBackColor = true; this.checkBoxPopupWarning.CheckedChanged += new System.EventHandler(this.checkBoxPopupWarning_CheckedChanged); // // buttonChooseSeasons // this.buttonChooseSeasons.Location = new System.Drawing.Point(219, 17); this.buttonChooseSeasons.Margin = new System.Windows.Forms.Padding(2); this.buttonChooseSeasons.Name = "buttonChooseSeasons"; this.buttonChooseSeasons.Size = new System.Drawing.Size(188, 22); this.buttonChooseSeasons.TabIndex = 4; this.buttonChooseSeasons.Text = "Choose seasons of interest..."; this.buttonChooseSeasons.UseVisualStyleBackColor = true; this.buttonChooseSeasons.Click += new System.EventHandler(this.buttonChooseSeasons_Click); // // buttonClearSound // this.buttonClearSound.Location = new System.Drawing.Point(145, 68); this.buttonClearSound.Margin = new System.Windows.Forms.Padding(2); this.buttonClearSound.Name = "buttonClearSound"; this.buttonClearSound.Size = new System.Drawing.Size(48, 23); this.buttonClearSound.TabIndex = 15; this.buttonClearSound.Text = "clear"; this.buttonClearSound.UseVisualStyleBackColor = true; this.buttonClearSound.Click += new System.EventHandler(this.buttonClearSound_Click); // // buttonChooseSound // this.buttonChooseSound.Location = new System.Drawing.Point(4, 68); this.buttonChooseSound.Margin = new System.Windows.Forms.Padding(2); this.buttonChooseSound.Name = "buttonChooseSound"; this.buttonChooseSound.Size = new System.Drawing.Size(138, 23); this.buttonChooseSound.TabIndex = 14; this.buttonChooseSound.Text = "Choose sound"; this.buttonChooseSound.UseVisualStyleBackColor = true; this.buttonChooseSound.Click += new System.EventHandler(this.buttonChooseSound_Click); // // groupBox2 // this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.groupBox2.Controls.Add(this.textBoxChosenSeasons); this.groupBox2.Controls.Add(this.checkBoxPopupWarning); this.groupBox2.Controls.Add(this.textBoxChosenSound); this.groupBox2.Controls.Add(this.buttonChooseSeasons); this.groupBox2.Controls.Add(this.buttonChooseSound); this.groupBox2.Controls.Add(this.checkBoxSoundWarning); this.groupBox2.Controls.Add(this.buttonClearSound); this.groupBox2.Location = new System.Drawing.Point(2, 105); this.groupBox2.Margin = new System.Windows.Forms.Padding(2); this.groupBox2.Name = "groupBox2"; this.groupBox2.Padding = new System.Windows.Forms.Padding(2); this.groupBox2.Size = new System.Drawing.Size(424, 122); this.groupBox2.TabIndex = 16; this.groupBox2.TabStop = false; this.groupBox2.Text = "Season reminders"; // // textBoxChosenSeasons // this.textBoxChosenSeasons.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.2F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); this.textBoxChosenSeasons.Location = new System.Drawing.Point(219, 43); this.textBoxChosenSeasons.Margin = new System.Windows.Forms.Padding(2); this.textBoxChosenSeasons.Multiline = true; this.textBoxChosenSeasons.Name = "textBoxChosenSeasons"; this.textBoxChosenSeasons.ReadOnly = true; this.textBoxChosenSeasons.Size = new System.Drawing.Size(189, 78); this.textBoxChosenSeasons.TabIndex = 17; // // textBoxChosenSound // this.textBoxChosenSound.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.2F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); this.textBoxChosenSound.Location = new System.Drawing.Point(4, 95); this.textBoxChosenSound.Margin = new System.Windows.Forms.Padding(2); this.textBoxChosenSound.Name = "textBoxChosenSound"; this.textBoxChosenSound.ReadOnly = true; this.textBoxChosenSound.Size = new System.Drawing.Size(189, 23); this.textBoxChosenSound.TabIndex = 16; // // listViewNFSeasons // this.listViewNFSeasons.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.listViewNFSeasons.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader4, this.columnHeader5, this.columnHeader6}); this.listViewNFSeasons.GridLines = true; this.listViewNFSeasons.HideSelection = false; this.listViewNFSeasons.Location = new System.Drawing.Point(9, 37); this.listViewNFSeasons.Margin = new System.Windows.Forms.Padding(2); this.listViewNFSeasons.Name = "listViewNFSeasons"; this.listViewNFSeasons.Size = new System.Drawing.Size(454, 296); this.listViewNFSeasons.TabIndex = 17; this.listViewNFSeasons.UseCompatibleStateImageBehavior = false; this.listViewNFSeasons.View = System.Windows.Forms.View.Details; // // columnHeader4 // this.columnHeader4.Text = "Plant"; this.columnHeader4.Width = 110; // // columnHeader5 // this.columnHeader5.Text = "Starts in..."; this.columnHeader5.Width = 240; // // columnHeader6 // this.columnHeader6.Text = "Lasts for..."; this.columnHeader6.Width = 200; // // groupBox3 // this.groupBox3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.groupBox3.Controls.Add(this.label1); this.groupBox3.Controls.Add(this.comboBoxChooseServer); this.groupBox3.Controls.Add(this.textBoxWurmDate); this.groupBox3.Location = new System.Drawing.Point(1, 1); this.groupBox3.Margin = new System.Windows.Forms.Padding(2); this.groupBox3.Name = "groupBox3"; this.groupBox3.Padding = new System.Windows.Forms.Padding(2); this.groupBox3.Size = new System.Drawing.Size(288, 99); this.groupBox3.TabIndex = 18; this.groupBox3.TabStop = false; this.groupBox3.Text = "Current Wurm Date"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(4, 27); this.label1.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(146, 13); this.label1.TabIndex = 20; this.label1.Text = "Track seasons for this server:"; // // comboBoxChooseServer // this.comboBoxChooseServer.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBoxChooseServer.Enabled = false; this.comboBoxChooseServer.FormattingEnabled = true; this.comboBoxChooseServer.Location = new System.Drawing.Point(156, 24); this.comboBoxChooseServer.Margin = new System.Windows.Forms.Padding(2); this.comboBoxChooseServer.MaxDropDownItems = 12; this.comboBoxChooseServer.Name = "comboBoxChooseServer"; this.comboBoxChooseServer.Size = new System.Drawing.Size(128, 21); this.comboBoxChooseServer.TabIndex = 19; this.comboBoxChooseServer.SelectedIndexChanged += new System.EventHandler(this.comboBoxChooseServer_SelectedIndexChanged); // // textBoxWurmDate // this.textBoxWurmDate.Location = new System.Drawing.Point(5, 49); this.textBoxWurmDate.Margin = new System.Windows.Forms.Padding(2); this.textBoxWurmDate.Multiline = true; this.textBoxWurmDate.Name = "textBoxWurmDate"; this.textBoxWurmDate.ReadOnly = true; this.textBoxWurmDate.Size = new System.Drawing.Size(279, 46); this.textBoxWurmDate.TabIndex = 0; // // panelOptions // this.panelOptions.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.panelOptions.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.panelOptions.Controls.Add(this.buttonModSeasonList); this.panelOptions.Controls.Add(this.groupBox2); this.panelOptions.Controls.Add(this.groupBox3); this.panelOptions.Controls.Add(this.groupBox1); this.panelOptions.Location = new System.Drawing.Point(9, 102); this.panelOptions.Margin = new System.Windows.Forms.Padding(2); this.panelOptions.Name = "panelOptions"; this.panelOptions.Size = new System.Drawing.Size(431, 231); this.panelOptions.TabIndex = 19; this.panelOptions.Visible = false; // // buttonModSeasonList // this.buttonModSeasonList.Location = new System.Drawing.Point(299, 78); this.buttonModSeasonList.Margin = new System.Windows.Forms.Padding(2); this.buttonModSeasonList.Name = "buttonModSeasonList"; this.buttonModSeasonList.Size = new System.Drawing.Size(110, 22); this.buttonModSeasonList.TabIndex = 18; this.buttonModSeasonList.Text = "Mod the season list"; this.buttonModSeasonList.UseVisualStyleBackColor = true; this.buttonModSeasonList.Click += new System.EventHandler(this.buttonModSeasonList_Click); // // buttonConfigure // this.buttonConfigure.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.buttonConfigure.Location = new System.Drawing.Point(9, 337); this.buttonConfigure.Margin = new System.Windows.Forms.Padding(2); this.buttonConfigure.Name = "buttonConfigure"; this.buttonConfigure.Size = new System.Drawing.Size(105, 28); this.buttonConfigure.TabIndex = 20; this.buttonConfigure.Text = "Configure"; this.buttonConfigure.UseVisualStyleBackColor = true; this.buttonConfigure.Click += new System.EventHandler(this.buttonConfigure_Click); // // labelDisplayTimeMode // this.labelDisplayTimeMode.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.labelDisplayTimeMode.AutoSize = true; this.labelDisplayTimeMode.Location = new System.Drawing.Point(128, 344); this.labelDisplayTimeMode.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.labelDisplayTimeMode.Name = "labelDisplayTimeMode"; this.labelDisplayTimeMode.Size = new System.Drawing.Size(98, 13); this.labelDisplayTimeMode.TabIndex = 21; this.labelDisplayTimeMode.Text = "Showing times as..."; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(12, 9); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(333, 26); this.label2.TabIndex = 22; this.label2.Text = "Note: Start time is an estimate, actual seasons are +/- 2 wurm weeks \r\n(1 wurm we" + "ek = about 21 real hours)"; // // CalendarForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(471, 376); this.Controls.Add(this.label2); this.Controls.Add(this.labelDisplayTimeMode); this.Controls.Add(this.buttonConfigure); this.Controls.Add(this.panelOptions); this.Controls.Add(this.listViewNFSeasons); this.DoubleBuffered = true; this.Margin = new System.Windows.Forms.Padding(2); this.Name = "CalendarForm"; this.ShowIcon = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Season Calendar"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FormCalendar_FormClosing); this.Load += new System.EventHandler(this.FormCalendar_Load); this.Resize += new System.EventHandler(this.FormCalendar_Resize); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); this.panelOptions.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.RadioButton radioButtonRealTime; private System.Windows.Forms.RadioButton radioButtonWurmTime; private System.Windows.Forms.CheckBox checkBoxSoundWarning; private System.Windows.Forms.CheckBox checkBoxPopupWarning; private System.Windows.Forms.Button buttonChooseSeasons; private System.Windows.Forms.Button buttonClearSound; private System.Windows.Forms.Button buttonChooseSound; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.TextBox textBoxChosenSeasons; private System.Windows.Forms.TextBox textBoxChosenSound; private ListViewNf listViewNFSeasons; private System.Windows.Forms.ColumnHeader columnHeader4; private System.Windows.Forms.ColumnHeader columnHeader5; private System.Windows.Forms.ColumnHeader columnHeader6; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.TextBox textBoxWurmDate; private System.Windows.Forms.Panel panelOptions; private System.Windows.Forms.Button buttonConfigure; private System.Windows.Forms.Label label1; private System.Windows.Forms.ComboBox comboBoxChooseServer; private System.Windows.Forms.Label labelDisplayTimeMode; private System.Windows.Forms.Button buttonModSeasonList; private System.Windows.Forms.Label label2; } }
mit
rhosilver/rhodes-1
lib/commonAPI/coreapi/ext/platform/android/src/com/rho/notification/NotificationSingleton.java
11757
package com.rho.notification; import java.io.InputStream; import java.nio.ShortBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.app.Dialog; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioTrack; import android.media.MediaPlayer; import android.os.Vibrator; import android.support.v4.app.NotificationCompat; import android.util.SparseArray; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.rho.notification.INotificationSingleton; import com.rhomobile.rhodes.Logger; import com.rhomobile.rhodes.R; import com.rhomobile.rhodes.RhodesActivity; import com.rhomobile.rhodes.RhodesApplication; import com.rhomobile.rhodes.api.IMethodResult; import com.rhomobile.rhodes.api.MethodResult; import com.rhomobile.rhodes.file.RhoFileApi; import com.rhomobile.rhodes.util.ContextFactory; import com.rhomobile.rhodes.util.PerformOnUiThread; /** * Singleton for the Notification extension. Holds all of the implementation for this extension. * Uses code from both RhoElements2 and Rhodes3 * @authors Ben Kennedy (reauthor), Alexey Tikhvinsky (aat103) */ public class NotificationSingleton implements INotificationSingleton { protected static String TAG = NotificationSingleton.class.getSimpleName(); //private static SparseArray<MethodResult> callbackMap = new SparseArray<MethodResult>(); //private static int callbackIdCount = 0; private SparseArray<Notification> notifications = new SparseArray<Notification> (); private int lastNotificationId = -1; protected AudioTrack audioTrack = null; private Vibrator vibrator; private MediaPlayer currentMP; @Override public void showPopup(final Map<String, Object> propertyMap, final IMethodResult result) { Logger.T(TAG, "showPopup"); Notification notification; synchronized (notifications) { ++lastNotificationId; Logger.T(TAG, "Add notification: " + lastNotificationId); notification = new Notification(lastNotificationId, propertyMap, result); notifications.append(lastNotificationId, notification); } if (notification.isForegroundToastNeeded()) { notification.showForegroundToast(); } if (notification.isNotificationAreaNeeded()) { notification.showNotification(); } if (notification.isDialogNeeded()) { notification.showDialog(); } } @Override public void hidePopup(final IMethodResult result) { synchronized (notifications) { if (notifications.size() == 0) { throw new RuntimeException("There are no active notifications."); } int notificationId = notifications.size() - 1; Notification notification = notifications.valueAt(notificationId); if (notification != null) { notification.dismiss(); notifications.removeAt(notificationId); Logger.T(TAG, "Remove notification: " + notification.id); } } } @Override public void showStatus(String title, String status, String hideLabel, final IMethodResult result) { Map<String, Object> propertyMap = new HashMap<String, Object> (); if (title != null) { propertyMap.put(HK_TITLE, title); } if (status != null) { propertyMap.put(HK_MESSAGE, status); } if (hideLabel != null) { List<String> buttons = new ArrayList<String>(); buttons.add(hideLabel); propertyMap.put(HK_BUTTONS, buttons); } ArrayList<String> types = new ArrayList<String>(); types.add(TYPE_DIALOG); types.add(TYPE_TOAST); propertyMap.put(HK_TYPES, types); showPopup(propertyMap, result); } void onAction(int notificationId, int actionIdx) { Logger.T(TAG, "Notification action: notificationID: " + notificationId + ", action index: " + actionIdx); Notification notification = null; synchronized (notifications) { notification = notifications.get(notificationId); if (notification != null) { notification.dismiss(); notifications.delete(notificationId); Logger.I(TAG, "Remove notification: " + notification.id); } } if (notification != null) { notification.dismiss(); notification.onAction(actionIdx); } } @Override public void playFile(String path, String mediaType, final IMethodResult result) { try { Logger.T(TAG, "playFile: " + path + " (" + mediaType + ")"); if (currentMP != null) currentMP.release(); currentMP = new MediaPlayer(); currentMP.setOnErrorListener(new MediaPlayer.OnErrorListener() { public boolean onError(MediaPlayer mp, int what, int extra) { Logger.E(TAG, "Error when playing file : " + what + ", " + extra); return false; } }); currentMP.setDataSource(RhoFileApi.openFd(path)); currentMP.prepare(); currentMP.start(); } catch (Exception e) { Logger.E(TAG, e); result.setError(e.getLocalizedMessage()); } } @Override public synchronized void beep(Map<String, Integer> propertyMap, IMethodResult result) { if(audioTrack != null) { try { audioTrack.stop(); } catch(IllegalStateException e) { Logger.D(TAG, "AudioTrack did not need to be stopped here"); } finally { audioTrack.release(); } audioTrack = null; } Integer userFrequency = propertyMap.get(HK_FREQUENCY); Integer userVolume = propertyMap.get(HK_VOLUME); Integer userDuration = propertyMap.get(HK_DURATION); int frequency = (userFrequency != null ? userFrequency : 2000); int volume = (userVolume != null && userVolume >= 0 && userVolume <= 3 ? userVolume : 1); int duration = (userDuration != null ? userDuration : 1000); (new NotificationBeep(frequency)).play(duration, volume); } @Override public void vibrate(int duration, IMethodResult result) { Logger.T(TAG, "Vibrate: " + duration); if (duration != 0) { Activity activity = RhodesActivity.safeGetInstance(); if(vibrator != null) vibrator.cancel(); vibrator = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE); if ( duration > 15000 ) { duration = 15000; } vibrator.vibrate(duration > 0 ? duration : 1000); } } /** * @author unknown (From RE1) */ private class NotificationBeep { private final int mSampleRate = 44100; // 44.1KHz sample rate private final int mBytesPerSample = 2; // 16 Bits (2 Bytes) per sample private double mLoopDuration = 5000; // maximum loop duration in milliseconds private int mSampleCount = (int) ((mLoopDuration * mSampleRate) / 1000); // total number of calculated samples private ShortBuffer mAudioBuffer = ShortBuffer.allocate(mSampleCount); private short[] mAudioData = (mAudioBuffer.hasArray() ? mAudioBuffer.array() : new short[mSampleCount]); // PCM track data public NotificationBeep(double frequency) { final double maxAmplitude = 32767; double wavePeriod = mSampleRate / frequency; // in samples // Create a sine wave of the required frequency at maximum amplitude for (int i = 0; i < mSampleCount; ++i) { mAudioData[i] = (short) ((Math.sin(2 * Math.PI * i / wavePeriod)) * maxAmplitude); if ((i > 0) && (mAudioData[i] == 0) && (mAudioData[i - 1] < 0)) { // we've completed a sine wave that will loop mSampleCount = i; mLoopDuration = mSampleCount * 1000 / mSampleRate; break; } } } /** * Plays the beep * @param duration the duration of the beep in milliseconds * @param inputVolume the volume to play the beep (0-3) * @author Unknown & Ben Kennedy */ public void play(int duration, int inputVolume) { //normalise to make the volume decrease seem linear float volume = ((inputVolume + 1.0f) * (inputVolume > 0 ? inputVolume : 1))/12.0f; // calculate how many times we need to play the entire buffer int cycles = (int) (duration / mLoopDuration); // calculate any part buffers required in samples int remainder = (int) ((duration % mLoopDuration) * mSampleRate / 1000); // get the minimum buffer size from AudioTrack int bufferSizeBytes = AudioTrack.getMinBufferSize(mSampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT); // calculate how big a rendering buffer to request from AudioTrack int reqdBytes = remainder * mBytesPerSample; if (cycles > 0) { reqdBytes += (mSampleCount * mBytesPerSample); } if (reqdBytes > bufferSizeBytes) { bufferSizeBytes = reqdBytes; } // configure AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, mSampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSizeBytes, AudioTrack.MODE_STATIC); if (cycles > 0) { // write the entire PCM data to the AudioTrack rendering buffer audioTrack.write(mAudioData, 0, mSampleCount); if (cycles > 1) { // tell AudioTrack how many times to repeat the sample audioTrack.setLoopPoints(0, mSampleCount, cycles - 1); } } if (remainder > 0) { // add a part buffer of the size of the remainder audioTrack.write(mAudioData, 0, remainder); } //TODO do i need to release??? // start playing in the background audioTrack.flush(); audioTrack.setStereoVolume(volume, volume); audioTrack.play(); } } /** * Stops and releases all resources * @author Ben Kennedy */ public void cleanUpResources() { if (audioTrack != null) { try { audioTrack.stop(); } catch(IllegalStateException e) { //No need to deal with Logger.D(TAG, "AudioTrack did not need to be stopped here"); } finally { audioTrack.release(); audioTrack = null; } } if(vibrator != null) { vibrator.cancel(); } if(currentMP != null) { try { currentMP.stop(); } catch(IllegalStateException e) { //No need to deal with. Logger.D(TAG, "CurrentMP did not need to be stopped here"); } finally { currentMP.release(); currentMP = null; } } } /** * Android onPause event */ public void onPause() { cleanUpResources(); } /** * Android onStop event */ public void onStop() { cleanUpResources(); } /** * Android onDestroy event */ public void onDestroy() { cleanUpResources(); } }
mit
hpinsley/angular-mashup
tools/tasks/build.e2e_test.ts
721
import {join} from 'path'; import {APP_SRC, TEST_SRC, TEST_E2E_DEST} from '../config'; import {templateLocals, tsProjectFn} from '../utils'; export = function buildE2eTest(gulp, plugins) { let tsProject = tsProjectFn(plugins); return function () { let src = [ 'typings/browser.d.ts', join(APP_SRC, '**/*.ts'), join(TEST_SRC, '**/*.e2e.ts'), '!' + join(TEST_SRC, '**/*.spec.ts') ]; let result = gulp.src(src) .pipe(plugins.plumber()) .pipe(plugins.sourcemaps.init()) .pipe(plugins.typescript(tsProject)); return result.js .pipe(plugins.sourcemaps.write()) .pipe(plugins.template(templateLocals())) .pipe(gulp.dest(TEST_E2E_DEST)); }; };
mit
hovsepm/azure-sdk-for-java
compute/resource-manager/v2017_09_01/src/main/java/com/microsoft/azure/management/compute/v2017_09_01/ResourceSkuCapabilities.java
1063
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.compute.v2017_09_01; import com.fasterxml.jackson.annotation.JsonProperty; /** * Describes The SKU capabilites object. */ public class ResourceSkuCapabilities { /** * An invariant to describe the feature. */ @JsonProperty(value = "name", access = JsonProperty.Access.WRITE_ONLY) private String name; /** * An invariant if the feature is measured by quantity. */ @JsonProperty(value = "value", access = JsonProperty.Access.WRITE_ONLY) private String value; /** * Get the name value. * * @return the name value */ public String name() { return this.name; } /** * Get the value value. * * @return the value value */ public String value() { return this.value; } }
mit
babel/babel
packages/babel-plugin-transform-template-literals/test/fixtures/default/template-revision/output.js
1186
var _templateObject, _templateObject2, _templateObject3, _templateObject4, _templateObject5, _templateObject6, _templateObject7, _templateObject8; tag(_templateObject || (_templateObject = babelHelpers.taggedTemplateLiteral([void 0], ["\\unicode and \\u{55}"]))); tag(_templateObject2 || (_templateObject2 = babelHelpers.taggedTemplateLiteral([void 0], ["\\01"]))); tag(_templateObject3 || (_templateObject3 = babelHelpers.taggedTemplateLiteral([void 0, "right"], ["\\xg", "right"])), 0); tag(_templateObject4 || (_templateObject4 = babelHelpers.taggedTemplateLiteral(["left", void 0], ["left", "\\xg"])), 0); tag(_templateObject5 || (_templateObject5 = babelHelpers.taggedTemplateLiteral(["left", void 0, "right"], ["left", "\\xg", "right"])), 0, 1); tag(_templateObject6 || (_templateObject6 = babelHelpers.taggedTemplateLiteral(["left", void 0, "right"], ["left", "\\u000g", "right"])), 0, 1); tag(_templateObject7 || (_templateObject7 = babelHelpers.taggedTemplateLiteral(["left", void 0, "right"], ["left", "\\u{-0}", "right"])), 0, 1); function a() { var undefined = 4; tag(_templateObject8 || (_templateObject8 = babelHelpers.taggedTemplateLiteral([void 0], ["\\01"]))); }
mit
hovsepm/azure-sdk-for-java
logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/WorkflowRunActionRepetitionsImpl.java
4067
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * */ package com.microsoft.azure.management.logic.v2016_06_01.implementation; import com.microsoft.azure.arm.model.implementation.WrapperImpl; import com.microsoft.azure.management.logic.v2016_06_01.WorkflowRunActionRepetitions; import rx.Observable; import rx.functions.Func1; import java.util.List; import com.microsoft.azure.management.logic.v2016_06_01.ExpressionRoot; import com.microsoft.azure.management.logic.v2016_06_01.ActionRunWorkflowWorkflowRunActionRepetitionDefinition; class WorkflowRunActionRepetitionsImpl extends WrapperImpl<WorkflowRunActionRepetitionsInner> implements WorkflowRunActionRepetitions { private final LogicManager manager; WorkflowRunActionRepetitionsImpl(LogicManager manager) { super(manager.inner().workflowRunActionRepetitions()); this.manager = manager; } public LogicManager manager() { return this.manager; } private ActionRunWorkflowWorkflowRunActionRepetitionDefinitionImpl wrapModel(WorkflowRunActionRepetitionDefinitionInner inner) { return new ActionRunWorkflowWorkflowRunActionRepetitionDefinitionImpl(inner, manager()); } @Override public Observable<ExpressionRoot> listExpressionTracesAsync(String resourceGroupName, String workflowName, String runName, String actionName, String repetitionName) { WorkflowRunActionRepetitionsInner client = this.inner(); return client.listExpressionTracesAsync(resourceGroupName, workflowName, runName, actionName, repetitionName) .flatMap(new Func1<List<ExpressionRootInner>, Observable<ExpressionRootInner>>() { @Override public Observable<ExpressionRootInner> call(List<ExpressionRootInner> innerList) { return Observable.from(innerList); } }) .map(new Func1<ExpressionRootInner, ExpressionRoot>() { @Override public ExpressionRoot call(ExpressionRootInner inner) { return new ExpressionRootImpl(inner, manager()); } }); } @Override public Observable<ActionRunWorkflowWorkflowRunActionRepetitionDefinition> listAsync(String resourceGroupName, String workflowName, String runName, String actionName) { WorkflowRunActionRepetitionsInner client = this.inner(); return client.listAsync(resourceGroupName, workflowName, runName, actionName) .flatMap(new Func1<List<WorkflowRunActionRepetitionDefinitionInner>, Observable<WorkflowRunActionRepetitionDefinitionInner>>() { @Override public Observable<WorkflowRunActionRepetitionDefinitionInner> call(List<WorkflowRunActionRepetitionDefinitionInner> innerList) { return Observable.from(innerList); } }) .map(new Func1<WorkflowRunActionRepetitionDefinitionInner, ActionRunWorkflowWorkflowRunActionRepetitionDefinition>() { @Override public ActionRunWorkflowWorkflowRunActionRepetitionDefinition call(WorkflowRunActionRepetitionDefinitionInner inner) { return wrapModel(inner); } }); } @Override public Observable<ActionRunWorkflowWorkflowRunActionRepetitionDefinition> getAsync(String resourceGroupName, String workflowName, String runName, String actionName, String repetitionName) { WorkflowRunActionRepetitionsInner client = this.inner(); return client.getAsync(resourceGroupName, workflowName, runName, actionName, repetitionName) .map(new Func1<WorkflowRunActionRepetitionDefinitionInner, ActionRunWorkflowWorkflowRunActionRepetitionDefinition>() { @Override public ActionRunWorkflowWorkflowRunActionRepetitionDefinition call(WorkflowRunActionRepetitionDefinitionInner inner) { return wrapModel(inner); } }); } }
mit
tagalpha/library
app/code/core/Mage/Weee/Model/Config/Source/Fpt/Tax.php
1718
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Mage * @package Mage_Weee * @copyright Copyright (c) 2006-2017 X.commerce, Inc. and affiliates (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ class Mage_Weee_Model_Config_Source_Fpt_Tax { /** * Array of options for FPT Tax Configuration * * @return array */ public function toOptionArray() { $weeeHelper = $this->_getHelper('weee'); return array( array('value' => 0, 'label' => $weeeHelper->__('Not Taxed')), array('value' => 1, 'label' => $weeeHelper->__('Taxed')), array('value' => 2, 'label' => $weeeHelper->__('Loaded and Displayed with Tax')), ); } /** * Return helper corresponding to given name * * @param string $helperName * @return Mage_Core_Helper_Abstract */ protected function _getHelper($helperName) { return Mage::helper($helperName); } }
mit
idosekely/python-lessons
lesson_5/__init__.py
22
__author__ = 'sekely'
mit
tmcgee/cmv-wab-widgets
wab/2.15/widgets/RelatedTableCharts/nls/pt-pt/strings.js
507
define({ "_widgetLabel": "Tabelas de Gráficos Relacionados", "searchHeaderText": "Pesquisar um endereço ou localizar no mapa", "addressInfowindowTitle": "Localização Pesquisada", "mouseOverTooltip": "Clique para ver os gráfico(s)", "errMsgNoResultsFound": "Não foram encontrados resultados", "errMsgNoFeaturesFound": "Não foram encontrados elementos", "noChatsConfigured": "Nenhum gráfico pré-configurado está disponível", "locationButtonAriaLabel": "Selecionar local no mapa" });
mit
pilor/azure-sdk-for-net
src/SDKs/ApplicationInsights/DataPlane/ApplicationInsights/Customized/Models/ErrorResponseException.cs
291
using Microsoft.Rest; namespace Microsoft.Azure.ApplicationInsights.Models { public partial class ErrorResponseException : RestException { public override string ToString() { return Body != null ? Body.ToString() : Response.Content; } } }
mit
code-computerlove/quarry
bin/cli.js
336
#!/usr/bin/env node // Enable strict mode for older versions of node // eslint-disable-next-line strict, lines-around-directive 'use strict'; const updateNotifier = require('update-notifier'); const pkg = require('../package.json'); const program = require('./programBuilder.js'); updateNotifier({ pkg, callback: program }).notify();
mit
MehdyKarimpour/extensions
Signum.Entities.Extensions/Basics/FileContent.cs
347
namespace Signum.Entities.Basics { public class FileContent { public string FileName { get; private set; } public byte[] Bytes { get; private set; } public FileContent(string fileName, byte[] bytes) { this.FileName = fileName; this.Bytes = bytes; } } }
mit
aratin/visualintelligence
models/allnewes.js
629
var keystone = require('keystone'), Types = keystone.Field.Types; var Allnewes = new keystone.List('Allnewes', { autokey: { from: 'name', path: 'key' } }); Allnewes.add({ image1: { type: Types.CloudinaryImage}, date1:{type: Date}, news1: { type: String }, image2: { type: Types.CloudinaryImage}, date2:{type: Date}, news2: { type: String }, image3: { type: Types.CloudinaryImage}, date3:{type: Date}, news3: { type: String }, image4: { type: Types.CloudinaryImage}, date4:{type: Date}, news4: { type: String }, }); /** Registration ============ */ Allnewes.addPattern('standard meta'); Allnewes.register();
mit
misfit-inc/misfit.co
wp-content/plugins/wp-ses/vendor/Aws3/Aws/data/personalize-events/2018-03-22/paginators-1.json.php
139
<?php // This file was auto-generated from sdk-root/src/data/personalize-events/2018-03-22/paginators-1.json return ['pagination' => []];
mit
dharmatech/BrightstarDB
src/core/BrightstarDB/Storage/BPlusTreeStore/ResourceIndex/ResourceStore.cs
3359
using System; using System.Text; using BrightstarDB.Profiling; using BrightstarDB.Storage.Persistence; namespace BrightstarDB.Storage.BPlusTreeStore.ResourceIndex { internal class ResourceStore : IResourceStore { private readonly IResourceTable _resourceTable; private const int MaxLocalLiteralLength = 46; private const int MaxLocalUriLength = 62; public ResourceStore(IResourceTable resourceTable) { _resourceTable = resourceTable; } #region Implementation of IResourceStore public IResource CreateNew(ulong txnId, string resourceValue, bool isLiteral, ulong dataTypeId, ulong langCodeId, BrightstarProfiler profiler) { var valueLength = Encoding.UTF8.GetByteCount(resourceValue); if (isLiteral) { return valueLength <= MaxLocalLiteralLength ? new ShortLiteralResource(resourceValue, dataTypeId, langCodeId) : CreateLongLiteralResource(txnId, resourceValue, dataTypeId, langCodeId, profiler); } return valueLength < MaxLocalUriLength ? new ShortUriResource(resourceValue) : CreateLongUriResource(txnId, resourceValue, profiler); } public IResource FromBTreeValue(byte[] btreeValue) { var header = btreeValue[0]; bool isShort = ((header & (byte) ResourceHeaderFlags.IsShort) == (byte) ResourceHeaderFlags.IsShort); bool isLiteral = ((header & (byte) ResourceHeaderFlags.IsLiteral) == (byte) ResourceHeaderFlags.IsLiteral); if (isShort) { if (isLiteral) { return new ShortLiteralResource(btreeValue); } return new ShortUriResource(btreeValue); } if(isLiteral) { return new LongLiteralResource(_resourceTable, btreeValue); } return new LongUriResource(_resourceTable, btreeValue); } #endregion private IResource CreateLongLiteralResource(ulong txnId, string resourceValue, ulong dataTypeId, ulong langCodeId, BrightstarProfiler profiler) { ulong pageId; byte segId; _resourceTable.Insert(txnId, resourceValue, out pageId, out segId, profiler); return new LongLiteralResource(resourceValue, dataTypeId, langCodeId, pageId, segId); } private IResource CreateLongUriResource(ulong txnId, string uri, BrightstarProfiler profiler) { ulong pageId; byte segId; _resourceTable.Insert(txnId, uri, out pageId, out segId, profiler); return new LongUriResource(uri, pageId, segId); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private bool _disposed; private void Dispose(bool disposing) { if (disposing) { if (!_disposed) { _resourceTable.Dispose(); _disposed = true; } } } ~ResourceStore() { Dispose(false); } } }
mit
CSC322-Grinnell/notifications
spec/helpers/parent_helper_spec.rb
411
require 'spec_helper' # Specs in this file have access to a helper object that includes # the ParentHelper. For example: # # describe ParentHelper do # describe "string concat" do # it "concats two strings with spaces" do # expect(helper.concat_strings("this","that")).to eq("this that") # end # end # end describe ParentHelper do pending "add some examples to (or delete) #{__FILE__}" end
mit
Aldrien-/three.js
src/renderers/WebGLRenderer.js
62655
import { REVISION, RGBAFormat, HalfFloatType, FloatType, UnsignedByteType, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, LinearToneMapping, BackSide } from '../constants.js'; import { _Math } from '../math/Math.js'; import { DataTexture } from '../textures/DataTexture.js'; import { Frustum } from '../math/Frustum.js'; import { Matrix4 } from '../math/Matrix4.js'; import { ShaderLib } from './shaders/ShaderLib.js'; import { UniformsLib } from './shaders/UniformsLib.js'; import { UniformsUtils } from './shaders/UniformsUtils.js'; import { Vector3 } from '../math/Vector3.js'; import { Vector4 } from '../math/Vector4.js'; import { WebGLAnimation } from './webgl/WebGLAnimation.js'; import { WebGLAttributes } from './webgl/WebGLAttributes.js'; import { WebGLBackground } from './webgl/WebGLBackground.js'; import { WebGLBufferRenderer } from './webgl/WebGLBufferRenderer.js'; import { WebGLCapabilities } from './webgl/WebGLCapabilities.js'; import { WebGLClipping } from './webgl/WebGLClipping.js'; import { WebGLExtensions } from './webgl/WebGLExtensions.js'; import { WebGLGeometries } from './webgl/WebGLGeometries.js'; import { WebGLIndexedBufferRenderer } from './webgl/WebGLIndexedBufferRenderer.js'; import { WebGLInfo } from './webgl/WebGLInfo.js'; import { WebGLMorphtargets } from './webgl/WebGLMorphtargets.js'; import { WebGLObjects } from './webgl/WebGLObjects.js'; import { WebGLPrograms } from './webgl/WebGLPrograms.js'; import { WebGLProperties } from './webgl/WebGLProperties.js'; import { WebGLRenderLists } from './webgl/WebGLRenderLists.js'; import { WebGLRenderStates } from './webgl/WebGLRenderStates.js'; import { WebGLShadowMap } from './webgl/WebGLShadowMap.js'; import { WebGLState } from './webgl/WebGLState.js'; import { WebGLTextures } from './webgl/WebGLTextures.js'; import { WebGLUniforms } from './webgl/WebGLUniforms.js'; import { WebGLUtils } from './webgl/WebGLUtils.js'; import { WebVRManager } from './webvr/WebVRManager.js'; import { WebXRManager } from './webvr/WebXRManager.js'; /** * @author supereggbert / http://www.paulbrunt.co.uk/ * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ * @author szimek / https://github.com/szimek/ * @author tschw */ function WebGLRenderer( parameters ) { console.log( 'THREE.WebGLRenderer', REVISION ); parameters = parameters || {}; var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ), _context = parameters.context !== undefined ? parameters.context : null, _alpha = parameters.alpha !== undefined ? parameters.alpha : false, _depth = parameters.depth !== undefined ? parameters.depth : true, _stencil = parameters.stencil !== undefined ? parameters.stencil : true, _antialias = parameters.antialias !== undefined ? parameters.antialias : false, _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true, _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false, _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default'; var currentRenderList = null; var currentRenderState = null; // public properties this.domElement = _canvas; this.context = null; // clearing this.autoClear = true; this.autoClearColor = true; this.autoClearDepth = true; this.autoClearStencil = true; // scene graph this.sortObjects = true; // user-defined clipping this.clippingPlanes = []; this.localClippingEnabled = false; // physically based shading this.gammaFactor = 2.0; // for backwards compatibility this.gammaInput = false; this.gammaOutput = false; // physical lights this.physicallyCorrectLights = false; // tone mapping this.toneMapping = LinearToneMapping; this.toneMappingExposure = 1.0; this.toneMappingWhitePoint = 1.0; // morphs this.maxMorphTargets = 8; this.maxMorphNormals = 4; // internal properties var _this = this, _isContextLost = false, // internal state cache _framebuffer = null, _currentRenderTarget = null, _currentFramebuffer = null, _currentMaterialId = - 1, // geometry and program caching _currentGeometryProgram = { geometry: null, program: null, wireframe: false }, _currentCamera = null, _currentArrayCamera = null, _currentViewport = new Vector4(), _currentScissor = new Vector4(), _currentScissorTest = null, // _usedTextureUnits = 0, // _width = _canvas.width, _height = _canvas.height, _pixelRatio = 1, _viewport = new Vector4( 0, 0, _width, _height ), _scissor = new Vector4( 0, 0, _width, _height ), _scissorTest = false, // frustum _frustum = new Frustum(), // clipping _clipping = new WebGLClipping(), _clippingEnabled = false, _localClippingEnabled = false, // camera matrices cache _projScreenMatrix = new Matrix4(), _vector3 = new Vector3(); function getTargetPixelRatio() { return _currentRenderTarget === null ? _pixelRatio : 1; } // initialize var _gl; try { var contextAttributes = { alpha: _alpha, depth: _depth, stencil: _stencil, antialias: _antialias, premultipliedAlpha: _premultipliedAlpha, preserveDrawingBuffer: _preserveDrawingBuffer, powerPreference: _powerPreference }; // event listeners must be registered before WebGL context is created, see #12753 _canvas.addEventListener( 'webglcontextlost', onContextLost, false ); _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false ); _gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes ); if ( _gl === null ) { if ( _canvas.getContext( 'webgl' ) !== null ) { throw new Error( 'Error creating WebGL context with your selected attributes.' ); } else { throw new Error( 'Error creating WebGL context.' ); } } // Some experimental-webgl implementations do not have getShaderPrecisionFormat if ( _gl.getShaderPrecisionFormat === undefined ) { _gl.getShaderPrecisionFormat = function () { return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 }; }; } } catch ( error ) { console.error( 'THREE.WebGLRenderer: ' + error.message ); } var extensions, capabilities, state, info; var properties, textures, attributes, geometries, objects; var programCache, renderLists, renderStates; var background, morphtargets, bufferRenderer, indexedBufferRenderer; var utils; function initGLContext() { extensions = new WebGLExtensions( _gl ); capabilities = new WebGLCapabilities( _gl, extensions, parameters ); if ( ! capabilities.isWebGL2 ) { extensions.get( 'WEBGL_depth_texture' ); extensions.get( 'OES_texture_float' ); extensions.get( 'OES_texture_half_float' ); extensions.get( 'OES_texture_half_float_linear' ); extensions.get( 'OES_standard_derivatives' ); extensions.get( 'OES_element_index_uint' ); extensions.get( 'ANGLE_instanced_arrays' ); } extensions.get( 'OES_texture_float_linear' ); utils = new WebGLUtils( _gl, extensions, capabilities ); state = new WebGLState( _gl, extensions, utils, capabilities ); state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) ); state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) ); info = new WebGLInfo( _gl ); properties = new WebGLProperties(); textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ); attributes = new WebGLAttributes( _gl ); geometries = new WebGLGeometries( _gl, attributes, info ); objects = new WebGLObjects( geometries, info ); morphtargets = new WebGLMorphtargets( _gl ); programCache = new WebGLPrograms( _this, extensions, capabilities ); renderLists = new WebGLRenderLists(); renderStates = new WebGLRenderStates(); background = new WebGLBackground( _this, state, objects, _premultipliedAlpha ); bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities ); indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities ); info.programs = programCache.programs; _this.context = _gl; _this.capabilities = capabilities; _this.extensions = extensions; _this.properties = properties; _this.renderLists = renderLists; _this.state = state; _this.info = info; } initGLContext(); // vr var vr = null; if ( typeof navigator !== 'undefined' ) { vr = ( 'xr' in navigator ) ? new WebXRManager( _this ) : new WebVRManager( _this ); } this.vr = vr; // shadow map var shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize ); this.shadowMap = shadowMap; // API this.getContext = function () { return _gl; }; this.getContextAttributes = function () { return _gl.getContextAttributes(); }; this.forceContextLoss = function () { var extension = extensions.get( 'WEBGL_lose_context' ); if ( extension ) extension.loseContext(); }; this.forceContextRestore = function () { var extension = extensions.get( 'WEBGL_lose_context' ); if ( extension ) extension.restoreContext(); }; this.getPixelRatio = function () { return _pixelRatio; }; this.setPixelRatio = function ( value ) { if ( value === undefined ) return; _pixelRatio = value; this.setSize( _width, _height, false ); }; this.getSize = function () { return { width: _width, height: _height }; }; this.setSize = function ( width, height, updateStyle ) { if ( vr.isPresenting() ) { console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' ); return; } _width = width; _height = height; _canvas.width = width * _pixelRatio; _canvas.height = height * _pixelRatio; if ( updateStyle !== false ) { _canvas.style.width = width + 'px'; _canvas.style.height = height + 'px'; } this.setViewport( 0, 0, width, height ); }; this.getDrawingBufferSize = function () { return { width: _width * _pixelRatio, height: _height * _pixelRatio }; }; this.setDrawingBufferSize = function ( width, height, pixelRatio ) { _width = width; _height = height; _pixelRatio = pixelRatio; _canvas.width = width * pixelRatio; _canvas.height = height * pixelRatio; this.setViewport( 0, 0, width, height ); }; this.getCurrentViewport = function () { return _currentViewport; }; this.setViewport = function ( x, y, width, height ) { _viewport.set( x, _height - y - height, width, height ); state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) ); }; this.setScissor = function ( x, y, width, height ) { _scissor.set( x, _height - y - height, width, height ); state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) ); }; this.setScissorTest = function ( boolean ) { state.setScissorTest( _scissorTest = boolean ); }; // Clearing this.getClearColor = function () { return background.getClearColor(); }; this.setClearColor = function () { background.setClearColor.apply( background, arguments ); }; this.getClearAlpha = function () { return background.getClearAlpha(); }; this.setClearAlpha = function () { background.setClearAlpha.apply( background, arguments ); }; this.clear = function ( color, depth, stencil ) { var bits = 0; if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT; if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT; if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT; _gl.clear( bits ); }; this.clearColor = function () { this.clear( true, false, false ); }; this.clearDepth = function () { this.clear( false, true, false ); }; this.clearStencil = function () { this.clear( false, false, true ); }; // this.dispose = function () { _canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false ); renderLists.dispose(); renderStates.dispose(); properties.dispose(); objects.dispose(); vr.dispose(); animation.stop(); }; // Events function onContextLost( event ) { event.preventDefault(); console.log( 'THREE.WebGLRenderer: Context Lost.' ); _isContextLost = true; } function onContextRestore( /* event */ ) { console.log( 'THREE.WebGLRenderer: Context Restored.' ); _isContextLost = false; initGLContext(); } function onMaterialDispose( event ) { var material = event.target; material.removeEventListener( 'dispose', onMaterialDispose ); deallocateMaterial( material ); } // Buffer deallocation function deallocateMaterial( material ) { releaseMaterialProgramReference( material ); properties.remove( material ); } function releaseMaterialProgramReference( material ) { var programInfo = properties.get( material ).program; material.program = undefined; if ( programInfo !== undefined ) { programCache.releaseProgram( programInfo ); } } // Buffer rendering function renderObjectImmediate( object, program ) { object.render( function ( object ) { _this.renderBufferImmediate( object, program ); } ); } this.renderBufferImmediate = function ( object, program ) { state.initAttributes(); var buffers = properties.get( object ); if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer(); if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer(); if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer(); if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer(); var programAttributes = program.getAttributes(); if ( object.hasPositions ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position ); _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW ); state.enableAttribute( programAttributes.position ); _gl.vertexAttribPointer( programAttributes.position, 3, _gl.FLOAT, false, 0, 0 ); } if ( object.hasNormals ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal ); _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW ); state.enableAttribute( programAttributes.normal ); _gl.vertexAttribPointer( programAttributes.normal, 3, _gl.FLOAT, false, 0, 0 ); } if ( object.hasUvs ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv ); _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW ); state.enableAttribute( programAttributes.uv ); _gl.vertexAttribPointer( programAttributes.uv, 2, _gl.FLOAT, false, 0, 0 ); } if ( object.hasColors ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color ); _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW ); state.enableAttribute( programAttributes.color ); _gl.vertexAttribPointer( programAttributes.color, 3, _gl.FLOAT, false, 0, 0 ); } state.disableUnusedAttributes(); _gl.drawArrays( _gl.TRIANGLES, 0, object.count ); object.count = 0; }; this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) { var frontFaceCW = ( object.isMesh && object.normalMatrix.determinant() < 0 ); state.setMaterial( material, frontFaceCW ); var program = setProgram( camera, fog, material, object ); var updateBuffers = false; if ( _currentGeometryProgram.geometry !== geometry.id || _currentGeometryProgram.program !== program.id || _currentGeometryProgram.wireframe !== ( material.wireframe === true ) ) { _currentGeometryProgram.geometry = geometry.id; _currentGeometryProgram.program = program.id; _currentGeometryProgram.wireframe = material.wireframe === true; updateBuffers = true; } if ( object.morphTargetInfluences ) { morphtargets.update( object, geometry, material, program ); updateBuffers = true; } // var index = geometry.index; var position = geometry.attributes.position; var rangeFactor = 1; if ( material.wireframe === true ) { index = geometries.getWireframeAttribute( geometry ); rangeFactor = 2; } var attribute; var renderer = bufferRenderer; if ( index !== null ) { attribute = attributes.get( index ); renderer = indexedBufferRenderer; renderer.setIndex( attribute ); } if ( updateBuffers ) { setupVertexAttributes( material, program, geometry ); if ( index !== null ) { _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attribute.buffer ); } } // var dataCount = Infinity; if ( index !== null ) { dataCount = index.count; } else if ( position !== undefined ) { dataCount = position.count; } var rangeStart = geometry.drawRange.start * rangeFactor; var rangeCount = geometry.drawRange.count * rangeFactor; var groupStart = group !== null ? group.start * rangeFactor : 0; var groupCount = group !== null ? group.count * rangeFactor : Infinity; var drawStart = Math.max( rangeStart, groupStart ); var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1; var drawCount = Math.max( 0, drawEnd - drawStart + 1 ); if ( drawCount === 0 ) return; // if ( object.isMesh ) { if ( material.wireframe === true ) { state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() ); renderer.setMode( _gl.LINES ); } else { switch ( object.drawMode ) { case TrianglesDrawMode: renderer.setMode( _gl.TRIANGLES ); break; case TriangleStripDrawMode: renderer.setMode( _gl.TRIANGLE_STRIP ); break; case TriangleFanDrawMode: renderer.setMode( _gl.TRIANGLE_FAN ); break; } } } else if ( object.isLine ) { var lineWidth = material.linewidth; if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material state.setLineWidth( lineWidth * getTargetPixelRatio() ); if ( object.isLineSegments ) { renderer.setMode( _gl.LINES ); } else if ( object.isLineLoop ) { renderer.setMode( _gl.LINE_LOOP ); } else { renderer.setMode( _gl.LINE_STRIP ); } } else if ( object.isPoints ) { renderer.setMode( _gl.POINTS ); } else if ( object.isSprite ) { renderer.setMode( _gl.TRIANGLES ); } if ( geometry && geometry.isInstancedBufferGeometry ) { if ( geometry.maxInstancedCount > 0 ) { renderer.renderInstances( geometry, drawStart, drawCount ); } } else { renderer.render( drawStart, drawCount ); } }; function setupVertexAttributes( material, program, geometry ) { if ( geometry && geometry.isInstancedBufferGeometry & ! capabilities.isWebGL2 ) { if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) { console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); return; } } state.initAttributes(); var geometryAttributes = geometry.attributes; var programAttributes = program.getAttributes(); var materialDefaultAttributeValues = material.defaultAttributeValues; for ( var name in programAttributes ) { var programAttribute = programAttributes[ name ]; if ( programAttribute >= 0 ) { var geometryAttribute = geometryAttributes[ name ]; if ( geometryAttribute !== undefined ) { var normalized = geometryAttribute.normalized; var size = geometryAttribute.itemSize; var attribute = attributes.get( geometryAttribute ); // TODO Attribute may not be available on context restore if ( attribute === undefined ) continue; var buffer = attribute.buffer; var type = attribute.type; var bytesPerElement = attribute.bytesPerElement; if ( geometryAttribute.isInterleavedBufferAttribute ) { var data = geometryAttribute.data; var stride = data.stride; var offset = geometryAttribute.offset; if ( data && data.isInstancedInterleavedBuffer ) { state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute ); if ( geometry.maxInstancedCount === undefined ) { geometry.maxInstancedCount = data.meshPerAttribute * data.count; } } else { state.enableAttribute( programAttribute ); } _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer ); _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement ); } else { if ( geometryAttribute.isInstancedBufferAttribute ) { state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute ); if ( geometry.maxInstancedCount === undefined ) { geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; } } else { state.enableAttribute( programAttribute ); } _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer ); _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 ); } } else if ( materialDefaultAttributeValues !== undefined ) { var value = materialDefaultAttributeValues[ name ]; if ( value !== undefined ) { switch ( value.length ) { case 2: _gl.vertexAttrib2fv( programAttribute, value ); break; case 3: _gl.vertexAttrib3fv( programAttribute, value ); break; case 4: _gl.vertexAttrib4fv( programAttribute, value ); break; default: _gl.vertexAttrib1fv( programAttribute, value ); } } } } } state.disableUnusedAttributes(); } // Compile this.compile = function ( scene, camera ) { currentRenderState = renderStates.get( scene, camera ); currentRenderState.init(); scene.traverse( function ( object ) { if ( object.isLight ) { currentRenderState.pushLight( object ); if ( object.castShadow ) { currentRenderState.pushShadow( object ); } } } ); currentRenderState.setupLights( camera ); scene.traverse( function ( object ) { if ( object.material ) { if ( Array.isArray( object.material ) ) { for ( var i = 0; i < object.material.length; i ++ ) { initMaterial( object.material[ i ], scene.fog, object ); } } else { initMaterial( object.material, scene.fog, object ); } } } ); }; // Animation Loop var onAnimationFrameCallback = null; function onAnimationFrame( time ) { if ( vr.isPresenting() ) return; if ( onAnimationFrameCallback ) onAnimationFrameCallback( time ); } var animation = new WebGLAnimation(); animation.setAnimationLoop( onAnimationFrame ); if ( typeof window !== 'undefined' ) animation.setContext( window ); this.setAnimationLoop = function ( callback ) { onAnimationFrameCallback = callback; vr.setAnimationLoop( callback ); animation.start(); }; // Rendering this.render = function ( scene, camera, renderTarget, forceClear ) { if ( ! ( camera && camera.isCamera ) ) { console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); return; } if ( _isContextLost ) return; // reset caching for this frame _currentGeometryProgram.geometry = null; _currentGeometryProgram.program = null; _currentGeometryProgram.wireframe = false; _currentMaterialId = - 1; _currentCamera = null; // update scene graph if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); // update camera matrices and frustum if ( camera.parent === null ) camera.updateMatrixWorld(); if ( vr.enabled ) { camera = vr.getCamera( camera ); } // currentRenderState = renderStates.get( scene, camera ); currentRenderState.init(); scene.onBeforeRender( _this, scene, camera, renderTarget ); _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); _frustum.setFromMatrix( _projScreenMatrix ); _localClippingEnabled = this.localClippingEnabled; _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera ); currentRenderList = renderLists.get( scene, camera ); currentRenderList.init(); projectObject( scene, camera, _this.sortObjects ); if ( _this.sortObjects === true ) { currentRenderList.sort(); } // if ( _clippingEnabled ) _clipping.beginShadows(); var shadowsArray = currentRenderState.state.shadowsArray; shadowMap.render( shadowsArray, scene, camera ); currentRenderState.setupLights( camera ); if ( _clippingEnabled ) _clipping.endShadows(); // if ( this.info.autoReset ) this.info.reset(); if ( renderTarget === undefined ) { renderTarget = null; } this.setRenderTarget( renderTarget ); // background.render( currentRenderList, scene, camera, forceClear ); // render scene var opaqueObjects = currentRenderList.opaque; var transparentObjects = currentRenderList.transparent; if ( scene.overrideMaterial ) { var overrideMaterial = scene.overrideMaterial; if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera, overrideMaterial ); if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera, overrideMaterial ); } else { // opaque pass (front-to-back order) if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera ); // transparent pass (back-to-front order) if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera ); } // Generate mipmap if we're using any kind of mipmap filtering if ( renderTarget ) { textures.updateRenderTargetMipmap( renderTarget ); } // Ensure depth buffer writing is enabled so it can be cleared on next render state.buffers.depth.setTest( true ); state.buffers.depth.setMask( true ); state.buffers.color.setMask( true ); state.setPolygonOffset( false ); scene.onAfterRender( _this, scene, camera ); if ( vr.enabled ) { vr.submitFrame(); } // _gl.finish(); currentRenderList = null; currentRenderState = null; }; function projectObject( object, camera, sortObjects ) { if ( object.visible === false ) return; var visible = object.layers.test( camera.layers ); if ( visible ) { if ( object.isLight ) { currentRenderState.pushLight( object ); if ( object.castShadow ) { currentRenderState.pushShadow( object ); } } else if ( object.isSprite ) { if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) { if ( sortObjects ) { _vector3.setFromMatrixPosition( object.matrixWorld ) .applyMatrix4( _projScreenMatrix ); } var geometry = objects.update( object ); var material = object.material; currentRenderList.push( object, geometry, material, _vector3.z, null ); } } else if ( object.isImmediateRenderObject ) { if ( sortObjects ) { _vector3.setFromMatrixPosition( object.matrixWorld ) .applyMatrix4( _projScreenMatrix ); } currentRenderList.push( object, null, object.material, _vector3.z, null ); } else if ( object.isMesh || object.isLine || object.isPoints ) { if ( object.isSkinnedMesh ) { object.skeleton.update(); } if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) { if ( sortObjects ) { _vector3.setFromMatrixPosition( object.matrixWorld ) .applyMatrix4( _projScreenMatrix ); } var geometry = objects.update( object ); var material = object.material; if ( Array.isArray( material ) ) { var groups = geometry.groups; for ( var i = 0, l = groups.length; i < l; i ++ ) { var group = groups[ i ]; var groupMaterial = material[ group.materialIndex ]; if ( groupMaterial && groupMaterial.visible ) { currentRenderList.push( object, geometry, groupMaterial, _vector3.z, group ); } } } else if ( material.visible ) { currentRenderList.push( object, geometry, material, _vector3.z, null ); } } } } var children = object.children; for ( var i = 0, l = children.length; i < l; i ++ ) { projectObject( children[ i ], camera, sortObjects ); } } function renderObjects( renderList, scene, camera, overrideMaterial ) { for ( var i = 0, l = renderList.length; i < l; i ++ ) { var renderItem = renderList[ i ]; var object = renderItem.object; var geometry = renderItem.geometry; var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial; var group = renderItem.group; if ( camera.isArrayCamera ) { _currentArrayCamera = camera; var cameras = camera.cameras; for ( var j = 0, jl = cameras.length; j < jl; j ++ ) { var camera2 = cameras[ j ]; if ( object.layers.test( camera2.layers ) ) { if ( 'viewport' in camera2 ) { // XR state.viewport( _currentViewport.copy( camera2.viewport ) ); } else { var bounds = camera2.bounds; var x = bounds.x * _width; var y = bounds.y * _height; var width = bounds.z * _width; var height = bounds.w * _height; state.viewport( _currentViewport.set( x, y, width, height ).multiplyScalar( _pixelRatio ) ); } currentRenderState.setupLights( camera2 ); renderObject( object, scene, camera2, geometry, material, group ); } } } else { _currentArrayCamera = null; renderObject( object, scene, camera, geometry, material, group ); } } } function renderObject( object, scene, camera, geometry, material, group ) { object.onBeforeRender( _this, scene, camera, geometry, material, group ); currentRenderState = renderStates.get( scene, _currentArrayCamera || camera ); object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); object.normalMatrix.getNormalMatrix( object.modelViewMatrix ); if ( object.isImmediateRenderObject ) { state.setMaterial( material ); var program = setProgram( camera, scene.fog, material, object ); _currentGeometryProgram.geometry = null; _currentGeometryProgram.program = null; _currentGeometryProgram.wireframe = false; renderObjectImmediate( object, program ); } else { _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group ); } object.onAfterRender( _this, scene, camera, geometry, material, group ); currentRenderState = renderStates.get( scene, _currentArrayCamera || camera ); } function initMaterial( material, fog, object ) { var materialProperties = properties.get( material ); var lights = currentRenderState.state.lights; var shadowsArray = currentRenderState.state.shadowsArray; var lightsHash = materialProperties.lightsHash; var lightsStateHash = lights.state.hash; var parameters = programCache.getParameters( material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object ); var code = programCache.getProgramCode( material, parameters ); var program = materialProperties.program; var programChange = true; if ( program === undefined ) { // new material material.addEventListener( 'dispose', onMaterialDispose ); } else if ( program.code !== code ) { // changed glsl or parameters releaseMaterialProgramReference( material ); } else if ( lightsHash.stateID !== lightsStateHash.stateID || lightsHash.directionalLength !== lightsStateHash.directionalLength || lightsHash.pointLength !== lightsStateHash.pointLength || lightsHash.spotLength !== lightsStateHash.spotLength || lightsHash.rectAreaLength !== lightsStateHash.rectAreaLength || lightsHash.hemiLength !== lightsStateHash.hemiLength || lightsHash.shadowsLength !== lightsStateHash.shadowsLength ) { lightsHash.stateID = lightsStateHash.stateID; lightsHash.directionalLength = lightsStateHash.directionalLength; lightsHash.pointLength = lightsStateHash.pointLength; lightsHash.spotLength = lightsStateHash.spotLength; lightsHash.rectAreaLength = lightsStateHash.rectAreaLength; lightsHash.hemiLength = lightsStateHash.hemiLength; lightsHash.shadowsLength = lightsStateHash.shadowsLength; programChange = false; } else if ( parameters.shaderID !== undefined ) { // same glsl and uniform list return; } else { // only rebuild uniform list programChange = false; } if ( programChange ) { if ( parameters.shaderID ) { var shader = ShaderLib[ parameters.shaderID ]; materialProperties.shader = { name: material.type, uniforms: UniformsUtils.clone( shader.uniforms ), vertexShader: shader.vertexShader, fragmentShader: shader.fragmentShader }; } else { materialProperties.shader = { name: material.type, uniforms: material.uniforms, vertexShader: material.vertexShader, fragmentShader: material.fragmentShader }; } material.onBeforeCompile( materialProperties.shader, _this ); // Computing code again as onBeforeCompile may have changed the shaders code = programCache.getProgramCode( material, parameters ); program = programCache.acquireProgram( material, materialProperties.shader, parameters, code ); materialProperties.program = program; material.program = program; } var programAttributes = program.getAttributes(); if ( material.morphTargets ) { material.numSupportedMorphTargets = 0; for ( var i = 0; i < _this.maxMorphTargets; i ++ ) { if ( programAttributes[ 'morphTarget' + i ] >= 0 ) { material.numSupportedMorphTargets ++; } } } if ( material.morphNormals ) { material.numSupportedMorphNormals = 0; for ( var i = 0; i < _this.maxMorphNormals; i ++ ) { if ( programAttributes[ 'morphNormal' + i ] >= 0 ) { material.numSupportedMorphNormals ++; } } } var uniforms = materialProperties.shader.uniforms; if ( ! material.isShaderMaterial && ! material.isRawShaderMaterial || material.clipping === true ) { materialProperties.numClippingPlanes = _clipping.numPlanes; materialProperties.numIntersection = _clipping.numIntersection; uniforms.clippingPlanes = _clipping.uniform; } materialProperties.fog = fog; // store the light setup it was created for if ( lightsHash === undefined ) { materialProperties.lightsHash = lightsHash = {}; } lightsHash.stateID = lightsStateHash.stateID; lightsHash.directionalLength = lightsStateHash.directionalLength; lightsHash.pointLength = lightsStateHash.pointLength; lightsHash.spotLength = lightsStateHash.spotLength; lightsHash.rectAreaLength = lightsStateHash.rectAreaLength; lightsHash.hemiLength = lightsStateHash.hemiLength; lightsHash.shadowsLength = lightsStateHash.shadowsLength; if ( material.lights ) { // wire up the material to this renderer's lighting state uniforms.ambientLightColor.value = lights.state.ambient; uniforms.directionalLights.value = lights.state.directional; uniforms.spotLights.value = lights.state.spot; uniforms.rectAreaLights.value = lights.state.rectArea; uniforms.pointLights.value = lights.state.point; uniforms.hemisphereLights.value = lights.state.hemi; uniforms.directionalShadowMap.value = lights.state.directionalShadowMap; uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; uniforms.spotShadowMap.value = lights.state.spotShadowMap; uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix; uniforms.pointShadowMap.value = lights.state.pointShadowMap; uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms } var progUniforms = materialProperties.program.getUniforms(), uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms ); materialProperties.uniformsList = uniformsList; } function setProgram( camera, fog, material, object ) { _usedTextureUnits = 0; var materialProperties = properties.get( material ); var lights = currentRenderState.state.lights; var lightsHash = materialProperties.lightsHash; var lightsStateHash = lights.state.hash; if ( _clippingEnabled ) { if ( _localClippingEnabled || camera !== _currentCamera ) { var useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup // object instead of the material, once it becomes feasible // (#8465, #8379) _clipping.setState( material.clippingPlanes, material.clipIntersection, material.clipShadows, camera, materialProperties, useCache ); } } if ( material.needsUpdate === false ) { if ( materialProperties.program === undefined ) { material.needsUpdate = true; } else if ( material.fog && materialProperties.fog !== fog ) { material.needsUpdate = true; } else if ( material.lights && ( lightsHash.stateID !== lightsStateHash.stateID || lightsHash.directionalLength !== lightsStateHash.directionalLength || lightsHash.pointLength !== lightsStateHash.pointLength || lightsHash.spotLength !== lightsStateHash.spotLength || lightsHash.rectAreaLength !== lightsStateHash.rectAreaLength || lightsHash.hemiLength !== lightsStateHash.hemiLength || lightsHash.shadowsLength !== lightsStateHash.shadowsLength ) ) { material.needsUpdate = true; } else if ( materialProperties.numClippingPlanes !== undefined && ( materialProperties.numClippingPlanes !== _clipping.numPlanes || materialProperties.numIntersection !== _clipping.numIntersection ) ) { material.needsUpdate = true; } } if ( material.needsUpdate ) { initMaterial( material, fog, object ); material.needsUpdate = false; } var refreshProgram = false; var refreshMaterial = false; var refreshLights = false; var program = materialProperties.program, p_uniforms = program.getUniforms(), m_uniforms = materialProperties.shader.uniforms; if ( state.useProgram( program.program ) ) { refreshProgram = true; refreshMaterial = true; refreshLights = true; } if ( material.id !== _currentMaterialId ) { _currentMaterialId = material.id; refreshMaterial = true; } if ( refreshProgram || _currentCamera !== camera ) { p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix ); if ( capabilities.logarithmicDepthBuffer ) { p_uniforms.setValue( _gl, 'logDepthBufFC', 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) ); } if ( _currentCamera !== camera ) { _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update // now, in case this material supports lights - or later, when // the next material that does gets activated: refreshMaterial = true; // set to true on material change refreshLights = true; // remains set until update done } // load material specific uniforms // (shader material also gets them for the sake of genericity) if ( material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.envMap ) { var uCamPos = p_uniforms.map.cameraPosition; if ( uCamPos !== undefined ) { uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) ); } } if ( material.isMeshPhongMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.skinning ) { p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse ); } } // skinning uniforms must be set even if material didn't change // auto-setting of texture unit for bone texture must go before other textures // not sure why, but otherwise weird things happen if ( material.skinning ) { p_uniforms.setOptional( _gl, object, 'bindMatrix' ); p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' ); var skeleton = object.skeleton; if ( skeleton ) { var bones = skeleton.bones; if ( capabilities.floatVertexTextures ) { if ( skeleton.boneTexture === undefined ) { // layout (1 matrix = 4 pixels) // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4) // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8) // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16) // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32) // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64) var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix size = _Math.ceilPowerOfTwo( size ); size = Math.max( size, 4 ); var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel boneMatrices.set( skeleton.boneMatrices ); // copy current values var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType ); boneTexture.needsUpdate = true; skeleton.boneMatrices = boneMatrices; skeleton.boneTexture = boneTexture; skeleton.boneTextureSize = size; } p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture ); p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize ); } else { p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' ); } } } if ( refreshMaterial ) { p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure ); p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint ); if ( material.lights ) { // the current material requires lighting info // note: all lighting uniforms are always set correctly // they simply reference the renderer's state for their // values // // use the current material's .needsUpdate flags to set // the GL state when required markUniformsLightsNeedsUpdate( m_uniforms, refreshLights ); } // refresh uniforms common to several materials if ( fog && material.fog ) { refreshUniformsFog( m_uniforms, fog ); } if ( material.isMeshBasicMaterial ) { refreshUniformsCommon( m_uniforms, material ); } else if ( material.isMeshLambertMaterial ) { refreshUniformsCommon( m_uniforms, material ); refreshUniformsLambert( m_uniforms, material ); } else if ( material.isMeshPhongMaterial ) { refreshUniformsCommon( m_uniforms, material ); if ( material.isMeshToonMaterial ) { refreshUniformsToon( m_uniforms, material ); } else { refreshUniformsPhong( m_uniforms, material ); } } else if ( material.isMeshStandardMaterial ) { refreshUniformsCommon( m_uniforms, material ); if ( material.isMeshPhysicalMaterial ) { refreshUniformsPhysical( m_uniforms, material ); } else { refreshUniformsStandard( m_uniforms, material ); } } else if ( material.isMeshMatcapMaterial ) { refreshUniformsCommon( m_uniforms, material ); refreshUniformsMatcap( m_uniforms, material ); } else if ( material.isMeshDepthMaterial ) { refreshUniformsCommon( m_uniforms, material ); refreshUniformsDepth( m_uniforms, material ); } else if ( material.isMeshDistanceMaterial ) { refreshUniformsCommon( m_uniforms, material ); refreshUniformsDistance( m_uniforms, material ); } else if ( material.isMeshNormalMaterial ) { refreshUniformsCommon( m_uniforms, material ); refreshUniformsNormal( m_uniforms, material ); } else if ( material.isLineBasicMaterial ) { refreshUniformsLine( m_uniforms, material ); if ( material.isLineDashedMaterial ) { refreshUniformsDash( m_uniforms, material ); } } else if ( material.isPointsMaterial ) { refreshUniformsPoints( m_uniforms, material ); } else if ( material.isSpriteMaterial ) { refreshUniformsSprites( m_uniforms, material ); } else if ( material.isShadowMaterial ) { m_uniforms.color.value = material.color; m_uniforms.opacity.value = material.opacity; } // RectAreaLight Texture // TODO (mrdoob): Find a nicer implementation if ( m_uniforms.ltc_1 !== undefined ) m_uniforms.ltc_1.value = UniformsLib.LTC_1; if ( m_uniforms.ltc_2 !== undefined ) m_uniforms.ltc_2.value = UniformsLib.LTC_2; WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, _this ); } if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) { WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, _this ); material.uniformsNeedUpdate = false; } if ( material.isSpriteMaterial ) { p_uniforms.setValue( _gl, 'center', object.center ); } // common matrices p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix ); p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix ); p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld ); return program; } // Uniforms (refresh uniforms objects) function refreshUniformsCommon( uniforms, material ) { uniforms.opacity.value = material.opacity; if ( material.color ) { uniforms.diffuse.value = material.color; } if ( material.emissive ) { uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity ); } if ( material.map ) { uniforms.map.value = material.map; } if ( material.alphaMap ) { uniforms.alphaMap.value = material.alphaMap; } if ( material.specularMap ) { uniforms.specularMap.value = material.specularMap; } if ( material.envMap ) { uniforms.envMap.value = material.envMap; // don't flip CubeTexture envMaps, flip everything else: // WebGLRenderTargetCube will be flipped for backwards compatibility // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1; uniforms.reflectivity.value = material.reflectivity; uniforms.refractionRatio.value = material.refractionRatio; uniforms.maxMipLevel.value = properties.get( material.envMap ).__maxMipLevel; } if ( material.lightMap ) { uniforms.lightMap.value = material.lightMap; uniforms.lightMapIntensity.value = material.lightMapIntensity; } if ( material.aoMap ) { uniforms.aoMap.value = material.aoMap; uniforms.aoMapIntensity.value = material.aoMapIntensity; } // uv repeat and offset setting priorities // 1. color map // 2. specular map // 3. normal map // 4. bump map // 5. alpha map // 6. emissive map var uvScaleMap; if ( material.map ) { uvScaleMap = material.map; } else if ( material.specularMap ) { uvScaleMap = material.specularMap; } else if ( material.displacementMap ) { uvScaleMap = material.displacementMap; } else if ( material.normalMap ) { uvScaleMap = material.normalMap; } else if ( material.bumpMap ) { uvScaleMap = material.bumpMap; } else if ( material.roughnessMap ) { uvScaleMap = material.roughnessMap; } else if ( material.metalnessMap ) { uvScaleMap = material.metalnessMap; } else if ( material.alphaMap ) { uvScaleMap = material.alphaMap; } else if ( material.emissiveMap ) { uvScaleMap = material.emissiveMap; } if ( uvScaleMap !== undefined ) { // backwards compatibility if ( uvScaleMap.isWebGLRenderTarget ) { uvScaleMap = uvScaleMap.texture; } if ( uvScaleMap.matrixAutoUpdate === true ) { uvScaleMap.updateMatrix(); } uniforms.uvTransform.value.copy( uvScaleMap.matrix ); } } function refreshUniformsLine( uniforms, material ) { uniforms.diffuse.value = material.color; uniforms.opacity.value = material.opacity; } function refreshUniformsDash( uniforms, material ) { uniforms.dashSize.value = material.dashSize; uniforms.totalSize.value = material.dashSize + material.gapSize; uniforms.scale.value = material.scale; } function refreshUniformsPoints( uniforms, material ) { uniforms.diffuse.value = material.color; uniforms.opacity.value = material.opacity; uniforms.size.value = material.size * _pixelRatio; uniforms.scale.value = _height * 0.5; uniforms.map.value = material.map; if ( material.map !== null ) { if ( material.map.matrixAutoUpdate === true ) { material.map.updateMatrix(); } uniforms.uvTransform.value.copy( material.map.matrix ); } } function refreshUniformsSprites( uniforms, material ) { uniforms.diffuse.value = material.color; uniforms.opacity.value = material.opacity; uniforms.rotation.value = material.rotation; uniforms.map.value = material.map; if ( material.map !== null ) { if ( material.map.matrixAutoUpdate === true ) { material.map.updateMatrix(); } uniforms.uvTransform.value.copy( material.map.matrix ); } } function refreshUniformsFog( uniforms, fog ) { uniforms.fogColor.value = fog.color; if ( fog.isFog ) { uniforms.fogNear.value = fog.near; uniforms.fogFar.value = fog.far; } else if ( fog.isFogExp2 ) { uniforms.fogDensity.value = fog.density; } } function refreshUniformsLambert( uniforms, material ) { if ( material.emissiveMap ) { uniforms.emissiveMap.value = material.emissiveMap; } } function refreshUniformsPhong( uniforms, material ) { uniforms.specular.value = material.specular; uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 ) if ( material.emissiveMap ) { uniforms.emissiveMap.value = material.emissiveMap; } if ( material.bumpMap ) { uniforms.bumpMap.value = material.bumpMap; uniforms.bumpScale.value = material.bumpScale; if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1; } if ( material.normalMap ) { uniforms.normalMap.value = material.normalMap; uniforms.normalScale.value.copy( material.normalScale ); if ( material.side === BackSide ) uniforms.normalScale.value.negate(); } if ( material.displacementMap ) { uniforms.displacementMap.value = material.displacementMap; uniforms.displacementScale.value = material.displacementScale; uniforms.displacementBias.value = material.displacementBias; } } function refreshUniformsToon( uniforms, material ) { refreshUniformsPhong( uniforms, material ); if ( material.gradientMap ) { uniforms.gradientMap.value = material.gradientMap; } } function refreshUniformsStandard( uniforms, material ) { uniforms.roughness.value = material.roughness; uniforms.metalness.value = material.metalness; if ( material.roughnessMap ) { uniforms.roughnessMap.value = material.roughnessMap; } if ( material.metalnessMap ) { uniforms.metalnessMap.value = material.metalnessMap; } if ( material.emissiveMap ) { uniforms.emissiveMap.value = material.emissiveMap; } if ( material.bumpMap ) { uniforms.bumpMap.value = material.bumpMap; uniforms.bumpScale.value = material.bumpScale; if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1; } if ( material.normalMap ) { uniforms.normalMap.value = material.normalMap; uniforms.normalScale.value.copy( material.normalScale ); if ( material.side === BackSide ) uniforms.normalScale.value.negate(); } if ( material.displacementMap ) { uniforms.displacementMap.value = material.displacementMap; uniforms.displacementScale.value = material.displacementScale; uniforms.displacementBias.value = material.displacementBias; } if ( material.envMap ) { //uniforms.envMap.value = material.envMap; // part of uniforms common uniforms.envMapIntensity.value = material.envMapIntensity; } } function refreshUniformsPhysical( uniforms, material ) { refreshUniformsStandard( uniforms, material ); uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common uniforms.clearCoat.value = material.clearCoat; uniforms.clearCoatRoughness.value = material.clearCoatRoughness; } function refreshUniformsMatcap( uniforms, material ) { if ( material.matcap ) { uniforms.matcap.value = material.matcap; } if ( material.bumpMap ) { uniforms.bumpMap.value = material.bumpMap; uniforms.bumpScale.value = material.bumpScale; if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1; } if ( material.normalMap ) { uniforms.normalMap.value = material.normalMap; uniforms.normalScale.value.copy( material.normalScale ); if ( material.side === BackSide ) uniforms.normalScale.value.negate(); } if ( material.displacementMap ) { uniforms.displacementMap.value = material.displacementMap; uniforms.displacementScale.value = material.displacementScale; uniforms.displacementBias.value = material.displacementBias; } } function refreshUniformsDepth( uniforms, material ) { if ( material.displacementMap ) { uniforms.displacementMap.value = material.displacementMap; uniforms.displacementScale.value = material.displacementScale; uniforms.displacementBias.value = material.displacementBias; } } function refreshUniformsDistance( uniforms, material ) { if ( material.displacementMap ) { uniforms.displacementMap.value = material.displacementMap; uniforms.displacementScale.value = material.displacementScale; uniforms.displacementBias.value = material.displacementBias; } uniforms.referencePosition.value.copy( material.referencePosition ); uniforms.nearDistance.value = material.nearDistance; uniforms.farDistance.value = material.farDistance; } function refreshUniformsNormal( uniforms, material ) { if ( material.bumpMap ) { uniforms.bumpMap.value = material.bumpMap; uniforms.bumpScale.value = material.bumpScale; if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1; } if ( material.normalMap ) { uniforms.normalMap.value = material.normalMap; uniforms.normalScale.value.copy( material.normalScale ); if ( material.side === BackSide ) uniforms.normalScale.value.negate(); } if ( material.displacementMap ) { uniforms.displacementMap.value = material.displacementMap; uniforms.displacementScale.value = material.displacementScale; uniforms.displacementBias.value = material.displacementBias; } } // If uniforms are marked as clean, they don't need to be loaded to the GPU. function markUniformsLightsNeedsUpdate( uniforms, value ) { uniforms.ambientLightColor.needsUpdate = value; uniforms.directionalLights.needsUpdate = value; uniforms.pointLights.needsUpdate = value; uniforms.spotLights.needsUpdate = value; uniforms.rectAreaLights.needsUpdate = value; uniforms.hemisphereLights.needsUpdate = value; } // Textures function allocTextureUnit() { var textureUnit = _usedTextureUnits; if ( textureUnit >= capabilities.maxTextures ) { console.warn( 'THREE.WebGLRenderer: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures ); } _usedTextureUnits += 1; return textureUnit; } this.allocTextureUnit = allocTextureUnit; // this.setTexture2D = setTexture2D; this.setTexture2D = ( function () { var warned = false; // backwards compatibility: peel texture.texture return function setTexture2D( texture, slot ) { if ( texture && texture.isWebGLRenderTarget ) { if ( ! warned ) { console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." ); warned = true; } texture = texture.texture; } textures.setTexture2D( texture, slot ); }; }() ); this.setTexture3D = ( function () { // backwards compatibility: peel texture.texture return function setTexture3D( texture, slot ) { textures.setTexture3D( texture, slot ); }; }() ); this.setTexture = ( function () { var warned = false; return function setTexture( texture, slot ) { if ( ! warned ) { console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." ); warned = true; } textures.setTexture2D( texture, slot ); }; }() ); this.setTextureCube = ( function () { var warned = false; return function setTextureCube( texture, slot ) { // backwards compatibility: peel texture.texture if ( texture && texture.isWebGLRenderTargetCube ) { if ( ! warned ) { console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." ); warned = true; } texture = texture.texture; } // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture // TODO: unify these code paths if ( ( texture && texture.isCubeTexture ) || ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) { // CompressedTexture can have Array in image :/ // this function alone should take care of cube textures textures.setTextureCube( texture, slot ); } else { // assumed: texture property of THREE.WebGLRenderTargetCube textures.setTextureCubeDynamic( texture, slot ); } }; }() ); // this.setFramebuffer = function ( value ) { _framebuffer = value; }; this.getRenderTarget = function () { return _currentRenderTarget; }; this.setRenderTarget = function ( renderTarget ) { _currentRenderTarget = renderTarget; if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) { textures.setupRenderTarget( renderTarget ); } var framebuffer = _framebuffer; var isCube = false; if ( renderTarget ) { var __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer; if ( renderTarget.isWebGLRenderTargetCube ) { framebuffer = __webglFramebuffer[ renderTarget.activeCubeFace ]; isCube = true; } else { framebuffer = __webglFramebuffer; } _currentViewport.copy( renderTarget.viewport ); _currentScissor.copy( renderTarget.scissor ); _currentScissorTest = renderTarget.scissorTest; } else { _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ); _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ); _currentScissorTest = _scissorTest; } if ( _currentFramebuffer !== framebuffer ) { _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); _currentFramebuffer = framebuffer; } state.viewport( _currentViewport ); state.scissor( _currentScissor ); state.setScissorTest( _currentScissorTest ); if ( isCube ) { var textureProperties = properties.get( renderTarget.texture ); _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel ); } }; this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) { if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) { console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); return; } var framebuffer = properties.get( renderTarget ).__webglFramebuffer; if ( framebuffer ) { var restore = false; if ( framebuffer !== _currentFramebuffer ) { _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); restore = true; } try { var texture = renderTarget.texture; var textureFormat = texture.format; var textureType = texture.type; if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) { console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' ); return; } if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513) ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox ! ( textureType === HalfFloatType && ( capabilities.isWebGL2 ? extensions.get( 'EXT_color_buffer_float' ) : extensions.get( 'EXT_color_buffer_half_float' ) ) ) ) { console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' ); return; } if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) { // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) { _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer ); } } else { console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' ); } } finally { if ( restore ) { _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer ); } } } }; this.copyFramebufferToTexture = function ( position, texture, level ) { var width = texture.image.width; var height = texture.image.height; var glFormat = utils.convert( texture.format ); this.setTexture2D( texture, 0 ); _gl.copyTexImage2D( _gl.TEXTURE_2D, level || 0, glFormat, position.x, position.y, width, height, 0 ); }; this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level ) { var width = srcTexture.image.width; var height = srcTexture.image.height; var glFormat = utils.convert( dstTexture.format ); var glType = utils.convert( dstTexture.type ); this.setTexture2D( dstTexture, 0 ); if ( srcTexture.isDataTexture ) { _gl.texSubImage2D( _gl.TEXTURE_2D, level || 0, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data ); } else { _gl.texSubImage2D( _gl.TEXTURE_2D, level || 0, position.x, position.y, glFormat, glType, srcTexture.image ); } }; } export { WebGLRenderer };
mit
c1t1zen/Neveshtar
vendor/yangqi/htmldom/src/Yangqi/Htmldom/HtmldomServiceProvider.php
684
<?php namespace Yangqi\Htmldom; use Illuminate\Support\ServiceProvider; class HtmldomServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->package('yangqi/htmldom'); } /** * Register the service provider. * * @return void */ public function register() { $this->app->bind('htmldom', function() { return new Htmldom; }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array(); } }
mit
phillbaker/analytics-js-rails
spec/rails-app-3.2.14/config/environments/development.rb
1285
RailsApp::Application.configure do # Settings specified here will take precedence over those in config/application.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false # Print deprecation notices to the Rails logger config.active_support.deprecation = :log # Only use best-standards-support built into browsers config.action_dispatch.best_standards_support = :builtin # Raise exception on mass assignment protection for Active Record models # config.active_record.mass_assignment_sanitizer = :strict # Log the query plan for queries taking more than this (works # with SQLite, MySQL, and PostgreSQL) # config.active_record.auto_explain_threshold_in_seconds = 0.5 # Do not compress assets config.assets.compress = false # Expands the lines which load the assets config.assets.debug = true end
mit
xzf158/yeoman-generator-ut-ss
node_modules/yeoman-generator/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/lib/pseudos.js
8215
/* pseudo selectors --- they are available in two forms: * filters called when the selector is compiled and return a function that needs to return next() * pseudos get called on execution they need to return a boolean */ var DomUtils = require("domutils"), isTag = DomUtils.isTag, getText = DomUtils.getText, getParent = DomUtils.getParent, getChildren = DomUtils.getChildren, getSiblings = DomUtils.getSiblings, hasAttrib = DomUtils.hasAttrib, getName = DomUtils.getName, getAttribute= DomUtils.getAttributeValue, getNCheck = require("nth-check"), checkAttrib = require("./attributes.js").rules.equals, BaseFuncs = require("boolbase"), trueFunc = BaseFuncs.trueFunc, falseFunc = BaseFuncs.falseFunc; //helper methods function getFirstElement(elems){ for(var i = 0; elems && i < elems.length; i++){ if(isTag(elems[i])) return elems[i]; } } function getAttribFunc(name, value){ var data = {name: name, value: value}; return function attribFunc(next){ return checkAttrib(next, data); }; } function getChildFunc(next){ return function(elem){ return !!getParent(elem) && next(elem); }; } var filters = { contains: function(next, text){ if( (text.charAt(0) === "\"" || text.charAt(0) === "'") && text.charAt(0) === text.substr(-1) ){ text = text.slice(1, -1); } return function contains(elem){ return getText(elem).indexOf(text) >= 0 && next(elem); }; }, //location specific methods //first- and last-child methods return as soon as they find another element "first-child": function(next){ return function firstChild(elem){ return getFirstElement(getSiblings(elem)) === elem && next(elem); }; }, "last-child": function(next){ return function lastChild(elem){ var siblings = getSiblings(elem); for(var i = siblings.length - 1; i >= 0; i--){ if(siblings[i] === elem) return next(elem); if(isTag(siblings[i])) break; } return false; }; }, "first-of-type": function(next){ return function firstOfType(elem){ var siblings = getSiblings(elem); for(var i = 0; i < siblings.length; i++){ if(isTag(siblings[i])){ if(siblings[i] === elem) return next(elem); if(getName(siblings[i]) === getName(elem)) break; } } return false; }; }, "last-of-type": function(next){ return function lastOfType(elem){ var siblings = getSiblings(elem); for(var i = siblings.length-1; i >= 0; i--){ if(isTag(siblings[i])){ if(siblings[i] === elem) return next(elem); if(getName(siblings[i]) === getName(elem)) break; } } return false; }; }, "only-of-type": function(next){ return function onlyOfType(elem){ var siblings = getSiblings(elem); for(var i = 0, j = siblings.length; i < j; i++){ if(isTag(siblings[i])){ if(siblings[i] === elem) continue; if(getName(siblings[i]) === getName(elem)) return false; } } return next(elem); }; }, "only-child": function(next){ return function onlyChild(elem){ var siblings = getSiblings(elem); for(var i = 0; i < siblings.length; i++){ if(isTag(siblings[i]) && siblings[i] !== elem) return false; } return next(elem); }; }, "nth-child": function(next, rule){ var func = getNCheck(rule); if(func === falseFunc) return func; if(func === trueFunc) return getChildFunc(next); return function nthChild(elem){ var siblings = getSiblings(elem); for(var i = 0, pos = 0; i < siblings.length; i++){ if(isTag(siblings[i])){ if(siblings[i] === elem) break; else pos++; } } return func(pos) && next(elem); }; }, "nth-last-child": function(next, rule){ var func = getNCheck(rule); if(func === falseFunc) return func; if(func === trueFunc) return getChildFunc(next); return function nthLastChild(elem){ var siblings = getSiblings(elem); for(var pos = 0, i = siblings.length - 1; i >= 0; i--){ if(isTag(siblings[i])){ if(siblings[i] === elem) break; else pos++; } } return func(pos) && next(elem); }; }, "nth-of-type": function(next, rule){ var func = getNCheck(rule); if(func === falseFunc) return func; if(func === trueFunc) return getChildFunc(next); return function nthOfType(elem){ var siblings = getSiblings(elem); for(var pos = 0, i = 0; i < siblings.length; i++){ if(isTag(siblings[i])){ if(siblings[i] === elem) break; if(getName(siblings[i]) === getName(elem)) pos++; } } return func(pos) && next(elem); }; }, "nth-last-of-type": function(next, rule){ var func = getNCheck(rule); if(func === falseFunc) return func; if(func === trueFunc) return getChildFunc(next); return function nthLastOfType(elem){ var siblings = getSiblings(elem); for(var pos = 0, i = siblings.length - 1; i >= 0; i--){ if(siblings[i] === elem) break; if(getName(siblings[i]) === getName(elem)) pos++; } return func(pos) && next(elem); }; }, //jQuery extensions (others follow as pseudos) checkbox: getAttribFunc("type", "checkbox"), file: getAttribFunc("type", "file"), password: getAttribFunc("type", "password"), radio: getAttribFunc("type", "radio"), reset: getAttribFunc("type", "reset"), image: getAttribFunc("type", "image"), submit: getAttribFunc("type", "submit") }; //while filters are precompiled, pseudos get called when they are needed var pseudos = { root: function(elem){ return !getParent(elem); }, empty: function(elem){ return !getChildren(elem).some(function(elem){ return isTag(elem) || elem.type === "text"; }); }, //forms //to consider: :target, :enabled selected: function(elem){ if(hasAttrib(elem, "selected")) return true; else if(getName(elem) !== "option") return false; //the first <option> in a <select> is also selected var parent = getParent(elem); if(!parent || getName(parent) !== "select") return false; var siblings = getChildren(parent), sawElem = false; for(var i = 0; i < siblings.length; i++){ if(isTag(siblings[i])){ if(siblings[i] === elem){ sawElem = true; } else if(!sawElem){ return false; } else if(hasAttrib(siblings[i], "selected")){ return false; } } } return sawElem; }, disabled: function(elem){ return hasAttrib(elem, "disabled"); }, enabled: function(elem){ return !hasAttrib(elem, "disabled"); }, checked: function(elem){ return hasAttrib(elem, "checked") || pseudos.selected(elem); }, //jQuery extensions //:parent is the inverse of :empty parent: function(elem){ return !pseudos.empty(elem); }, header: function(elem){ var name = getName(elem); return name === "h1" || name === "h2" || name === "h3" || name === "h4" || name === "h5" || name === "h6"; }, button: function(elem){ var name = getName(elem); return name === "button" || name === "input" && getAttribute(elem, "type") === "button"; }, input: function(elem){ var name = getName(elem); return name === "input" || name === "textarea" || name === "select" || name === "button"; }, text: function(elem){ var attr; return getName(elem) === "input" && ( !(attr = getAttribute(elem, "type")) || attr.toLowerCase() === "text" ); } }; function verifyArgs(func, name, subselect){ if(subselect === null){ if(func.length > 1){ throw new SyntaxError("pseudo-selector :" + name + " requires an argument"); } } else { if(func.length === 1){ throw new SyntaxError("pseudo-selector :" + name + " doesn't have any arguments"); } } } module.exports = { compile: function(next, data){ var name = data.name, subselect = data.data; if(typeof filters[name] === "function"){ verifyArgs(filters[name], name, subselect); return filters[name](next, subselect); } else if(typeof pseudos[name] === "function"){ var func = pseudos[name]; verifyArgs(func, name, subselect); return function pseudoArgs(elem){ return func(elem, subselect) && next(elem); }; } else { throw new SyntaxError("unmatched pseudo-class :" + name); } }, filters: filters, pseudos: pseudos };
mit
planetargon/active_merchant
test/unit/gateways/authorize_net_cim_test.rb
47734
require 'test_helper' class AuthorizeNetCimTest < Test::Unit::TestCase include CommStub def setup @gateway = AuthorizeNetCimGateway.new( login: 'X', password: 'Y' ) @amount = 100 @credit_card = credit_card @address = address @customer_profile_id = '3187' @customer_payment_profile_id = '7813' @customer_address_id = '4321' @payment = { credit_card: @credit_card } @profile = { merchant_customer_id: 'Up to 20 chars', # Optional description: 'Up to 255 Characters', # Optional email: 'Up to 255 Characters', # Optional payment_profiles: { # Optional customer_type: 'individual or business', # Optional bill_to: @address, payment: @payment }, ship_to_list: { first_name: 'John', last_name: 'Doe', company: 'Widgets, Inc', address1: '1234 Fake Street', city: 'Anytown', state: 'MD', zip: '12345', country: 'USA', phone_number: '(123)123-1234', # Optional - Up to 25 digits (no letters) fax_number: '(123)123-1234' # Optional - Up to 25 digits (no letters) } } @options = { ref_id: '1234', # Optional profile: @profile } end def test_expdate_formatting assert_equal '2009-09', @gateway.send(:expdate, credit_card('4111111111111111', month: '9', year: '2009')) assert_equal '2013-11', @gateway.send(:expdate, credit_card('4111111111111111', month: '11', year: '2013')) assert_equal 'XXXX', @gateway.send(:expdate, credit_card('XXXX1234', month: nil, year: nil)) end def test_should_create_customer_profile_request @gateway.expects(:ssl_post).returns(successful_create_customer_profile_response) assert response = @gateway.create_customer_profile(@options) assert_instance_of Response, response assert_success response assert_equal @customer_profile_id, response.authorization assert_equal 'Successful.', response.message end def test_should_create_customer_payment_profile_request @gateway.expects(:ssl_post).returns(successful_create_customer_payment_profile_response) assert response = @gateway.create_customer_payment_profile( customer_profile_id: @customer_profile_id, payment_profile: { customer_type: 'individual', bill_to: @address, payment: @payment }, validation_mode: :test ) assert_instance_of Response, response assert_success response assert_equal @customer_payment_profile_id, response.params['customer_payment_profile_id'] assert_equal 'This output is only present if the ValidationMode input parameter is passed with a value of testMode or liveMode', response.params['validation_direct_response'] end def test_should_create_customer_shipping_address_request @gateway.expects(:ssl_post).returns(successful_create_customer_shipping_address_response) assert response = @gateway.create_customer_shipping_address( customer_profile_id: @customer_profile_id, address: { first_name: 'John', last_name: 'Doe', company: 'Widgets, Inc', address1: '1234 Fake Street', city: 'Anytown', state: 'MD', country: 'USA', phone_number: '(123)123-1234', fax_number: '(123)123-1234' } ) assert_instance_of Response, response assert_success response assert_nil response.authorization assert_equal 'customerAddressId', response.params['customer_address_id'] end def test_should_create_customer_profile_transaction_auth_only_and_then_prior_auth_capture_requests @gateway.expects(:ssl_post).returns(successful_create_customer_profile_transaction_response(:auth_only)) assert response = @gateway.create_customer_profile_transaction( transaction: { customer_profile_id: @customer_profile_id, customer_payment_profile_id: @customer_payment_profile_id, type: :auth_only, amount: @amount } ) assert_instance_of Response, response assert_success response assert_equal response.authorization, response.params['direct_response']['transaction_id'] assert_equal 'This transaction has been approved.', response.params['direct_response']['message'] assert_equal 'auth_only', response.params['direct_response']['transaction_type'] assert_equal 'Gw4NGI', response.params['direct_response']['approval_code'] assert_equal '508223659', trans_id = response.params['direct_response']['transaction_id'] assert_equal '1', response.params['direct_response']['response_code'] assert_equal '1', response.params['direct_response']['response_subcode'] assert_equal '1', response.params['direct_response']['response_reason_code'] assert_equal 'Y', response.params['direct_response']['avs_response'] assert_equal '', response.params['direct_response']['invoice_number'] assert_equal '', response.params['direct_response']['order_description'] assert_equal '100.00', response.params['direct_response']['amount'] assert_equal 'CC', response.params['direct_response']['method'] assert_equal 'Up to 20 chars', response.params['direct_response']['customer_id'] assert_equal '', response.params['direct_response']['first_name'] assert_equal '', response.params['direct_response']['last_name'] assert_equal '', response.params['direct_response']['company'] assert_equal '', response.params['direct_response']['address'] assert_equal '', response.params['direct_response']['city'] assert_equal '', response.params['direct_response']['state'] assert_equal '', response.params['direct_response']['zip_code'] assert_equal '', response.params['direct_response']['country'] assert_equal '', response.params['direct_response']['phone'] assert_equal '', response.params['direct_response']['fax'] assert_equal 'Up to 255 Characters', response.params['direct_response']['email_address'] assert_equal '', response.params['direct_response']['ship_to_first_name'] assert_equal '', response.params['direct_response']['ship_to_last_name'] assert_equal '', response.params['direct_response']['ship_to_company'] assert_equal '', response.params['direct_response']['ship_to_address'] assert_equal '', response.params['direct_response']['ship_to_city'] assert_equal '', response.params['direct_response']['ship_to_state'] assert_equal '', response.params['direct_response']['ship_to_zip_code'] assert_equal '', response.params['direct_response']['ship_to_country'] assert_equal '', response.params['direct_response']['tax'] assert_equal '', response.params['direct_response']['duty'] assert_equal '', response.params['direct_response']['freight'] assert_equal '', response.params['direct_response']['tax_exempt'] assert_equal '', response.params['direct_response']['purchase_order_number'] assert_equal '6E5334C13C78EA078173565FD67318E4', response.params['direct_response']['md5_hash'] assert_equal '', response.params['direct_response']['card_code'] assert_equal '2', response.params['direct_response']['cardholder_authentication_verification_response'] assert_equal response.authorization, trans_id @gateway.expects(:ssl_post).returns(successful_create_customer_profile_transaction_response(:prior_auth_capture)) assert response = @gateway.create_customer_profile_transaction( transaction: { customer_profile_id: @customer_profile_id, customer_payment_profile_id: @customer_payment_profile_id, type: :prior_auth_capture, amount: @amount, trans_id: trans_id } ) assert_instance_of Response, response assert_success response assert_equal 'This transaction has been approved.', response.params['direct_response']['message'] end # NOTE - do not pattern your production application after this (refer to # test_should_create_customer_profile_transaction_auth_only_and_then_prior_auth_capture_requests # instead as the correct way to do an auth then capture). capture_only # "is used to complete a previously authorized transaction that was not # originally submitted through the payment gateway or that required voice # authorization" and can in some situations perform an auth_capture leaking # the original authorization. def test_should_create_customer_profile_transaction_auth_only_and_then_capture_only_requests @gateway.expects(:ssl_post).returns(successful_create_customer_profile_transaction_response(:auth_only)) assert response = @gateway.create_customer_profile_transaction( transaction: { customer_profile_id: @customer_profile_id, customer_payment_profile_id: @customer_payment_profile_id, type: :auth_only, amount: @amount } ) assert_instance_of Response, response assert_success response assert_equal response.authorization, response.params['direct_response']['transaction_id'] assert_equal 'This transaction has been approved.', response.params['direct_response']['message'] assert_equal 'auth_only', response.params['direct_response']['transaction_type'] assert_equal 'Gw4NGI', approval_code = response.params['direct_response']['approval_code'] @gateway.expects(:ssl_post).returns(successful_create_customer_profile_transaction_response(:capture_only)) assert response = @gateway.create_customer_profile_transaction( transaction: { customer_profile_id: @customer_profile_id, customer_payment_profile_id: @customer_payment_profile_id, type: :capture_only, amount: @amount, approval_code: approval_code } ) assert_instance_of Response, response assert_success response assert_equal 'This transaction has been approved.', response.params['direct_response']['message'] end def test_should_create_customer_profile_transaction_auth_capture_request @gateway.expects(:ssl_post).returns(successful_create_customer_profile_transaction_response(:auth_capture)) assert response = @gateway.create_customer_profile_transaction( transaction: { customer_profile_id: @customer_profile_id, customer_payment_profile_id: @customer_payment_profile_id, type: :auth_capture, order: { invoice_number: '1234', description: 'Test Order Description', purchase_order_number: '4321' }, amount: @amount, card_code: '123' } ) assert_instance_of Response, response assert_success response assert_equal 'M', response.params['direct_response']['card_code'] # M => match assert_equal response.authorization, response.params['direct_response']['transaction_id'] assert_equal 'This transaction has been approved.', response.params['direct_response']['message'] end def test_should_create_customer_profile_transaction_auth_capture_request_for_version_3_1 @gateway.expects(:ssl_post).returns(successful_create_customer_profile_transaction_response(:auth_capture_version_3_1)) assert response = @gateway.create_customer_profile_transaction( transaction: { customer_profile_id: @customer_profile_id, customer_payment_profile_id: @customer_payment_profile_id, type: :auth_capture, order: { invoice_number: '1234', description: 'Test Order Description', purchase_order_number: '4321' }, amount: @amount } ) assert_instance_of Response, response assert_success response assert_equal response.authorization, response.params['direct_response']['transaction_id'] assert_equal 'This transaction has been approved.', response.params['direct_response']['message'] assert_equal 'auth_capture', response.params['direct_response']['transaction_type'] assert_equal 'CSYM0K', response.params['direct_response']['approval_code'] assert_equal '2163585627', response.params['direct_response']['transaction_id'] assert_equal '1', response.params['direct_response']['response_code'] assert_equal '1', response.params['direct_response']['response_subcode'] assert_equal '1', response.params['direct_response']['response_reason_code'] assert_equal 'Y', response.params['direct_response']['avs_response'] assert_equal '1234', response.params['direct_response']['invoice_number'] assert_equal 'Test Order Description', response.params['direct_response']['order_description'] assert_equal '100.00', response.params['direct_response']['amount'] assert_equal 'CC', response.params['direct_response']['method'] assert_equal 'Up to 20 chars', response.params['direct_response']['customer_id'] assert_equal '', response.params['direct_response']['first_name'] assert_equal '', response.params['direct_response']['last_name'] assert_equal 'Widgets Inc', response.params['direct_response']['company'] assert_equal '1234 My Street', response.params['direct_response']['address'] assert_equal 'Ottawa', response.params['direct_response']['city'] assert_equal 'ON', response.params['direct_response']['state'] assert_equal 'K1C2N6', response.params['direct_response']['zip_code'] assert_equal 'CA', response.params['direct_response']['country'] assert_equal '', response.params['direct_response']['phone'] assert_equal '', response.params['direct_response']['fax'] assert_equal 'Up to 255 Characters', response.params['direct_response']['email_address'] assert_equal '', response.params['direct_response']['ship_to_first_name'] assert_equal '', response.params['direct_response']['ship_to_last_name'] assert_equal '', response.params['direct_response']['ship_to_company'] assert_equal '', response.params['direct_response']['ship_to_address'] assert_equal '', response.params['direct_response']['ship_to_city'] assert_equal '', response.params['direct_response']['ship_to_state'] assert_equal '', response.params['direct_response']['ship_to_zip_code'] assert_equal '', response.params['direct_response']['ship_to_country'] assert_equal '', response.params['direct_response']['tax'] assert_equal '', response.params['direct_response']['duty'] assert_equal '', response.params['direct_response']['freight'] assert_equal '', response.params['direct_response']['tax_exempt'] assert_equal '4321', response.params['direct_response']['purchase_order_number'] assert_equal '02DFBD7934AD862AB16688D44F045D31', response.params['direct_response']['md5_hash'] assert_equal '', response.params['direct_response']['card_code'] assert_equal '2', response.params['direct_response']['cardholder_authentication_verification_response'] assert_equal 'XXXX4242', response.params['direct_response']['account_number'] assert_equal 'Visa', response.params['direct_response']['card_type'] assert_equal '', response.params['direct_response']['split_tender_id'] assert_equal '', response.params['direct_response']['requested_amount'] assert_equal '', response.params['direct_response']['balance_on_card'] end def test_should_delete_customer_profile_request @gateway.expects(:ssl_post).returns(successful_delete_customer_profile_response) assert response = @gateway.delete_customer_profile(customer_profile_id: @customer_profile_id) assert_instance_of Response, response assert_success response assert_equal @customer_profile_id, response.authorization end def test_should_delete_customer_payment_profile_request @gateway.expects(:ssl_post).returns(successful_delete_customer_payment_profile_response) assert response = @gateway.delete_customer_payment_profile(customer_profile_id: @customer_profile_id, customer_payment_profile_id: @customer_payment_profile_id) assert_instance_of Response, response assert_success response assert_nil response.authorization end def test_should_delete_customer_shipping_address_request @gateway.expects(:ssl_post).returns(successful_delete_customer_shipping_address_response) assert response = @gateway.delete_customer_shipping_address(customer_profile_id: @customer_profile_id, customer_address_id: @customer_address_id) assert_instance_of Response, response assert_success response assert_nil response.authorization end def test_should_get_customer_profile_request @gateway.expects(:ssl_post).returns(successful_get_customer_profile_response) assert response = @gateway.get_customer_profile(customer_profile_id: @customer_profile_id) assert_instance_of Response, response assert_success response assert_equal @customer_profile_id, response.authorization end def test_should_get_customer_profile_ids_request @gateway.expects(:ssl_post).returns(successful_get_customer_profile_ids_response) assert response = @gateway.get_customer_profile_ids assert_instance_of Response, response assert_success response end def test_should_get_customer_profile_request_with_multiple_payment_profiles @gateway.expects(:ssl_post).returns(successful_get_customer_profile_response_with_multiple_payment_profiles) assert response = @gateway.get_customer_profile(customer_profile_id: @customer_profile_id) assert_instance_of Response, response assert_success response assert_equal @customer_profile_id, response.authorization assert_equal 2, response.params['profile']['payment_profiles'].size end def test_should_get_customer_payment_profile_request @gateway.expects(:ssl_post).returns(successful_get_customer_payment_profile_response) assert response = @gateway.get_customer_payment_profile( customer_profile_id: @customer_profile_id, customer_payment_profile_id: @customer_payment_profile_id, unmask_expiration_date: true ) assert_instance_of Response, response assert_success response assert_nil response.authorization assert_equal @customer_payment_profile_id, response.params['profile']['payment_profiles']['customer_payment_profile_id'] assert_equal formatted_expiration_date(@credit_card), response.params['profile']['payment_profiles']['payment']['credit_card']['expiration_date'] end def test_should_get_customer_shipping_address_request @gateway.expects(:ssl_post).returns(successful_get_customer_shipping_address_response) assert response = @gateway.get_customer_shipping_address( customer_profile_id: @customer_profile_id, customer_address_id: @customer_address_id ) assert_instance_of Response, response assert_success response assert_nil response.authorization end def test_should_update_customer_profile_request @gateway.expects(:ssl_post).returns(successful_update_customer_profile_response) assert response = @gateway.update_customer_profile( profile: { customer_profile_id: @customer_profile_id, email: 'new email address' } ) assert_instance_of Response, response assert_success response assert_equal @customer_profile_id, response.authorization end def test_should_update_customer_payment_profile_request @gateway.expects(:ssl_post).returns(successful_update_customer_payment_profile_response) assert response = @gateway.update_customer_payment_profile( customer_profile_id: @customer_profile_id, payment_profile: { customer_payment_profile_id: @customer_payment_profile_id, customer_type: 'business' } ) assert_instance_of Response, response assert_success response assert_nil response.authorization end def test_should_update_customer_payment_profile_request_with_last_four_digits last_four_credit_card = ActiveMerchant::Billing::CreditCard.new(number: '4242') # Credit card with only last four digits response = stub_comms do @gateway.update_customer_payment_profile( customer_profile_id: @customer_profile_id, payment_profile: { customer_payment_profile_id: @customer_payment_profile_id, bill_to: address(address1: '345 Avenue B', address2: 'Apt 101'), payment: { credit_card: last_four_credit_card } } ) end.check_request do |endpoint, data, headers| assert_match %r{<cardNumber>XXXX4242</cardNumber>}, data end.respond_with(successful_update_customer_payment_profile_response) assert_instance_of Response, response assert_success response assert_nil response.authorization end def test_should_update_customer_shipping_address_request @gateway.expects(:ssl_post).returns(successful_update_customer_shipping_address_response) assert response = @gateway.update_customer_shipping_address( customer_profile_id: @customer_profile_id, address: { customer_address_id: @customer_address_id, city: 'New City' } ) assert_instance_of Response, response assert_success response assert_nil response.authorization end def test_should_validate_customer_payment_profile_request @gateway.expects(:ssl_post).returns(successful_validate_customer_payment_profile_response) assert response = @gateway.validate_customer_payment_profile( customer_profile_id: @customer_profile_id, customer_payment_profile_id: @customer_payment_profile_id, customer_address_id: @customer_address_id, validation_mode: :live ) assert_instance_of Response, response assert_success response assert_equal response.authorization, response.params['direct_response']['transaction_id'] assert_equal 'This transaction has been approved.', response.params['direct_response']['message'] end def test_should_create_customer_profile_transaction_auth_capture_and_then_void_request response = get_and_validate_auth_capture_response @gateway.expects(:ssl_post).returns(successful_create_customer_profile_transaction_response(:void)) assert response = @gateway.create_customer_profile_transaction( transaction: { type: :void, trans_id: response.params['direct_response']['transaction_id'] } ) assert_instance_of Response, response assert_success response assert_equal response.authorization, response.params['direct_response']['transaction_id'] assert_equal 'This transaction has been approved.', response.params['direct_response']['message'] return response end def test_should_create_customer_profile_transaction_auth_capture_and_then_refund_using_profile_ids_request response = get_and_validate_auth_capture_response @gateway.expects(:ssl_post).returns(unsuccessful_create_customer_profile_transaction_response(:refund)) assert response = @gateway.create_customer_profile_transaction( transaction: { type: :refund, amount: 1, customer_profile_id: @customer_profile_id, customer_payment_profile_id: @customer_payment_profile_id, trans_id: response.params['direct_response']['transaction_id'] } ) assert_instance_of Response, response # You can't test refunds in TEST MODE. If you authorize or capture a transaction, and the transaction is not yet settled by the payment gateway, you cannot issue a refund. You get an error message saying "The referenced transaction does not meet the criteria for issuing a credit.". # more on this http://help.ablecommerce.com/mergedProjects/ablecommerce7/orders/payments/entering_payments.htm and # http://www.modernbill.com/support/manual/old/v4/adminhelp/english/Configuration/Payment_Settings/Gateway_API/AuthorizeNet/Module_Authorize.net.htm assert_failure response assert_equal 'The referenced transaction does not meet the criteria for issuing a credit.', response.params['direct_response']['message'] assert_equal 'The transaction was unsuccessful.', response.message assert_equal 'E00027', response.error_code return response end def test_should_create_customer_profile_transaction_auth_capture_and_then_refund_using_masked_credit_card_request response = get_and_validate_auth_capture_response @gateway.expects(:ssl_post).returns(unsuccessful_create_customer_profile_transaction_response(:refund)) assert response = @gateway.create_customer_profile_transaction( transaction: { type: :refund, amount: 1, customer_profile_id: @customer_profile_id, customer_payment_profile_id: @customer_payment_profile_id, trans_id: response.params['direct_response']['transaction_id'] } ) assert_instance_of Response, response # You can't test refunds in TEST MODE. If you authorize or capture a transaction, and the transaction is not yet settled by the payment gateway, you cannot issue a refund. You get an error message saying "The referenced transaction does not meet the criteria for issuing a credit.". # more on this http://help.ablecommerce.com/mergedProjects/ablecommerce7/orders/payments/entering_payments.htm and # http://www.modernbill.com/support/manual/old/v4/adminhelp/english/Configuration/Payment_Settings/Gateway_API/AuthorizeNet/Module_Authorize.net.htm assert_failure response assert_equal 'The referenced transaction does not meet the criteria for issuing a credit.', response.params['direct_response']['message'] return response end # TODO - implement this # def test_should_create_customer_profile_transaction_auth_capture_and_then_refund_using_masked_electronic_checking_info_request # response = get_and_validate_auth_capture_response # # @gateway.expects(:ssl_post).returns(successful_create_customer_profile_transaction_response(:void)) # assert response = @gateway.create_customer_profile_transaction( # :transaction => { # :type => :void, # :trans_id => response.params['direct_response']['transaction_id'] # } # ) # assert_instance_of Response, response # assert_success response # assert_nil response.authorization # assert_equal 'This transaction has been approved.', response.params['direct_response']['message'] # return response # end def test_should_create_customer_profile_transaction_for_void_request @gateway.expects(:ssl_post).returns(successful_create_customer_profile_transaction_response(:void)) assert response = @gateway.create_customer_profile_transaction_for_void( transaction: { trans_id: 1 } ) assert_instance_of Response, response assert_success response assert_equal response.authorization, response.params['direct_response']['transaction_id'] assert_equal 'This transaction has been approved.', response.params['direct_response']['message'] end def test_should_create_customer_profile_transaction_for_refund_request @gateway.expects(:ssl_post).returns(successful_create_customer_profile_transaction_response(:refund)) assert response = @gateway.create_customer_profile_transaction_for_refund( transaction: { trans_id: 1, amount: '1.00', credit_card_number_masked: 'XXXX1234' } ) assert_instance_of Response, response assert_success response assert_equal response.authorization, response.params['direct_response']['transaction_id'] assert_equal 'This transaction has been approved.', response.params['direct_response']['message'] end def test_should_create_customer_profile_transaction_passing_recurring_flag response = stub_comms do @gateway.create_customer_profile_transaction( transaction: { customer_profile_id: @customer_profile_id, customer_payment_profile_id: @customer_payment_profile_id, type: :auth_capture, order: { invoice_number: '1234', description: 'Test Order Description', purchase_order_number: '4321' }, amount: @amount, card_code: '123', recurring_billing: true } ) end.check_request do |endpoint, data, headers| assert_match %r{<recurringBilling>true</recurringBilling>}, data end.respond_with(successful_create_customer_profile_transaction_response(:auth_capture)) assert_instance_of Response, response assert_success response assert_equal 'M', response.params['direct_response']['card_code'] # M => match assert_equal response.authorization, response.params['direct_response']['transaction_id'] assert_equal 'This transaction has been approved.', response.params['direct_response']['message'] end def test_full_or_masked_card_number assert_equal nil, @gateway.send(:full_or_masked_card_number, nil) assert_equal '', @gateway.send(:full_or_masked_card_number, '') assert_equal '4242424242424242', @gateway.send(:full_or_masked_card_number, @credit_card.number) assert_equal 'XXXX1234', @gateway.send(:full_or_masked_card_number, '1234') end def test_multiple_errors_when_creating_customer_profile @gateway.expects(:ssl_post).returns(unsuccessful_create_customer_profile_transaction_response_with_multiple_errors(:refund)) assert response = @gateway.create_customer_profile_transaction( transaction: { type: :refund, amount: 1, customer_profile_id: @customer_profile_id, customer_payment_profile_id: @customer_payment_profile_id, trans_id: 1 } ) assert_equal 'The transaction was unsuccessful.', response.message assert_equal 'E00027', response.error_code end private def get_auth_only_response @gateway.expects(:ssl_post).returns(successful_create_customer_profile_transaction_response(:auth_only)) assert response = @gateway.create_customer_profile_transaction( transaction: { customer_profile_id: @customer_profile_id, customer_payment_profile_id: @customer_payment_profile_id, type: :auth_only, amount: @amount } ) assert_instance_of Response, response assert_success response assert_nil response.authorization assert_equal 'This transaction has been approved.', response.params['direct_response']['message'] assert_equal 'auth_only', response.params['direct_response']['transaction_type'] assert_equal 'Gw4NGI', response.params['direct_response']['approval_code'] return response end def get_and_validate_auth_capture_response @gateway.expects(:ssl_post).returns(successful_create_customer_profile_transaction_response(:auth_capture)) assert response = @gateway.create_customer_profile_transaction( transaction: { customer_profile_id: @customer_profile_id, customer_payment_profile_id: @customer_payment_profile_id, type: :auth_capture, order: { invoice_number: '1234', description: 'Test Order Description', purchase_order_number: '4321' }, amount: @amount } ) assert_instance_of Response, response assert_success response assert_equal response.authorization, response.params['direct_response']['transaction_id'] assert_equal 'This transaction has been approved.', response.params['direct_response']['message'] return response end def successful_create_customer_profile_response <<-XML <?xml version="1.0" encoding="utf-8" ?> <createCustomerProfileResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"> <refId>refid1</refId> <messages> <resultCode>Ok</resultCode> <message> <code>I00001</code> <text>Successful.</text> </message> </messages> <customerProfileId>#{@customer_profile_id}</customerProfileId> </createCustomerProfileResponse> XML end def successful_create_customer_payment_profile_response <<-XML <?xml version="1.0" encoding="utf-8" ?> <createCustomerPaymentProfileResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"> <refId>refid1</refId> <messages> <resultCode>Ok</resultCode> <message> <code>I00001</code> <text>Successful.</text> </message> </messages> <customerPaymentProfileId>#{@customer_payment_profile_id}</customerPaymentProfileId> <validationDirectResponse>This output is only present if the ValidationMode input parameter is passed with a value of testMode or liveMode</validationDirectResponse> </createCustomerPaymentProfileResponse> XML end def successful_create_customer_shipping_address_response <<-XML <?xml version="1.0" encoding="utf-8" ?> <createCustomerShippingAddressResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"> <refId>refid1</refId> <messages> <resultCode>Ok</resultCode> <message> <code>I00001</code> <text>Successful.</text> </message> </messages> <customerAddressId>customerAddressId</customerAddressId> </createCustomerShippingAddressResponse> XML end def successful_delete_customer_profile_response <<-XML <?xml version="1.0" encoding="utf-8" ?> <deleteCustomerProfileResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"> <refId>refid1</refId> <messages> <resultCode>Ok</resultCode> <message> <code>I00001</code> <text>Successful.</text> </message> </messages> <customerProfileId>#{@customer_profile_id}</customerProfileId> </deleteCustomerProfileResponse> XML end def successful_delete_customer_payment_profile_response <<-XML <?xml version="1.0" encoding="utf-8" ?> <deleteCustomerPaymentProfileResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"> <refId>refid1</refId> <messages> <resultCode>Ok</resultCode> <message> <code>I00001</code> <text>Successful.</text> </message> </messages> </deleteCustomerPaymentProfileResponse> XML end def successful_delete_customer_shipping_address_response <<-XML <?xml version="1.0" encoding="utf-8" ?> <deleteCustomerShippingAddressResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"> <refId>refid1</refId> <messages> <resultCode>Ok</resultCode> <message> <code>I00001</code> <text>Successful.</text> </message> </messages> </deleteCustomerShippingAddressResponse> XML end def successful_get_customer_profile_response <<-XML <?xml version="1.0" encoding="utf-8" ?> <getCustomerProfileResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"> <refId>refid1</refId> <messages> <resultCode>Ok</resultCode> <message> <code>I00001</code> <text>Successful.</text> </message> </messages> <customerProfileId>#{@customer_profile_id}</customerProfileId> <profile> <paymentProfiles> <customerPaymentProfileId>123456</customerPaymentProfileId> <payment> <creditCard> <cardNumber>#{@credit_card.number}</cardNumber> <expirationDate>#{@gateway.send(:expdate, @credit_card)}</expirationDate> </creditCard> </payment> </paymentProfiles> </profile> </getCustomerProfileResponse> XML end def successful_get_customer_profile_ids_response <<-XML <?xml version="1.0" encoding="utf-8"?> <getCustomerProfileIdsResponse xmlns="AnetApi/xml/v1/schema/ AnetApiSchema.xsd"> <messages> <resultCode>Ok</resultCode> <message> <code>I00001</code> <text>Successful.</text> </message> </messages> <ids> <numericString>10000</numericString> <numericString>10001</numericString> <numericString>10002</numericString> </ids> </getCustomerProfileIdsResponse> XML end def successful_get_customer_profile_response_with_multiple_payment_profiles <<-XML <?xml version="1.0" encoding="utf-8"?> <getCustomerProfileResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"> <messages> <resultCode>Ok</resultCode> <message> <code>I00001</code> <text>Successful.</text> </message> </messages> <profile> <merchantCustomerId>Up to 20 chars</merchantCustomerId> <description>Up to 255 Characters</description> <email>Up to 255 Characters</email> <customerProfileId>#{@customer_profile_id}</customerProfileId> <paymentProfiles> <customerPaymentProfileId>1000</customerPaymentProfileId> <payment> <creditCard> <cardNumber>#{@credit_card.number}</cardNumber> <expirationDate>#{@gateway.send(:expdate, @credit_card)}</expirationDate> </creditCard> </payment> </paymentProfiles> <paymentProfiles> <customerType>individual</customerType> <customerPaymentProfileId>1001</customerPaymentProfileId> <payment> <creditCard> <cardNumber>XXXX1234</cardNumber> <expirationDate>XXXX</expirationDate> </creditCard> </payment> </paymentProfiles> </profile> </getCustomerProfileResponse> XML end def successful_get_customer_payment_profile_response <<-XML <?xml version="1.0" encoding="utf-8" ?> <getCustomerPaymentProfileResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"> <refId>refid1</refId> <messages> <resultCode>Ok</resultCode> <message> <code>I00001</code> <text>Successful.</text> </message> </messages> <profile> <paymentProfiles> <customerPaymentProfileId>#{@customer_payment_profile_id}</customerPaymentProfileId> <payment> <creditCard> <cardNumber>#{@credit_card.number}</cardNumber> <expirationDate>#{@gateway.send(:expdate, @credit_card)}</expirationDate> </creditCard> </payment> </paymentProfiles> </profile> </getCustomerPaymentProfileResponse> XML end def successful_get_customer_shipping_address_response <<-XML <?xml version="1.0" encoding="utf-8" ?> <getCustomerShippingAddressResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"> <refId>refid1</refId> <messages> <resultCode>Ok</resultCode> <message> <code>I00001</code> <text>Successful.</text> </message> </messages> <address> <customerAddressId>#{@customer_address_id}</customerAddressId> </address> </getCustomerShippingAddressResponse> XML end def successful_update_customer_profile_response <<-XML <?xml version="1.0" encoding="utf-8" ?> <updateCustomerProfileResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"> <refId>refid1</refId> <messages> <resultCode>Ok</resultCode> <message> <code>I00001</code> <text>Successful.</text> </message> </messages> <customerProfileId>#{@customer_profile_id}</customerProfileId> </updateCustomerProfileResponse> XML end def successful_update_customer_payment_profile_response <<-XML <?xml version="1.0" encoding="utf-8" ?> <updateCustomerPaymentProfileResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"> <refId>refid1</refId> <messages> <resultCode>Ok</resultCode> <message> <code>I00001</code> <text>Successful.</text> </message> </messages> </updateCustomerPaymentProfileResponse> XML end def successful_update_customer_shipping_address_response <<-XML <?xml version="1.0" encoding="utf-8" ?> <updateCustomerShippingAddressResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"> <refId>refid1</refId> <messages> <resultCode>Ok</resultCode> <message> <code>I00001</code> <text>Successful.</text> </message> </messages> </updateCustomerShippingAddressResponse> XML end SUCCESSFUL_DIRECT_RESPONSE = { auth_only: '1,1,1,This transaction has been approved.,Gw4NGI,Y,508223659,,,100.00,CC,auth_only,Up to 20 chars,,,,,,,,,,,Up to 255 Characters,,,,,,,,,,,,,,6E5334C13C78EA078173565FD67318E4,,2,,,,,,,,,,,,,,,,,,,,,,,,,,,,', capture_only: '1,1,1,This transaction has been approved.,,Y,508223660,,,100.00,CC,capture_only,Up to 20 chars,,,,,,,,,,,Up to 255 Characters,,,,,,,,,,,,,,6E5334C13C78EA078173565FD67318E4,,2,,,,,,,,,,,,,,,,,,,,,,,,,,,,', auth_capture: '1,1,1,This transaction has been approved.,d1GENk,Y,508223661,32968c18334f16525227,Store purchase,1.00,CC,auth_capture,,Longbob,Longsen,,,,,,,,,,,,,,,,,,,,,,,269862C030129C1173727CC10B1935ED,M,2,,,,,,,,,,,,,,,,,,,,,,,,,,,,', void: '1,1,1,This transaction has been approved.,nnCMEx,P,2149222068,1245879759,,0.00,CC,void,1245879759,,,,,,,K1C2N6,,,,,,,,,,,,,,,,,,F240D65BB27ADCB8C80410B92342B22C,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,', refund: '1,1,1,This transaction has been approved.,nnCMEx,P,2149222068,1245879759,,0.00,CC,refund,1245879759,,,,,,,K1C2N6,,,,,,,,,,,,,,,,,,F240D65BB27ADCB8C80410B92342B22C,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,', prior_auth_capture: '1,1,1,This transaction has been approved.,VR0lrD,P,2149227870,1245958544,,1.00,CC,prior_auth_capture,1245958544,,,,,,,K1C2N6,,,,,,,,,,,,,,,,,,0B8BFE0A0DE6FDB69740ED20F79D04B0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,', auth_capture_version_3_1: '1,1,1,This transaction has been approved.,CSYM0K,Y,2163585627,1234,Test Order Description,100.00,CC,auth_capture,Up to 20 chars,,,Widgets Inc,1234 My Street,Ottawa,ON,K1C2N6,CA,,,Up to 255 Characters,,,,,,,,,,,,,4321,02DFBD7934AD862AB16688D44F045D31,,2,,,,,,,,,,,XXXX4242,Visa,,,,,,,,,,,,,,,,' } UNSUCCESSUL_DIRECT_RESPONSE = { refund: '3,2,54,The referenced transaction does not meet the criteria for issuing a credit.,,P,0,,,1.00,CC,credit,1245952682,,,Widgets Inc,1245952682 My Street,Ottawa,ON,K1C2N6,CA,,,bob1245952682@email.com,,,,,,,,,,,,,,207BCBBF78E85CF174C87AE286B472D2,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,447250,406104' } def successful_create_customer_profile_transaction_response(transaction_type) <<-XML <?xml version="1.0" encoding="utf-8" ?> <createCustomerProfileTransactionResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"> <refId>refid1</refId> <messages> <resultCode>Ok</resultCode> <message> <code>I00001</code> <text>Successful.</text> </message> </messages> <directResponse>#{SUCCESSFUL_DIRECT_RESPONSE[transaction_type]}</directResponse> </createCustomerProfileTransactionResponse> XML end def successful_validate_customer_payment_profile_response <<-XML <?xml version="1.0" encoding="utf-8" ?> <validateCustomerPaymentProfileResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"> <refId>refid1</refId> <messages> <resultCode>Ok</resultCode> <message> <code>I00001</code> <text>Successful.</text> </message> </messages> <directResponse>1,1,1,This transaction has been approved.,DEsVh8,Y,508276300,none,Test transaction for ValidateCustomerPaymentProfile.,0.01,CC,auth_only,Up to 20 chars,,,,,,,,,,,Up to 255 Characters,John,Doe,Widgets, Inc,1234 Fake Street,Anytown,MD,12345,USA,0.0000,0.0000,0.0000,TRUE,none,7EB3A44624C0C10FAAE47E276B48BF17,,2,,,,,,,,,,,,,,,,,,,,,,,,,,,,</directResponse> </validateCustomerPaymentProfileResponse> XML end def unsuccessful_create_customer_profile_transaction_response(transaction_type) <<-XML <?xml version="1.0" encoding="utf-8"?> <createCustomerProfileTransactionResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"> <messages> <resultCode>Error</resultCode> <message> <code>E00027</code> <text>The transaction was unsuccessful.</text> </message> </messages> <directResponse>#{UNSUCCESSUL_DIRECT_RESPONSE[transaction_type]}</directResponse> </createCustomerProfileTransactionResponse> XML end def unsuccessful_create_customer_profile_transaction_response_with_multiple_errors(transaction_type) <<-XML <?xml version="1.0" encoding="utf-8"?> <createCustomerProfileTransactionResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"> <messages> <resultCode>Error</resultCode> <message> <code>E00027</code> <text>The transaction was unsuccessful.</text> </message> <message> <code>E00001</code> <text>An error occurred during processing. Please try again.</text> </message> </messages> <directResponse>#{UNSUCCESSUL_DIRECT_RESPONSE[transaction_type]}</directResponse> </createCustomerProfileTransactionResponse> XML end end
mit
Triiistan/symfony
src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php
40995
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\Loader; use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use Symfony\Component\DependencyInjection\Loader\IniFileLoader; use Symfony\Component\Config\Loader\LoaderResolver; use Symfony\Component\Config\FileLocator; use Symfony\Component\Config\Resource\FileResource; use Symfony\Component\Config\Resource\GlobResource; use Symfony\Component\DependencyInjection\Tests\Fixtures\CaseSensitiveClass; use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype; use Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy; use Symfony\Component\ExpressionLanguage\Expression; class XmlFileLoaderTest extends TestCase { protected static $fixturesPath; public static function setUpBeforeClass() { self::$fixturesPath = realpath(__DIR__.'/../Fixtures/'); require_once self::$fixturesPath.'/includes/foo.php'; require_once self::$fixturesPath.'/includes/ProjectExtension.php'; require_once self::$fixturesPath.'/includes/ProjectWithXsdExtension.php'; } public function testLoad() { $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/ini')); try { $loader->load('foo.xml'); $this->fail('->load() throws an InvalidArgumentException if the loaded file does not exist'); } catch (\Exception $e) { $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the loaded file does not exist'); $this->assertStringStartsWith('The file "foo.xml" does not exist (in:', $e->getMessage(), '->load() throws an InvalidArgumentException if the loaded file does not exist'); } } public function testParseFile() { $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/ini')); $r = new \ReflectionObject($loader); $m = $r->getMethod('parseFileToDOM'); $m->setAccessible(true); try { $m->invoke($loader, self::$fixturesPath.'/ini/parameters.ini'); $this->fail('->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file'); $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'parameters.ini'), $e->getMessage(), '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file'); $e = $e->getPrevious(); $this->assertInstanceOf('InvalidArgumentException', $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file'); $this->assertStringStartsWith('[ERROR 4] Start tag expected, \'<\' not found (in', $e->getMessage(), '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file'); } $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/xml')); try { $m->invoke($loader, self::$fixturesPath.'/xml/nonvalid.xml'); $this->fail('->parseFileToDOM() throws an InvalidArgumentException if the loaded file does not validate the XSD'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file does not validate the XSD'); $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'nonvalid.xml'), $e->getMessage(), '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file'); $e = $e->getPrevious(); $this->assertInstanceOf('InvalidArgumentException', $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file does not validate the XSD'); $this->assertStringStartsWith('[ERROR 1845] Element \'nonvalid\': No matching global declaration available for the validation root. (in', $e->getMessage(), '->parseFileToDOM() throws an InvalidArgumentException if the loaded file does not validate the XSD'); } $xml = $m->invoke($loader, self::$fixturesPath.'/xml/services1.xml'); $this->assertInstanceOf('DOMDocument', $xml, '->parseFileToDOM() returns an SimpleXMLElement object'); } public function testLoadWithExternalEntitiesDisabled() { $disableEntities = libxml_disable_entity_loader(true); $containerBuilder = new ContainerBuilder(); $loader = new XmlFileLoader($containerBuilder, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services2.xml'); libxml_disable_entity_loader($disableEntities); $this->assertTrue(count($containerBuilder->getParameterBag()->all()) > 0, 'Parameters can be read from the config file.'); } public function testLoadParameters() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services2.xml'); $actual = $container->getParameterBag()->all(); $expected = array( 'a string', 'foo' => 'bar', 'values' => array( 0, 'integer' => 4, 100 => null, 'true', true, false, 'on', 'off', 'float' => 1.3, 1000.3, 'a string', array('foo', 'bar'), ), 'mixedcase' => array('MixedCaseKey' => 'value'), 'constant' => PHP_EOL, ); $this->assertEquals($expected, $actual, '->load() converts XML values to PHP ones'); } public function testLoadImports() { $container = new ContainerBuilder(); $resolver = new LoaderResolver(array( new IniFileLoader($container, new FileLocator(self::$fixturesPath.'/ini')), new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yml')), $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')), )); $loader->setResolver($resolver); $loader->load('services4.xml'); $actual = $container->getParameterBag()->all(); $expected = array( 'a string', 'foo' => 'bar', 'values' => array( 0, 'integer' => 4, 100 => null, 'true', true, false, 'on', 'off', 'float' => 1.3, 1000.3, 'a string', array('foo', 'bar'), ), 'mixedcase' => array('MixedCaseKey' => 'value'), 'constant' => PHP_EOL, 'bar' => '%foo%', 'imported_from_ini' => true, 'imported_from_yaml' => true, 'with_wrong_ext' => 'from yaml', ); $this->assertEquals(array_keys($expected), array_keys($actual), '->load() imports and merges imported files'); $this->assertTrue($actual['imported_from_ini']); // Bad import throws no exception due to ignore_errors value. $loader->load('services4_bad_import.xml'); } public function testLoadAnonymousServices() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services5.xml'); $services = $container->getDefinitions(); $this->assertCount(7, $services, '->load() attributes unique ids to anonymous services'); // anonymous service as an argument $args = $services['foo']->getArguments(); $this->assertCount(1, $args, '->load() references anonymous services as "normal" ones'); $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Reference', $args[0], '->load() converts anonymous services to references to "normal" services'); $this->assertTrue(isset($services[(string) $args[0]]), '->load() makes a reference to the created ones'); $inner = $services[(string) $args[0]]; $this->assertEquals('BarClass', $inner->getClass(), '->load() uses the same configuration as for the anonymous ones'); $this->assertFalse($inner->isPublic()); // inner anonymous services $args = $inner->getArguments(); $this->assertCount(1, $args, '->load() references anonymous services as "normal" ones'); $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Reference', $args[0], '->load() converts anonymous services to references to "normal" services'); $this->assertTrue(isset($services[(string) $args[0]]), '->load() makes a reference to the created ones'); $inner = $services[(string) $args[0]]; $this->assertEquals('BazClass', $inner->getClass(), '->load() uses the same configuration as for the anonymous ones'); $this->assertFalse($inner->isPublic()); // anonymous service as a property $properties = $services['foo']->getProperties(); $property = $properties['p']; $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Reference', $property, '->load() converts anonymous services to references to "normal" services'); $this->assertTrue(isset($services[(string) $property]), '->load() makes a reference to the created ones'); $inner = $services[(string) $property]; $this->assertEquals('BuzClass', $inner->getClass(), '->load() uses the same configuration as for the anonymous ones'); $this->assertFalse($inner->isPublic()); // "wild" service $service = $container->findTaggedServiceIds('biz_tag'); $this->assertCount(1, $service); foreach ($service as $id => $tag) { $service = $container->getDefinition($id); } $this->assertEquals('BizClass', $service->getClass(), '->load() uses the same configuration as for the anonymous ones'); $this->assertTrue($service->isPublic()); // anonymous services are shared when using decoration definitions $container->compile(); $services = $container->getDefinitions(); $fooArgs = $services['foo']->getArguments(); $barArgs = $services['bar']->getArguments(); $this->assertSame($fooArgs[0], $barArgs[0]); } /** * @group legacy * @expectedDeprecation Top-level anonymous services are deprecated since Symfony 3.4, the "id" attribute will be required in version 4.0 in %sservices_without_id.xml at line 4. */ public function testLoadAnonymousServicesWithoutId() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services_without_id.xml'); } public function testLoadAnonymousNestedServices() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('nested_service_without_id.xml'); $this->assertTrue($container->hasDefinition('FooClass')); $arguments = $container->getDefinition('FooClass')->getArguments(); $this->assertInstanceOf(Reference::class, array_shift($arguments)); } public function testLoadServices() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services6.xml'); $services = $container->getDefinitions(); $this->assertTrue(isset($services['foo']), '->load() parses <service> elements'); $this->assertFalse($services['not_shared']->isShared(), '->load() parses shared flag'); $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Definition', $services['foo'], '->load() converts <service> element to Definition instances'); $this->assertEquals('FooClass', $services['foo']->getClass(), '->load() parses the class attribute'); $this->assertEquals('%path%/foo.php', $services['file']->getFile(), '->load() parses the file tag'); $this->assertEquals(array('foo', new Reference('foo'), array(true, false)), $services['arguments']->getArguments(), '->load() parses the argument tags'); $this->assertEquals('sc_configure', $services['configurator1']->getConfigurator(), '->load() parses the configurator tag'); $this->assertEquals(array(new Reference('baz'), 'configure'), $services['configurator2']->getConfigurator(), '->load() parses the configurator tag'); $this->assertEquals(array('BazClass', 'configureStatic'), $services['configurator3']->getConfigurator(), '->load() parses the configurator tag'); $this->assertEquals(array(array('setBar', array()), array('setBar', array(new Expression('service("foo").foo() ~ (container.hasParameter("foo") ? parameter("foo") : "default")')))), $services['method_call1']->getMethodCalls(), '->load() parses the method_call tag'); $this->assertEquals(array(array('setBar', array('foo', new Reference('foo'), array(true, false)))), $services['method_call2']->getMethodCalls(), '->load() parses the method_call tag'); $this->assertEquals('factory', $services['new_factory1']->getFactory(), '->load() parses the factory tag'); $this->assertEquals(array(new Reference('baz'), 'getClass'), $services['new_factory2']->getFactory(), '->load() parses the factory tag'); $this->assertEquals(array('BazClass', 'getInstance'), $services['new_factory3']->getFactory(), '->load() parses the factory tag'); $this->assertSame(array(null, 'getInstance'), $services['new_factory4']->getFactory(), '->load() accepts factory tag without class'); $aliases = $container->getAliases(); $this->assertTrue(isset($aliases['alias_for_foo']), '->load() parses <service> elements'); $this->assertEquals('foo', (string) $aliases['alias_for_foo'], '->load() parses aliases'); $this->assertTrue($aliases['alias_for_foo']->isPublic()); $this->assertTrue(isset($aliases['another_alias_for_foo'])); $this->assertEquals('foo', (string) $aliases['another_alias_for_foo']); $this->assertFalse($aliases['another_alias_for_foo']->isPublic()); $this->assertEquals(array('decorated', null, 0), $services['decorator_service']->getDecoratedService()); $this->assertEquals(array('decorated', 'decorated.pif-pouf', 0), $services['decorator_service_with_name']->getDecoratedService()); $this->assertEquals(array('decorated', 'decorated.pif-pouf', 5), $services['decorator_service_with_name_and_priority']->getDecoratedService()); } public function testParsesIteratorArgument() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services9.xml'); $lazyDefinition = $container->getDefinition('lazy_context'); $this->assertEquals(array(new IteratorArgument(array('k1' => new Reference('foo.baz'), 'k2' => new Reference('service_container'))), new IteratorArgument(array())), $lazyDefinition->getArguments(), '->load() parses lazy arguments'); } public function testParsesTags() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services10.xml'); $services = $container->findTaggedServiceIds('foo_tag'); $this->assertCount(1, $services); foreach ($services as $id => $tagAttributes) { foreach ($tagAttributes as $attributes) { $this->assertArrayHasKey('other_option', $attributes); $this->assertEquals('lorem', $attributes['other_option']); $this->assertArrayHasKey('other-option', $attributes, 'unnormalized tag attributes should not be removed'); $this->assertEquals('ciz', $attributes['some_option'], 'no overriding should be done when normalizing'); $this->assertEquals('cat', $attributes['some-option']); $this->assertArrayNotHasKey('an_other_option', $attributes, 'normalization should not be done when an underscore is already found'); } } } /** * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException */ public function testParseTagsWithoutNameThrowsException() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('tag_without_name.xml'); } /** * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException * @expectedExceptionMessageRegExp /The tag name for service ".+" in .* must be a non-empty string/ */ public function testParseTagWithEmptyNameThrowsException() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('tag_with_empty_name.xml'); } public function testDeprecated() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services_deprecated.xml'); $this->assertTrue($container->getDefinition('foo')->isDeprecated()); $message = 'The "foo" service is deprecated. You should stop using it, as it will soon be removed.'; $this->assertSame($message, $container->getDefinition('foo')->getDeprecationMessage('foo')); $this->assertTrue($container->getDefinition('bar')->isDeprecated()); $message = 'The "bar" service is deprecated.'; $this->assertSame($message, $container->getDefinition('bar')->getDeprecationMessage('bar')); } public function testConvertDomElementToArray() { $doc = new \DOMDocument('1.0'); $doc->loadXML('<foo>bar</foo>'); $this->assertEquals('bar', XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array'); $doc = new \DOMDocument('1.0'); $doc->loadXML('<foo foo="bar" />'); $this->assertEquals(array('foo' => 'bar'), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array'); $doc = new \DOMDocument('1.0'); $doc->loadXML('<foo><foo>bar</foo></foo>'); $this->assertEquals(array('foo' => 'bar'), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array'); $doc = new \DOMDocument('1.0'); $doc->loadXML('<foo><foo>bar<foo>bar</foo></foo></foo>'); $this->assertEquals(array('foo' => array('value' => 'bar', 'foo' => 'bar')), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array'); $doc = new \DOMDocument('1.0'); $doc->loadXML('<foo><foo></foo></foo>'); $this->assertEquals(array('foo' => null), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array'); $doc = new \DOMDocument('1.0'); $doc->loadXML('<foo><foo><!-- foo --></foo></foo>'); $this->assertEquals(array('foo' => null), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array'); $doc = new \DOMDocument('1.0'); $doc->loadXML('<foo><foo foo="bar"/><foo foo="bar"/></foo>'); $this->assertEquals(array('foo' => array(array('foo' => 'bar'), array('foo' => 'bar'))), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array'); } public function testExtensions() { $container = new ContainerBuilder(); $container->registerExtension(new \ProjectExtension()); $container->registerExtension(new \ProjectWithXsdExtension()); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); // extension without an XSD $loader->load('extensions/services1.xml'); $container->compile(); $services = $container->getDefinitions(); $parameters = $container->getParameterBag()->all(); $this->assertTrue(isset($services['project.service.bar']), '->load() parses extension elements'); $this->assertTrue(isset($parameters['project.parameter.bar']), '->load() parses extension elements'); $this->assertEquals('BAR', $services['project.service.foo']->getClass(), '->load() parses extension elements'); $this->assertEquals('BAR', $parameters['project.parameter.foo'], '->load() parses extension elements'); // extension with an XSD $container = new ContainerBuilder(); $container->registerExtension(new \ProjectExtension()); $container->registerExtension(new \ProjectWithXsdExtension()); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('extensions/services2.xml'); $container->compile(); $services = $container->getDefinitions(); $parameters = $container->getParameterBag()->all(); $this->assertTrue(isset($services['project.service.bar']), '->load() parses extension elements'); $this->assertTrue(isset($parameters['project.parameter.bar']), '->load() parses extension elements'); $this->assertEquals('BAR', $services['project.service.foo']->getClass(), '->load() parses extension elements'); $this->assertEquals('BAR', $parameters['project.parameter.foo'], '->load() parses extension elements'); $container = new ContainerBuilder(); $container->registerExtension(new \ProjectExtension()); $container->registerExtension(new \ProjectWithXsdExtension()); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); // extension with an XSD (does not validate) try { $loader->load('extensions/services3.xml'); $this->fail('->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'services3.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); $e = $e->getPrevious(); $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); $this->assertContains('The attribute \'bar\' is not allowed', $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); } // non-registered extension try { $loader->load('extensions/services4.xml'); $this->fail('->load() throws an InvalidArgumentException if the tag is not valid'); } catch (\Exception $e) { $this->assertInstanceOf('\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the tag is not valid'); $this->assertStringStartsWith('There is no extension able to load the configuration for "project:bar" (in', $e->getMessage(), '->load() throws an InvalidArgumentException if the tag is not valid'); } } public function testExtensionInPhar() { if (extension_loaded('suhosin') && false === strpos(ini_get('suhosin.executor.include.whitelist'), 'phar')) { $this->markTestSkipped('To run this test, add "phar" to the "suhosin.executor.include.whitelist" settings in your php.ini file.'); } require_once self::$fixturesPath.'/includes/ProjectWithXsdExtensionInPhar.phar'; // extension with an XSD in PHAR archive $container = new ContainerBuilder(); $container->registerExtension(new \ProjectWithXsdExtensionInPhar()); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('extensions/services6.xml'); // extension with an XSD in PHAR archive (does not validate) try { $loader->load('extensions/services7.xml'); $this->fail('->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'services7.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); $e = $e->getPrevious(); $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); $this->assertContains('The attribute \'bar\' is not allowed', $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); } } public function testSupports() { $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator()); $this->assertTrue($loader->supports('foo.xml'), '->supports() returns true if the resource is loadable'); $this->assertFalse($loader->supports('foo.foo'), '->supports() returns false if the resource is not loadable'); $this->assertTrue($loader->supports('with_wrong_ext.yml', 'xml'), '->supports() returns true if the resource with forced type is loadable'); } public function testNoNamingConflictsForAnonymousServices() { $container = new ContainerBuilder(); $loader1 = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml/extension1')); $loader1->load('services.xml'); $services = $container->getDefinitions(); $this->assertCount(3, $services, '->load() attributes unique ids to anonymous services'); $loader2 = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml/extension2')); $loader2->load('services.xml'); $services = $container->getDefinitions(); $this->assertCount(5, $services, '->load() attributes unique ids to anonymous services'); $services = $container->getDefinitions(); $args1 = $services['extension1.foo']->getArguments(); $inner1 = $services[(string) $args1[0]]; $this->assertEquals('BarClass1', $inner1->getClass(), '->load() uses the same configuration as for the anonymous ones'); $args2 = $services['extension2.foo']->getArguments(); $inner2 = $services[(string) $args2[0]]; $this->assertEquals('BarClass2', $inner2->getClass(), '->load() uses the same configuration as for the anonymous ones'); } public function testDocTypeIsNotAllowed() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); // document types are not allowed. try { $loader->load('withdoctype.xml'); $this->fail('->load() throws an InvalidArgumentException if the configuration contains a document type'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration contains a document type'); $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'withdoctype.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration contains a document type'); $e = $e->getPrevious(); $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration contains a document type'); $this->assertSame('Document types are not allowed.', $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration contains a document type'); } } public function testXmlNamespaces() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('namespaces.xml'); $services = $container->getDefinitions(); $this->assertTrue(isset($services['foo']), '->load() parses <srv:service> elements'); $this->assertEquals(1, count($services['foo']->getTag('foo.tag')), '->load parses <srv:tag> elements'); $this->assertEquals(array(array('setBar', array('foo'))), $services['foo']->getMethodCalls(), '->load() parses the <srv:call> tag'); } public function testLoadIndexedArguments() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services14.xml'); $this->assertEquals(array('index_0' => 'app'), $container->findDefinition('logger')->getArguments()); } public function testLoadInlinedServices() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services21.xml'); $foo = $container->getDefinition('foo'); $fooFactory = $foo->getFactory(); $this->assertInstanceOf(Reference::class, $fooFactory[0]); $this->assertTrue($container->has((string) $fooFactory[0])); $fooFactoryDefinition = $container->getDefinition((string) $fooFactory[0]); $this->assertSame('FooFactory', $fooFactoryDefinition->getClass()); $this->assertSame('createFoo', $fooFactory[1]); $fooFactoryFactory = $fooFactoryDefinition->getFactory(); $this->assertInstanceOf(Reference::class, $fooFactoryFactory[0]); $this->assertTrue($container->has((string) $fooFactoryFactory[0])); $this->assertSame('Foobar', $container->getDefinition((string) $fooFactoryFactory[0])->getClass()); $this->assertSame('createFooFactory', $fooFactoryFactory[1]); $fooConfigurator = $foo->getConfigurator(); $this->assertInstanceOf(Reference::class, $fooConfigurator[0]); $this->assertTrue($container->has((string) $fooConfigurator[0])); $fooConfiguratorDefinition = $container->getDefinition((string) $fooConfigurator[0]); $this->assertSame('Bar', $fooConfiguratorDefinition->getClass()); $this->assertSame('configureFoo', $fooConfigurator[1]); $barConfigurator = $fooConfiguratorDefinition->getConfigurator(); $this->assertInstanceOf(Reference::class, $barConfigurator[0]); $this->assertSame('Baz', $container->getDefinition((string) $barConfigurator[0])->getClass()); $this->assertSame('configureBar', $barConfigurator[1]); } public function testAutowire() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services23.xml'); $this->assertTrue($container->getDefinition('bar')->isAutowired()); } public function testClassFromId() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('class_from_id.xml'); $container->compile(); $this->assertEquals(CaseSensitiveClass::class, $container->getDefinition(CaseSensitiveClass::class)->getClass()); } public function testPrototype() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services_prototype.xml'); $ids = array_keys($container->getDefinitions()); sort($ids); $this->assertSame(array(Prototype\Foo::class, Prototype\Sub\Bar::class, 'service_container'), $ids); $resources = $container->getResources(); $fixturesDir = dirname(__DIR__).DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR; $this->assertTrue(false !== array_search(new FileResource($fixturesDir.'xml'.DIRECTORY_SEPARATOR.'services_prototype.xml'), $resources)); $this->assertTrue(false !== array_search(new GlobResource($fixturesDir.'Prototype', '/*', true), $resources)); $resources = array_map('strval', $resources); $this->assertContains('reflection.Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Foo', $resources); $this->assertContains('reflection.Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Sub\Bar', $resources); } /** * @group legacy * @expectedDeprecation Using the attribute "class" is deprecated for the service "bar" which is defined as an alias %s. * @expectedDeprecation Using the element "tag" is deprecated for the service "bar" which is defined as an alias %s. * @expectedDeprecation Using the element "factory" is deprecated for the service "bar" which is defined as an alias %s. */ public function testAliasDefinitionContainsUnsupportedElements() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('legacy_invalid_alias_definition.xml'); $this->assertTrue($container->has('bar')); } public function testArgumentWithKeyOutsideCollection() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('with_key_outside_collection.xml'); $this->assertSame(array('type' => 'foo', 'bar'), $container->getDefinition('foo')->getArguments()); } public function testDefaults() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services28.xml'); $this->assertFalse($container->getDefinition('with_defaults')->isPublic()); $this->assertSame(array('foo' => array(array())), $container->getDefinition('with_defaults')->getTags()); $this->assertTrue($container->getDefinition('with_defaults')->isAutowired()); $this->assertArrayNotHasKey('public', $container->getDefinition('with_defaults')->getChanges()); $this->assertArrayNotHasKey('autowire', $container->getDefinition('with_defaults')->getChanges()); $container->compile(); $this->assertTrue($container->getDefinition('no_defaults')->isPublic()); $this->assertSame(array('foo' => array(array())), $container->getDefinition('no_defaults')->getTags()); $this->assertFalse($container->getDefinition('no_defaults')->isAutowired()); $this->assertTrue($container->getDefinition('child_def')->isPublic()); $this->assertSame(array('foo' => array(array())), $container->getDefinition('child_def')->getTags()); $this->assertFalse($container->getDefinition('child_def')->isAutowired()); $definitions = $container->getDefinitions(); $this->assertSame('service_container', key($definitions)); array_shift($definitions); $anonymous = current($definitions); $this->assertSame('bar', key($definitions)); $this->assertTrue($anonymous->isPublic()); $this->assertTrue($anonymous->isAutowired()); $this->assertSame(array('foo' => array(array())), $anonymous->getTags()); } public function testNamedArguments() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services_named_args.xml'); $this->assertEquals(array(null, '$apiKey' => 'ABCD'), $container->getDefinition(NamedArgumentsDummy::class)->getArguments()); $container->compile(); $this->assertEquals(array(null, 'ABCD'), $container->getDefinition(NamedArgumentsDummy::class)->getArguments()); $this->assertEquals(array(array('setApiKey', array('123'))), $container->getDefinition(NamedArgumentsDummy::class)->getMethodCalls()); } public function testInstanceof() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services_instanceof.xml'); $container->compile(); $definition = $container->getDefinition(Bar::class); $this->assertTrue($definition->isAutowired()); $this->assertTrue($definition->isLazy()); $this->assertSame(array('foo' => array(array()), 'bar' => array(array())), $definition->getTags()); } /** * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException * @expectedExceptionMessage The service "child_service" cannot use the "parent" option in the same file where "instanceof" configuration is defined as using both is not supported. Move your child definitions to a separate file. */ public function testInstanceOfAndChildDefinitionNotAllowed() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services_instanceof_with_parent.xml'); $container->compile(); } /** * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException * @expectedExceptionMessage The service "child_service" cannot have a "parent" and also have "autoconfigure". Try setting autoconfigure="false" for the service. */ public function testAutoConfigureAndChildDefinitionNotAllowed() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services_autoconfigure_with_parent.xml'); $container->compile(); } /** * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException * @expectedExceptionMessage Attribute "autowire" on service "child_service" cannot be inherited from "defaults" when a "parent" is set. Move your child definitions to a separate file or define this attribute explicitly. */ public function testDefaultsAndChildDefinitionNotAllowed() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services_defaults_with_parent.xml'); $container->compile(); } public function testAutoConfigureInstanceof() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services_autoconfigure.xml'); $this->assertTrue($container->getDefinition('use_defaults_settings')->isAutoconfigured()); $this->assertFalse($container->getDefinition('override_defaults_settings_to_false')->isAutoconfigured()); } } interface BarInterface { } class Bar implements BarInterface { }
mit
lale-help/lale-help
db/migrate/20160417005737_create_file_uploads.rb
542
class CreateFileUploads < ActiveRecord::Migration def change enable_extension 'uuid-ossp' create_table :file_uploads, id: :uuid do |t| t.string :name t.string :upload_type t.boolean :is_public, default: false t.integer :uploader_id t.string :uploadable_type t.integer :uploadable_id t.string :file_name t.string :file_path t.string :file_content_type t.string :file_extension t.string :file_encryption_details t.timestamps null: false end end end
mit
zweidner/hubzero-cms
core/modules/mod_myactivity/mod_myactivity.php
277
<?php /** * @package hubzero-cms * @copyright Copyright 2005-2019 HUBzero Foundation, LLC. * @license http://opensource.org/licenses/MIT MIT */ namespace Modules\MyActivity; require_once __DIR__ . DS . 'helper.php'; with(new Helper($params, $module))->display();
mit
geekhack/incsyncwebfinal
app/cache/prod/translations/catalogue.en.php
4455
<?php use Symfony\Component\Translation\MessageCatalogue; $catalogue = new MessageCatalogue('en', array ( 'validators' => array ( 'fos_user.username.already_used' => 'The username is already used', 'fos_user.username.blank' => 'Please enter a username', 'fos_user.username.short' => 'The username is too short', 'fos_user.username.long' => 'The username is too long', 'fos_user.email.already_used' => 'The email is already used', 'fos_user.email.blank' => 'Please enter an email', 'fos_user.email.short' => 'The email is too short', 'fos_user.email.long' => 'The email is too long', 'fos_user.email.invalid' => 'The email is not valid', 'fos_user.password.blank' => 'Please enter a password', 'fos_user.password.short' => 'The password is too short', 'fos_user.new_password.blank' => 'Please enter a new password', 'fos_user.new_password.short' => 'The new password is too short', 'fos_user.current_password.invalid' => 'The entered password is invalid', 'fos_user.group.blank' => 'Please enter a name', 'fos_user.group.short' => 'The name is too short', 'fos_user.group.long' => 'The name is too long', ), 'FOSUserBundle' => array ( 'Bad credentials' => 'Invalid username or password', 'fos_user_group_form_name' => 'Group name:', 'fos_user_profile_form_user_username' => 'Username:', 'fos_user_profile_form_user_email' => 'Email:', 'fos_user_profile_form_current' => 'Current Password:', 'fos_user_registration_form_username' => 'Username:', 'fos_user_registration_form_email' => 'Email:', 'fos_user_registration_form_plainPassword_first' => 'Password:', 'fos_user_registration_form_plainPassword_second' => 'Verification:', 'fos_user_resetting_form_new_first' => 'New password:', 'fos_user_resetting_form_new_second' => 'Verification:', 'fos_user_change_password_form_new_first' => 'New password:', 'fos_user_change_password_form_new_second' => 'Verification:', 'fos_user_change_password_form_current' => 'Current password:', 'group.edit.submit' => 'Update group', 'group.show.name' => 'Group name', 'group.new.submit' => 'Create group', 'group.flash.updated' => 'The group has been updated', 'group.flash.created' => 'The group has been created', 'group.flash.deleted' => 'The group has been deleted', 'security.login.username' => 'Username:', 'security.login.password' => 'Password:', 'security.login.remember_me' => 'Remember me', 'security.login.submit' => 'Login', 'profile.show.username' => 'Username', 'profile.show.email' => 'Email', 'profile.edit.submit' => 'Update', 'profile.flash.updated' => 'The profile has been updated', 'change_password.submit' => 'Change password', 'change_password.flash.success' => 'The password has been changed', 'registration.check_email' => 'An email has been sent to %email%. It contains an activation link you must click to activate your account.', 'registration.confirmed' => 'Congrats %username%, your account is now activated.', 'registration.back' => 'Back to the originating page.', 'registration.submit' => 'Register', 'registration.flash.user_created' => 'The user has been created successfully', 'registration.email.subject' => 'Welcome %username%!', 'registration.email.message' => 'Hello %username%! To finish activating your account - please visit %confirmationUrl% Regards, the Team. ', 'resetting.password_already_requested' => 'The password for this user has already been requested within the last 24 hours.', 'resetting.check_email' => 'An email has been sent to %email%. It contains a link you must click to reset your password.', 'resetting.request.invalid_username' => 'The username or email address "%username%" does not exist.', 'resetting.request.username' => 'Username or email address:', 'resetting.request.submit' => 'Reset password', 'resetting.reset.submit' => 'Change password', 'resetting.flash.success' => 'The password has been reset successfully', 'resetting.email.subject' => 'Reset Password', 'resetting.email.message' => 'Hello %username%! To reset your password - please visit %confirmationUrl% Regards, the Team. ', 'layout.logout' => 'Logout', 'layout.login' => 'Login', 'layout.register' => 'Register', 'layout.logged_in_as' => 'Logged in as %username%', ), )); return $catalogue;
mit
daiyu/gitlab-zh
spec/lib/gitlab/data_builder/push_spec.rb
2197
require 'spec_helper' describe Gitlab::DataBuilder::Push, lib: true do let(:project) { create(:project) } let(:user) { create(:user) } describe '.build_sample' do let(:data) { described_class.build_sample(project, user) } it { expect(data).to be_a(Hash) } it { expect(data[:before]).to eq('1b12f15a11fc6e62177bef08f47bc7b5ce50b141') } it { expect(data[:after]).to eq('b83d6e391c22777fca1ed3012fce84f633d7fed0') } it { expect(data[:ref]).to eq('refs/heads/master') } it { expect(data[:commits].size).to eq(3) } it { expect(data[:total_commits_count]).to eq(3) } it { expect(data[:commits].first[:added]).to eq(['bar/branch-test.txt']) } it { expect(data[:commits].first[:modified]).to eq([]) } it { expect(data[:commits].first[:removed]).to eq([]) } include_examples 'project hook data with deprecateds' include_examples 'deprecated repository hook data' end describe '.build' do let(:data) do described_class.build(project, user, Gitlab::Git::BLANK_SHA, '8a2a6eb295bb170b34c24c76c49ed0e9b2eaf34b', 'refs/tags/v1.1.0') end it { expect(data).to be_a(Hash) } it { expect(data[:before]).to eq(Gitlab::Git::BLANK_SHA) } it { expect(data[:checkout_sha]).to eq('5937ac0a7beb003549fc5fd26fc247adbce4a52e') } it { expect(data[:after]).to eq('8a2a6eb295bb170b34c24c76c49ed0e9b2eaf34b') } it { expect(data[:ref]).to eq('refs/tags/v1.1.0') } it { expect(data[:user_id]).to eq(user.id) } it { expect(data[:user_name]).to eq(user.name) } it { expect(data[:user_email]).to eq(user.email) } it { expect(data[:user_avatar]).to eq(user.avatar_url) } it { expect(data[:project_id]).to eq(project.id) } it { expect(data[:project]).to be_a(Hash) } it { expect(data[:commits]).to be_empty } it { expect(data[:total_commits_count]).to be_zero } include_examples 'project hook data with deprecateds' include_examples 'deprecated repository hook data' it 'does not raise an error when given nil commits' do expect { described_class.build(spy, spy, spy, spy, spy, nil) }. not_to raise_error end end end
mit
influxdb/influxdb
kv/migration/all/0018_repair-missing-shard-group-durations_test.go
143
package all import "testing" func TestMigration_PostUpgradeShardGroupDuration(t *testing.T) { testRepairMissingShardGroupDurations(t, 18) }
mit
isaacs/express
test/res.sendfile.js
5671
var express = require('../') , request = require('./support/http') , assert = require('assert'); describe('res', function(){ describe('.sendfile(path, fn)', function(){ it('should invoke the callback when complete', function(done){ var app = express() , calls = 0; app.use(function(req, res){ res.sendfile('test/fixtures/user.html', function(err){ assert(!err); ++calls; }); }); request(app) .get('/') .end(function(res){ calls.should.equal(1); res.statusCode.should.equal(200); done(); }); }) it('should invoke the callback on 404', function(done){ var app = express() , calls = 0; app.use(function(req, res){ res.sendfile('test/fixtures/nope.html', function(err){ assert(!res.headerSent); ++calls; res.send(err.message); }); }); request(app) .get('/') .end(function(res){ calls.should.equal(1); res.body.should.equal('Not Found'); res.statusCode.should.equal(200); done(); }); }) it('should not override manual content-types', function(done){ var app = express(); app.use(function(req, res){ res.contentType('txt'); res.sendfile('test/fixtures/user.html'); }); request(app) .get('/') .end(function(res){ res.should.have.header('content-type', 'text/plain'); done(); }); }) it('should invoke the callback on 403', function(done){ var app = express() , calls = 0; app.use(function(req, res){ res.sendfile('test/fixtures/foo/../user.html', function(err){ assert(!res.headerSent); ++calls; res.send(err.message); }); }); request(app) .get('/') .end(function(res){ res.body.should.equal('Forbidden'); res.statusCode.should.equal(200); calls.should.equal(1); done(); }); }) }) describe('.sendfile(path)', function(){ describe('with an absolute path', function(){ it('should transfer the file', function(done){ var app = express(); app.use(function(req, res){ res.sendfile(__dirname + '/fixtures/user.html'); }); request(app) .get('/') .end(function(res){ res.body.should.equal('<p>{{user.name}}</p>'); res.headers.should.have.property('content-type', 'text/html; charset=UTF-8'); done(); }); }) }) describe('with a relative path', function(){ it('should transfer the file', function(done){ var app = express(); app.use(function(req, res){ res.sendfile('test/fixtures/user.html'); }); request(app) .get('/') .end(function(res){ res.body.should.equal('<p>{{user.name}}</p>'); res.headers.should.have.property('content-type', 'text/html; charset=UTF-8'); done(); }); }) it('should serve relative to "root"', function(done){ var app = express(); app.use(function(req, res){ res.sendfile('user.html', { root: 'test/fixtures/' }); }); request(app) .get('/') .end(function(res){ res.body.should.equal('<p>{{user.name}}</p>'); res.headers.should.have.property('content-type', 'text/html; charset=UTF-8'); done(); }); }) it('should consider ../ malicious when "root" is not set', function(done){ var app = express(); app.use(function(req, res){ res.sendfile('test/fixtures/foo/../user.html'); }); request(app) .get('/') .end(function(res){ res.statusCode.should.equal(403); done(); }); }) it('should allow ../ when "root" is set', function(done){ var app = express(); app.use(function(req, res){ res.sendfile('foo/../user.html', { root: 'test/fixtures' }); }); request(app) .get('/') .end(function(res){ res.statusCode.should.equal(200); done(); }); }) it('should disallow requesting out of "root"', function(done){ var app = express(); app.use(function(req, res){ res.sendfile('foo/../../user.html', { root: 'test/fixtures' }); }); request(app) .get('/') .end(function(res){ res.statusCode.should.equal(403); done(); }); }) it('should next(404) when not found', function(done){ var app = express() , calls = 0; app.use(function(req, res){ res.sendfile('user.html'); }); app.use(function(req, res){ assert(0, 'this should not be called'); }); app.use(function(err, req, res, next){ ++calls; next(err); }); request(app) .get('/') .end(function(res){ res.statusCode.should.equal(404); calls.should.equal(1); done(); }); }) describe('with non-GET', function(){ it('should still serve', function(done){ var app = express() , calls = 0; app.use(function(req, res){ res.sendfile(__dirname + '/fixtures/name.txt'); }); request(app) .get('/') .expect('tobi', done); }) }) }) }) })
mit
toukajiang/sztw
src/main/java/betahouse/service/power/PowerTypeServiceImpl.java
1960
package betahouse.service.power; import betahouse.mapper.PowerTypeMapper; import betahouse.model.Power; import betahouse.model.PowerType; import betahouse.model.VO.PowerVO; import betahouse.service.form.FormTypeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by x1654 on 2017/7/18. */ @Service public class PowerTypeServiceImpl implements PowerTypeService{ @Autowired private PowerTypeMapper powerTypeMapper; @Autowired private FormTypeService formTypeService; @Override public List<PowerVO> listPowerVO() { List<PowerVO> powerVOList = new ArrayList<>(); List<PowerType> listDTO = powerTypeMapper.selectAll(); for(PowerType p: listDTO){ int maxLv = 0; PowerVO powerVO = new PowerVO(); powerVO.setId(p.getPowerId()); powerVO.setPowerName(p.getPowerName()); powerVO.setMaxLv(maxLv); powerVO.setPermit(0); if(null!=p.getFormType()){ maxLv = formTypeService.getFormTypeByFormType(p.getFormType()).getMaxLv(); powerVO.setMaxLv(maxLv); //强行修改bug if(p.getPowerId()==3||p.getPowerId()==10){ powerVO.setPermit(-1); } } powerVOList.add(powerVO); } return powerVOList; } @Override public List<Integer> listPower() { List<Integer> listDTO = new ArrayList<>(); List<PowerType> listDTO2 = powerTypeMapper.selectAll(); for(PowerType p: listDTO2){ listDTO.add(p.getPowerId()); } return listDTO; } @Override public PowerType getPowerTypeByPowerId(int powerId) { return powerTypeMapper.selectByPowerId(powerId); } }
mit
icede/Gridcoin-master
src/boinc/boinc/OpenPop/source/OpenPop/Mime/Decode/QuotedPrintable.cs
14050
using System; using System.IO; using System.Text; using System.Text.RegularExpressions; namespace OpenPop.Mime.Decode { /// <summary> /// Used for decoding Quoted-Printable text.<br/> /// This is a robust implementation of a Quoted-Printable decoder defined in <a href="http://tools.ietf.org/html/rfc2045">RFC 2045</a> and <a href="http://tools.ietf.org/html/rfc2047">RFC 2047</a>.<br/> /// Every measurement has been taken to conform to the RFC. /// </summary> internal static class QuotedPrintable { /// <summary> /// Decodes a Quoted-Printable string according to <a href="http://tools.ietf.org/html/rfc2047">RFC 2047</a>.<br/> /// RFC 2047 is used for decoding Encoded-Word encoded strings. /// </summary> /// <param name="toDecode">Quoted-Printable encoded string</param> /// <param name="encoding">Specifies which encoding the returned string will be in</param> /// <returns>A decoded string in the correct encoding</returns> /// <exception cref="ArgumentNullException">If <paramref name="toDecode"/> or <paramref name="encoding"/> is <see langword="null"/></exception> public static string DecodeEncodedWord(string toDecode, Encoding encoding) { if (toDecode == null) throw new ArgumentNullException("toDecode"); if (encoding == null) throw new ArgumentNullException("encoding"); // Decode the QuotedPrintable string and return it return encoding.GetString(Rfc2047QuotedPrintableDecode(toDecode, true)); } /// <summary> /// Decodes a Quoted-Printable string according to <a href="http://tools.ietf.org/html/rfc2045">RFC 2045</a>.<br/> /// RFC 2045 specifies the decoding of a body encoded with Content-Transfer-Encoding of quoted-printable. /// </summary> /// <param name="toDecode">Quoted-Printable encoded string</param> /// <returns>A decoded byte array that the Quoted-Printable encoded string described</returns> /// <exception cref="ArgumentNullException">If <paramref name="toDecode"/> is <see langword="null"/></exception> public static byte[] DecodeContentTransferEncoding(string toDecode) { if (toDecode == null) throw new ArgumentNullException("toDecode"); // Decode the QuotedPrintable string and return it return Rfc2047QuotedPrintableDecode(toDecode, false); } /// <summary> /// This is the actual decoder. /// </summary> /// <param name="toDecode">The string to be decoded from Quoted-Printable</param> /// <param name="encodedWordVariant"> /// If <see langword="true"/>, specifies that RFC 2047 quoted printable decoding is used.<br/> /// This is for quoted-printable encoded words<br/> /// <br/> /// If <see langword="false"/>, specifies that RFC 2045 quoted printable decoding is used.<br/> /// This is for quoted-printable Content-Transfer-Encoding /// </param> /// <returns>A decoded byte array that was described by <paramref name="toDecode"/></returns> /// <exception cref="ArgumentNullException">If <paramref name="toDecode"/> is <see langword="null"/></exception> /// <remarks>See <a href="http://tools.ietf.org/html/rfc2047#section-4.2">RFC 2047 section 4.2</a> for RFC details</remarks> private static byte[] Rfc2047QuotedPrintableDecode(string toDecode, bool encodedWordVariant) { if (toDecode == null) throw new ArgumentNullException("toDecode"); // Create a byte array builder which is roughly equivalent to a StringBuilder using (MemoryStream byteArrayBuilder = new MemoryStream()) { // Remove illegal control characters toDecode = RemoveIllegalControlCharacters(toDecode); // Run through the whole string that needs to be decoded for (int i = 0; i < toDecode.Length; i++) { char currentChar = toDecode[i]; if (currentChar == '=') { // Check that there is at least two characters behind the equal sign if (toDecode.Length - i < 3) { // We are at the end of the toDecode string, but something is missing. Handle it the way RFC 2045 states WriteAllBytesToStream(byteArrayBuilder, DecodeEqualSignNotLongEnough(toDecode.Substring(i))); // Since it was the last part, we should stop parsing anymore break; } // Decode the Quoted-Printable part string quotedPrintablePart = toDecode.Substring(i, 3); WriteAllBytesToStream(byteArrayBuilder, DecodeEqualSign(quotedPrintablePart)); // We now consumed two extra characters. Go forward two extra characters i += 2; } else { // This character is not quoted printable hex encoded. // Could it be the _ character, which represents space // and are we using the encoded word variant of QuotedPrintable if (currentChar == '_' && encodedWordVariant) { // The RFC specifies that the "_" always represents hexadecimal 20 even if the // SPACE character occupies a different code position in the character set in use. byteArrayBuilder.WriteByte(0x20); } else { // This is not encoded at all. This is a literal which should just be included into the output. byteArrayBuilder.WriteByte((byte)currentChar); } } } return byteArrayBuilder.ToArray(); } } /// <summary> /// Writes all bytes in a byte array to a stream /// </summary> /// <param name="stream">The stream to write to</param> /// <param name="toWrite">The bytes to write to the <paramref name="stream"/></param> private static void WriteAllBytesToStream(Stream stream, byte[] toWrite) { stream.Write(toWrite, 0, toWrite.Length); } /// <summary> /// RFC 2045 states about robustness:<br/> /// <code> /// Control characters other than TAB, or CR and LF as parts of CRLF pairs, /// must not appear. The same is true for octets with decimal values greater /// than 126. If found in incoming quoted-printable data by a decoder, a /// robust implementation might exclude them from the decoded data and warn /// the user that illegal characters were discovered. /// </code> /// Control characters are defined in RFC 2396 as<br/> /// <c>control = US-ASCII coded characters 00-1F and 7F hexadecimal</c> /// </summary> /// <param name="input">String to be stripped from illegal control characters</param> /// <returns>A string with no illegal control characters</returns> /// <exception cref="ArgumentNullException">If <paramref name="input"/> is <see langword="null"/></exception> private static string RemoveIllegalControlCharacters(string input) { if(input == null) throw new ArgumentNullException("input"); // First we remove any \r or \n which is not part of a \r\n pair input = RemoveCarriageReturnAndNewLinewIfNotInPair(input); // Here only legal \r\n is left over // We now simply keep them, and the \t which is also allowed // \x0A = \n // \x0D = \r // \x09 = \t) return Regex.Replace(input, "[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]", ""); } /// <summary> /// This method will remove any \r and \n which is not paired as \r\n /// </summary> /// <param name="input">String to remove lonely \r and \n's from</param> /// <returns>A string without lonely \r and \n's</returns> /// <exception cref="ArgumentNullException">If <paramref name="input"/> is <see langword="null"/></exception> private static string RemoveCarriageReturnAndNewLinewIfNotInPair(string input) { if (input == null) throw new ArgumentNullException("input"); // Use this for building up the new string. This is used for performance instead // of altering the input string each time a illegal token is found StringBuilder newString = new StringBuilder(input.Length); for (int i = 0; i < input.Length; i++) { // There is a character after it // Check for lonely \r // There is a lonely \r if it is the last character in the input or if there // is no \n following it if (input[i] == '\r' && (i + 1 >= input.Length || input[i + 1] != '\n')) { // Illegal token \r found. Do not add it to the new string // Check for lonely \n // There is a lonely \n if \n is the first character or if there // is no \r in front of it } else if (input[i] == '\n' && (i - 1 < 0 || input[i - 1] != '\r')) { // Illegal token \n found. Do not add it to the new string } else { // No illegal tokens found. Simply insert the character we are at // in our new string newString.Append(input[i]); } } return newString.ToString(); } /// <summary> /// RFC 2045 says that a robust implementation should handle:<br/> /// <code> /// An "=" cannot be the ultimate or penultimate character in an encoded /// object. This could be handled as in case (2) above. /// </code> /// Case (2) is:<br/> /// <code> /// An "=" followed by a character that is neither a /// hexadecimal digit (including "abcdef") nor the CR character of a CRLF pair /// is illegal. This case can be the result of US-ASCII text having been /// included in a quoted-printable part of a message without itself having /// been subjected to quoted-printable encoding. A reasonable approach by a /// robust implementation might be to include the "=" character and the /// following character in the decoded data without any transformation and, if /// possible, indicate to the user that proper decoding was not possible at /// this point in the data. /// </code> /// </summary> /// <param name="decode"> /// The string to decode which cannot have length above or equal to 3 /// and must start with an equal sign. /// </param> /// <returns>A decoded byte array</returns> /// <exception cref="ArgumentNullException">If <paramref name="decode"/> is <see langword="null"/></exception> /// <exception cref="ArgumentException">Thrown if a the <paramref name="decode"/> parameter has length above 2 or does not start with an equal sign.</exception> private static byte[] DecodeEqualSignNotLongEnough(string decode) { if (decode == null) throw new ArgumentNullException("decode"); // We can only decode wrong length equal signs if (decode.Length >= 3) throw new ArgumentException("decode must have length lower than 3", "decode"); if(decode.Length <= 0) throw new ArgumentException("decode must have length lower at least 1", "decode"); // First char must be = if (decode[0] != '=') throw new ArgumentException("First part of decode must be an equal sign", "decode"); // We will now believe that the string sent to us, was actually not encoded // Therefore it must be in US-ASCII and we will return the bytes it corrosponds to return Encoding.ASCII.GetBytes(decode); } /// <summary> /// This helper method will decode a string of the form "=XX" where X is any character.<br/> /// This method will never fail, unless an argument of length not equal to three is passed. /// </summary> /// <param name="decode">The length 3 character that needs to be decoded</param> /// <returns>A decoded byte array</returns> /// <exception cref="ArgumentNullException">If <paramref name="decode"/> is <see langword="null"/></exception> /// <exception cref="ArgumentException">Thrown if a the <paramref name="decode"/> parameter does not have length 3 or does not start with an equal sign.</exception> private static byte[] DecodeEqualSign(string decode) { if (decode == null) throw new ArgumentNullException("decode"); // We can only decode the string if it has length 3 - other calls to this function is invalid if (decode.Length != 3) throw new ArgumentException("decode must have length 3", "decode"); // First char must be = if (decode[0] != '=') throw new ArgumentException("decode must start with an equal sign", "decode"); // There are two cases where an equal sign might appear // It might be a // - hex-string like =3D, denoting the character with hex value 3D // - it might be the last character on the line before a CRLF // pair, denoting a soft linebreak, which simply // splits the text up, because of the 76 chars per line restriction if (decode.Contains("\r\n")) { // Soft break detected // We want to return string.Empty which is equivalent to a zero-length byte array return new byte[0]; } // Hex string detected. Convertion needed. // It might be that the string located after the equal sign is not hex characters // An example: =JU // In that case we would like to catch the FormatException and do something else try { // The number part of the string is the last two digits. Here we simply remove the equal sign string numberString = decode.Substring(1); // Now we create a byte array with the converted number encoded in the string as a hex value (base 16) // This will also handle illegal encodings like =3d where the hex digits are not uppercase, // which is a robustness requirement from RFC 2045. byte[] oneByte = new[] { Convert.ToByte(numberString, 16) }; // Simply return our one byte byte array return oneByte; } catch (FormatException) { // RFC 2045 says about robust implementation: // An "=" followed by a character that is neither a // hexadecimal digit (including "abcdef") nor the CR // character of a CRLF pair is illegal. This case can be // the result of US-ASCII text having been included in a // quoted-printable part of a message without itself // having been subjected to quoted-printable encoding. A // reasonable approach by a robust implementation might be // to include the "=" character and the following // character in the decoded data without any // transformation and, if possible, indicate to the user // that proper decoding was not possible at this point in // the data. // So we choose to believe this is actually an un-encoded string // Therefore it must be in US-ASCII and we will return the bytes it corrosponds to return Encoding.ASCII.GetBytes(decode); } } } }
mit
corneliusweig/rollup
test/function/samples/member-expression-assignment-in-function/_config.js
388
const assert = require('assert'); module.exports = { description: 'detect side effect in member expression assignment when not top level', code(code) { assert.equal(code.indexOf('function set(key, value) { foo[key] = value; }') >= 0, true, code); assert.equal(code.indexOf('set("bar", 2);') >= 0, true, code); assert.equal(code.indexOf('set("qux", 3);') >= 0, true, code); } };
mit
abhiesa-tolexo/ElasticsearchBundle
Tests/app/fixture/Acme/TestBundle/Document/Category.php
464
<?php /* * This file is part of the ONGR package. * * (c) NFQ Technologies UAB <info@nfq.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace ONGR\ElasticsearchBundle\Tests\app\fixture\Acme\TestBundle\Document; use ONGR\ElasticsearchBundle\Annotation as ES; /** * Category document for testing. * * @ES\Object */ class Category { public $hiddenField; }
mit
jakzale/ogre
OgreMain/src/OgreRenderTarget.cpp
18652
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2013 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "OgreRenderTarget.h" #include "OgreStringConverter.h" #include "OgreViewport.h" #include "OgreException.h" #include "OgreLogManager.h" #include "OgreRenderTargetListener.h" #include "OgreRoot.h" #include "OgreRenderSystem.h" #include "OgreDepthBuffer.h" #include "OgreProfiler.h" namespace Ogre { RenderTarget::RenderTarget() : mPriority(OGRE_DEFAULT_RT_GROUP) , mDepthBufferPoolId(DepthBuffer::POOL_DEFAULT) , mDepthBuffer(0) , mActive(true) , mAutoUpdate(true) , mHwGamma(false) , mFSAA(0) { mTimer = Root::getSingleton().getTimer(); resetStatistics(); } RenderTarget::~RenderTarget() { // Delete viewports for (ViewportList::iterator i = mViewportList.begin(); i != mViewportList.end(); ++i) { fireViewportRemoved(i->second); OGRE_DELETE (*i).second; } //DepthBuffer keeps track of us, avoid a dangling pointer detachDepthBuffer(); // Write closing message LogManager::getSingleton().stream(LML_TRIVIAL) << "Render Target '" << mName << "' " << "Average FPS: " << mStats.avgFPS << " " << "Best FPS: " << mStats.bestFPS << " " << "Worst FPS: " << mStats.worstFPS; } const String& RenderTarget::getName(void) const { return mName; } void RenderTarget::getMetrics(unsigned int& width, unsigned int& height, unsigned int& colourDepth) { width = mWidth; height = mHeight; colourDepth = mColourDepth; } unsigned int RenderTarget::getWidth(void) const { return mWidth; } unsigned int RenderTarget::getHeight(void) const { return mHeight; } unsigned int RenderTarget::getColourDepth(void) const { return mColourDepth; } //----------------------------------------------------------------------- void RenderTarget::setDepthBufferPool( uint16 poolId ) { if( mDepthBufferPoolId != poolId ) { mDepthBufferPoolId = poolId; detachDepthBuffer(); } } //----------------------------------------------------------------------- uint16 RenderTarget::getDepthBufferPool() const { return mDepthBufferPoolId; } //----------------------------------------------------------------------- DepthBuffer* RenderTarget::getDepthBuffer() const { return mDepthBuffer; } //----------------------------------------------------------------------- bool RenderTarget::attachDepthBuffer( DepthBuffer *depthBuffer ) { bool retVal = false; if( (retVal = depthBuffer->isCompatible( this )) ) { detachDepthBuffer(); mDepthBuffer = depthBuffer; mDepthBuffer->_notifyRenderTargetAttached( this ); } return retVal; } //----------------------------------------------------------------------- void RenderTarget::detachDepthBuffer() { if( mDepthBuffer ) { mDepthBuffer->_notifyRenderTargetDetached( this ); mDepthBuffer = 0; } } //----------------------------------------------------------------------- void RenderTarget::_detachDepthBuffer() { mDepthBuffer = 0; } void RenderTarget::updateImpl(void) { _beginUpdate(); _updateAutoUpdatedViewports(true); _endUpdate(); } void RenderTarget::_beginUpdate() { // notify listeners (pre) firePreUpdate(); mStats.triangleCount = 0; mStats.batchCount = 0; } void RenderTarget::_updateAutoUpdatedViewports(bool updateStatistics) { // Go through viewports in Z-order // Tell each to refresh ViewportList::iterator it = mViewportList.begin(); while (it != mViewportList.end()) { Viewport* viewport = (*it).second; if(viewport->isAutoUpdated()) { _updateViewport(viewport,updateStatistics); } ++it; } } void RenderTarget::_endUpdate() { // notify listeners (post) firePostUpdate(); // Update statistics (always on top) updateStats(); } void RenderTarget::_updateViewport(Viewport* viewport, bool updateStatistics) { assert(viewport->getTarget() == this && "RenderTarget::_updateViewport the requested viewport is " "not bound to the rendertarget!"); fireViewportPreUpdate(viewport); viewport->update(); if(updateStatistics) { mStats.triangleCount += viewport->_getNumRenderedFaces(); mStats.batchCount += viewport->_getNumRenderedBatches(); } fireViewportPostUpdate(viewport); } void RenderTarget::_updateViewport(int zorder, bool updateStatistics) { ViewportList::iterator it = mViewportList.find(zorder); if (it != mViewportList.end()) { _updateViewport((*it).second,updateStatistics); } else { OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND,"No viewport with given zorder : " + StringConverter::toString(zorder), "RenderTarget::_updateViewport"); } } Viewport* RenderTarget::addViewport(Camera* cam, int ZOrder, float left, float top , float width , float height) { // Check no existing viewport with this Z-order ViewportList::iterator it = mViewportList.find(ZOrder); if (it != mViewportList.end()) { StringUtil::StrStreamType str; str << "Can't create another viewport for " << mName << " with Z-Order " << ZOrder << " because a viewport exists with this Z-Order already."; OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, str.str(), "RenderTarget::addViewport"); } // Add viewport to list // Order based on Z-Order Viewport* vp = OGRE_NEW Viewport(cam, this, left, top, width, height, ZOrder); mViewportList.insert(ViewportList::value_type(ZOrder, vp)); fireViewportAdded(vp); return vp; } //----------------------------------------------------------------------- void RenderTarget::removeViewport(int ZOrder) { ViewportList::iterator it = mViewportList.find(ZOrder); if (it != mViewportList.end()) { fireViewportRemoved((*it).second); OGRE_DELETE (*it).second; mViewportList.erase(ZOrder); } } void RenderTarget::removeAllViewports(void) { for (ViewportList::iterator it = mViewportList.begin(); it != mViewportList.end(); ++it) { fireViewportRemoved(it->second); OGRE_DELETE (*it).second; } mViewportList.clear(); } void RenderTarget::getStatistics(float& lastFPS, float& avgFPS, float& bestFPS, float& worstFPS) const { // Note - the will have been updated by the last render lastFPS = mStats.lastFPS; avgFPS = mStats.avgFPS; bestFPS = mStats.bestFPS; worstFPS = mStats.worstFPS; } const RenderTarget::FrameStats& RenderTarget::getStatistics(void) const { return mStats; } float RenderTarget::getLastFPS() const { return mStats.lastFPS; } float RenderTarget::getAverageFPS() const { return mStats.avgFPS; } float RenderTarget::getBestFPS() const { return mStats.bestFPS; } float RenderTarget::getWorstFPS() const { return mStats.worstFPS; } size_t RenderTarget::getTriangleCount(void) const { return mStats.triangleCount; } size_t RenderTarget::getBatchCount(void) const { return mStats.batchCount; } float RenderTarget::getBestFrameTime() const { return (float)mStats.bestFrameTime; } float RenderTarget::getWorstFrameTime() const { return (float)mStats.worstFrameTime; } void RenderTarget::resetStatistics(void) { mStats.avgFPS = 0.0; mStats.bestFPS = 0.0; mStats.lastFPS = 0.0; mStats.worstFPS = 999.0; mStats.triangleCount = 0; mStats.batchCount = 0; mStats.bestFrameTime = 999999; mStats.worstFrameTime = 0; mLastTime = mTimer->getMilliseconds(); mLastSecond = mLastTime; mFrameCount = 0; } void RenderTarget::updateStats(void) { ++mFrameCount; unsigned long thisTime = mTimer->getMilliseconds(); // check frame time unsigned long frameTime = thisTime - mLastTime ; mLastTime = thisTime ; mStats.bestFrameTime = std::min(mStats.bestFrameTime, frameTime); mStats.worstFrameTime = std::max(mStats.worstFrameTime, frameTime); // check if new second (update only once per second) if (thisTime - mLastSecond > 1000) { // new second - not 100% precise mStats.lastFPS = (float)mFrameCount / (float)(thisTime - mLastSecond) * 1000.0f; if (mStats.avgFPS == 0) mStats.avgFPS = mStats.lastFPS; else mStats.avgFPS = (mStats.avgFPS + mStats.lastFPS) / 2; // not strictly correct, but good enough mStats.bestFPS = std::max(mStats.bestFPS, mStats.lastFPS); mStats.worstFPS = std::min(mStats.worstFPS, mStats.lastFPS); mLastSecond = thisTime ; mFrameCount = 0; } } void RenderTarget::getCustomAttribute(const String& name, void* pData) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Attribute not found. " + name, " RenderTarget::getCustomAttribute"); } //----------------------------------------------------------------------- void RenderTarget::addListener(RenderTargetListener* listener) { mListeners.push_back(listener); } //----------------------------------------------------------------------- void RenderTarget::removeListener(RenderTargetListener* listener) { RenderTargetListenerList::iterator i; for (i = mListeners.begin(); i != mListeners.end(); ++i) { if (*i == listener) { mListeners.erase(i); break; } } } //----------------------------------------------------------------------- void RenderTarget::removeAllListeners(void) { mListeners.clear(); } //----------------------------------------------------------------------- void RenderTarget::firePreUpdate(void) { RenderTargetEvent evt; evt.source = this; RenderTargetListenerList::iterator i, iend; i = mListeners.begin(); iend = mListeners.end(); for(; i != iend; ++i) { (*i)->preRenderTargetUpdate(evt); } } //----------------------------------------------------------------------- void RenderTarget::firePostUpdate(void) { RenderTargetEvent evt; evt.source = this; RenderTargetListenerList::iterator i, iend; i = mListeners.begin(); iend = mListeners.end(); for(; i != iend; ++i) { (*i)->postRenderTargetUpdate(evt); } } //----------------------------------------------------------------------- unsigned short RenderTarget::getNumViewports(void) const { return (unsigned short)mViewportList.size(); } //----------------------------------------------------------------------- Viewport* RenderTarget::getViewport(unsigned short index) { assert (index < mViewportList.size() && "Index out of bounds"); ViewportList::iterator i = mViewportList.begin(); while (index--) ++i; return i->second; } //----------------------------------------------------------------------- Viewport* RenderTarget::getViewportByZOrder(int ZOrder) { ViewportList::iterator i = mViewportList.find(ZOrder); if(i == mViewportList.end()) { OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND,"No viewport with given zorder : " + StringConverter::toString(ZOrder), "RenderTarget::getViewportByZOrder"); } return i->second; } //----------------------------------------------------------------------- bool RenderTarget::hasViewportWithZOrder(int ZOrder) { ViewportList::iterator i = mViewportList.find(ZOrder); return i != mViewportList.end(); } //----------------------------------------------------------------------- bool RenderTarget::isActive() const { return mActive; } //----------------------------------------------------------------------- void RenderTarget::setActive( bool state ) { mActive = state; } //----------------------------------------------------------------------- void RenderTarget::fireViewportPreUpdate(Viewport* vp) { RenderTargetViewportEvent evt; evt.source = vp; RenderTargetListenerList::iterator i, iend; i = mListeners.begin(); iend = mListeners.end(); for(; i != iend; ++i) { (*i)->preViewportUpdate(evt); } } //----------------------------------------------------------------------- void RenderTarget::fireViewportPostUpdate(Viewport* vp) { RenderTargetViewportEvent evt; evt.source = vp; RenderTargetListenerList::iterator i, iend; i = mListeners.begin(); iend = mListeners.end(); for(; i != iend; ++i) { (*i)->postViewportUpdate(evt); } } //----------------------------------------------------------------------- void RenderTarget::fireViewportAdded(Viewport* vp) { RenderTargetViewportEvent evt; evt.source = vp; RenderTargetListenerList::iterator i, iend; i = mListeners.begin(); iend = mListeners.end(); for(; i != iend; ++i) { (*i)->viewportAdded(evt); } } //----------------------------------------------------------------------- void RenderTarget::fireViewportRemoved(Viewport* vp) { RenderTargetViewportEvent evt; evt.source = vp; // Make a temp copy of the listeners // some will want to remove themselves as listeners when they get this RenderTargetListenerList tempList = mListeners; RenderTargetListenerList::iterator i, iend; i = tempList.begin(); iend = tempList.end(); for(; i != iend; ++i) { (*i)->viewportRemoved(evt); } } //----------------------------------------------------------------------- String RenderTarget::writeContentsToTimestampedFile(const String& filenamePrefix, const String& filenameSuffix) { struct tm *pTime; time_t ctTime; time(&ctTime); pTime = localtime( &ctTime ); Ogre::StringStream oss; oss << std::setw(2) << std::setfill('0') << (pTime->tm_mon + 1) << std::setw(2) << std::setfill('0') << pTime->tm_mday << std::setw(2) << std::setfill('0') << (pTime->tm_year + 1900) << "_" << std::setw(2) << std::setfill('0') << pTime->tm_hour << std::setw(2) << std::setfill('0') << pTime->tm_min << std::setw(2) << std::setfill('0') << pTime->tm_sec << std::setw(3) << std::setfill('0') << (mTimer->getMilliseconds() % 1000); String filename = filenamePrefix + oss.str() + filenameSuffix; writeContentsToFile(filename); return filename; } //----------------------------------------------------------------------- void RenderTarget::writeContentsToFile(const String& filename) { PixelFormat pf = suggestPixelFormat(); uchar *data = OGRE_ALLOC_T(uchar, mWidth * mHeight * PixelUtil::getNumElemBytes(pf), MEMCATEGORY_RENDERSYS); PixelBox pb(mWidth, mHeight, 1, pf, data); copyContentsToMemory(pb); Image().loadDynamicImage(data, mWidth, mHeight, 1, pf, false, 1, 0).save(filename); OGRE_FREE(data, MEMCATEGORY_RENDERSYS); } //----------------------------------------------------------------------- void RenderTarget::_notifyCameraRemoved(const Camera* cam) { ViewportList::iterator i, iend; iend = mViewportList.end(); for (i = mViewportList.begin(); i != iend; ++i) { Viewport* v = i->second; if (v->getCamera() == cam) { // disable camera link v->setCamera(0); } } } //----------------------------------------------------------------------- void RenderTarget::setAutoUpdated(bool autoup) { mAutoUpdate = autoup; } //----------------------------------------------------------------------- bool RenderTarget::isAutoUpdated(void) const { return mAutoUpdate; } //----------------------------------------------------------------------- bool RenderTarget::isPrimary(void) const { // RenderWindow will override and return true for the primary window return false; } //----------------------------------------------------------------------- RenderTarget::Impl *RenderTarget::_getImpl() { return 0; } //----------------------------------------------------------------------- void RenderTarget::update(bool swap) { OgreProfileBeginGPUEvent("RenderTarget: " + getName()); // call implementation updateImpl(); if (swap) { // Swap buffers swapBuffers(Root::getSingleton().getRenderSystem()->getWaitForVerticalBlank()); } OgreProfileEndGPUEvent("RenderTarget: " + getName()); } }
mit
briandilley/jsonrpc4j
src/main/java/com/googlecode/jsonrpc4j/JsonRpcService.java
491
package com.googlecode.jsonrpc4j; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * Annotation to define the path of a JSON-RPC service. */ @Target(TYPE) @Retention(RUNTIME) public @interface JsonRpcService { /** * The path that the service is available at. * * @return the service path */ String value(); }
mit
never615/laravel-admin
src/Console/PublishCommand.php
913
<?php namespace Encore\Admin\Console; use Illuminate\Console\Command; class PublishCommand extends Command { /** * The console command name. * * @var string */ protected $signature = 'admin:publish {--force}'; /** * The console command description. * * @var string */ protected $description = "re-publish laravel-admin's assets, configuration, language and migration files. If you want overwrite the existing files, you can add the `--force` option"; /** * Execute the console command. * * @return void */ public function handle() { $force = $this->option('force'); $options = ['--provider' => 'Encore\Admin\AdminServiceProvider']; if ($force == true) { $options['--force'] = true; } $this->call('vendor:publish', $options); $this->call('view:clear'); } }
mit
eugenkiss/kotlinfx-ensemble
src/main/java/ensemble/samples/controls/text/TextFieldSample.java
2125
/* * Copyright (c) 2008, 2012 Oracle and/or its affiliates. * All rights reserved. Use is subject to license terms. * * This file is available and licensed under the following license: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the distribution. * - Neither the name of Oracle Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ensemble.samples.controls.text; import ensemble.Sample; import javafx.scene.control.TextField; /** * Demonstrates a TextField control that allows you to enter text. * * @see javafx.scene.control.TextField */ public class TextFieldSample extends Sample { public TextFieldSample() { TextField text = new TextField("Text"); text.setMaxSize(140, 20); getChildren().add(text); } }
mit
ouraspnet/ENode.Standard
src/ENode.Standard/Eventing/Impl/InMemoryEventStore.cs
5594
using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using ECommon.IO; using ECommon.Logging; namespace ENode.Eventing.Impl { public class InMemoryEventStore : IEventStore { private const int Editing = 1; private const int UnEditing = 0; private readonly ConcurrentDictionary<string, AggregateInfo> _aggregateInfoDict; private readonly ILogger _logger; public bool SupportBatchAppendEvent { get; set; } public InMemoryEventStore(ILoggerFactory loggerFactory) { _aggregateInfoDict = new ConcurrentDictionary<string, AggregateInfo>(); SupportBatchAppendEvent = true; _logger = loggerFactory.Create(GetType().FullName); } public IEnumerable<DomainEventStream> QueryAggregateEvents(string aggregateRootId, string aggregateRootTypeName, int minVersion, int maxVersion) { var eventStreams = new List<DomainEventStream>(); AggregateInfo aggregateInfo; if (!_aggregateInfoDict.TryGetValue(aggregateRootId, out aggregateInfo)) { return eventStreams; } var min = minVersion > 1 ? minVersion : 1; var max = maxVersion < aggregateInfo.CurrentVersion ? maxVersion : aggregateInfo.CurrentVersion; return aggregateInfo.EventDict.Where(x => x.Key >= min && x.Key <= max).Select(x => x.Value).ToList(); } public Task<AsyncTaskResult<EventAppendResult>> BatchAppendAsync(IEnumerable<DomainEventStream> eventStreams) { foreach (var eventStream in eventStreams) { var task = AppendAsync(eventStream); if (task.Result.Data != EventAppendResult.Success) { return task; } } return Task.FromResult(new AsyncTaskResult<EventAppendResult>(AsyncTaskStatus.Success, EventAppendResult.Success)); } public Task<AsyncTaskResult<EventAppendResult>> AppendAsync(DomainEventStream eventStream) { return Task.FromResult(new AsyncTaskResult<EventAppendResult>(AsyncTaskStatus.Success, null, Append(eventStream))); } public Task<AsyncTaskResult<DomainEventStream>> FindAsync(string aggregateRootId, int version) { return Task.FromResult(new AsyncTaskResult<DomainEventStream>(AsyncTaskStatus.Success, null, Find(aggregateRootId, version))); } public Task<AsyncTaskResult<DomainEventStream>> FindAsync(string aggregateRootId, string commandId) { return Task.FromResult(new AsyncTaskResult<DomainEventStream>(AsyncTaskStatus.Success, null, Find(aggregateRootId, commandId))); } public Task<AsyncTaskResult<IEnumerable<DomainEventStream>>> QueryAggregateEventsAsync(string aggregateRootId, string aggregateRootTypeName, int minVersion, int maxVersion) { return Task.FromResult(new AsyncTaskResult<IEnumerable<DomainEventStream>>(AsyncTaskStatus.Success, null, QueryAggregateEvents(aggregateRootId, aggregateRootTypeName, minVersion, maxVersion))); } private EventAppendResult Append(DomainEventStream eventStream) { var aggregateInfo = _aggregateInfoDict.GetOrAdd(eventStream.AggregateRootId, x => new AggregateInfo()); var originalStatus = Interlocked.CompareExchange(ref aggregateInfo.Status, Editing, UnEditing); if (originalStatus == aggregateInfo.Status) { return EventAppendResult.DuplicateEvent; } try { if (eventStream.Version == aggregateInfo.CurrentVersion + 1) { aggregateInfo.EventDict[eventStream.Version] = eventStream; aggregateInfo.CommandDict[eventStream.CommandId] = eventStream; aggregateInfo.CurrentVersion = eventStream.Version; return EventAppendResult.Success; } return EventAppendResult.DuplicateEvent; } finally { Interlocked.Exchange(ref aggregateInfo.Status, UnEditing); } } private DomainEventStream Find(string aggregateRootId, int version) { AggregateInfo aggregateInfo; if (!_aggregateInfoDict.TryGetValue(aggregateRootId, out aggregateInfo)) { return null; } DomainEventStream eventStream; return aggregateInfo.EventDict.TryGetValue(version, out eventStream) ? eventStream : null; } private DomainEventStream Find(string aggregateRootId, string commandId) { AggregateInfo aggregateInfo; if (!_aggregateInfoDict.TryGetValue(aggregateRootId, out aggregateInfo)) { return null; } DomainEventStream eventStream; return aggregateInfo.CommandDict.TryGetValue(commandId, out eventStream) ? eventStream : null; } class AggregateInfo { public int Status; public long CurrentVersion; public ConcurrentDictionary<int, DomainEventStream> EventDict = new ConcurrentDictionary<int, DomainEventStream>(); public ConcurrentDictionary<string, DomainEventStream> CommandDict = new ConcurrentDictionary<string, DomainEventStream>(); } } }
mit
yogeshsaroya/new-cdnjs
ajax/libs/dojo/1.5.1/_base.js
128
version https://git-lfs.github.com/spec/v1 oid sha256:6003581f5682a735209c7a30edef3f002544a2a3c402a4a5b41eef8b5338c412 size 599
mit
labboy0276/cli
tests/unit_tests/test-products.php
413
<?php use \Terminus\Products; class ProductsTest extends PHPUnit_Framework_TestCase { /** * @vcr products_instance */ function testProductsInstance() { $products = Products::instance(); $test = $products->getById('3b754bc2-48f8-4388-b5b5-2631098d03de'); $this->assertEquals('CiviCRM Starter Kit', $test['longname']); $test = $products->query(); $this->assertNotEmpty($test); } }
mit
Azure/azure-sdk-for-java
sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/TrackingUtil.java
908
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.microsoft.azure.eventhubs.impl; import org.apache.qpid.proton.engine.Session; public final class TrackingUtil { public static final String TRACKING_ID_TOKEN_SEPARATOR = "_"; private TrackingUtil() { } public static String getLinkName(final Session session) { // LN_1479943074829_ea9cac_8b_G27 final String linkNamePrefix = StringUtil.getRandomString("LN"); return session.getConnection() != null && !StringUtil.isNullOrEmpty(session.getConnection().getRemoteContainer()) ? linkNamePrefix.concat(TrackingUtil.TRACKING_ID_TOKEN_SEPARATOR).concat(session.getConnection().getRemoteContainer() .substring(Math.max(session.getConnection().getRemoteContainer().length() - 7, 0))) : linkNamePrefix; } }
mit
Beefster09/PlatE
lib/angelscript-sdk/source/as_context.cpp
159286
/* AngelCode Scripting Library Copyright (c) 2003-2016 Andreas Jonsson This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. The original version of this library can be located at: http://www.angelcode.com/angelscript/ Andreas Jonsson andreas@angelcode.com */ // // as_context.cpp // // This class handles the execution of the byte code // #include <math.h> // fmodf() pow() #include "as_config.h" #include "as_context.h" #include "as_scriptengine.h" #include "as_tokendef.h" #include "as_texts.h" #include "as_callfunc.h" #include "as_generic.h" #include "as_debug.h" // mkdir() #include "as_bytecode.h" #include "as_scriptobject.h" #ifdef _MSC_VER #pragma warning(disable:4702) // unreachable code #endif BEGIN_AS_NAMESPACE // We need at least 2 PTRs reserved for exception handling // We need at least 1 PTR reserved for calling system functions const int RESERVE_STACK = 2*AS_PTR_SIZE; // For each script function call we push 9 PTRs on the call stack const int CALLSTACK_FRAME_SIZE = 9; #if defined(AS_DEBUG) class asCDebugStats { public: asCDebugStats() { memset(instrCount, 0, sizeof(instrCount)); memset(instrCount2, 0, sizeof(instrCount2)); lastBC = 255; } ~asCDebugStats() { // This code writes out some statistics for the VM. // It's useful for determining what needs to be optimized. _mkdir("AS_DEBUG"); #if _MSC_VER >= 1500 && !defined(AS_MARMALADE) FILE *f; fopen_s(&f, "AS_DEBUG/stats.txt", "wt"); #else FILE *f = fopen("AS_DEBUG/stats.txt", "wt"); #endif if( f ) { // Output instruction statistics fprintf(f, "\nTotal count\n"); int n; for( n = 0; n < asBC_MAXBYTECODE; n++ ) { if( asBCInfo[n].name && instrCount[n] > 0 ) fprintf(f, "%-10.10s : %.0f\n", asBCInfo[n].name, instrCount[n]); } fprintf(f, "\nNever executed\n"); for( n = 0; n < asBC_MAXBYTECODE; n++ ) { if( asBCInfo[n].name && instrCount[n] == 0 ) fprintf(f, "%-10.10s\n", asBCInfo[n].name); } fprintf(f, "\nSequences\n"); for( n = 0; n < 256; n++ ) { if( asBCInfo[n].name ) { for( int m = 0; m < 256; m++ ) { if( instrCount2[n][m] ) fprintf(f, "%-10.10s, %-10.10s : %.0f\n", asBCInfo[n].name, asBCInfo[m].name, instrCount2[n][m]); } } } fclose(f); } } void Instr(asBYTE bc) { ++instrCount[bc]; ++instrCount2[lastBC][bc]; lastBC = bc; } // Instruction statistics double instrCount[256]; double instrCount2[256][256]; int lastBC; } stats; #endif // interface AS_API asIScriptContext *asGetActiveContext() { asCThreadLocalData *tld = asCThreadManager::GetLocalData(); // tld can be 0 if asGetActiveContext is called before any engine has been created. // Observe! I've seen a case where an application linked with the library twice // and thus ended up with two separate instances of the code and global variables. // The application somehow mixed the two instances so that a function called from // a script ended up calling asGetActiveContext from the other instance that had // never been initialized. if( tld == 0 || tld->activeContexts.GetLength() == 0 ) return 0; return tld->activeContexts[tld->activeContexts.GetLength()-1]; } // internal // Note: There is no asPopActiveContext(), just call tld->activeContexts.PopLast() instead asCThreadLocalData *asPushActiveContext(asIScriptContext *ctx) { asCThreadLocalData *tld = asCThreadManager::GetLocalData(); asASSERT( tld ); if( tld == 0 ) return 0; tld->activeContexts.PushLast(ctx); return tld; } asCContext::asCContext(asCScriptEngine *engine, bool holdRef) { m_refCount.set(1); m_holdEngineRef = holdRef; if( holdRef ) engine->AddRef(); m_engine = engine; m_status = asEXECUTION_UNINITIALIZED; m_stackBlockSize = 0; m_originalStackPointer = 0; m_inExceptionHandler = false; m_isStackMemoryNotAllocated = false; m_needToCleanupArgs = false; m_currentFunction = 0; m_callingSystemFunction = 0; m_regs.objectRegister = 0; m_initialFunction = 0; m_lineCallback = false; m_exceptionCallback = false; m_regs.doProcessSuspend = false; m_doSuspend = false; m_userData = 0; m_regs.ctx = this; } asCContext::~asCContext() { DetachEngine(); } // interface bool asCContext::IsNested(asUINT *nestCount) const { if( nestCount ) *nestCount = 0; asUINT c = GetCallstackSize(); if( c == 0 ) return false; // Search for a marker on the call stack // This loop starts at 2 because the 0th entry is not stored in m_callStack, // and then we need to subtract one more to get the base of each frame for( asUINT n = 2; n <= c; n++ ) { const asPWORD *s = m_callStack.AddressOf() + (c - n)*CALLSTACK_FRAME_SIZE; if( s && s[0] == 0 ) { if( nestCount ) (*nestCount)++; else return true; } } if( nestCount && *nestCount > 0 ) return true; return false; } // interface int asCContext::AddRef() const { return m_refCount.atomicInc(); } // interface int asCContext::Release() const { int r = m_refCount.atomicDec(); if( r == 0 ) { asDELETE(const_cast<asCContext*>(this),asCContext); return 0; } return r; } // internal void asCContext::DetachEngine() { if( m_engine == 0 ) return; // Clean up all calls, included nested ones do { // Abort any execution Abort(); // Free all resources Unprepare(); } while( IsNested() ); // Free the stack blocks for( asUINT n = 0; n < m_stackBlocks.GetLength(); n++ ) { if( m_stackBlocks[n] ) { #ifndef WIP_16BYTE_ALIGN asDELETEARRAY(m_stackBlocks[n]); #else asDELETEARRAYALIGNED(m_stackBlocks[n]); #endif } } m_stackBlocks.SetLength(0); m_stackBlockSize = 0; // Clean the user data for( asUINT n = 0; n < m_userData.GetLength(); n += 2 ) { if( m_userData[n+1] ) { for( asUINT c = 0; c < m_engine->cleanContextFuncs.GetLength(); c++ ) if( m_engine->cleanContextFuncs[c].type == m_userData[n] ) m_engine->cleanContextFuncs[c].cleanFunc(this); } } m_userData.SetLength(0); // Clear engine pointer if( m_holdEngineRef ) m_engine->Release(); m_engine = 0; } // interface asIScriptEngine *asCContext::GetEngine() const { return m_engine; } // interface void *asCContext::SetUserData(void *data, asPWORD type) { // As a thread might add a new new user data at the same time as another // it is necessary to protect both read and write access to the userData member ACQUIREEXCLUSIVE(m_engine->engineRWLock); // It is not intended to store a lot of different types of userdata, // so a more complex structure like a associative map would just have // more overhead than a simple array. for( asUINT n = 0; n < m_userData.GetLength(); n += 2 ) { if( m_userData[n] == type ) { void *oldData = reinterpret_cast<void*>(m_userData[n+1]); m_userData[n+1] = reinterpret_cast<asPWORD>(data); RELEASEEXCLUSIVE(m_engine->engineRWLock); return oldData; } } m_userData.PushLast(type); m_userData.PushLast(reinterpret_cast<asPWORD>(data)); RELEASEEXCLUSIVE(m_engine->engineRWLock); return 0; } // interface void *asCContext::GetUserData(asPWORD type) const { // There may be multiple threads reading, but when // setting the user data nobody must be reading. ACQUIRESHARED(m_engine->engineRWLock); for( asUINT n = 0; n < m_userData.GetLength(); n += 2 ) { if( m_userData[n] == type ) { RELEASESHARED(m_engine->engineRWLock); return reinterpret_cast<void*>(m_userData[n+1]); } } RELEASESHARED(m_engine->engineRWLock); return 0; } // interface asIScriptFunction *asCContext::GetSystemFunction() { return m_callingSystemFunction; } // interface int asCContext::Prepare(asIScriptFunction *func) { if( func == 0 ) { asCString str; str.Format(TXT_FAILED_IN_FUNC_s_WITH_s_d, "Prepare", "null", asNO_FUNCTION); m_engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf()); return asNO_FUNCTION; } if( m_status == asEXECUTION_ACTIVE || m_status == asEXECUTION_SUSPENDED ) { asCString str; str.Format(TXT_FAILED_IN_FUNC_s_WITH_s_d, "Prepare", func->GetDeclaration(true, true), asCONTEXT_ACTIVE); m_engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf()); return asCONTEXT_ACTIVE; } // Clean the stack if not done before if( m_status != asEXECUTION_FINISHED && m_status != asEXECUTION_UNINITIALIZED ) CleanStack(); // Release the returned object (if any) CleanReturnObject(); // Release the object if it is a script object if( m_initialFunction && m_initialFunction->objectType && (m_initialFunction->objectType->flags & asOBJ_SCRIPT_OBJECT) ) { asCScriptObject *obj = *(asCScriptObject**)&m_regs.stackFramePointer[0]; if( obj ) obj->Release(); *(asPWORD*)&m_regs.stackFramePointer[0] = 0; } if( m_initialFunction && m_initialFunction == func ) { // If the same function is executed again, we can skip a lot of the setup m_currentFunction = m_initialFunction; // Reset stack pointer m_regs.stackPointer = m_originalStackPointer; // Make sure the stack pointer is pointing to the original position, // otherwise something is wrong with the way it is being updated asASSERT( IsNested() || m_stackIndex > 0 || (m_regs.stackPointer == m_stackBlocks[0] + m_stackBlockSize) ); } else { asASSERT( m_engine ); // Make sure the function is from the same engine as the context to avoid mixups if( m_engine != func->GetEngine() ) { asCString str; str.Format(TXT_FAILED_IN_FUNC_s_WITH_s_d, "Prepare", func->GetDeclaration(true, true), asINVALID_ARG); m_engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf()); return asINVALID_ARG; } if( m_initialFunction ) { m_initialFunction->Release(); // Reset stack pointer m_regs.stackPointer = m_originalStackPointer; // Make sure the stack pointer is pointing to the original position, // otherwise something is wrong with the way it is being updated asASSERT( IsNested() || m_stackIndex > 0 || (m_regs.stackPointer == m_stackBlocks[0] + m_stackBlockSize) ); } // We trust the application not to pass anything else but a asCScriptFunction m_initialFunction = reinterpret_cast<asCScriptFunction *>(func); m_initialFunction->AddRef(); m_currentFunction = m_initialFunction; // TODO: runtime optimize: GetSpaceNeededForArguments() should be precomputed m_argumentsSize = m_currentFunction->GetSpaceNeededForArguments() + (m_currentFunction->objectType ? AS_PTR_SIZE : 0); // Reserve space for the arguments and return value if( m_currentFunction->DoesReturnOnStack() ) { m_returnValueSize = m_currentFunction->returnType.GetSizeInMemoryDWords(); m_argumentsSize += AS_PTR_SIZE; } else m_returnValueSize = 0; // Determine the minimum stack size needed int stackSize = m_argumentsSize + m_returnValueSize; if( m_currentFunction->scriptData ) stackSize += m_currentFunction->scriptData->stackNeeded; // Make sure there is enough space on the stack for the arguments and return value if( !ReserveStackSpace(stackSize) ) return asOUT_OF_MEMORY; } // Reset state // Most of the time the previous state will be asEXECUTION_FINISHED, in which case the values are already initialized if( m_status != asEXECUTION_FINISHED ) { m_exceptionLine = -1; m_exceptionFunction = 0; m_doAbort = false; m_doSuspend = false; m_regs.doProcessSuspend = m_lineCallback; m_externalSuspendRequest = false; } m_status = asEXECUTION_PREPARED; m_regs.programPointer = 0; // Reserve space for the arguments and return value m_regs.stackFramePointer = m_regs.stackPointer - m_argumentsSize - m_returnValueSize; m_originalStackPointer = m_regs.stackPointer; m_regs.stackPointer = m_regs.stackFramePointer; // Set arguments to 0 memset(m_regs.stackPointer, 0, 4*m_argumentsSize); if( m_returnValueSize ) { // Set the address of the location where the return value should be put asDWORD *ptr = m_regs.stackFramePointer; if( m_currentFunction->objectType ) ptr += AS_PTR_SIZE; *(void**)ptr = (void*)(m_regs.stackFramePointer + m_argumentsSize); } return asSUCCESS; } // Free all resources int asCContext::Unprepare() { if( m_status == asEXECUTION_ACTIVE || m_status == asEXECUTION_SUSPENDED ) return asCONTEXT_ACTIVE; // Only clean the stack if the context was prepared but not executed until the end if( m_status != asEXECUTION_UNINITIALIZED && m_status != asEXECUTION_FINISHED ) CleanStack(); asASSERT( m_needToCleanupArgs == false ); // Release the returned object (if any) CleanReturnObject(); // Release the object if it is a script object if( m_initialFunction && m_initialFunction->objectType && (m_initialFunction->objectType->flags & asOBJ_SCRIPT_OBJECT) ) { asCScriptObject *obj = *(asCScriptObject**)&m_regs.stackFramePointer[0]; if( obj ) obj->Release(); } // Release the initial function if( m_initialFunction ) { m_initialFunction->Release(); // Reset stack pointer m_regs.stackPointer = m_originalStackPointer; // Make sure the stack pointer is pointing to the original position, // otherwise something is wrong with the way it is being updated asASSERT( IsNested() || m_stackIndex > 0 || (m_regs.stackPointer == m_stackBlocks[0] + m_stackBlockSize) ); } // Clear function pointers m_initialFunction = 0; m_currentFunction = 0; m_exceptionFunction = 0; m_regs.programPointer = 0; // Reset status m_status = asEXECUTION_UNINITIALIZED; m_regs.stackFramePointer = 0; return 0; } asBYTE asCContext::GetReturnByte() { if( m_status != asEXECUTION_FINISHED ) return 0; asCDataType *dt = &m_initialFunction->returnType; if( dt->IsObject() || dt->IsFuncdef() || dt->IsReference() ) return 0; return *(asBYTE*)&m_regs.valueRegister; } asWORD asCContext::GetReturnWord() { if( m_status != asEXECUTION_FINISHED ) return 0; asCDataType *dt = &m_initialFunction->returnType; if( dt->IsObject() || dt->IsFuncdef() || dt->IsReference() ) return 0; return *(asWORD*)&m_regs.valueRegister; } asDWORD asCContext::GetReturnDWord() { if( m_status != asEXECUTION_FINISHED ) return 0; asCDataType *dt = &m_initialFunction->returnType; if( dt->IsObject() || dt->IsFuncdef() || dt->IsReference() ) return 0; return *(asDWORD*)&m_regs.valueRegister; } asQWORD asCContext::GetReturnQWord() { if( m_status != asEXECUTION_FINISHED ) return 0; asCDataType *dt = &m_initialFunction->returnType; if( dt->IsObject() || dt->IsFuncdef() || dt->IsReference() ) return 0; return m_regs.valueRegister; } float asCContext::GetReturnFloat() { if( m_status != asEXECUTION_FINISHED ) return 0; asCDataType *dt = &m_initialFunction->returnType; if( dt->IsObject() || dt->IsFuncdef() || dt->IsReference() ) return 0; return *(float*)&m_regs.valueRegister; } double asCContext::GetReturnDouble() { if( m_status != asEXECUTION_FINISHED ) return 0; asCDataType *dt = &m_initialFunction->returnType; if( dt->IsObject() || dt->IsFuncdef() || dt->IsReference() ) return 0; return *(double*)&m_regs.valueRegister; } void *asCContext::GetReturnAddress() { if( m_status != asEXECUTION_FINISHED ) return 0; asCDataType *dt = &m_initialFunction->returnType; if( dt->IsReference() ) return *(void**)&m_regs.valueRegister; else if( dt->IsObject() || dt->IsFuncdef() ) { if( m_initialFunction->DoesReturnOnStack() ) { // The address of the return value was passed as the first argument, after the object pointer int offset = 0; if( m_initialFunction->objectType ) offset += AS_PTR_SIZE; return *(void**)(&m_regs.stackFramePointer[offset]); } return m_regs.objectRegister; } return 0; } void *asCContext::GetReturnObject() { if( m_status != asEXECUTION_FINISHED ) return 0; asCDataType *dt = &m_initialFunction->returnType; if( !dt->IsObject() && !dt->IsFuncdef() ) return 0; if( dt->IsReference() ) return *(void**)(asPWORD)m_regs.valueRegister; else { if( m_initialFunction->DoesReturnOnStack() ) { // The address of the return value was passed as the first argument, after the object pointer int offset = 0; if( m_initialFunction->objectType ) offset += AS_PTR_SIZE; return *(void**)(&m_regs.stackFramePointer[offset]); } return m_regs.objectRegister; } } void *asCContext::GetAddressOfReturnValue() { if( m_status != asEXECUTION_FINISHED ) return 0; asCDataType *dt = &m_initialFunction->returnType; // An object is stored in the objectRegister if( !dt->IsReference() && (dt->IsObject() || dt->IsFuncdef()) ) { // Need to dereference objects if( !dt->IsObjectHandle() ) { if( m_initialFunction->DoesReturnOnStack() ) { // The address of the return value was passed as the first argument, after the object pointer int offset = 0; if( m_initialFunction->objectType ) offset += AS_PTR_SIZE; return *(void**)(&m_regs.stackFramePointer[offset]); } return *(void**)&m_regs.objectRegister; } return &m_regs.objectRegister; } // Primitives and references are stored in valueRegister return &m_regs.valueRegister; } int asCContext::SetObject(void *obj) { if( m_status != asEXECUTION_PREPARED ) return asCONTEXT_NOT_PREPARED; if( !m_initialFunction->objectType ) { m_status = asEXECUTION_ERROR; return asERROR; } asASSERT( *(asPWORD*)&m_regs.stackFramePointer[0] == 0 ); *(asPWORD*)&m_regs.stackFramePointer[0] = (asPWORD)obj; // TODO: This should be optional by having a flag where the application can chose whether it should be done or not // The flag could be named something like takeOwnership and have default value of true if( obj && (m_initialFunction->objectType->flags & asOBJ_SCRIPT_OBJECT) ) reinterpret_cast<asCScriptObject*>(obj)->AddRef(); return 0; } int asCContext::SetArgByte(asUINT arg, asBYTE value) { if( m_status != asEXECUTION_PREPARED ) return asCONTEXT_NOT_PREPARED; if( arg >= (unsigned)m_initialFunction->parameterTypes.GetLength() ) { m_status = asEXECUTION_ERROR; return asINVALID_ARG; } // Verify the type of the argument asCDataType *dt = &m_initialFunction->parameterTypes[arg]; if( dt->IsObject() || dt->IsFuncdef() || dt->IsReference() ) { m_status = asEXECUTION_ERROR; return asINVALID_TYPE; } if( dt->GetSizeInMemoryBytes() != 1 ) { m_status = asEXECUTION_ERROR; return asINVALID_TYPE; } // Determine the position of the argument int offset = 0; if( m_initialFunction->objectType ) offset += AS_PTR_SIZE; // If function returns object by value an extra pointer is pushed on the stack if( m_returnValueSize ) offset += AS_PTR_SIZE; for( asUINT n = 0; n < arg; n++ ) offset += m_initialFunction->parameterTypes[n].GetSizeOnStackDWords(); // Set the value *(asBYTE*)&m_regs.stackFramePointer[offset] = value; return 0; } int asCContext::SetArgWord(asUINT arg, asWORD value) { if( m_status != asEXECUTION_PREPARED ) return asCONTEXT_NOT_PREPARED; if( arg >= m_initialFunction->parameterTypes.GetLength() ) { m_status = asEXECUTION_ERROR; return asINVALID_ARG; } // Verify the type of the argument asCDataType *dt = &m_initialFunction->parameterTypes[arg]; if( dt->IsObject() || dt->IsFuncdef() || dt->IsReference() ) { m_status = asEXECUTION_ERROR; return asINVALID_TYPE; } if( dt->GetSizeInMemoryBytes() != 2 ) { m_status = asEXECUTION_ERROR; return asINVALID_TYPE; } // Determine the position of the argument int offset = 0; if( m_initialFunction->objectType ) offset += AS_PTR_SIZE; // If function returns object by value an extra pointer is pushed on the stack if( m_returnValueSize ) offset += AS_PTR_SIZE; for( asUINT n = 0; n < arg; n++ ) offset += m_initialFunction->parameterTypes[n].GetSizeOnStackDWords(); // Set the value *(asWORD*)&m_regs.stackFramePointer[offset] = value; return 0; } int asCContext::SetArgDWord(asUINT arg, asDWORD value) { if( m_status != asEXECUTION_PREPARED ) return asCONTEXT_NOT_PREPARED; if( arg >= (unsigned)m_initialFunction->parameterTypes.GetLength() ) { m_status = asEXECUTION_ERROR; return asINVALID_ARG; } // Verify the type of the argument asCDataType *dt = &m_initialFunction->parameterTypes[arg]; if( dt->IsObject() || dt->IsFuncdef() || dt->IsReference() ) { m_status = asEXECUTION_ERROR; return asINVALID_TYPE; } if( dt->GetSizeInMemoryBytes() != 4 ) { m_status = asEXECUTION_ERROR; return asINVALID_TYPE; } // Determine the position of the argument int offset = 0; if( m_initialFunction->objectType ) offset += AS_PTR_SIZE; // If function returns object by value an extra pointer is pushed on the stack if( m_returnValueSize ) offset += AS_PTR_SIZE; for( asUINT n = 0; n < arg; n++ ) offset += m_initialFunction->parameterTypes[n].GetSizeOnStackDWords(); // Set the value *(asDWORD*)&m_regs.stackFramePointer[offset] = value; return 0; } int asCContext::SetArgQWord(asUINT arg, asQWORD value) { if( m_status != asEXECUTION_PREPARED ) return asCONTEXT_NOT_PREPARED; if( arg >= (unsigned)m_initialFunction->parameterTypes.GetLength() ) { m_status = asEXECUTION_ERROR; return asINVALID_ARG; } // Verify the type of the argument asCDataType *dt = &m_initialFunction->parameterTypes[arg]; if( dt->IsObject() || dt->IsFuncdef() || dt->IsReference() ) { m_status = asEXECUTION_ERROR; return asINVALID_TYPE; } if( dt->GetSizeOnStackDWords() != 2 ) { m_status = asEXECUTION_ERROR; return asINVALID_TYPE; } // Determine the position of the argument int offset = 0; if( m_initialFunction->objectType ) offset += AS_PTR_SIZE; // If function returns object by value an extra pointer is pushed on the stack if( m_returnValueSize ) offset += AS_PTR_SIZE; for( asUINT n = 0; n < arg; n++ ) offset += m_initialFunction->parameterTypes[n].GetSizeOnStackDWords(); // Set the value *(asQWORD*)(&m_regs.stackFramePointer[offset]) = value; return 0; } int asCContext::SetArgFloat(asUINT arg, float value) { if( m_status != asEXECUTION_PREPARED ) return asCONTEXT_NOT_PREPARED; if( arg >= (unsigned)m_initialFunction->parameterTypes.GetLength() ) { m_status = asEXECUTION_ERROR; return asINVALID_ARG; } // Verify the type of the argument asCDataType *dt = &m_initialFunction->parameterTypes[arg]; if( dt->IsObject() || dt->IsFuncdef() || dt->IsReference() ) { m_status = asEXECUTION_ERROR; return asINVALID_TYPE; } if( dt->GetSizeOnStackDWords() != 1 ) { m_status = asEXECUTION_ERROR; return asINVALID_TYPE; } // Determine the position of the argument int offset = 0; if( m_initialFunction->objectType ) offset += AS_PTR_SIZE; // If function returns object by value an extra pointer is pushed on the stack if( m_returnValueSize ) offset += AS_PTR_SIZE; for( asUINT n = 0; n < arg; n++ ) offset += m_initialFunction->parameterTypes[n].GetSizeOnStackDWords(); // Set the value *(float*)(&m_regs.stackFramePointer[offset]) = value; return 0; } int asCContext::SetArgDouble(asUINT arg, double value) { if( m_status != asEXECUTION_PREPARED ) return asCONTEXT_NOT_PREPARED; if( arg >= (unsigned)m_initialFunction->parameterTypes.GetLength() ) { m_status = asEXECUTION_ERROR; return asINVALID_ARG; } // Verify the type of the argument asCDataType *dt = &m_initialFunction->parameterTypes[arg]; if( dt->IsObject() || dt->IsFuncdef() || dt->IsReference() ) { m_status = asEXECUTION_ERROR; return asINVALID_TYPE; } if( dt->GetSizeOnStackDWords() != 2 ) { m_status = asEXECUTION_ERROR; return asINVALID_TYPE; } // Determine the position of the argument int offset = 0; if( m_initialFunction->objectType ) offset += AS_PTR_SIZE; // If function returns object by value an extra pointer is pushed on the stack if( m_returnValueSize ) offset += AS_PTR_SIZE; for( asUINT n = 0; n < arg; n++ ) offset += m_initialFunction->parameterTypes[n].GetSizeOnStackDWords(); // Set the value *(double*)(&m_regs.stackFramePointer[offset]) = value; return 0; } int asCContext::SetArgAddress(asUINT arg, void *value) { if( m_status != asEXECUTION_PREPARED ) return asCONTEXT_NOT_PREPARED; if( arg >= (unsigned)m_initialFunction->parameterTypes.GetLength() ) { m_status = asEXECUTION_ERROR; return asINVALID_ARG; } // Verify the type of the argument asCDataType *dt = &m_initialFunction->parameterTypes[arg]; if( !dt->IsReference() && !dt->IsObjectHandle() ) { m_status = asEXECUTION_ERROR; return asINVALID_TYPE; } // Determine the position of the argument int offset = 0; if( m_initialFunction->objectType ) offset += AS_PTR_SIZE; // If function returns object by value an extra pointer is pushed on the stack if( m_returnValueSize ) offset += AS_PTR_SIZE; for( asUINT n = 0; n < arg; n++ ) offset += m_initialFunction->parameterTypes[n].GetSizeOnStackDWords(); // Set the value *(asPWORD*)(&m_regs.stackFramePointer[offset]) = (asPWORD)value; return 0; } int asCContext::SetArgObject(asUINT arg, void *obj) { if( m_status != asEXECUTION_PREPARED ) return asCONTEXT_NOT_PREPARED; if( arg >= (unsigned)m_initialFunction->parameterTypes.GetLength() ) { m_status = asEXECUTION_ERROR; return asINVALID_ARG; } // Verify the type of the argument asCDataType *dt = &m_initialFunction->parameterTypes[arg]; if( !dt->IsObject() && !dt->IsFuncdef() ) { m_status = asEXECUTION_ERROR; return asINVALID_TYPE; } // If the object should be sent by value we must make a copy of it if( !dt->IsReference() ) { if( dt->IsObjectHandle() ) { // Increase the reference counter if (obj && dt->IsFuncdef()) ((asIScriptFunction*)obj)->AddRef(); else { asSTypeBehaviour *beh = &CastToObjectType(dt->GetTypeInfo())->beh; if (obj && beh->addref) m_engine->CallObjectMethod(obj, beh->addref); } } else { obj = m_engine->CreateScriptObjectCopy(obj, dt->GetTypeInfo()); } } // Determine the position of the argument int offset = 0; if( m_initialFunction->objectType ) offset += AS_PTR_SIZE; // If function returns object by value an extra pointer is pushed on the stack if( m_returnValueSize ) offset += AS_PTR_SIZE; for( asUINT n = 0; n < arg; n++ ) offset += m_initialFunction->parameterTypes[n].GetSizeOnStackDWords(); // Set the value *(asPWORD*)(&m_regs.stackFramePointer[offset]) = (asPWORD)obj; return 0; } int asCContext::SetArgVarType(asUINT arg, void *ptr, int typeId) { if( m_status != asEXECUTION_PREPARED ) return asCONTEXT_NOT_PREPARED; if( arg >= (unsigned)m_initialFunction->parameterTypes.GetLength() ) { m_status = asEXECUTION_ERROR; return asINVALID_ARG; } // Verify the type of the argument asCDataType *dt = &m_initialFunction->parameterTypes[arg]; if( dt->GetTokenType() != ttQuestion ) { m_status = asEXECUTION_ERROR; return asINVALID_TYPE; } // Determine the position of the argument int offset = 0; if( m_initialFunction->objectType ) offset += AS_PTR_SIZE; // If function returns object by value an extra pointer is pushed on the stack if( m_returnValueSize ) offset += AS_PTR_SIZE; for( asUINT n = 0; n < arg; n++ ) offset += m_initialFunction->parameterTypes[n].GetSizeOnStackDWords(); // Set the typeId and pointer *(asPWORD*)(&m_regs.stackFramePointer[offset]) = (asPWORD)ptr; offset += AS_PTR_SIZE; *(int*)(&m_regs.stackFramePointer[offset]) = typeId; return 0; } // TODO: Instead of GetAddressOfArg, maybe we need a SetArgValue(int arg, void *value, bool takeOwnership) instead. // interface void *asCContext::GetAddressOfArg(asUINT arg) { if( m_status != asEXECUTION_PREPARED ) return 0; if( arg >= (unsigned)m_initialFunction->parameterTypes.GetLength() ) return 0; // Determine the position of the argument int offset = 0; if( m_initialFunction->objectType ) offset += AS_PTR_SIZE; // If function returns object by value an extra pointer is pushed on the stack if( m_returnValueSize ) offset += AS_PTR_SIZE; for( asUINT n = 0; n < arg; n++ ) offset += m_initialFunction->parameterTypes[n].GetSizeOnStackDWords(); // We should return the address of the location where the argument value will be placed // All registered types are always sent by reference, even if // the function is declared to receive the argument by value. return &m_regs.stackFramePointer[offset]; } int asCContext::Abort() { if( m_engine == 0 ) return asERROR; // TODO: multithread: Make thread safe. There is a chance that the status // changes to something else after being set to ABORTED here. if( m_status == asEXECUTION_SUSPENDED ) m_status = asEXECUTION_ABORTED; m_doSuspend = true; m_regs.doProcessSuspend = true; m_externalSuspendRequest = true; m_doAbort = true; return 0; } // interface int asCContext::Suspend() { // This function just sets some internal flags and is safe // to call from a secondary thread, even if the library has // been built without multi-thread support. if( m_engine == 0 ) return asERROR; m_doSuspend = true; m_externalSuspendRequest = true; m_regs.doProcessSuspend = true; return 0; } // interface int asCContext::Execute() { asASSERT( m_engine != 0 ); if( m_status != asEXECUTION_SUSPENDED && m_status != asEXECUTION_PREPARED ) { asCString str; str.Format(TXT_FAILED_IN_FUNC_s_d, "Execute", asCONTEXT_NOT_PREPARED); m_engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf()); return asCONTEXT_NOT_PREPARED; } m_status = asEXECUTION_ACTIVE; asCThreadLocalData *tld = asPushActiveContext((asIScriptContext *)this); if( m_regs.programPointer == 0 ) { if( m_currentFunction->funcType == asFUNC_DELEGATE ) { // Push the object pointer onto the stack asASSERT( m_regs.stackPointer - AS_PTR_SIZE >= m_stackBlocks[m_stackIndex] ); m_regs.stackPointer -= AS_PTR_SIZE; m_regs.stackFramePointer -= AS_PTR_SIZE; *(asPWORD*)m_regs.stackPointer = asPWORD(m_currentFunction->objForDelegate); // Make the call to the delegated object method m_currentFunction = m_currentFunction->funcForDelegate; } if( m_currentFunction->funcType == asFUNC_VIRTUAL || m_currentFunction->funcType == asFUNC_INTERFACE ) { // The currentFunction is a virtual method // Determine the true function from the object asCScriptObject *obj = *(asCScriptObject**)(asPWORD*)m_regs.stackFramePointer; if( obj == 0 ) { SetInternalException(TXT_NULL_POINTER_ACCESS); } else { asCObjectType *objType = obj->objType; asCScriptFunction *realFunc = 0; if( m_currentFunction->funcType == asFUNC_VIRTUAL ) { if( objType->virtualFunctionTable.GetLength() > (asUINT)m_currentFunction->vfTableIdx ) { realFunc = objType->virtualFunctionTable[m_currentFunction->vfTableIdx]; } } else { // Search the object type for a function that matches the interface function for( asUINT n = 0; n < objType->methods.GetLength(); n++ ) { asCScriptFunction *f2 = m_engine->scriptFunctions[objType->methods[n]]; if( f2->signatureId == m_currentFunction->signatureId ) { if( f2->funcType == asFUNC_VIRTUAL ) realFunc = objType->virtualFunctionTable[f2->vfTableIdx]; else realFunc = f2; break; } } } if( realFunc && realFunc->signatureId == m_currentFunction->signatureId ) m_currentFunction = realFunc; else SetInternalException(TXT_NULL_POINTER_ACCESS); } } else if( m_currentFunction->funcType == asFUNC_IMPORTED ) { int funcId = m_engine->importedFunctions[m_currentFunction->id & ~FUNC_IMPORTED]->boundFunctionId; if( funcId > 0 ) m_currentFunction = m_engine->scriptFunctions[funcId]; else SetInternalException(TXT_UNBOUND_FUNCTION); } if( m_currentFunction->funcType == asFUNC_SCRIPT ) { m_regs.programPointer = m_currentFunction->scriptData->byteCode.AddressOf(); // Set up the internal registers for executing the script function PrepareScriptFunction(); } else if( m_currentFunction->funcType == asFUNC_SYSTEM ) { // The current function is an application registered function // Call the function directly CallSystemFunction(m_currentFunction->id, this); // Was the call successful? if( m_status == asEXECUTION_ACTIVE ) { m_status = asEXECUTION_FINISHED; } } else { // This shouldn't happen unless there was an error in which // case an exception should have been raised already asASSERT( m_status == asEXECUTION_EXCEPTION ); } } asUINT gcPreObjects = 0; if( m_engine->ep.autoGarbageCollect ) m_engine->gc.GetStatistics(&gcPreObjects, 0, 0, 0, 0); while( m_status == asEXECUTION_ACTIVE ) ExecuteNext(); if( m_lineCallback ) { // Call the line callback one last time before leaving // so anyone listening can catch the state change CallLineCallback(); m_regs.doProcessSuspend = true; } else m_regs.doProcessSuspend = false; m_doSuspend = false; if( m_engine->ep.autoGarbageCollect ) { asUINT gcPosObjects = 0; m_engine->gc.GetStatistics(&gcPosObjects, 0, 0, 0, 0); if( gcPosObjects > gcPreObjects ) { // Execute as many steps as there were new objects created m_engine->GarbageCollect(asGC_ONE_STEP | asGC_DESTROY_GARBAGE | asGC_DETECT_GARBAGE, gcPosObjects - gcPreObjects); } else if( gcPosObjects > 0 ) { // Execute at least one step, even if no new objects were created m_engine->GarbageCollect(asGC_ONE_STEP | asGC_DESTROY_GARBAGE | asGC_DETECT_GARBAGE, 1); } } // Pop the active context asASSERT(tld && tld->activeContexts[tld->activeContexts.GetLength()-1] == this); if( tld ) tld->activeContexts.PopLast(); if( m_status == asEXECUTION_FINISHED ) { m_regs.objectType = m_initialFunction->returnType.GetTypeInfo(); return asEXECUTION_FINISHED; } if( m_doAbort ) { m_doAbort = false; m_status = asEXECUTION_ABORTED; return asEXECUTION_ABORTED; } if( m_status == asEXECUTION_SUSPENDED ) return asEXECUTION_SUSPENDED; if( m_status == asEXECUTION_EXCEPTION ) return asEXECUTION_EXCEPTION; return asERROR; } int asCContext::PushState() { // Only allow the state to be pushed when active // TODO: Can we support a suspended state too? So the reuse of // the context can be done outside the Execute() call? if( m_status != asEXECUTION_ACTIVE ) { // TODO: Write message. Wrong usage return asERROR; } // Push the current script function that is calling the system function PushCallState(); // Push the system function too, which will serve both as a marker and // informing which system function that created the nested call if( m_callStack.GetLength() == m_callStack.GetCapacity() ) { // Allocate space for 10 call states at a time to save time m_callStack.AllocateNoConstruct(m_callStack.GetLength() + 10*CALLSTACK_FRAME_SIZE, true); } m_callStack.SetLengthNoConstruct(m_callStack.GetLength() + CALLSTACK_FRAME_SIZE); // Need to push m_initialFunction as it must be restored later asPWORD *tmp = m_callStack.AddressOf() + m_callStack.GetLength() - CALLSTACK_FRAME_SIZE; tmp[0] = 0; tmp[1] = (asPWORD)m_callingSystemFunction; tmp[2] = (asPWORD)m_initialFunction; tmp[3] = (asPWORD)m_originalStackPointer; tmp[4] = (asPWORD)m_argumentsSize; // Need to push the value of registers so they can be restored tmp[5] = (asPWORD)asDWORD(m_regs.valueRegister); tmp[6] = (asPWORD)asDWORD(m_regs.valueRegister>>32); tmp[7] = (asPWORD)m_regs.objectRegister; tmp[8] = (asPWORD)m_regs.objectType; // Decrease stackpointer to prevent the top value from being overwritten m_regs.stackPointer -= 2; // Clear the initial function so that Prepare() knows it must do all validations m_initialFunction = 0; // After this the state should appear as if uninitialized m_callingSystemFunction = 0; m_regs.objectRegister = 0; m_regs.objectType = 0; // Set the status to uninitialized as application // should call Prepare() after this to reuse the context m_status = asEXECUTION_UNINITIALIZED; return asSUCCESS; } int asCContext::PopState() { if( !IsNested() ) return asERROR; // Clean up the current execution Unprepare(); // The topmost state must be a marker for nested call asASSERT( m_callStack[m_callStack.GetLength() - CALLSTACK_FRAME_SIZE] == 0 ); // Restore the previous state asPWORD *tmp = &m_callStack[m_callStack.GetLength() - CALLSTACK_FRAME_SIZE]; m_callingSystemFunction = reinterpret_cast<asCScriptFunction*>(tmp[1]); m_callStack.SetLength(m_callStack.GetLength() - CALLSTACK_FRAME_SIZE); // Restore the previous initial function and the associated values m_initialFunction = reinterpret_cast<asCScriptFunction*>(tmp[2]); m_originalStackPointer = (asDWORD*)tmp[3]; m_argumentsSize = (int)tmp[4]; m_regs.valueRegister = asQWORD(asDWORD(tmp[5])); m_regs.valueRegister |= asQWORD(tmp[6])<<32; m_regs.objectRegister = (void*)tmp[7]; m_regs.objectType = (asITypeInfo*)tmp[8]; // Calculate the returnValueSize if( m_initialFunction->DoesReturnOnStack() ) m_returnValueSize = m_initialFunction->returnType.GetSizeInMemoryDWords(); else m_returnValueSize = 0; // Pop the current script function. This will also restore the previous stack pointer PopCallState(); m_status = asEXECUTION_ACTIVE; return asSUCCESS; } void asCContext::PushCallState() { if( m_callStack.GetLength() == m_callStack.GetCapacity() ) { // Allocate space for 10 call states at a time to save time m_callStack.AllocateNoConstruct(m_callStack.GetLength() + 10*CALLSTACK_FRAME_SIZE, true); } m_callStack.SetLengthNoConstruct(m_callStack.GetLength() + CALLSTACK_FRAME_SIZE); // Separating the loads and stores limits data cache trash, and with a smart compiler // could turn into SIMD style loading/storing if available. // The compiler can't do this itself due to potential pointer aliasing between the pointers, // ie writing to tmp could overwrite the data contained in registers.stackFramePointer for example // for all the compiler knows. So introducing the local variable s, which is never referred to by // its address we avoid this issue. asPWORD s[5]; s[0] = (asPWORD)m_regs.stackFramePointer; s[1] = (asPWORD)m_currentFunction; s[2] = (asPWORD)m_regs.programPointer; s[3] = (asPWORD)m_regs.stackPointer; s[4] = m_stackIndex; asPWORD *tmp = m_callStack.AddressOf() + m_callStack.GetLength() - CALLSTACK_FRAME_SIZE; tmp[0] = s[0]; tmp[1] = s[1]; tmp[2] = s[2]; tmp[3] = s[3]; tmp[4] = s[4]; } void asCContext::PopCallState() { // See comments in PushCallState about pointer aliasing and data cache trashing asPWORD *tmp = m_callStack.AddressOf() + m_callStack.GetLength() - CALLSTACK_FRAME_SIZE; asPWORD s[5]; s[0] = tmp[0]; s[1] = tmp[1]; s[2] = tmp[2]; s[3] = tmp[3]; s[4] = tmp[4]; m_regs.stackFramePointer = (asDWORD*)s[0]; m_currentFunction = (asCScriptFunction*)s[1]; m_regs.programPointer = (asDWORD*)s[2]; m_regs.stackPointer = (asDWORD*)s[3]; m_stackIndex = (int)s[4]; m_callStack.SetLength(m_callStack.GetLength() - CALLSTACK_FRAME_SIZE); } // interface asUINT asCContext::GetCallstackSize() const { if( m_currentFunction == 0 ) return 0; // The current function is accessed at stackLevel 0 return asUINT(1 + m_callStack.GetLength() / CALLSTACK_FRAME_SIZE); } // interface asIScriptFunction *asCContext::GetFunction(asUINT stackLevel) { if( stackLevel >= GetCallstackSize() ) return 0; if( stackLevel == 0 ) return m_currentFunction; asPWORD *s = m_callStack.AddressOf() + (GetCallstackSize() - stackLevel - 1)*CALLSTACK_FRAME_SIZE; asCScriptFunction *func = (asCScriptFunction*)s[1]; return func; } // interface int asCContext::GetLineNumber(asUINT stackLevel, int *column, const char **sectionName) { if( stackLevel >= GetCallstackSize() ) return asINVALID_ARG; asCScriptFunction *func; asDWORD *bytePos; if( stackLevel == 0 ) { func = m_currentFunction; if( func->scriptData == 0 ) return 0; bytePos = m_regs.programPointer; } else { asPWORD *s = m_callStack.AddressOf() + (GetCallstackSize()-stackLevel-1)*CALLSTACK_FRAME_SIZE; func = (asCScriptFunction*)s[1]; if( func->scriptData == 0 ) return 0; bytePos = (asDWORD*)s[2]; // Subract 1 from the bytePos, because we want the line where // the call was made, and not the instruction after the call bytePos -= 1; } // For nested calls it is possible that func is null if( func == 0 ) { if( column ) *column = 0; if( sectionName ) *sectionName = 0; return 0; } int sectionIdx; asDWORD line = func->GetLineNumber(int(bytePos - func->scriptData->byteCode.AddressOf()), &sectionIdx); if( column ) *column = (line >> 20); if( sectionName ) { asASSERT( sectionIdx < int(m_engine->scriptSectionNames.GetLength()) ); if( sectionIdx >= 0 && asUINT(sectionIdx) < m_engine->scriptSectionNames.GetLength() ) *sectionName = m_engine->scriptSectionNames[sectionIdx]->AddressOf(); else *sectionName = 0; } return (line & 0xFFFFF); } // internal bool asCContext::ReserveStackSpace(asUINT size) { #ifdef WIP_16BYTE_ALIGN // Pad size to a multiple of MAX_TYPE_ALIGNMENT. const asUINT remainder = size % MAX_TYPE_ALIGNMENT; if(remainder != 0) { size = size + (MAX_TYPE_ALIGNMENT - (size % MAX_TYPE_ALIGNMENT)); } #endif // Make sure the first stack block is allocated if( m_stackBlocks.GetLength() == 0 ) { m_stackBlockSize = m_engine->initialContextStackSize; asASSERT( m_stackBlockSize > 0 ); #ifndef WIP_16BYTE_ALIGN asDWORD *stack = asNEWARRAY(asDWORD,m_stackBlockSize); #else asDWORD *stack = asNEWARRAYALIGNED(asDWORD, m_stackBlockSize, MAX_TYPE_ALIGNMENT); #endif if( stack == 0 ) { // Out of memory return false; } #ifdef WIP_16BYTE_ALIGN asASSERT( isAligned(stack, MAX_TYPE_ALIGNMENT) ); #endif m_stackBlocks.PushLast(stack); m_stackIndex = 0; m_regs.stackPointer = m_stackBlocks[0] + m_stackBlockSize; #ifdef WIP_16BYTE_ALIGN // Align the stack pointer. This is necessary as the m_stackBlockSize is not necessarily evenly divisable with the max alignment ((asPWORD&)m_regs.stackPointer) &= ~(MAX_TYPE_ALIGNMENT-1); asASSERT( isAligned(m_regs.stackPointer, MAX_TYPE_ALIGNMENT) ); #endif } // Check if there is enough space on the current stack block, otherwise move // to the next one. New and larger blocks will be allocated as necessary while( m_regs.stackPointer - (size + RESERVE_STACK) < m_stackBlocks[m_stackIndex] ) { // Make sure we don't allocate more space than allowed if( m_engine->ep.maximumContextStackSize ) { // This test will only stop growth once it has already crossed the limit if( m_stackBlockSize * ((1 << (m_stackIndex+1)) - 1) > m_engine->ep.maximumContextStackSize ) { m_isStackMemoryNotAllocated = true; // Set the stackFramePointer, even though the stackPointer wasn't updated m_regs.stackFramePointer = m_regs.stackPointer; SetInternalException(TXT_STACK_OVERFLOW); return false; } } m_stackIndex++; if( m_stackBlocks.GetLength() == m_stackIndex ) { // Allocate the new stack block, with twice the size of the previous #ifndef WIP_16BYTE_ALIGN asDWORD *stack = asNEWARRAY(asDWORD, (m_stackBlockSize << m_stackIndex)); #else asDWORD *stack = asNEWARRAYALIGNED(asDWORD, (m_stackBlockSize << m_stackIndex), MAX_TYPE_ALIGNMENT); #endif if( stack == 0 ) { // Out of memory m_isStackMemoryNotAllocated = true; // Set the stackFramePointer, even though the stackPointer wasn't updated m_regs.stackFramePointer = m_regs.stackPointer; SetInternalException(TXT_STACK_OVERFLOW); return false; } #ifdef WIP_16BYTE_ALIGN asASSERT( isAligned(stack, MAX_TYPE_ALIGNMENT) ); #endif m_stackBlocks.PushLast(stack); } // Update the stack pointer to point to the new block. // Leave enough room above the stackpointer to copy the arguments from the previous stackblock m_regs.stackPointer = m_stackBlocks[m_stackIndex] + (m_stackBlockSize<<m_stackIndex) - m_currentFunction->GetSpaceNeededForArguments() - (m_currentFunction->objectType ? AS_PTR_SIZE : 0) - (m_currentFunction->DoesReturnOnStack() ? AS_PTR_SIZE : 0); #ifdef WIP_16BYTE_ALIGN // Align the stack pointer (asPWORD&)m_regs.stackPointer &= ~(MAX_TYPE_ALIGNMENT-1); asASSERT( isAligned(m_regs.stackPointer, MAX_TYPE_ALIGNMENT) ); #endif } return true; } // internal void asCContext::CallScriptFunction(asCScriptFunction *func) { asASSERT( func->scriptData ); // Push the framepointer, function id and programCounter on the stack PushCallState(); // Update the current function and program position before increasing the stack // so the exception handler will know what to do if there is a stack overflow m_currentFunction = func; m_regs.programPointer = m_currentFunction->scriptData->byteCode.AddressOf(); PrepareScriptFunction(); } void asCContext::PrepareScriptFunction() { asASSERT( m_currentFunction->scriptData ); // Make sure there is space on the stack to execute the function asDWORD *oldStackPointer = m_regs.stackPointer; if( !ReserveStackSpace(m_currentFunction->scriptData->stackNeeded) ) return; // If a new stack block was allocated then we'll need to move // over the function arguments to the new block. if( m_regs.stackPointer != oldStackPointer ) { int numDwords = m_currentFunction->GetSpaceNeededForArguments() + (m_currentFunction->objectType ? AS_PTR_SIZE : 0) + (m_currentFunction->DoesReturnOnStack() ? AS_PTR_SIZE : 0); memcpy(m_regs.stackPointer, oldStackPointer, sizeof(asDWORD)*numDwords); } // Update framepointer m_regs.stackFramePointer = m_regs.stackPointer; // Set all object variables to 0 to guarantee that they are null before they are used // Only variables on the heap should be cleared. The rest will be cleared by calling the constructor asUINT n = m_currentFunction->scriptData->objVariablesOnHeap; while( n-- > 0 ) { int pos = m_currentFunction->scriptData->objVariablePos[n]; *(asPWORD*)&m_regs.stackFramePointer[-pos] = 0; } // Initialize the stack pointer with the space needed for local variables m_regs.stackPointer -= m_currentFunction->scriptData->variableSpace; // Call the line callback for each script function, to guarantee that infinitely recursive scripts can // be interrupted, even if the scripts have been compiled with asEP_BUILD_WITHOUT_LINE_CUES if( m_regs.doProcessSuspend ) { if( m_lineCallback ) CallLineCallback(); if( m_doSuspend ) m_status = asEXECUTION_SUSPENDED; } } void asCContext::CallInterfaceMethod(asCScriptFunction *func) { // Resolve the interface method using the current script type asCScriptObject *obj = *(asCScriptObject**)(asPWORD*)m_regs.stackPointer; if( obj == 0 ) { // Tell the exception handler to clean up the arguments to this method m_needToCleanupArgs = true; SetInternalException(TXT_NULL_POINTER_ACCESS); return; } asCObjectType *objType = obj->objType; // Search the object type for a function that matches the interface function asCScriptFunction *realFunc = 0; if( func->funcType == asFUNC_INTERFACE ) { // Find the offset for the interface's virtual function table chunk asUINT offset = 0; bool found = false; asCObjectType *findInterface = func->objectType; // TODO: runtime optimize: The list of interfaces should be ordered by the address // Then a binary search pattern can be used. asUINT intfCount = asUINT(objType->interfaces.GetLength()); for( asUINT n = 0; n < intfCount; n++ ) { if( objType->interfaces[n] == findInterface ) { offset = objType->interfaceVFTOffsets[n]; found = true; break; } } if( !found ) { // Tell the exception handler to clean up the arguments to this method m_needToCleanupArgs = true; SetInternalException(TXT_NULL_POINTER_ACCESS); return; } // Find the real function in the virtual table chunk with the found offset realFunc = objType->virtualFunctionTable[func->vfTableIdx + offset]; // Since the interface was implemented by the class, it shouldn't // be possible that the real function isn't found asASSERT( realFunc ); asASSERT( realFunc->signatureId == func->signatureId ); } else // if( func->funcType == asFUNC_VIRTUAL ) { realFunc = objType->virtualFunctionTable[func->vfTableIdx]; } // Then call the true script function CallScriptFunction(realFunc); } void asCContext::ExecuteNext() { asDWORD *l_bc = m_regs.programPointer; asDWORD *l_sp = m_regs.stackPointer; asDWORD *l_fp = m_regs.stackFramePointer; for(;;) { #ifdef AS_DEBUG // Gather statistics on executed bytecode stats.Instr(*(asBYTE*)l_bc); // Used to verify that the size of the instructions are correct asDWORD *old = l_bc; #endif // Remember to keep the cases in order and without // gaps, because that will make the switch faster. // It will be faster since only one lookup will be // made to find the correct jump destination. If not // in order, the switch will make two lookups. switch( *(asBYTE*)l_bc ) { //-------------- // memory access functions case asBC_PopPtr: // Pop a pointer from the stack l_sp += AS_PTR_SIZE; l_bc++; break; case asBC_PshGPtr: // Replaces PGA + RDSPtr l_sp -= AS_PTR_SIZE; *(asPWORD*)l_sp = *(asPWORD*)asBC_PTRARG(l_bc); l_bc += 1 + AS_PTR_SIZE; break; // Push a dword value on the stack case asBC_PshC4: --l_sp; *l_sp = asBC_DWORDARG(l_bc); l_bc += 2; break; // Push the dword value of a variable on the stack case asBC_PshV4: --l_sp; *l_sp = *(l_fp - asBC_SWORDARG0(l_bc)); l_bc++; break; // Push the address of a variable on the stack case asBC_PSF: l_sp -= AS_PTR_SIZE; *(asPWORD*)l_sp = asPWORD(l_fp - asBC_SWORDARG0(l_bc)); l_bc++; break; // Swap the top 2 pointers on the stack case asBC_SwapPtr: { asPWORD p = *(asPWORD*)l_sp; *(asPWORD*)l_sp = *(asPWORD*)(l_sp+AS_PTR_SIZE); *(asPWORD*)(l_sp+AS_PTR_SIZE) = p; l_bc++; } break; // Do a boolean not operation, modifying the value of the variable case asBC_NOT: #if AS_SIZEOF_BOOL == 1 { // Set the value to true if it is equal to 0 // We need to use volatile here to tell the compiler it cannot // change the order of read and write operations on the pointer. volatile asBYTE *ptr = (asBYTE*)(l_fp - asBC_SWORDARG0(l_bc)); asBYTE val = (ptr[0] == 0) ? VALUE_OF_BOOLEAN_TRUE : 0; ptr[0] = val; // The result is stored in the lower byte ptr[1] = 0; // Make sure the rest of the DWORD is 0 ptr[2] = 0; ptr[3] = 0; } #else *(l_fp - asBC_SWORDARG0(l_bc)) = (*(l_fp - asBC_SWORDARG0(l_bc)) == 0 ? VALUE_OF_BOOLEAN_TRUE : 0); #endif l_bc++; break; // Push the dword value of a global variable on the stack case asBC_PshG4: --l_sp; *l_sp = *(asDWORD*)asBC_PTRARG(l_bc); l_bc += 1 + AS_PTR_SIZE; break; // Load the address of a global variable in the register, then // copy the value of the global variable into a local variable case asBC_LdGRdR4: *(void**)&m_regs.valueRegister = (void*)asBC_PTRARG(l_bc); *(l_fp - asBC_SWORDARG0(l_bc)) = **(asDWORD**)&m_regs.valueRegister; l_bc += 1+AS_PTR_SIZE; break; //---------------- // path control instructions // Begin execution of a script function case asBC_CALL: { int i = asBC_INTARG(l_bc); l_bc += 2; asASSERT( i >= 0 ); asASSERT( (i & FUNC_IMPORTED) == 0 ); // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; CallScriptFunction(m_engine->scriptFunctions[i]); // Extract the values from the context again l_bc = m_regs.programPointer; l_sp = m_regs.stackPointer; l_fp = m_regs.stackFramePointer; // If status isn't active anymore then we must stop if( m_status != asEXECUTION_ACTIVE ) return; } break; // Return to the caller, and remove the arguments from the stack case asBC_RET: { // Return if this was the first function, or a nested execution if( m_callStack.GetLength() == 0 || m_callStack[m_callStack.GetLength() - CALLSTACK_FRAME_SIZE] == 0 ) { m_status = asEXECUTION_FINISHED; return; } asWORD w = asBC_WORDARG0(l_bc); // Read the old framepointer, functionid, and programCounter from the call stack PopCallState(); // Extract the values from the context again l_bc = m_regs.programPointer; l_sp = m_regs.stackPointer; l_fp = m_regs.stackFramePointer; // Pop arguments from stack l_sp += w; } break; // Jump to a relative position case asBC_JMP: l_bc += 2 + asBC_INTARG(l_bc); break; //---------------- // Conditional jumps // Jump to a relative position if the value in the register is 0 case asBC_JZ: if( *(int*)&m_regs.valueRegister == 0 ) l_bc += asBC_INTARG(l_bc) + 2; else l_bc += 2; break; // Jump to a relative position if the value in the register is not 0 case asBC_JNZ: if( *(int*)&m_regs.valueRegister != 0 ) l_bc += asBC_INTARG(l_bc) + 2; else l_bc += 2; break; // Jump to a relative position if the value in the register is negative case asBC_JS: if( *(int*)&m_regs.valueRegister < 0 ) l_bc += asBC_INTARG(l_bc) + 2; else l_bc += 2; break; // Jump to a relative position if the value in the register it not negative case asBC_JNS: if( *(int*)&m_regs.valueRegister >= 0 ) l_bc += asBC_INTARG(l_bc) + 2; else l_bc += 2; break; // Jump to a relative position if the value in the register is greater than 0 case asBC_JP: if( *(int*)&m_regs.valueRegister > 0 ) l_bc += asBC_INTARG(l_bc) + 2; else l_bc += 2; break; // Jump to a relative position if the value in the register is not greater than 0 case asBC_JNP: if( *(int*)&m_regs.valueRegister <= 0 ) l_bc += asBC_INTARG(l_bc) + 2; else l_bc += 2; break; //-------------------- // test instructions // If the value in the register is 0, then set the register to 1, else to 0 case asBC_TZ: #if AS_SIZEOF_BOOL == 1 { // Set the value to true if it is equal to 0 // We need to use volatile here to tell the compiler it cannot // change the order of read and write operations on valueRegister. volatile int *regPtr = (int*)&m_regs.valueRegister; volatile asBYTE *regBptr = (asBYTE*)&m_regs.valueRegister; asBYTE val = (regPtr[0] == 0) ? VALUE_OF_BOOLEAN_TRUE : 0; regBptr[0] = val; // The result is stored in the lower byte regBptr[1] = 0; // Make sure the rest of the register is 0 regBptr[2] = 0; regBptr[3] = 0; regBptr[4] = 0; regBptr[5] = 0; regBptr[6] = 0; regBptr[7] = 0; } #else *(int*)&m_regs.valueRegister = (*(int*)&m_regs.valueRegister == 0 ? VALUE_OF_BOOLEAN_TRUE : 0); #endif l_bc++; break; // If the value in the register is not 0, then set the register to 1, else to 0 case asBC_TNZ: #if AS_SIZEOF_BOOL == 1 { // Set the value to true if it is not equal to 0 // We need to use volatile here to tell the compiler it cannot // change the order of read and write operations on valueRegister. volatile int *regPtr = (int*)&m_regs.valueRegister; volatile asBYTE *regBptr = (asBYTE*)&m_regs.valueRegister; asBYTE val = (regPtr[0] == 0) ? 0 : VALUE_OF_BOOLEAN_TRUE; regBptr[0] = val; // The result is stored in the lower byte regBptr[1] = 0; // Make sure the rest of the register is 0 regBptr[2] = 0; regBptr[3] = 0; regBptr[4] = 0; regBptr[5] = 0; regBptr[6] = 0; regBptr[7] = 0; } #else *(int*)&m_regs.valueRegister = (*(int*)&m_regs.valueRegister == 0 ? 0 : VALUE_OF_BOOLEAN_TRUE); #endif l_bc++; break; // If the value in the register is negative, then set the register to 1, else to 0 case asBC_TS: #if AS_SIZEOF_BOOL == 1 { // Set the value to true if it is less than 0 // We need to use volatile here to tell the compiler it cannot // change the order of read and write operations on valueRegister. volatile int *regPtr = (int*)&m_regs.valueRegister; volatile asBYTE *regBptr = (asBYTE*)&m_regs.valueRegister; asBYTE val = (regPtr[0] < 0) ? VALUE_OF_BOOLEAN_TRUE : 0; regBptr[0] = val; // The result is stored in the lower byte regBptr[1] = 0; // Make sure the rest of the register is 0 regBptr[2] = 0; regBptr[3] = 0; regBptr[4] = 0; regBptr[5] = 0; regBptr[6] = 0; regBptr[7] = 0; } #else *(int*)&m_regs.valueRegister = (*(int*)&m_regs.valueRegister < 0 ? VALUE_OF_BOOLEAN_TRUE : 0); #endif l_bc++; break; // If the value in the register is not negative, then set the register to 1, else to 0 case asBC_TNS: #if AS_SIZEOF_BOOL == 1 { // Set the value to true if it is not less than 0 // We need to use volatile here to tell the compiler it cannot // change the order of read and write operations on valueRegister. volatile int *regPtr = (int*)&m_regs.valueRegister; volatile asBYTE *regBptr = (asBYTE*)&m_regs.valueRegister; asBYTE val = (regPtr[0] >= 0) ? VALUE_OF_BOOLEAN_TRUE : 0; regBptr[0] = val; // The result is stored in the lower byte regBptr[1] = 0; // Make sure the rest of the register is 0 regBptr[2] = 0; regBptr[3] = 0; regBptr[4] = 0; regBptr[5] = 0; regBptr[6] = 0; regBptr[7] = 0; } #else *(int*)&m_regs.valueRegister = (*(int*)&m_regs.valueRegister < 0 ? 0 : VALUE_OF_BOOLEAN_TRUE); #endif l_bc++; break; // If the value in the register is greater than 0, then set the register to 1, else to 0 case asBC_TP: #if AS_SIZEOF_BOOL == 1 { // Set the value to true if it is greater than 0 // We need to use volatile here to tell the compiler it cannot // change the order of read and write operations on valueRegister. volatile int *regPtr = (int*)&m_regs.valueRegister; volatile asBYTE *regBptr = (asBYTE*)&m_regs.valueRegister; asBYTE val = (regPtr[0] > 0) ? VALUE_OF_BOOLEAN_TRUE : 0; regBptr[0] = val; // The result is stored in the lower byte regBptr[1] = 0; // Make sure the rest of the register is 0 regBptr[2] = 0; regBptr[3] = 0; regBptr[4] = 0; regBptr[5] = 0; regBptr[6] = 0; regBptr[7] = 0; } #else *(int*)&m_regs.valueRegister = (*(int*)&m_regs.valueRegister > 0 ? VALUE_OF_BOOLEAN_TRUE : 0); #endif l_bc++; break; // If the value in the register is not greater than 0, then set the register to 1, else to 0 case asBC_TNP: #if AS_SIZEOF_BOOL == 1 { // Set the value to true if it is not greater than 0 // We need to use volatile here to tell the compiler it cannot // change the order of read and write operations on valueRegister. volatile int *regPtr = (int*)&m_regs.valueRegister; volatile asBYTE *regBptr = (asBYTE*)&m_regs.valueRegister; asBYTE val = (regPtr[0] <= 0) ? VALUE_OF_BOOLEAN_TRUE : 0; regBptr[0] = val; // The result is stored in the lower byte regBptr[1] = 0; // Make sure the rest of the register is 0 regBptr[2] = 0; regBptr[3] = 0; regBptr[4] = 0; regBptr[5] = 0; regBptr[6] = 0; regBptr[7] = 0; } #else *(int*)&m_regs.valueRegister = (*(int*)&m_regs.valueRegister > 0 ? 0 : VALUE_OF_BOOLEAN_TRUE); #endif l_bc++; break; //-------------------- // negate value // Negate the integer value in the variable case asBC_NEGi: *(l_fp - asBC_SWORDARG0(l_bc)) = asDWORD(-int(*(l_fp - asBC_SWORDARG0(l_bc)))); l_bc++; break; // Negate the float value in the variable case asBC_NEGf: *(float*)(l_fp - asBC_SWORDARG0(l_bc)) = -*(float*)(l_fp - asBC_SWORDARG0(l_bc)); l_bc++; break; // Negate the double value in the variable case asBC_NEGd: *(double*)(l_fp - asBC_SWORDARG0(l_bc)) = -*(double*)(l_fp - asBC_SWORDARG0(l_bc)); l_bc++; break; //------------------------- // Increment value pointed to by address in register // Increment the short value pointed to by the register case asBC_INCi16: (**(short**)&m_regs.valueRegister)++; l_bc++; break; // Increment the byte value pointed to by the register case asBC_INCi8: (**(char**)&m_regs.valueRegister)++; l_bc++; break; // Decrement the short value pointed to by the register case asBC_DECi16: (**(short**)&m_regs.valueRegister)--; l_bc++; break; // Decrement the byte value pointed to by the register case asBC_DECi8: (**(char**)&m_regs.valueRegister)--; l_bc++; break; // Increment the integer value pointed to by the register case asBC_INCi: ++(**(int**)&m_regs.valueRegister); l_bc++; break; // Decrement the integer value pointed to by the register case asBC_DECi: --(**(int**)&m_regs.valueRegister); l_bc++; break; // Increment the float value pointed to by the register case asBC_INCf: ++(**(float**)&m_regs.valueRegister); l_bc++; break; // Decrement the float value pointed to by the register case asBC_DECf: --(**(float**)&m_regs.valueRegister); l_bc++; break; // Increment the double value pointed to by the register case asBC_INCd: ++(**(double**)&m_regs.valueRegister); l_bc++; break; // Decrement the double value pointed to by the register case asBC_DECd: --(**(double**)&m_regs.valueRegister); l_bc++; break; // Increment the local integer variable case asBC_IncVi: (*(int*)(l_fp - asBC_SWORDARG0(l_bc)))++; l_bc++; break; // Decrement the local integer variable case asBC_DecVi: (*(int*)(l_fp - asBC_SWORDARG0(l_bc)))--; l_bc++; break; //-------------------- // bits instructions // Do a bitwise not on the value in the variable case asBC_BNOT: *(l_fp - asBC_SWORDARG0(l_bc)) = ~*(l_fp - asBC_SWORDARG0(l_bc)); l_bc++; break; // Do a bitwise and of two variables and store the result in a third variable case asBC_BAND: *(l_fp - asBC_SWORDARG0(l_bc)) = *(l_fp - asBC_SWORDARG1(l_bc)) & *(l_fp - asBC_SWORDARG2(l_bc)); l_bc += 2; break; // Do a bitwise or of two variables and store the result in a third variable case asBC_BOR: *(l_fp - asBC_SWORDARG0(l_bc)) = *(l_fp - asBC_SWORDARG1(l_bc)) | *(l_fp - asBC_SWORDARG2(l_bc)); l_bc += 2; break; // Do a bitwise xor of two variables and store the result in a third variable case asBC_BXOR: *(l_fp - asBC_SWORDARG0(l_bc)) = *(l_fp - asBC_SWORDARG1(l_bc)) ^ *(l_fp - asBC_SWORDARG2(l_bc)); l_bc += 2; break; // Do a logical shift left of two variables and store the result in a third variable case asBC_BSLL: *(l_fp - asBC_SWORDARG0(l_bc)) = *(l_fp - asBC_SWORDARG1(l_bc)) << *(l_fp - asBC_SWORDARG2(l_bc)); l_bc += 2; break; // Do a logical shift right of two variables and store the result in a third variable case asBC_BSRL: *(l_fp - asBC_SWORDARG0(l_bc)) = *(l_fp - asBC_SWORDARG1(l_bc)) >> *(l_fp - asBC_SWORDARG2(l_bc)); l_bc += 2; break; // Do an arithmetic shift right of two variables and store the result in a third variable case asBC_BSRA: *(l_fp - asBC_SWORDARG0(l_bc)) = int(*(l_fp - asBC_SWORDARG1(l_bc))) >> *(l_fp - asBC_SWORDARG2(l_bc)); l_bc += 2; break; case asBC_COPY: { void *d = (void*)*(asPWORD*)l_sp; l_sp += AS_PTR_SIZE; void *s = (void*)*(asPWORD*)l_sp; if( s == 0 || d == 0 ) { // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Raise exception SetInternalException(TXT_NULL_POINTER_ACCESS); return; } memcpy(d, s, asBC_WORDARG0(l_bc)*4); // replace the pointer on the stack with the lvalue *(asPWORD**)l_sp = (asPWORD*)d; } l_bc += 2; break; case asBC_PshC8: l_sp -= 2; *(asQWORD*)l_sp = asBC_QWORDARG(l_bc); l_bc += 3; break; case asBC_PshVPtr: l_sp -= AS_PTR_SIZE; *(asPWORD*)l_sp = *(asPWORD*)(l_fp - asBC_SWORDARG0(l_bc)); l_bc++; break; case asBC_RDSPtr: { // The pointer must not be null asPWORD a = *(asPWORD*)l_sp; if( a == 0 ) { m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; SetInternalException(TXT_NULL_POINTER_ACCESS); return; } // Pop an address from the stack, read a pointer from that address and push it on the stack *(asPWORD*)l_sp = *(asPWORD*)a; } l_bc++; break; //---------------------------- // Comparisons case asBC_CMPd: { // Do a comparison of the values, rather than a subtraction // in order to get proper behaviour for infinity values. double dbl1 = *(double*)(l_fp - asBC_SWORDARG0(l_bc)); double dbl2 = *(double*)(l_fp - asBC_SWORDARG1(l_bc)); if( dbl1 == dbl2 ) *(int*)&m_regs.valueRegister = 0; else if( dbl1 < dbl2 ) *(int*)&m_regs.valueRegister = -1; else *(int*)&m_regs.valueRegister = 1; l_bc += 2; } break; case asBC_CMPu: { asDWORD d1 = *(asDWORD*)(l_fp - asBC_SWORDARG0(l_bc)); asDWORD d2 = *(asDWORD*)(l_fp - asBC_SWORDARG1(l_bc)); if( d1 == d2 ) *(int*)&m_regs.valueRegister = 0; else if( d1 < d2 ) *(int*)&m_regs.valueRegister = -1; else *(int*)&m_regs.valueRegister = 1; l_bc += 2; } break; case asBC_CMPf: { // Do a comparison of the values, rather than a subtraction // in order to get proper behaviour for infinity values. float f1 = *(float*)(l_fp - asBC_SWORDARG0(l_bc)); float f2 = *(float*)(l_fp - asBC_SWORDARG1(l_bc)); if( f1 == f2 ) *(int*)&m_regs.valueRegister = 0; else if( f1 < f2 ) *(int*)&m_regs.valueRegister = -1; else *(int*)&m_regs.valueRegister = 1; l_bc += 2; } break; case asBC_CMPi: { int i1 = *(int*)(l_fp - asBC_SWORDARG0(l_bc)); int i2 = *(int*)(l_fp - asBC_SWORDARG1(l_bc)); if( i1 == i2 ) *(int*)&m_regs.valueRegister = 0; else if( i1 < i2 ) *(int*)&m_regs.valueRegister = -1; else *(int*)&m_regs.valueRegister = 1; l_bc += 2; } break; //---------------------------- // Comparisons with constant value case asBC_CMPIi: { int i1 = *(int*)(l_fp - asBC_SWORDARG0(l_bc)); int i2 = asBC_INTARG(l_bc); if( i1 == i2 ) *(int*)&m_regs.valueRegister = 0; else if( i1 < i2 ) *(int*)&m_regs.valueRegister = -1; else *(int*)&m_regs.valueRegister = 1; l_bc += 2; } break; case asBC_CMPIf: { // Do a comparison of the values, rather than a subtraction // in order to get proper behaviour for infinity values. float f1 = *(float*)(l_fp - asBC_SWORDARG0(l_bc)); float f2 = asBC_FLOATARG(l_bc); if( f1 == f2 ) *(int*)&m_regs.valueRegister = 0; else if( f1 < f2 ) *(int*)&m_regs.valueRegister = -1; else *(int*)&m_regs.valueRegister = 1; l_bc += 2; } break; case asBC_CMPIu: { asDWORD d1 = *(asDWORD*)(l_fp - asBC_SWORDARG0(l_bc)); asDWORD d2 = asBC_DWORDARG(l_bc); if( d1 == d2 ) *(int*)&m_regs.valueRegister = 0; else if( d1 < d2 ) *(int*)&m_regs.valueRegister = -1; else *(int*)&m_regs.valueRegister = 1; l_bc += 2; } break; case asBC_JMPP: l_bc += 1 + (*(int*)(l_fp - asBC_SWORDARG0(l_bc)))*2; break; case asBC_PopRPtr: *(asPWORD*)&m_regs.valueRegister = *(asPWORD*)l_sp; l_sp += AS_PTR_SIZE; l_bc++; break; case asBC_PshRPtr: l_sp -= AS_PTR_SIZE; *(asPWORD*)l_sp = *(asPWORD*)&m_regs.valueRegister; l_bc++; break; case asBC_STR: { // Get the string id from the argument asWORD w = asBC_WORDARG0(l_bc); // Push the string pointer on the stack const asCString &b = m_engine->GetConstantString(w); l_sp -= AS_PTR_SIZE; *(asPWORD*)l_sp = (asPWORD)b.AddressOf(); // Push the string length on the stack --l_sp; *l_sp = (asDWORD)b.GetLength(); l_bc++; } break; case asBC_CALLSYS: { // Get function ID from the argument int i = asBC_INTARG(l_bc); // Need to move the values back to the context as the called functions // may use the debug interface to inspect the registers m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; l_sp += CallSystemFunction(i, this); // Update the program position after the call so that line number is correct l_bc += 2; if( m_regs.doProcessSuspend ) { // Should the execution be suspended? if( m_doSuspend ) { m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; m_status = asEXECUTION_SUSPENDED; return; } // An exception might have been raised if( m_status != asEXECUTION_ACTIVE ) { m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; return; } } } break; case asBC_CALLBND: { // TODO: Clean-up: This code is very similar to asBC_CallPtr. Create a shared method for them // Get the function ID from the stack int i = asBC_INTARG(l_bc); asASSERT( i >= 0 ); asASSERT( i & FUNC_IMPORTED ); // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; int funcId = m_engine->importedFunctions[i & ~FUNC_IMPORTED]->boundFunctionId; if( funcId == -1 ) { // Need to update the program pointer for the exception handler m_regs.programPointer += 2; // Tell the exception handler to clean up the arguments to this function m_needToCleanupArgs = true; SetInternalException(TXT_UNBOUND_FUNCTION); return; } else { asCScriptFunction *func = m_engine->GetScriptFunction(funcId); if( func->funcType == asFUNC_SCRIPT ) { m_regs.programPointer += 2; CallScriptFunction(func); } else if( func->funcType == asFUNC_DELEGATE ) { // Push the object pointer on the stack. There is always a reserved space for this so // we don't don't need to worry about overflowing the allocated memory buffer asASSERT( m_regs.stackPointer - AS_PTR_SIZE >= m_stackBlocks[m_stackIndex] ); m_regs.stackPointer -= AS_PTR_SIZE; *(asPWORD*)m_regs.stackPointer = asPWORD(func->objForDelegate); // Call the delegated method if( func->funcForDelegate->funcType == asFUNC_SYSTEM ) { m_regs.stackPointer += CallSystemFunction(func->funcForDelegate->id, this); // Update program position after the call so the line number // is correct in case the system function queries it m_regs.programPointer += 2; } else { m_regs.programPointer += 2; // TODO: run-time optimize: The true method could be figured out when creating the delegate CallInterfaceMethod(func->funcForDelegate); } } else { asASSERT( func->funcType == asFUNC_SYSTEM ); m_regs.stackPointer += CallSystemFunction(func->id, this); // Update program position after the call so the line number // is correct in case the system function queries it m_regs.programPointer += 2; } } // Extract the values from the context again l_bc = m_regs.programPointer; l_sp = m_regs.stackPointer; l_fp = m_regs.stackFramePointer; // If status isn't active anymore then we must stop if( m_status != asEXECUTION_ACTIVE ) return; } break; case asBC_SUSPEND: if( m_regs.doProcessSuspend ) { if( m_lineCallback ) { m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; CallLineCallback(); } if( m_doSuspend ) { l_bc++; // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; m_status = asEXECUTION_SUSPENDED; return; } } l_bc++; break; case asBC_ALLOC: { asCObjectType *objType = (asCObjectType*)asBC_PTRARG(l_bc); int func = asBC_INTARG(l_bc+AS_PTR_SIZE); if( objType->flags & asOBJ_SCRIPT_OBJECT ) { // Need to move the values back to the context as the construction // of the script object may reuse the context for nested calls. m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Pre-allocate the memory asDWORD *mem = (asDWORD*)m_engine->CallAlloc(objType); // Pre-initialize the memory by calling the constructor for asCScriptObject ScriptObject_Construct(objType, (asCScriptObject*)mem); // Call the constructor to initalize the memory asCScriptFunction *f = m_engine->scriptFunctions[func]; asDWORD **a = (asDWORD**)*(asPWORD*)(m_regs.stackPointer + f->GetSpaceNeededForArguments()); if( a ) *a = mem; // Push the object pointer on the stack m_regs.stackPointer -= AS_PTR_SIZE; *(asPWORD*)m_regs.stackPointer = (asPWORD)mem; m_regs.programPointer += 2+AS_PTR_SIZE; CallScriptFunction(f); // Extract the values from the context again l_bc = m_regs.programPointer; l_sp = m_regs.stackPointer; l_fp = m_regs.stackFramePointer; // If status isn't active anymore then we must stop if( m_status != asEXECUTION_ACTIVE ) return; } else { // Pre-allocate the memory asDWORD *mem = (asDWORD*)m_engine->CallAlloc(objType); if( func ) { // Push the object pointer on the stack (it will be popped by the function) l_sp -= AS_PTR_SIZE; *(asPWORD*)l_sp = (asPWORD)mem; // Need to move the values back to the context as the called functions // may use the debug interface to inspect the registers m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; l_sp += CallSystemFunction(func, this); } // Pop the variable address from the stack asDWORD **a = (asDWORD**)*(asPWORD*)l_sp; l_sp += AS_PTR_SIZE; if( a ) *a = mem; l_bc += 2+AS_PTR_SIZE; if( m_regs.doProcessSuspend ) { // Should the execution be suspended? if( m_doSuspend ) { m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; m_status = asEXECUTION_SUSPENDED; return; } // An exception might have been raised if( m_status != asEXECUTION_ACTIVE ) { m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; m_engine->CallFree(mem); *a = 0; return; } } } } break; case asBC_FREE: { // Get the variable that holds the object handle/reference asPWORD *a = (asPWORD*)asPWORD(l_fp - asBC_SWORDARG0(l_bc)); if( *a ) { asCObjectType *objType = (asCObjectType*)asBC_PTRARG(l_bc); asSTypeBehaviour *beh = &objType->beh; // Need to move the values back to the context as the called functions // may use the debug interface to inspect the registers m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; if( objType->flags & asOBJ_REF ) { asASSERT( (objType->flags & asOBJ_NOCOUNT) || beh->release ); if( beh->release ) m_engine->CallObjectMethod((void*)(asPWORD)*a, beh->release); } else { if( beh->destruct ) m_engine->CallObjectMethod((void*)(asPWORD)*a, beh->destruct); else if( objType->flags & asOBJ_LIST_PATTERN ) m_engine->DestroyList((asBYTE*)(asPWORD)*a, objType); m_engine->CallFree((void*)(asPWORD)*a); } // Clear the variable *a = 0; } } l_bc += 1+AS_PTR_SIZE; break; case asBC_LOADOBJ: { // Move the object pointer from the object variable into the object register void **a = (void**)(l_fp - asBC_SWORDARG0(l_bc)); m_regs.objectType = 0; m_regs.objectRegister = *a; *a = 0; } l_bc++; break; case asBC_STOREOBJ: // Move the object pointer from the object register to the object variable *(asPWORD*)(l_fp - asBC_SWORDARG0(l_bc)) = asPWORD(m_regs.objectRegister); m_regs.objectRegister = 0; l_bc++; break; case asBC_GETOBJ: { // Read variable index from location on stack asPWORD *a = (asPWORD*)(l_sp + asBC_WORDARG0(l_bc)); asPWORD offset = *a; // Move pointer from variable to the same location on the stack asPWORD *v = (asPWORD*)(l_fp - offset); *a = *v; // Clear variable *v = 0; } l_bc++; break; case asBC_REFCPY: { asCObjectType *objType = (asCObjectType*)asBC_PTRARG(l_bc); asSTypeBehaviour *beh = &objType->beh; // Pop address of destination pointer from the stack void **d = (void**)*(asPWORD*)l_sp; l_sp += AS_PTR_SIZE; // Read wanted pointer from the stack void *s = (void*)*(asPWORD*)l_sp; // Need to move the values back to the context as the called functions // may use the debug interface to inspect the registers m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; if( !(objType->flags & asOBJ_NOCOUNT) ) { // Release previous object held by destination pointer if( *d != 0 ) m_engine->CallObjectMethod(*d, beh->release); // Increase ref counter of wanted object if( s != 0 ) m_engine->CallObjectMethod(s, beh->addref); } // Set the new object in the destination *d = s; } l_bc += 1+AS_PTR_SIZE; break; case asBC_CHKREF: { // Verify if the pointer on the stack is null // This is used when validating a pointer that an operator will work on asPWORD a = *(asPWORD*)l_sp; if( a == 0 ) { m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; SetInternalException(TXT_NULL_POINTER_ACCESS); return; } } l_bc++; break; case asBC_GETOBJREF: { // Get the location on the stack where the reference will be placed asPWORD *a = (asPWORD*)(l_sp + asBC_WORDARG0(l_bc)); // Replace the variable index with the object handle held in the variable *(asPWORD**)a = *(asPWORD**)(l_fp - *a); } l_bc++; break; case asBC_GETREF: { // Get the location on the stack where the reference will be placed asPWORD *a = (asPWORD*)(l_sp + asBC_WORDARG0(l_bc)); // Replace the variable index with the address of the variable *(asPWORD**)a = (asPWORD*)(l_fp - (int)*a); } l_bc++; break; case asBC_PshNull: // Push a null pointer on the stack l_sp -= AS_PTR_SIZE; *(asPWORD*)l_sp = 0; l_bc++; break; case asBC_ClrVPtr: // TODO: runtime optimize: Is this instruction really necessary? // CallScriptFunction() can clear the null handles upon entry, just as is done for // all other object variables // Clear pointer variable *(asPWORD*)(l_fp - asBC_SWORDARG0(l_bc)) = 0; l_bc++; break; case asBC_OBJTYPE: // Push the object type on the stack l_sp -= AS_PTR_SIZE; *(asPWORD*)l_sp = asBC_PTRARG(l_bc); l_bc += 1+AS_PTR_SIZE; break; case asBC_TYPEID: // Equivalent to PshC4, but kept as separate instruction for bytecode serialization --l_sp; *l_sp = asBC_DWORDARG(l_bc); l_bc += 2; break; case asBC_SetV4: *(l_fp - asBC_SWORDARG0(l_bc)) = asBC_DWORDARG(l_bc); l_bc += 2; break; case asBC_SetV8: *(asQWORD*)(l_fp - asBC_SWORDARG0(l_bc)) = asBC_QWORDARG(l_bc); l_bc += 3; break; case asBC_ADDSi: { // The pointer must not be null asPWORD a = *(asPWORD*)l_sp; if( a == 0 ) { m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; SetInternalException(TXT_NULL_POINTER_ACCESS); return; } // Add an offset to the pointer *(asPWORD*)l_sp = a + asBC_SWORDARG0(l_bc); } l_bc += 2; break; case asBC_CpyVtoV4: *(l_fp - asBC_SWORDARG0(l_bc)) = *(l_fp - asBC_SWORDARG1(l_bc)); l_bc += 2; break; case asBC_CpyVtoV8: *(asQWORD*)(l_fp - asBC_SWORDARG0(l_bc)) = *(asQWORD*)(l_fp - asBC_SWORDARG1(l_bc)); l_bc += 2; break; case asBC_CpyVtoR4: *(asDWORD*)&m_regs.valueRegister = *(asDWORD*)(l_fp - asBC_SWORDARG0(l_bc)); l_bc++; break; case asBC_CpyVtoR8: *(asQWORD*)&m_regs.valueRegister = *(asQWORD*)(l_fp - asBC_SWORDARG0(l_bc)); l_bc++; break; case asBC_CpyVtoG4: *(asDWORD*)asBC_PTRARG(l_bc) = *(asDWORD*)(l_fp - asBC_SWORDARG0(l_bc)); l_bc += 1 + AS_PTR_SIZE; break; case asBC_CpyRtoV4: *(asDWORD*)(l_fp - asBC_SWORDARG0(l_bc)) = *(asDWORD*)&m_regs.valueRegister; l_bc++; break; case asBC_CpyRtoV8: *(asQWORD*)(l_fp - asBC_SWORDARG0(l_bc)) = m_regs.valueRegister; l_bc++; break; case asBC_CpyGtoV4: *(asDWORD*)(l_fp - asBC_SWORDARG0(l_bc)) = *(asDWORD*)asBC_PTRARG(l_bc); l_bc += 1 + AS_PTR_SIZE; break; case asBC_WRTV1: // The pointer in the register points to a byte, and *(l_fp - offset) too **(asBYTE**)&m_regs.valueRegister = *(asBYTE*)(l_fp - asBC_SWORDARG0(l_bc)); l_bc++; break; case asBC_WRTV2: // The pointer in the register points to a word, and *(l_fp - offset) too **(asWORD**)&m_regs.valueRegister = *(asWORD*)(l_fp - asBC_SWORDARG0(l_bc)); l_bc++; break; case asBC_WRTV4: **(asDWORD**)&m_regs.valueRegister = *(l_fp - asBC_SWORDARG0(l_bc)); l_bc++; break; case asBC_WRTV8: **(asQWORD**)&m_regs.valueRegister = *(asQWORD*)(l_fp - asBC_SWORDARG0(l_bc)); l_bc++; break; case asBC_RDR1: { // The pointer in the register points to a byte, and *(l_fp - offset) will also point to a byte asBYTE *bPtr = (asBYTE*)(l_fp - asBC_SWORDARG0(l_bc)); bPtr[0] = **(asBYTE**)&m_regs.valueRegister; // read the byte bPtr[1] = 0; // 0 the rest of the DWORD bPtr[2] = 0; bPtr[3] = 0; } l_bc++; break; case asBC_RDR2: { // The pointer in the register points to a word, and *(l_fp - offset) will also point to a word asWORD *wPtr = (asWORD*)(l_fp - asBC_SWORDARG0(l_bc)); wPtr[0] = **(asWORD**)&m_regs.valueRegister; // read the word wPtr[1] = 0; // 0 the rest of the DWORD } l_bc++; break; case asBC_RDR4: *(asDWORD*)(l_fp - asBC_SWORDARG0(l_bc)) = **(asDWORD**)&m_regs.valueRegister; l_bc++; break; case asBC_RDR8: *(asQWORD*)(l_fp - asBC_SWORDARG0(l_bc)) = **(asQWORD**)&m_regs.valueRegister; l_bc++; break; case asBC_LDG: *(asPWORD*)&m_regs.valueRegister = asBC_PTRARG(l_bc); l_bc += 1+AS_PTR_SIZE; break; case asBC_LDV: *(asDWORD**)&m_regs.valueRegister = (l_fp - asBC_SWORDARG0(l_bc)); l_bc++; break; case asBC_PGA: l_sp -= AS_PTR_SIZE; *(asPWORD*)l_sp = asBC_PTRARG(l_bc); l_bc += 1+AS_PTR_SIZE; break; case asBC_CmpPtr: { // TODO: runtime optimize: This instruction should really just be an equals, and return true or false. // The instruction is only used for is and !is tests anyway. asPWORD p1 = *(asPWORD*)(l_fp - asBC_SWORDARG0(l_bc)); asPWORD p2 = *(asPWORD*)(l_fp - asBC_SWORDARG1(l_bc)); if( p1 == p2 ) *(int*)&m_regs.valueRegister = 0; else if( p1 < p2 ) *(int*)&m_regs.valueRegister = -1; else *(int*)&m_regs.valueRegister = 1; l_bc += 2; } break; case asBC_VAR: l_sp -= AS_PTR_SIZE; *(asPWORD*)l_sp = (asPWORD)asBC_SWORDARG0(l_bc); l_bc++; break; //---------------------------- // Type conversions case asBC_iTOf: *(float*)(l_fp - asBC_SWORDARG0(l_bc)) = float(*(int*)(l_fp - asBC_SWORDARG0(l_bc))); l_bc++; break; case asBC_fTOi: *(l_fp - asBC_SWORDARG0(l_bc)) = int(*(float*)(l_fp - asBC_SWORDARG0(l_bc))); l_bc++; break; case asBC_uTOf: *(float*)(l_fp - asBC_SWORDARG0(l_bc)) = float(*(l_fp - asBC_SWORDARG0(l_bc))); l_bc++; break; case asBC_fTOu: // We must cast to int first, because on some compilers the cast of a negative float value to uint result in 0 *(l_fp - asBC_SWORDARG0(l_bc)) = asUINT(int(*(float*)(l_fp - asBC_SWORDARG0(l_bc)))); l_bc++; break; case asBC_sbTOi: // *(l_fp - offset) points to a char, and will point to an int afterwards *(l_fp - asBC_SWORDARG0(l_bc)) = *(signed char*)(l_fp - asBC_SWORDARG0(l_bc)); l_bc++; break; case asBC_swTOi: // *(l_fp - offset) points to a short, and will point to an int afterwards *(l_fp - asBC_SWORDARG0(l_bc)) = *(short*)(l_fp - asBC_SWORDARG0(l_bc)); l_bc++; break; case asBC_ubTOi: // (l_fp - offset) points to a byte, and will point to an int afterwards *(l_fp - asBC_SWORDARG0(l_bc)) = *(asBYTE*)(l_fp - asBC_SWORDARG0(l_bc)); l_bc++; break; case asBC_uwTOi: // *(l_fp - offset) points to a word, and will point to an int afterwards *(l_fp - asBC_SWORDARG0(l_bc)) = *(asWORD*)(l_fp - asBC_SWORDARG0(l_bc)); l_bc++; break; case asBC_dTOi: *(l_fp - asBC_SWORDARG0(l_bc)) = int(*(double*)(l_fp - asBC_SWORDARG1(l_bc))); l_bc += 2; break; case asBC_dTOu: // We must cast to int first, because on some compilers the cast of a negative float value to uint result in 0 *(l_fp - asBC_SWORDARG0(l_bc)) = asUINT(int(*(double*)(l_fp - asBC_SWORDARG1(l_bc)))); l_bc += 2; break; case asBC_dTOf: *(float*)(l_fp - asBC_SWORDARG0(l_bc)) = float(*(double*)(l_fp - asBC_SWORDARG1(l_bc))); l_bc += 2; break; case asBC_iTOd: *(double*)(l_fp - asBC_SWORDARG0(l_bc)) = double(*(int*)(l_fp - asBC_SWORDARG1(l_bc))); l_bc += 2; break; case asBC_uTOd: *(double*)(l_fp - asBC_SWORDARG0(l_bc)) = double(*(asUINT*)(l_fp - asBC_SWORDARG1(l_bc))); l_bc += 2; break; case asBC_fTOd: *(double*)(l_fp - asBC_SWORDARG0(l_bc)) = double(*(float*)(l_fp - asBC_SWORDARG1(l_bc))); l_bc += 2; break; //------------------------------ // Math operations case asBC_ADDi: *(int*)(l_fp - asBC_SWORDARG0(l_bc)) = *(int*)(l_fp - asBC_SWORDARG1(l_bc)) + *(int*)(l_fp - asBC_SWORDARG2(l_bc)); l_bc += 2; break; case asBC_SUBi: *(int*)(l_fp - asBC_SWORDARG0(l_bc)) = *(int*)(l_fp - asBC_SWORDARG1(l_bc)) - *(int*)(l_fp - asBC_SWORDARG2(l_bc)); l_bc += 2; break; case asBC_MULi: *(int*)(l_fp - asBC_SWORDARG0(l_bc)) = *(int*)(l_fp - asBC_SWORDARG1(l_bc)) * *(int*)(l_fp - asBC_SWORDARG2(l_bc)); l_bc += 2; break; case asBC_DIVi: { int divider = *(int*)(l_fp - asBC_SWORDARG2(l_bc)); if( divider == 0 ) { // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Raise exception SetInternalException(TXT_DIVIDE_BY_ZERO); return; } else if( divider == -1 ) { // Need to check if the value that is divided is 0x80000000 // as dividing it with -1 will cause an overflow exception if( *(int*)(l_fp - asBC_SWORDARG1(l_bc)) == int(0x80000000) ) { // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Raise exception SetInternalException(TXT_DIVIDE_OVERFLOW); return; } } *(int*)(l_fp - asBC_SWORDARG0(l_bc)) = *(int*)(l_fp - asBC_SWORDARG1(l_bc)) / divider; } l_bc += 2; break; case asBC_MODi: { int divider = *(int*)(l_fp - asBC_SWORDARG2(l_bc)); if( divider == 0 ) { // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Raise exception SetInternalException(TXT_DIVIDE_BY_ZERO); return; } else if( divider == -1 ) { // Need to check if the value that is divided is 0x80000000 // as dividing it with -1 will cause an overflow exception if( *(int*)(l_fp - asBC_SWORDARG1(l_bc)) == int(0x80000000) ) { // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Raise exception SetInternalException(TXT_DIVIDE_OVERFLOW); return; } } *(int*)(l_fp - asBC_SWORDARG0(l_bc)) = *(int*)(l_fp - asBC_SWORDARG1(l_bc)) % divider; } l_bc += 2; break; case asBC_ADDf: *(float*)(l_fp - asBC_SWORDARG0(l_bc)) = *(float*)(l_fp - asBC_SWORDARG1(l_bc)) + *(float*)(l_fp - asBC_SWORDARG2(l_bc)); l_bc += 2; break; case asBC_SUBf: *(float*)(l_fp - asBC_SWORDARG0(l_bc)) = *(float*)(l_fp - asBC_SWORDARG1(l_bc)) - *(float*)(l_fp - asBC_SWORDARG2(l_bc)); l_bc += 2; break; case asBC_MULf: *(float*)(l_fp - asBC_SWORDARG0(l_bc)) = *(float*)(l_fp - asBC_SWORDARG1(l_bc)) * *(float*)(l_fp - asBC_SWORDARG2(l_bc)); l_bc += 2; break; case asBC_DIVf: { float divider = *(float*)(l_fp - asBC_SWORDARG2(l_bc)); if( divider == 0 ) { // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Raise exception SetInternalException(TXT_DIVIDE_BY_ZERO); return; } *(float*)(l_fp - asBC_SWORDARG0(l_bc)) = *(float*)(l_fp - asBC_SWORDARG1(l_bc)) / divider; } l_bc += 2; break; case asBC_MODf: { float divider = *(float*)(l_fp - asBC_SWORDARG2(l_bc)); if( divider == 0 ) { // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Raise exception SetInternalException(TXT_DIVIDE_BY_ZERO); return; } *(float*)(l_fp - asBC_SWORDARG0(l_bc)) = fmodf(*(float*)(l_fp - asBC_SWORDARG1(l_bc)), divider); } l_bc += 2; break; case asBC_ADDd: *(double*)(l_fp - asBC_SWORDARG0(l_bc)) = *(double*)(l_fp - asBC_SWORDARG1(l_bc)) + *(double*)(l_fp - asBC_SWORDARG2(l_bc)); l_bc += 2; break; case asBC_SUBd: *(double*)(l_fp - asBC_SWORDARG0(l_bc)) = *(double*)(l_fp - asBC_SWORDARG1(l_bc)) - *(double*)(l_fp - asBC_SWORDARG2(l_bc)); l_bc += 2; break; case asBC_MULd: *(double*)(l_fp - asBC_SWORDARG0(l_bc)) = *(double*)(l_fp - asBC_SWORDARG1(l_bc)) * *(double*)(l_fp - asBC_SWORDARG2(l_bc)); l_bc += 2; break; case asBC_DIVd: { double divider = *(double*)(l_fp - asBC_SWORDARG2(l_bc)); if( divider == 0 ) { // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Raise exception SetInternalException(TXT_DIVIDE_BY_ZERO); return; } *(double*)(l_fp - asBC_SWORDARG0(l_bc)) = *(double*)(l_fp - asBC_SWORDARG1(l_bc)) / divider; l_bc += 2; } break; case asBC_MODd: { double divider = *(double*)(l_fp - asBC_SWORDARG2(l_bc)); if( divider == 0 ) { // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Raise exception SetInternalException(TXT_DIVIDE_BY_ZERO); return; } *(double*)(l_fp - asBC_SWORDARG0(l_bc)) = fmod(*(double*)(l_fp - asBC_SWORDARG1(l_bc)), divider); l_bc += 2; } break; //------------------------------ // Math operations with constant value case asBC_ADDIi: *(int*)(l_fp - asBC_SWORDARG0(l_bc)) = *(int*)(l_fp - asBC_SWORDARG1(l_bc)) + asBC_INTARG(l_bc+1); l_bc += 3; break; case asBC_SUBIi: *(int*)(l_fp - asBC_SWORDARG0(l_bc)) = *(int*)(l_fp - asBC_SWORDARG1(l_bc)) - asBC_INTARG(l_bc+1); l_bc += 3; break; case asBC_MULIi: *(int*)(l_fp - asBC_SWORDARG0(l_bc)) = *(int*)(l_fp - asBC_SWORDARG1(l_bc)) * asBC_INTARG(l_bc+1); l_bc += 3; break; case asBC_ADDIf: *(float*)(l_fp - asBC_SWORDARG0(l_bc)) = *(float*)(l_fp - asBC_SWORDARG1(l_bc)) + asBC_FLOATARG(l_bc+1); l_bc += 3; break; case asBC_SUBIf: *(float*)(l_fp - asBC_SWORDARG0(l_bc)) = *(float*)(l_fp - asBC_SWORDARG1(l_bc)) - asBC_FLOATARG(l_bc+1); l_bc += 3; break; case asBC_MULIf: *(float*)(l_fp - asBC_SWORDARG0(l_bc)) = *(float*)(l_fp - asBC_SWORDARG1(l_bc)) * asBC_FLOATARG(l_bc+1); l_bc += 3; break; //----------------------------------- case asBC_SetG4: *(asDWORD*)asBC_PTRARG(l_bc) = asBC_DWORDARG(l_bc+AS_PTR_SIZE); l_bc += 2 + AS_PTR_SIZE; break; case asBC_ChkRefS: { // Verify if the pointer on the stack refers to a non-null value // This is used to validate a reference to a handle asPWORD *a = (asPWORD*)*(asPWORD*)l_sp; if( *a == 0 ) { m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; SetInternalException(TXT_NULL_POINTER_ACCESS); return; } } l_bc++; break; case asBC_ChkNullV: { // Verify if variable (on the stack) is not null asDWORD *a = *(asDWORD**)(l_fp - asBC_SWORDARG0(l_bc)); if( a == 0 ) { m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; SetInternalException(TXT_NULL_POINTER_ACCESS); return; } } l_bc++; break; case asBC_CALLINTF: { int i = asBC_INTARG(l_bc); l_bc += 2; asASSERT( i >= 0 ); asASSERT( (i & FUNC_IMPORTED) == 0 ); // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; CallInterfaceMethod(m_engine->GetScriptFunction(i)); // Extract the values from the context again l_bc = m_regs.programPointer; l_sp = m_regs.stackPointer; l_fp = m_regs.stackFramePointer; // If status isn't active anymore then we must stop if( m_status != asEXECUTION_ACTIVE ) return; } break; case asBC_iTOb: { // *(l_fp - offset) points to an int, and will point to a byte afterwards // We need to use volatile here to tell the compiler not to rearrange // read and write operations during optimizations. volatile asDWORD val = *(l_fp - asBC_SWORDARG0(l_bc)); volatile asBYTE *bPtr = (asBYTE*)(l_fp - asBC_SWORDARG0(l_bc)); bPtr[0] = (asBYTE)val; // write the byte bPtr[1] = 0; // 0 the rest of the DWORD bPtr[2] = 0; bPtr[3] = 0; } l_bc++; break; case asBC_iTOw: { // *(l_fp - offset) points to an int, and will point to word afterwards // We need to use volatile here to tell the compiler not to rearrange // read and write operations during optimizations. volatile asDWORD val = *(l_fp - asBC_SWORDARG0(l_bc)); volatile asWORD *wPtr = (asWORD*)(l_fp - asBC_SWORDARG0(l_bc)); wPtr[0] = (asWORD)val; // write the word wPtr[1] = 0; // 0 the rest of the DWORD } l_bc++; break; case asBC_SetV1: // TODO: This is exactly the same as SetV4. This is a left over from the time // when the bytecode instructions were more tightly packed. It can now // be removed. When removing it, make sure the value is correctly converted // on big-endian CPUs. // The byte is already stored correctly in the argument *(l_fp - asBC_SWORDARG0(l_bc)) = asBC_DWORDARG(l_bc); l_bc += 2; break; case asBC_SetV2: // TODO: This is exactly the same as SetV4. This is a left over from the time // when the bytecode instructions were more tightly packed. It can now // be removed. When removing it, make sure the value is correctly converted // on big-endian CPUs. // The word is already stored correctly in the argument *(l_fp - asBC_SWORDARG0(l_bc)) = asBC_DWORDARG(l_bc); l_bc += 2; break; case asBC_Cast: // Cast the handle at the top of the stack to the type in the argument { asDWORD **a = (asDWORD**)*(asPWORD*)l_sp; if( a && *a ) { asDWORD typeId = asBC_DWORDARG(l_bc); asCScriptObject *obj = (asCScriptObject *)* a; asCObjectType *objType = obj->objType; asCObjectType *to = m_engine->GetObjectTypeFromTypeId(typeId); // This instruction can only be used with script classes and interfaces asASSERT( objType->flags & asOBJ_SCRIPT_OBJECT ); asASSERT( to->flags & asOBJ_SCRIPT_OBJECT ); if( objType->Implements(to) || objType->DerivesFrom(to) ) { m_regs.objectType = 0; m_regs.objectRegister = obj; obj->AddRef(); } else { // The object register should already be null, so there // is no need to clear it if the cast is unsuccessful asASSERT( m_regs.objectRegister == 0 ); } } l_sp += AS_PTR_SIZE; } l_bc += 2; break; case asBC_i64TOi: *(l_fp - asBC_SWORDARG0(l_bc)) = int(*(asINT64*)(l_fp - asBC_SWORDARG1(l_bc))); l_bc += 2; break; case asBC_uTOi64: *(asINT64*)(l_fp - asBC_SWORDARG0(l_bc)) = asINT64(*(asUINT*)(l_fp - asBC_SWORDARG1(l_bc))); l_bc += 2; break; case asBC_iTOi64: *(asINT64*)(l_fp - asBC_SWORDARG0(l_bc)) = asINT64(*(int*)(l_fp - asBC_SWORDARG1(l_bc))); l_bc += 2; break; case asBC_fTOi64: *(asINT64*)(l_fp - asBC_SWORDARG0(l_bc)) = asINT64(*(float*)(l_fp - asBC_SWORDARG1(l_bc))); l_bc += 2; break; case asBC_dTOi64: *(asINT64*)(l_fp - asBC_SWORDARG0(l_bc)) = asINT64(*(double*)(l_fp - asBC_SWORDARG0(l_bc))); l_bc++; break; case asBC_fTOu64: *(asQWORD*)(l_fp - asBC_SWORDARG0(l_bc)) = asQWORD(asINT64(*(float*)(l_fp - asBC_SWORDARG1(l_bc)))); l_bc += 2; break; case asBC_dTOu64: *(asQWORD*)(l_fp - asBC_SWORDARG0(l_bc)) = asQWORD(asINT64(*(double*)(l_fp - asBC_SWORDARG0(l_bc)))); l_bc++; break; case asBC_i64TOf: *(float*)(l_fp - asBC_SWORDARG0(l_bc)) = float(*(asINT64*)(l_fp - asBC_SWORDARG1(l_bc))); l_bc += 2; break; case asBC_u64TOf: #if defined(_MSC_VER) && _MSC_VER <= 1200 // MSVC6 { // MSVC6 doesn't permit UINT64 to double asINT64 v = *(asINT64*)(l_fp - asBC_SWORDARG1(l_bc)); if( v < 0 ) *(float*)(l_fp - asBC_SWORDARG0(l_bc)) = 18446744073709551615.0f+float(v); else *(float*)(l_fp - asBC_SWORDARG0(l_bc)) = float(v); } #else *(float*)(l_fp - asBC_SWORDARG0(l_bc)) = float(*(asQWORD*)(l_fp - asBC_SWORDARG1(l_bc))); #endif l_bc += 2; break; case asBC_i64TOd: *(double*)(l_fp - asBC_SWORDARG0(l_bc)) = double(*(asINT64*)(l_fp - asBC_SWORDARG0(l_bc))); l_bc++; break; case asBC_u64TOd: #if defined(_MSC_VER) && _MSC_VER <= 1200 // MSVC6 { // MSVC6 doesn't permit UINT64 to double asINT64 v = *(asINT64*)(l_fp - asBC_SWORDARG0(l_bc)); if( v < 0 ) *(double*)(l_fp - asBC_SWORDARG0(l_bc)) = 18446744073709551615.0+double(v); else *(double*)(l_fp - asBC_SWORDARG0(l_bc)) = double(v); } #else *(double*)(l_fp - asBC_SWORDARG0(l_bc)) = double(*(asQWORD*)(l_fp - asBC_SWORDARG0(l_bc))); #endif l_bc++; break; case asBC_NEGi64: *(asINT64*)(l_fp - asBC_SWORDARG0(l_bc)) = -*(asINT64*)(l_fp - asBC_SWORDARG0(l_bc)); l_bc++; break; case asBC_INCi64: ++(**(asQWORD**)&m_regs.valueRegister); l_bc++; break; case asBC_DECi64: --(**(asQWORD**)&m_regs.valueRegister); l_bc++; break; case asBC_BNOT64: *(asQWORD*)(l_fp - asBC_SWORDARG0(l_bc)) = ~*(asQWORD*)(l_fp - asBC_SWORDARG0(l_bc)); l_bc++; break; case asBC_ADDi64: *(asQWORD*)(l_fp - asBC_SWORDARG0(l_bc)) = *(asQWORD*)(l_fp - asBC_SWORDARG1(l_bc)) + *(asQWORD*)(l_fp - asBC_SWORDARG2(l_bc)); l_bc += 2; break; case asBC_SUBi64: *(asQWORD*)(l_fp - asBC_SWORDARG0(l_bc)) = *(asQWORD*)(l_fp - asBC_SWORDARG1(l_bc)) - *(asQWORD*)(l_fp - asBC_SWORDARG2(l_bc)); l_bc += 2; break; case asBC_MULi64: *(asQWORD*)(l_fp - asBC_SWORDARG0(l_bc)) = *(asQWORD*)(l_fp - asBC_SWORDARG1(l_bc)) * *(asQWORD*)(l_fp - asBC_SWORDARG2(l_bc)); l_bc += 2; break; case asBC_DIVi64: { asINT64 divider = *(asINT64*)(l_fp - asBC_SWORDARG2(l_bc)); if( divider == 0 ) { // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Raise exception SetInternalException(TXT_DIVIDE_BY_ZERO); return; } else if( divider == -1 ) { // Need to check if the value that is divided is 1<<63 // as dividing it with -1 will cause an overflow exception if( *(asINT64*)(l_fp - asBC_SWORDARG1(l_bc)) == (asINT64(1)<<63) ) { // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Raise exception SetInternalException(TXT_DIVIDE_OVERFLOW); return; } } *(asINT64*)(l_fp - asBC_SWORDARG0(l_bc)) = *(asINT64*)(l_fp - asBC_SWORDARG1(l_bc)) / divider; } l_bc += 2; break; case asBC_MODi64: { asINT64 divider = *(asINT64*)(l_fp - asBC_SWORDARG2(l_bc)); if( divider == 0 ) { // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Raise exception SetInternalException(TXT_DIVIDE_BY_ZERO); return; } else if( divider == -1 ) { // Need to check if the value that is divided is 1<<63 // as dividing it with -1 will cause an overflow exception if( *(asINT64*)(l_fp - asBC_SWORDARG1(l_bc)) == (asINT64(1)<<63) ) { // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Raise exception SetInternalException(TXT_DIVIDE_OVERFLOW); return; } } *(asINT64*)(l_fp - asBC_SWORDARG0(l_bc)) = *(asINT64*)(l_fp - asBC_SWORDARG1(l_bc)) % divider; } l_bc += 2; break; case asBC_BAND64: *(asQWORD*)(l_fp - asBC_SWORDARG0(l_bc)) = *(asQWORD*)(l_fp - asBC_SWORDARG1(l_bc)) & *(asQWORD*)(l_fp - asBC_SWORDARG2(l_bc)); l_bc += 2; break; case asBC_BOR64: *(asQWORD*)(l_fp - asBC_SWORDARG0(l_bc)) = *(asQWORD*)(l_fp - asBC_SWORDARG1(l_bc)) | *(asQWORD*)(l_fp - asBC_SWORDARG2(l_bc)); l_bc += 2; break; case asBC_BXOR64: *(asQWORD*)(l_fp - asBC_SWORDARG0(l_bc)) = *(asQWORD*)(l_fp - asBC_SWORDARG1(l_bc)) ^ *(asQWORD*)(l_fp - asBC_SWORDARG2(l_bc)); l_bc += 2; break; case asBC_BSLL64: *(asQWORD*)(l_fp - asBC_SWORDARG0(l_bc)) = *(asQWORD*)(l_fp - asBC_SWORDARG1(l_bc)) << *(l_fp - asBC_SWORDARG2(l_bc)); l_bc += 2; break; case asBC_BSRL64: *(asQWORD*)(l_fp - asBC_SWORDARG0(l_bc)) = *(asQWORD*)(l_fp - asBC_SWORDARG1(l_bc)) >> *(l_fp - asBC_SWORDARG2(l_bc)); l_bc += 2; break; case asBC_BSRA64: *(asINT64*)(l_fp - asBC_SWORDARG0(l_bc)) = *(asINT64*)(l_fp - asBC_SWORDARG1(l_bc)) >> *(l_fp - asBC_SWORDARG2(l_bc)); l_bc += 2; break; case asBC_CMPi64: { asINT64 i1 = *(asINT64*)(l_fp - asBC_SWORDARG0(l_bc)); asINT64 i2 = *(asINT64*)(l_fp - asBC_SWORDARG1(l_bc)); if( i1 == i2 ) *(int*)&m_regs.valueRegister = 0; else if( i1 < i2 ) *(int*)&m_regs.valueRegister = -1; else *(int*)&m_regs.valueRegister = 1; l_bc += 2; } break; case asBC_CMPu64: { asQWORD d1 = *(asQWORD*)(l_fp - asBC_SWORDARG0(l_bc)); asQWORD d2 = *(asQWORD*)(l_fp - asBC_SWORDARG1(l_bc)); if( d1 == d2 ) *(int*)&m_regs.valueRegister = 0; else if( d1 < d2 ) *(int*)&m_regs.valueRegister = -1; else *(int*)&m_regs.valueRegister = 1; l_bc += 2; } break; case asBC_ChkNullS: { // Verify if the pointer on the stack is null // This is used for example when validating handles passed as function arguments asPWORD a = *(asPWORD*)(l_sp + asBC_WORDARG0(l_bc)); if( a == 0 ) { m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; SetInternalException(TXT_NULL_POINTER_ACCESS); return; } } l_bc++; break; case asBC_ClrHi: #if AS_SIZEOF_BOOL == 1 { // Clear the upper bytes, so that trash data don't interfere with boolean operations // We need to use volatile here to tell the compiler it cannot // change the order of read and write operations on the pointer. volatile asBYTE *ptr = (asBYTE*)&m_regs.valueRegister; ptr[1] = 0; // The boolean value is stored in the lower byte, so we clear the rest ptr[2] = 0; ptr[3] = 0; } #else // We don't have anything to do here #endif l_bc++; break; case asBC_JitEntry: { if( m_currentFunction->scriptData->jitFunction ) { asPWORD jitArg = asBC_PTRARG(l_bc); if( jitArg ) { // Resume JIT operation m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; (m_currentFunction->scriptData->jitFunction)(&m_regs, jitArg); l_bc = m_regs.programPointer; l_sp = m_regs.stackPointer; l_fp = m_regs.stackFramePointer; // If status isn't active anymore then we must stop if( m_status != asEXECUTION_ACTIVE ) return; break; } } // Not a JIT resume point, treat as nop l_bc += 1+AS_PTR_SIZE; } break; case asBC_CallPtr: { // Get the function pointer from the local variable asCScriptFunction *func = *(asCScriptFunction**)(l_fp - asBC_SWORDARG0(l_bc)); // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; if( func == 0 ) { // Need to update the program pointer anyway for the exception handler m_regs.programPointer++; // Tell the exception handler to clean up the arguments to this method m_needToCleanupArgs = true; // TODO: funcdef: Should we have a different exception string? SetInternalException(TXT_UNBOUND_FUNCTION); return; } else { if( func->funcType == asFUNC_SCRIPT ) { m_regs.programPointer++; CallScriptFunction(func); } else if( func->funcType == asFUNC_DELEGATE ) { // Push the object pointer on the stack. There is always a reserved space for this so // we don't don't need to worry about overflowing the allocated memory buffer asASSERT( m_regs.stackPointer - AS_PTR_SIZE >= m_stackBlocks[m_stackIndex] ); m_regs.stackPointer -= AS_PTR_SIZE; *(asPWORD*)m_regs.stackPointer = asPWORD(func->objForDelegate); // Call the delegated method if( func->funcForDelegate->funcType == asFUNC_SYSTEM ) { m_regs.stackPointer += CallSystemFunction(func->funcForDelegate->id, this); // Update program position after the call so the line number // is correct in case the system function queries it m_regs.programPointer++; } else { m_regs.programPointer++; // TODO: run-time optimize: The true method could be figured out when creating the delegate CallInterfaceMethod(func->funcForDelegate); } } else { asASSERT( func->funcType == asFUNC_SYSTEM ); m_regs.stackPointer += CallSystemFunction(func->id, this); // Update program position after the call so the line number // is correct in case the system function queries it m_regs.programPointer++; } } // Extract the values from the context again l_bc = m_regs.programPointer; l_sp = m_regs.stackPointer; l_fp = m_regs.stackFramePointer; // If status isn't active anymore then we must stop if( m_status != asEXECUTION_ACTIVE ) return; } break; case asBC_FuncPtr: // Push the function pointer on the stack. The pointer is in the argument l_sp -= AS_PTR_SIZE; *(asPWORD*)l_sp = asBC_PTRARG(l_bc); l_bc += 1+AS_PTR_SIZE; break; case asBC_LoadThisR: { // PshVPtr 0 asPWORD tmp = *(asPWORD*)l_fp; // Make sure the pointer is not null if( tmp == 0 ) { // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Raise exception SetInternalException(TXT_NULL_POINTER_ACCESS); return; } // ADDSi tmp = tmp + asBC_SWORDARG0(l_bc); // PopRPtr *(asPWORD*)&m_regs.valueRegister = tmp; l_bc += 2; } break; // Push the qword value of a variable on the stack case asBC_PshV8: l_sp -= 2; *(asQWORD*)l_sp = *(asQWORD*)(l_fp - asBC_SWORDARG0(l_bc)); l_bc++; break; case asBC_DIVu: { asUINT divider = *(asUINT*)(l_fp - asBC_SWORDARG2(l_bc)); if( divider == 0 ) { // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Raise exception SetInternalException(TXT_DIVIDE_BY_ZERO); return; } *(asUINT*)(l_fp - asBC_SWORDARG0(l_bc)) = *(asUINT*)(l_fp - asBC_SWORDARG1(l_bc)) / divider; } l_bc += 2; break; case asBC_MODu: { asUINT divider = *(asUINT*)(l_fp - asBC_SWORDARG2(l_bc)); if( divider == 0 ) { // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Raise exception SetInternalException(TXT_DIVIDE_BY_ZERO); return; } *(asUINT*)(l_fp - asBC_SWORDARG0(l_bc)) = *(asUINT*)(l_fp - asBC_SWORDARG1(l_bc)) % divider; } l_bc += 2; break; case asBC_DIVu64: { asQWORD divider = *(asQWORD*)(l_fp - asBC_SWORDARG2(l_bc)); if( divider == 0 ) { // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Raise exception SetInternalException(TXT_DIVIDE_BY_ZERO); return; } *(asQWORD*)(l_fp - asBC_SWORDARG0(l_bc)) = *(asQWORD*)(l_fp - asBC_SWORDARG1(l_bc)) / divider; } l_bc += 2; break; case asBC_MODu64: { asQWORD divider = *(asQWORD*)(l_fp - asBC_SWORDARG2(l_bc)); if( divider == 0 ) { // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Raise exception SetInternalException(TXT_DIVIDE_BY_ZERO); return; } *(asQWORD*)(l_fp - asBC_SWORDARG0(l_bc)) = *(asQWORD*)(l_fp - asBC_SWORDARG1(l_bc)) % divider; } l_bc += 2; break; case asBC_LoadRObjR: { // PshVPtr x asPWORD tmp = *(asPWORD*)(l_fp - asBC_SWORDARG0(l_bc)); // Make sure the pointer is not null if( tmp == 0 ) { // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Raise exception SetInternalException(TXT_NULL_POINTER_ACCESS); return; } // ADDSi y tmp = tmp + asBC_SWORDARG1(l_bc); // PopRPtr *(asPWORD*)&m_regs.valueRegister = tmp; l_bc += 3; } break; case asBC_LoadVObjR: { // PSF x asPWORD tmp = (asPWORD)(l_fp - asBC_SWORDARG0(l_bc)); // ADDSi y tmp = tmp + asBC_SWORDARG1(l_bc); // PopRPtr *(asPWORD*)&m_regs.valueRegister = tmp; l_bc += 3; } break; case asBC_RefCpyV: // Same as PSF v, REFCPY { asCObjectType *objType = (asCObjectType*)asBC_PTRARG(l_bc); asSTypeBehaviour *beh = &objType->beh; // Determine destination from argument void **d = (void**)asPWORD(l_fp - asBC_SWORDARG0(l_bc)); // Read wanted pointer from the stack void *s = (void*)*(asPWORD*)l_sp; // Need to move the values back to the context as the called functions // may use the debug interface to inspect the registers m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; if( !(objType->flags & asOBJ_NOCOUNT) ) { // Release previous object held by destination pointer if( *d != 0 ) m_engine->CallObjectMethod(*d, beh->release); // Increase ref counter of wanted object if( s != 0 ) m_engine->CallObjectMethod(s, beh->addref); } // Set the new object in the destination *d = s; } l_bc += 1+AS_PTR_SIZE; break; case asBC_JLowZ: if( *(asBYTE*)&m_regs.valueRegister == 0 ) l_bc += asBC_INTARG(l_bc) + 2; else l_bc += 2; break; case asBC_JLowNZ: if( *(asBYTE*)&m_regs.valueRegister != 0 ) l_bc += asBC_INTARG(l_bc) + 2; else l_bc += 2; break; case asBC_AllocMem: // Allocate a buffer and store the pointer in the local variable { // TODO: runtime optimize: As the list buffers are going to be short lived, it may be interesting // to use a memory pool to avoid reallocating the memory all the time asUINT size = asBC_DWORDARG(l_bc); asBYTE **var = (asBYTE**)(l_fp - asBC_SWORDARG0(l_bc)); #ifndef WIP_16BYTE_ALIGN *var = asNEWARRAY(asBYTE, size); #else *var = asNEWARRAYALIGNED(asBYTE, size, MAX_TYPE_ALIGNMENT); #endif // Clear the buffer for the pointers that will be placed in it memset(*var, 0, size); } l_bc += 2; break; case asBC_SetListSize: { // Set the size element in the buffer asBYTE *var = *(asBYTE**)(l_fp - asBC_SWORDARG0(l_bc)); asUINT off = asBC_DWORDARG(l_bc); asUINT size = asBC_DWORDARG(l_bc+1); asASSERT( var ); *(asUINT*)(var+off) = size; } l_bc += 3; break; case asBC_PshListElmnt: { // Push the pointer to the list element on the stack // In essence it does the same as PSF, RDSPtr, ADDSi asBYTE *var = *(asBYTE**)(l_fp - asBC_SWORDARG0(l_bc)); asUINT off = asBC_DWORDARG(l_bc); asASSERT( var ); l_sp -= AS_PTR_SIZE; *(asPWORD*)l_sp = asPWORD(var+off); } l_bc += 2; break; case asBC_SetListType: { // Set the type id in the buffer asBYTE *var = *(asBYTE**)(l_fp - asBC_SWORDARG0(l_bc)); asUINT off = asBC_DWORDARG(l_bc); asUINT type = asBC_DWORDARG(l_bc+1); asASSERT( var ); *(asUINT*)(var+off) = type; } l_bc += 3; break; //------------------------------ // Exponent operations case asBC_POWi: { bool isOverflow; *(int*)(l_fp - asBC_SWORDARG0(l_bc)) = as_powi(*(int*)(l_fp - asBC_SWORDARG1(l_bc)), *(int*)(l_fp - asBC_SWORDARG2(l_bc)), isOverflow); if( isOverflow ) { // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Raise exception SetInternalException(TXT_POW_OVERFLOW); return; } } l_bc += 2; break; case asBC_POWu: { bool isOverflow; *(asDWORD*)(l_fp - asBC_SWORDARG0(l_bc)) = as_powu(*(asDWORD*)(l_fp - asBC_SWORDARG1(l_bc)), *(asDWORD*)(l_fp - asBC_SWORDARG2(l_bc)), isOverflow); if( isOverflow ) { // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Raise exception SetInternalException(TXT_POW_OVERFLOW); return; } } l_bc += 2; break; case asBC_POWf: { float r = powf(*(float*)(l_fp - asBC_SWORDARG1(l_bc)), *(float*)(l_fp - asBC_SWORDARG2(l_bc))); *(float*)(l_fp - asBC_SWORDARG0(l_bc)) = r; if( r == float(HUGE_VAL) ) { // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Raise exception SetInternalException(TXT_POW_OVERFLOW); return; } } l_bc += 2; break; case asBC_POWd: { double r = pow(*(double*)(l_fp - asBC_SWORDARG1(l_bc)), *(double*)(l_fp - asBC_SWORDARG2(l_bc))); *(double*)(l_fp - asBC_SWORDARG0(l_bc)) = r; if( r == HUGE_VAL ) { // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Raise exception SetInternalException(TXT_POW_OVERFLOW); return; } } l_bc += 2; break; case asBC_POWdi: { double r = pow(*(double*)(l_fp - asBC_SWORDARG1(l_bc)), *(int*)(l_fp - asBC_SWORDARG2(l_bc))); *(double*)(l_fp - asBC_SWORDARG0(l_bc)) = r; if( r == HUGE_VAL ) { // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Raise exception SetInternalException(TXT_POW_OVERFLOW); return; } l_bc += 2; } break; case asBC_POWi64: { bool isOverflow; *(asINT64*)(l_fp - asBC_SWORDARG0(l_bc)) = as_powi64(*(asINT64*)(l_fp - asBC_SWORDARG1(l_bc)), *(asINT64*)(l_fp - asBC_SWORDARG2(l_bc)), isOverflow); if( isOverflow ) { // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Raise exception SetInternalException(TXT_POW_OVERFLOW); return; } } l_bc += 2; break; case asBC_POWu64: { bool isOverflow; *(asQWORD*)(l_fp - asBC_SWORDARG0(l_bc)) = as_powu64(*(asQWORD*)(l_fp - asBC_SWORDARG1(l_bc)), *(asQWORD*)(l_fp - asBC_SWORDARG2(l_bc)), isOverflow); if( isOverflow ) { // Need to move the values back to the context m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Raise exception SetInternalException(TXT_POW_OVERFLOW); return; } } l_bc += 2; break; case asBC_Thiscall1: // This instruction is a faster version of asBC_CALLSYS. It is faster because // it has much less runtime overhead with determining the calling convention // and no dynamic code for loading the parameters. The instruction can only // be used to call functions with the following signatures: // // type &obj::func(int) // type &obj::func(uint) // void obj::func(int) // void obj::func(uint) { // Get function ID from the argument int i = asBC_INTARG(l_bc); // Need to move the values back to the context as the called functions // may use the debug interface to inspect the registers m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; // Pop the thispointer from the stack void *obj = *(void**)l_sp; if (obj == 0) SetInternalException(TXT_NULL_POINTER_ACCESS); else { // Only update the stack pointer if all is OK so the // exception handler can properly clean up the stack l_sp += AS_PTR_SIZE; // Pop the int arg from the stack int arg = *(int*)l_sp; l_sp++; // Call the method m_callingSystemFunction = m_engine->scriptFunctions[i]; void *ptr = m_engine->CallObjectMethodRetPtr(obj, arg, m_callingSystemFunction); m_callingSystemFunction = 0; *(asPWORD*)&m_regs.valueRegister = (asPWORD)ptr; } // Update the program position after the call so that line number is correct l_bc += 2; if( m_regs.doProcessSuspend ) { // Should the execution be suspended? if( m_doSuspend ) { m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; m_status = asEXECUTION_SUSPENDED; return; } // An exception might have been raised if( m_status != asEXECUTION_ACTIVE ) { m_regs.programPointer = l_bc; m_regs.stackPointer = l_sp; m_regs.stackFramePointer = l_fp; return; } } } break; // Don't let the optimizer optimize for size, // since it requires extra conditions and jumps case 201: l_bc = (asDWORD*)201; break; case 202: l_bc = (asDWORD*)202; break; case 203: l_bc = (asDWORD*)203; break; case 204: l_bc = (asDWORD*)204; break; case 205: l_bc = (asDWORD*)205; break; case 206: l_bc = (asDWORD*)206; break; case 207: l_bc = (asDWORD*)207; break; case 208: l_bc = (asDWORD*)208; break; case 209: l_bc = (asDWORD*)209; break; case 210: l_bc = (asDWORD*)210; break; case 211: l_bc = (asDWORD*)211; break; case 212: l_bc = (asDWORD*)212; break; case 213: l_bc = (asDWORD*)213; break; case 214: l_bc = (asDWORD*)214; break; case 215: l_bc = (asDWORD*)215; break; case 216: l_bc = (asDWORD*)216; break; case 217: l_bc = (asDWORD*)217; break; case 218: l_bc = (asDWORD*)218; break; case 219: l_bc = (asDWORD*)219; break; case 220: l_bc = (asDWORD*)220; break; case 221: l_bc = (asDWORD*)221; break; case 222: l_bc = (asDWORD*)222; break; case 223: l_bc = (asDWORD*)223; break; case 224: l_bc = (asDWORD*)224; break; case 225: l_bc = (asDWORD*)225; break; case 226: l_bc = (asDWORD*)226; break; case 227: l_bc = (asDWORD*)227; break; case 228: l_bc = (asDWORD*)228; break; case 229: l_bc = (asDWORD*)229; break; case 230: l_bc = (asDWORD*)230; break; case 231: l_bc = (asDWORD*)231; break; case 232: l_bc = (asDWORD*)232; break; case 233: l_bc = (asDWORD*)233; break; case 234: l_bc = (asDWORD*)234; break; case 235: l_bc = (asDWORD*)235; break; case 236: l_bc = (asDWORD*)236; break; case 237: l_bc = (asDWORD*)237; break; case 238: l_bc = (asDWORD*)238; break; case 239: l_bc = (asDWORD*)239; break; case 240: l_bc = (asDWORD*)240; break; case 241: l_bc = (asDWORD*)241; break; case 242: l_bc = (asDWORD*)242; break; case 243: l_bc = (asDWORD*)243; break; case 244: l_bc = (asDWORD*)244; break; case 245: l_bc = (asDWORD*)245; break; case 246: l_bc = (asDWORD*)246; break; case 247: l_bc = (asDWORD*)247; break; case 248: l_bc = (asDWORD*)248; break; case 249: l_bc = (asDWORD*)249; break; case 250: l_bc = (asDWORD*)250; break; case 251: l_bc = (asDWORD*)251; break; case 252: l_bc = (asDWORD*)252; break; case 253: l_bc = (asDWORD*)253; break; case 254: l_bc = (asDWORD*)254; break; case 255: l_bc = (asDWORD*)255; break; #ifdef AS_DEBUG default: asASSERT(false); SetInternalException(TXT_UNRECOGNIZED_BYTE_CODE); #endif #if defined(_MSC_VER) && !defined(AS_DEBUG) default: // This Microsoft specific code allows the // compiler to optimize the switch case as // it will know that the code will never // reach this point __assume(0); #endif } #ifdef AS_DEBUG asDWORD instr = *(asBYTE*)old; if( instr != asBC_JMP && instr != asBC_JMPP && (instr < asBC_JZ || instr > asBC_JNP) && instr != asBC_JLowZ && instr != asBC_JLowNZ && instr != asBC_CALL && instr != asBC_CALLBND && instr != asBC_CALLINTF && instr != asBC_RET && instr != asBC_ALLOC && instr != asBC_CallPtr && instr != asBC_JitEntry ) { asASSERT( (l_bc - old) == asBCTypeSize[asBCInfo[instr].type] ); } #endif } } int asCContext::SetException(const char *descr) { // Only allow this if we're executing a CALL byte code if( m_callingSystemFunction == 0 ) return asERROR; SetInternalException(descr); return 0; } void asCContext::SetInternalException(const char *descr) { if( m_inExceptionHandler ) { asASSERT(false); // Shouldn't happen return; // but if it does, at least this will not crash the application } m_status = asEXECUTION_EXCEPTION; m_regs.doProcessSuspend = true; m_exceptionString = descr; m_exceptionFunction = m_currentFunction->id; if( m_currentFunction->scriptData ) { m_exceptionLine = m_currentFunction->GetLineNumber(int(m_regs.programPointer - m_currentFunction->scriptData->byteCode.AddressOf()), &m_exceptionSectionIdx); m_exceptionColumn = m_exceptionLine >> 20; m_exceptionLine &= 0xFFFFF; } else { m_exceptionSectionIdx = 0; m_exceptionLine = 0; m_exceptionColumn = 0; } if( m_exceptionCallback ) CallExceptionCallback(); } void asCContext::CleanReturnObject() { if( m_initialFunction && m_initialFunction->DoesReturnOnStack() && m_status == asEXECUTION_FINISHED ) { // If function returns on stack we need to call the destructor on the returned object if(CastToObjectType(m_initialFunction->returnType.GetTypeInfo())->beh.destruct ) m_engine->CallObjectMethod(GetReturnObject(), CastToObjectType(m_initialFunction->returnType.GetTypeInfo())->beh.destruct); return; } if( m_regs.objectRegister == 0 ) return; asASSERT( m_regs.objectType != 0 ); if( m_regs.objectType ) { if (m_regs.objectType->GetFlags() & asOBJ_FUNCDEF) { // Release the function pointer reinterpret_cast<asIScriptFunction*>(m_regs.objectRegister)->Release(); m_regs.objectRegister = 0; } else { // Call the destructor on the object asSTypeBehaviour *beh = &(CastToObjectType(reinterpret_cast<asCTypeInfo*>(m_regs.objectType))->beh); if (m_regs.objectType->GetFlags() & asOBJ_REF) { asASSERT(beh->release || (m_regs.objectType->GetFlags() & asOBJ_NOCOUNT)); if (beh->release) m_engine->CallObjectMethod(m_regs.objectRegister, beh->release); m_regs.objectRegister = 0; } else { if (beh->destruct) m_engine->CallObjectMethod(m_regs.objectRegister, beh->destruct); // Free the memory m_engine->CallFree(m_regs.objectRegister); m_regs.objectRegister = 0; } } } } void asCContext::CleanStack() { m_inExceptionHandler = true; // Run the clean up code for each of the functions called CleanStackFrame(); // Set the status to exception so that the stack unwind is done correctly. // This shouldn't be done for the current function, which is why we only // do this after the first CleanStackFrame() is done. m_status = asEXECUTION_EXCEPTION; while( m_callStack.GetLength() > 0 ) { // Only clean up until the top most marker for a nested call asPWORD *s = m_callStack.AddressOf() + m_callStack.GetLength() - CALLSTACK_FRAME_SIZE; if( s[0] == 0 ) break; PopCallState(); CleanStackFrame(); } m_inExceptionHandler = false; } // Interface bool asCContext::IsVarInScope(asUINT varIndex, asUINT stackLevel) { // Don't return anything if there is no bytecode, e.g. before calling Execute() if( m_regs.programPointer == 0 ) return false; if( stackLevel >= GetCallstackSize() ) return false; asCScriptFunction *func; asUINT pos; if( stackLevel == 0 ) { func = m_currentFunction; if( func->scriptData == 0 ) return false; pos = asUINT(m_regs.programPointer - func->scriptData->byteCode.AddressOf()); } else { asPWORD *s = m_callStack.AddressOf() + (GetCallstackSize()-stackLevel-1)*CALLSTACK_FRAME_SIZE; func = (asCScriptFunction*)s[1]; if( func->scriptData == 0 ) return false; pos = asUINT((asDWORD*)s[2] - func->scriptData->byteCode.AddressOf()); } // First determine if the program position is after the variable declaration if( func->scriptData->variables.GetLength() <= varIndex ) return false; if( func->scriptData->variables[varIndex]->declaredAtProgramPos > pos ) return false; asUINT declaredAt = func->scriptData->variables[varIndex]->declaredAtProgramPos; // If the program position is after the variable declaration it is necessary // determine if the program position is still inside the statement block where // the variable was delcared. for( int n = 0; n < (int)func->scriptData->objVariableInfo.GetLength(); n++ ) { if( func->scriptData->objVariableInfo[n].programPos >= declaredAt ) { // If the current block ends between the declaredAt and current // program position, then we know the variable is no longer visible int level = 0; for( ; n < (int)func->scriptData->objVariableInfo.GetLength(); n++ ) { if( func->scriptData->objVariableInfo[n].programPos > pos ) break; if( func->scriptData->objVariableInfo[n].option == asBLOCK_BEGIN ) level++; if( func->scriptData->objVariableInfo[n].option == asBLOCK_END && --level < 0 ) return false; } break; } } // Variable is visible return true; } // Internal void asCContext::DetermineLiveObjects(asCArray<int> &liveObjects, asUINT stackLevel) { asASSERT( stackLevel < GetCallstackSize() ); asCScriptFunction *func; asUINT pos; if( stackLevel == 0 ) { func = m_currentFunction; if( func->scriptData == 0 ) return; pos = asUINT(m_regs.programPointer - func->scriptData->byteCode.AddressOf()); if( m_status == asEXECUTION_EXCEPTION ) { // Don't consider the last instruction as executed, as it failed with an exception // It's not actually necessary to decrease the exact size of the instruction. Just // before the current position is enough to disconsider it. pos--; } } else { asPWORD *s = m_callStack.AddressOf() + (GetCallstackSize()-stackLevel-1)*CALLSTACK_FRAME_SIZE; func = (asCScriptFunction*)s[1]; if( func->scriptData == 0 ) return; pos = asUINT((asDWORD*)s[2] - func->scriptData->byteCode.AddressOf()); // Don't consider the last instruction as executed, as the function that was called by it // is still being executed. If we consider it as executed already, then a value object // returned by value would be considered alive, which it is not. pos--; } // Determine which object variables that are really live ones liveObjects.SetLength(func->scriptData->objVariablePos.GetLength()); memset(liveObjects.AddressOf(), 0, sizeof(int)*liveObjects.GetLength()); for( int n = 0; n < (int)func->scriptData->objVariableInfo.GetLength(); n++ ) { // Find the first variable info with a larger position than the current // As the variable info are always placed on the instruction right after the // one that initialized or freed the object, the current position needs to be // considered as valid. if( func->scriptData->objVariableInfo[n].programPos > pos ) { // We've determined how far the execution ran, now determine which variables are alive for( --n; n >= 0; n-- ) { switch( func->scriptData->objVariableInfo[n].option ) { case asOBJ_UNINIT: // Object was destroyed { // TODO: optimize: This should have been done by the compiler already // Which variable is this? asUINT var = 0; for( asUINT v = 0; v < func->scriptData->objVariablePos.GetLength(); v++ ) if( func->scriptData->objVariablePos[v] == func->scriptData->objVariableInfo[n].variableOffset ) { var = v; break; } liveObjects[var] -= 1; } break; case asOBJ_INIT: // Object was created { // Which variable is this? asUINT var = 0; for( asUINT v = 0; v < func->scriptData->objVariablePos.GetLength(); v++ ) if( func->scriptData->objVariablePos[v] == func->scriptData->objVariableInfo[n].variableOffset ) { var = v; break; } liveObjects[var] += 1; } break; case asBLOCK_BEGIN: // Start block // We should ignore start blocks, since it just means the // program was within the block when the exception ocurred break; case asBLOCK_END: // End block // We need to skip the entire block, as the objects created // and destroyed inside this block are already out of scope { int nested = 1; while( nested > 0 ) { int option = func->scriptData->objVariableInfo[--n].option; if( option == 3 ) nested++; if( option == 2 ) nested--; } } break; } } // We're done with the investigation break; } } } void asCContext::CleanArgsOnStack() { if( !m_needToCleanupArgs ) return; asASSERT( m_currentFunction->scriptData ); // Find the instruction just before the current program pointer asDWORD *instr = m_currentFunction->scriptData->byteCode.AddressOf(); asDWORD *prevInstr = 0; while( instr < m_regs.programPointer ) { prevInstr = instr; instr += asBCTypeSize[asBCInfo[*(asBYTE*)(instr)].type]; } // Determine what function was being called asCScriptFunction *func = 0; asBYTE bc = *(asBYTE*)prevInstr; if( bc == asBC_CALL || bc == asBC_CALLSYS || bc == asBC_CALLINTF ) { int funcId = asBC_INTARG(prevInstr); func = m_engine->scriptFunctions[funcId]; } else if( bc == asBC_CALLBND ) { int funcId = asBC_INTARG(prevInstr); func = m_engine->importedFunctions[funcId & ~FUNC_IMPORTED]->importedFunctionSignature; } else if( bc == asBC_CallPtr ) { asUINT v; int var = asBC_SWORDARG0(prevInstr); // Find the funcdef from the local variable for( v = 0; v < m_currentFunction->scriptData->objVariablePos.GetLength(); v++ ) if( m_currentFunction->scriptData->objVariablePos[v] == var ) { func = CastToFuncdefType(m_currentFunction->scriptData->objVariableTypes[v])->funcdef; break; } if( func == 0 ) { // Look in parameters int paramPos = 0; if( m_currentFunction->objectType ) paramPos -= AS_PTR_SIZE; if( m_currentFunction->DoesReturnOnStack() ) paramPos -= AS_PTR_SIZE; for( v = 0; v < m_currentFunction->parameterTypes.GetLength(); v++ ) { if( var == paramPos ) { if (m_currentFunction->parameterTypes[v].IsFuncdef()) func = CastToFuncdefType(m_currentFunction->parameterTypes[v].GetTypeInfo())->funcdef; break; } paramPos -= m_currentFunction->parameterTypes[v].GetSizeOnStackDWords(); } } } else asASSERT( false ); asASSERT( func ); // Clean parameters int offset = 0; if( func->objectType ) offset += AS_PTR_SIZE; if( func->DoesReturnOnStack() ) offset += AS_PTR_SIZE; for( asUINT n = 0; n < func->parameterTypes.GetLength(); n++ ) { if( (func->parameterTypes[n].IsObject() || func->parameterTypes[n].IsFuncdef()) && !func->parameterTypes[n].IsReference() ) { // TODO: cleanup: This logic is repeated twice in CleanStackFrame too. Should create a common function to share the code if( *(asPWORD*)&m_regs.stackPointer[offset] ) { // Call the object's destructor asSTypeBehaviour *beh = func->parameterTypes[n].GetBehaviour(); if (func->parameterTypes[n].GetTypeInfo()->flags & asOBJ_FUNCDEF) { (*(asCScriptFunction**)&m_regs.stackPointer[offset])->Release(); } else if( func->parameterTypes[n].GetTypeInfo()->flags & asOBJ_REF ) { asASSERT( (func->parameterTypes[n].GetTypeInfo()->flags & asOBJ_NOCOUNT) || beh->release ); if( beh->release ) m_engine->CallObjectMethod((void*)*(asPWORD*)&m_regs.stackPointer[offset], beh->release); } else { if( beh->destruct ) m_engine->CallObjectMethod((void*)*(asPWORD*)&m_regs.stackPointer[offset], beh->destruct); // Free the memory m_engine->CallFree((void*)*(asPWORD*)&m_regs.stackPointer[offset]); } *(asPWORD*)&m_regs.stackPointer[offset] = 0; } } offset += func->parameterTypes[n].GetSizeOnStackDWords(); } m_needToCleanupArgs = false; } void asCContext::CleanStackFrame() { // Clean object variables on the stack // If the stack memory is not allocated or the program pointer // is not set, then there is nothing to clean up on the stack frame if( !m_isStackMemoryNotAllocated && m_regs.programPointer ) { // If the exception occurred while calling a function it is necessary // to clean up the arguments that were put on the stack. CleanArgsOnStack(); // Restore the stack pointer asASSERT( m_currentFunction->scriptData ); m_regs.stackPointer += m_currentFunction->scriptData->variableSpace; // Determine which object variables that are really live ones asCArray<int> liveObjects; DetermineLiveObjects(liveObjects, 0); for( asUINT n = 0; n < m_currentFunction->scriptData->objVariablePos.GetLength(); n++ ) { int pos = m_currentFunction->scriptData->objVariablePos[n]; if( n < m_currentFunction->scriptData->objVariablesOnHeap ) { // Check if the pointer is initialized if( *(asPWORD*)&m_regs.stackFramePointer[-pos] ) { // Call the object's destructor if (m_currentFunction->scriptData->objVariableTypes[n]->flags & asOBJ_FUNCDEF) { (*(asCScriptFunction**)&m_regs.stackFramePointer[-pos])->Release(); } else if( m_currentFunction->scriptData->objVariableTypes[n]->flags & asOBJ_REF ) { asSTypeBehaviour *beh = &CastToObjectType(m_currentFunction->scriptData->objVariableTypes[n])->beh; asASSERT( (m_currentFunction->scriptData->objVariableTypes[n]->flags & asOBJ_NOCOUNT) || beh->release ); if( beh->release ) m_engine->CallObjectMethod((void*)*(asPWORD*)&m_regs.stackFramePointer[-pos], beh->release); } else { asSTypeBehaviour *beh = &CastToObjectType(m_currentFunction->scriptData->objVariableTypes[n])->beh; if( beh->destruct ) m_engine->CallObjectMethod((void*)*(asPWORD*)&m_regs.stackFramePointer[-pos], beh->destruct); else if( m_currentFunction->scriptData->objVariableTypes[n]->flags & asOBJ_LIST_PATTERN ) m_engine->DestroyList((asBYTE*)*(asPWORD*)&m_regs.stackFramePointer[-pos], CastToObjectType(m_currentFunction->scriptData->objVariableTypes[n])); // Free the memory m_engine->CallFree((void*)*(asPWORD*)&m_regs.stackFramePointer[-pos]); } *(asPWORD*)&m_regs.stackFramePointer[-pos] = 0; } } else { asASSERT( m_currentFunction->scriptData->objVariableTypes[n]->GetFlags() & asOBJ_VALUE ); // Only destroy the object if it is truly alive if( liveObjects[n] > 0 ) { asSTypeBehaviour *beh = &CastToObjectType(m_currentFunction->scriptData->objVariableTypes[n])->beh; if( beh->destruct ) m_engine->CallObjectMethod((void*)(asPWORD*)&m_regs.stackFramePointer[-pos], beh->destruct); } } } } else m_isStackMemoryNotAllocated = false; // Functions that do not own the object and parameters shouldn't do any clean up if( m_currentFunction->dontCleanUpOnException ) return; // Clean object and parameters int offset = 0; if( m_currentFunction->objectType ) offset += AS_PTR_SIZE; if( m_currentFunction->DoesReturnOnStack() ) offset += AS_PTR_SIZE; for( asUINT n = 0; n < m_currentFunction->parameterTypes.GetLength(); n++ ) { if( (m_currentFunction->parameterTypes[n].IsObject() ||m_currentFunction->parameterTypes[n].IsFuncdef()) && !m_currentFunction->parameterTypes[n].IsReference() ) { if( *(asPWORD*)&m_regs.stackFramePointer[offset] ) { // Call the object's destructor asSTypeBehaviour *beh = m_currentFunction->parameterTypes[n].GetBehaviour(); if (m_currentFunction->parameterTypes[n].GetTypeInfo()->flags & asOBJ_FUNCDEF) { (*(asCScriptFunction**)&m_regs.stackFramePointer[offset])->Release(); } else if( m_currentFunction->parameterTypes[n].GetTypeInfo()->flags & asOBJ_REF ) { asASSERT( (m_currentFunction->parameterTypes[n].GetTypeInfo()->flags & asOBJ_NOCOUNT) || beh->release ); if( beh->release ) m_engine->CallObjectMethod((void*)*(asPWORD*)&m_regs.stackFramePointer[offset], beh->release); } else { if( beh->destruct ) m_engine->CallObjectMethod((void*)*(asPWORD*)&m_regs.stackFramePointer[offset], beh->destruct); // Free the memory m_engine->CallFree((void*)*(asPWORD*)&m_regs.stackFramePointer[offset]); } *(asPWORD*)&m_regs.stackFramePointer[offset] = 0; } } offset += m_currentFunction->parameterTypes[n].GetSizeOnStackDWords(); } } // interface int asCContext::GetExceptionLineNumber(int *column, const char **sectionName) { if( GetState() != asEXECUTION_EXCEPTION ) return asERROR; if( column ) *column = m_exceptionColumn; if( sectionName ) { // The section index can be -1 if the exception was raised in a generated function, e.g. $fact for templates if( m_exceptionSectionIdx >= 0 ) *sectionName = m_engine->scriptSectionNames[m_exceptionSectionIdx]->AddressOf(); else *sectionName = 0; } return m_exceptionLine; } // interface asIScriptFunction *asCContext::GetExceptionFunction() { if( GetState() != asEXECUTION_EXCEPTION ) return 0; return m_engine->scriptFunctions[m_exceptionFunction]; } // interface const char *asCContext::GetExceptionString() { if( GetState() != asEXECUTION_EXCEPTION ) return 0; return m_exceptionString.AddressOf(); } // interface asEContextState asCContext::GetState() const { return m_status; } // interface int asCContext::SetLineCallback(asSFuncPtr callback, void *obj, int callConv) { // First turn off the line callback to avoid a second thread // attempting to call it while the new one is still being set m_lineCallback = false; m_lineCallbackObj = obj; bool isObj = false; if( (unsigned)callConv == asCALL_GENERIC || (unsigned)callConv == asCALL_THISCALL_OBJFIRST || (unsigned)callConv == asCALL_THISCALL_OBJLAST ) { m_regs.doProcessSuspend = m_doSuspend; return asNOT_SUPPORTED; } if( (unsigned)callConv >= asCALL_THISCALL ) { isObj = true; if( obj == 0 ) { m_regs.doProcessSuspend = m_doSuspend; return asINVALID_ARG; } } int r = DetectCallingConvention(isObj, callback, callConv, 0, &m_lineCallbackFunc); // Turn on the line callback after setting both the function pointer and object pointer if( r >= 0 ) m_lineCallback = true; // The BC_SUSPEND instruction should be processed if either line // callback is set or if the application has requested a suspension m_regs.doProcessSuspend = m_doSuspend || m_lineCallback; return r; } void asCContext::CallLineCallback() { if( m_lineCallbackFunc.callConv < ICC_THISCALL ) m_engine->CallGlobalFunction(this, m_lineCallbackObj, &m_lineCallbackFunc, 0); else m_engine->CallObjectMethod(m_lineCallbackObj, this, &m_lineCallbackFunc, 0); } // interface int asCContext::SetExceptionCallback(asSFuncPtr callback, void *obj, int callConv) { m_exceptionCallback = true; m_exceptionCallbackObj = obj; bool isObj = false; if( (unsigned)callConv == asCALL_GENERIC || (unsigned)callConv == asCALL_THISCALL_OBJFIRST || (unsigned)callConv == asCALL_THISCALL_OBJLAST ) return asNOT_SUPPORTED; if( (unsigned)callConv >= asCALL_THISCALL ) { isObj = true; if( obj == 0 ) { m_exceptionCallback = false; return asINVALID_ARG; } } int r = DetectCallingConvention(isObj, callback, callConv, 0, &m_exceptionCallbackFunc); if( r < 0 ) m_exceptionCallback = false; return r; } void asCContext::CallExceptionCallback() { if( m_exceptionCallbackFunc.callConv < ICC_THISCALL ) m_engine->CallGlobalFunction(this, m_exceptionCallbackObj, &m_exceptionCallbackFunc, 0); else m_engine->CallObjectMethod(m_exceptionCallbackObj, this, &m_exceptionCallbackFunc, 0); } // interface void asCContext::ClearLineCallback() { m_lineCallback = false; m_regs.doProcessSuspend = m_doSuspend; } // interface void asCContext::ClearExceptionCallback() { m_exceptionCallback = false; } int asCContext::CallGeneric(asCScriptFunction *descr) { asSSystemFunctionInterface *sysFunc = descr->sysFuncIntf; void (*func)(asIScriptGeneric*) = (void (*)(asIScriptGeneric*))sysFunc->func; int popSize = sysFunc->paramSize; asDWORD *args = m_regs.stackPointer; // Verify the object pointer if it is a class method void *currentObject = 0; asASSERT( sysFunc->callConv == ICC_GENERIC_FUNC || sysFunc->callConv == ICC_GENERIC_METHOD ); if( sysFunc->callConv == ICC_GENERIC_METHOD ) { // The object pointer should be popped from the context stack popSize += AS_PTR_SIZE; // Check for null pointer currentObject = (void*)*(asPWORD*)(args); if( currentObject == 0 ) { SetInternalException(TXT_NULL_POINTER_ACCESS); return 0; } asASSERT( sysFunc->baseOffset == 0 ); // Skip object pointer args += AS_PTR_SIZE; } if( descr->DoesReturnOnStack() ) { // Skip the address where the return value will be stored args += AS_PTR_SIZE; popSize += AS_PTR_SIZE; } asCGeneric gen(m_engine, descr, currentObject, args); m_callingSystemFunction = descr; #ifdef AS_NO_EXCEPTIONS func(&gen); #else // This try/catch block is to catch potential exception that may // be thrown by the registered function. try { func(&gen); } catch (...) { // Convert the exception to a script exception so the VM can // properly report the error to the application and then clean up SetException(TXT_EXCEPTION_CAUGHT); } #endif m_callingSystemFunction = 0; m_regs.valueRegister = gen.returnVal; m_regs.objectRegister = gen.objectRegister; m_regs.objectType = descr->returnType.GetTypeInfo(); // Clean up arguments const asUINT cleanCount = sysFunc->cleanArgs.GetLength(); if( cleanCount ) { asSSystemFunctionInterface::SClean *clean = sysFunc->cleanArgs.AddressOf(); for( asUINT n = 0; n < cleanCount; n++, clean++ ) { void **addr = (void**)&args[clean->off]; if( clean->op == 0 ) { if( *addr != 0 ) { m_engine->CallObjectMethod(*addr, clean->ot->beh.release); *addr = 0; } } else { asASSERT( clean->op == 1 || clean->op == 2 ); asASSERT( *addr ); if( clean->op == 2 ) m_engine->CallObjectMethod(*addr, clean->ot->beh.destruct); m_engine->CallFree(*addr); } } } // Return how much should be popped from the stack return popSize; } // interface int asCContext::GetVarCount(asUINT stackLevel) { asIScriptFunction *func = GetFunction(stackLevel); if( func == 0 ) return asINVALID_ARG; return func->GetVarCount(); } // interface const char *asCContext::GetVarName(asUINT varIndex, asUINT stackLevel) { asIScriptFunction *func = GetFunction(stackLevel); if( func == 0 ) return 0; const char *name = 0; int r = func->GetVar(varIndex, &name); return r >= 0 ? name : 0; } // interface const char *asCContext::GetVarDeclaration(asUINT varIndex, asUINT stackLevel, bool includeNamespace) { asIScriptFunction *func = GetFunction(stackLevel); if( func == 0 ) return 0; return func->GetVarDecl(varIndex, includeNamespace); } // interface int asCContext::GetVarTypeId(asUINT varIndex, asUINT stackLevel) { asIScriptFunction *func = GetFunction(stackLevel); if( func == 0 ) return asINVALID_ARG; int typeId; int r = func->GetVar(varIndex, 0, &typeId); return r < 0 ? r : typeId; } // interface void *asCContext::GetAddressOfVar(asUINT varIndex, asUINT stackLevel) { // Don't return anything if there is no bytecode, e.g. before calling Execute() if( m_regs.programPointer == 0 ) return 0; if( stackLevel >= GetCallstackSize() ) return 0; asCScriptFunction *func; asDWORD *sf; if( stackLevel == 0 ) { func = m_currentFunction; sf = m_regs.stackFramePointer; } else { asPWORD *s = m_callStack.AddressOf() + (GetCallstackSize()-stackLevel-1)*CALLSTACK_FRAME_SIZE; func = (asCScriptFunction*)s[1]; sf = (asDWORD*)s[0]; } if( func == 0 ) return 0; if( func->scriptData == 0 ) return 0; if( varIndex >= func->scriptData->variables.GetLength() ) return 0; // For object variables it's necessary to dereference the pointer to get the address of the value // Reference parameters must also be dereferenced to give the address of the value int pos = func->scriptData->variables[varIndex]->stackOffset; if( (func->scriptData->variables[varIndex]->type.IsObject() && !func->scriptData->variables[varIndex]->type.IsObjectHandle()) || (pos <= 0) ) { // Determine if the object is really on the heap bool onHeap = false; if( func->scriptData->variables[varIndex]->type.IsObject() && !func->scriptData->variables[varIndex]->type.IsObjectHandle() ) { onHeap = true; if( func->scriptData->variables[varIndex]->type.GetTypeInfo()->GetFlags() & asOBJ_VALUE ) { for( asUINT n = 0; n < func->scriptData->objVariablePos.GetLength(); n++ ) { if( func->scriptData->objVariablePos[n] == pos ) { onHeap = n < func->scriptData->objVariablesOnHeap; if( !onHeap ) { // If the object on the stack is not initialized return a null pointer instead asCArray<int> liveObjects; DetermineLiveObjects(liveObjects, stackLevel); if( liveObjects[n] <= 0 ) return 0; } break; } } } } // If it wasn't an object on the heap, then check if it is a reference parameter if( !onHeap && pos <= 0 ) { // Determine what function argument this position matches int stackPos = 0; if( func->objectType ) stackPos -= AS_PTR_SIZE; if( func->DoesReturnOnStack() ) stackPos -= AS_PTR_SIZE; for( asUINT n = 0; n < func->parameterTypes.GetLength(); n++ ) { if( stackPos == pos ) { // The right argument was found. Is this a reference parameter? if( func->inOutFlags[n] != asTM_NONE ) onHeap = true; break; } stackPos -= func->parameterTypes[n].GetSizeOnStackDWords(); } } if( onHeap ) return *(void**)(sf - func->scriptData->variables[varIndex]->stackOffset); } return sf - func->scriptData->variables[varIndex]->stackOffset; } // interface // returns the typeId of the 'this' object at the given call stack level (-1 for current) // returns 0 if the function call at the given stack level is not a method int asCContext::GetThisTypeId(asUINT stackLevel) { asIScriptFunction *func = GetFunction(stackLevel); if( func == 0 ) return asINVALID_ARG; if( func->GetObjectType() == 0 ) return 0; // not in a method // create a datatype asCDataType dt = asCDataType::CreateType((asCObjectType*)func->GetObjectType(), false); // return a typeId from the data type return m_engine->GetTypeIdFromDataType(dt); } // interface // returns the 'this' object pointer at the given call stack level (-1 for current) // returns 0 if the function call at the given stack level is not a method void *asCContext::GetThisPointer(asUINT stackLevel) { if( stackLevel >= GetCallstackSize() ) return 0; asCScriptFunction *func; asDWORD *sf; if( stackLevel == 0 ) { func = m_currentFunction; sf = m_regs.stackFramePointer; } else { asPWORD *s = m_callStack.AddressOf() + (GetCallstackSize()-stackLevel-1)*CALLSTACK_FRAME_SIZE; func = (asCScriptFunction*)s[1]; sf = (asDWORD*)s[0]; } if( func == 0 ) return 0; if( func->objectType == 0 ) return 0; // not in a method void *thisPointer = (void*)*(asPWORD*)(sf); if( thisPointer == 0 ) { return 0; } // NOTE: this returns the pointer to the 'this' while the GetVarPointer functions return // a pointer to a pointer. I can't imagine someone would want to change the 'this' return thisPointer; } // TODO: Move these to as_utils.cpp struct POW_INFO { asQWORD MaxBaseu64; asDWORD MaxBasei64; asWORD MaxBaseu32; asWORD MaxBasei32; char HighBit; }; const POW_INFO pow_info[] = { { 0ULL, 0UL, 0, 0, 0 }, // 0 is a special case { 0ULL, 0UL, 0, 0, 1 }, // 1 is a special case { 3037000499ULL, 2147483647UL, 65535, 46340, 2 }, // 2 { 2097152ULL, 1664510UL, 1625, 1290, 2 }, // 3 { 55108ULL, 46340UL, 255, 215, 3 }, // 4 { 6208ULL, 5404UL, 84, 73, 3 }, // 5 { 1448ULL, 1290UL, 40, 35, 3 }, // 6 { 511ULL, 463UL, 23, 21, 3 }, // 7 { 234ULL, 215UL, 15, 14, 4 }, // 8 { 128ULL, 118UL, 11, 10, 4 }, // 9 { 78ULL, 73UL, 9, 8, 4 }, // 10 { 52ULL, 49UL, 7, 7, 4 }, // 11 { 38ULL, 35UL, 6, 5, 4 }, // 12 { 28ULL, 27UL, 5, 5, 4 }, // 13 { 22ULL, 21UL, 4, 4, 4 }, // 14 { 18ULL, 17UL, 4, 4, 4 }, // 15 { 15ULL, 14UL, 3, 3, 5 }, // 16 { 13ULL, 12UL, 3, 3, 5 }, // 17 { 11ULL, 10UL, 3, 3, 5 }, // 18 { 9ULL, 9UL, 3, 3, 5 }, // 19 { 8ULL, 8UL, 3, 2, 5 }, // 20 { 8ULL, 7UL, 2, 2, 5 }, // 21 { 7ULL, 7UL, 2, 2, 5 }, // 22 { 6ULL, 6UL, 2, 2, 5 }, // 23 { 6ULL, 5UL, 2, 2, 5 }, // 24 { 5ULL, 5UL, 2, 2, 5 }, // 25 { 5ULL, 5UL, 2, 2, 5 }, // 26 { 5ULL, 4UL, 2, 2, 5 }, // 27 { 4ULL, 4UL, 2, 2, 5 }, // 28 { 4ULL, 4UL, 2, 2, 5 }, // 29 { 4ULL, 4UL, 2, 2, 5 }, // 30 { 4ULL, 4UL, 2, 1, 5 }, // 31 { 3ULL, 3UL, 1, 1, 6 }, // 32 { 3ULL, 3UL, 1, 1, 6 }, // 33 { 3ULL, 3UL, 1, 1, 6 }, // 34 { 3ULL, 3UL, 1, 1, 6 }, // 35 { 3ULL, 3UL, 1, 1, 6 }, // 36 { 3ULL, 3UL, 1, 1, 6 }, // 37 { 3ULL, 3UL, 1, 1, 6 }, // 38 { 3ULL, 3UL, 1, 1, 6 }, // 39 { 2ULL, 2UL, 1, 1, 6 }, // 40 { 2ULL, 2UL, 1, 1, 6 }, // 41 { 2ULL, 2UL, 1, 1, 6 }, // 42 { 2ULL, 2UL, 1, 1, 6 }, // 43 { 2ULL, 2UL, 1, 1, 6 }, // 44 { 2ULL, 2UL, 1, 1, 6 }, // 45 { 2ULL, 2UL, 1, 1, 6 }, // 46 { 2ULL, 2UL, 1, 1, 6 }, // 47 { 2ULL, 2UL, 1, 1, 6 }, // 48 { 2ULL, 2UL, 1, 1, 6 }, // 49 { 2ULL, 2UL, 1, 1, 6 }, // 50 { 2ULL, 2UL, 1, 1, 6 }, // 51 { 2ULL, 2UL, 1, 1, 6 }, // 52 { 2ULL, 2UL, 1, 1, 6 }, // 53 { 2ULL, 2UL, 1, 1, 6 }, // 54 { 2ULL, 2UL, 1, 1, 6 }, // 55 { 2ULL, 2UL, 1, 1, 6 }, // 56 { 2ULL, 2UL, 1, 1, 6 }, // 57 { 2ULL, 2UL, 1, 1, 6 }, // 58 { 2ULL, 2UL, 1, 1, 6 }, // 59 { 2ULL, 2UL, 1, 1, 6 }, // 60 { 2ULL, 2UL, 1, 1, 6 }, // 61 { 2ULL, 2UL, 1, 1, 6 }, // 62 { 2ULL, 1UL, 1, 1, 6 }, // 63 }; int as_powi(int base, int exponent, bool& isOverflow) { if( exponent < 0 ) { if( base == 0 ) // Divide by zero isOverflow = true; else // Result is less than 1, so it truncates to 0 isOverflow = false; return 0; } else if( exponent == 0 && base == 0 ) { // Domain error isOverflow = true; return 0; } else if( exponent >= 31 ) { switch( base ) { case -1: isOverflow = false; return exponent & 1 ? -1 : 1; case 0: isOverflow = false; break; case 1: isOverflow = false; return 1; default: isOverflow = true; break; } return 0; } else { const asWORD max_base = pow_info[exponent].MaxBasei32; const char high_bit = pow_info[exponent].HighBit; if( max_base != 0 && max_base < (base < 0 ? -base : base) ) { isOverflow = true; return 0; // overflow } int result = 1; switch( high_bit ) { case 5: if( exponent & 1 ) result *= base; exponent >>= 1; base *= base; case 4: if( exponent & 1 ) result *= base; exponent >>= 1; base *= base; case 3: if( exponent & 1 ) result *= base; exponent >>= 1; base *= base; case 2: if( exponent & 1 ) result *= base; exponent >>= 1; base *= base; case 1: if( exponent ) result *= base; default: isOverflow = false; return result; } } } asDWORD as_powu(asDWORD base, asDWORD exponent, bool& isOverflow) { if( exponent == 0 && base == 0 ) { // Domain error isOverflow = true; return 0; } else if( exponent >= 32 ) { switch( base ) { case 0: isOverflow = false; break; case 1: isOverflow = false; return 1; default: isOverflow = true; break; } return 0; } else { const asWORD max_base = pow_info[exponent].MaxBaseu32; const char high_bit = pow_info[exponent].HighBit; if( max_base != 0 && max_base < base ) { isOverflow = true; return 0; // overflow } asDWORD result = 1; switch( high_bit ) { case 5: if( exponent & 1 ) result *= base; exponent >>= 1; base *= base; case 4: if( exponent & 1 ) result *= base; exponent >>= 1; base *= base; case 3: if( exponent & 1 ) result *= base; exponent >>= 1; base *= base; case 2: if( exponent & 1 ) result *= base; exponent >>= 1; base *= base; case 1: if( exponent ) result *= base; default: isOverflow = false; return result; } } } asINT64 as_powi64(asINT64 base, asINT64 exponent, bool& isOverflow) { if( exponent < 0 ) { if( base == 0 ) // Divide by zero isOverflow = true; else // Result is less than 1, so it truncates to 0 isOverflow = false; return 0; } else if( exponent == 0 && base == 0 ) { // Domain error isOverflow = true; return 0; } else if( exponent >= 63 ) { switch( base ) { case -1: isOverflow = false; return exponent & 1 ? -1 : 1; case 0: isOverflow = false; break; case 1: isOverflow = false; return 1; default: isOverflow = true; break; } return 0; } else { const asDWORD max_base = pow_info[exponent].MaxBasei64; const char high_bit = pow_info[exponent].HighBit; if( max_base != 0 && max_base < (base < 0 ? -base : base) ) { isOverflow = true; return 0; // overflow } asINT64 result = 1; switch( high_bit ) { case 6: if( exponent & 1 ) result *= base; exponent >>= 1; base *= base; case 5: if( exponent & 1 ) result *= base; exponent >>= 1; base *= base; case 4: if( exponent & 1 ) result *= base; exponent >>= 1; base *= base; case 3: if( exponent & 1 ) result *= base; exponent >>= 1; base *= base; case 2: if( exponent & 1 ) result *= base; exponent >>= 1; base *= base; case 1: if( exponent ) result *= base; default: isOverflow = false; return result; } } } asQWORD as_powu64(asQWORD base, asQWORD exponent, bool& isOverflow) { if( exponent == 0 && base == 0 ) { // Domain error isOverflow = true; return 0; } else if( exponent >= 64 ) { switch( base ) { case 0: isOverflow = false; break; case 1: isOverflow = false; return 1; default: isOverflow = true; break; } return 0; } else { const asQWORD max_base = pow_info[exponent].MaxBaseu64; const char high_bit = pow_info[exponent].HighBit; if( max_base != 0 && max_base < base ) { isOverflow = true; return 0; // overflow } asQWORD result = 1; switch( high_bit ) { case 6: if( exponent & 1 ) result *= base; exponent >>= 1; base *= base; case 5: if( exponent & 1 ) result *= base; exponent >>= 1; base *= base; case 4: if( exponent & 1 ) result *= base; exponent >>= 1; base *= base; case 3: if( exponent & 1 ) result *= base; exponent >>= 1; base *= base; case 2: if( exponent & 1 ) result *= base; exponent >>= 1; base *= base; case 1: if( exponent ) result *= base; default: isOverflow = false; return result; } } } END_AS_NAMESPACE
mit
ywong19/napa
lib/napa/deprecations/application_api.rb
412
module Napa class Deprecations URL = 'https://github.com/bellycard/napa/blob/master/lib/napa/cli/templates/new/app/apis/application_api.rb' WARNING = "no application_api.rb file found in app/apis, see #{URL} for an example" def self.application_api_check unless File.exists?('./app/apis/application_api.rb') ActiveSupport::Deprecation.warn WARNING, caller end end end end
mit
polats/aframe-polats-extras
src/lib/ParabolicCurve.js
496
/* global THREE */ // Parabolic motion equation, y = p0 + v0*t + 1/2at^2 function parabolicCurveScalar (p0, v0, a, t) { return p0 + v0 * t + 0.5 * a * t * t; } // Parabolic motion equation applied to 3 dimensions function parabolicCurve (p0, v0, a, t) { var ret = new THREE.Vector3(); ret.x = parabolicCurveScalar(p0.x, v0.x, a.x, t); ret.y = parabolicCurveScalar(p0.y, v0.y, a.y, t); ret.z = parabolicCurveScalar(p0.z, v0.z, a.z, t); return ret; } module.exports = parabolicCurve;
mit
mrkno/TvdbApi
tvdbApi/TvdbEpisode.cs
15326
using System; using System.ComponentModel; using System.Xml.Serialization; namespace MediaFileParser.MediaTypes.TvFile.Tvdb { /// <summary> /// Categories that an episode image could be. /// </summary> public enum TvdbEpisodeImageFlag { /// <summary> /// Indicates an image is a proper 4:3 (1.31 to 1.35) aspect ratio. /// </summary> Proper4By3 = 1, /// <summary> /// Indicates an image is a proper 16:9 (1.739 to 1.818) aspect ratio. /// </summary> Proper16By9 = 2, /// <summary> /// Indicates anything not in a 4:3 or 16:9 ratio. TVDB doesn't bother listing any other non standard ratios. /// </summary> InvalidAspectRatio = 3, /// <summary> /// Image is smaller then 300x170. /// </summary> ImageTooSmall = 4, /// <summary> /// Indicates there are black bars along one or all four sides of the image. /// </summary> BlackBars = 5, /// <summary> /// Could mean a number of things, usually used when someone uploads a promotional picture that isn't actually /// from that episode but does refrence the episode, it could also mean it's a credit shot or that there is /// writting all over it. It's rarely used. /// </summary> ImproperActionShot = 6 } /// <summary> /// TV Show individual episode data from the TVDB. /// </summary> [Serializable, ReadOnly(true), XmlType("Episode", AnonymousType = true)] public class TvdbEpisode { /// <summary> /// This class should only be deserialised, not instantiated directly. /// </summary> protected TvdbEpisode() {} /// <summary> /// An unsigned integer assigned by the TVDB to the episode. Cannot be null. /// </summary> [XmlElement(ElementName = "id")] public uint TvdbId { get; set; } /// <summary> /// This returns the value of DvdEpisodeNumber if that field is not null. /// Otherwise it returns the value from EpisodeNumber. Cannot be null. /// </summary> [XmlElement(ElementName = "Combined_episodenumber")] public decimal CombinedEpisodeNumber { get; set; } /// <summary> /// This returns the value of DVD_season if that field is not null. /// Otherwise it returns the value from SeasonNumber. Cannot be null. /// </summary> [XmlElement(ElementName = "Combined_season")] public uint CombinedSeason { get; set; } /// <summary> /// Was meant to be used to aid in scrapping of actual DVD's but has never been populated properly. /// Any information returned in this field shouldn't be trusted. Will usually be null. /// /// This field has been deprecated and should not be trusted. /// </summary> [XmlElement(ElementName = "DVD_chapter")] public string DvdChapter { get; set; } /// <summary> /// Was meant to be used to aid in scrapping of actual DVD's but has never been populated properly. /// Any information returned in this field shouldn't be trusted. Will usually be null. /// /// This field has been deprecated and should not be trusted. /// </summary> [XmlElement(ElementName = "DVD_discid")] public string DvdDiscId { get; set; } /// <summary> /// Used to join episodes that aired as two episodes but were released on DVD as a single episode. /// Can be null. If you see an episode 1.1 and 1.2 that means both records should be combined to make episode 1. /// </summary> [XmlElement(ElementName = "DVD_episodenumber")] public string DvdEpisodeNumberString { get; set; } /// <summary> /// Used to join episodes that aired as two episodes but were released on DVD as a single episode. /// If you see an episode 1.1 and 1.2 that means both records should be combined to make episode 1. /// Throws an exception if null. /// </summary> [XmlIgnore] public double DvdEpisodeNumber { get { return double.Parse(DvdEpisodeNumberString); } } /// <summary> /// An unsigned integer indicating the season the episode was in according to the DVD release. /// Usually is the same as SeasonNumber but can be different. Can be null. /// </summary> [XmlElement(ElementName = "DVD_season")] public string DvdSeasonString { get; set; } /// <summary> /// An unsigned integer indicating the season the episode was in according to the DVD release. /// Usually is the same as SeasonNumber but can be different. Throws an exception if null. /// </summary> [XmlIgnore] public uint DvdSeason { get { return uint.Parse(DvdSeasonString); } } /// <summary> /// A pipe delimited string of directors in plain text. Can be null. /// </summary> [XmlElement(ElementName = "Director")] public string Director { get; set; } /// <summary> /// Array of all directors that produced the episode. Throws an exception if null. /// </summary> [XmlIgnore] public string[] Directors { get { return Director.Split('|'); } } /// <summary> /// Category that the current episode image falls in to (as a string). /// </summary> [XmlElement(ElementName = "EpImgFlag")] public string EpisodeImageFlagString { get { return ((int) EpisodeImageFlag).ToString(); } set { TvdbEpisodeImageFlag flag; EpisodeImageFlag = Enum.TryParse(value, out flag) ? flag : TvdbEpisodeImageFlag.ImproperActionShot; } } /// <summary> /// Category that the current episode image falls in to. Defaults to ImproperActionShot. /// </summary> [XmlIgnore] public TvdbEpisodeImageFlag EpisodeImageFlag { get; set; } /// <summary> /// Episode name in the current API localisation. /// </summary> [XmlElement("EpisodeName")] public string EpisodeName { get; set; } /// <summary> /// Episode number in its season. Cannot be null. /// </summary> [XmlElement(ElementName = "EpisodeNumber")] public uint EpisodeNumber { get; set; } /// <summary> /// The date the series first aired in plain text using the format "YYYY-MM-DD". Can be null. /// </summary> [XmlElement(ElementName = "FirstAired")] public string FirstAiredString { get; set; } /// <summary> /// The date the series first aired. Throws an exception if null. /// </summary> [XmlIgnore] public DateTime FirstAiredDate { get { return DateTime.Parse(FirstAiredString); } } /// <summary> /// A pipe delimited string of guest stars in plain text. Can be null. /// </summary> [XmlElement(ElementName = "GuestStars")] public string GuestStarsString { get; set; } /// <summary> /// Guest stars in this episode. Throws an exception if null. /// </summary> [XmlIgnore] public string[] GuestStars { get { return GuestStarsString.Split(new[] {'|'}, StringSplitOptions.RemoveEmptyEntries); } } /// <summary> /// An alphanumeric string containing the IMDB ID for the series. Can be null. /// </summary> [XmlElement(ElementName = "IMDB_ID")] public string ImdbId { get; set; } /// <summary> /// A two character string indicating the language in accordance with ISO-639-1. Cannot be null. /// </summary> [XmlElement(ElementName = "Language")] public string Language { get; set; } /// <summary> /// Short description of the content of the episode. Can be null. /// </summary> [XmlElement(ElementName = "Overview")] public string Synopsis { get; set; } /// <summary> /// An alphanumeric string. Can be null. /// </summary> [XmlElement(ElementName = "ProductionCode")] public string ProductionCode { get; set; } /// <summary> /// The average rating TVDB users have rated the series out of 10, rounded to 1 decimal place. Can be null. /// </summary> [XmlElement(ElementName = "Rating")] public string RatingString { get; set; } /// <summary> /// The average rating TVDB users have rated the series out of 10, rounded to 1 decimal place. Throws an exception if null. /// </summary> [XmlIgnore] public float Rating { get { return float.Parse(RatingString); } } /// <summary> /// Number of TVDB users who have rated the series. Can be null. /// </summary> [XmlElement(ElementName = "RatingCount")] public string RatingCountString { get; set; } /// <summary> /// Number of TVDB users who have rated the series. Throws an exception if null. /// </summary> [XmlIgnore] public uint RatingCount { get { return uint.Parse(RatingCountString); } } /// <summary> /// Season number for the episode according to the aired order. Cannot be null. /// </summary> [XmlElement(ElementName = "SeasonNumber")] public uint SeasonNumber { get; set; } /// <summary> /// A pipe delimited string of writers in plain text. Can be null. /// </summary> [XmlElement(ElementName = "Writer")] public string WriterString { get; set; } /// <summary> /// Writers of this episode. Throws an exception if null. /// </summary> [XmlIgnore] public string[] Writers { get { return WriterString.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); } } /// <summary> /// Indicates the absolute episode number (completely ignoring seasons). Can be null. /// </summary> [XmlElement("absolute_number")] public string AbsoluteNumberString { get; set; } /// <summary> /// Indicates the absolute episode number (completely ignoring seasons). Throws an exception if null. /// </summary> [XmlIgnore] public uint AbsoluteNumber { get { return uint.Parse(AbsoluteNumberString); } } /// <summary> /// Indicates the season number this episode comes after. This field is only available for special episodes. Can be null. /// </summary> [XmlElement(ElementName = "airsafter_season")] public string AirsAfterSeasonString { get; set; } /// <summary> /// Indicates the season number this episode comes after. This field is only available for special episodes. Throws an exception if null. /// </summary> [XmlIgnore] public uint AirsAfterSeason { get { return uint.Parse(AirsAfterSeasonString); } } /// <summary> /// Indicates the episode number this special episode airs before. Used in conjunction with AirsBeforeSeason, /// but not with AirsAfterSeason. This field is only available for special episodes. Can be null. /// </summary> [XmlElement(ElementName = "airsbefore_episode")] public string AirsBeforeEpisodeString { get; set; } /// <summary> /// Indicates the episode number this special episode airs before. Used in conjunction with AirsBeforeSeason, /// but not with AirsAfterSeason. This field is only available for special episodes. Throws an exception if null. /// </summary> [XmlIgnore] public uint AirsBeforeEpisode { get { return uint.Parse(AirsBeforeEpisodeString); } } /// <summary> /// Indicates the season number this special episode airs before. Used in conjunction with AirsBeforeEpisode /// for exact placement. This field is only available for special episodes. Can be null. /// </summary> [XmlElement(ElementName = "airsbefore_season")] public string AirsBeforeSeasonString { get; set; } /// <summary> /// Indicates the season number this special episode airs before. Used in conjunction with AirsBeforeEpisode /// for exact placement. This field is only available for special episodes. Throws an exception if null. /// </summary> [XmlIgnore] public uint AirsBeforeSeason { get { return uint.Parse(AirsBeforeSeasonString); } } /// <summary> /// A string which should be appended to http://thetvdb.com/banners/ to determine the /// actual location of the artwork. Returns the location of the episode image. Can be null. /// </summary> [XmlElement(ElementName = "filename")] public string FileName { get; set; } /// <summary> /// Unix time stamp indicating the last time any changes were made to the episode. Can be null. /// </summary> [XmlElement(ElementName = "lastupdated")] public uint LastUpdated { get; set; } /// <summary> /// An unsigned integer assigned by the TVDB to the season. Cannot be null. /// </summary> [XmlElement(ElementName = "seasonid")] public uint SeasonId { get; set; } /// <summary> /// An unsigned integer assigned by the TVDB to the series. It does not change and will /// always represent the same series. Cannot be null. /// </summary> [XmlElement(ElementName = "seriesid")] public uint SeriesId { get; set; } /// <summary> /// Time the episode image was added to the TVDB in the format "YYYY-MM-DD HH:MM:SS" /// based on a 24 hour clock. Can be null. /// </summary> [XmlElement(ElementName = "thumb_added")] public string ThumbnailAddedString { get; set; } /// <summary> /// Date/time the episode image was added to the TVDB. Throws an exception if null. /// </summary> [XmlIgnore] public DateTime ThumbnailAdded { get { return DateTime.Parse(ThumbnailAddedString); } } /// <summary> /// Represents the height of the episode image in pixels. Can be null. /// </summary> [XmlElement(ElementName = "thumb_height")] public string ThumbnailHeightString { get; set; } /// <summary> /// Represents the height of the episode image in pixels. Throws an exception if null. /// </summary> [XmlIgnore] public uint ThumbnailHeight { get { return uint.Parse(ThumbnailHeightString); } } /// <summary> /// Represents the width of the episode image in pixels. Can be null. /// </summary> [XmlElement(ElementName = "thumb_width")] public string ThumbnailWidthString { get; set; } /// <summary> /// Represents the width of the episode image in pixels. Throws an exception if null. /// </summary> [XmlIgnore] public uint ThumbnailWidth { get { return uint.Parse(ThumbnailWidthString); } } } }
mit
akochurov/mxcache
mxcache-idea-api-stubs/src/main/java/com/intellij/psi/util/PsiTreeUtil.java
464
/* * Copyright (c) 2008-2014 Maxifier Ltd. All Rights Reserved. */ package com.intellij.psi.util; import com.intellij.psi.PsiElement; /** * THIS CLASS WAS GENERATED AUTOMATICALLY WITH StubGen BASED ON IDEA BINARIES * DON'T MODIFY IT MANUALLY! * @author Alexander Kochurov (alexander.kochurov@maxifier.com) */ public class PsiTreeUtil { public static PsiElement[] collectElements(PsiElement p1, PsiElementFilter p2) { return null; } }
mit
almadaocta/lordbike-production
errors/includes/src/phpseclib_Crypt_TripleDES.php
23979
<?php /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ /** * Pure-PHP implementation of Triple DES. * * Uses mcrypt, if available, and an internal implementation, otherwise. Operates in the EDE3 mode (encrypt-decrypt-encrypt). * * PHP versions 4 and 5 * * Here's a short example of how to use this library: * <code> * <?php * include('Crypt/TripleDES.php'); * * $des = new Crypt_TripleDES(); * * $des->setKey('abcdefghijklmnopqrstuvwx'); * * $size = 10 * 1024; * $plaintext = ''; * for ($i = 0; $i < $size; $i++) { * $plaintext.= 'a'; * } * * echo $des->decrypt($des->encrypt($plaintext)); * ?> * </code> * * LICENSE: This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * @category Crypt * @package Crypt_TripleDES * @author Jim Wigginton <terrafrost@php.net> * @copyright MMVII Jim Wigginton * @license http://www.gnu.org/licenses/lgpl.txt * @version $Id: TripleDES.php,v 1.13 2010/02/26 03:40:25 terrafrost Exp $ * @link http://phpseclib.sourceforge.net */ /** * Include Crypt_DES */ require_once 'DES.php'; /** * Encrypt / decrypt using inner chaining * * Inner chaining is used by SSH-1 and is generally considered to be less secure then outer chaining (CRYPT_DES_MODE_CBC3). */ define('CRYPT_DES_MODE_3CBC', 3); /** * Encrypt / decrypt using outer chaining * * Outer chaining is used by SSH-2 and when the mode is set to CRYPT_DES_MODE_CBC. */ define('CRYPT_DES_MODE_CBC3', CRYPT_DES_MODE_CBC); /** * Pure-PHP implementation of Triple DES. * * @author Jim Wigginton <terrafrost@php.net> * @version 0.1.0 * @access public * @package Crypt_TerraDES */ class Crypt_TripleDES { /** * The Three Keys * * @see Crypt_TripleDES::setKey() * @var String * @access private */ var $key = "\0\0\0\0\0\0\0\0"; /** * The Encryption Mode * * @see Crypt_TripleDES::Crypt_TripleDES() * @var Integer * @access private */ var $mode = CRYPT_DES_MODE_CBC; /** * Continuous Buffer status * * @see Crypt_TripleDES::enableContinuousBuffer() * @var Boolean * @access private */ var $continuousBuffer = false; /** * Padding status * * @see Crypt_TripleDES::enablePadding() * @var Boolean * @access private */ var $padding = true; /** * The Initialization Vector * * @see Crypt_TripleDES::setIV() * @var String * @access private */ var $iv = "\0\0\0\0\0\0\0\0"; /** * A "sliding" Initialization Vector * * @see Crypt_TripleDES::enableContinuousBuffer() * @var String * @access private */ var $encryptIV = "\0\0\0\0\0\0\0\0"; /** * A "sliding" Initialization Vector * * @see Crypt_TripleDES::enableContinuousBuffer() * @var String * @access private */ var $decryptIV = "\0\0\0\0\0\0\0\0"; /** * The Crypt_DES objects * * @var Array * @access private */ var $des; /** * mcrypt resource for encryption * * The mcrypt resource can be recreated every time something needs to be created or it can be created just once. * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode. * * @see Crypt_AES::encrypt() * @var String * @access private */ var $enmcrypt; /** * mcrypt resource for decryption * * The mcrypt resource can be recreated every time something needs to be created or it can be created just once. * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode. * * @see Crypt_AES::decrypt() * @var String * @access private */ var $demcrypt; /** * Does the (en|de)mcrypt resource need to be (re)initialized? * * @see setKey() * @see setIV() * @var Boolean * @access private */ var $changed = true; /** * Default Constructor. * * Determines whether or not the mcrypt extension should be used. $mode should only, at present, be * CRYPT_DES_MODE_ECB or CRYPT_DES_MODE_CBC. If not explictly set, CRYPT_DES_MODE_CBC will be used. * * @param optional Integer $mode * @return Crypt_TripleDES * @access public */ function Crypt_TripleDES($mode = CRYPT_DES_MODE_CBC) { if ( !defined('CRYPT_DES_MODE') ) { switch (true) { case extension_loaded('mcrypt'): // i'd check to see if des was supported, by doing in_array('des', mcrypt_list_algorithms('')), // but since that can be changed after the object has been created, there doesn't seem to be // a lot of point... define('CRYPT_DES_MODE', CRYPT_DES_MODE_MCRYPT); break; default: define('CRYPT_DES_MODE', CRYPT_DES_MODE_INTERNAL); } } if ( $mode == CRYPT_DES_MODE_3CBC ) { $this->mode = CRYPT_DES_MODE_3CBC; $this->des = array( new Crypt_DES(CRYPT_DES_MODE_CBC), new Crypt_DES(CRYPT_DES_MODE_CBC), new Crypt_DES(CRYPT_DES_MODE_CBC) ); // we're going to be doing the padding, ourselves, so disable it in the Crypt_DES objects $this->des[0]->disablePadding(); $this->des[1]->disablePadding(); $this->des[2]->disablePadding(); return; } switch ( CRYPT_DES_MODE ) { case CRYPT_DES_MODE_MCRYPT: switch ($mode) { case CRYPT_DES_MODE_ECB: $this->mode = MCRYPT_MODE_ECB; break; case CRYPT_DES_MODE_CTR: $this->mode = 'ctr'; break; case CRYPT_DES_MODE_CBC: default: $this->mode = MCRYPT_MODE_CBC; } break; default: $this->des = array( new Crypt_DES(CRYPT_DES_MODE_ECB), new Crypt_DES(CRYPT_DES_MODE_ECB), new Crypt_DES(CRYPT_DES_MODE_ECB) ); // we're going to be doing the padding, ourselves, so disable it in the Crypt_DES objects $this->des[0]->disablePadding(); $this->des[1]->disablePadding(); $this->des[2]->disablePadding(); switch ($mode) { case CRYPT_DES_MODE_ECB: case CRYPT_DES_MODE_CTR: case CRYPT_DES_MODE_CBC: $this->mode = $mode; break; default: $this->mode = CRYPT_DES_MODE_CBC; } } } /** * Sets the key. * * Keys can be of any length. Triple DES, itself, can use 128-bit (eg. strlen($key) == 16) or * 192-bit (eg. strlen($key) == 24) keys. This function pads and truncates $key as appropriate. * * DES also requires that every eighth bit be a parity bit, however, we'll ignore that. * * If the key is not explicitly set, it'll be assumed to be all zero's. * * @access public * @param String $key */ function setKey($key) { $length = strlen($key); if ($length > 8) { $key = str_pad($key, 24, chr(0)); // if $key is between 64 and 128-bits, use the first 64-bits as the last, per this: // http://php.net/function.mcrypt-encrypt#47973 //$key = $length <= 16 ? substr_replace($key, substr($key, 0, 8), 16) : substr($key, 0, 24); } $this->key = $key; switch (true) { case CRYPT_DES_MODE == CRYPT_DES_MODE_INTERNAL: case $this->mode == CRYPT_DES_MODE_3CBC: $this->des[0]->setKey(substr($key, 0, 8)); $this->des[1]->setKey(substr($key, 8, 8)); $this->des[2]->setKey(substr($key, 16, 8)); } $this->changed = true; } /** * Sets the initialization vector. (optional) * * SetIV is not required when CRYPT_DES_MODE_ECB is being used. If not explictly set, it'll be assumed * to be all zero's. * * @access public * @param String $iv */ function setIV($iv) { $this->encryptIV = $this->decryptIV = $this->iv = str_pad(substr($iv, 0, 8), 8, chr(0)); if ($this->mode == CRYPT_DES_MODE_3CBC) { $this->des[0]->setIV($iv); $this->des[1]->setIV($iv); $this->des[2]->setIV($iv); } $this->changed = true; } /** * Generate CTR XOR encryption key * * Encrypt the output of this and XOR it against the ciphertext / plaintext to get the * plaintext / ciphertext in CTR mode. * * @see Crypt_DES::decrypt() * @see Crypt_DES::encrypt() * @access public * @param Integer $length * @param String $iv */ function _generate_xor($length, &$iv) { $xor = ''; $num_blocks = ($length + 7) >> 3; for ($i = 0; $i < $num_blocks; $i++) { $xor.= $iv; for ($j = 4; $j <= 8; $j+=4) { $temp = substr($iv, -$j, 4); switch ($temp) { case "\xFF\xFF\xFF\xFF": $iv = substr_replace($iv, "\x00\x00\x00\x00", -$j, 4); break; case "\x7F\xFF\xFF\xFF": $iv = substr_replace($iv, "\x80\x00\x00\x00", -$j, 4); break 2; default: extract(unpack('Ncount', $temp)); $iv = substr_replace($iv, pack('N', $count + 1), -$j, 4); break 2; } } } return $xor; } /** * Encrypts a message. * * @access public * @param String $plaintext */ function encrypt($plaintext) { if ($this->mode != CRYPT_DES_MODE_CTR && $this->mode != 'ctr') { $plaintext = $this->_pad($plaintext); } // if the key is smaller then 8, do what we'd normally do if ($this->mode == CRYPT_DES_MODE_3CBC && strlen($this->key) > 8) { $ciphertext = $this->des[2]->encrypt($this->des[1]->decrypt($this->des[0]->encrypt($plaintext))); return $ciphertext; } if ( CRYPT_DES_MODE == CRYPT_DES_MODE_MCRYPT ) { if ($this->changed) { if (!isset($this->enmcrypt)) { $this->enmcrypt = mcrypt_module_open(MCRYPT_3DES, '', $this->mode, ''); } mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV); $this->changed = false; } $ciphertext = mcrypt_generic($this->enmcrypt, $plaintext); if (!$this->continuousBuffer) { mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV); } return $ciphertext; } if (strlen($this->key) <= 8) { $this->des[0]->mode = $this->mode; return $this->des[0]->encrypt($plaintext); } // we pad with chr(0) since that's what mcrypt_generic does. to quote from http://php.net/function.mcrypt-generic : // "The data is padded with "\0" to make sure the length of the data is n * blocksize." $plaintext = str_pad($plaintext, ceil(strlen($plaintext) / 8) * 8, chr(0)); $des = $this->des; $ciphertext = ''; switch ($this->mode) { case CRYPT_DES_MODE_ECB: for ($i = 0; $i < strlen($plaintext); $i+=8) { $block = substr($plaintext, $i, 8); $block = $des[0]->_processBlock($block, CRYPT_DES_ENCRYPT); $block = $des[1]->_processBlock($block, CRYPT_DES_DECRYPT); $block = $des[2]->_processBlock($block, CRYPT_DES_ENCRYPT); $ciphertext.= $block; } break; case CRYPT_DES_MODE_CBC: $xor = $this->encryptIV; for ($i = 0; $i < strlen($plaintext); $i+=8) { $block = substr($plaintext, $i, 8) ^ $xor; $block = $des[0]->_processBlock($block, CRYPT_DES_ENCRYPT); $block = $des[1]->_processBlock($block, CRYPT_DES_DECRYPT); $block = $des[2]->_processBlock($block, CRYPT_DES_ENCRYPT); $xor = $block; $ciphertext.= $block; } if ($this->continuousBuffer) { $this->encryptIV = $xor; } break; case CRYPT_DES_MODE_CTR: $xor = $this->encryptIV; for ($i = 0; $i < strlen($plaintext); $i+=8) { $key = $this->_generate_xor(8, $xor); $key = $des[0]->_processBlock($key, CRYPT_DES_ENCRYPT); $key = $des[1]->_processBlock($key, CRYPT_DES_DECRYPT); $key = $des[2]->_processBlock($key, CRYPT_DES_ENCRYPT); $block = substr($plaintext, $i, 8); $ciphertext.= $block ^ $key; } if ($this->continuousBuffer) { $this->encryptIV = $xor; } } return $ciphertext; } /** * Decrypts a message. * * @access public * @param String $ciphertext */ function decrypt($ciphertext) { if ($this->mode == CRYPT_DES_MODE_3CBC && strlen($this->key) > 8) { $plaintext = $this->des[0]->decrypt($this->des[1]->encrypt($this->des[2]->decrypt($ciphertext))); return $this->_unpad($plaintext); } // we pad with chr(0) since that's what mcrypt_generic does. to quote from http://php.net/function.mcrypt-generic : // "The data is padded with "\0" to make sure the length of the data is n * blocksize." $ciphertext = str_pad($ciphertext, (strlen($ciphertext) + 7) & 0xFFFFFFF8, chr(0)); if ( CRYPT_DES_MODE == CRYPT_DES_MODE_MCRYPT ) { if ($this->changed) { if (!isset($this->demcrypt)) { $this->demcrypt = mcrypt_module_open(MCRYPT_3DES, '', $this->mode, ''); } mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV); $this->changed = false; } $plaintext = mdecrypt_generic($this->demcrypt, $ciphertext); if (!$this->continuousBuffer) { mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV); } return $this->mode != 'ctr' ? $this->_unpad($plaintext) : $plaintext; } if (strlen($this->key) <= 8) { $this->des[0]->mode = $this->mode; return $this->_unpad($this->des[0]->decrypt($plaintext)); } $des = $this->des; $plaintext = ''; switch ($this->mode) { case CRYPT_DES_MODE_ECB: for ($i = 0; $i < strlen($ciphertext); $i+=8) { $block = substr($ciphertext, $i, 8); $block = $des[2]->_processBlock($block, CRYPT_DES_DECRYPT); $block = $des[1]->_processBlock($block, CRYPT_DES_ENCRYPT); $block = $des[0]->_processBlock($block, CRYPT_DES_DECRYPT); $plaintext.= $block; } break; case CRYPT_DES_MODE_CBC: $xor = $this->decryptIV; for ($i = 0; $i < strlen($ciphertext); $i+=8) { $orig = $block = substr($ciphertext, $i, 8); $block = $des[2]->_processBlock($block, CRYPT_DES_DECRYPT); $block = $des[1]->_processBlock($block, CRYPT_DES_ENCRYPT); $block = $des[0]->_processBlock($block, CRYPT_DES_DECRYPT); $plaintext.= $block ^ $xor; $xor = $orig; } if ($this->continuousBuffer) { $this->decryptIV = $xor; } break; case CRYPT_DES_MODE_CTR: $xor = $this->decryptIV; for ($i = 0; $i < strlen($ciphertext); $i+=8) { $key = $this->_generate_xor(8, $xor); $key = $des[0]->_processBlock($key, CRYPT_DES_ENCRYPT); $key = $des[1]->_processBlock($key, CRYPT_DES_DECRYPT); $key = $des[2]->_processBlock($key, CRYPT_DES_ENCRYPT); $block = substr($ciphertext, $i, 8); $plaintext.= $block ^ $key; } if ($this->continuousBuffer) { $this->decryptIV = $xor; } } return $this->mode != CRYPT_DES_MODE_CTR ? $this->_unpad($plaintext) : $plaintext; } /** * Treat consecutive "packets" as if they are a continuous buffer. * * Say you have a 16-byte plaintext $plaintext. Using the default behavior, the two following code snippets * will yield different outputs: * * <code> * echo $des->encrypt(substr($plaintext, 0, 8)); * echo $des->encrypt(substr($plaintext, 8, 8)); * </code> * <code> * echo $des->encrypt($plaintext); * </code> * * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates * another, as demonstrated with the following: * * <code> * $des->encrypt(substr($plaintext, 0, 8)); * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8))); * </code> * <code> * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8))); * </code> * * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different * outputs. The reason is due to the fact that the initialization vector's change after every encryption / * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant. * * Put another way, when the continuous buffer is enabled, the state of the Crypt_DES() object changes after each * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them), * however, they are also less intuitive and more likely to cause you problems. * * @see Crypt_TripleDES::disableContinuousBuffer() * @access public */ function enableContinuousBuffer() { $this->continuousBuffer = true; if ($this->mode == CRYPT_DES_MODE_3CBC) { $this->des[0]->enableContinuousBuffer(); $this->des[1]->enableContinuousBuffer(); $this->des[2]->enableContinuousBuffer(); } } /** * Treat consecutive packets as if they are a discontinuous buffer. * * The default behavior. * * @see Crypt_TripleDES::enableContinuousBuffer() * @access public */ function disableContinuousBuffer() { $this->continuousBuffer = false; $this->encryptIV = $this->iv; $this->decryptIV = $this->iv; if ($this->mode == CRYPT_DES_MODE_3CBC) { $this->des[0]->disableContinuousBuffer(); $this->des[1]->disableContinuousBuffer(); $this->des[2]->disableContinuousBuffer(); } } /** * Pad "packets". * * DES works by encrypting eight bytes at a time. If you ever need to encrypt or decrypt something that's not * a multiple of eight, it becomes necessary to pad the input so that it's length is a multiple of eight. * * Padding is enabled by default. Sometimes, however, it is undesirable to pad strings. Such is the case in SSH1, * where "packets" are padded with random bytes before being encrypted. Unpad these packets and you risk stripping * away characters that shouldn't be stripped away. (SSH knows how many bytes are added because the length is * transmitted separately) * * @see Crypt_TripleDES::disablePadding() * @access public */ function enablePadding() { $this->padding = true; } /** * Do not pad packets. * * @see Crypt_TripleDES::enablePadding() * @access public */ function disablePadding() { $this->padding = false; } /** * Pads a string * * Pads a string using the RSA PKCS padding standards so that its length is a multiple of the blocksize (8). * 8 - (strlen($text) & 7) bytes are added, each of which is equal to chr(8 - (strlen($text) & 7) * * If padding is disabled and $text is not a multiple of the blocksize, the string will be padded regardless * and padding will, hence forth, be enabled. * * @see Crypt_TripleDES::_unpad() * @access private */ function _pad($text) { $length = strlen($text); if (!$this->padding) { if (($length & 7) == 0) { return $text; } else { user_error("The plaintext's length ($length) is not a multiple of the block size (8)", E_USER_NOTICE); $this->padding = true; } } $pad = 8 - ($length & 7); return str_pad($text, $length + $pad, chr($pad)); } /** * Unpads a string * * If padding is enabled and the reported padding length is invalid the encryption key will be assumed to be wrong * and false will be returned. * * @see Crypt_TripleDES::_pad() * @access private */ function _unpad($text) { if (!$this->padding) { return $text; } $length = ord($text[strlen($text) - 1]); if (!$length || $length > 8) { return false; } return substr($text, 0, -$length); } } // vim: ts=4:sw=4:et: // vim6: fdl=1:
mit
cdnjs/cdnjs
ajax/libs/primereact/6.4.0/components/utils/index.d.ts
72
export declare function classNames(...args: any[]): string | undefined;
mit
YMRYMR/duality
Test/Core/Components/ICmpInitializableTest.cs
8170
using System; using System.Text; using System.Collections.Generic; using System.Linq; using System.IO; using Duality; using Duality.Resources; using Duality.Components; using Duality.Serialization; using Duality.Tests.Components; using NUnit.Framework; namespace Duality.Tests.Components { [TestFixture] public class ICmpInitializableTest { private Scene scene; private GameObject obj; [SetUp] public void Setup() { this.scene = new Scene(); this.obj = new GameObject("TestObject"); this.scene.AddObject(this.obj); } [TearDown] public void Teardown() { this.scene.Dispose(); this.scene = null; this.obj = null; } [Test] public void AddRemove() { InitializableEventReceiver initTester = new InitializableEventReceiver(); // Adding and Removing this.obj.AddComponent(initTester); Assert.IsTrue(initTester.HasReceived(InitializableEventReceiver.EventFlag.AddToGameObject)); this.obj.RemoveComponent(initTester); Assert.IsTrue(initTester.HasReceived(InitializableEventReceiver.EventFlag.RemovingFromGameObject)); } [Test] public void ActivateDeactivate() { InitializableEventReceiver initTester = this.obj.AddComponent<InitializableEventReceiver>(); // Activate by Scene.Current Scene.SwitchTo(this.scene, true); Assert.IsTrue(initTester.HasReceived(InitializableEventReceiver.EventFlag.Activate), "Activate by Scene.Current"); initTester.Reset(); // Deactivate by GameObject.Active this.obj.Active = false; Assert.IsTrue(initTester.HasReceived(InitializableEventReceiver.EventFlag.Deactivate), "Deactivate by GameObject.Active"); initTester.Reset(); { // Removing inactive object shouldn't trigger events this.scene.RemoveObject(this.obj); Assert.IsFalse(initTester.HasReceived(InitializableEventReceiver.EventFlag.Deactivate), "Removing inactive object shouldn't trigger events"); initTester.Reset(); // Adding inactive object shouldn't trigger events this.scene.AddObject(this.obj); Assert.IsFalse(initTester.HasReceived(InitializableEventReceiver.EventFlag.Activate), "Adding inactive object shouldn't trigger events"); initTester.Reset(); // Removing inactive objects Component shouldn't trigger events this.obj.RemoveComponent(initTester); Assert.IsFalse(initTester.HasReceived(InitializableEventReceiver.EventFlag.Deactivate), "Removing inactive objects Component shouldn't trigger events"); initTester.Reset(); // Adding inactive objects Component shouldn't trigger events this.obj.AddComponent(initTester); Assert.IsFalse(initTester.HasReceived(InitializableEventReceiver.EventFlag.Activate), "Adding inactive objects Component shouldn't trigger events"); initTester.Reset(); } // Activate by GameObject.Active this.obj.Active = true; Assert.IsTrue(initTester.HasReceived(InitializableEventReceiver.EventFlag.Activate), "Activate by GameObject.Active"); initTester.Reset(); // Deactivate by Component.Active initTester.Active = false; Assert.IsTrue(initTester.HasReceived(InitializableEventReceiver.EventFlag.Deactivate), "Deactivate by Component.Active"); initTester.Reset(); { // Removing inactive Components object shouldn't trigger events this.scene.RemoveObject(this.obj); Assert.IsFalse(initTester.HasReceived(InitializableEventReceiver.EventFlag.Deactivate), "Removing inactive Components object shouldn't trigger events"); initTester.Reset(); // Adding inactive Components object shouldn't trigger events this.scene.AddObject(this.obj); Assert.IsFalse(initTester.HasReceived(InitializableEventReceiver.EventFlag.Activate), "Adding inactive Components object shouldn't trigger events"); initTester.Reset(); // Removing inactive Component shouldn't trigger events this.obj.RemoveComponent(initTester); Assert.IsFalse(initTester.HasReceived(InitializableEventReceiver.EventFlag.Deactivate), "Removing inactive Component shouldn't trigger events"); initTester.Reset(); // Adding inactive Component shouldn't trigger events this.obj.AddComponent(initTester); Assert.IsFalse(initTester.HasReceived(InitializableEventReceiver.EventFlag.Activate), "Adding inactive Component shouldn't trigger events"); initTester.Reset(); } // Activate by Component.Active initTester.Active = true; Assert.IsTrue(initTester.HasReceived(InitializableEventReceiver.EventFlag.Activate), "Activate by Component.Active"); initTester.Reset(); // Deactivate by removing from Scene this.scene.RemoveObject(this.obj); Assert.IsTrue(initTester.HasReceived(InitializableEventReceiver.EventFlag.Deactivate), "Deactivate by removing from Scene"); initTester.Reset(); // Activate by adding to Scene this.scene.AddObject(this.obj); Assert.IsTrue(initTester.HasReceived(InitializableEventReceiver.EventFlag.Activate), "Activate by adding to Scene"); initTester.Reset(); // Deactivate by Scene.Current Scene.SwitchTo(null, true); Assert.IsTrue(initTester.HasReceived(InitializableEventReceiver.EventFlag.Deactivate), "Deactivate by Scene.Current"); initTester.Reset(); } [Test] public void DeactivateGameObjectDispose() { InitializableEventReceiver initTester = this.obj.AddComponent<InitializableEventReceiver>(); Scene.SwitchTo(this.scene, true); this.obj.Dispose(); DualityApp.RunCleanup(); // Need to run cleanup, so disposed GameObjects will be processed. Assert.IsTrue(initTester.HasReceived(InitializableEventReceiver.EventFlag.Deactivate)); } [Test] public void DeactivateDeepGameObjectDispose() { GameObject childObj = new GameObject("ChildObject", this.obj); InitializableEventReceiver initTester = childObj.AddComponent<InitializableEventReceiver>(); Scene.SwitchTo(this.scene, true); this.obj.Dispose(); DualityApp.RunCleanup(); // Need to run cleanup, so disposed GameObjects will be processed. Assert.IsTrue(initTester.HasReceived(InitializableEventReceiver.EventFlag.Deactivate)); } [Test] public void DeactivateComponentDispose() { InitializableEventReceiver initTester = this.obj.AddComponent<InitializableEventReceiver>(); Scene.SwitchTo(this.scene, true); initTester.Dispose(); Assert.IsTrue(initTester.HasReceived(InitializableEventReceiver.EventFlag.Deactivate)); } [Test] public void DeactivateSceneDispose() { InitializableEventReceiver initTester = this.obj.AddComponent<InitializableEventReceiver>(); Scene.SwitchTo(this.scene, true); this.scene.Dispose(); Assert.IsTrue(initTester.HasReceived(InitializableEventReceiver.EventFlag.Deactivate)); } [Test] public void IgnoreActiveStateInNonCurrentScene() { InitializableEventReceiver initTester = this.obj.AddComponent<InitializableEventReceiver>(); // Deactivate by GameObject.Active this.obj.Active = false; Assert.IsFalse(initTester.HasReceived(InitializableEventReceiver.EventFlag.Deactivate)); initTester.Reset(); // Activate by GameObject.Active this.obj.Active = true; Assert.IsFalse(initTester.HasReceived(InitializableEventReceiver.EventFlag.Activate)); initTester.Reset(); // Deactivate by Component.Active initTester.Active = false; Assert.IsFalse(initTester.HasReceived(InitializableEventReceiver.EventFlag.Deactivate)); initTester.Reset(); // Activate by Component.Active initTester.Active = true; Assert.IsFalse(initTester.HasReceived(InitializableEventReceiver.EventFlag.Activate)); initTester.Reset(); } [Test] public void Serialize() { InitializableEventReceiver initTester = this.obj.AddComponent<InitializableEventReceiver>(); using (MemoryStream stream = new MemoryStream()) { this.scene.Save(stream); Assert.IsTrue(initTester.HasReceived(InitializableEventReceiver.EventFlag.Saving)); Assert.IsTrue(initTester.HasReceived(InitializableEventReceiver.EventFlag.Saved)); stream.Seek(0, SeekOrigin.Begin); this.scene = Resource.Load<Scene>(stream); Assert.IsTrue(this.scene.FindComponent<InitializableEventReceiver>().HasReceived(InitializableEventReceiver.EventFlag.Loaded)); } } } }
mit
stefsava/rspec_api_documentation
lib/rspec_api_documentation/dsl/endpoint.rb
3865
require 'rspec/core/formatters/base_formatter' require 'rack/utils' require 'rack/test/utils' module RspecApiDocumentation::DSL # DSL methods available inside the RSpec example. module Endpoint extend ActiveSupport::Concern include Rack::Test::Utils delegate :response_headers, :response_status, :response_body, :to => :rspec_api_documentation_client module ClassMethods def example_request(description, params = {}, &block) example description, :caller => block.send(:caller) do do_request(params) instance_eval &block if block_given? end end private # from rspec-core def relative_path(line) line = line.sub(File.expand_path("."), ".") line = line.sub(/\A([^:]+:\d+)$/, '\\1') return nil if line == '-e:1' line end end def do_request(extra_params = {}) @extra_params = extra_params params_or_body = nil path_or_query = path if http_method == :get && !query_string.blank? path_or_query += "?#{query_string}" else if respond_to?(:raw_post) params_or_body = raw_post else formatter = RspecApiDocumentation.configuration.post_body_formatter case formatter when :json params_or_body = params.empty? ? nil : params.to_json when :xml params_or_body = params.to_xml when Proc params_or_body = formatter.call(params) else params_or_body = params end end end rspec_api_documentation_client.send(http_method, path_or_query, params_or_body, headers) end def query_string build_nested_query(params || {}) end def params parameters = example.metadata.fetch(:parameters, {}).inject({}) do |hash, param| set_param(hash, param) end parameters.deep_merge!(extra_params) parameters end def header(name, value) example.metadata[:headers] ||= {} example.metadata[:headers][name] = value end def headers return unless example.metadata[:headers] example.metadata[:headers].inject({}) do |hash, (header, value)| if value.is_a?(Symbol) hash[header] = send(value) if respond_to?(value) else hash[header] = value end hash end end def http_method example.metadata[:method] end def method http_method end def status rspec_api_documentation_client.status end def in_path?(param) path_params.include?(param) end def path_params example.metadata[:route].scan(/:(\w+)/).flatten end def path example.metadata[:route].gsub(/:(\w+)/) do |match| if extra_params.keys.include?($1) delete_extra_param($1) elsif respond_to?($1) send($1) else match end end end def explanation(text) example.metadata[:explanation] = text end def example RSpec.current_example end private def rspec_api_documentation_client send(RspecApiDocumentation.configuration.client_method) end def extra_params return {} if @extra_params.nil? @extra_params.inject({}) do |h, (k, v)| v = v.is_a?(Hash) ? v.stringify_keys : v h[k.to_s] = v h end end def delete_extra_param(key) @extra_params.delete(key.to_sym) || @extra_params.delete(key.to_s) end def set_param(hash, param) key = param[:name] return hash if !respond_to?(key) || in_path?(key) if param[:scope] hash[param[:scope].to_s] ||= {} hash[param[:scope].to_s][key] = send(key) else hash[key] = send(key) end hash end end end
mit
timshannon/rollup-166
src/js/lib/lodash/object/defaults.js
824
import assign from './assign'; import assignDefaults from '../internal/assignDefaults'; import createDefaults from '../internal/createDefaults'; /** * Assigns own enumerable properties of source object(s) to the destination * object for all destination properties that resolve to `undefined`. Once a * property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * _.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' }); * // => { 'user': 'barney', 'age': 36 } */ var defaults = createDefaults(assign, assignDefaults); export default defaults;
mit
sarutobi/ritmserdtsa
rynda/geozones/tests/xUnit/test_models.py
331
# -*- coding: utf-8 -*- from django.test import TestCase from rynda.geozones.factories import RegionFactory class TestRegion(TestCase): def setUp(self): self.region = RegionFactory.build() def test_unicode(self): self.assertEqual( "%s" % self.region, self.region.name )
mit
JoshuaEstes/apostrophePlugin
modules/a/templates/_simpleEditButton.php
1926
<?php // Compatible with sf_escaping_strategy: true $class = isset($class) ? $sf_data->getRaw('class') : null; $controlsSlot = isset($controlsSlot) ? $sf_data->getRaw('controlsSlot') : null; $label = isset($label) ? $sf_data->getRaw('label') : null; $name = isset($name) ? $sf_data->getRaw('name') : null; $pageid = isset($pageid) ? $sf_data->getRaw('pageid') : null; $permid = isset($permid) ? $sf_data->getRaw('permid') : null; $title = isset($title) ? $sf_data->getRaw('title') : null; $slot = isset($slot) ? $sf_data->getRaw('slot') : null; ?> <?php use_helper('a') ?> <?php if (is_null($slot)): ?> Apostrophe 1.5: this slot's normalView partial must be upgraded to pass slot => $slot as one of its parameters to the simpleEditButton partial. <?php else: ?> <?php if (!isset($controlsSlot)): ?> <?php $controlsSlot = true ?> <?php endif ?> <?php if ($controlsSlot): ?> <?php slot("a-slot-controls-$pageid-$name-$permid") ?> <?php endif ?> <li> <?php // We want to eliminate jQuery helpers, but writing this link as raw HTML is tricky because ?> <?php // of the need to quote the title option right. And link_to doesn't like '#' as a URL. So we use ?> <?php // content_tag, Symfony's lower-level helper for outputting any tag and its content programmatically ?> <?php echo content_tag('a', '<span class="icon"></span>'.(isset($label) ? a_($label) : a_("Edit")), array( 'href' => '#edit-slot-'.$pageid.'-'.$name.'-'.$permid, 'id' => "a-slot-edit-$pageid-$name-$permid", 'class' => isset($class) ? $class : 'a-btn icon a-edit', 'title' => isset($title) ? $title : a_('Edit'), )) ?> <?php a_js_call('apostrophe.slotEnableEditButton(?, ?, ?, ?, ?)', $pageid, $name, $permid, a_url($slot->type . 'Slot', 'ajaxEditView'), aTools::getRealUrl()) ?> </li> <?php if ($controlsSlot): ?> <?php end_slot() ?> <?php endif ?> <?php endif ?>
mit
achojs/acho
test/index.js
3541
/* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ 'use strict' const should = require('should') const util = require('./util') const acho = require('..') const Acho = acho describe('acho', function () { describe('constructor', function () { it('new keyword', () => should(acho()).be.an.Object()) it('non new keyword', () => should(new Acho()).be.an.Object()) }) describe('internal store', function () { describe('initialization', () => it('passing a initial store state', function () { const log = acho({ transport: util.createFakeTransport(), messages: { info: ['info message'] } }) log.print() return should(log.transport.store.length).be.equal(1) })) describe('.push', () => it('add message into a internal level collection', function () { const log = acho().push('error', 'hello world') return should(log.messages.error.length).be.equal(1) })) return describe('.add', () => it('push and print a message', function () { const log = acho({ transport: util.createFakeTransport() }) log.add('error', 'hello world') should(log.transport.store.length).be.equal(1) should(log.messages.error.length).be.equal(1) return should(log.messages.error[0]).be.equal('hello world') })) }) describe('levels', function () { it('print a normal level message', function () { const log = acho({ transport: util.createFakeTransport() }) log.warn('warn message') return should(log.transport.store.length).be.equal(1) }) return it('no ouptut messages out of the level', function () { const log = acho({ transport: util.createFakeTransport(), level: 'fatal' }) log.error('test of message') return should(log.transport.store.length).be.equal(0) }) }) return describe('customization', function () { it('default skin', function () { const log = acho() util.printLogs(log) return should(log.keyword != null).be.false() }) it('change the color behavior', function () { const log = acho({ transport: util.createFakeTransport(), types: { error: { color: ['underline', 'bgRed'] } } }) log.push('error', 'hello world') log.print() return should(log.transport.store.length).be.equal(1) }) it('specifying a keyword', function () { const log = acho({ keyword: 'acho' }) util.printLogs(log) return should(log.keyword).be.equal('acho') }) it('specifying "symbol" keyword', function () { const log = acho({ keyword: 'symbol' }) util.printLogs(log) return should(log.keyword).be.equal('symbol') }) return it('enabling diff between logs', function (done) { const log = acho({ diff: true, trace: true }) const printWarn = () => log.warn('hello world') const printErr = () => log.error('oh noes!') const warn = setInterval(printWarn, util.randomInterval(1000, 2000)) const err = setInterval(printErr, util.randomInterval(2000, 2500)) return setTimeout(function () { clearInterval(warn) clearInterval(err) return done() }, 5000) }) }) })
mit
hegemone/kore-poc
koredata-goa/vendor/github.com/goadesign/goa/middleware/xray/middleware_test.go
10770
package xray import ( "context" "encoding/json" "errors" "net" "net/http" "net/http/httptest" "net/url" "regexp" "strings" "sync" "testing" "time" "github.com/goadesign/goa" "github.com/goadesign/goa/middleware" ) const ( // udp host:port used to run test server udplisten = "127.0.0.1:62111" ) func TestNew(t *testing.T) { cases := map[string]struct { Daemon string Success bool }{ "ok": {udplisten, true}, "not-ok": {"1002.0.0.0:62111", false}, } for k, c := range cases { m, err := New("", c.Daemon) if err == nil && !c.Success { t.Errorf("%s: expected failure but err is nil", k) } if err != nil && c.Success { t.Errorf("%s: unexpected error %s", k, err) } if m == nil && c.Success { t.Errorf("%s: middleware is nil", k) } } } func TestMiddleware(t *testing.T) { type ( Tra struct { TraceID, SpanID, ParentID string } Req struct { Method, Host, IP, RemoteAddr string RemoteHost, UserAgent string URL *url.URL } Res struct { Status int } Seg struct { Exception string Error bool } ) var ( traceID = "traceID" spanID = "spanID" parentID = "parentID" host = "goa.design" method = "GET" ip = "104.18.42.42" remoteAddr = "104.18.43.42:443" remoteNoPort = "104.18.43.42" remoteHost = "104.18.43.42" agent = "user agent" url, _ = url.Parse("https://goa.design/path?query#fragment") ) cases := map[string]struct { Trace Tra Request Req Response Res Segment Seg }{ "no-trace": { Trace: Tra{"", "", ""}, Request: Req{"", "", "", "", "", "", nil}, Response: Res{0}, Segment: Seg{"", false}, }, "basic": { Trace: Tra{traceID, spanID, ""}, Request: Req{method, host, ip, remoteAddr, remoteHost, agent, url}, Response: Res{http.StatusOK}, Segment: Seg{"", false}, }, "with-parent": { Trace: Tra{traceID, spanID, parentID}, Request: Req{method, host, ip, remoteAddr, remoteHost, agent, url}, Response: Res{http.StatusOK}, Segment: Seg{"", false}, }, "without-ip": { Trace: Tra{traceID, spanID, parentID}, Request: Req{method, host, "", remoteAddr, remoteHost, agent, url}, Response: Res{http.StatusOK}, Segment: Seg{"", false}, }, "without-ip-remote-port": { Trace: Tra{traceID, spanID, parentID}, Request: Req{method, host, "", remoteNoPort, remoteHost, agent, url}, Response: Res{http.StatusOK}, Segment: Seg{"", false}, }, "error": { Trace: Tra{traceID, spanID, ""}, Request: Req{method, host, ip, remoteAddr, remoteHost, agent, url}, Response: Res{http.StatusBadRequest}, Segment: Seg{"error", true}, }, "fault": { Trace: Tra{traceID, spanID, ""}, Request: Req{method, host, ip, remoteAddr, remoteHost, agent, url}, Response: Res{http.StatusInternalServerError}, Segment: Seg{"", true}, }, } for k, c := range cases { m, err := New("service", udplisten) if err != nil { t.Fatalf("%s: failed to create middleware: %s", k, err) } if c.Response.Status == 0 { continue } var ( req, _ = http.NewRequest(c.Request.Method, c.Request.URL.String(), nil) rw = httptest.NewRecorder() ctx = goa.NewContext(context.Background(), rw, req, nil) h = func(ctx context.Context, rw http.ResponseWriter, _ *http.Request) error { if c.Segment.Exception != "" { ContextSegment(ctx).RecordError(errors.New(c.Segment.Exception)) } rw.WriteHeader(c.Response.Status) return nil } ) ctx = middleware.WithTrace(ctx, c.Trace.TraceID, c.Trace.SpanID, c.Trace.ParentID) if c.Request.UserAgent != "" { req.Header.Set("User-Agent", c.Request.UserAgent) } if c.Request.IP != "" { req.Header.Set("X-Forwarded-For", c.Request.IP) } if c.Request.RemoteAddr != "" { req.RemoteAddr = c.Request.RemoteAddr } if c.Request.Host != "" { req.Host = c.Request.Host } js := readUDP(t, func() { m(h)(ctx, goa.ContextResponse(ctx), req) }) var s *Segment elems := strings.Split(js, "\n") if len(elems) != 2 { t.Fatalf("%s: invalid number of lines, expected 2 got %d: %v", k, len(elems), elems) } if elems[0] != udpHeader[:len(udpHeader)-1] { t.Errorf("%s: invalid header, got %s", k, elems[0]) } err = json.Unmarshal([]byte(elems[1]), &s) if err != nil { t.Fatal(err) } if s.Name != "service" { t.Errorf("%s: unexpected segment name, expected service - got %s", k, s.Name) } if s.Type != "" { t.Errorf("%s: expected Type to be empty but got %s", k, s.Type) } if s.ID != c.Trace.SpanID { t.Errorf("%s: unexpected segment ID, expected %s - got %s", k, c.Trace.SpanID, s.ID) } if s.TraceID != c.Trace.TraceID { t.Errorf("%s: unexpected trace ID, expected %s - got %s", k, c.Trace.TraceID, s.TraceID) } if s.ParentID != c.Trace.ParentID { t.Errorf("%s: unexpected parent ID, expected %s - got %s", k, c.Trace.ParentID, s.ParentID) } if s.StartTime == 0 { t.Errorf("%s: StartTime is 0", k) } if s.EndTime == 0 { t.Errorf("%s: EndTime is 0", k) } if s.StartTime > s.EndTime { t.Errorf("%s: StartTime (%v) is after EndTime (%v)", k, s.StartTime, s.EndTime) } if s.HTTP == nil { t.Fatalf("%s: HTTP field is nil", k) } if s.HTTP.Request == nil { t.Fatalf("%s: HTTP Request field is nil", k) } if c.Request.IP != "" && s.HTTP.Request.ClientIP != c.Request.IP { t.Errorf("%s: HTTP Request ClientIP is invalid, expected %#v got %#v", k, c.Request.IP, s.HTTP.Request.ClientIP) } if c.Request.IP == "" && s.HTTP.Request.ClientIP != c.Request.RemoteHost { t.Errorf("%s: HTTP Request ClientIP is invalid, expected host %#v got %#v", k, c.Request.RemoteHost, s.HTTP.Request.ClientIP) } if s.HTTP.Request.Method != c.Request.Method { t.Errorf("%s: HTTP Request Method is invalid, expected %#v got %#v", k, c.Request.Method, s.HTTP.Request.Method) } expected := strings.Split(c.Request.URL.String(), "?")[0] if s.HTTP.Request.URL != expected { t.Errorf("%s: HTTP Request URL is invalid, expected %#v got %#v", k, expected, s.HTTP.Request.URL) } if s.HTTP.Request.UserAgent != c.Request.UserAgent { t.Errorf("%s: HTTP Request UserAgent is invalid, expected %#v got %#v", k, c.Request.UserAgent, s.HTTP.Request.UserAgent) } if s.Cause == nil && c.Segment.Exception != "" { t.Errorf("%s: Exception is invalid, expected %v but got nil Cause", k, c.Segment.Exception) } if s.Cause != nil && s.Cause.Exceptions[0].Message != c.Segment.Exception { t.Errorf("%s: Exception is invalid, expected %v got %v", k, c.Segment.Exception, s.Cause.Exceptions[0].Message) } if s.Error != c.Segment.Error { t.Errorf("%s: Error is invalid, expected %v got %v", k, c.Segment.Error, s.Error) } } } func TestNewID(t *testing.T) { id := NewID() if len(id) != 16 { t.Errorf("invalid ID length, expected 16 got %d", len(id)) } if !regexp.MustCompile("[0-9a-f]{16}").MatchString(id) { t.Errorf("invalid ID format, should be hexadecimal, got %s", id) } if id == NewID() { t.Errorf("ids not unique") } } func TestNewTraceID(t *testing.T) { id := NewTraceID() if len(id) != 35 { t.Errorf("invalid ID length, expected 35 got %d", len(id)) } if !regexp.MustCompile("1-[0-9a-f]{8}-[0-9a-f]{16}").MatchString(id) { t.Errorf("invalid Trace ID format, got %s", id) } if id == NewTraceID() { t.Errorf("trace ids not unique") } } func TestPeriodicallyRedialingConn(t *testing.T) { t.Run("dial fails, returns error immediately", func(t *testing.T) { dialErr := errors.New("dialErr") _, err := periodicallyRedialingConn(context.Background(), time.Millisecond, func() (net.Conn, error) { return nil, dialErr }) if err != dialErr { t.Fatalf("Unexpected err, got %q, expected %q", err, dialErr) } }) t.Run("connection gets replaced by new one", func(t *testing.T) { var ( firstConn = &net.UDPConn{} secondConn = &net.UnixConn{} callCount = 0 ) wgCheckFirstConnection := sync.WaitGroup{} wgCheckFirstConnection.Add(1) wgThirdDial := sync.WaitGroup{} wgThirdDial.Add(1) dial := func() (net.Conn, error) { callCount++ if callCount == 1 { return firstConn, nil } wgCheckFirstConnection.Wait() if callCount == 3 { wgThirdDial.Done() } return secondConn, nil } ctx, cancel := context.WithCancel(context.Background()) defer cancel() conn, err := periodicallyRedialingConn(ctx, time.Millisecond, dial) if err != nil { t.Fatalf("Expected nil err but got: %v", err) } if c := conn(); c != firstConn { t.Fatalf("Unexpected first connection: got %#v, expected %#v", c, firstConn) } wgCheckFirstConnection.Done() // by the time the 3rd dial happens, we know conn() should be returning the second connection wgThirdDial.Wait() if c := conn(); c != secondConn { t.Fatalf("Unexpected second connection: got %#v, expected %#v", c, secondConn) } }) t.Run("connection not replaced if dial errored", func(t *testing.T) { var ( firstConn = &net.UDPConn{} callCount = 0 ) wgCheckFirstConnection := sync.WaitGroup{} wgCheckFirstConnection.Add(1) wgThirdDial := sync.WaitGroup{} wgThirdDial.Add(1) dial := func() (net.Conn, error) { callCount++ if callCount == 1 { return firstConn, nil } wgCheckFirstConnection.Wait() if callCount == 3 { wgThirdDial.Done() } return nil, errors.New("dialErr") } ctx, cancel := context.WithCancel(context.Background()) defer cancel() conn, err := periodicallyRedialingConn(ctx, time.Millisecond, dial) if err != nil { t.Fatalf("Expected nil err but got: %v", err) } if c := conn(); c != firstConn { t.Fatalf("Unexpected first connection: got %#v, expected %#v", c, firstConn) } wgCheckFirstConnection.Done() // by the time the 3rd dial happens, we know the second dial was processed, and shouldn't have replaced conn() wgThirdDial.Wait() if c := conn(); c != firstConn { t.Fatalf("Connection unexpectedly replaced: got %#v, expected %#v", c, firstConn) } }) } // readUDP calls sender, reads and returns UDP messages received on udplisten. func readUDP(t *testing.T, sender func()) string { var ( readChan = make(chan string) msg = make([]byte, 1024*32) ) resAddr, err := net.ResolveUDPAddr("udp", udplisten) if err != nil { t.Fatal(err) } listener, err := net.ListenUDP("udp", resAddr) if err != nil { t.Fatal(err) } go func() { listener.SetReadDeadline(time.Now().Add(time.Second)) n, _, _ := listener.ReadFrom(msg) readChan <- string(msg[0:n]) }() sender() defer func() { if err := listener.Close(); err != nil { t.Fatal(err) } }() return <-readChan }
mit
zweidner/hubzero-cms
core/components/com_media/admin/views/medialist/tmpl/info.php
4160
<?php /** * @package hubzero-cms * @copyright Copyright 2005-2019 HUBzero Foundation, LLC. * @license http://opensource.org/licenses/MIT MIT */ // No direct access. defined('_HZEXEC_') or die(); if ($this->data['type'] != 'folder'): $ext = Filesystem::extension($this->data['name']); $icon = Html::asset('image', 'assets/filetypes/' . $ext . '.svg', '', null, true, true); if (!$icon): $icon = Html::asset('image', 'assets/filetypes/file.svg', '', null, true, true); endif; else: $icon = Html::asset('image', 'assets/filetypes/folder.svg', '', null, true, true); endif; ?> <form action="<?php echo Route::url('index.php?option=' . $this->option . '&controller=medialist&file=' . urlencode($this->data['path'])); ?>" id="component-form" method="post" name="adminForm" autocomplete="off"> <fieldset> <h2 class="modal-title"> <?php echo Lang::txt('COM_MEDIA_FILE_INFO'); ?> </h2> </fieldset> <div class="grid"> <div class="col span5"> <div class="media-preview"> <div class="media-preview-inner"> <?php if ($this->data['type'] == 'img'): ?> <div class="media-thumb img-preview <?php echo Filesystem::extension($this->data['name']); ?>" title="<?php echo $this->escape($this->data['name']); ?>" > <span class="media-preview-shim"></span><!-- --><img src="<?php echo COM_MEDIA_BASEURL . $this->data['path']; ?>" alt="<?php echo $this->escape(Lang::txt('COM_MEDIA_IMAGE_TITLE', $this->data['name'], Components\Media\Admin\Helpers\MediaHelper::parseSize($this->data['size']))); ?>" width="<?php echo ($this->data['width'] < 260) ? $this->data['width'] : '260'; ?>" /> </div> <?php else: ?> <div class="media-thumb doc-item <?php echo Filesystem::extension($this->data['name']); ?>" title="<?php echo $this->escape($this->data['name']); ?>" > <span class="media-preview-shim"></span><!-- --><img src="<?php echo $icon; ?>" alt="<?php echo $this->escape(Lang::txt('COM_MEDIA_IMAGE_TITLE', $this->data['name'], Components\Media\Admin\Helpers\MediaHelper::parseSize($this->data['size']))); ?>" width="80" /> </div> <?php endif; ?> </div> </div> </div> <div class="col span7"> <div class="input-wrap"> <span class="media-info-label"><?php echo Lang::txt('COM_MEDIA_LIST_HEADER_NAME'); ?>:</span> <span class="media-info-value"><?php echo $this->escape($this->data['name']); ?></span> </div> <div class="input-wrap"> <span class="media-info-label"><?php echo Lang::txt('COM_MEDIA_LIST_HEADER_PATH'); ?>:</span> <span class="media-info-value"><?php echo $this->escape($this->data['path']); ?></span> </div> <?php if ($this->data['type'] != 'folder'): ?> <?php if ($this->data['type'] == 'img'): ?> <div class="grid"> <div class="col span4"> <?php endif; ?> <div class="input-wrap"> <span class="media-info-label"><?php echo Lang::txt('COM_MEDIA_LIST_HEADER_SIZE'); ?>:</span> <span class="media-info-value"><?php echo Hubzero\Utility\Number::formatBytes($this->data['size']); ?></span> </div> <?php if ($this->data['type'] == 'img'): ?> </div> <div class="col span4"> <div class="input-wrap"> <span class="media-info-label"><?php echo Lang::txt('COM_MEDIA_LIST_HEADER_WIDTH'); ?>:</span> <span class="media-info-value"><?php echo $this->data['width']; ?>px</span> </div> </div> <div class="col span4"> <div class="input-wrap"> <span class="media-info-label"><?php echo Lang::txt('COM_MEDIA_LIST_HEADER_HEIGHT'); ?>:</span> <span class="media-info-value"><?php echo $this->data['height']; ?>px</span> </div> </div> </div> <?php endif; ?> <?php endif; ?> <div class="input-wrap"> <span class="media-info-label"><?php echo Lang::txt('COM_MEDIA_LIST_HEADER_MODIFIED'); ?>:</span> <span class="media-info-value"><?php echo Date::of($this->data['modified'])->toSql(); ?></span> </div> </div> </div> <input type="hidden" name="task" value="" /> <input type="hidden" name="option" value="<?php echo $this->option; ?>" /> <?php echo Html::input('token'); ?> </form>
mit
cmc333333/api-umbrella-web
app/assets/javascripts/admin/controllers/apis_form_controller.js
4403
Admin.ApisFormController = Ember.ObjectController.extend(Admin.Save, { needs: [ 'apis_server_form', 'apis_url_match_form', 'apis_sub_settings_form', 'apis_rewrite_form', ], backendProtocolOptions: [ { id: 'http', name: 'http' }, { id: 'https', name: 'https' }, ], balanceAlgorithmOptions: [ { id: 'least_conn', name: 'Least Connections' }, { id: 'round_robin', name: 'Round Robin' }, { id: 'ip_hash', name: 'Source IP Hash' }, ], actions: { submit: function() { this.save({ transitionToRoute: 'apis', message: 'Successfully saved the "' + _.escape(this.get('model.name')) + '" API backend<br><strong>Note:</strong> Your changes are not yet live. <a href="/admin/#/config/publish">Publish Changes</a> to send your updates live.', }); }, delete: function() { bootbox.confirm('Are you sure you want to delete this API backend?', _.bind(function(result) { if(result) { this.get('model').deleteRecord(); this.transitionToRoute('apis'); } }, this)); }, addServer: function() { this.get('controllers.apis_server_form').add(this.get('model'), 'servers'); // For new servers, intelligently pick the default port based on the // backend protocol selected. if(this.get('model.backendProtocol') === 'https') { this.set('controllers.apis_server_form.model.port', 443); } else { this.set('controllers.apis_server_form.model.port', 80); } // After the first server is added, fill out a default value for the // "Backend Host" field based on the server's host (because in most // non-load balancing situations they will match). this.get('controllers.apis_server_form').on('closeOk', _.bind(function() { var server = this.get('model.servers.firstObject'); if(!this.get('model.backendHost') && server) { this.set('model.backendHost', server.get('host')); } }, this)); this.send('openModal', 'apis/server_form'); }, editServer: function(server) { this.get('controllers.apis_server_form').edit(this.get('model'), 'servers', server); this.send('openModal', 'apis/server_form'); }, deleteServer: function(server) { this.deleteChildRecord('servers', server, 'Are you sure you want to remove this server?'); }, addUrlMatch: function() { this.get('controllers.apis_url_match_form').add(this.get('model'), 'urlMatches'); this.send('openModal', 'apis/url_match_form'); }, editUrlMatch: function(urlMatch) { this.get('controllers.apis_url_match_form').edit(this.get('model'), 'urlMatches', urlMatch); this.send('openModal', 'apis/url_match_form'); }, deleteUrlMatch: function(urlMatch) { this.deleteChildRecord('urlMatches', urlMatch, 'Are you sure you want to remove this URL prefix?'); }, addSubSettings: function() { this.get('controllers.apis_sub_settings_form').add(this.get('model'), 'subSettings'); this.send('openModal', 'apis/sub_settings_form'); }, editSubSettings: function(subSettings) { this.get('controllers.apis_sub_settings_form').edit(this.get('model'), 'subSettings', subSettings); this.send('openModal', 'apis/sub_settings_form'); }, deleteSubSettings: function(subSettings) { this.deleteChildRecord('subSettings', subSettings, 'Are you sure you want to remove this URL setting?'); }, addRewrite: function() { this.get('controllers.apis_rewrite_form').add(this.get('model'), 'rewrites'); this.send('openModal', 'apis/rewrite_form'); }, editRewrite: function(rewrite) { this.get('controllers.apis_rewrite_form').edit(this.get('model'), 'rewrites', rewrite); this.send('openModal', 'apis/rewrite_form'); }, deleteRewrite: function(rewrite) { this.deleteChildRecord('rewrites', rewrite, 'Are you sure you want to remove this rewrite?'); }, }, deleteChildRecord: function(collectionName, record, message) { var collection = this.get('model').get(collectionName); bootbox.confirm(message, function(result) { if(result) { collection.removeObject(record); } }); }, }); Admin.ApisEditController = Admin.ApisFormController.extend(); Admin.ApisNewController = Admin.ApisFormController.extend();
mit
erubboli/gotrade
testdata/indicator-test-generator/Properties/AssemblyInfo.cs
999
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle ("indicator-test-generator")] [assembly: AssemblyDescription ("")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("")] [assembly: AssemblyProduct ("")] [assembly: AssemblyCopyright ("eugened")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion ("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
mit
EvNaverniouk/doby-grid
examples/menuextensions.js
1493
/*global define*/ define(['faker', 'dataset'], function (Faker, dataset) { "use strict"; // Generate Grid Options return [function () { var idExtractor = function (item) { return item.id; }; // Generate Columns var columns = [ { id: "id", dataExtractor: idExtractor, name: "ID", maxWidth: 150, sortable: true, tooltip: "ID of the item" }, { id: "name", name: "Name", field: "name", minWidth: 100, sortable: true, tooltip: "This is the name of the individual" }, { id: "email", name: "Email", field: "email", sortable: true, tooltip: "Their email address" }, { id: "company", name: "Company", field: "company", sortable: true, tooltip: "The user's company" }, { id: "random", name: "Random Words", field: "lorem", sortable: true, tooltip: "Some random words" } ]; return { columns: columns, data: dataset, menuExtensions: function (event, grid, args) { return [{ icon: '', name: "Menu Item", menu: [{ name: "Submenu Item", fn: function (event) { console.log('Click the submenu.'); } }] }, { divider: true }, { name: "Toggle Button", value: 'BTN!', fn: function (event) { console.log('Toggle the button.'); } }] }, // Possible values are "top" and "bottom", with the latter the default. menuExtensionsPosition: 'bottom' }; }]; });
mit
ghetolay/angular
aio/tools/transforms/angular-base-package/index.js
5679
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ const path = require('path'); const Package = require('dgeni').Package; const jsdocPackage = require('dgeni-packages/jsdoc'); const nunjucksPackage = require('dgeni-packages/nunjucks'); const linksPackage = require('../links-package'); const examplesPackage = require('../examples-package'); const targetPackage = require('../target-package'); const remarkPackage = require('../remark-package'); const postProcessPackage = require('../post-process-package'); const { PROJECT_ROOT, CONTENTS_PATH, OUTPUT_PATH, DOCS_OUTPUT_PATH, TEMPLATES_PATH, AIO_PATH, requireFolder } = require('../config'); module.exports = new Package('angular-base', [ jsdocPackage, nunjucksPackage, linksPackage, examplesPackage, targetPackage, remarkPackage, postProcessPackage ]) // Register the processors .processor(require('./processors/generateKeywords')) .processor(require('./processors/createOverviewDump')) .processor(require('./processors/checkUnbalancedBackTicks')) .processor(require('./processors/convertToJson')) .processor(require('./processors/fixInternalDocumentLinks')) .processor(require('./processors/copyContentAssets')) .processor(require('./processors/renderLinkInfo')) // overrides base packageInfo and returns the one for the 'angular/angular' repo. .factory('packageInfo', function() { return require(path.resolve(PROJECT_ROOT, 'package.json')); }) .factory(require('./readers/json')) .factory(require('./services/copyFolder')) .factory(require('./services/filterPipes')) .factory(require('./services/filterAmbiguousDirectiveAliases')) .factory(require('./services/getImageDimensions')) .factory(require('./post-processors/add-image-dimensions')) .factory(require('./post-processors/auto-link-code')) .config(function(checkAnchorLinksProcessor) { // This is disabled here to prevent false negatives for the `docs-watch` task. // It is re-enabled in the main `angular.io-package` checkAnchorLinksProcessor.$enabled = false; }) // Where do we get the source files? .config(function(readFilesProcessor, collectExamples, generateKeywordsProcessor, jsonFileReader) { readFilesProcessor.fileReaders.push(jsonFileReader); readFilesProcessor.basePath = PROJECT_ROOT; readFilesProcessor.sourceFiles = []; collectExamples.exampleFolders = []; generateKeywordsProcessor.ignoreWordsFile = path.resolve(__dirname, 'ignore.words'); generateKeywordsProcessor.docTypesToIgnore = ['example-region']; generateKeywordsProcessor.propertiesToIgnore = ['renderedContent']; }) // Where do we write the output files? .config(function(writeFilesProcessor) { writeFilesProcessor.outputFolder = DOCS_OUTPUT_PATH; }) // Target environments .config(function(targetEnvironments) { const ALLOWED_LANGUAGES = ['ts', 'js', 'dart']; const TARGET_LANGUAGE = 'ts'; ALLOWED_LANGUAGES.forEach(target => targetEnvironments.addAllowed(target)); targetEnvironments.activate(TARGET_LANGUAGE); }) // Configure nunjucks rendering of docs via templates .config(function( renderDocsProcessor, templateFinder, templateEngine, getInjectables) { // Where to find the templates for the doc rendering templateFinder.templateFolders = [TEMPLATES_PATH]; // Standard patterns for matching docs to templates templateFinder.templatePatterns = [ '${ doc.template }', '${ doc.id }.${ doc.docType }.template.html', '${ doc.id }.template.html', '${ doc.docType }.template.html', '${ doc.id }.${ doc.docType }.template.js', '${ doc.id }.template.js', '${ doc.docType }.template.js', '${ doc.id }.${ doc.docType }.template.json', '${ doc.id }.template.json', '${ doc.docType }.template.json', 'common.template.html' ]; // Nunjucks and Angular conflict in their template bindings so change Nunjucks templateEngine.config.tags = {variableStart: '{$', variableEnd: '$}'}; templateEngine.filters = templateEngine.filters.concat(getInjectables(requireFolder(__dirname, './rendering'))); // helpers are made available to the nunjucks templates renderDocsProcessor.helpers.relativePath = function(from, to) { return path.relative(from, to); }; }) .config(function(copyContentAssetsProcessor) { copyContentAssetsProcessor.assetMappings.push( { from: path.resolve(CONTENTS_PATH, 'images'), to: path.resolve(OUTPUT_PATH, 'images') } ); }) // We are not going to be relaxed about ambiguous links .config(function(getLinkInfo) { getLinkInfo.useFirstAmbiguousLink = false; }) .config(function(computePathsProcessor, generateKeywordsProcessor) { generateKeywordsProcessor.outputFolder = 'app'; // Replace any path templates inherited from other packages // (we want full and transparent control) computePathsProcessor.pathTemplates = [ {docTypes: ['example-region'], getOutputPath: function() {}}, ]; }) .config(function(postProcessHtml, addImageDimensions, autoLinkCode, filterPipes, filterAmbiguousDirectiveAliases) { addImageDimensions.basePath = path.resolve(AIO_PATH, 'src'); autoLinkCode.customFilters = [filterPipes, filterAmbiguousDirectiveAliases]; postProcessHtml.plugins = [ require('./post-processors/autolink-headings'), addImageDimensions, require('./post-processors/h1-checker'), autoLinkCode, ]; }) .config(function(convertToJsonProcessor) { convertToJsonProcessor.docTypes = []; });
mit
sch8906/JSdep
src/js_wala/normalizer/test/data/normalized.test45.js
533
(function(__global) { var tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7, tmp8, tmp9, tmp10; try { try { tmp1 = "f"; tmp0 = __global[tmp1]; tmp2 = tmp0(); } catch (e) { tmp4 = "alert"; tmp3 = __global[tmp4]; tmp5 = e; tmp6 = tmp3(tmp5); } } finally { tmp8 = "alert"; tmp7 = __global[tmp8]; tmp9 = "done"; tmp10 = tmp7(tmp9); } })(typeof global === 'undefined' ? this : global);
mit
Taluu/symfony
src/Symfony/Component/Security/Core/Encoder/PlaintextPasswordEncoder.php
1674
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Security\Core\Encoder; use Symfony\Component\Security\Core\Exception\BadCredentialsException; /** * PlaintextPasswordEncoder does not do any encoding but is useful in testing environments. * * As this encoder is not cryptographically secure, usage of it in production environments is discouraged. * * @author Fabien Potencier <fabien@symfony.com> */ class PlaintextPasswordEncoder extends BasePasswordEncoder { private $ignorePasswordCase; /** * @param bool $ignorePasswordCase Compare password case-insensitive */ public function __construct(bool $ignorePasswordCase = false) { $this->ignorePasswordCase = $ignorePasswordCase; } /** * {@inheritdoc} */ public function encodePassword($raw, $salt) { if ($this->isPasswordTooLong($raw)) { throw new BadCredentialsException('Invalid password.'); } return $this->mergePasswordAndSalt($raw, $salt); } /** * {@inheritdoc} */ public function isPasswordValid($encoded, $raw, $salt) { if ($this->isPasswordTooLong($raw)) { return false; } $pass2 = $this->mergePasswordAndSalt($raw, $salt); if (!$this->ignorePasswordCase) { return $this->comparePasswords($encoded, $pass2); } return $this->comparePasswords(strtolower($encoded), strtolower($pass2)); } }
mit
mda-ut/SubZero
src/model/interface/HwInterface.cpp
398
/* * HwInterface.cpp * * Created on: Jan 17, 2015 * Author: ahsueh1996 */ #include "HwInterface.h" /* ========================================================================== * CONSTRUCTOR AND DESTRUCTOR * ========================================================================== */ HwInterface::HwInterface() { } HwInterface::~HwInterface() { delete logger; }
mit
jonathanleang/SpineMask
Assets/spine-csharp/SlotData.cs
3028
/****************************************************************************** * Spine Runtimes Software License * Version 2.3 * * Copyright (c) 2013-2015, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable and * non-transferable license to use, install, execute and perform the Spine * Runtimes Software (the "Software") and derivative works solely for personal * or internal use. Without the written permission of Esoteric Software (see * Section 2 of the Spine Software License Agreement), you may not (a) modify, * translate, adapt or otherwise create derivative works, improvements of the * Software or develop new applications using the Software or (b) remove, * delete, alter or obscure any trademarks or any copyright, trademark, patent * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ using System; namespace Spine { public class SlotData { internal String name; internal BoneData boneData; internal float r = 1, g = 1, b = 1, a = 1; internal String attachmentName; internal BlendMode blendMode; public String Name { get { return name; } } public BoneData BoneData { get { return boneData; } } public float R { get { return r; } set { r = value; } } public float G { get { return g; } set { g = value; } } public float B { get { return b; } set { b = value; } } public float A { get { return a; } set { a = value; } } /// <summary>May be null.</summary> public String AttachmentName { get { return attachmentName; } set { attachmentName = value; } } public BlendMode BlendMode { get { return blendMode; } set { blendMode = value; } } public SlotData (String name, BoneData boneData) { if (name == null) throw new ArgumentNullException("name cannot be null."); if (boneData == null) throw new ArgumentNullException("boneData cannot be null."); this.name = name; this.boneData = boneData; } override public String ToString () { return name; } } }
mit
Sorsly/subtle
google-cloud-sdk/lib/surface/app/regions/list.py
1234
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The `app regions list` command.""" from googlecloudsdk.api_lib.app import appengine_api_client from googlecloudsdk.calliope import base class List(base.ListCommand): """List the availability of flex and standard environments for each region.""" detailed_help = { 'DESCRIPTION': '{description}', 'EXAMPLES': """\ To view regional availability of App Engine runtime environments, run: $ {command} """, } def Collection(self): return 'appengine.regions' def Run(self, args): api_client = appengine_api_client.GetApiClient() return sorted(api_client.ListRegions())
mit
sachintaware/PHP-DI
tests/UnitTest/Definition/Source/Fixtures/ReflectionFixtureChild.php
385
<?php /** * PHP-DI * * @link http://php-di.org/ * @copyright Matthieu Napoli (http://mnapoli.fr/) * @license http://www.opensource.org/licenses/mit-license.php MIT (see the LICENSE file) */ namespace DI\Test\UnitTest\Definition\Source\Fixtures; /** * Fixture class for the ReflectionDefinitionSource tests */ class ReflectionFixtureChild extends ReflectionFixture { }
mit
dbuhrman/extjs-reactor
packages/reactor/src/overrides.js
1162
import Template from './Template'; const Ext = window.Ext; // add support for functions that return JSX elements in place of XTemplates const getTpl = Ext.XTemplate.getTpl; const originalGet = Ext.XTemplate.get; Ext.XTemplate.get = function(fn) { if (typeof(fn) === 'function') { return new Template(fn); } else { return originalGet.apply(Ext.XTemplate, arguments); } } Ext.XTemplate.getTpl = function() { return getTpl.apply(Ext.XTemplate, arguments); } // automatically persist event before rippling const originalRipple = Ext.dom.Element.prototype.ripple; Ext.dom.Element.prototype.ripple = function(event) { if (event && event.persist) event.persist(); return originalRipple.apply(this, arguments); } // enable component query by component name in Sencha Test const originalWidgetIsXtype = Ext.Widget.prototype.isXType; Ext.Widget.prototype.isXType = function(xtype, shallow) { return originalWidgetIsXtype.call(this, xtype.toLowerCase().replace(/_/g, '-'), shallow); } // needed for classic if (Ext.Component.prototype.isXType) { Ext.Component.prototype.isXType = Ext.Widget.prototype.isXType }
mit
Fenex/Pinta
Pinta.Core/Managers/ResourceManager.cs
1651
// // ResourceManager.cs // // Author: // Jonathan Pobst <monkey@jpobst.com> // // Copyright (c) 2010 Jonathan Pobst // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.IO; using Pinta.Resources; namespace Pinta { public class ResourceManager { public Gdk.Pixbuf GetIcon (string name) { return GetIcon (name, 16); } public Gdk.Pixbuf GetIcon (string name, int size) { return ResourceLoader.GetIcon (name, size); } public Stream GetResourceIconStream (string name) { return ResourceLoader.GetResourceIconStream (name); } } }
mit
innogames/gitlabhq
spec/features/projects/members/master_manages_access_requests_spec.rb
314
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Projects > Members > Maintainer manages access requests' do it_behaves_like 'Maintainer manages access requests' do let(:entity) { create(:project, :public) } let(:members_page_path) { project_project_members_path(entity) } end end
mit
Djamy/platform
src/Oro/Bundle/FormBundle/Validator/DoctrineInitializer.php
1109
<?php namespace Oro\Bundle\FormBundle\Validator; use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\Util\OrderedHashMap; use Symfony\Component\Validator\ObjectInitializerInterface; /** * The default Symfony's implementation is decorated to avoid initialization * of all entity managers for widely used types of objects * that are not Doctrine manageable entities. * @see \Symfony\Bridge\Doctrine\Validator\DoctrineInitializer::initialize */ class DoctrineInitializer implements ObjectInitializerInterface { /** @var ObjectInitializerInterface */ private $innerInitializer; /** * @param ObjectInitializerInterface $innerInitializer */ public function __construct(ObjectInitializerInterface $innerInitializer) { $this->innerInitializer = $innerInitializer; } /** * {@inheritdoc} */ public function initialize($object) { if ($object instanceof FormInterface || $object instanceof OrderedHashMap ) { return; } $this->innerInitializer->initialize($object); } }
mit
cginternals/libzeug
source/reflectionzeug/source/base/Color.cpp
1957
#include <reflectionzeug/base/Color.h> #include <cassert> namespace reflectionzeug { Color::Color() : m_v{0u} { } Color::Color(unsigned int bgra) : m_v{bgra} { } Color::Color(int red, int green, int blue, int alpha) { m_rgba.a = static_cast<unsigned char>(alpha); m_rgba.r = static_cast<unsigned char>(red); m_rgba.g = static_cast<unsigned char>(green); m_rgba.b = static_cast<unsigned char>(blue); } bool Color::operator==(const Color & rhs) const { return m_v == rhs.m_v; } bool Color::operator!=(const Color & rhs) const { return !(*this == rhs); } int Color::red() const { return m_rgba.r; } void Color::setRed(int value) { assert(0 <= value && value <= 255); m_rgba.r = static_cast<unsigned char>(value); } int Color::green() const { return m_rgba.g; } void Color::setGreen(int value) { assert(0 <= value && value <= 255); m_rgba.g = static_cast<unsigned char>(value); } int Color::blue() const { return m_rgba.b; } void Color::setBlue(int value) { assert(0 <= value && value <= 255); m_rgba.b = static_cast<unsigned char>(value); } int Color::alpha() const { return m_rgba.a; } void Color::setAlpha(int value) { assert(0 <= value && value <= 255); m_rgba.a = static_cast<unsigned char>(value); } unsigned int Color::bgra() const { return m_v; } void Color::setBgra(unsigned int bgra) { m_v = bgra; } Color Color::interpolate(const Color & other, float interpolationValue) const { return Color( static_cast<int>(m_rgba.r * (1.0 - interpolationValue) + other.m_rgba.r * interpolationValue), static_cast<int>(m_rgba.g * (1.0 - interpolationValue) + other.m_rgba.g * interpolationValue), static_cast<int>(m_rgba.b * (1.0 - interpolationValue) + other.m_rgba.b * interpolationValue), static_cast<int>(m_rgba.a * (1.0 - interpolationValue) + other.m_rgba.a * interpolationValue) ); } } // namespace reflectionzeug
mit
stoye/LiveSplit
LiveSplit/LiveSplit.Core/Model/Comparisons/MedianSegmentsComparisonGenerator.cs
3273
using LiveSplit.Options; using System; using System.Collections.Generic; using System.Linq; namespace LiveSplit.Model.Comparisons { public class MedianSegmentsComparisonGenerator : IComparisonGenerator { public IRun Run { get; set; } public const string ComparisonName = "Median Segments"; //you win glacials public const string ShortComparisonName = "Median"; public const double Weight = 0.75; public string Name { get { return ComparisonName; } } public MedianSegmentsComparisonGenerator(IRun run) { Run = run; } protected TimeSpan CalculateMedian(IEnumerable<TimeSpan> curList) { var elementCount = curList.Count(); var weightedList = curList.Select((x, i) => new KeyValuePair<double, TimeSpan>(GetWeight(i, elementCount), x)).ToList(); weightedList = weightedList.OrderBy(x => x.Value).ToList(); var totalWeights = weightedList.Aggregate(0.0, (s, x) => (s + x.Key)); var halfTotalWeights = totalWeights / 2; var curTotal = 0.0; foreach (var element in weightedList) { curTotal += element.Key; if (curTotal >= halfTotalWeights) return element.Value; } return TimeSpan.Zero; } protected double GetWeight(int index, int count) { return Math.Pow(Weight, count - index - 1); } public void Generate(TimingMethod method) { var allHistory = new List<List<TimeSpan>>(); foreach (var segment in Run) allHistory.Add(new List<TimeSpan>()); foreach (var attempt in Run.AttemptHistory) { var ind = attempt.Index; var ignoreNextHistory = false; foreach (var segment in Run) { IIndexedTime history; history = segment.SegmentHistory.FirstOrDefault(x => x.Index == ind); if (history != null) { if (history.Time[method] == null) ignoreNextHistory = true; else if (!ignoreNextHistory) { allHistory[Run.IndexOf(segment)].Add(history.Time[method].Value); } else ignoreNextHistory = false; } else break; } } TimeSpan? totalTime = TimeSpan.Zero; for (var ind = 0; ind < Run.Count; ind++) { var curList = allHistory[ind]; if (curList.Count == 0) totalTime = null; if (totalTime != null) totalTime += CalculateMedian(curList); var time = new Time(Run[ind].Comparisons[Name]); time[method] = totalTime; Run[ind].Comparisons[Name] = time; } } public void Generate(ISettings settings) { Generate(TimingMethod.RealTime); Generate(TimingMethod.GameTime); } } }
mit
OmicronPersei/nunit
src/NUnitFramework/framework/Interfaces/ITest.cs
4391
// *********************************************************************** // Copyright (c) 2007-2015 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** namespace NUnit.Framework.Interfaces { /// <summary> /// Common interface supported by all representations /// of a test. Only includes informational fields. /// The Run method is specifically excluded to allow /// for data-only representations of a test. /// </summary> public interface ITest : IXmlNodeBuilder { /// <summary> /// Gets the id of the test /// </summary> string Id { get; } /// <summary> /// Gets the name of the test /// </summary> string Name { get; } /// <summary> /// Gets the type of the test /// </summary> string TestType { get; } /// <summary> /// Gets the fully qualified name of the test /// </summary> string FullName { get; } /// <summary> /// Gets the name of the class containing this test. Returns /// null if the test is not associated with a class. /// </summary> string ClassName { get; } /// <summary> /// Gets the name of the method implementing this test. /// Returns null if the test is not implemented as a method. /// </summary> string MethodName { get; } /// <summary> /// Gets the Type of the test fixture, if applicable, or /// null if no fixture type is associated with this test. /// </summary> ITypeInfo TypeInfo { get; } /// <summary> /// Gets the method which declares the test, or <see langword="null"/> /// if no method is associated with this test. /// </summary> IMethodInfo Method { get; } /// <summary> /// Gets the RunState of the test, indicating whether it can be run. /// </summary> RunState RunState { get; } /// <summary> /// Count of the test cases ( 1 if this is a test case ) /// </summary> int TestCaseCount { get; } /// <summary> /// Gets the properties of the test /// </summary> IPropertyBag Properties { get; } /// <summary> /// Gets the parent test, if any. /// </summary> /// <value>The parent test or null if none exists.</value> ITest Parent { get; } /// <summary> /// Returns true if this is a test suite /// </summary> bool IsSuite { get; } /// <summary> /// Gets a bool indicating whether the current test /// has any descendant tests. /// </summary> bool HasChildren { get; } /// <summary> /// Gets this test's child tests /// </summary> /// <value>A list of child tests</value> System.Collections.Generic.IList<ITest> Tests { get; } /// <summary> /// Gets a fixture object for running this test. /// </summary> object Fixture { get; } /// <summary> /// The arguments to use in creating the test or empty array if none are required. /// </summary> object[] Arguments { get; } } }
mit
tagalpha/library
app/code/core/Mage/Adminhtml/Block/Widget/Accordion/Item.php
2648
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Mage * @package Mage_Adminhtml * @copyright Copyright (c) 2006-2017 X.commerce, Inc. and affiliates (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * Accordion item * * @category Mage * @package Mage_Adminhtml * @author Magento Core Team <core@magentocommerce.com> */ class Mage_Adminhtml_Block_Widget_Accordion_Item extends Mage_Adminhtml_Block_Widget { protected $_accordion; public function __construct() { parent::__construct(); } public function setAccordion($accordion) { $this->_accordion = $accordion; return $this; } public function getTarget() { return ($this->getAjax()) ? 'ajax' : ''; } public function getTitle() { $title = $this->getData('title'); $url = $this->getContentUrl() ? $this->getContentUrl() : '#'; $title = '<a href="'.$url.'" class="'.$this->getTarget().'">'.$title.'</a>'; return $title; } public function getContent() { $content = $this->getData('content'); if (is_string($content)) { return $content; } if ($content instanceof Mage_Core_Block_Abstract) { return $content->toHtml(); } return null; } public function getClass() { $class = $this->getData('class'); if ($this->getOpen()) { $class.= ' open'; } return $class; } protected function _toHtml() { $content = $this->getContent(); $html = '<dt id="dt-'.$this->getHtmlId().'" class="'.$this->getClass().'">'; $html.= $this->getTitle(); $html.= '</dt>'; $html.= '<dd id="dd-'.$this->getHtmlId().'" class="'.$this->getClass().'">'; $html.= $content; $html.= '</dd>'; return $html; } }
mit