code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30
values | license stringclasses 15
values | size int64 3 1.01M |
|---|---|---|---|---|---|
<!DOCTYPE html>
<meta charset="utf-8">
<title>cross-origin webvtt returned by service worker is detected</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/common/get-host-info.sub.js"></script>
<script src="resources/test-helpers.sub.js?pipe=sub"></script>
<body>
<script>
// This file tests responses for WebVTT text track from a service worker. It
// creates an iframe with a <track> element, controlled by a service worker.
// Each test tries to load a text track, the service worker intercepts the
// requests and responds with opaque or non-opaque responses. As the
// crossorigin attribute is not set, request's mode is always "same-origin",
// and as specified in https://fetch.spec.whatwg.org/#http-fetch,
// a response from a service worker whose type is neither "basic" nor
// "default" is rejected.
const host_info = get_host_info();
const kScript = 'resources/fetch-rewrite-worker.js';
// Add '?ignore' so the service worker falls back for the navigation.
const kScope = 'resources/vtt-frame.html?ignore';
let frame;
function load_track(url) {
const track = frame.contentDocument.querySelector('track');
const result = new Promise((resolve, reject) => {
track.onload = (e => {
resolve('load event');
});
track.onerror = (e => {
resolve('error event');
});
});
track.src = url;
// Setting mode to hidden seems needed, or else the text track requests don't
// occur.
track.track.mode = 'hidden';
return result;
}
promise_test(t => {
return service_worker_unregister_and_register(t, kScript, kScope)
.then(registration => {
promise_test(() => {
frame.remove();
return registration.unregister();
}, 'restore global state');
return wait_for_state(t, registration.installing, 'activated');
})
.then(() => {
return with_iframe(kScope);
})
.then(f => {
frame = f;
})
}, 'initialize global state');
promise_test(t => {
let url = '/media/foo.vtt';
// Add '?url' and tell the service worker to fetch a same-origin URL.
url += '?url=' + host_info.HTTPS_ORIGIN + '/media/foo.vtt';
return load_track(url)
.then(result => {
assert_equals(result, 'load event');
});
}, 'same-origin text track should load');
promise_test(t => {
let url = '/media/foo.vtt';
// Add '?url' and tell the service worker to fetch a cross-origin URL.
url += '?url=' + get_host_info().HTTPS_REMOTE_ORIGIN + '/media/foo.vtt';
return load_track(url)
.then(result => {
assert_equals(result, 'error event');
});
}, 'cross-origin text track with no-cors request should not load');
promise_test(t => {
let url = '/media/foo.vtt';
// Add '?url' and tell the service worker to fetch a cross-origin URL that
// doesn't support CORS.
url += '?url=' + get_host_info().HTTPS_REMOTE_ORIGIN +
'/media/foo-no-cors.vtt';
// Add '&mode' to tell the service worker to do a CORS request.
url += '&mode=cors';
return load_track(url)
.then(result => {
assert_equals(result, 'error event');
});
}, 'cross-origin text track with rejected cors request should not load');
promise_test(t => {
let url = '/media/foo.vtt';
// Add '?url' and tell the service worker to fetch a cross-origin URL.
url += '?url=' + get_host_info().HTTPS_REMOTE_ORIGIN + '/media/foo.vtt';
// Add '&mode' to tell the service worker to do a CORS request.
url += '&mode=cors';
// Add '&credentials=same-origin' to allow Access-Control-Allow-Origin=* so
// that CORS will succeed if the service approves it.
url += '&credentials=same-origin';
return load_track(url)
.then(result => {
assert_equals(result, 'error event');
});
}, 'cross-origin text track with approved cors request should not load');
// Redirect tests.
promise_test(t => {
let url = '/media/foo.vtt';
// Add '?url' and tell the service worker to fetch a same-origin URL that redirects...
redirector_url = host_info.HTTPS_ORIGIN + base_path() + 'resources/redirect.py?Redirect=';
// ... to a same-origin URL.
redirect_target = host_info.HTTPS_ORIGIN + '/media/foo.vtt';
url += '?url=' + encodeURIComponent(redirector_url + encodeURIComponent(redirect_target));
return load_track(url)
.then(result => {
assert_equals(result, 'load event');
});
}, 'same-origin text track that redirects same-origin should load');
promise_test(t => {
let url = '/media/foo.vtt';
// Add '?url' and tell the service worker to fetch a same-origin URL that redirects...
redirector_url = host_info.HTTPS_ORIGIN + base_path() + 'resources/redirect.py?Redirect=';
// ... to a cross-origin URL.
redirect_target = host_info.HTTPS_REMOTE_ORIGIN + '/media/foo.vtt';
url += '?url=' + encodeURIComponent(redirector_url + encodeURIComponent(redirect_target));
return load_track(url)
.then(result => {
assert_equals(result, 'error event');
});
}, 'same-origin text track that redirects cross-origin should not load');
promise_test(t => {
let url = '/media/foo.vtt';
// Add '?url' and tell the service worker to fetch a same-origin URL that redirects...
redirector_url = host_info.HTTPS_ORIGIN + base_path() + 'resources/redirect.py?Redirect=';
// ... to a cross-origin URL.
redirect_target = host_info.HTTPS_REMOTE_ORIGIN + '/media/foo-no-cors.vtt';
url += '?url=' + encodeURIComponent(redirector_url + encodeURIComponent(redirect_target));
// Add '&mode' to tell the service worker to do a CORS request.
url += '&mode=cors';
// Add '&credentials=same-origin' to allow Access-Control-Allow-Origin=* so
// that CORS will succeed if the server approves it.
url += '&credentials=same-origin';
return load_track(url)
.then(result => {
assert_equals(result, 'error event');
});
}, 'same-origin text track that redirects to a cross-origin text track with rejected cors should not load');
promise_test(t => {
let url = '/media/foo.vtt';
// Add '?url' and tell the service worker to fetch a same-origin URL that redirects...
redirector_url = host_info.HTTPS_ORIGIN + base_path() + 'resources/redirect.py?Redirect=';
// ... to a cross-origin URL.
redirect_target = host_info.HTTPS_REMOTE_ORIGIN + '/media/foo.vtt';
url += '?url=' + encodeURIComponent(redirector_url + encodeURIComponent(redirect_target));
// Add '&mode' to tell the service worker to do a CORS request.
url += '&mode=cors';
// Add '&credentials=same-origin' to allow Access-Control-Allow-Origin=* so
// that CORS will succeed if the server approves it.
url += '&credentials=same-origin';
return load_track(url)
.then(result => {
assert_equals(result, 'error event');
});
}, 'same-origin text track that redirects to a cross-origin text track with approved cors should not load');
</script>
</body>
| nwjs/chromium.src | third_party/blink/web_tests/external/wpt/service-workers/service-worker/webvtt-cross-origin.https.html | HTML | bsd-3-clause | 7,155 |
/************************************************************************************
This source file is part of the Theora Video Playback Library
For latest info, see http://libtheoraplayer.googlecode.com
*************************************************************************************
Copyright (c) 2008-2014 Kresimir Spes (kspes@cateia.com)
This program is free software; you can redistribute it and/or modify it under
the terms of the BSD license: http://opensource.org/licenses/BSD-3-Clause
*************************************************************************************/
#ifndef _YUV_LIBYUV_h
#define _YUV_LIBYUV_h
#include "TheoraPixelTransform.h"
#endif
| heroes9898/libtheoraplayer | theoraplayer/src/YUV/libyuv/yuv_libyuv.h | C | bsd-3-clause | 676 |
<html>
<head>
<script src="../../resources/js-test.js"></script>
<script src="resources/shared.js"></script>
</head>
<body>
<script src="resources/removed.js"></script>
</body>
</html>
| js0701/chromium-crosswalk | third_party/WebKit/LayoutTests/storage/indexeddb/removed.html | HTML | bsd-3-clause | 185 |
// Copyright 2006 The RE2 Authors. All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test parse.cc, dump.cc, and tostring.cc.
#include <string>
#include <vector>
#include "util/test.h"
#include "re2/regexp.h"
namespace re2 {
// Test that overflowed ref counts work.
TEST(Regexp, BigRef) {
Regexp* re;
re = Regexp::Parse("x", Regexp::NoParseFlags, NULL);
for (int i = 0; i < 100000; i++)
re->Incref();
for (int i = 0; i < 100000; i++)
re->Decref();
CHECK_EQ(re->Ref(), 1);
re->Decref();
}
// Test that very large Concats work.
// Depends on overflowed ref counts working.
TEST(Regexp, BigConcat) {
Regexp* x;
x = Regexp::Parse("x", Regexp::NoParseFlags, NULL);
vector<Regexp*> v(90000, x); // ToString bails out at 100000
for (int i = 0; i < v.size(); i++)
x->Incref();
CHECK_EQ(x->Ref(), 1 + v.size()) << x->Ref();
Regexp* re = Regexp::Concat(&v[0], v.size(), Regexp::NoParseFlags);
CHECK_EQ(re->ToString(), string(v.size(), 'x'));
re->Decref();
CHECK_EQ(x->Ref(), 1) << x->Ref();
x->Decref();
}
TEST(Regexp, NamedCaptures) {
Regexp* x;
RegexpStatus status;
x = Regexp::Parse(
"(?P<g1>a+)|(e)(?P<g2>w*)+(?P<g1>b+)", Regexp::PerlX, &status);
EXPECT_TRUE(status.ok());
EXPECT_EQ(4, x->NumCaptures());
const map<string, int>* have = x->NamedCaptures();
EXPECT_TRUE(have != NULL);
EXPECT_EQ(2, have->size()); // there are only two named groups in
// the regexp: 'g1' and 'g2'.
map<string, int> want;
want["g1"] = 1;
want["g2"] = 3;
EXPECT_EQ(want, *have);
x->Decref();
delete have;
}
TEST(Regexp, CaptureNames) {
Regexp* x;
RegexpStatus status;
x = Regexp::Parse(
"(?P<g1>a+)|(e)(?P<g2>w*)+(?P<g1>b+)", Regexp::PerlX, &status);
EXPECT_TRUE(status.ok());
EXPECT_EQ(4, x->NumCaptures());
const map<int, string>* have = x->CaptureNames();
EXPECT_TRUE(have != NULL);
EXPECT_EQ(3, have->size());
map<int, string> want;
want[1] = "g1";
want[3] = "g2";
want[4] = "g1";
EXPECT_EQ(want, *have);
x->Decref();
delete have;
}
} // namespace re2
| maxdjohnson/node-re2 | vendor/re2/re2/testing/regexp_test.cc | C++ | mit | 2,165 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* 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@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Log
* @subpackage Filter
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/** Zend_Log_Filter_Abstract */
require_once 'Zend/Log/Filter/Abstract.php';
/**
* @category Zend
* @package Zend_Log
* @subpackage Filter
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
class Zend_Log_Filter_Priority extends Zend_Log_Filter_Abstract
{
/**
* @var integer
*/
protected $_priority;
/**
* @var string
*/
protected $_operator;
/**
* Filter logging by $priority. By default, it will accept any log
* event whose priority value is less than or equal to $priority.
*
* @param integer $priority Priority
* @param string $operator Comparison operator
* @return void
* @throws Zend_Log_Exception
*/
public function __construct($priority, $operator = null)
{
if (! is_int($priority)) {
require_once 'Zend/Log/Exception.php';
throw new Zend_Log_Exception('Priority must be an integer');
}
$this->_priority = $priority;
$this->_operator = $operator === null ? '<=' : $operator;
}
/**
* Create a new instance of Zend_Log_Filter_Priority
*
* @param array|Zend_Config $config
* @return Zend_Log_Filter_Priority
*/
static public function factory($config)
{
$config = self::_parseConfig($config);
$config = array_merge(array(
'priority' => null,
'operator' => null,
), $config);
// Add support for constants
if (!is_numeric($config['priority']) && isset($config['priority']) && defined($config['priority'])) {
$config['priority'] = constant($config['priority']);
}
return new self(
(int) $config['priority'],
$config['operator']
);
}
/**
* Returns TRUE to accept the message, FALSE to block it.
*
* @param array $event event data
* @return boolean accepted?
*/
public function accept($event)
{
return version_compare($event['priority'], $this->_priority, $this->_operator);
}
}
| groundcall/jobeet | vendor/Zend/Log/Filter/Priority.php | PHP | mit | 2,942 |
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.XHRLoader = function ( manager ) {
this.cache = new THREE.Cache();
this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
};
THREE.XHRLoader.prototype = {
constructor: THREE.XHRLoader,
load: function ( url, onLoad, onProgress, onError ) {
var scope = this;
var cached = scope.cache.get( url );
if ( cached !== undefined ) {
if ( onLoad ) onLoad( cached );
return;
}
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
request.addEventListener( 'load', function ( event ) {
scope.cache.add( url, this.response );
if ( onLoad ) onLoad( this.response );
scope.manager.itemEnd( url );
}, false );
if ( onProgress !== undefined ) {
request.addEventListener( 'progress', function ( event ) {
onProgress( event );
}, false );
}
if ( onError !== undefined ) {
request.addEventListener( 'error', function ( event ) {
onError( event );
}, false );
}
if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
if ( this.responseType !== undefined ) request.responseType = this.responseType;
request.send( null );
scope.manager.itemStart( url );
},
setResponseType: function ( value ) {
this.responseType = value;
},
setCrossOrigin: function ( value ) {
this.crossOrigin = value;
}
};
| ccclayton/DataWar | static/js/threejs.r70/src/loaders/XHRLoader.js | JavaScript | mit | 1,408 |
import type { INoiseFactor } from "./INoiseFactor";
import type { IOptionLoader } from "../../IOptionLoader";
import type { INoiseDelay } from "./INoiseDelay";
export interface INoise extends IOptionLoader<INoise> {
delay: INoiseDelay;
enable: boolean;
factor: INoiseFactor;
}
| cdnjs/cdnjs | ajax/libs/tsparticles/1.16.0-alpha.5/Options/Interfaces/Particles/Noise/INoise.d.ts | TypeScript | mit | 289 |
/*
* Marvell PATA driver.
*
* For the moment we drive the PATA port in legacy mode. That
* isn't making full use of the device functionality but it is
* easy to get working.
*
* (c) 2006 Red Hat
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <scsi/scsi_host.h>
#include <linux/libata.h>
#include <linux/ata.h>
#define DRV_NAME "pata_marvell"
#define DRV_VERSION "0.1.6"
/**
* marvell_pata_active - check if PATA is active
* @pdev: PCI device
*
* Returns 1 if the PATA port may be active. We know how to check this
* for the 6145 but not the other devices
*/
static int marvell_pata_active(struct pci_dev *pdev)
{
int i;
u32 devices;
void __iomem *barp;
/* We don't yet know how to do this for other devices */
if (pdev->device != 0x6145)
return 1;
barp = pci_iomap(pdev, 5, 0x10);
if (barp == NULL)
return -ENOMEM;
printk("BAR5:");
for(i = 0; i <= 0x0F; i++)
printk("%02X:%02X ", i, ioread8(barp + i));
printk("\n");
devices = ioread32(barp + 0x0C);
pci_iounmap(pdev, barp);
if (devices & 0x10)
return 1;
return 0;
}
/**
* marvell_pre_reset - check for 40/80 pin
* @link: link
* @deadline: deadline jiffies for the operation
*
* Perform the PATA port setup we need.
*/
static int marvell_pre_reset(struct ata_link *link, unsigned long deadline)
{
struct ata_port *ap = link->ap;
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
if (pdev->device == 0x6145 && ap->port_no == 0 &&
!marvell_pata_active(pdev)) /* PATA enable ? */
return -ENOENT;
return ata_sff_prereset(link, deadline);
}
static int marvell_cable_detect(struct ata_port *ap)
{
/* Cable type */
switch(ap->port_no)
{
case 0:
if (ioread8(ap->ioaddr.bmdma_addr + 1) & 1)
return ATA_CBL_PATA40;
return ATA_CBL_PATA80;
case 1: /* Legacy SATA port */
return ATA_CBL_SATA;
}
BUG();
return 0; /* Our BUG macro needs the right markup */
}
/* No PIO or DMA methods needed for this device */
static struct scsi_host_template marvell_sht = {
ATA_BMDMA_SHT(DRV_NAME),
};
static struct ata_port_operations marvell_ops = {
.inherits = &ata_bmdma_port_ops,
.cable_detect = marvell_cable_detect,
.prereset = marvell_pre_reset,
};
/**
* marvell_init_one - Register Marvell ATA PCI device with kernel services
* @pdev: PCI device to register
* @ent: Entry in marvell_pci_tbl matching with @pdev
*
* Called from kernel PCI layer.
*
* LOCKING:
* Inherited from PCI layer (may sleep).
*
* RETURNS:
* Zero on success, or -ERRNO value.
*/
static int marvell_init_one (struct pci_dev *pdev, const struct pci_device_id *id)
{
static const struct ata_port_info info = {
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA5,
.port_ops = &marvell_ops,
};
static const struct ata_port_info info_sata = {
/* Slave possible as its magically mapped not real */
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA6,
.port_ops = &marvell_ops,
};
const struct ata_port_info *ppi[] = { &info, &info_sata };
if (pdev->device == 0x6101)
ppi[1] = &ata_dummy_port_info;
#if defined(CONFIG_SATA_AHCI) || defined(CONFIG_SATA_AHCI_MODULE)
if (!marvell_pata_active(pdev)) {
printk(KERN_INFO DRV_NAME ": PATA port not active, deferring to AHCI driver.\n");
return -ENODEV;
}
#endif
return ata_pci_sff_init_one(pdev, ppi, &marvell_sht, NULL);
}
static const struct pci_device_id marvell_pci_tbl[] = {
{ PCI_DEVICE(0x11AB, 0x6101), },
{ PCI_DEVICE(0x11AB, 0x6121), },
{ PCI_DEVICE(0x11AB, 0x6123), },
{ PCI_DEVICE(0x11AB, 0x6145), },
{ } /* terminate list */
};
static struct pci_driver marvell_pci_driver = {
.name = DRV_NAME,
.id_table = marvell_pci_tbl,
.probe = marvell_init_one,
.remove = ata_pci_remove_one,
#ifdef CONFIG_PM
.suspend = ata_pci_device_suspend,
.resume = ata_pci_device_resume,
#endif
};
static int __init marvell_init(void)
{
return pci_register_driver(&marvell_pci_driver);
}
static void __exit marvell_exit(void)
{
pci_unregister_driver(&marvell_pci_driver);
}
module_init(marvell_init);
module_exit(marvell_exit);
MODULE_AUTHOR("Alan Cox");
MODULE_DESCRIPTION("SCSI low-level driver for Marvell ATA in legacy mode");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, marvell_pci_tbl);
MODULE_VERSION(DRV_VERSION);
| MetSystem/fastsocket | kernel/drivers/ata/pata_marvell.c | C | gpl-2.0 | 4,476 |
#!/bin/sh
# generate a set of ABI signatures from a shared library
SHAREDLIB="$1"
GDBSCRIPT="gdb_syms.$$"
(
cat <<EOF
set height 0
set width 0
EOF
nm "$SHAREDLIB" | cut -d' ' -f2- | egrep '^[BDGTRVWS]' | grep -v @ | egrep -v ' (__bss_start|_edata|_init|_fini|_end)' | cut -c3- | sort | while read s; do
echo "echo $s: "
echo p $s
done
) > $GDBSCRIPT
# forcing the terminal avoids a problem on Fedora12
TERM=none gdb -batch -x $GDBSCRIPT "$SHAREDLIB" < /dev/null
rm -f $GDBSCRIPT
| SVoxel/R7800 | git_home/samba.git/buildtools/scripts/abi_gen.sh | Shell | gpl-2.0 | 491 |
// { dg-do compile }
// 2001-08-27 Benjamin Kosnik <bkoz@redhat.com>
// Copyright (C) 2001, 2003, 2009 Free Software Foundation
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, 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 General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// 22.2.6.2 Template class money_put
#include <locale>
void test01()
{
// Check for required base class.
typedef std::money_put<char> test_type;
typedef std::locale::facet base_type;
const test_type& obj = std::use_facet<test_type>(std::locale());
const base_type* base __attribute__((unused)) = &obj;
}
| SanDisk-Open-Source/SSD_Dashboard | uefi/gcc/gcc-4.6.3/libstdc++-v3/testsuite/22_locale/money_put/requirements/base_classes.cc | C++ | gpl-2.0 | 1,155 |
/*
* Video for Linux Two
*
* A generic video device interface for the LINUX operating system
* using a set of device structures/vectors for low level operations.
*
* This file replaces the videodev.c file that comes with the
* regular kernel distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Author: Bill Dirks <bill@thedirks.org>
* based on code by Alan Cox, <alan@cymru.net>
*
*/
/*
* Video capture interface for Linux
*
* A generic video device interface for the LINUX operating system
* using a set of device structures/vectors for low level operations.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Author: Alan Cox, <alan@lxorguk.ukuu.org.uk>
*
* Fixes:
*/
/*
* Video4linux 1/2 integration by Justin Schoeman
* <justin@suntiger.ee.up.ac.za>
* 2.4 PROCFS support ported from 2.4 kernels by
* Iñaki García Etxebarria <garetxe@euskalnet.net>
* Makefile fix by "W. Michael Petullo" <mike@flyn.org>
* 2.4 devfs support ported from 2.4 kernels by
* Dan Merillat <dan@merillat.org>
* Added Gerd Knorrs v4l1 enhancements (Justin Schoeman)
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/i2c.h>
#if defined(CONFIG_SPI)
#include <linux/spi/spi.h>
#endif
#include <asm/uaccess.h>
#include <asm/pgtable.h>
#include <asm/io.h>
#include <asm/div64.h>
#include <media/v4l2-common.h>
#include <media/v4l2-device.h>
#include <media/v4l2-ctrls.h>
#include <media/v4l2-chip-ident.h>
#include <linux/videodev2.h>
MODULE_AUTHOR("Bill Dirks, Justin Schoeman, Gerd Knorr");
MODULE_DESCRIPTION("misc helper functions for v4l2 device drivers");
MODULE_LICENSE("GPL");
/*
*
* V 4 L 2 D R I V E R H E L P E R A P I
*
*/
/*
* Video Standard Operations (contributed by Michael Schimek)
*/
/* Helper functions for control handling */
/* Check for correctness of the ctrl's value based on the data from
struct v4l2_queryctrl and the available menu items. Note that
menu_items may be NULL, in that case it is ignored. */
int v4l2_ctrl_check(struct v4l2_ext_control *ctrl, struct v4l2_queryctrl *qctrl,
const char * const *menu_items)
{
if (qctrl->flags & V4L2_CTRL_FLAG_DISABLED)
return -EINVAL;
if (qctrl->flags & V4L2_CTRL_FLAG_GRABBED)
return -EBUSY;
if (qctrl->type == V4L2_CTRL_TYPE_STRING)
return 0;
if (qctrl->type == V4L2_CTRL_TYPE_BUTTON ||
qctrl->type == V4L2_CTRL_TYPE_INTEGER64 ||
qctrl->type == V4L2_CTRL_TYPE_CTRL_CLASS)
return 0;
if (ctrl->value < qctrl->minimum || ctrl->value > qctrl->maximum)
return -ERANGE;
if (qctrl->type == V4L2_CTRL_TYPE_MENU && menu_items != NULL) {
if (menu_items[ctrl->value] == NULL ||
menu_items[ctrl->value][0] == '\0')
return -EINVAL;
}
if (qctrl->type == V4L2_CTRL_TYPE_BITMASK &&
(ctrl->value & ~qctrl->maximum))
return -ERANGE;
return 0;
}
EXPORT_SYMBOL(v4l2_ctrl_check);
/* Fill in a struct v4l2_queryctrl */
int v4l2_ctrl_query_fill(struct v4l2_queryctrl *qctrl, s32 min, s32 max, s32 step, s32 def)
{
const char *name;
v4l2_ctrl_fill(qctrl->id, &name, &qctrl->type,
&min, &max, &step, &def, &qctrl->flags);
if (name == NULL)
return -EINVAL;
qctrl->minimum = min;
qctrl->maximum = max;
qctrl->step = step;
qctrl->default_value = def;
qctrl->reserved[0] = qctrl->reserved[1] = 0;
strlcpy(qctrl->name, name, sizeof(qctrl->name));
return 0;
}
EXPORT_SYMBOL(v4l2_ctrl_query_fill);
/* Fill in a struct v4l2_querymenu based on the struct v4l2_queryctrl and
the menu. The qctrl pointer may be NULL, in which case it is ignored.
If menu_items is NULL, then the menu items are retrieved using
v4l2_ctrl_get_menu. */
int v4l2_ctrl_query_menu(struct v4l2_querymenu *qmenu, struct v4l2_queryctrl *qctrl,
const char * const *menu_items)
{
int i;
qmenu->reserved = 0;
if (menu_items == NULL)
menu_items = v4l2_ctrl_get_menu(qmenu->id);
if (menu_items == NULL ||
(qctrl && (qmenu->index < qctrl->minimum || qmenu->index > qctrl->maximum)))
return -EINVAL;
for (i = 0; i < qmenu->index && menu_items[i]; i++) ;
if (menu_items[i] == NULL || menu_items[i][0] == '\0')
return -EINVAL;
strlcpy(qmenu->name, menu_items[qmenu->index], sizeof(qmenu->name));
return 0;
}
EXPORT_SYMBOL(v4l2_ctrl_query_menu);
/* Fill in a struct v4l2_querymenu based on the specified array of valid
menu items (terminated by V4L2_CTRL_MENU_IDS_END).
Use this if there are 'holes' in the list of valid menu items. */
int v4l2_ctrl_query_menu_valid_items(struct v4l2_querymenu *qmenu, const u32 *ids)
{
const char * const *menu_items = v4l2_ctrl_get_menu(qmenu->id);
qmenu->reserved = 0;
if (menu_items == NULL || ids == NULL)
return -EINVAL;
while (*ids != V4L2_CTRL_MENU_IDS_END) {
if (*ids++ == qmenu->index) {
strlcpy(qmenu->name, menu_items[qmenu->index],
sizeof(qmenu->name));
return 0;
}
}
return -EINVAL;
}
EXPORT_SYMBOL(v4l2_ctrl_query_menu_valid_items);
/* ctrl_classes points to an array of u32 pointers, the last element is
a NULL pointer. Each u32 array is a 0-terminated array of control IDs.
Each array must be sorted low to high and belong to the same control
class. The array of u32 pointers must also be sorted, from low class IDs
to high class IDs.
This function returns the first ID that follows after the given ID.
When no more controls are available 0 is returned. */
u32 v4l2_ctrl_next(const u32 * const * ctrl_classes, u32 id)
{
u32 ctrl_class = V4L2_CTRL_ID2CLASS(id);
const u32 *pctrl;
if (ctrl_classes == NULL)
return 0;
/* if no query is desired, then check if the ID is part of ctrl_classes */
if ((id & V4L2_CTRL_FLAG_NEXT_CTRL) == 0) {
/* find class */
while (*ctrl_classes && V4L2_CTRL_ID2CLASS(**ctrl_classes) != ctrl_class)
ctrl_classes++;
if (*ctrl_classes == NULL)
return 0;
pctrl = *ctrl_classes;
/* find control ID */
while (*pctrl && *pctrl != id) pctrl++;
return *pctrl ? id : 0;
}
id &= V4L2_CTRL_ID_MASK;
id++; /* select next control */
/* find first class that matches (or is greater than) the class of
the ID */
while (*ctrl_classes && V4L2_CTRL_ID2CLASS(**ctrl_classes) < ctrl_class)
ctrl_classes++;
/* no more classes */
if (*ctrl_classes == NULL)
return 0;
pctrl = *ctrl_classes;
/* find first ctrl within the class that is >= ID */
while (*pctrl && *pctrl < id) pctrl++;
if (*pctrl)
return *pctrl;
/* we are at the end of the controls of the current class. */
/* continue with next class if available */
ctrl_classes++;
if (*ctrl_classes == NULL)
return 0;
return **ctrl_classes;
}
EXPORT_SYMBOL(v4l2_ctrl_next);
int v4l2_chip_match_host(const struct v4l2_dbg_match *match)
{
switch (match->type) {
case V4L2_CHIP_MATCH_HOST:
return match->addr == 0;
default:
return 0;
}
}
EXPORT_SYMBOL(v4l2_chip_match_host);
#if defined(CONFIG_I2C) || (defined(CONFIG_I2C_MODULE) && defined(MODULE))
int v4l2_chip_match_i2c_client(struct i2c_client *c, const struct v4l2_dbg_match *match)
{
int len;
if (c == NULL || match == NULL)
return 0;
switch (match->type) {
case V4L2_CHIP_MATCH_I2C_DRIVER:
if (c->driver == NULL || c->driver->driver.name == NULL)
return 0;
len = strlen(c->driver->driver.name);
/* legacy drivers have a ' suffix, don't try to match that */
if (len && c->driver->driver.name[len - 1] == '\'')
len--;
return len && !strncmp(c->driver->driver.name, match->name, len);
case V4L2_CHIP_MATCH_I2C_ADDR:
return c->addr == match->addr;
default:
return 0;
}
}
EXPORT_SYMBOL(v4l2_chip_match_i2c_client);
int v4l2_chip_ident_i2c_client(struct i2c_client *c, struct v4l2_dbg_chip_ident *chip,
u32 ident, u32 revision)
{
if (!v4l2_chip_match_i2c_client(c, &chip->match))
return 0;
if (chip->ident == V4L2_IDENT_NONE) {
chip->ident = ident;
chip->revision = revision;
}
else {
chip->ident = V4L2_IDENT_AMBIGUOUS;
chip->revision = 0;
}
return 0;
}
EXPORT_SYMBOL(v4l2_chip_ident_i2c_client);
/* ----------------------------------------------------------------- */
/* I2C Helper functions */
void v4l2_i2c_subdev_init(struct v4l2_subdev *sd, struct i2c_client *client,
const struct v4l2_subdev_ops *ops)
{
v4l2_subdev_init(sd, ops);
sd->flags |= V4L2_SUBDEV_FL_IS_I2C;
/* the owner is the same as the i2c_client's driver owner */
sd->owner = client->driver->driver.owner;
/* i2c_client and v4l2_subdev point to one another */
v4l2_set_subdevdata(sd, client);
i2c_set_clientdata(client, sd);
/* initialize name */
snprintf(sd->name, sizeof(sd->name), "%s %d-%04x",
client->driver->driver.name, i2c_adapter_id(client->adapter),
client->addr);
}
EXPORT_SYMBOL_GPL(v4l2_i2c_subdev_init);
/* Load an i2c sub-device. */
struct v4l2_subdev *v4l2_i2c_new_subdev_board(struct v4l2_device *v4l2_dev,
struct i2c_adapter *adapter, struct i2c_board_info *info,
const unsigned short *probe_addrs)
{
struct v4l2_subdev *sd = NULL;
struct i2c_client *client;
BUG_ON(!v4l2_dev);
request_module(I2C_MODULE_PREFIX "%s", info->type);
/* Create the i2c client */
if (info->addr == 0 && probe_addrs)
client = i2c_new_probed_device(adapter, info, probe_addrs,
NULL);
else
client = i2c_new_device(adapter, info);
/* Note: by loading the module first we are certain that c->driver
will be set if the driver was found. If the module was not loaded
first, then the i2c core tries to delay-load the module for us,
and then c->driver is still NULL until the module is finally
loaded. This delay-load mechanism doesn't work if other drivers
want to use the i2c device, so explicitly loading the module
is the best alternative. */
if (client == NULL || client->driver == NULL)
goto error;
/* Lock the module so we can safely get the v4l2_subdev pointer */
if (!try_module_get(client->driver->driver.owner))
goto error;
sd = i2c_get_clientdata(client);
/* Register with the v4l2_device which increases the module's
use count as well. */
if (v4l2_device_register_subdev(v4l2_dev, sd))
sd = NULL;
/* Decrease the module use count to match the first try_module_get. */
module_put(client->driver->driver.owner);
error:
/* If we have a client but no subdev, then something went wrong and
we must unregister the client. */
if (client && sd == NULL)
i2c_unregister_device(client);
return sd;
}
EXPORT_SYMBOL_GPL(v4l2_i2c_new_subdev_board);
struct v4l2_subdev *v4l2_i2c_new_subdev(struct v4l2_device *v4l2_dev,
struct i2c_adapter *adapter, const char *client_type,
u8 addr, const unsigned short *probe_addrs)
{
struct i2c_board_info info;
/* Setup the i2c board info with the device type and
the device address. */
memset(&info, 0, sizeof(info));
strlcpy(info.type, client_type, sizeof(info.type));
info.addr = addr;
return v4l2_i2c_new_subdev_board(v4l2_dev, adapter, &info, probe_addrs);
}
EXPORT_SYMBOL_GPL(v4l2_i2c_new_subdev);
/* Return i2c client address of v4l2_subdev. */
unsigned short v4l2_i2c_subdev_addr(struct v4l2_subdev *sd)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
return client ? client->addr : I2C_CLIENT_END;
}
EXPORT_SYMBOL_GPL(v4l2_i2c_subdev_addr);
/* Return a list of I2C tuner addresses to probe. Use only if the tuner
addresses are unknown. */
const unsigned short *v4l2_i2c_tuner_addrs(enum v4l2_i2c_tuner_type type)
{
static const unsigned short radio_addrs[] = {
#if defined(CONFIG_MEDIA_TUNER_TEA5761) || defined(CONFIG_MEDIA_TUNER_TEA5761_MODULE)
0x10,
#endif
0x60,
I2C_CLIENT_END
};
static const unsigned short demod_addrs[] = {
0x42, 0x43, 0x4a, 0x4b,
I2C_CLIENT_END
};
static const unsigned short tv_addrs[] = {
0x42, 0x43, 0x4a, 0x4b, /* tda8290 */
0x60, 0x61, 0x62, 0x63, 0x64,
I2C_CLIENT_END
};
switch (type) {
case ADDRS_RADIO:
return radio_addrs;
case ADDRS_DEMOD:
return demod_addrs;
case ADDRS_TV:
return tv_addrs;
case ADDRS_TV_WITH_DEMOD:
return tv_addrs + 4;
}
return NULL;
}
EXPORT_SYMBOL_GPL(v4l2_i2c_tuner_addrs);
#endif /* defined(CONFIG_I2C) */
#if defined(CONFIG_SPI)
/* Load an spi sub-device. */
void v4l2_spi_subdev_init(struct v4l2_subdev *sd, struct spi_device *spi,
const struct v4l2_subdev_ops *ops)
{
v4l2_subdev_init(sd, ops);
sd->flags |= V4L2_SUBDEV_FL_IS_SPI;
/* the owner is the same as the spi_device's driver owner */
sd->owner = spi->dev.driver->owner;
/* spi_device and v4l2_subdev point to one another */
v4l2_set_subdevdata(sd, spi);
spi_set_drvdata(spi, sd);
/* initialize name */
strlcpy(sd->name, spi->dev.driver->name, sizeof(sd->name));
}
EXPORT_SYMBOL_GPL(v4l2_spi_subdev_init);
struct v4l2_subdev *v4l2_spi_new_subdev(struct v4l2_device *v4l2_dev,
struct spi_master *master, struct spi_board_info *info)
{
struct v4l2_subdev *sd = NULL;
struct spi_device *spi = NULL;
BUG_ON(!v4l2_dev);
if (info->modalias[0])
request_module(info->modalias);
spi = spi_new_device(master, info);
if (spi == NULL || spi->dev.driver == NULL)
goto error;
if (!try_module_get(spi->dev.driver->owner))
goto error;
sd = spi_get_drvdata(spi);
/* Register with the v4l2_device which increases the module's
use count as well. */
if (v4l2_device_register_subdev(v4l2_dev, sd))
sd = NULL;
/* Decrease the module use count to match the first try_module_get. */
module_put(spi->dev.driver->owner);
error:
/* If we have a client but no subdev, then something went wrong and
we must unregister the client. */
if (spi && sd == NULL)
spi_unregister_device(spi);
return sd;
}
EXPORT_SYMBOL_GPL(v4l2_spi_new_subdev);
#endif /* defined(CONFIG_SPI) */
/* Clamp x to be between min and max, aligned to a multiple of 2^align. min
* and max don't have to be aligned, but there must be at least one valid
* value. E.g., min=17,max=31,align=4 is not allowed as there are no multiples
* of 16 between 17 and 31. */
static unsigned int clamp_align(unsigned int x, unsigned int min,
unsigned int max, unsigned int align)
{
/* Bits that must be zero to be aligned */
unsigned int mask = ~((1 << align) - 1);
/* Round to nearest aligned value */
if (align)
x = (x + (1 << (align - 1))) & mask;
/* Clamp to aligned value of min and max */
if (x < min)
x = (min + ~mask) & mask;
else if (x > max)
x = max & mask;
return x;
}
/* Bound an image to have a width between wmin and wmax, and height between
* hmin and hmax, inclusive. Additionally, the width will be a multiple of
* 2^walign, the height will be a multiple of 2^halign, and the overall size
* (width*height) will be a multiple of 2^salign. The image may be shrunk
* or enlarged to fit the alignment constraints.
*
* The width or height maximum must not be smaller than the corresponding
* minimum. The alignments must not be so high there are no possible image
* sizes within the allowed bounds. wmin and hmin must be at least 1
* (don't use 0). If you don't care about a certain alignment, specify 0,
* as 2^0 is 1 and one byte alignment is equivalent to no alignment. If
* you only want to adjust downward, specify a maximum that's the same as
* the initial value.
*/
void v4l_bound_align_image(u32 *w, unsigned int wmin, unsigned int wmax,
unsigned int walign,
u32 *h, unsigned int hmin, unsigned int hmax,
unsigned int halign, unsigned int salign)
{
*w = clamp_align(*w, wmin, wmax, walign);
*h = clamp_align(*h, hmin, hmax, halign);
/* Usually we don't need to align the size and are done now. */
if (!salign)
return;
/* How much alignment do we have? */
walign = __ffs(*w);
halign = __ffs(*h);
/* Enough to satisfy the image alignment? */
if (walign + halign < salign) {
/* Max walign where there is still a valid width */
unsigned int wmaxa = __fls(wmax ^ (wmin - 1));
/* Max halign where there is still a valid height */
unsigned int hmaxa = __fls(hmax ^ (hmin - 1));
/* up the smaller alignment until we have enough */
do {
if (halign >= hmaxa ||
(walign <= halign && walign < wmaxa)) {
*w = clamp_align(*w, wmin, wmax, walign + 1);
walign = __ffs(*w);
} else {
*h = clamp_align(*h, hmin, hmax, halign + 1);
halign = __ffs(*h);
}
} while (halign + walign < salign);
}
}
EXPORT_SYMBOL_GPL(v4l_bound_align_image);
/**
* v4l_fill_dv_preset_info - fill description of a digital video preset
* @preset - preset value
* @info - pointer to struct v4l2_dv_enum_preset
*
* drivers can use this helper function to fill description of dv preset
* in info.
*/
int v4l_fill_dv_preset_info(u32 preset, struct v4l2_dv_enum_preset *info)
{
static const struct v4l2_dv_preset_info {
u16 width;
u16 height;
const char *name;
} dv_presets[] = {
{ 0, 0, "Invalid" }, /* V4L2_DV_INVALID */
{ 720, 480, "480p@59.94" }, /* V4L2_DV_480P59_94 */
{ 720, 576, "576p@50" }, /* V4L2_DV_576P50 */
{ 1280, 720, "720p@24" }, /* V4L2_DV_720P24 */
{ 1280, 720, "720p@25" }, /* V4L2_DV_720P25 */
{ 1280, 720, "720p@30" }, /* V4L2_DV_720P30 */
{ 1280, 720, "720p@50" }, /* V4L2_DV_720P50 */
{ 1280, 720, "720p@59.94" }, /* V4L2_DV_720P59_94 */
{ 1280, 720, "720p@60" }, /* V4L2_DV_720P60 */
{ 1920, 1080, "1080i@29.97" }, /* V4L2_DV_1080I29_97 */
{ 1920, 1080, "1080i@30" }, /* V4L2_DV_1080I30 */
{ 1920, 1080, "1080i@25" }, /* V4L2_DV_1080I25 */
{ 1920, 1080, "1080i@50" }, /* V4L2_DV_1080I50 */
{ 1920, 1080, "1080i@60" }, /* V4L2_DV_1080I60 */
{ 1920, 1080, "1080p@24" }, /* V4L2_DV_1080P24 */
{ 1920, 1080, "1080p@25" }, /* V4L2_DV_1080P25 */
{ 1920, 1080, "1080p@30" }, /* V4L2_DV_1080P30 */
{ 1920, 1080, "1080p@50" }, /* V4L2_DV_1080P50 */
{ 1920, 1080, "1080p@60" }, /* V4L2_DV_1080P60 */
};
if (info == NULL || preset >= ARRAY_SIZE(dv_presets))
return -EINVAL;
info->preset = preset;
info->width = dv_presets[preset].width;
info->height = dv_presets[preset].height;
strlcpy(info->name, dv_presets[preset].name, sizeof(info->name));
return 0;
}
EXPORT_SYMBOL_GPL(v4l_fill_dv_preset_info);
/**
* v4l_match_dv_timings - check if two timings match
* @t1 - compare this v4l2_dv_timings struct...
* @t2 - with this struct.
* @pclock_delta - the allowed pixelclock deviation.
*
* Compare t1 with t2 with a given margin of error for the pixelclock.
*/
bool v4l_match_dv_timings(const struct v4l2_dv_timings *t1,
const struct v4l2_dv_timings *t2,
unsigned pclock_delta)
{
if (t1->type != t2->type || t1->type != V4L2_DV_BT_656_1120)
return false;
if (t1->bt.width == t2->bt.width &&
t1->bt.height == t2->bt.height &&
t1->bt.interlaced == t2->bt.interlaced &&
t1->bt.polarities == t2->bt.polarities &&
t1->bt.pixelclock >= t2->bt.pixelclock - pclock_delta &&
t1->bt.pixelclock <= t2->bt.pixelclock + pclock_delta &&
t1->bt.hfrontporch == t2->bt.hfrontporch &&
t1->bt.vfrontporch == t2->bt.vfrontporch &&
t1->bt.vsync == t2->bt.vsync &&
t1->bt.vbackporch == t2->bt.vbackporch &&
(!t1->bt.interlaced ||
(t1->bt.il_vfrontporch == t2->bt.il_vfrontporch &&
t1->bt.il_vsync == t2->bt.il_vsync &&
t1->bt.il_vbackporch == t2->bt.il_vbackporch)))
return true;
return false;
}
EXPORT_SYMBOL_GPL(v4l_match_dv_timings);
/*
* CVT defines
* Based on Coordinated Video Timings Standard
* version 1.1 September 10, 2003
*/
#define CVT_PXL_CLK_GRAN 250000 /* pixel clock granularity */
/* Normal blanking */
#define CVT_MIN_V_BPORCH 7 /* lines */
#define CVT_MIN_V_PORCH_RND 3 /* lines */
#define CVT_MIN_VSYNC_BP 550 /* min time of vsync + back porch (us) */
/* Normal blanking for CVT uses GTF to calculate horizontal blanking */
#define CVT_CELL_GRAN 8 /* character cell granularity */
#define CVT_M 600 /* blanking formula gradient */
#define CVT_C 40 /* blanking formula offset */
#define CVT_K 128 /* blanking formula scaling factor */
#define CVT_J 20 /* blanking formula scaling factor */
#define CVT_C_PRIME (((CVT_C - CVT_J) * CVT_K / 256) + CVT_J)
#define CVT_M_PRIME (CVT_K * CVT_M / 256)
/* Reduced Blanking */
#define CVT_RB_MIN_V_BPORCH 7 /* lines */
#define CVT_RB_V_FPORCH 3 /* lines */
#define CVT_RB_MIN_V_BLANK 460 /* us */
#define CVT_RB_H_SYNC 32 /* pixels */
#define CVT_RB_H_BPORCH 80 /* pixels */
#define CVT_RB_H_BLANK 160 /* pixels */
/** v4l2_detect_cvt - detect if the given timings follow the CVT standard
* @frame_height - the total height of the frame (including blanking) in lines.
* @hfreq - the horizontal frequency in Hz.
* @vsync - the height of the vertical sync in lines.
* @polarities - the horizontal and vertical polarities (same as struct
* v4l2_bt_timings polarities).
* @fmt - the resulting timings.
*
* This function will attempt to detect if the given values correspond to a
* valid CVT format. If so, then it will return true, and fmt will be filled
* in with the found CVT timings.
*/
bool v4l2_detect_cvt(unsigned frame_height, unsigned hfreq, unsigned vsync,
u32 polarities, struct v4l2_dv_timings *fmt)
{
int v_fp, v_bp, h_fp, h_bp, hsync;
int frame_width, image_height, image_width;
bool reduced_blanking;
unsigned pix_clk;
if (vsync < 4 || vsync > 7)
return false;
if (polarities == V4L2_DV_VSYNC_POS_POL)
reduced_blanking = false;
else if (polarities == V4L2_DV_HSYNC_POS_POL)
reduced_blanking = true;
else
return false;
/* Vertical */
if (reduced_blanking) {
v_fp = CVT_RB_V_FPORCH;
v_bp = (CVT_RB_MIN_V_BLANK * hfreq + 999999) / 1000000;
v_bp -= vsync + v_fp;
if (v_bp < CVT_RB_MIN_V_BPORCH)
v_bp = CVT_RB_MIN_V_BPORCH;
} else {
v_fp = CVT_MIN_V_PORCH_RND;
v_bp = (CVT_MIN_VSYNC_BP * hfreq + 999999) / 1000000 - vsync;
if (v_bp < CVT_MIN_V_BPORCH)
v_bp = CVT_MIN_V_BPORCH;
}
image_height = (frame_height - v_fp - vsync - v_bp + 1) & ~0x1;
/* Aspect ratio based on vsync */
switch (vsync) {
case 4:
image_width = (image_height * 4) / 3;
break;
case 5:
image_width = (image_height * 16) / 9;
break;
case 6:
image_width = (image_height * 16) / 10;
break;
case 7:
/* special case */
if (image_height == 1024)
image_width = (image_height * 5) / 4;
else if (image_height == 768)
image_width = (image_height * 15) / 9;
else
return false;
break;
default:
return false;
}
image_width = image_width & ~7;
/* Horizontal */
if (reduced_blanking) {
pix_clk = (image_width + CVT_RB_H_BLANK) * hfreq;
pix_clk = (pix_clk / CVT_PXL_CLK_GRAN) * CVT_PXL_CLK_GRAN;
h_bp = CVT_RB_H_BPORCH;
hsync = CVT_RB_H_SYNC;
h_fp = CVT_RB_H_BLANK - h_bp - hsync;
frame_width = image_width + CVT_RB_H_BLANK;
} else {
int h_blank;
unsigned ideal_duty_cycle = CVT_C_PRIME - (CVT_M_PRIME * 1000) / hfreq;
h_blank = (image_width * ideal_duty_cycle + (100 - ideal_duty_cycle) / 2) /
(100 - ideal_duty_cycle);
h_blank = h_blank - h_blank % (2 * CVT_CELL_GRAN);
if (h_blank * 100 / image_width < 20) {
h_blank = image_width / 5;
h_blank = (h_blank + 0x7) & ~0x7;
}
pix_clk = (image_width + h_blank) * hfreq;
pix_clk = (pix_clk / CVT_PXL_CLK_GRAN) * CVT_PXL_CLK_GRAN;
h_bp = h_blank / 2;
frame_width = image_width + h_blank;
hsync = (frame_width * 8 + 50) / 100;
hsync = hsync - hsync % CVT_CELL_GRAN;
h_fp = h_blank - hsync - h_bp;
}
fmt->bt.polarities = polarities;
fmt->bt.width = image_width;
fmt->bt.height = image_height;
fmt->bt.hfrontporch = h_fp;
fmt->bt.vfrontporch = v_fp;
fmt->bt.hsync = hsync;
fmt->bt.vsync = vsync;
fmt->bt.hbackporch = frame_width - image_width - h_fp - hsync;
fmt->bt.vbackporch = frame_height - image_height - v_fp - vsync;
fmt->bt.pixelclock = pix_clk;
fmt->bt.standards = V4L2_DV_BT_STD_CVT;
if (reduced_blanking)
fmt->bt.flags |= V4L2_DV_FL_REDUCED_BLANKING;
return true;
}
EXPORT_SYMBOL_GPL(v4l2_detect_cvt);
/*
* GTF defines
* Based on Generalized Timing Formula Standard
* Version 1.1 September 2, 1999
*/
#define GTF_PXL_CLK_GRAN 250000 /* pixel clock granularity */
#define GTF_MIN_VSYNC_BP 550 /* min time of vsync + back porch (us) */
#define GTF_V_FP 1 /* vertical front porch (lines) */
#define GTF_CELL_GRAN 8 /* character cell granularity */
/* Default */
#define GTF_D_M 600 /* blanking formula gradient */
#define GTF_D_C 40 /* blanking formula offset */
#define GTF_D_K 128 /* blanking formula scaling factor */
#define GTF_D_J 20 /* blanking formula scaling factor */
#define GTF_D_C_PRIME ((((GTF_D_C - GTF_D_J) * GTF_D_K) / 256) + GTF_D_J)
#define GTF_D_M_PRIME ((GTF_D_K * GTF_D_M) / 256)
/* Secondary */
#define GTF_S_M 3600 /* blanking formula gradient */
#define GTF_S_C 40 /* blanking formula offset */
#define GTF_S_K 128 /* blanking formula scaling factor */
#define GTF_S_J 35 /* blanking formula scaling factor */
#define GTF_S_C_PRIME ((((GTF_S_C - GTF_S_J) * GTF_S_K) / 256) + GTF_S_J)
#define GTF_S_M_PRIME ((GTF_S_K * GTF_S_M) / 256)
/** v4l2_detect_gtf - detect if the given timings follow the GTF standard
* @frame_height - the total height of the frame (including blanking) in lines.
* @hfreq - the horizontal frequency in Hz.
* @vsync - the height of the vertical sync in lines.
* @polarities - the horizontal and vertical polarities (same as struct
* v4l2_bt_timings polarities).
* @aspect - preferred aspect ratio. GTF has no method of determining the
* aspect ratio in order to derive the image width from the
* image height, so it has to be passed explicitly. Usually
* the native screen aspect ratio is used for this. If it
* is not filled in correctly, then 16:9 will be assumed.
* @fmt - the resulting timings.
*
* This function will attempt to detect if the given values correspond to a
* valid GTF format. If so, then it will return true, and fmt will be filled
* in with the found GTF timings.
*/
bool v4l2_detect_gtf(unsigned frame_height,
unsigned hfreq,
unsigned vsync,
u32 polarities,
struct v4l2_fract aspect,
struct v4l2_dv_timings *fmt)
{
int pix_clk;
int v_fp, v_bp, h_fp, h_bp, hsync;
int frame_width, image_height, image_width;
bool default_gtf;
int h_blank;
if (vsync != 3)
return false;
if (polarities == V4L2_DV_VSYNC_POS_POL)
default_gtf = true;
else if (polarities == V4L2_DV_HSYNC_POS_POL)
default_gtf = false;
else
return false;
/* Vertical */
v_fp = GTF_V_FP;
v_bp = (GTF_MIN_VSYNC_BP * hfreq + 999999) / 1000000 - vsync;
image_height = (frame_height - v_fp - vsync - v_bp + 1) & ~0x1;
if (aspect.numerator == 0 || aspect.denominator == 0) {
aspect.numerator = 16;
aspect.denominator = 9;
}
image_width = ((image_height * aspect.numerator) / aspect.denominator);
/* Horizontal */
if (default_gtf)
h_blank = ((image_width * GTF_D_C_PRIME * hfreq) -
(image_width * GTF_D_M_PRIME * 1000) +
(hfreq * (100 - GTF_D_C_PRIME) + GTF_D_M_PRIME * 1000) / 2) /
(hfreq * (100 - GTF_D_C_PRIME) + GTF_D_M_PRIME * 1000);
else
h_blank = ((image_width * GTF_S_C_PRIME * hfreq) -
(image_width * GTF_S_M_PRIME * 1000) +
(hfreq * (100 - GTF_S_C_PRIME) + GTF_S_M_PRIME * 1000) / 2) /
(hfreq * (100 - GTF_S_C_PRIME) + GTF_S_M_PRIME * 1000);
h_blank = h_blank - h_blank % (2 * GTF_CELL_GRAN);
frame_width = image_width + h_blank;
pix_clk = (image_width + h_blank) * hfreq;
pix_clk = pix_clk / GTF_PXL_CLK_GRAN * GTF_PXL_CLK_GRAN;
hsync = (frame_width * 8 + 50) / 100;
hsync = hsync - hsync % GTF_CELL_GRAN;
h_fp = h_blank / 2 - hsync;
h_bp = h_blank / 2;
fmt->bt.polarities = polarities;
fmt->bt.width = image_width;
fmt->bt.height = image_height;
fmt->bt.hfrontporch = h_fp;
fmt->bt.vfrontporch = v_fp;
fmt->bt.hsync = hsync;
fmt->bt.vsync = vsync;
fmt->bt.hbackporch = frame_width - image_width - h_fp - hsync;
fmt->bt.vbackporch = frame_height - image_height - v_fp - vsync;
fmt->bt.pixelclock = pix_clk;
fmt->bt.standards = V4L2_DV_BT_STD_GTF;
if (!default_gtf)
fmt->bt.flags |= V4L2_DV_FL_REDUCED_BLANKING;
return true;
}
EXPORT_SYMBOL_GPL(v4l2_detect_gtf);
/** v4l2_calc_aspect_ratio - calculate the aspect ratio based on bytes
* 0x15 and 0x16 from the EDID.
* @hor_landscape - byte 0x15 from the EDID.
* @vert_portrait - byte 0x16 from the EDID.
*
* Determines the aspect ratio from the EDID.
* See VESA Enhanced EDID standard, release A, rev 2, section 3.6.2:
* "Horizontal and Vertical Screen Size or Aspect Ratio"
*/
struct v4l2_fract v4l2_calc_aspect_ratio(u8 hor_landscape, u8 vert_portrait)
{
struct v4l2_fract aspect = { 16, 9 };
u32 tmp;
u8 ratio;
/* Nothing filled in, fallback to 16:9 */
if (!hor_landscape && !vert_portrait)
return aspect;
/* Both filled in, so they are interpreted as the screen size in cm */
if (hor_landscape && vert_portrait) {
aspect.numerator = hor_landscape;
aspect.denominator = vert_portrait;
return aspect;
}
/* Only one is filled in, so interpret them as a ratio:
(val + 99) / 100 */
ratio = hor_landscape | vert_portrait;
/* Change some rounded values into the exact aspect ratio */
if (ratio == 79) {
aspect.numerator = 16;
aspect.denominator = 9;
} else if (ratio == 34) {
aspect.numerator = 4;
aspect.numerator = 3;
} else if (ratio == 68) {
aspect.numerator = 15;
aspect.numerator = 9;
} else {
aspect.numerator = hor_landscape + 99;
aspect.denominator = 100;
}
if (hor_landscape)
return aspect;
/* The aspect ratio is for portrait, so swap numerator and denominator */
tmp = aspect.denominator;
aspect.denominator = aspect.numerator;
aspect.numerator = tmp;
return aspect;
}
EXPORT_SYMBOL_GPL(v4l2_calc_aspect_ratio);
const struct v4l2_frmsize_discrete *v4l2_find_nearest_format(
const struct v4l2_discrete_probe *probe,
s32 width, s32 height)
{
int i;
u32 error, min_error = UINT_MAX;
const struct v4l2_frmsize_discrete *size, *best = NULL;
if (!probe)
return best;
for (i = 0, size = probe->sizes; i < probe->num_sizes; i++, size++) {
error = abs(size->width - width) + abs(size->height - height);
if (error < min_error) {
min_error = error;
best = size;
}
if (!error)
break;
}
return best;
}
EXPORT_SYMBOL_GPL(v4l2_find_nearest_format);
| ystk/linux-poky-debian | drivers/media/v4l2-core/v4l2-common.c | C | gpl-2.0 | 30,460 |
<?php
// Heading
$_['heading_title'] = 'Return Status';
// Text
$_['text_success'] = 'Success: You have modified return statuses!';
// Column
$_['column_name'] = 'Return Status Name';
$_['column_action'] = 'Action';
// Entry
$_['entry_name'] = 'Return Status Name:';
// Error
$_['error_permission'] = 'Warning: You do not have permission to modify return statues!';
$_['error_name'] = 'Return Status Name must be between 3 and 32 characters!';
$_['error_default'] = 'Warning: This return status cannot be deleted as it is currently assigned as the default return status!';
$_['error_return'] = 'Warning: This return status cannot be deleted as it is currently assigned to %s returns!';
?> | BROcart/2.7.8 | www/admin/language/english/localisation/return_status.php | PHP | gpl-3.0 | 726 |
"""Local settings and globals."""
import sys
from os.path import normpath, join
from .base import *
# Import secrets -- not needed
#sys.path.append(
# abspath(join(PROJECT_ROOT, '../secrets/TimelineJS/stg'))
#)
#from secrets import *
# Set static URL
STATIC_URL = '/static' | deenjohn/TimelineJS | website/core/settings/loc.py | Python | mpl-2.0 | 279 |
// @(#)root/matrix:$Id$
// Authors: Fons Rademakers, Eddy Offermann Nov 2003
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_TMatrixFBase
#define ROOT_TMatrixFBase
//////////////////////////////////////////////////////////////////////////
// //
// TMatrixFBase //
// //
// Instantation of TMatrixTBase<Float_t> //
// //
//////////////////////////////////////////////////////////////////////////
#ifndef ROOT_TMatrixTBase
#include "TMatrixTBase.h"
#endif
#ifndef ROOT_TMatrixFBase
#include "TMatrixFBase.h"
#endif
#endif
| smuzaffar/root | math/matrix/inc/TMatrixFBase.h | C | lgpl-2.1 | 1,312 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you 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.
*/
package org.elasticsearch.action;
import com.google.common.collect.Lists;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.action.search.SearchPhaseExecutionException;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.search.ShardSearchFailure;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.test.ElasticsearchIntegrationTest;
import org.elasticsearch.test.ElasticsearchIntegrationTest.ClusterScope;
import org.junit.Test;
import java.util.Locale;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import static org.hamcrest.Matchers.equalTo;
/**
*/
@ClusterScope(scope = ElasticsearchIntegrationTest.Scope.SUITE, numDataNodes = 2)
public class RejectionActionTests extends ElasticsearchIntegrationTest {
@Override
protected Settings nodeSettings(int nodeOrdinal) {
return ImmutableSettings.builder()
.put(super.nodeSettings(nodeOrdinal))
.put("threadpool.search.size", 1)
.put("threadpool.search.queue_size", 1)
.put("threadpool.index.size", 1)
.put("threadpool.index.queue_size", 1)
.put("threadpool.get.size", 1)
.put("threadpool.get.queue_size", 1)
.build();
}
@Test
public void simulateSearchRejectionLoad() throws Throwable {
for (int i = 0; i < 10; i++) {
client().prepareIndex("test", "type", Integer.toString(i)).setSource("field", "1").get();
}
int numberOfAsyncOps = randomIntBetween(200, 700);
final CountDownLatch latch = new CountDownLatch(numberOfAsyncOps);
final CopyOnWriteArrayList<Object> responses = Lists.newCopyOnWriteArrayList();
for (int i = 0; i < numberOfAsyncOps; i++) {
client().prepareSearch("test")
.setSearchType(SearchType.QUERY_THEN_FETCH)
.setQuery(QueryBuilders.matchQuery("field", "1"))
.execute(new ActionListener<SearchResponse>() {
@Override
public void onResponse(SearchResponse searchResponse) {
responses.add(searchResponse);
latch.countDown();
}
@Override
public void onFailure(Throwable e) {
responses.add(e);
latch.countDown();
}
});
}
latch.await();
assertThat(responses.size(), equalTo(numberOfAsyncOps));
// validate all responses
for (Object response : responses) {
if (response instanceof SearchResponse) {
SearchResponse searchResponse = (SearchResponse) response;
for (ShardSearchFailure failure : searchResponse.getShardFailures()) {
assertTrue("got unexpected reason..." + failure.reason(), failure.reason().toLowerCase(Locale.ENGLISH).contains("rejected"));
}
} else {
Throwable t = (Throwable) response;
Throwable unwrap = ExceptionsHelper.unwrapCause(t);
if (unwrap instanceof SearchPhaseExecutionException) {
SearchPhaseExecutionException e = (SearchPhaseExecutionException) unwrap;
for (ShardSearchFailure failure : e.shardFailures()) {
assertTrue("got unexpected reason..." + failure.reason(), failure.reason().toLowerCase(Locale.ENGLISH).contains("rejected"));
}
} else if ((unwrap instanceof EsRejectedExecutionException) == false) {
throw new AssertionError("unexpected failure", (Throwable) response);
}
}
}
}
}
| dantuffery/elasticsearch | src/test/java/org/elasticsearch/action/RejectionActionTests.java | Java | apache-2.0 | 4,951 |
import _ = require("../index");
// tslint:disable-next-line:strict-export-declare-modifiers
type GlobalPartial<T> = Partial<T>;
declare module "../index" {
type PartialObject<T> = GlobalPartial<T>;
type Many<T> = T | ReadonlyArray<T>;
interface LoDashStatic {
/**
* Creates a lodash object which wraps value to enable implicit method chain sequences.
* Methods that operate on and return arrays, collections, and functions can be chained together.
* Methods that retrieve a single value or may return a primitive value will automatically end the
* chain sequence and return the unwrapped value. Otherwise, the value must be unwrapped with value().
*
* Explicit chain sequences, which must be unwrapped with value(), may be enabled using _.chain.
*
* The execution of chained methods is lazy, that is, it's deferred until value() is
* implicitly or explicitly called.
*
* Lazy evaluation allows several methods to support shortcut fusion. Shortcut fusion
* is an optimization to merge iteratee calls; this avoids the creation of intermediate
* arrays and can greatly reduce the number of iteratee executions. Sections of a chain
* sequence qualify for shortcut fusion if the section is applied to an array and iteratees
* accept only one argument. The heuristic for whether a section qualifies for shortcut
* fusion is subject to change.
*
* Chaining is supported in custom builds as long as the value() method is directly or
* indirectly included in the build.
*
* In addition to lodash methods, wrappers have Array and String methods.
* The wrapper Array methods are:
* concat, join, pop, push, shift, sort, splice, and unshift.
* The wrapper String methods are:
* replace and split.
*
* The wrapper methods that support shortcut fusion are:
* at, compact, drop, dropRight, dropWhile, filter, find, findLast, head, initial, last,
* map, reject, reverse, slice, tail, take, takeRight, takeRightWhile, takeWhile, and toArray
*
* The chainable wrapper methods are:
* after, ary, assign, assignIn, assignInWith, assignWith, at, before, bind, bindAll, bindKey,
* castArray, chain, chunk, commit, compact, concat, conforms, constant, countBy, create,
* curry, debounce, defaults, defaultsDeep, defer, delay, difference, differenceBy, differenceWith,
* drop, dropRight, dropRightWhile, dropWhile, extend, extendWith, fill, filter, flatMap,
* flatMapDeep, flatMapDepth, flatten, flattenDeep, flattenDepth, flip, flow, flowRight,
* fromPairs, functions, functionsIn, groupBy, initial, intersection, intersectionBy, intersectionWith,
* invert, invertBy, invokeMap, iteratee, keyBy, keys, keysIn, map, mapKeys, mapValues,
* matches, matchesProperty, memoize, merge, mergeWith, method, methodOf, mixin, negate,
* nthArg, omit, omitBy, once, orderBy, over, overArgs, overEvery, overSome, partial, partialRight,
* partition, pick, pickBy, plant, property, propertyOf, pull, pullAll, pullAllBy, pullAllWith, pullAt,
* push, range, rangeRight, rearg, reject, remove, rest, reverse, sampleSize, set, setWith,
* shuffle, slice, sort, sortBy, sortedUniq, sortedUniqBy, splice, spread, tail, take,
* takeRight, takeRightWhile, takeWhile, tap, throttle, thru, toArray, toPairs, toPairsIn,
* toPath, toPlainObject, transform, unary, union, unionBy, unionWith, uniq, uniqBy, uniqWith,
* unset, unshift, unzip, unzipWith, update, updateWith, values, valuesIn, without, wrap,
* xor, xorBy, xorWith, zip, zipObject, zipObjectDeep, and zipWith.
*
* The wrapper methods that are not chainable by default are:
* add, attempt, camelCase, capitalize, ceil, clamp, clone, cloneDeep, cloneDeepWith, cloneWith,
* conformsTo, deburr, defaultTo, divide, each, eachRight, endsWith, eq, escape, escapeRegExp,
* every, find, findIndex, findKey, findLast, findLastIndex, findLastKey, first, floor, forEach,
* forEachRight, forIn, forInRight, forOwn, forOwnRight, get, gt, gte, has, hasIn, head,
* identity, includes, indexOf, inRange, invoke, isArguments, isArray, isArrayBuffer,
* isArrayLike, isArrayLikeObject, isBoolean, isBuffer, isDate, isElement, isEmpty, isEqual, isEqualWith,
* isError, isFinite, isFunction, isInteger, isLength, isMap, isMatch, isMatchWith, isNaN,
* isNative, isNil, isNull, isNumber, isObject, isObjectLike, isPlainObject, isRegExp,
* isSafeInteger, isSet, isString, isUndefined, isTypedArray, isWeakMap, isWeakSet, join,
* kebabCase, last, lastIndexOf, lowerCase, lowerFirst, lt, lte, max, maxBy, mean, meanBy,
* min, minBy, multiply, noConflict, noop, now, nth, pad, padEnd, padStart, parseInt, pop,
* random, reduce, reduceRight, repeat, result, round, runInContext, sample, shift, size,
* snakeCase, some, sortedIndex, sortedIndexBy, sortedLastIndex, sortedLastIndexBy, startCase,
* startsWith, stubArray, stubFalse, stubObject, stubString, stubTrue, subtract, sum, sumBy,
* template, times, toFinite, toInteger, toJSON, toLength, toLower, toNumber, toSafeInteger,
* toString, toUpper, trim, trimEnd, trimStart, truncate, unescape, uniqueId, upperCase,
* upperFirst, value, and words.
**/
<T>(value: T): LoDashImplicitWrapper<T>;
/**
* The semantic version number.
**/
VERSION: string;
/**
* By default, the template delimiters used by Lo-Dash are similar to those in embedded Ruby
* (ERB). Change the following template settings to use alternative delimiters.
**/
templateSettings: TemplateSettings;
}
/**
* By default, the template delimiters used by Lo-Dash are similar to those in embedded Ruby
* (ERB). Change the following template settings to use alternative delimiters.
**/
interface TemplateSettings {
/**
* The "escape" delimiter.
**/
escape?: RegExp;
/**
* The "evaluate" delimiter.
**/
evaluate?: RegExp;
/**
* An object to import into the template as local variables.
**/
imports?: Dictionary<any>;
/**
* The "interpolate" delimiter.
**/
interpolate?: RegExp;
/**
* Used to reference the data object in the template text.
**/
variable?: string;
}
/**
* Creates a cache object to store key/value pairs.
*/
interface MapCache {
/**
* Removes `key` and its value from the cache.
* @param key The key of the value to remove.
* @return Returns `true` if the entry was removed successfully, else `false`.
*/
delete(key: any): boolean;
/**
* Gets the cached value for `key`.
* @param key The key of the value to get.
* @return Returns the cached value.
*/
get(key: any): any;
/**
* Checks if a cached value for `key` exists.
* @param key The key of the entry to check.
* @return Returns `true` if an entry for `key` exists, else `false`.
*/
has(key: any): boolean;
/**
* Sets `value` to `key` of the cache.
* @param key The key of the value to cache.
* @param value The value to cache.
* @return Returns the cache object.
*/
set(key: any, value: any): this;
/**
* Removes all key-value entries from the map.
*/
clear?: () => void;
}
interface MapCacheConstructor {
new (): MapCache;
}
interface LoDashImplicitWrapper<TValue> extends LoDashWrapper<TValue> {
pop<T>(this: LoDashImplicitWrapper<List<T> | null | undefined>): T | undefined;
push<T>(this: LoDashImplicitWrapper<List<T> | null | undefined>, ...items: T[]): this;
shift<T>(this: LoDashImplicitWrapper<List<T> | null | undefined>): T | undefined;
sort<T>(this: LoDashImplicitWrapper<List<T> | null | undefined>, compareFn?: (a: T, b: T) => number): this;
splice<T>(this: LoDashImplicitWrapper<List<T> | null | undefined>, start: number, deleteCount?: number, ...items: T[]): this;
unshift<T>(this: LoDashImplicitWrapper<List<T> | null | undefined>, ...items: T[]): this;
}
interface LoDashExplicitWrapper<TValue> extends LoDashWrapper<TValue> {
pop<T>(this: LoDashExplicitWrapper<List<T> | null | undefined>): LoDashExplicitWrapper<T | undefined>;
push<T>(this: LoDashExplicitWrapper<List<T> | null | undefined>, ...items: T[]): this;
shift<T>(this: LoDashExplicitWrapper<List<T> | null | undefined>): LoDashExplicitWrapper<T | undefined>;
sort<T>(this: LoDashExplicitWrapper<List<T> | null | undefined>, compareFn?: (a: T, b: T) => number): this;
splice<T>(this: LoDashExplicitWrapper<List<T> | null | undefined>, start: number, deleteCount?: number, ...items: T[]): this;
unshift<T>(this: LoDashExplicitWrapper<List<T> | null | undefined>, ...items: T[]): this;
}
type NotVoid = {} | null | undefined;
type IterateeShorthand<T> = PropertyName | [PropertyName, any] | PartialDeep<T>;
type ArrayIterator<T, TResult> = (value: T, index: number, collection: T[]) => TResult;
type ListIterator<T, TResult> = (value: T, index: number, collection: List<T>) => TResult;
type ListIteratee<T> = ListIterator<T, NotVoid> | IterateeShorthand<T>;
type ListIterateeCustom<T, TResult> = ListIterator<T, TResult> | IterateeShorthand<T>;
type ListIteratorTypeGuard<T, S extends T> = (value: T, index: number, collection: List<T>) => value is S;
// Note: key should be string, not keyof T, because the actual object may contain extra properties that were not specified in the type.
type ObjectIterator<TObject, TResult> = (value: TObject[keyof TObject], key: string, collection: TObject) => TResult;
type ObjectIteratee<TObject> = ObjectIterator<TObject, NotVoid> | IterateeShorthand<TObject[keyof TObject]>;
type ObjectIterateeCustom<TObject, TResult> = ObjectIterator<TObject, TResult> | IterateeShorthand<TObject[keyof TObject]>;
type ObjectIteratorTypeGuard<TObject, S extends TObject[keyof TObject]> = (value: TObject[keyof TObject], key: string, collection: TObject) => value is S;
type StringIterator<TResult> = (char: string, index: number, string: string) => TResult;
/** @deprecated Use MemoVoidArrayIterator or MemoVoidDictionaryIterator instead. */
type MemoVoidIterator<T, TResult> = (prev: TResult, curr: T, indexOrKey: any, list: T[]) => void;
/** @deprecated Use MemoListIterator or MemoObjectIterator instead. */
type MemoIterator<T, TResult> = (prev: TResult, curr: T, indexOrKey: any, list: T[]) => TResult;
type MemoListIterator<T, TResult, TList> = (prev: TResult, curr: T, index: number, list: TList) => TResult;
type MemoObjectIterator<T, TResult, TList> = (prev: TResult, curr: T, key: string, list: TList) => TResult;
type MemoIteratorCapped<T, TResult> = (prev: TResult, curr: T) => TResult;
type MemoIteratorCappedRight<T, TResult> = (curr: T, prev: TResult) => TResult;
type MemoVoidArrayIterator<T, TResult> = (acc: TResult, curr: T, index: number, arr: T[]) => void;
type MemoVoidDictionaryIterator<T, TResult> = (acc: TResult, curr: T, key: string, dict: Dictionary<T>) => void;
type MemoVoidIteratorCapped<T, TResult> = (acc: TResult, curr: T) => void;
type ValueIteratee<T> = ((value: T) => NotVoid) | IterateeShorthand<T>;
type ValueIterateeCustom<T, TResult> = ((value: T) => TResult) | IterateeShorthand<T>;
type ValueIteratorTypeGuard<T, S extends T> = (value: T) => value is S;
type ValueKeyIteratee<T> = ((value: T, key: string) => NotVoid) | IterateeShorthand<T>;
type ValueKeyIterateeTypeGuard<T, S extends T> = (value: T, key: string) => value is S;
type Comparator<T> = (a: T, b: T) => boolean;
type Comparator2<T1, T2> = (a: T1, b: T2) => boolean;
type PropertyName = string | number | symbol;
type PropertyPath = Many<PropertyName>;
type Omit<T, K extends keyof T> = Pick<T, ({ [P in keyof T]: P } & { [P in K]: never } & { [x: string]: never })[keyof T]>;
/** Common interface between Arrays and jQuery objects */
type List<T> = ArrayLike<T>;
interface Dictionary<T> {
[index: string]: T;
}
interface NumericDictionary<T> {
[index: number]: T;
}
// Crazy typedef needed get _.omit to work properly with Dictionary and NumericDictionary
type AnyKindOfDictionary =
| Dictionary<{} | null | undefined>
| NumericDictionary<{} | null | undefined>;
interface Cancelable {
cancel(): void;
flush(): void;
}
type PartialDeep<T> = {
[P in keyof T]?: PartialDeep<T[P]>;
};
// For backwards compatibility
type LoDashImplicitArrayWrapper<T> = LoDashImplicitWrapper<T[]>;
type LoDashImplicitNillableArrayWrapper<T> = LoDashImplicitWrapper<T[] | null | undefined>;
type LoDashImplicitObjectWrapper<T> = LoDashImplicitWrapper<T>;
type LoDashImplicitNillableObjectWrapper<T> = LoDashImplicitWrapper<T | null | undefined>;
type LoDashImplicitNumberArrayWrapper = LoDashImplicitWrapper<number[]>;
type LoDashImplicitStringWrapper = LoDashImplicitWrapper<string>;
type LoDashExplicitArrayWrapper<T> = LoDashExplicitWrapper<T[]>;
type LoDashExplicitNillableArrayWrapper<T> = LoDashExplicitWrapper<T[] | null | undefined>;
type LoDashExplicitObjectWrapper<T> = LoDashExplicitWrapper<T>;
type LoDashExplicitNillableObjectWrapper<T> = LoDashExplicitWrapper<T | null | undefined>;
type LoDashExplicitNumberArrayWrapper = LoDashExplicitWrapper<number[]>;
type LoDashExplicitStringWrapper = LoDashExplicitWrapper<string>;
type DictionaryIterator<T, TResult> = ObjectIterator<Dictionary<T>, TResult>;
type DictionaryIteratee<T> = ObjectIteratee<Dictionary<T>>;
type DictionaryIteratorTypeGuard<T, S extends T> = ObjectIteratorTypeGuard<Dictionary<T>, S>;
// NOTE: keys of objects at run time are always strings, even when a NumericDictionary is being iterated.
type NumericDictionaryIterator<T, TResult> = (value: T, key: string, collection: NumericDictionary<T>) => TResult;
type NumericDictionaryIteratee<T> = NumericDictionaryIterator<T, NotVoid> | IterateeShorthand<T>;
type NumericDictionaryIterateeCustom<T, TResult> = NumericDictionaryIterator<T, TResult> | IterateeShorthand<T>;
}
| BigBoss424/portfolio | v8/development/node_modules/@types/lodash/common/common.d.ts | TypeScript | apache-2.0 | 14,825 |
{% extends 'airflow/master.html' %}
{% block body %}
<div>
<h3 style="float: left">
{% block page_header %}Hive Metastore Browser{% endblock%}
</h3>
<div id="object" class="select2-drop-mask" style="margin-top: 25px; width: 400px;float: right"></div>
<div style="clear: both"></div>
</div>
{% block plugin_content %}{% endblock %}
{% endblock %}
{% block head %}
{{ super() }}
<link rel="stylesheet" type="text/css" href="{{ url_for("static", filename="dataTables.bootstrap.css") }}">
<link href="/admin/static/vendor/select2/select2.css" rel="stylesheet">
{% endblock %}
{% block tail %}
{{ super() }}
<script src="{{ url_for('static', filename='jquery.dataTables.min.js') }}"></script>
<script src="{{ url_for('static', filename='dataTables.bootstrap.js') }}"></script>
<script src="/admin/static/vendor/select2/select2.min.js" type="text/javascript"></script>
<script>
// Filling up the table selector
url = "{{ url_for('.objects') }}";
$.get(url, function( data ) {
$("#object").select2({
data: data,
placeholder: "Table Selector",
})
.on("change", function(e){
window.location = "{{ url_for('.table') }}?table=" + e.val;
});
}, "json");
</script>
{% endblock %}
| mtustin-handy/airflow | airflow/contrib/plugins/metastore_browser/templates/metastore_browser/base.html | HTML | apache-2.0 | 1,279 |
/* crypto/evp/evp_enc.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* 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 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.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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 AUTHOR 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.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#ifndef OPENSSL_NO_ENGINE
#include <openssl/engine.h>
#endif
#ifdef OPENSSL_FIPS
#include <openssl/fips.h>
#endif
#include "evp_locl.h"
#ifdef OPENSSL_FIPS
#define M_do_cipher(ctx, out, in, inl) FIPS_cipher(ctx, out, in, inl)
#else
#define M_do_cipher(ctx, out, in, inl) ctx->cipher->do_cipher(ctx, out, in, inl)
#endif
const char EVP_version[]="EVP" OPENSSL_VERSION_PTEXT;
void EVP_CIPHER_CTX_init(EVP_CIPHER_CTX *ctx)
{
memset(ctx,0,sizeof(EVP_CIPHER_CTX));
/* ctx->cipher=NULL; */
}
EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void)
{
EVP_CIPHER_CTX *ctx=OPENSSL_malloc(sizeof *ctx);
if (ctx)
EVP_CIPHER_CTX_init(ctx);
return ctx;
}
int EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
const unsigned char *key, const unsigned char *iv, int enc)
{
if (cipher)
EVP_CIPHER_CTX_init(ctx);
return EVP_CipherInit_ex(ctx,cipher,NULL,key,iv,enc);
}
int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, ENGINE *impl,
const unsigned char *key, const unsigned char *iv, int enc)
{
if (enc == -1)
enc = ctx->encrypt;
else
{
if (enc)
enc = 1;
ctx->encrypt = enc;
}
#ifndef OPENSSL_NO_ENGINE
/* Whether it's nice or not, "Inits" can be used on "Final"'d contexts
* so this context may already have an ENGINE! Try to avoid releasing
* the previous handle, re-querying for an ENGINE, and having a
* reinitialisation, when it may all be unecessary. */
if (ctx->engine && ctx->cipher && (!cipher ||
(cipher && (cipher->nid == ctx->cipher->nid))))
goto skip_to_init;
#endif
if (cipher)
{
/* Ensure a context left lying around from last time is cleared
* (the previous check attempted to avoid this if the same
* ENGINE and EVP_CIPHER could be used). */
if (ctx->cipher)
{
unsigned long flags = ctx->flags;
EVP_CIPHER_CTX_cleanup(ctx);
/* Restore encrypt and flags */
ctx->encrypt = enc;
ctx->flags = flags;
}
#ifndef OPENSSL_NO_ENGINE
if(impl)
{
if (!ENGINE_init(impl))
{
EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
return 0;
}
}
else
/* Ask if an ENGINE is reserved for this job */
impl = ENGINE_get_cipher_engine(cipher->nid);
if(impl)
{
/* There's an ENGINE for this job ... (apparently) */
const EVP_CIPHER *c = ENGINE_get_cipher(impl, cipher->nid);
if(!c)
{
/* One positive side-effect of US's export
* control history, is that we should at least
* be able to avoid using US mispellings of
* "initialisation"? */
EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
return 0;
}
/* We'll use the ENGINE's private cipher definition */
cipher = c;
/* Store the ENGINE functional reference so we know
* 'cipher' came from an ENGINE and we need to release
* it when done. */
ctx->engine = impl;
}
else
ctx->engine = NULL;
#endif
#ifdef OPENSSL_FIPS
return FIPS_cipherinit(ctx, cipher, key, iv, enc);
#else
ctx->cipher=cipher;
if (ctx->cipher->ctx_size)
{
ctx->cipher_data=OPENSSL_malloc(ctx->cipher->ctx_size);
if (!ctx->cipher_data)
{
EVPerr(EVP_F_EVP_CIPHERINIT_EX, ERR_R_MALLOC_FAILURE);
return 0;
}
}
else
{
ctx->cipher_data = NULL;
}
ctx->key_len = cipher->key_len;
ctx->flags = 0;
if(ctx->cipher->flags & EVP_CIPH_CTRL_INIT)
{
if(!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_INIT, 0, NULL))
{
EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
return 0;
}
}
#endif
}
else if(!ctx->cipher)
{
EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_NO_CIPHER_SET);
return 0;
}
#ifndef OPENSSL_NO_ENGINE
skip_to_init:
#endif
#ifdef OPENSSL_FIPS
return FIPS_cipherinit(ctx, cipher, key, iv, enc);
#else
/* we assume block size is a power of 2 in *cryptUpdate */
OPENSSL_assert(ctx->cipher->block_size == 1
|| ctx->cipher->block_size == 8
|| ctx->cipher->block_size == 16);
if(!(EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_CUSTOM_IV)) {
switch(EVP_CIPHER_CTX_mode(ctx)) {
case EVP_CIPH_STREAM_CIPHER:
case EVP_CIPH_ECB_MODE:
break;
case EVP_CIPH_CFB_MODE:
case EVP_CIPH_OFB_MODE:
ctx->num = 0;
/* fall-through */
case EVP_CIPH_CBC_MODE:
OPENSSL_assert(EVP_CIPHER_CTX_iv_length(ctx) <=
(int)sizeof(ctx->iv));
if(iv) memcpy(ctx->oiv, iv, EVP_CIPHER_CTX_iv_length(ctx));
memcpy(ctx->iv, ctx->oiv, EVP_CIPHER_CTX_iv_length(ctx));
break;
case EVP_CIPH_CTR_MODE:
ctx->num = 0;
/* Don't reuse IV for CTR mode */
if(iv)
memcpy(ctx->iv, iv, EVP_CIPHER_CTX_iv_length(ctx));
break;
default:
return 0;
break;
}
}
if(key || (ctx->cipher->flags & EVP_CIPH_ALWAYS_CALL_INIT)) {
if(!ctx->cipher->init(ctx,key,iv,enc)) return 0;
}
ctx->buf_len=0;
ctx->final_used=0;
ctx->block_mask=ctx->cipher->block_size-1;
return 1;
#endif
}
int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
const unsigned char *in, int inl)
{
if (ctx->encrypt)
return EVP_EncryptUpdate(ctx,out,outl,in,inl);
else return EVP_DecryptUpdate(ctx,out,outl,in,inl);
}
int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
{
if (ctx->encrypt)
return EVP_EncryptFinal_ex(ctx,out,outl);
else return EVP_DecryptFinal_ex(ctx,out,outl);
}
int EVP_CipherFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
{
if (ctx->encrypt)
return EVP_EncryptFinal(ctx,out,outl);
else return EVP_DecryptFinal(ctx,out,outl);
}
int EVP_EncryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
const unsigned char *key, const unsigned char *iv)
{
return EVP_CipherInit(ctx, cipher, key, iv, 1);
}
int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx,const EVP_CIPHER *cipher, ENGINE *impl,
const unsigned char *key, const unsigned char *iv)
{
return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 1);
}
int EVP_DecryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
const unsigned char *key, const unsigned char *iv)
{
return EVP_CipherInit(ctx, cipher, key, iv, 0);
}
int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, ENGINE *impl,
const unsigned char *key, const unsigned char *iv)
{
return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 0);
}
int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
const unsigned char *in, int inl)
{
int i,j,bl;
if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER)
{
i = M_do_cipher(ctx, out, in, inl);
if (i < 0)
return 0;
else
*outl = i;
return 1;
}
if (inl <= 0)
{
*outl = 0;
return inl == 0;
}
if(ctx->buf_len == 0 && (inl&(ctx->block_mask)) == 0)
{
if(M_do_cipher(ctx,out,in,inl))
{
*outl=inl;
return 1;
}
else
{
*outl=0;
return 0;
}
}
i=ctx->buf_len;
bl=ctx->cipher->block_size;
OPENSSL_assert(bl <= (int)sizeof(ctx->buf));
if (i != 0)
{
if (i+inl < bl)
{
memcpy(&(ctx->buf[i]),in,inl);
ctx->buf_len+=inl;
*outl=0;
return 1;
}
else
{
j=bl-i;
memcpy(&(ctx->buf[i]),in,j);
if(!M_do_cipher(ctx,out,ctx->buf,bl)) return 0;
inl-=j;
in+=j;
out+=bl;
*outl=bl;
}
}
else
*outl = 0;
i=inl&(bl-1);
inl-=i;
if (inl > 0)
{
if(!M_do_cipher(ctx,out,in,inl)) return 0;
*outl+=inl;
}
if (i != 0)
memcpy(ctx->buf,&(in[inl]),i);
ctx->buf_len=i;
return 1;
}
int EVP_EncryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
{
int ret;
ret = EVP_EncryptFinal_ex(ctx, out, outl);
return ret;
}
int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
{
int n,ret;
unsigned int i, b, bl;
if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER)
{
ret = M_do_cipher(ctx, out, NULL, 0);
if (ret < 0)
return 0;
else
*outl = ret;
return 1;
}
b=ctx->cipher->block_size;
OPENSSL_assert(b <= sizeof ctx->buf);
if (b == 1)
{
*outl=0;
return 1;
}
bl=ctx->buf_len;
if (ctx->flags & EVP_CIPH_NO_PADDING)
{
if(bl)
{
EVPerr(EVP_F_EVP_ENCRYPTFINAL_EX,EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
return 0;
}
*outl = 0;
return 1;
}
n=b-bl;
for (i=bl; i<b; i++)
ctx->buf[i]=n;
ret=M_do_cipher(ctx,out,ctx->buf,b);
if(ret)
*outl=b;
return ret;
}
int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
const unsigned char *in, int inl)
{
int fix_len;
unsigned int b;
if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER)
{
fix_len = M_do_cipher(ctx, out, in, inl);
if (fix_len < 0)
{
*outl = 0;
return 0;
}
else
*outl = fix_len;
return 1;
}
if (inl <= 0)
{
*outl = 0;
return inl == 0;
}
if (ctx->flags & EVP_CIPH_NO_PADDING)
return EVP_EncryptUpdate(ctx, out, outl, in, inl);
b=ctx->cipher->block_size;
OPENSSL_assert(b <= sizeof ctx->final);
if(ctx->final_used)
{
memcpy(out,ctx->final,b);
out+=b;
fix_len = 1;
}
else
fix_len = 0;
if(!EVP_EncryptUpdate(ctx,out,outl,in,inl))
return 0;
/* if we have 'decrypted' a multiple of block size, make sure
* we have a copy of this last block */
if (b > 1 && !ctx->buf_len)
{
*outl-=b;
ctx->final_used=1;
memcpy(ctx->final,&out[*outl],b);
}
else
ctx->final_used = 0;
if (fix_len)
*outl += b;
return 1;
}
int EVP_DecryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
{
int ret;
ret = EVP_DecryptFinal_ex(ctx, out, outl);
return ret;
}
int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
{
int i,n;
unsigned int b;
*outl=0;
if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER)
{
i = M_do_cipher(ctx, out, NULL, 0);
if (i < 0)
return 0;
else
*outl = i;
return 1;
}
b=ctx->cipher->block_size;
if (ctx->flags & EVP_CIPH_NO_PADDING)
{
if(ctx->buf_len)
{
EVPerr(EVP_F_EVP_DECRYPTFINAL_EX,EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
return 0;
}
*outl = 0;
return 1;
}
if (b > 1)
{
if (ctx->buf_len || !ctx->final_used)
{
EVPerr(EVP_F_EVP_DECRYPTFINAL_EX,EVP_R_WRONG_FINAL_BLOCK_LENGTH);
return(0);
}
OPENSSL_assert(b <= sizeof ctx->final);
n=ctx->final[b-1];
if (n == 0 || n > (int)b)
{
EVPerr(EVP_F_EVP_DECRYPTFINAL_EX,EVP_R_BAD_DECRYPT);
return(0);
}
for (i=0; i<n; i++)
{
if (ctx->final[--b] != n)
{
EVPerr(EVP_F_EVP_DECRYPTFINAL_EX,EVP_R_BAD_DECRYPT);
return(0);
}
}
n=ctx->cipher->block_size-n;
for (i=0; i<n; i++)
out[i]=ctx->final[i];
*outl=n;
}
else
*outl=0;
return(1);
}
void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *ctx)
{
if (ctx)
{
EVP_CIPHER_CTX_cleanup(ctx);
OPENSSL_free(ctx);
}
}
int EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *c)
{
#ifndef OPENSSL_FIPS
if (c->cipher != NULL)
{
if(c->cipher->cleanup && !c->cipher->cleanup(c))
return 0;
/* Cleanse cipher context data */
if (c->cipher_data)
OPENSSL_cleanse(c->cipher_data, c->cipher->ctx_size);
}
if (c->cipher_data)
OPENSSL_free(c->cipher_data);
#endif
#ifndef OPENSSL_NO_ENGINE
if (c->engine)
/* The EVP_CIPHER we used belongs to an ENGINE, release the
* functional reference we held for this reason. */
ENGINE_finish(c->engine);
#endif
#ifdef OPENSSL_FIPS
FIPS_cipher_ctx_cleanup(c);
#endif
memset(c,0,sizeof(EVP_CIPHER_CTX));
return 1;
}
int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *c, int keylen)
{
if(c->cipher->flags & EVP_CIPH_CUSTOM_KEY_LENGTH)
return EVP_CIPHER_CTX_ctrl(c, EVP_CTRL_SET_KEY_LENGTH, keylen, NULL);
if(c->key_len == keylen) return 1;
if((keylen > 0) && (c->cipher->flags & EVP_CIPH_VARIABLE_LENGTH))
{
c->key_len = keylen;
return 1;
}
EVPerr(EVP_F_EVP_CIPHER_CTX_SET_KEY_LENGTH,EVP_R_INVALID_KEY_LENGTH);
return 0;
}
int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *ctx, int pad)
{
if (pad) ctx->flags &= ~EVP_CIPH_NO_PADDING;
else ctx->flags |= EVP_CIPH_NO_PADDING;
return 1;
}
int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr)
{
int ret;
if(!ctx->cipher) {
EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_NO_CIPHER_SET);
return 0;
}
if(!ctx->cipher->ctrl) {
EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_CTRL_NOT_IMPLEMENTED);
return 0;
}
ret = ctx->cipher->ctrl(ctx, type, arg, ptr);
if(ret == -1) {
EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_CTRL_OPERATION_NOT_IMPLEMENTED);
return 0;
}
return ret;
}
int EVP_CIPHER_CTX_rand_key(EVP_CIPHER_CTX *ctx, unsigned char *key)
{
if (ctx->cipher->flags & EVP_CIPH_RAND_KEY)
return EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_RAND_KEY, 0, key);
if (RAND_bytes(key, ctx->key_len) <= 0)
return 0;
return 1;
}
int EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX *out, const EVP_CIPHER_CTX *in)
{
if ((in == NULL) || (in->cipher == NULL))
{
EVPerr(EVP_F_EVP_CIPHER_CTX_COPY,EVP_R_INPUT_NOT_INITIALIZED);
return 0;
}
#ifndef OPENSSL_NO_ENGINE
/* Make sure it's safe to copy a cipher context using an ENGINE */
if (in->engine && !ENGINE_init(in->engine))
{
EVPerr(EVP_F_EVP_CIPHER_CTX_COPY,ERR_R_ENGINE_LIB);
return 0;
}
#endif
EVP_CIPHER_CTX_cleanup(out);
memcpy(out,in,sizeof *out);
if (in->cipher_data && in->cipher->ctx_size)
{
out->cipher_data=OPENSSL_malloc(in->cipher->ctx_size);
if (!out->cipher_data)
{
EVPerr(EVP_F_EVP_CIPHER_CTX_COPY,ERR_R_MALLOC_FAILURE);
return 0;
}
memcpy(out->cipher_data,in->cipher_data,in->cipher->ctx_size);
}
if (in->cipher->flags & EVP_CIPH_CUSTOM_COPY)
return in->cipher->ctrl((EVP_CIPHER_CTX *)in, EVP_CTRL_COPY, 0, out);
return 1;
}
| 837468220/python-for-android | python3-alpha/openssl/crypto/evp/evp_enc.c | C | apache-2.0 | 16,714 |
class Orientdb < Formula
desc "Graph database"
homepage "https://orientdb.com"
url "https://orientdb.com/download.php?email=unknown@unknown.com&file=orientdb-community-2.1.6.tar.gz&os=mac"
version "2.1.6"
sha256 "c5aa4791b965812362e8faf50ff03e1970de1c81c707b9d0220cdadf8e61d0c1"
bottle do
cellar :any_skip_relocation
sha256 "6f04b2646e4deae8be36ebc18eead46982b11f53aa2652414946ca221f09e3f8" => :el_capitan
sha256 "c4a54eddf8503b82fd8452d6c502ca647cfe7469d4bf1a54bbfc9422536c3fc2" => :yosemite
sha256 "b83e829bf06ba825b60058f0fd2484b2df3cfbdf7d3c24ed90879e47579c5b1b" => :mavericks
end
# Fixing OrientDB init scripts
patch do
url "https://gist.githubusercontent.com/maggiolo00/84835e0b82a94fe9970a/raw/1ed577806db4411fd8b24cd90e516580218b2d53/orientdbsh"
sha256 "d8b89ecda7cb78c940b3c3a702eee7b5e0f099338bb569b527c63efa55e6487e"
end
def install
rm_rf Dir["{bin,benchmarks}/*.{bat,exe}"]
inreplace %W[bin/orientdb.sh bin/console.sh bin/gremlin.sh],
'"YOUR_ORIENTDB_INSTALLATION_PATH"', libexec
chmod 0755, Dir["bin/*"]
libexec.install Dir["*"]
mkpath "#{libexec}/log"
touch "#{libexec}/log/orientdb.err"
touch "#{libexec}/log/orientdb.log"
bin.install_symlink "#{libexec}/bin/orientdb.sh" => "orientdb"
bin.install_symlink "#{libexec}/bin/console.sh" => "orientdb-console"
bin.install_symlink "#{libexec}/bin/gremlin.sh" => "orientdb-gremlin"
end
def caveats
"Use `orientdb <start | stop | status>`, `orientdb-console` and `orientdb-gremlin`."
end
end
| rokn/Count_Words_2015 | fetched_code/ruby/orientdb.rb | Ruby | mit | 1,560 |
/* Area: ffi_call, closure_call
Purpose: Check structure alignment of uint16.
Limitations: none.
PR: none.
Originator: <hos@tamanegi.org> 20031203 */
/* { dg-do run } */
#include "ffitest.h"
typedef struct cls_struct_align {
unsigned char a;
unsigned short b;
unsigned char c;
} cls_struct_align;
cls_struct_align cls_struct_align_fn(struct cls_struct_align a1,
struct cls_struct_align a2)
{
struct cls_struct_align result;
result.a = a1.a + a2.a;
result.b = a1.b + a2.b;
result.c = a1.c + a2.c;
printf("%d %d %d %d %d %d: %d %d %d\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c, result.a, result.b, result.c);
return result;
}
static void
cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
void* userdata __UNUSED__)
{
struct cls_struct_align a1, a2;
a1 = *(struct cls_struct_align*)(args[0]);
a2 = *(struct cls_struct_align*)(args[1]);
*(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
}
int main (void)
{
ffi_cif cif;
#ifndef USING_MMAP
static ffi_closure cl;
#endif
ffi_closure *pcl;
void* args_dbl[5];
ffi_type* cls_struct_fields[4];
ffi_type cls_struct_type;
ffi_type* dbl_arg_types[5];
#ifdef USING_MMAP
pcl = allocate_mmap (sizeof(ffi_closure));
#else
pcl = &cl;
#endif
cls_struct_type.size = 0;
cls_struct_type.alignment = 0;
cls_struct_type.type = FFI_TYPE_STRUCT;
cls_struct_type.elements = cls_struct_fields;
struct cls_struct_align g_dbl = { 12, 4951, 127 };
struct cls_struct_align f_dbl = { 1, 9320, 13 };
struct cls_struct_align res_dbl;
cls_struct_fields[0] = &ffi_type_uchar;
cls_struct_fields[1] = &ffi_type_ushort;
cls_struct_fields[2] = &ffi_type_uchar;
cls_struct_fields[3] = NULL;
dbl_arg_types[0] = &cls_struct_type;
dbl_arg_types[1] = &cls_struct_type;
dbl_arg_types[2] = NULL;
CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
dbl_arg_types) == FFI_OK);
args_dbl[0] = &g_dbl;
args_dbl[1] = &f_dbl;
args_dbl[2] = NULL;
ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl);
/* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */
printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
/* { dg-output "\nres: 13 14271 140" } */
CHECK(ffi_prep_closure(pcl, &cif, cls_struct_align_gn, NULL) == FFI_OK);
res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(pcl))(g_dbl, f_dbl);
/* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */
printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
/* { dg-output "\nres: 13 14271 140" } */
exit(0);
}
| lshain-android-source/external-libffi | testsuite/libffi.call/cls_align_uint16.c | C | mit | 2,592 |
ext3_mount () {
modprobe -q ext3
mkdir -p $2
mount -t ext3 -onoatime,data=journal,errors=continue $1 $2
}
for arg in $CMDLINE; do
optarg=`expr "x$arg" : 'x[^=]*=\(.*\)'`
echo $arg xxx $optarg
case $arg in
ext3=*)
dev=`expr "$optarg" : '\([^:]*\).*'`
path=`expr "$optarg" : '[^:]*:\([^:]*\).*'`
ext3_mount $dev $path ;;
esac
done
| bticino/openembedded | recipes/initrdscripts/files/80-ext3.sh | Shell | mit | 383 |
require 'fog/openstack/models/model'
module Fog
module Compute
class OpenStack
class Flavor < Fog::OpenStack::Model
identity :id
attribute :name
attribute :ram
attribute :disk
attribute :vcpus
attribute :links
attribute :swap
attribute :rxtx_factor
attribute :metadata
attribute :ephemeral, :aliases => 'OS-FLV-EXT-DATA:ephemeral'
attribute :is_public, :aliases => 'os-flavor-access:is_public'
attribute :disabled, :aliases => 'OS-FLV-DISABLED:disabled'
def save
requires :name, :ram, :vcpus, :disk
attributes[:ephemeral] = self.ephemeral || 0
attributes[:is_public] = self.is_public || false
attributes[:disabled] = self.disabled || false
attributes[:swap] = self.swap || 0
attributes[:rxtx_factor] = self.rxtx_factor || 1.0
merge_attributes(service.create_flavor(self.attributes).body['flavor'])
self
end
def destroy
requires :id
service.delete_flavor(self.id)
true
end
def metadata
service.get_flavor_metadata(self.id).body['extra_specs']
rescue Fog::Compute::OpenStack::NotFound
nil
end
def create_metadata(metadata)
service.create_flavor_metadata(self.id, metadata)
rescue Fog::Compute::OpenStack::NotFound
nil
end
end
end
end
end
| ralzate/Aerosanidad-Correciones | vendor/bundle/ruby/2.2.0/gems/fog-1.35.0/lib/fog/openstack/models/compute/flavor.rb | Ruby | mit | 1,492 |
/*
* Copyright 2009 Freescale Semicondutor, Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* provides masks and opcode images for use by code generation, emulation
* and for instructions that older assemblers might not know about
*/
#ifndef _ASM_POWERPC_PPC_OPCODE_H
#define _ASM_POWERPC_PPC_OPCODE_H
#include <linux/stringify.h>
#include <asm/asm-compat.h>
#define __REG_R0 0
#define __REG_R1 1
#define __REG_R2 2
#define __REG_R3 3
#define __REG_R4 4
#define __REG_R5 5
#define __REG_R6 6
#define __REG_R7 7
#define __REG_R8 8
#define __REG_R9 9
#define __REG_R10 10
#define __REG_R11 11
#define __REG_R12 12
#define __REG_R13 13
#define __REG_R14 14
#define __REG_R15 15
#define __REG_R16 16
#define __REG_R17 17
#define __REG_R18 18
#define __REG_R19 19
#define __REG_R20 20
#define __REG_R21 21
#define __REG_R22 22
#define __REG_R23 23
#define __REG_R24 24
#define __REG_R25 25
#define __REG_R26 26
#define __REG_R27 27
#define __REG_R28 28
#define __REG_R29 29
#define __REG_R30 30
#define __REG_R31 31
#define __REGA0_0 0
#define __REGA0_R1 1
#define __REGA0_R2 2
#define __REGA0_R3 3
#define __REGA0_R4 4
#define __REGA0_R5 5
#define __REGA0_R6 6
#define __REGA0_R7 7
#define __REGA0_R8 8
#define __REGA0_R9 9
#define __REGA0_R10 10
#define __REGA0_R11 11
#define __REGA0_R12 12
#define __REGA0_R13 13
#define __REGA0_R14 14
#define __REGA0_R15 15
#define __REGA0_R16 16
#define __REGA0_R17 17
#define __REGA0_R18 18
#define __REGA0_R19 19
#define __REGA0_R20 20
#define __REGA0_R21 21
#define __REGA0_R22 22
#define __REGA0_R23 23
#define __REGA0_R24 24
#define __REGA0_R25 25
#define __REGA0_R26 26
#define __REGA0_R27 27
#define __REGA0_R28 28
#define __REGA0_R29 29
#define __REGA0_R30 30
#define __REGA0_R31 31
/* sorted alphabetically */
#define PPC_INST_DCBA 0x7c0005ec
#define PPC_INST_DCBA_MASK 0xfc0007fe
#define PPC_INST_DCBAL 0x7c2005ec
#define PPC_INST_DCBZL 0x7c2007ec
#define PPC_INST_ISEL 0x7c00001e
#define PPC_INST_ISEL_MASK 0xfc00003e
#define PPC_INST_LDARX 0x7c0000a8
#define PPC_INST_LSWI 0x7c0004aa
#define PPC_INST_LSWX 0x7c00042a
#define PPC_INST_LWARX 0x7c000028
#define PPC_INST_LWSYNC 0x7c2004ac
#define PPC_INST_LXVD2X 0x7c000698
#define PPC_INST_MCRXR 0x7c000400
#define PPC_INST_MCRXR_MASK 0xfc0007fe
#define PPC_INST_MFSPR_PVR 0x7c1f42a6
#define PPC_INST_MFSPR_PVR_MASK 0xfc1fffff
#define PPC_INST_MSGSND 0x7c00019c
#define PPC_INST_NOP 0x60000000
#define PPC_INST_POPCNTB 0x7c0000f4
#define PPC_INST_POPCNTB_MASK 0xfc0007fe
#define PPC_INST_POPCNTD 0x7c0003f4
#define PPC_INST_POPCNTW 0x7c0002f4
#define PPC_INST_RFCI 0x4c000066
#define PPC_INST_RFDI 0x4c00004e
#define PPC_INST_RFMCI 0x4c00004c
#define PPC_INST_MFSPR_DSCR 0x7c1102a6
#define PPC_INST_MFSPR_DSCR_MASK 0xfc1fffff
#define PPC_INST_MTSPR_DSCR 0x7c1103a6
#define PPC_INST_MTSPR_DSCR_MASK 0xfc1fffff
#define PPC_INST_SLBFEE 0x7c0007a7
#define PPC_INST_STRING 0x7c00042a
#define PPC_INST_STRING_MASK 0xfc0007fe
#define PPC_INST_STRING_GEN_MASK 0xfc00067e
#define PPC_INST_STSWI 0x7c0005aa
#define PPC_INST_STSWX 0x7c00052a
#define PPC_INST_STXVD2X 0x7c000798
#define PPC_INST_TLBIE 0x7c000264
#define PPC_INST_TLBILX 0x7c000024
#define PPC_INST_WAIT 0x7c00007c
#define PPC_INST_TLBIVAX 0x7c000624
#define PPC_INST_TLBSRX_DOT 0x7c0006a5
#define PPC_INST_XXLOR 0xf0000510
#define PPC_INST_XVCPSGNDP 0xf0000780
#define PPC_INST_NAP 0x4c000364
#define PPC_INST_SLEEP 0x4c0003a4
/* A2 specific instructions */
#define PPC_INST_ERATWE 0x7c0001a6
#define PPC_INST_ERATRE 0x7c000166
#define PPC_INST_ERATILX 0x7c000066
#define PPC_INST_ERATIVAX 0x7c000666
#define PPC_INST_ERATSX 0x7c000126
#define PPC_INST_ERATSX_DOT 0x7c000127
/* Misc instructions for BPF compiler */
#define PPC_INST_LD 0xe8000000
#define PPC_INST_LHZ 0xa0000000
#define PPC_INST_LWZ 0x80000000
#define PPC_INST_STD 0xf8000000
#define PPC_INST_STDU 0xf8000001
#define PPC_INST_MFLR 0x7c0802a6
#define PPC_INST_MTLR 0x7c0803a6
#define PPC_INST_CMPWI 0x2c000000
#define PPC_INST_CMPDI 0x2c200000
#define PPC_INST_CMPLW 0x7c000040
#define PPC_INST_CMPLWI 0x28000000
#define PPC_INST_ADDI 0x38000000
#define PPC_INST_ADDIS 0x3c000000
#define PPC_INST_ADD 0x7c000214
#define PPC_INST_SUB 0x7c000050
#define PPC_INST_BLR 0x4e800020
#define PPC_INST_BLRL 0x4e800021
#define PPC_INST_MULLW 0x7c0001d6
#define PPC_INST_MULHWU 0x7c000016
#define PPC_INST_MULLI 0x1c000000
#define PPC_INST_DIVWU 0x7c0003d6
#define PPC_INST_RLWINM 0x54000000
#define PPC_INST_RLDICR 0x78000004
#define PPC_INST_SLW 0x7c000030
#define PPC_INST_SRW 0x7c000430
#define PPC_INST_AND 0x7c000038
#define PPC_INST_ANDDOT 0x7c000039
#define PPC_INST_OR 0x7c000378
#define PPC_INST_ANDI 0x70000000
#define PPC_INST_ORI 0x60000000
#define PPC_INST_ORIS 0x64000000
#define PPC_INST_NEG 0x7c0000d0
#define PPC_INST_BRANCH 0x48000000
#define PPC_INST_BRANCH_COND 0x40800000
#define PPC_INST_LBZCIX 0x7c0006aa
#define PPC_INST_STBCIX 0x7c0007aa
/* macros to insert fields into opcodes */
#define ___PPC_RA(a) (((a) & 0x1f) << 16)
#define ___PPC_RB(b) (((b) & 0x1f) << 11)
#define ___PPC_RS(s) (((s) & 0x1f) << 21)
#define ___PPC_RT(t) ___PPC_RS(t)
#define __PPC_RA(a) ___PPC_RA(__REG_##a)
#define __PPC_RA0(a) ___PPC_RA(__REGA0_##a)
#define __PPC_RB(b) ___PPC_RB(__REG_##b)
#define __PPC_RS(s) ___PPC_RS(__REG_##s)
#define __PPC_RT(t) ___PPC_RT(__REG_##t)
#define __PPC_XA(a) ((((a) & 0x1f) << 16) | (((a) & 0x20) >> 3))
#define __PPC_XB(b) ((((b) & 0x1f) << 11) | (((b) & 0x20) >> 4))
#define __PPC_XS(s) ((((s) & 0x1f) << 21) | (((s) & 0x20) >> 5))
#define __PPC_XT(s) __PPC_XS(s)
#define __PPC_T_TLB(t) (((t) & 0x3) << 21)
#define __PPC_WC(w) (((w) & 0x3) << 21)
#define __PPC_WS(w) (((w) & 0x1f) << 11)
#define __PPC_SH(s) __PPC_WS(s)
#define __PPC_MB(s) (((s) & 0x1f) << 6)
#define __PPC_ME(s) (((s) & 0x1f) << 1)
#define __PPC_BI(s) (((s) & 0x1f) << 16)
/*
* Only use the larx hint bit on 64bit CPUs. e500v1/v2 based CPUs will treat a
* larx with EH set as an illegal instruction.
*/
#ifdef CONFIG_PPC64
#define __PPC_EH(eh) (((eh) & 0x1) << 0)
#else
#define __PPC_EH(eh) 0
#endif
/* Deal with instructions that older assemblers aren't aware of */
#define PPC_DCBAL(a, b) stringify_in_c(.long PPC_INST_DCBAL | \
__PPC_RA(a) | __PPC_RB(b))
#define PPC_DCBZL(a, b) stringify_in_c(.long PPC_INST_DCBZL | \
__PPC_RA(a) | __PPC_RB(b))
#define PPC_LDARX(t, a, b, eh) stringify_in_c(.long PPC_INST_LDARX | \
___PPC_RT(t) | ___PPC_RA(a) | \
___PPC_RB(b) | __PPC_EH(eh))
#define PPC_LWARX(t, a, b, eh) stringify_in_c(.long PPC_INST_LWARX | \
___PPC_RT(t) | ___PPC_RA(a) | \
___PPC_RB(b) | __PPC_EH(eh))
#define PPC_MSGSND(b) stringify_in_c(.long PPC_INST_MSGSND | \
___PPC_RB(b))
#define PPC_POPCNTB(a, s) stringify_in_c(.long PPC_INST_POPCNTB | \
__PPC_RA(a) | __PPC_RS(s))
#define PPC_POPCNTD(a, s) stringify_in_c(.long PPC_INST_POPCNTD | \
__PPC_RA(a) | __PPC_RS(s))
#define PPC_POPCNTW(a, s) stringify_in_c(.long PPC_INST_POPCNTW | \
__PPC_RA(a) | __PPC_RS(s))
#define PPC_RFCI stringify_in_c(.long PPC_INST_RFCI)
#define PPC_RFDI stringify_in_c(.long PPC_INST_RFDI)
#define PPC_RFMCI stringify_in_c(.long PPC_INST_RFMCI)
#define PPC_TLBILX(t, a, b) stringify_in_c(.long PPC_INST_TLBILX | \
__PPC_T_TLB(t) | __PPC_RA0(a) | __PPC_RB(b))
#define PPC_TLBILX_ALL(a, b) PPC_TLBILX(0, a, b)
#define PPC_TLBILX_PID(a, b) PPC_TLBILX(1, a, b)
#define PPC_TLBILX_VA(a, b) PPC_TLBILX(3, a, b)
#define PPC_WAIT(w) stringify_in_c(.long PPC_INST_WAIT | \
__PPC_WC(w))
#define PPC_TLBIE(lp,a) stringify_in_c(.long PPC_INST_TLBIE | \
___PPC_RB(a) | ___PPC_RS(lp))
#define PPC_TLBSRX_DOT(a,b) stringify_in_c(.long PPC_INST_TLBSRX_DOT | \
__PPC_RA0(a) | __PPC_RB(b))
#define PPC_TLBIVAX(a,b) stringify_in_c(.long PPC_INST_TLBIVAX | \
__PPC_RA0(a) | __PPC_RB(b))
#define PPC_ERATWE(s, a, w) stringify_in_c(.long PPC_INST_ERATWE | \
__PPC_RS(s) | __PPC_RA(a) | __PPC_WS(w))
#define PPC_ERATRE(s, a, w) stringify_in_c(.long PPC_INST_ERATRE | \
__PPC_RS(s) | __PPC_RA(a) | __PPC_WS(w))
#define PPC_ERATILX(t, a, b) stringify_in_c(.long PPC_INST_ERATILX | \
__PPC_T_TLB(t) | __PPC_RA0(a) | \
__PPC_RB(b))
#define PPC_ERATIVAX(s, a, b) stringify_in_c(.long PPC_INST_ERATIVAX | \
__PPC_RS(s) | __PPC_RA0(a) | __PPC_RB(b))
#define PPC_ERATSX(t, a, w) stringify_in_c(.long PPC_INST_ERATSX | \
__PPC_RS(t) | __PPC_RA0(a) | __PPC_RB(b))
#define PPC_ERATSX_DOT(t, a, w) stringify_in_c(.long PPC_INST_ERATSX_DOT | \
__PPC_RS(t) | __PPC_RA0(a) | __PPC_RB(b))
#define PPC_SLBFEE_DOT(t, b) stringify_in_c(.long PPC_INST_SLBFEE | \
__PPC_RT(t) | __PPC_RB(b))
/* PASemi instructions */
#define LBZCIX(t,a,b) stringify_in_c(.long PPC_INST_LBZCIX | \
__PPC_RT(t) | __PPC_RA(a) | __PPC_RB(b))
#define STBCIX(s,a,b) stringify_in_c(.long PPC_INST_STBCIX | \
__PPC_RS(s) | __PPC_RA(a) | __PPC_RB(b))
/*
* Define what the VSX XX1 form instructions will look like, then add
* the 128 bit load store instructions based on that.
*/
#define VSX_XX1(s, a, b) (__PPC_XS(s) | __PPC_RA(a) | __PPC_RB(b))
#define VSX_XX3(t, a, b) (__PPC_XT(t) | __PPC_XA(a) | __PPC_XB(b))
#define STXVD2X(s, a, b) stringify_in_c(.long PPC_INST_STXVD2X | \
VSX_XX1((s), a, b))
#define LXVD2X(s, a, b) stringify_in_c(.long PPC_INST_LXVD2X | \
VSX_XX1((s), a, b))
#define XXLOR(t, a, b) stringify_in_c(.long PPC_INST_XXLOR | \
VSX_XX3((t), a, b))
#define XVCPSGNDP(t, a, b) stringify_in_c(.long (PPC_INST_XVCPSGNDP | \
VSX_XX3((t), (a), (b))))
#define PPC_NAP stringify_in_c(.long PPC_INST_NAP)
#define PPC_SLEEP stringify_in_c(.long PPC_INST_SLEEP)
#endif /* _ASM_POWERPC_PPC_OPCODE_H */
| ystk/linux-poky-debian | arch/powerpc/include/asm/ppc-opcode.h | C | gpl-2.0 | 10,038 |
/*
* Quota code necessary even when VFS quota support is not compiled
* into the kernel. The interesting stuff is over in dquot.c, here
* we have symbols for initial quotactl(2) handling, the sysctl(2)
* variables, etc - things needed even when quota support disabled.
*/
#include <linux/fs.h>
#include <linux/namei.h>
#include <linux/slab.h>
#include <asm/current.h>
#include <linux/uaccess.h>
#include <linux/kernel.h>
#include <linux/security.h>
#include <linux/syscalls.h>
#include <linux/capability.h>
#include <linux/quotaops.h>
#include <linux/types.h>
#include <linux/writeback.h>
static int check_quotactl_permission(struct super_block *sb, int type, int cmd,
qid_t id)
{
switch (cmd) {
/* these commands do not require any special privilegues */
case Q_GETFMT:
case Q_SYNC:
case Q_GETINFO:
case Q_XGETQSTAT:
case Q_XGETQSTATV:
case Q_XQUOTASYNC:
break;
/* allow to query information for dquots we "own" */
case Q_GETQUOTA:
case Q_XGETQUOTA:
if ((type == USRQUOTA && uid_eq(current_euid(), make_kuid(current_user_ns(), id))) ||
(type == GRPQUOTA && in_egroup_p(make_kgid(current_user_ns(), id))))
break;
/*FALLTHROUGH*/
default:
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
}
return security_quotactl(cmd, type, id, sb);
}
static void quota_sync_one(struct super_block *sb, void *arg)
{
int type = *(int *)arg;
if (sb->s_qcop && sb->s_qcop->quota_sync &&
(sb->s_quota_types & (1 << type)))
sb->s_qcop->quota_sync(sb, type);
}
static int quota_sync_all(int type)
{
int ret;
if (type >= MAXQUOTAS)
return -EINVAL;
ret = security_quotactl(Q_SYNC, type, 0, NULL);
if (!ret)
iterate_supers(quota_sync_one, &type);
return ret;
}
unsigned int qtype_enforce_flag(int type)
{
switch (type) {
case USRQUOTA:
return FS_QUOTA_UDQ_ENFD;
case GRPQUOTA:
return FS_QUOTA_GDQ_ENFD;
case PRJQUOTA:
return FS_QUOTA_PDQ_ENFD;
}
return 0;
}
static int quota_quotaon(struct super_block *sb, int type, qid_t id,
struct path *path)
{
if (!sb->s_qcop->quota_on && !sb->s_qcop->quota_enable)
return -ENOSYS;
if (sb->s_qcop->quota_enable)
return sb->s_qcop->quota_enable(sb, qtype_enforce_flag(type));
if (IS_ERR(path))
return PTR_ERR(path);
return sb->s_qcop->quota_on(sb, type, id, path);
}
static int quota_quotaoff(struct super_block *sb, int type)
{
if (!sb->s_qcop->quota_off && !sb->s_qcop->quota_disable)
return -ENOSYS;
if (sb->s_qcop->quota_disable)
return sb->s_qcop->quota_disable(sb, qtype_enforce_flag(type));
return sb->s_qcop->quota_off(sb, type);
}
static int quota_getfmt(struct super_block *sb, int type, void __user *addr)
{
__u32 fmt;
mutex_lock(&sb_dqopt(sb)->dqonoff_mutex);
if (!sb_has_quota_active(sb, type)) {
mutex_unlock(&sb_dqopt(sb)->dqonoff_mutex);
return -ESRCH;
}
fmt = sb_dqopt(sb)->info[type].dqi_format->qf_fmt_id;
mutex_unlock(&sb_dqopt(sb)->dqonoff_mutex);
if (copy_to_user(addr, &fmt, sizeof(fmt)))
return -EFAULT;
return 0;
}
static int quota_getinfo(struct super_block *sb, int type, void __user *addr)
{
struct qc_state state;
struct qc_type_state *tstate;
struct if_dqinfo uinfo;
int ret;
/* This checks whether qc_state has enough entries... */
BUILD_BUG_ON(MAXQUOTAS > XQM_MAXQUOTAS);
if (!sb->s_qcop->get_state)
return -ENOSYS;
ret = sb->s_qcop->get_state(sb, &state);
if (ret)
return ret;
tstate = state.s_state + type;
if (!(tstate->flags & QCI_ACCT_ENABLED))
return -ESRCH;
memset(&uinfo, 0, sizeof(uinfo));
uinfo.dqi_bgrace = tstate->spc_timelimit;
uinfo.dqi_igrace = tstate->ino_timelimit;
if (tstate->flags & QCI_SYSFILE)
uinfo.dqi_flags |= DQF_SYS_FILE;
if (tstate->flags & QCI_ROOT_SQUASH)
uinfo.dqi_flags |= DQF_ROOT_SQUASH;
uinfo.dqi_valid = IIF_ALL;
if (copy_to_user(addr, &uinfo, sizeof(uinfo)))
return -EFAULT;
return 0;
}
static int quota_setinfo(struct super_block *sb, int type, void __user *addr)
{
struct if_dqinfo info;
struct qc_info qinfo;
if (copy_from_user(&info, addr, sizeof(info)))
return -EFAULT;
if (!sb->s_qcop->set_info)
return -ENOSYS;
if (info.dqi_valid & ~(IIF_FLAGS | IIF_BGRACE | IIF_IGRACE))
return -EINVAL;
memset(&qinfo, 0, sizeof(qinfo));
if (info.dqi_valid & IIF_FLAGS) {
if (info.dqi_flags & ~DQF_SETINFO_MASK)
return -EINVAL;
if (info.dqi_flags & DQF_ROOT_SQUASH)
qinfo.i_flags |= QCI_ROOT_SQUASH;
qinfo.i_fieldmask |= QC_FLAGS;
}
if (info.dqi_valid & IIF_BGRACE) {
qinfo.i_spc_timelimit = info.dqi_bgrace;
qinfo.i_fieldmask |= QC_SPC_TIMER;
}
if (info.dqi_valid & IIF_IGRACE) {
qinfo.i_ino_timelimit = info.dqi_igrace;
qinfo.i_fieldmask |= QC_INO_TIMER;
}
return sb->s_qcop->set_info(sb, type, &qinfo);
}
static inline qsize_t qbtos(qsize_t blocks)
{
return blocks << QIF_DQBLKSIZE_BITS;
}
static inline qsize_t stoqb(qsize_t space)
{
return (space + QIF_DQBLKSIZE - 1) >> QIF_DQBLKSIZE_BITS;
}
static void copy_to_if_dqblk(struct if_dqblk *dst, struct qc_dqblk *src)
{
memset(dst, 0, sizeof(*dst));
dst->dqb_bhardlimit = stoqb(src->d_spc_hardlimit);
dst->dqb_bsoftlimit = stoqb(src->d_spc_softlimit);
dst->dqb_curspace = src->d_space;
dst->dqb_ihardlimit = src->d_ino_hardlimit;
dst->dqb_isoftlimit = src->d_ino_softlimit;
dst->dqb_curinodes = src->d_ino_count;
dst->dqb_btime = src->d_spc_timer;
dst->dqb_itime = src->d_ino_timer;
dst->dqb_valid = QIF_ALL;
}
static int quota_getquota(struct super_block *sb, int type, qid_t id,
void __user *addr)
{
struct kqid qid;
struct qc_dqblk fdq;
struct if_dqblk idq;
int ret;
if (!sb->s_qcop->get_dqblk)
return -ENOSYS;
qid = make_kqid(current_user_ns(), type, id);
if (!qid_has_mapping(sb->s_user_ns, qid))
return -EINVAL;
ret = sb->s_qcop->get_dqblk(sb, qid, &fdq);
if (ret)
return ret;
copy_to_if_dqblk(&idq, &fdq);
if (copy_to_user(addr, &idq, sizeof(idq)))
return -EFAULT;
return 0;
}
/*
* Return quota for next active quota >= this id, if any exists,
* otherwise return -ENOENT via ->get_nextdqblk
*/
static int quota_getnextquota(struct super_block *sb, int type, qid_t id,
void __user *addr)
{
struct kqid qid;
struct qc_dqblk fdq;
struct if_nextdqblk idq;
int ret;
if (!sb->s_qcop->get_nextdqblk)
return -ENOSYS;
qid = make_kqid(current_user_ns(), type, id);
if (!qid_has_mapping(sb->s_user_ns, qid))
return -EINVAL;
ret = sb->s_qcop->get_nextdqblk(sb, &qid, &fdq);
if (ret)
return ret;
/* struct if_nextdqblk is a superset of struct if_dqblk */
copy_to_if_dqblk((struct if_dqblk *)&idq, &fdq);
idq.dqb_id = from_kqid(current_user_ns(), qid);
if (copy_to_user(addr, &idq, sizeof(idq)))
return -EFAULT;
return 0;
}
static void copy_from_if_dqblk(struct qc_dqblk *dst, struct if_dqblk *src)
{
dst->d_spc_hardlimit = qbtos(src->dqb_bhardlimit);
dst->d_spc_softlimit = qbtos(src->dqb_bsoftlimit);
dst->d_space = src->dqb_curspace;
dst->d_ino_hardlimit = src->dqb_ihardlimit;
dst->d_ino_softlimit = src->dqb_isoftlimit;
dst->d_ino_count = src->dqb_curinodes;
dst->d_spc_timer = src->dqb_btime;
dst->d_ino_timer = src->dqb_itime;
dst->d_fieldmask = 0;
if (src->dqb_valid & QIF_BLIMITS)
dst->d_fieldmask |= QC_SPC_SOFT | QC_SPC_HARD;
if (src->dqb_valid & QIF_SPACE)
dst->d_fieldmask |= QC_SPACE;
if (src->dqb_valid & QIF_ILIMITS)
dst->d_fieldmask |= QC_INO_SOFT | QC_INO_HARD;
if (src->dqb_valid & QIF_INODES)
dst->d_fieldmask |= QC_INO_COUNT;
if (src->dqb_valid & QIF_BTIME)
dst->d_fieldmask |= QC_SPC_TIMER;
if (src->dqb_valid & QIF_ITIME)
dst->d_fieldmask |= QC_INO_TIMER;
}
static int quota_setquota(struct super_block *sb, int type, qid_t id,
void __user *addr)
{
struct qc_dqblk fdq;
struct if_dqblk idq;
struct kqid qid;
if (copy_from_user(&idq, addr, sizeof(idq)))
return -EFAULT;
if (!sb->s_qcop->set_dqblk)
return -ENOSYS;
qid = make_kqid(current_user_ns(), type, id);
if (!qid_has_mapping(sb->s_user_ns, qid))
return -EINVAL;
copy_from_if_dqblk(&fdq, &idq);
return sb->s_qcop->set_dqblk(sb, qid, &fdq);
}
static int quota_enable(struct super_block *sb, void __user *addr)
{
__u32 flags;
if (copy_from_user(&flags, addr, sizeof(flags)))
return -EFAULT;
if (!sb->s_qcop->quota_enable)
return -ENOSYS;
return sb->s_qcop->quota_enable(sb, flags);
}
static int quota_disable(struct super_block *sb, void __user *addr)
{
__u32 flags;
if (copy_from_user(&flags, addr, sizeof(flags)))
return -EFAULT;
if (!sb->s_qcop->quota_disable)
return -ENOSYS;
return sb->s_qcop->quota_disable(sb, flags);
}
static int quota_state_to_flags(struct qc_state *state)
{
int flags = 0;
if (state->s_state[USRQUOTA].flags & QCI_ACCT_ENABLED)
flags |= FS_QUOTA_UDQ_ACCT;
if (state->s_state[USRQUOTA].flags & QCI_LIMITS_ENFORCED)
flags |= FS_QUOTA_UDQ_ENFD;
if (state->s_state[GRPQUOTA].flags & QCI_ACCT_ENABLED)
flags |= FS_QUOTA_GDQ_ACCT;
if (state->s_state[GRPQUOTA].flags & QCI_LIMITS_ENFORCED)
flags |= FS_QUOTA_GDQ_ENFD;
if (state->s_state[PRJQUOTA].flags & QCI_ACCT_ENABLED)
flags |= FS_QUOTA_PDQ_ACCT;
if (state->s_state[PRJQUOTA].flags & QCI_LIMITS_ENFORCED)
flags |= FS_QUOTA_PDQ_ENFD;
return flags;
}
static int quota_getstate(struct super_block *sb, struct fs_quota_stat *fqs)
{
int type;
struct qc_state state;
int ret;
ret = sb->s_qcop->get_state(sb, &state);
if (ret < 0)
return ret;
memset(fqs, 0, sizeof(*fqs));
fqs->qs_version = FS_QSTAT_VERSION;
fqs->qs_flags = quota_state_to_flags(&state);
/* No quota enabled? */
if (!fqs->qs_flags)
return -ENOSYS;
fqs->qs_incoredqs = state.s_incoredqs;
/*
* GETXSTATE quotactl has space for just one set of time limits so
* report them for the first enabled quota type
*/
for (type = 0; type < XQM_MAXQUOTAS; type++)
if (state.s_state[type].flags & QCI_ACCT_ENABLED)
break;
BUG_ON(type == XQM_MAXQUOTAS);
fqs->qs_btimelimit = state.s_state[type].spc_timelimit;
fqs->qs_itimelimit = state.s_state[type].ino_timelimit;
fqs->qs_rtbtimelimit = state.s_state[type].rt_spc_timelimit;
fqs->qs_bwarnlimit = state.s_state[type].spc_warnlimit;
fqs->qs_iwarnlimit = state.s_state[type].ino_warnlimit;
if (state.s_state[USRQUOTA].flags & QCI_ACCT_ENABLED) {
fqs->qs_uquota.qfs_ino = state.s_state[USRQUOTA].ino;
fqs->qs_uquota.qfs_nblks = state.s_state[USRQUOTA].blocks;
fqs->qs_uquota.qfs_nextents = state.s_state[USRQUOTA].nextents;
}
if (state.s_state[GRPQUOTA].flags & QCI_ACCT_ENABLED) {
fqs->qs_gquota.qfs_ino = state.s_state[GRPQUOTA].ino;
fqs->qs_gquota.qfs_nblks = state.s_state[GRPQUOTA].blocks;
fqs->qs_gquota.qfs_nextents = state.s_state[GRPQUOTA].nextents;
}
if (state.s_state[PRJQUOTA].flags & QCI_ACCT_ENABLED) {
/*
* Q_XGETQSTAT doesn't have room for both group and project
* quotas. So, allow the project quota values to be copied out
* only if there is no group quota information available.
*/
if (!(state.s_state[GRPQUOTA].flags & QCI_ACCT_ENABLED)) {
fqs->qs_gquota.qfs_ino = state.s_state[PRJQUOTA].ino;
fqs->qs_gquota.qfs_nblks =
state.s_state[PRJQUOTA].blocks;
fqs->qs_gquota.qfs_nextents =
state.s_state[PRJQUOTA].nextents;
}
}
return 0;
}
static int quota_getxstate(struct super_block *sb, void __user *addr)
{
struct fs_quota_stat fqs;
int ret;
if (!sb->s_qcop->get_state)
return -ENOSYS;
ret = quota_getstate(sb, &fqs);
if (!ret && copy_to_user(addr, &fqs, sizeof(fqs)))
return -EFAULT;
return ret;
}
static int quota_getstatev(struct super_block *sb, struct fs_quota_statv *fqs)
{
int type;
struct qc_state state;
int ret;
ret = sb->s_qcop->get_state(sb, &state);
if (ret < 0)
return ret;
memset(fqs, 0, sizeof(*fqs));
fqs->qs_version = FS_QSTAT_VERSION;
fqs->qs_flags = quota_state_to_flags(&state);
/* No quota enabled? */
if (!fqs->qs_flags)
return -ENOSYS;
fqs->qs_incoredqs = state.s_incoredqs;
/*
* GETXSTATV quotactl has space for just one set of time limits so
* report them for the first enabled quota type
*/
for (type = 0; type < XQM_MAXQUOTAS; type++)
if (state.s_state[type].flags & QCI_ACCT_ENABLED)
break;
BUG_ON(type == XQM_MAXQUOTAS);
fqs->qs_btimelimit = state.s_state[type].spc_timelimit;
fqs->qs_itimelimit = state.s_state[type].ino_timelimit;
fqs->qs_rtbtimelimit = state.s_state[type].rt_spc_timelimit;
fqs->qs_bwarnlimit = state.s_state[type].spc_warnlimit;
fqs->qs_iwarnlimit = state.s_state[type].ino_warnlimit;
if (state.s_state[USRQUOTA].flags & QCI_ACCT_ENABLED) {
fqs->qs_uquota.qfs_ino = state.s_state[USRQUOTA].ino;
fqs->qs_uquota.qfs_nblks = state.s_state[USRQUOTA].blocks;
fqs->qs_uquota.qfs_nextents = state.s_state[USRQUOTA].nextents;
}
if (state.s_state[GRPQUOTA].flags & QCI_ACCT_ENABLED) {
fqs->qs_gquota.qfs_ino = state.s_state[GRPQUOTA].ino;
fqs->qs_gquota.qfs_nblks = state.s_state[GRPQUOTA].blocks;
fqs->qs_gquota.qfs_nextents = state.s_state[GRPQUOTA].nextents;
}
if (state.s_state[PRJQUOTA].flags & QCI_ACCT_ENABLED) {
fqs->qs_pquota.qfs_ino = state.s_state[PRJQUOTA].ino;
fqs->qs_pquota.qfs_nblks = state.s_state[PRJQUOTA].blocks;
fqs->qs_pquota.qfs_nextents = state.s_state[PRJQUOTA].nextents;
}
return 0;
}
static int quota_getxstatev(struct super_block *sb, void __user *addr)
{
struct fs_quota_statv fqs;
int ret;
if (!sb->s_qcop->get_state)
return -ENOSYS;
memset(&fqs, 0, sizeof(fqs));
if (copy_from_user(&fqs, addr, 1)) /* Just read qs_version */
return -EFAULT;
/* If this kernel doesn't support user specified version, fail */
switch (fqs.qs_version) {
case FS_QSTATV_VERSION1:
break;
default:
return -EINVAL;
}
ret = quota_getstatev(sb, &fqs);
if (!ret && copy_to_user(addr, &fqs, sizeof(fqs)))
return -EFAULT;
return ret;
}
/*
* XFS defines BBTOB and BTOBB macros inside fs/xfs/ and we cannot move them
* out of there as xfsprogs rely on definitions being in that header file. So
* just define same functions here for quota purposes.
*/
#define XFS_BB_SHIFT 9
static inline u64 quota_bbtob(u64 blocks)
{
return blocks << XFS_BB_SHIFT;
}
static inline u64 quota_btobb(u64 bytes)
{
return (bytes + (1 << XFS_BB_SHIFT) - 1) >> XFS_BB_SHIFT;
}
static void copy_from_xfs_dqblk(struct qc_dqblk *dst, struct fs_disk_quota *src)
{
dst->d_spc_hardlimit = quota_bbtob(src->d_blk_hardlimit);
dst->d_spc_softlimit = quota_bbtob(src->d_blk_softlimit);
dst->d_ino_hardlimit = src->d_ino_hardlimit;
dst->d_ino_softlimit = src->d_ino_softlimit;
dst->d_space = quota_bbtob(src->d_bcount);
dst->d_ino_count = src->d_icount;
dst->d_ino_timer = src->d_itimer;
dst->d_spc_timer = src->d_btimer;
dst->d_ino_warns = src->d_iwarns;
dst->d_spc_warns = src->d_bwarns;
dst->d_rt_spc_hardlimit = quota_bbtob(src->d_rtb_hardlimit);
dst->d_rt_spc_softlimit = quota_bbtob(src->d_rtb_softlimit);
dst->d_rt_space = quota_bbtob(src->d_rtbcount);
dst->d_rt_spc_timer = src->d_rtbtimer;
dst->d_rt_spc_warns = src->d_rtbwarns;
dst->d_fieldmask = 0;
if (src->d_fieldmask & FS_DQ_ISOFT)
dst->d_fieldmask |= QC_INO_SOFT;
if (src->d_fieldmask & FS_DQ_IHARD)
dst->d_fieldmask |= QC_INO_HARD;
if (src->d_fieldmask & FS_DQ_BSOFT)
dst->d_fieldmask |= QC_SPC_SOFT;
if (src->d_fieldmask & FS_DQ_BHARD)
dst->d_fieldmask |= QC_SPC_HARD;
if (src->d_fieldmask & FS_DQ_RTBSOFT)
dst->d_fieldmask |= QC_RT_SPC_SOFT;
if (src->d_fieldmask & FS_DQ_RTBHARD)
dst->d_fieldmask |= QC_RT_SPC_HARD;
if (src->d_fieldmask & FS_DQ_BTIMER)
dst->d_fieldmask |= QC_SPC_TIMER;
if (src->d_fieldmask & FS_DQ_ITIMER)
dst->d_fieldmask |= QC_INO_TIMER;
if (src->d_fieldmask & FS_DQ_RTBTIMER)
dst->d_fieldmask |= QC_RT_SPC_TIMER;
if (src->d_fieldmask & FS_DQ_BWARNS)
dst->d_fieldmask |= QC_SPC_WARNS;
if (src->d_fieldmask & FS_DQ_IWARNS)
dst->d_fieldmask |= QC_INO_WARNS;
if (src->d_fieldmask & FS_DQ_RTBWARNS)
dst->d_fieldmask |= QC_RT_SPC_WARNS;
if (src->d_fieldmask & FS_DQ_BCOUNT)
dst->d_fieldmask |= QC_SPACE;
if (src->d_fieldmask & FS_DQ_ICOUNT)
dst->d_fieldmask |= QC_INO_COUNT;
if (src->d_fieldmask & FS_DQ_RTBCOUNT)
dst->d_fieldmask |= QC_RT_SPACE;
}
static void copy_qcinfo_from_xfs_dqblk(struct qc_info *dst,
struct fs_disk_quota *src)
{
memset(dst, 0, sizeof(*dst));
dst->i_spc_timelimit = src->d_btimer;
dst->i_ino_timelimit = src->d_itimer;
dst->i_rt_spc_timelimit = src->d_rtbtimer;
dst->i_ino_warnlimit = src->d_iwarns;
dst->i_spc_warnlimit = src->d_bwarns;
dst->i_rt_spc_warnlimit = src->d_rtbwarns;
if (src->d_fieldmask & FS_DQ_BWARNS)
dst->i_fieldmask |= QC_SPC_WARNS;
if (src->d_fieldmask & FS_DQ_IWARNS)
dst->i_fieldmask |= QC_INO_WARNS;
if (src->d_fieldmask & FS_DQ_RTBWARNS)
dst->i_fieldmask |= QC_RT_SPC_WARNS;
if (src->d_fieldmask & FS_DQ_BTIMER)
dst->i_fieldmask |= QC_SPC_TIMER;
if (src->d_fieldmask & FS_DQ_ITIMER)
dst->i_fieldmask |= QC_INO_TIMER;
if (src->d_fieldmask & FS_DQ_RTBTIMER)
dst->i_fieldmask |= QC_RT_SPC_TIMER;
}
static int quota_setxquota(struct super_block *sb, int type, qid_t id,
void __user *addr)
{
struct fs_disk_quota fdq;
struct qc_dqblk qdq;
struct kqid qid;
if (copy_from_user(&fdq, addr, sizeof(fdq)))
return -EFAULT;
if (!sb->s_qcop->set_dqblk)
return -ENOSYS;
qid = make_kqid(current_user_ns(), type, id);
if (!qid_has_mapping(sb->s_user_ns, qid))
return -EINVAL;
/* Are we actually setting timer / warning limits for all users? */
if (from_kqid(sb->s_user_ns, qid) == 0 &&
fdq.d_fieldmask & (FS_DQ_WARNS_MASK | FS_DQ_TIMER_MASK)) {
struct qc_info qinfo;
int ret;
if (!sb->s_qcop->set_info)
return -EINVAL;
copy_qcinfo_from_xfs_dqblk(&qinfo, &fdq);
ret = sb->s_qcop->set_info(sb, type, &qinfo);
if (ret)
return ret;
/* These are already done */
fdq.d_fieldmask &= ~(FS_DQ_WARNS_MASK | FS_DQ_TIMER_MASK);
}
copy_from_xfs_dqblk(&qdq, &fdq);
return sb->s_qcop->set_dqblk(sb, qid, &qdq);
}
static void copy_to_xfs_dqblk(struct fs_disk_quota *dst, struct qc_dqblk *src,
int type, qid_t id)
{
memset(dst, 0, sizeof(*dst));
dst->d_version = FS_DQUOT_VERSION;
dst->d_id = id;
if (type == USRQUOTA)
dst->d_flags = FS_USER_QUOTA;
else if (type == PRJQUOTA)
dst->d_flags = FS_PROJ_QUOTA;
else
dst->d_flags = FS_GROUP_QUOTA;
dst->d_blk_hardlimit = quota_btobb(src->d_spc_hardlimit);
dst->d_blk_softlimit = quota_btobb(src->d_spc_softlimit);
dst->d_ino_hardlimit = src->d_ino_hardlimit;
dst->d_ino_softlimit = src->d_ino_softlimit;
dst->d_bcount = quota_btobb(src->d_space);
dst->d_icount = src->d_ino_count;
dst->d_itimer = src->d_ino_timer;
dst->d_btimer = src->d_spc_timer;
dst->d_iwarns = src->d_ino_warns;
dst->d_bwarns = src->d_spc_warns;
dst->d_rtb_hardlimit = quota_btobb(src->d_rt_spc_hardlimit);
dst->d_rtb_softlimit = quota_btobb(src->d_rt_spc_softlimit);
dst->d_rtbcount = quota_btobb(src->d_rt_space);
dst->d_rtbtimer = src->d_rt_spc_timer;
dst->d_rtbwarns = src->d_rt_spc_warns;
}
static int quota_getxquota(struct super_block *sb, int type, qid_t id,
void __user *addr)
{
struct fs_disk_quota fdq;
struct qc_dqblk qdq;
struct kqid qid;
int ret;
if (!sb->s_qcop->get_dqblk)
return -ENOSYS;
qid = make_kqid(current_user_ns(), type, id);
if (!qid_has_mapping(sb->s_user_ns, qid))
return -EINVAL;
ret = sb->s_qcop->get_dqblk(sb, qid, &qdq);
if (ret)
return ret;
copy_to_xfs_dqblk(&fdq, &qdq, type, id);
if (copy_to_user(addr, &fdq, sizeof(fdq)))
return -EFAULT;
return ret;
}
/*
* Return quota for next active quota >= this id, if any exists,
* otherwise return -ENOENT via ->get_nextdqblk.
*/
static int quota_getnextxquota(struct super_block *sb, int type, qid_t id,
void __user *addr)
{
struct fs_disk_quota fdq;
struct qc_dqblk qdq;
struct kqid qid;
qid_t id_out;
int ret;
if (!sb->s_qcop->get_nextdqblk)
return -ENOSYS;
qid = make_kqid(current_user_ns(), type, id);
if (!qid_has_mapping(sb->s_user_ns, qid))
return -EINVAL;
ret = sb->s_qcop->get_nextdqblk(sb, &qid, &qdq);
if (ret)
return ret;
id_out = from_kqid(current_user_ns(), qid);
copy_to_xfs_dqblk(&fdq, &qdq, type, id_out);
if (copy_to_user(addr, &fdq, sizeof(fdq)))
return -EFAULT;
return ret;
}
static int quota_rmxquota(struct super_block *sb, void __user *addr)
{
__u32 flags;
if (copy_from_user(&flags, addr, sizeof(flags)))
return -EFAULT;
if (!sb->s_qcop->rm_xquota)
return -ENOSYS;
return sb->s_qcop->rm_xquota(sb, flags);
}
/* Copy parameters and call proper function */
static int do_quotactl(struct super_block *sb, int type, int cmd, qid_t id,
void __user *addr, struct path *path)
{
int ret;
if (type >= (XQM_COMMAND(cmd) ? XQM_MAXQUOTAS : MAXQUOTAS))
return -EINVAL;
/*
* Quota not supported on this fs? Check this before s_quota_types
* since they needn't be set if quota is not supported at all.
*/
if (!sb->s_qcop)
return -ENOSYS;
if (!(sb->s_quota_types & (1 << type)))
return -EINVAL;
ret = check_quotactl_permission(sb, type, cmd, id);
if (ret < 0)
return ret;
switch (cmd) {
case Q_QUOTAON:
return quota_quotaon(sb, type, id, path);
case Q_QUOTAOFF:
return quota_quotaoff(sb, type);
case Q_GETFMT:
return quota_getfmt(sb, type, addr);
case Q_GETINFO:
return quota_getinfo(sb, type, addr);
case Q_SETINFO:
return quota_setinfo(sb, type, addr);
case Q_GETQUOTA:
return quota_getquota(sb, type, id, addr);
case Q_GETNEXTQUOTA:
return quota_getnextquota(sb, type, id, addr);
case Q_SETQUOTA:
return quota_setquota(sb, type, id, addr);
case Q_SYNC:
if (!sb->s_qcop->quota_sync)
return -ENOSYS;
return sb->s_qcop->quota_sync(sb, type);
case Q_XQUOTAON:
return quota_enable(sb, addr);
case Q_XQUOTAOFF:
return quota_disable(sb, addr);
case Q_XQUOTARM:
return quota_rmxquota(sb, addr);
case Q_XGETQSTAT:
return quota_getxstate(sb, addr);
case Q_XGETQSTATV:
return quota_getxstatev(sb, addr);
case Q_XSETQLIM:
return quota_setxquota(sb, type, id, addr);
case Q_XGETQUOTA:
return quota_getxquota(sb, type, id, addr);
case Q_XGETNEXTQUOTA:
return quota_getnextxquota(sb, type, id, addr);
case Q_XQUOTASYNC:
if (sb->s_flags & MS_RDONLY)
return -EROFS;
/* XFS quotas are fully coherent now, making this call a noop */
return 0;
default:
return -EINVAL;
}
}
#ifdef CONFIG_BLOCK
/* Return 1 if 'cmd' will block on frozen filesystem */
static int quotactl_cmd_write(int cmd)
{
/*
* We cannot allow Q_GETQUOTA and Q_GETNEXTQUOTA without write access
* as dquot_acquire() may allocate space for new structure and OCFS2
* needs to increment on-disk use count.
*/
switch (cmd) {
case Q_GETFMT:
case Q_GETINFO:
case Q_SYNC:
case Q_XGETQSTAT:
case Q_XGETQSTATV:
case Q_XGETQUOTA:
case Q_XGETNEXTQUOTA:
case Q_XQUOTASYNC:
return 0;
}
return 1;
}
#endif /* CONFIG_BLOCK */
/*
* look up a superblock on which quota ops will be performed
* - use the name of a block device to find the superblock thereon
*/
static struct super_block *quotactl_block(const char __user *special, int cmd)
{
#ifdef CONFIG_BLOCK
struct block_device *bdev;
struct super_block *sb;
struct filename *tmp = getname(special);
if (IS_ERR(tmp))
return ERR_CAST(tmp);
bdev = lookup_bdev(tmp->name);
putname(tmp);
if (IS_ERR(bdev))
return ERR_CAST(bdev);
if (quotactl_cmd_write(cmd))
sb = get_super_thawed(bdev);
else
sb = get_super(bdev);
bdput(bdev);
if (!sb)
return ERR_PTR(-ENODEV);
return sb;
#else
return ERR_PTR(-ENODEV);
#endif
}
/*
* This is the system call interface. This communicates with
* the user-level programs. Currently this only supports diskquota
* calls. Maybe we need to add the process quotas etc. in the future,
* but we probably should use rlimits for that.
*/
SYSCALL_DEFINE4(quotactl, unsigned int, cmd, const char __user *, special,
qid_t, id, void __user *, addr)
{
uint cmds, type;
struct super_block *sb = NULL;
struct path path, *pathp = NULL;
int ret;
cmds = cmd >> SUBCMDSHIFT;
type = cmd & SUBCMDMASK;
/*
* As a special case Q_SYNC can be called without a specific device.
* It will iterate all superblocks that have quota enabled and call
* the sync action on each of them.
*/
if (!special) {
if (cmds == Q_SYNC)
return quota_sync_all(type);
return -ENODEV;
}
/*
* Path for quotaon has to be resolved before grabbing superblock
* because that gets s_umount sem which is also possibly needed by path
* resolution (think about autofs) and thus deadlocks could arise.
*/
if (cmds == Q_QUOTAON) {
ret = user_path_at(AT_FDCWD, addr, LOOKUP_FOLLOW|LOOKUP_AUTOMOUNT, &path);
if (ret)
pathp = ERR_PTR(ret);
else
pathp = &path;
}
sb = quotactl_block(special, cmds);
if (IS_ERR(sb)) {
ret = PTR_ERR(sb);
goto out;
}
ret = do_quotactl(sb, type, cmds, id, addr, pathp);
drop_super(sb);
out:
if (pathp && !IS_ERR(pathp))
path_put(pathp);
return ret;
}
| jigpu/input | fs/quota/quota.c | C | gpl-2.0 | 24,683 |
ansible_tower_cli
==============
Install ansible-tower-cli rpm.
Requirements
------------
None
Role Variables
--------------
None
Dependencies
------------
None
Example Playbook
----------------
Including an example of how to use your role (for instance, with variables passed in as parameters) is always nice for users too:
- hosts: servers
roles:
- roles/ansible_tower_cli
License
-------
Copyright 2012-2014 Red Hat, 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.
Author Information
------------------
openshift operations
| appuio/ansible-role-openshift-zabbix-monitoring | vendor/openshift-tools/ansible/roles/ansible_tower_cli/README.md | Markdown | apache-2.0 | 1,063 |
<!doctype html>
<style>
div {
font-size: 50px;
text-decoration: underline solid red;
}
</style>
<script>
onload = function() {
target.style.textDecorationColor = "green";
};
</script>
<p>Test that changes in text-decoration-color are recalculated correctly. PASS
if the text below has a solid green underline, and no red.</p>
<div id="target">
Filler text
</div>
| axinging/chromium-crosswalk | third_party/WebKit/LayoutTests/fast/css3-text/css3-text-decoration/text-decoration-color-recalc.html | HTML | bsd-3-clause | 407 |
#!/bin/sh
# Copyright 2015, Google Inc.
# All rights reserved.
#
# 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 Google Inc. 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.
set -e
if [ -f cache.mk ] ; then
echo "Please don't commit cache.mk"
exit 1
fi
| 7anner/grpc | tools/run_tests/sanity/check_cache_mk.sh | Shell | bsd-3-clause | 1,626 |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit script for Chromium browser resources.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into depot_tools, and see
http://www.chromium.org/developers/web-development-style-guide for the rules
we're checking against here.
"""
import os
import struct
class InvalidPNGException(Exception):
pass
class ResourceScaleFactors(object):
"""Verifier of image dimensions for Chromium resources.
This class verifies the image dimensions of resources in the various
resource subdirectories.
Attributes:
paths: An array of tuples giving the folders to check and their
relevant scale factors. For example:
[(100, 'default_100_percent'), (200, 'default_200_percent')]
"""
def __init__(self, input_api, output_api, paths):
""" Initializes ResourceScaleFactors with paths."""
self.input_api = input_api
self.output_api = output_api
self.paths = paths
def RunChecks(self):
"""Verifies the scale factors of resources being added or modified.
Returns:
An array of presubmit errors if any images were detected not
having the correct dimensions.
"""
def ImageSize(filename):
with open(filename, 'rb', buffering=0) as f:
data = f.read(24)
if data[:8] != '\x89PNG\r\n\x1A\n' or data[12:16] != 'IHDR':
raise InvalidPNGException
return struct.unpack('>ii', data[16:24])
# Returns a list of valid scaled image sizes. The valid sizes are the
# floor and ceiling of (base_size * scale_percent / 100). This is equivalent
# to requiring that the actual scaled size is less than one pixel away from
# the exact scaled size.
def ValidSizes(base_size, scale_percent):
return sorted(set([(base_size * scale_percent) / 100,
(base_size * scale_percent + 99) / 100]))
repository_path = self.input_api.os_path.relpath(
self.input_api.PresubmitLocalPath(),
self.input_api.change.RepositoryRoot())
results = []
# Check for affected files in any of the paths specified.
affected_files = self.input_api.AffectedFiles(include_deletes=False)
files = []
for f in affected_files:
for path_spec in self.paths:
path_root = self.input_api.os_path.join(
repository_path, path_spec[1])
if (f.LocalPath().endswith('.png') and
f.LocalPath().startswith(path_root)):
# Only save the relative path from the resource directory.
relative_path = self.input_api.os_path.relpath(f.LocalPath(),
path_root)
if relative_path not in files:
files.append(relative_path)
corrupt_png_error = ('Corrupt PNG in file %s. Note that binaries are not '
'correctly uploaded to the code review tool and must be directly '
'submitted using the dcommit command.')
for f in files:
base_image = self.input_api.os_path.join(self.paths[0][1], f)
if not os.path.exists(base_image):
results.append(self.output_api.PresubmitError(
'Base image %s does not exist' % self.input_api.os_path.join(
repository_path, base_image)))
continue
try:
base_dimensions = ImageSize(base_image)
except InvalidPNGException:
results.append(self.output_api.PresubmitError(corrupt_png_error %
self.input_api.os_path.join(repository_path, base_image)))
continue
# Find all scaled versions of the base image and verify their sizes.
for i in range(1, len(self.paths)):
image_path = self.input_api.os_path.join(self.paths[i][1], f)
if not os.path.exists(image_path):
continue
# Ensure that each image for a particular scale factor is the
# correct scale of the base image.
try:
scaled_dimensions = ImageSize(image_path)
except InvalidPNGException:
results.append(self.output_api.PresubmitError(corrupt_png_error %
self.input_api.os_path.join(repository_path, image_path)))
continue
for dimension_name, base_size, scaled_size in zip(
('width', 'height'), base_dimensions, scaled_dimensions):
valid_sizes = ValidSizes(base_size, self.paths[i][0])
if scaled_size not in valid_sizes:
results.append(self.output_api.PresubmitError(
'Image %s has %s %d, expected to be %s' % (
self.input_api.os_path.join(repository_path, image_path),
dimension_name,
scaled_size,
' or '.join(map(str, valid_sizes)))))
return results
| guorendong/iridium-browser-ubuntu | ui/resources/resource_check/resource_scale_factors.py | Python | bsd-3-clause | 4,859 |
/*
* KineticJS JavaScript Framework v5.1.0
* http://www.kineticjs.com/
* Copyright 2013, Eric Rowell
* Licensed under the MIT or GPL Version 2 licenses.
* Date: 2014-03-27
*
* Copyright (C) 2011 - 2013 by Eric Rowell
*
* 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 Kinetic
*/
/*jshint -W079, -W020*/
var Kinetic = {};
(function(root) {
var PI_OVER_180 = Math.PI / 180;
Kinetic = {
// public
version: '5.1.0',
// private
stages: [],
idCounter: 0,
ids: {},
names: {},
shapes: {},
listenClickTap: false,
inDblClickWindow: false,
// configurations
enableTrace: false,
traceArrMax: 100,
dblClickWindow: 400,
pixelRatio: undefined,
dragDistance : 0,
angleDeg: true,
// user agent
UA: (function() {
var userAgent = (root.navigator && root.navigator.userAgent) || '';
var ua = userAgent.toLowerCase(),
// jQuery UA regex
match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf('compatible') < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[],
// adding mobile flag as well
mobile = !!(userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i));
return {
browser: match[ 1 ] || '',
version: match[ 2 ] || '0',
// adding mobile flab
mobile: mobile
};
})(),
/**
* @namespace Filters
* @memberof Kinetic
*/
Filters: {},
/**
* Node constructor. Nodes are entities that can be transformed, layered,
* and have bound events. The stage, layers, groups, and shapes all extend Node.
* @constructor
* @memberof Kinetic
* @abstract
* @param {Object} config
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
*/
Node: function(config) {
this._init(config);
},
/**
* Shape constructor. Shapes are primitive objects such as rectangles,
* circles, text, lines, etc.
* @constructor
* @memberof Kinetic
* @augments Kinetic.Node
* @param {Object} config
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var customShape = new Kinetic.Shape({<br>
* x: 5,<br>
* y: 10,<br>
* fill: 'red',<br>
* // a Kinetic.Canvas renderer is passed into the drawFunc function<br>
* drawFunc: function(context) {<br>
* context.beginPath();<br>
* context.moveTo(200, 50);<br>
* context.lineTo(420, 80);<br>
* context.quadraticCurveTo(300, 100, 260, 170);<br>
* context.closePath();<br>
* context.fillStrokeShape(this);<br>
* }<br>
*});
*/
Shape: function(config) {
this.__init(config);
},
/**
* Container constructor. Containers are used to contain nodes or other containers
* @constructor
* @memberof Kinetic
* @augments Kinetic.Node
* @abstract
* @param {Object} config
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @param {Function} [config.clipFunc] clipping function
*/
Container: function(config) {
this.__init(config);
},
/**
* Stage constructor. A stage is used to contain multiple layers
* @constructor
* @memberof Kinetic
* @augments Kinetic.Container
* @param {Object} config
* @param {String|DomElement} config.container Container id or DOM element
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @param {Function} [config.clipFunc] clipping function
* @example
* var stage = new Kinetic.Stage({<br>
* width: 500,<br>
* height: 800,<br>
* container: 'containerId'<br>
* });
*/
Stage: function(config) {
this.___init(config);
},
/**
* BaseLayer constructor.
* @constructor
* @memberof Kinetic
* @augments Kinetic.Container
* @param {Object} config
* @param {Boolean} [config.clearBeforeDraw] set this property to false if you don't want
* to clear the canvas before each layer draw. The default value is true.
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @param {Function} [config.clipFunc] clipping function
* @example
* var layer = new Kinetic.Layer();
*/
BaseLayer: function(config) {
this.___init(config);
},
/**
* Layer constructor. Layers are tied to their own canvas element and are used
* to contain groups or shapes
* @constructor
* @memberof Kinetic
* @augments Kinetic.Container
* @param {Object} config
* @param {Boolean} [config.clearBeforeDraw] set this property to false if you don't want
* to clear the canvas before each layer draw. The default value is true.
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @param {Function} [config.clipFunc] clipping function
* @example
* var layer = new Kinetic.Layer();
*/
Layer: function(config) {
this.____init(config);
},
/**
* FastLayer constructor. Layers are tied to their own canvas element and are used
* to contain groups or shapes
* @constructor
* @memberof Kinetic
* @augments Kinetic.Container
* @param {Object} config
* @param {Boolean} [config.clearBeforeDraw] set this property to false if you don't want
* to clear the canvas before each layer draw. The default value is true.
* @example
* var layer = new Kinetic.FastLayer();
*/
FastLayer: function(config) {
this.____init(config);
},
/**
* Group constructor. Groups are used to contain shapes or other groups.
* @constructor
* @memberof Kinetic
* @augments Kinetic.Container
* @param {Object} config
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @param {Function} [config.clipFunc] clipping function
* @example
* var group = new Kinetic.Group();
*/
Group: function(config) {
this.___init(config);
},
/**
* returns whether or not drag and drop is currently active
* @method
* @memberof Kinetic
*/
isDragging: function() {
var dd = Kinetic.DD;
// if DD is not included with the build, then
// drag and drop is not even possible
if (!dd) {
return false;
}
// if DD is included with the build
else {
return dd.isDragging;
}
},
/**
* returns whether or not a drag and drop operation is ready, but may
* not necessarily have started
* @method
* @memberof Kinetic
*/
isDragReady: function() {
var dd = Kinetic.DD;
// if DD is not included with the build, then
// drag and drop is not even possible
if (!dd) {
return false;
}
// if DD is included with the build
else {
return !!dd.node;
}
},
_addId: function(node, id) {
if(id !== undefined) {
this.ids[id] = node;
}
},
_removeId: function(id) {
if(id !== undefined) {
delete this.ids[id];
}
},
_addName: function(node, name) {
if(name !== undefined) {
if(this.names[name] === undefined) {
this.names[name] = [];
}
this.names[name].push(node);
}
},
_removeName: function(name, _id) {
if(name !== undefined) {
var nodes = this.names[name];
if(nodes !== undefined) {
for(var n = 0; n < nodes.length; n++) {
var no = nodes[n];
if(no._id === _id) {
nodes.splice(n, 1);
}
}
if(nodes.length === 0) {
delete this.names[name];
}
}
}
},
getAngle: function(angle) {
return this.angleDeg ? angle * PI_OVER_180 : angle;
}
};
})(this);
// Uses Node, AMD or browser globals to create a module.
// If you want something that will work in other stricter CommonJS environments,
// or if you need to create a circular dependency, see commonJsStrict.js
// Defines a module "returnExports" that depends another module called "b".
// Note that the name of the module is implied by the file name. It is best
// if the file name and the exported global have matching names.
// If the 'b' module also uses this type of boilerplate, then
// in the browser, it will create a global .b that is used below.
// If you do not want to support the browser global path, then you
// can remove the `root` use and the passing `this` as the first arg to
// the top function.
// if the module has no dependencies, the above pattern can be simplified to
( function(root, factory) {
if( typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like enviroments that support module.exports,
// like Node.
var Canvas = require('canvas');
var jsdom = require('jsdom').jsdom;
var doc = jsdom('<!DOCTYPE html><html><head></head><body></body></html>');
var KineticJS = factory();
Kinetic.document = doc;
Kinetic.window = Kinetic.document.createWindow();
Kinetic.window.Image = Canvas.Image;
Kinetic.root = root;
Kinetic._nodeCanvas = Canvas;
module.exports = KineticJS;
return;
}
else if( typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(factory);
}
Kinetic.document = document;
Kinetic.window = window;
Kinetic.root = root;
}((1, eval)('this'), function() {
// Just return a value to define the module export.
// This example returns an object, but the module
// can return a function as the exported value.
return Kinetic;
}));
;(function() {
/**
* Collection constructor. Collection extends
* Array. This class is used in conjunction with {@link Kinetic.Container#get}
* @constructor
* @memberof Kinetic
*/
Kinetic.Collection = function() {
var args = [].slice.call(arguments), length = args.length, i = 0;
this.length = length;
for(; i < length; i++) {
this[i] = args[i];
}
return this;
};
Kinetic.Collection.prototype = [];
/**
* iterate through node array and run a function for each node.
* The node and index is passed into the function
* @method
* @memberof Kinetic.Collection.prototype
* @param {Function} func
* @example
* // get all nodes with name foo inside layer, and set x to 10 for each
* layer.get('.foo').each(function(shape, n) {<br>
* shape.setX(10);<br>
* });
*/
Kinetic.Collection.prototype.each = function(func) {
for(var n = 0; n < this.length; n++) {
func(this[n], n);
}
};
/**
* convert collection into an array
* @method
* @memberof Kinetic.Collection.prototype
*/
Kinetic.Collection.prototype.toArray = function() {
var arr = [],
len = this.length,
n;
for(n = 0; n < len; n++) {
arr.push(this[n]);
}
return arr;
};
/**
* convert array into a collection
* @method
* @memberof Kinetic.Collection
* @param {Array} arr
*/
Kinetic.Collection.toCollection = function(arr) {
var collection = new Kinetic.Collection(),
len = arr.length,
n;
for(n = 0; n < len; n++) {
collection.push(arr[n]);
}
return collection;
};
// map one method by it's name
Kinetic.Collection._mapMethod = function(methodName) {
Kinetic.Collection.prototype[methodName] = function() {
var len = this.length,
i;
var args = [].slice.call(arguments);
for(i = 0; i < len; i++) {
this[i][methodName].apply(this[i], args);
}
return this;
};
};
Kinetic.Collection.mapMethods = function(constructor) {
var prot = constructor.prototype;
for(var methodName in prot) {
Kinetic.Collection._mapMethod(methodName);
}
};
/*
* Last updated November 2011
* By Simon Sarris
* www.simonsarris.com
* sarris@acm.org
*
* Free to use and distribute at will
* So long as you are nice to people, etc
*/
/*
* The usage of this class was inspired by some of the work done by a forked
* project, KineticJS-Ext by Wappworks, which is based on Simon's Transform
* class. Modified by Eric Rowell
*/
/**
* Transform constructor
* @constructor
* @param {Array} Optional six-element matrix
* @memberof Kinetic
*/
Kinetic.Transform = function(m) {
this.m = (m && m.slice()) || [1, 0, 0, 1, 0, 0];
};
Kinetic.Transform.prototype = {
/**
* Copy Kinetic.Transform object
* @method
* @memberof Kinetic.Transform.prototype
* @returns {Kinetic.Transform}
*/
copy: function() {
return new Kinetic.Transform(this.m);
},
/**
* Transform point
* @method
* @memberof Kinetic.Transform.prototype
* @param {Object} 2D point(x, y)
* @returns {Object} 2D point(x, y)
*/
point: function(p) {
var m = this.m;
return {
x: m[0] * p.x + m[2] * p.y + m[4],
y: m[1] * p.x + m[3] * p.y + m[5]
};
},
/**
* Apply translation
* @method
* @memberof Kinetic.Transform.prototype
* @param {Number} x
* @param {Number} y
* @returns {Kinetic.Transform}
*/
translate: function(x, y) {
this.m[4] += this.m[0] * x + this.m[2] * y;
this.m[5] += this.m[1] * x + this.m[3] * y;
return this;
},
/**
* Apply scale
* @method
* @memberof Kinetic.Transform.prototype
* @param {Number} sx
* @param {Number} sy
* @returns {Kinetic.Transform}
*/
scale: function(sx, sy) {
this.m[0] *= sx;
this.m[1] *= sx;
this.m[2] *= sy;
this.m[3] *= sy;
return this;
},
/**
* Apply rotation
* @method
* @memberof Kinetic.Transform.prototype
* @param {Number} rad Angle in radians
* @returns {Kinetic.Transform}
*/
rotate: function(rad) {
var c = Math.cos(rad);
var s = Math.sin(rad);
var m11 = this.m[0] * c + this.m[2] * s;
var m12 = this.m[1] * c + this.m[3] * s;
var m21 = this.m[0] * -s + this.m[2] * c;
var m22 = this.m[1] * -s + this.m[3] * c;
this.m[0] = m11;
this.m[1] = m12;
this.m[2] = m21;
this.m[3] = m22;
return this;
},
/**
* Returns the translation
* @method
* @memberof Kinetic.Transform.prototype
* @returns {Object} 2D point(x, y)
*/
getTranslation: function() {
return {
x: this.m[4],
y: this.m[5]
};
},
/**
* Apply skew
* @method
* @memberof Kinetic.Transform.prototype
* @param {Number} sx
* @param {Number} sy
* @returns {Kinetic.Transform}
*/
skew: function(sx, sy) {
var m11 = this.m[0] + this.m[2] * sy;
var m12 = this.m[1] + this.m[3] * sy;
var m21 = this.m[2] + this.m[0] * sx;
var m22 = this.m[3] + this.m[1] * sx;
this.m[0] = m11;
this.m[1] = m12;
this.m[2] = m21;
this.m[3] = m22;
return this;
},
/**
* Transform multiplication
* @method
* @memberof Kinetic.Transform.prototype
* @param {Kinetic.Transform} matrix
* @returns {Kinetic.Transform}
*/
multiply: function(matrix) {
var m11 = this.m[0] * matrix.m[0] + this.m[2] * matrix.m[1];
var m12 = this.m[1] * matrix.m[0] + this.m[3] * matrix.m[1];
var m21 = this.m[0] * matrix.m[2] + this.m[2] * matrix.m[3];
var m22 = this.m[1] * matrix.m[2] + this.m[3] * matrix.m[3];
var dx = this.m[0] * matrix.m[4] + this.m[2] * matrix.m[5] + this.m[4];
var dy = this.m[1] * matrix.m[4] + this.m[3] * matrix.m[5] + this.m[5];
this.m[0] = m11;
this.m[1] = m12;
this.m[2] = m21;
this.m[3] = m22;
this.m[4] = dx;
this.m[5] = dy;
return this;
},
/**
* Invert the matrix
* @method
* @memberof Kinetic.Transform.prototype
* @returns {Kinetic.Transform}
*/
invert: function() {
var d = 1 / (this.m[0] * this.m[3] - this.m[1] * this.m[2]);
var m0 = this.m[3] * d;
var m1 = -this.m[1] * d;
var m2 = -this.m[2] * d;
var m3 = this.m[0] * d;
var m4 = d * (this.m[2] * this.m[5] - this.m[3] * this.m[4]);
var m5 = d * (this.m[1] * this.m[4] - this.m[0] * this.m[5]);
this.m[0] = m0;
this.m[1] = m1;
this.m[2] = m2;
this.m[3] = m3;
this.m[4] = m4;
this.m[5] = m5;
return this;
},
/**
* return matrix
* @method
* @memberof Kinetic.Transform.prototype
*/
getMatrix: function() {
return this.m;
},
/**
* set to absolute position via translation
* @method
* @memberof Kinetic.Transform.prototype
* @returns {Kinetic.Transform}
* @author ericdrowell
*/
setAbsolutePosition: function(x, y) {
var m0 = this.m[0],
m1 = this.m[1],
m2 = this.m[2],
m3 = this.m[3],
m4 = this.m[4],
m5 = this.m[5],
yt = ((m0 * (y - m5)) - (m1 * (x - m4))) / ((m0 * m3) - (m1 * m2)),
xt = (x - m4 - (m2 * yt)) / m0;
return this.translate(xt, yt);
}
};
// CONSTANTS
var CANVAS = 'canvas',
CONTEXT_2D = '2d',
OBJECT_ARRAY = '[object Array]',
OBJECT_NUMBER = '[object Number]',
OBJECT_STRING = '[object String]',
PI_OVER_DEG180 = Math.PI / 180,
DEG180_OVER_PI = 180 / Math.PI,
HASH = '#',
EMPTY_STRING = '',
ZERO = '0',
KINETIC_WARNING = 'Kinetic warning: ',
KINETIC_ERROR = 'Kinetic error: ',
RGB_PAREN = 'rgb(',
COLORS = {
aqua: [0,255,255],
lime: [0,255,0],
silver: [192,192,192],
black: [0,0,0],
maroon: [128,0,0],
teal: [0,128,128],
blue: [0,0,255],
navy: [0,0,128],
white: [255,255,255],
fuchsia: [255,0,255],
olive:[128,128,0],
yellow: [255,255,0],
orange: [255,165,0],
gray: [128,128,128],
purple: [128,0,128],
green: [0,128,0],
red: [255,0,0],
pink: [255,192,203],
cyan: [0,255,255],
transparent: [255,255,255,0]
},
RGB_REGEX = /rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;
/**
* @namespace Util
* @memberof Kinetic
*/
Kinetic.Util = {
/*
* cherry-picked utilities from underscore.js
*/
_isElement: function(obj) {
return !!(obj && obj.nodeType == 1);
},
_isFunction: function(obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
},
_isObject: function(obj) {
return (!!obj && obj.constructor == Object);
},
_isArray: function(obj) {
return Object.prototype.toString.call(obj) == OBJECT_ARRAY;
},
_isNumber: function(obj) {
return Object.prototype.toString.call(obj) == OBJECT_NUMBER;
},
_isString: function(obj) {
return Object.prototype.toString.call(obj) == OBJECT_STRING;
},
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time. Normally, the throttled function will run
// as much as it can, without ever going more than once per `wait` duration;
// but if you'd like to disable the execution on the leading edge, pass
// `{leading: false}`. To disable execution on the trailing edge, ditto.
_throttle: function(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
options || (options = {});
var later = function() {
previous = options.leading === false ? 0 : new Date().getTime();
timeout = null;
result = func.apply(context, args);
context = args = null;
};
return function() {
var now = new Date().getTime();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
},
/*
* other utils
*/
_hasMethods: function(obj) {
var names = [],
key;
for(key in obj) {
if(this._isFunction(obj[key])) {
names.push(key);
}
}
return names.length > 0;
},
createCanvasElement: function() {
var canvas = Kinetic.document.createElement('canvas');
canvas.style = canvas.style || {};
return canvas;
},
isBrowser: function() {
return (typeof exports !== 'object');
},
_isInDocument: function(el) {
while(el = el.parentNode) {
if(el == Kinetic.document) {
return true;
}
}
return false;
},
_simplifyArray: function(arr) {
var retArr = [],
len = arr.length,
util = Kinetic.Util,
n, val;
for (n=0; n<len; n++) {
val = arr[n];
if (util._isNumber(val)) {
val = Math.round(val * 1000) / 1000;
}
else if (!util._isString(val)) {
val = val.toString();
}
retArr.push(val);
}
return retArr;
},
/*
* arg can be an image object or image data
*/
_getImage: function(arg, callback) {
var imageObj, canvas;
// if arg is null or undefined
if(!arg) {
callback(null);
}
// if arg is already an image object
else if(this._isElement(arg)) {
callback(arg);
}
// if arg is a string, then it's a data url
else if(this._isString(arg)) {
imageObj = new Kinetic.window.Image();
imageObj.onload = function() {
callback(imageObj);
};
imageObj.src = arg;
}
//if arg is an object that contains the data property, it's an image object
else if(arg.data) {
canvas = Kinetic.Util.createCanvasElement();
canvas.width = arg.width;
canvas.height = arg.height;
var _context = canvas.getContext(CONTEXT_2D);
_context.putImageData(arg, 0, 0);
this._getImage(canvas.toDataURL(), callback);
}
else {
callback(null);
}
},
_getRGBAString: function(obj) {
var red = obj.red || 0,
green = obj.green || 0,
blue = obj.blue || 0,
alpha = obj.alpha || 1;
return [
'rgba(',
red,
',',
green,
',',
blue,
',',
alpha,
')'
].join(EMPTY_STRING);
},
_rgbToHex: function(r, g, b) {
return ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
},
_hexToRgb: function(hex) {
hex = hex.replace(HASH, EMPTY_STRING);
var bigint = parseInt(hex, 16);
return {
r: (bigint >> 16) & 255,
g: (bigint >> 8) & 255,
b: bigint & 255
};
},
/**
* return random hex color
* @method
* @memberof Kinetic.Util.prototype
*/
getRandomColor: function() {
var randColor = (Math.random() * 0xFFFFFF << 0).toString(16);
while (randColor.length < 6) {
randColor = ZERO + randColor;
}
return HASH + randColor;
},
/**
* return value with default fallback
* @method
* @memberof Kinetic.Util.prototype
*/
get: function(val, def) {
if (val === undefined) {
return def;
}
else {
return val;
}
},
/**
* get RGB components of a color
* @method
* @memberof Kinetic.Util.prototype
* @param {String} color
* @example
* // each of the following examples return {r:0, g:0, b:255}<br>
* var rgb = Kinetic.Util.getRGB('blue');<br>
* var rgb = Kinetic.Util.getRGB('#0000ff');<br>
* var rgb = Kinetic.Util.getRGB('rgb(0,0,255)');
*/
getRGB: function(color) {
var rgb;
// color string
if (color in COLORS) {
rgb = COLORS[color];
return {
r: rgb[0],
g: rgb[1],
b: rgb[2]
};
}
// hex
else if (color[0] === HASH) {
return this._hexToRgb(color.substring(1));
}
// rgb string
else if (color.substr(0, 4) === RGB_PAREN) {
rgb = RGB_REGEX.exec(color.replace(/ /g,''));
return {
r: parseInt(rgb[1], 10),
g: parseInt(rgb[2], 10),
b: parseInt(rgb[3], 10)
};
}
// default
else {
return {
r: 0,
g: 0,
b: 0
};
}
},
// o1 takes precedence over o2
_merge: function(o1, o2) {
var retObj = this._clone(o2);
for(var key in o1) {
if(this._isObject(o1[key])) {
retObj[key] = this._merge(o1[key], retObj[key]);
}
else {
retObj[key] = o1[key];
}
}
return retObj;
},
cloneObject: function(obj) {
var retObj = {};
for(var key in obj) {
if(this._isObject(obj[key])) {
retObj[key] = this.cloneObject(obj[key]);
}
else if (this._isArray(obj[key])) {
retObj[key] = this.cloneArray(obj[key]);
} else {
retObj[key] = obj[key];
}
}
return retObj;
},
cloneArray: function(arr) {
return arr.slice(0);
},
_degToRad: function(deg) {
return deg * PI_OVER_DEG180;
},
_radToDeg: function(rad) {
return rad * DEG180_OVER_PI;
},
_capitalize: function(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
},
error: function(str) {
throw new Error(KINETIC_ERROR + str);
},
warn: function(str) {
/*
* IE9 on Windows7 64bit will throw a JS error
* if we don't use window.console in the conditional
*/
if(Kinetic.root.console && console.warn) {
console.warn(KINETIC_WARNING + str);
}
},
extend: function(c1, c2) {
for(var key in c2.prototype) {
if(!( key in c1.prototype)) {
c1.prototype[key] = c2.prototype[key];
}
}
},
/**
* adds methods to a constructor prototype
* @method
* @memberof Kinetic.Util.prototype
* @param {Function} constructor
* @param {Object} methods
*/
addMethods: function(constructor, methods) {
var key;
for (key in methods) {
constructor.prototype[key] = methods[key];
}
},
_getControlPoints: function(x0, y0, x1, y1, x2, y2, t) {
var d01 = Math.sqrt(Math.pow(x1 - x0, 2) + Math.pow(y1 - y0, 2)),
d12 = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)),
fa = t * d01 / (d01 + d12),
fb = t * d12 / (d01 + d12),
p1x = x1 - fa * (x2 - x0),
p1y = y1 - fa * (y2 - y0),
p2x = x1 + fb * (x2 - x0),
p2y = y1 + fb * (y2 - y0);
return [p1x ,p1y, p2x, p2y];
},
_expandPoints: function(p, tension) {
var len = p.length,
allPoints = [],
n, cp;
for (n=2; n<len-2; n+=2) {
cp = Kinetic.Util._getControlPoints(p[n-2], p[n-1], p[n], p[n+1], p[n+2], p[n+3], tension);
allPoints.push(cp[0]);
allPoints.push(cp[1]);
allPoints.push(p[n]);
allPoints.push(p[n+1]);
allPoints.push(cp[2]);
allPoints.push(cp[3]);
}
return allPoints;
},
_removeLastLetter: function(str) {
return str.substring(0, str.length - 1);
}
};
})();
;(function() {
// calculate pixel ratio
var canvas = Kinetic.Util.createCanvasElement(),
context = canvas.getContext('2d'),
// if using a mobile device, calculate the pixel ratio. Otherwise, just use
// 1. For desktop browsers, if the user has zoom enabled, it affects the pixel ratio
// and causes artifacts on the canvas. As of 02/26/2014, there doesn't seem to be a way
// to reliably calculate the browser zoom for modern browsers, which is why we just set
// the pixel ratio to 1 for desktops
_pixelRatio = Kinetic.UA.mobile ? (function() {
var devicePixelRatio = window.devicePixelRatio || 1,
backingStoreRatio = context.webkitBackingStorePixelRatio
|| context.mozBackingStorePixelRatio
|| context.msBackingStorePixelRatio
|| context.oBackingStorePixelRatio
|| context.backingStorePixelRatio
|| 1;
return devicePixelRatio / backingStoreRatio;
})() : 1;
/**
* Canvas Renderer constructor
* @constructor
* @abstract
* @memberof Kinetic
* @param {Number} width
* @param {Number} height
* @param {Number} pixelRatio KineticJS automatically handles pixel ratio adustments in order to render crisp drawings
* on all devices. Most desktops, low end tablets, and low end phones, have device pixel ratios
* of 1. Some high end tablets and phones, like iPhones and iPads (not the mini) have a device pixel ratio
* of 2. Some Macbook Pros, and iMacs also have a device pixel ratio of 2. Some high end Android devices have pixel
* ratios of 2 or 3. Some browsers like Firefox allow you to configure the pixel ratio of the viewport. Unless otherwise
* specificed, the pixel ratio will be defaulted to the actual device pixel ratio. You can override the device pixel
* ratio for special situations, or, if you don't want the pixel ratio to be taken into account, you can set it to 1.
*/
Kinetic.Canvas = function(config) {
this.init(config);
};
Kinetic.Canvas.prototype = {
init: function(config) {
config = config || {};
var pixelRatio = config.pixelRatio || Kinetic.pixelRatio || _pixelRatio;
this.pixelRatio = pixelRatio;
this._canvas = Kinetic.Util.createCanvasElement();
// set inline styles
this._canvas.style.padding = 0;
this._canvas.style.margin = 0;
this._canvas.style.border = 0;
this._canvas.style.background = 'transparent';
this._canvas.style.position = 'absolute';
this._canvas.style.top = 0;
this._canvas.style.left = 0;
},
/**
* get canvas context
* @method
* @memberof Kinetic.Canvas.prototype
* @returns {CanvasContext} context
*/
getContext: function() {
return this.context;
},
/**
* get pixel ratio
* @method
* @memberof Kinetic.Canvas.prototype
* @returns {Number} pixel ratio
*/
getPixelRatio: function() {
return this.pixelRatio;
},
/**
* get pixel ratio
* @method
* @memberof Kinetic.Canvas.prototype
* @param {Number} pixelRatio KineticJS automatically handles pixel ratio adustments in order to render crisp drawings
* on all devices. Most desktops, low end tablets, and low end phones, have device pixel ratios
* of 1. Some high end tablets and phones, like iPhones and iPads (not the mini) have a device pixel ratio
* of 2. Some Macbook Pros, and iMacs also have a device pixel ratio of 2. Some high end Android devices have pixel
* ratios of 2 or 3. Some browsers like Firefox allow you to configure the pixel ratio of the viewport. Unless otherwise
* specificed, the pixel ratio will be defaulted to the actual device pixel ratio. You can override the device pixel
* ratio for special situations, or, if you don't want the pixel ratio to be taken into account, you can set it to 1.
*/
setPixelRatio: function(pixelRatio) {
this.pixelRatio = pixelRatio;
this.setSize(this.getWidth(), this.getHeight());
},
/**
* set width
* @method
* @memberof Kinetic.Canvas.prototype
* @param {Number} width
*/
setWidth: function(width) {
// take into account pixel ratio
this.width = this._canvas.width = width * this.pixelRatio;
this._canvas.style.width = width + 'px';
},
/**
* set height
* @method
* @memberof Kinetic.Canvas.prototype
* @param {Number} height
*/
setHeight: function(height) {
// take into account pixel ratio
this.height = this._canvas.height = height * this.pixelRatio;
this._canvas.style.height = height + 'px';
},
/**
* get width
* @method
* @memberof Kinetic.Canvas.prototype
* @returns {Number} width
*/
getWidth: function() {
return this.width;
},
/**
* get height
* @method
* @memberof Kinetic.Canvas.prototype
* @returns {Number} height
*/
getHeight: function() {
return this.height;
},
/**
* set size
* @method
* @memberof Kinetic.Canvas.prototype
* @param {Number} width
* @param {Number} height
*/
setSize: function(width, height) {
this.setWidth(width);
this.setHeight(height);
},
/**
* to data url
* @method
* @memberof Kinetic.Canvas.prototype
* @param {String} mimeType
* @param {Number} quality between 0 and 1 for jpg mime types
* @returns {String} data url string
*/
toDataURL: function(mimeType, quality) {
try {
// If this call fails (due to browser bug, like in Firefox 3.6),
// then revert to previous no-parameter image/png behavior
return this._canvas.toDataURL(mimeType, quality);
}
catch(e) {
try {
return this._canvas.toDataURL();
}
catch(err) {
Kinetic.Util.warn('Unable to get data URL. ' + err.message);
return '';
}
}
}
};
Kinetic.SceneCanvas = function(config) {
config = config || {};
var width = config.width || 0,
height = config.height || 0;
Kinetic.Canvas.call(this, config);
this.context = new Kinetic.SceneContext(this);
this.setSize(width, height);
};
Kinetic.SceneCanvas.prototype = {
setWidth: function(width) {
var pixelRatio = this.pixelRatio,
_context = this.getContext()._context;
Kinetic.Canvas.prototype.setWidth.call(this, width);
_context.scale(pixelRatio, pixelRatio);
},
setHeight: function(height) {
var pixelRatio = this.pixelRatio,
_context = this.getContext()._context;
Kinetic.Canvas.prototype.setHeight.call(this, height);
_context.scale(pixelRatio, pixelRatio);
}
};
Kinetic.Util.extend(Kinetic.SceneCanvas, Kinetic.Canvas);
Kinetic.HitCanvas = function(config) {
config = config || {};
var width = config.width || 0,
height = config.height || 0;
Kinetic.Canvas.call(this, config);
this.context = new Kinetic.HitContext(this);
this.setSize(width, height);
};
Kinetic.Util.extend(Kinetic.HitCanvas, Kinetic.Canvas);
})();
;(function() {
var COMMA = ',',
OPEN_PAREN = '(',
CLOSE_PAREN = ')',
OPEN_PAREN_BRACKET = '([',
CLOSE_BRACKET_PAREN = '])',
SEMICOLON = ';',
DOUBLE_PAREN = '()',
// EMPTY_STRING = '',
EQUALS = '=',
// SET = 'set',
CONTEXT_METHODS = [
'arc',
'arcTo',
'beginPath',
'bezierCurveTo',
'clearRect',
'clip',
'closePath',
'createLinearGradient',
'createPattern',
'createRadialGradient',
'drawImage',
'fill',
'fillText',
'getImageData',
'createImageData',
'lineTo',
'moveTo',
'putImageData',
'quadraticCurveTo',
'rect',
'restore',
'rotate',
'save',
'scale',
'setLineDash',
'setTransform',
'stroke',
'strokeText',
'transform',
'translate'
];
/**
* Canvas Context constructor
* @constructor
* @abstract
* @memberof Kinetic
*/
Kinetic.Context = function(canvas) {
this.init(canvas);
};
Kinetic.Context.prototype = {
init: function(canvas) {
this.canvas = canvas;
this._context = canvas._canvas.getContext('2d');
if (Kinetic.enableTrace) {
this.traceArr = [];
this._enableTrace();
}
},
/**
* fill shape
* @method
* @memberof Kinetic.Context.prototype
* @param {Kinetic.Shape} shape
*/
fillShape: function(shape) {
if(shape.getFillEnabled()) {
this._fill(shape);
}
},
/**
* stroke shape
* @method
* @memberof Kinetic.Context.prototype
* @param {Kinetic.Shape} shape
*/
strokeShape: function(shape) {
if(shape.getStrokeEnabled()) {
this._stroke(shape);
}
},
/**
* fill then stroke
* @method
* @memberof Kinetic.Context.prototype
* @param {Kinetic.Shape} shape
*/
fillStrokeShape: function(shape) {
var fillEnabled = shape.getFillEnabled();
if(fillEnabled) {
this._fill(shape);
}
if(shape.getStrokeEnabled()) {
this._stroke(shape);
}
},
/**
* get context trace if trace is enabled
* @method
* @memberof Kinetic.Context.prototype
* @param {Boolean} relaxed if false, return strict context trace, which includes method names, method parameters
* properties, and property values. If true, return relaxed context trace, which only returns method names and
* properites.
* @returns {String}
*/
getTrace: function(relaxed) {
var traceArr = this.traceArr,
len = traceArr.length,
str = '',
n, trace, method, args;
for (n=0; n<len; n++) {
trace = traceArr[n];
method = trace.method;
// methods
if (method) {
args = trace.args;
str += method;
if (relaxed) {
str += DOUBLE_PAREN;
}
else {
if (Kinetic.Util._isArray(args[0])) {
str += OPEN_PAREN_BRACKET + args.join(COMMA) + CLOSE_BRACKET_PAREN;
}
else {
str += OPEN_PAREN + args.join(COMMA) + CLOSE_PAREN;
}
}
}
// properties
else {
str += trace.property;
if (!relaxed) {
str += EQUALS + trace.val;
}
}
str += SEMICOLON;
}
return str;
},
/**
* clear trace if trace is enabled
* @method
* @memberof Kinetic.Context.prototype
*/
clearTrace: function() {
this.traceArr = [];
},
_trace: function(str) {
var traceArr = this.traceArr,
len;
traceArr.push(str);
len = traceArr.length;
if (len >= Kinetic.traceArrMax) {
traceArr.shift();
}
},
/**
* reset canvas context transform
* @method
* @memberof Kinetic.Context.prototype
*/
reset: function() {
var pixelRatio = this.getCanvas().getPixelRatio();
this.setTransform(1 * pixelRatio, 0, 0, 1 * pixelRatio, 0, 0);
},
/**
* get canvas
* @method
* @memberof Kinetic.Context.prototype
* @returns {Kinetic.Canvas}
*/
getCanvas: function() {
return this.canvas;
},
/**
* clear canvas
* @method
* @memberof Kinetic.Context.prototype
* @param {Object} [bounds]
* @param {Number} [bounds.x]
* @param {Number} [bounds.y]
* @param {Number} [bounds.width]
* @param {Number} [bounds.height]
*/
clear: function(bounds) {
var canvas = this.getCanvas();
if (bounds) {
this.clearRect(bounds.x || 0, bounds.y || 0, bounds.width || 0, bounds.height || 0);
}
else {
this.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
}
},
_applyLineCap: function(shape) {
var lineCap = shape.getLineCap();
if(lineCap) {
this.setAttr('lineCap', lineCap);
}
},
_applyOpacity: function(shape) {
var absOpacity = shape.getAbsoluteOpacity();
if(absOpacity !== 1) {
this.setAttr('globalAlpha', absOpacity);
}
},
_applyLineJoin: function(shape) {
var lineJoin = shape.getLineJoin();
if(lineJoin) {
this.setAttr('lineJoin', lineJoin);
}
},
setAttr: function(attr, val) {
this._context[attr] = val;
},
// context pass through methods
arc: function() {
var a = arguments;
this._context.arc(a[0], a[1], a[2], a[3], a[4], a[5]);
},
beginPath: function() {
this._context.beginPath();
},
bezierCurveTo: function() {
var a = arguments;
this._context.bezierCurveTo(a[0], a[1], a[2], a[3], a[4], a[5]);
},
clearRect: function() {
var a = arguments;
this._context.clearRect(a[0], a[1], a[2], a[3]);
},
clip: function() {
this._context.clip();
},
closePath: function() {
this._context.closePath();
},
createImageData: function() {
var a = arguments;
if(a.length === 2) {
return this._context.createImageData(a[0], a[1]);
}
else if(a.length === 1) {
return this._context.createImageData(a[0]);
}
},
createLinearGradient: function() {
var a = arguments;
return this._context.createLinearGradient(a[0], a[1], a[2], a[3]);
},
createPattern: function() {
var a = arguments;
return this._context.createPattern(a[0], a[1]);
},
createRadialGradient: function() {
var a = arguments;
return this._context.createRadialGradient(a[0], a[1], a[2], a[3], a[4], a[5]);
},
drawImage: function() {
var a = arguments,
_context = this._context;
if(a.length === 3) {
_context.drawImage(a[0], a[1], a[2]);
}
else if(a.length === 5) {
_context.drawImage(a[0], a[1], a[2], a[3], a[4]);
}
else if(a.length === 9) {
_context.drawImage(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]);
}
},
fill: function() {
this._context.fill();
},
fillText: function() {
var a = arguments;
this._context.fillText(a[0], a[1], a[2]);
},
getImageData: function() {
var a = arguments;
return this._context.getImageData(a[0], a[1], a[2], a[3]);
},
lineTo: function() {
var a = arguments;
this._context.lineTo(a[0], a[1]);
},
moveTo: function() {
var a = arguments;
this._context.moveTo(a[0], a[1]);
},
rect: function() {
var a = arguments;
this._context.rect(a[0], a[1], a[2], a[3]);
},
putImageData: function() {
var a = arguments;
this._context.putImageData(a[0], a[1], a[2]);
},
quadraticCurveTo: function() {
var a = arguments;
this._context.quadraticCurveTo(a[0], a[1], a[2], a[3]);
},
restore: function() {
this._context.restore();
},
rotate: function() {
var a = arguments;
this._context.rotate(a[0]);
},
save: function() {
this._context.save();
},
scale: function() {
var a = arguments;
this._context.scale(a[0], a[1]);
},
setLineDash: function() {
var a = arguments,
_context = this._context;
// works for Chrome and IE11
if(this._context.setLineDash) {
_context.setLineDash(a[0]);
}
// verified that this works in firefox
else if('mozDash' in _context) {
_context.mozDash = a[0];
}
// does not currently work for Safari
else if('webkitLineDash' in _context) {
_context.webkitLineDash = a[0];
}
// no support for IE9 and IE10
},
setTransform: function() {
var a = arguments;
this._context.setTransform(a[0], a[1], a[2], a[3], a[4], a[5]);
},
stroke: function() {
this._context.stroke();
},
strokeText: function() {
var a = arguments;
this._context.strokeText(a[0], a[1], a[2]);
},
transform: function() {
var a = arguments;
this._context.transform(a[0], a[1], a[2], a[3], a[4], a[5]);
},
translate: function() {
var a = arguments;
this._context.translate(a[0], a[1]);
},
_enableTrace: function() {
var that = this,
len = CONTEXT_METHODS.length,
_simplifyArray = Kinetic.Util._simplifyArray,
origSetter = this.setAttr,
n, args;
// to prevent creating scope function at each loop
var func = function(methodName) {
var origMethod = that[methodName],
ret;
that[methodName] = function() {
args = _simplifyArray(Array.prototype.slice.call(arguments, 0));
ret = origMethod.apply(that, arguments);
that._trace({
method: methodName,
args: args
});
return ret;
};
};
// methods
for (n=0; n<len; n++) {
func(CONTEXT_METHODS[n]);
}
// attrs
that.setAttr = function() {
origSetter.apply(that, arguments);
that._trace({
property: arguments[0],
val: arguments[1]
});
};
}
};
Kinetic.SceneContext = function(canvas) {
Kinetic.Context.call(this, canvas);
};
Kinetic.SceneContext.prototype = {
_fillColor: function(shape) {
var fill = shape.fill()
|| Kinetic.Util._getRGBAString({
red: shape.fillRed(),
green: shape.fillGreen(),
blue: shape.fillBlue(),
alpha: shape.fillAlpha()
});
this.setAttr('fillStyle', fill);
shape._fillFunc(this);
},
_fillPattern: function(shape) {
var fillPatternImage = shape.getFillPatternImage(),
fillPatternX = shape.getFillPatternX(),
fillPatternY = shape.getFillPatternY(),
fillPatternScale = shape.getFillPatternScale(),
fillPatternRotation = Kinetic.getAngle(shape.getFillPatternRotation()),
fillPatternOffset = shape.getFillPatternOffset(),
fillPatternRepeat = shape.getFillPatternRepeat();
if(fillPatternX || fillPatternY) {
this.translate(fillPatternX || 0, fillPatternY || 0);
}
if(fillPatternRotation) {
this.rotate(fillPatternRotation);
}
if(fillPatternScale) {
this.scale(fillPatternScale.x, fillPatternScale.y);
}
if(fillPatternOffset) {
this.translate(-1 * fillPatternOffset.x, -1 * fillPatternOffset.y);
}
this.setAttr('fillStyle', this.createPattern(fillPatternImage, fillPatternRepeat || 'repeat'));
this.fill();
},
_fillLinearGradient: function(shape) {
var start = shape.getFillLinearGradientStartPoint(),
end = shape.getFillLinearGradientEndPoint(),
colorStops = shape.getFillLinearGradientColorStops(),
grd = this.createLinearGradient(start.x, start.y, end.x, end.y);
if (colorStops) {
// build color stops
for(var n = 0; n < colorStops.length; n += 2) {
grd.addColorStop(colorStops[n], colorStops[n + 1]);
}
this.setAttr('fillStyle', grd);
this.fill();
}
},
_fillRadialGradient: function(shape) {
var start = shape.getFillRadialGradientStartPoint(),
end = shape.getFillRadialGradientEndPoint(),
startRadius = shape.getFillRadialGradientStartRadius(),
endRadius = shape.getFillRadialGradientEndRadius(),
colorStops = shape.getFillRadialGradientColorStops(),
grd = this.createRadialGradient(start.x, start.y, startRadius, end.x, end.y, endRadius);
// build color stops
for(var n = 0; n < colorStops.length; n += 2) {
grd.addColorStop(colorStops[n], colorStops[n + 1]);
}
this.setAttr('fillStyle', grd);
this.fill();
},
_fill: function(shape) {
var hasColor = shape.fill() || shape.fillRed() || shape.fillGreen() || shape.fillBlue(),
hasPattern = shape.getFillPatternImage(),
hasLinearGradient = shape.getFillLinearGradientColorStops(),
hasRadialGradient = shape.getFillRadialGradientColorStops(),
fillPriority = shape.getFillPriority();
// priority fills
if(hasColor && fillPriority === 'color') {
this._fillColor(shape);
}
else if(hasPattern && fillPriority === 'pattern') {
this._fillPattern(shape);
}
else if(hasLinearGradient && fillPriority === 'linear-gradient') {
this._fillLinearGradient(shape);
}
else if(hasRadialGradient && fillPriority === 'radial-gradient') {
this._fillRadialGradient(shape);
}
// now just try and fill with whatever is available
else if(hasColor) {
this._fillColor(shape);
}
else if(hasPattern) {
this._fillPattern(shape);
}
else if(hasLinearGradient) {
this._fillLinearGradient(shape);
}
else if(hasRadialGradient) {
this._fillRadialGradient(shape);
}
},
_stroke: function(shape) {
var dash = shape.dash(),
strokeScaleEnabled = shape.getStrokeScaleEnabled();
if(shape.hasStroke()) {
if (!strokeScaleEnabled) {
this.save();
this.setTransform(1, 0, 0, 1, 0, 0);
}
this._applyLineCap(shape);
if(dash && shape.dashEnabled()) {
this.setLineDash(dash);
}
this.setAttr('lineWidth', shape.strokeWidth());
this.setAttr('strokeStyle', shape.stroke()
|| Kinetic.Util._getRGBAString({
red: shape.strokeRed(),
green: shape.strokeGreen(),
blue: shape.strokeBlue(),
alpha: shape.strokeAlpha()
}));
shape._strokeFunc(this);
if (!strokeScaleEnabled) {
this.restore();
}
}
},
_applyShadow: function(shape) {
var util = Kinetic.Util,
absOpacity = shape.getAbsoluteOpacity(),
color = util.get(shape.getShadowColor(), 'black'),
blur = util.get(shape.getShadowBlur(), 5),
shadowOpacity = util.get(shape.getShadowOpacity(), 1),
offset = util.get(shape.getShadowOffset(), {
x: 0,
y: 0
});
if(shadowOpacity) {
this.setAttr('globalAlpha', shadowOpacity * absOpacity);
}
this.setAttr('shadowColor', color);
this.setAttr('shadowBlur', blur);
this.setAttr('shadowOffsetX', offset.x);
this.setAttr('shadowOffsetY', offset.y);
}
};
Kinetic.Util.extend(Kinetic.SceneContext, Kinetic.Context);
Kinetic.HitContext = function(canvas) {
Kinetic.Context.call(this, canvas);
};
Kinetic.HitContext.prototype = {
_fill: function(shape) {
this.save();
this.setAttr('fillStyle', shape.colorKey);
shape._fillFuncHit(this);
this.restore();
},
_stroke: function(shape) {
if(shape.hasStroke()) {
this._applyLineCap(shape);
this.setAttr('lineWidth', shape.strokeWidth());
this.setAttr('strokeStyle', shape.colorKey);
shape._strokeFuncHit(this);
}
}
};
Kinetic.Util.extend(Kinetic.HitContext, Kinetic.Context);
})();
;/*jshint unused:false */
(function() {
// CONSTANTS
var ABSOLUTE_OPACITY = 'absoluteOpacity',
ABSOLUTE_TRANSFORM = 'absoluteTransform',
ADD = 'add',
B = 'b',
BEFORE = 'before',
BLACK = 'black',
CHANGE = 'Change',
CHILDREN = 'children',
DEG = 'Deg',
DOT = '.',
EMPTY_STRING = '',
G = 'g',
GET = 'get',
HASH = '#',
ID = 'id',
KINETIC = 'kinetic',
LISTENING = 'listening',
MOUSEENTER = 'mouseenter',
MOUSELEAVE = 'mouseleave',
NAME = 'name',
OFF = 'off',
ON = 'on',
PRIVATE_GET = '_get',
R = 'r',
RGB = 'RGB',
SET = 'set',
SHAPE = 'Shape',
SPACE = ' ',
STAGE = 'Stage',
TRANSFORM = 'transform',
UPPER_B = 'B',
UPPER_G = 'G',
UPPER_HEIGHT = 'Height',
UPPER_R = 'R',
UPPER_WIDTH = 'Width',
UPPER_X = 'X',
UPPER_Y = 'Y',
VISIBLE = 'visible',
X = 'x',
Y = 'y';
Kinetic.Factory = {
addGetterSetter: function(constructor, attr, def, validator, after) {
this.addGetter(constructor, attr, def);
this.addSetter(constructor, attr, validator, after);
this.addOverloadedGetterSetter(constructor, attr);
},
addGetter: function(constructor, attr, def) {
var method = GET + Kinetic.Util._capitalize(attr);
constructor.prototype[method] = function() {
var val = this.attrs[attr];
return val === undefined ? def : val;
};
},
addSetter: function(constructor, attr, validator, after) {
var method = SET + Kinetic.Util._capitalize(attr);
constructor.prototype[method] = function(val) {
if (validator) {
val = validator.call(this, val);
}
this._setAttr(attr, val);
if (after) {
after.call(this);
}
return this;
};
},
addComponentsGetterSetter: function(constructor, attr, components, validator, after) {
var len = components.length,
capitalize = Kinetic.Util._capitalize,
getter = GET + capitalize(attr),
setter = SET + capitalize(attr),
n, component;
// getter
constructor.prototype[getter] = function() {
var ret = {};
for (n=0; n<len; n++) {
component = components[n];
ret[component] = this.getAttr(attr + capitalize(component));
}
return ret;
};
// setter
constructor.prototype[setter] = function(val) {
var oldVal = this.attrs[attr],
key;
if (validator) {
val = validator.call(this, val);
}
for (key in val) {
this._setAttr(attr + capitalize(key), val[key]);
}
this._fireChangeEvent(attr, oldVal, val);
if (after) {
after.call(this);
}
return this;
};
this.addOverloadedGetterSetter(constructor, attr);
},
addOverloadedGetterSetter: function(constructor, attr) {
var capitalizedAttr = Kinetic.Util._capitalize(attr),
setter = SET + capitalizedAttr,
getter = GET + capitalizedAttr;
constructor.prototype[attr] = function() {
// setting
if (arguments.length) {
this[setter](arguments[0]);
return this;
}
// getting
else {
return this[getter]();
}
};
},
backCompat: function(constructor, methods) {
var key;
for (key in methods) {
constructor.prototype[key] = constructor.prototype[methods[key]];
}
},
afterSetFilter: function() {
this._filterUpToDate = false;
}
};
Kinetic.Validators = {
RGBComponent: function(val) {
if (val > 255) {
return 255;
}
else if (val < 0) {
return 0;
}
else {
return Math.round(val);
}
},
alphaComponent: function(val) {
if (val > 1) {
return 1;
}
// chrome does not honor alpha values of 0
else if (val < 0.0001) {
return 0.0001;
}
else {
return val;
}
}
};
})();;(function() {
// CONSTANTS
var ABSOLUTE_OPACITY = 'absoluteOpacity',
ABSOLUTE_TRANSFORM = 'absoluteTransform',
BEFORE = 'before',
CHANGE = 'Change',
CHILDREN = 'children',
DOT = '.',
EMPTY_STRING = '',
GET = 'get',
ID = 'id',
KINETIC = 'kinetic',
LISTENING = 'listening',
MOUSEENTER = 'mouseenter',
MOUSELEAVE = 'mouseleave',
NAME = 'name',
SET = 'set',
SHAPE = 'Shape',
SPACE = ' ',
STAGE = 'stage',
TRANSFORM = 'transform',
UPPER_STAGE = 'Stage',
VISIBLE = 'visible',
CLONE_BLACK_LIST = ['id'],
TRANSFORM_CHANGE_STR = [
'xChange.kinetic',
'yChange.kinetic',
'scaleXChange.kinetic',
'scaleYChange.kinetic',
'skewXChange.kinetic',
'skewYChange.kinetic',
'rotationChange.kinetic',
'offsetXChange.kinetic',
'offsetYChange.kinetic',
'transformsEnabledChange.kinetic'
].join(SPACE);
Kinetic.Util.addMethods(Kinetic.Node, {
_init: function(config) {
var that = this;
this._id = Kinetic.idCounter++;
this.eventListeners = {};
this.attrs = {};
this._cache = {};
this._filterUpToDate = false;
this.setAttrs(config);
// event bindings for cache handling
this.on(TRANSFORM_CHANGE_STR, function() {
this._clearCache(TRANSFORM);
that._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM);
});
this.on('visibleChange.kinetic', function() {
that._clearSelfAndDescendantCache(VISIBLE);
});
this.on('listeningChange.kinetic', function() {
that._clearSelfAndDescendantCache(LISTENING);
});
this.on('opacityChange.kinetic', function() {
that._clearSelfAndDescendantCache(ABSOLUTE_OPACITY);
});
},
_clearCache: function(attr){
if (attr) {
delete this._cache[attr];
}
else {
this._cache = {};
}
},
_getCache: function(attr, privateGetter){
var cache = this._cache[attr];
// if not cached, we need to set it using the private getter method.
if (cache === undefined) {
this._cache[attr] = privateGetter.call(this);
}
return this._cache[attr];
},
/*
* when the logic for a cached result depends on ancestor propagation, use this
* method to clear self and children cache
*/
_clearSelfAndDescendantCache: function(attr) {
this._clearCache(attr);
if (this.children) {
this.getChildren().each(function(node) {
node._clearSelfAndDescendantCache(attr);
});
}
},
/**
* clear cached canvas
* @method
* @memberof Kinetic.Node.prototype
* @returns {Kinetic.Node}
* @example
* node.clearCache();
*/
clearCache: function() {
delete this._cache.canvas;
this._filterUpToDate = false;
return this;
},
/**
* cache node to improve drawing performance, apply filters, or create more accurate
* hit regions
* @method
* @memberof Kinetic.Node.prototype
* @param {Object} config
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.drawBorder] when set to true, a red border will be drawn around the cached
* region for debugging purposes
* @returns {Kinetic.Node}
* @example
* // cache a shape with the x,y position of the bounding box at the center and<br>
* // the width and height of the bounding box equal to the width and height of<br>
* // the shape obtained from shape.width() and shape.height()<br>
* image.cache();<br><br>
*
* // cache a node and define the bounding box position and size<br>
* node.cache({<br>
* x: -30,<br>
* y: -30,<br>
* width: 100,<br>
* height: 200<br>
* });<br><br>
*
* // cache a node and draw a red border around the bounding box<br>
* // for debugging purposes<br>
* node.cache({<br>
* x: -30,<br>
* y: -30,<br>
* width: 100,<br>
* height: 200,<br>
* drawBorder: true<br>
* });
*/
cache: function(config) {
var conf = config || {},
x = conf.x || 0,
y = conf.y || 0,
width = conf.width || this.width(),
height = conf.height || this.height(),
drawBorder = conf.drawBorder || false,
layer = this.getLayer();
if (width === 0 || height === 0) {
Kinetic.Util.warn('Width or height of caching configuration equals 0. Cache is ignored.');
return;
}
var cachedSceneCanvas = new Kinetic.SceneCanvas({
pixelRatio: 1,
width: width,
height: height
}),
cachedFilterCanvas = new Kinetic.SceneCanvas({
pixelRatio: 1,
width: width,
height: height
}),
cachedHitCanvas = new Kinetic.HitCanvas({
width: width,
height: height
}),
origTransEnabled = this.transformsEnabled(),
origX = this.x(),
origY = this.y(),
sceneContext = cachedSceneCanvas.getContext(),
hitContext = cachedHitCanvas.getContext();
this.clearCache();
sceneContext.save();
hitContext.save();
// this will draw a red border around the cached box for
// debugging purposes
if (drawBorder) {
sceneContext.save();
sceneContext.beginPath();
sceneContext.rect(0, 0, width, height);
sceneContext.closePath();
sceneContext.setAttr('strokeStyle', 'red');
sceneContext.setAttr('lineWidth', 5);
sceneContext.stroke();
sceneContext.restore();
}
sceneContext.translate(x * -1, y * -1);
hitContext.translate(x * -1, y * -1);
if (this.nodeType === 'Shape') {
sceneContext.translate(this.x() * -1, this.y() * -1);
hitContext.translate(this.x() * -1, this.y() * -1);
}
this.drawScene(cachedSceneCanvas, this);
this.drawHit(cachedHitCanvas, this);
sceneContext.restore();
hitContext.restore();
this._cache.canvas = {
scene: cachedSceneCanvas,
filter: cachedFilterCanvas,
hit: cachedHitCanvas
};
return this;
},
_drawCachedSceneCanvas: function(context) {
context.save();
this.getLayer()._applyTransform(this, context);
context.drawImage(this._getCachedSceneCanvas()._canvas, 0, 0);
context.restore();
},
_getCachedSceneCanvas: function() {
var filters = this.filters(),
cachedCanvas = this._cache.canvas,
sceneCanvas = cachedCanvas.scene,
filterCanvas = cachedCanvas.filter,
filterContext = filterCanvas.getContext(),
len, imageData, n, filter;
if (filters) {
if (!this._filterUpToDate) {
try {
len = filters.length;
filterContext.clear();
// copy cached canvas onto filter context
filterContext.drawImage(sceneCanvas._canvas, 0, 0);
imageData = filterContext.getImageData(0, 0, filterCanvas.getWidth(), filterCanvas.getHeight());
// apply filters to filter context
for (n=0; n<len; n++) {
filter = filters[n];
filter.call(this, imageData);
filterContext.putImageData(imageData, 0, 0);
}
}
catch(e) {
Kinetic.Util.warn('Unable to apply filter. ' + e.message);
}
this._filterUpToDate = true;
}
return filterCanvas;
}
else {
return sceneCanvas;
}
},
_drawCachedHitCanvas: function(context) {
var cachedCanvas = this._cache.canvas,
hitCanvas = cachedCanvas.hit;
context.save();
this.getLayer()._applyTransform(this, context);
context.drawImage(hitCanvas._canvas, 0, 0);
context.restore();
},
/**
* bind events to the node. KineticJS supports mouseover, mousemove,
* mouseout, mouseenter, mouseleave, mousedown, mouseup, click, dblclick, touchstart, touchmove,
* touchend, tap, dbltap, dragstart, dragmove, and dragend events. The Kinetic Stage supports
* contentMouseover, contentMousemove, contentMouseout, contentMousedown, contentMouseup,
* contentClick, contentDblclick, contentTouchstart, contentTouchmove, contentTouchend, contentTap,
* and contentDblTap. Pass in a string of events delimmited by a space to bind multiple events at once
* such as 'mousedown mouseup mousemove'. Include a namespace to bind an
* event by name such as 'click.foobar'.
* @method
* @memberof Kinetic.Node.prototype
* @param {String} evtStr e.g. 'click', 'mousedown touchstart', 'mousedown.foo touchstart.foo'
* @param {Function} handler The handler function is passed an event object
* @returns {Kinetic.Node}
* @example
* // add click listener<br>
* node.on('click', function() {<br>
* console.log('you clicked me!');<br>
* });<br><br>
*
* // get the target node<br>
* node.on('click', function(evt) {<br>
* console.log(evt.target);<br>
* });<br><br>
*
* // stop event propagation<br>
* node.on('click', function(evt) {<br>
* evt.cancelBubble = true;<br>
* });<br><br>
*
* // bind multiple listeners<br>
* node.on('click touchstart', function() {<br>
* console.log('you clicked/touched me!');<br>
* });<br><br>
*
* // namespace listener<br>
* node.on('click.foo', function() {<br>
* console.log('you clicked/touched me!');<br>
* });<br><br>
*
* // get the event type<br>
* node.on('click tap', function(evt) {<br>
* var eventType = evt.type;<br>
* });<br><br>
*
* // get native event object<br>
* node.on('click tap', function(evt) {<br>
* var nativeEvent = evt.evt;<br>
* });<br><br>
*
* // for change events, get the old and new val<br>
* node.on('xChange', function(evt) {<br>
* var oldVal = evt.oldVal;<br>
* var newVal = evt.newVal;<br>
* });
*/
on: function(evtStr, handler) {
var events = evtStr.split(SPACE),
len = events.length,
n, event, parts, baseEvent, name;
/*
* loop through types and attach event listeners to
* each one. eg. 'click mouseover.namespace mouseout'
* will create three event bindings
*/
for(n = 0; n < len; n++) {
event = events[n];
parts = event.split(DOT);
baseEvent = parts[0];
name = parts[1] || EMPTY_STRING;
// create events array if it doesn't exist
if(!this.eventListeners[baseEvent]) {
this.eventListeners[baseEvent] = [];
}
this.eventListeners[baseEvent].push({
name: name,
handler: handler
});
// NOTE: this flag is set to true when any event handler is added, even non
// mouse or touch gesture events. This improves performance for most
// cases where users aren't using events, but is still very light weight.
// To ensure perfect accuracy, devs can explicitly set listening to false.
/*
if (name !== KINETIC) {
this._listeningEnabled = true;
this._clearSelfAndAncestorCache(LISTENING_ENABLED);
}
*/
}
return this;
},
/**
* remove event bindings from the node. Pass in a string of
* event types delimmited by a space to remove multiple event
* bindings at once such as 'mousedown mouseup mousemove'.
* include a namespace to remove an event binding by name
* such as 'click.foobar'. If you only give a name like '.foobar',
* all events in that namespace will be removed.
* @method
* @memberof Kinetic.Node.prototype
* @param {String} evtStr e.g. 'click', 'mousedown touchstart', '.foobar'
* @returns {Kinetic.Node}
* @example
* // remove listener<br>
* node.off('click');<br><br>
*
* // remove multiple listeners<br>
* node.off('click touchstart');<br><br>
*
* // remove listener by name<br>
* node.off('click.foo');
*/
off: function(evtStr) {
var events = evtStr.split(SPACE),
len = events.length,
n, t, event, parts, baseEvent, name;
for(n = 0; n < len; n++) {
event = events[n];
parts = event.split(DOT);
baseEvent = parts[0];
name = parts[1];
if(baseEvent) {
if(this.eventListeners[baseEvent]) {
this._off(baseEvent, name);
}
}
else {
for(t in this.eventListeners) {
this._off(t, name);
}
}
}
return this;
},
// some event aliases for third party integration like HammerJS
dispatchEvent: function(evt) {
var e = {
target: this,
type: evt.type,
evt: evt
};
this.fire(evt.type, e);
},
addEventListener: function(type, handler) {
// we to pass native event to handler
this.on(type, function(evt){
handler.call(this, evt.evt);
});
},
/**
* remove self from parent, but don't destroy
* @method
* @memberof Kinetic.Node.prototype
* @returns {Kinetic.Node}
* @example
* node.remove();
*/
remove: function() {
var parent = this.getParent();
if(parent && parent.children) {
parent.children.splice(this.index, 1);
parent._setChildrenIndices();
delete this.parent;
}
// every cached attr that is calculated via node tree
// traversal must be cleared when removing a node
this._clearSelfAndDescendantCache(STAGE);
this._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM);
this._clearSelfAndDescendantCache(VISIBLE);
this._clearSelfAndDescendantCache(LISTENING);
this._clearSelfAndDescendantCache(ABSOLUTE_OPACITY);
return this;
},
/**
* remove and destroy self
* @method
* @memberof Kinetic.Node.prototype
* @example
* node.destroy();
*/
destroy: function() {
// remove from ids and names hashes
Kinetic._removeId(this.getId());
Kinetic._removeName(this.getName(), this._id);
this.remove();
},
/**
* get attr
* @method
* @memberof Kinetic.Node.prototype
* @param {String} attr
* @returns {Integer|String|Object|Array}
* @example
* var x = node.getAttr('x');
*/
getAttr: function(attr) {
var method = GET + Kinetic.Util._capitalize(attr);
if(Kinetic.Util._isFunction(this[method])) {
return this[method]();
}
// otherwise get directly
else {
return this.attrs[attr];
}
},
/**
* get ancestors
* @method
* @memberof Kinetic.Node.prototype
* @returns {Kinetic.Collection}
* @example
* shape.getAncestors().each(function(node) {
* console.log(node.getId());
* })
*/
getAncestors: function() {
var parent = this.getParent(),
ancestors = new Kinetic.Collection();
while (parent) {
ancestors.push(parent);
parent = parent.getParent();
}
return ancestors;
},
/**
* get attrs object literal
* @method
* @memberof Kinetic.Node.prototype
* @returns {Object}
*/
getAttrs: function() {
return this.attrs || {};
},
/**
* set multiple attrs at once using an object literal
* @method
* @memberof Kinetic.Node.prototype
* @param {Object} config object containing key value pairs
* @returns {Kinetic.Node}
* @example
* node.setAttrs({<br>
* x: 5,<br>
* fill: 'red'<br>
* });<br>
*/
setAttrs: function(config) {
var key, method;
if(config) {
for(key in config) {
if (key === CHILDREN) {
}
else {
method = SET + Kinetic.Util._capitalize(key);
// use setter if available
if(Kinetic.Util._isFunction(this[method])) {
this[method](config[key]);
}
// otherwise set directly
else {
this._setAttr(key, config[key]);
}
}
}
}
return this;
},
/**
* determine if node is listening for events by taking into account ancestors.
*
* Parent | Self | isListening
* listening | listening |
* ----------+-----------+------------
* T | T | T
* T | F | F
* F | T | T
* F | F | F
* ----------+-----------+------------
* T | I | T
* F | I | F
* I | I | T
*
* @method
* @memberof Kinetic.Node.prototype
* @returns {Boolean}
*/
isListening: function() {
return this._getCache(LISTENING, this._isListening);
},
_isListening: function() {
var listening = this.getListening(),
parent = this.getParent();
// the following conditions are a simplification of the truth table above.
// please modify carefully
if (listening === 'inherit') {
if (parent) {
return parent.isListening();
}
else {
return true;
}
}
else {
return listening;
}
},
/**
* determine if node is visible by taking into account ancestors.
*
* Parent | Self | isVisible
* visible | visible |
* ----------+-----------+------------
* T | T | T
* T | F | F
* F | T | T
* F | F | F
* ----------+-----------+------------
* T | I | T
* F | I | F
* I | I | T
* @method
* @memberof Kinetic.Node.prototype
* @returns {Boolean}
*/
isVisible: function() {
return this._getCache(VISIBLE, this._isVisible);
},
_isVisible: function() {
var visible = this.getVisible(),
parent = this.getParent();
// the following conditions are a simplification of the truth table above.
// please modify carefully
if (visible === 'inherit') {
if (parent) {
return parent.isVisible();
}
else {
return true;
}
}
else {
return visible;
}
},
/**
* determine if listening is enabled by taking into account descendants. If self or any children
* have _isListeningEnabled set to true, then self also has listening enabled.
* @method
* @memberof Kinetic.Node.prototype
* @returns {Boolean}
*/
shouldDrawHit: function() {
var layer = this.getLayer();
return layer && layer.hitGraphEnabled() && this.isListening() && this.isVisible() && !Kinetic.isDragging();
},
/**
* show node
* @method
* @memberof Kinetic.Node.prototype
* @returns {Kinetic.Node}
*/
show: function() {
this.setVisible(true);
return this;
},
/**
* hide node. Hidden nodes are no longer detectable
* @method
* @memberof Kinetic.Node.prototype
* @returns {Kinetic.Node}
*/
hide: function() {
this.setVisible(false);
return this;
},
/**
* get zIndex relative to the node's siblings who share the same parent
* @method
* @memberof Kinetic.Node.prototype
* @returns {Integer}
*/
getZIndex: function() {
return this.index || 0;
},
/**
* get absolute z-index which takes into account sibling
* and ancestor indices
* @method
* @memberof Kinetic.Node.prototype
* @returns {Integer}
*/
getAbsoluteZIndex: function() {
var depth = this.getDepth(),
that = this,
index = 0,
nodes, len, n, child;
function addChildren(children) {
nodes = [];
len = children.length;
for(n = 0; n < len; n++) {
child = children[n];
index++;
if(child.nodeType !== SHAPE) {
nodes = nodes.concat(child.getChildren().toArray());
}
if(child._id === that._id) {
n = len;
}
}
if(nodes.length > 0 && nodes[0].getDepth() <= depth) {
addChildren(nodes);
}
}
if(that.nodeType !== UPPER_STAGE) {
addChildren(that.getStage().getChildren());
}
return index;
},
/**
* get node depth in node tree. Returns an integer.<br><br>
* e.g. Stage depth will always be 0. Layers will always be 1. Groups and Shapes will always
* be >= 2
* @method
* @memberof Kinetic.Node.prototype
* @returns {Integer}
*/
getDepth: function() {
var depth = 0,
parent = this.parent;
while(parent) {
depth++;
parent = parent.parent;
}
return depth;
},
setPosition: function(pos) {
this.setX(pos.x);
this.setY(pos.y);
return this;
},
getPosition: function() {
return {
x: this.getX(),
y: this.getY()
};
},
/**
* get absolute position relative to the top left corner of the stage container div
* @method
* @memberof Kinetic.Node.prototype
* @returns {Object}
*/
getAbsolutePosition: function() {
var absoluteMatrix = this.getAbsoluteTransform().getMatrix(),
absoluteTransform = new Kinetic.Transform(),
offset = this.offset();
// clone the matrix array
absoluteTransform.m = absoluteMatrix.slice();
absoluteTransform.translate(offset.x, offset.y);
return absoluteTransform.getTranslation();
},
/**
* set absolute position
* @method
* @memberof Kinetic.Node.prototype
* @param {Object} pos
* @param {Number} pos.x
* @param {Number} pos.y
* @returns {Kinetic.Node}
*/
setAbsolutePosition: function(pos) {
var origTrans = this._clearTransform(),
it;
// don't clear translation
this.attrs.x = origTrans.x;
this.attrs.y = origTrans.y;
delete origTrans.x;
delete origTrans.y;
// unravel transform
it = this.getAbsoluteTransform();
it.invert();
it.translate(pos.x, pos.y);
pos = {
x: this.attrs.x + it.getTranslation().x,
y: this.attrs.y + it.getTranslation().y
};
this.setPosition({x:pos.x, y:pos.y});
this._setTransform(origTrans);
return this;
},
_setTransform: function(trans) {
var key;
for(key in trans) {
this.attrs[key] = trans[key];
}
this._clearCache(TRANSFORM);
this._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM);
},
_clearTransform: function() {
var trans = {
x: this.getX(),
y: this.getY(),
rotation: this.getRotation(),
scaleX: this.getScaleX(),
scaleY: this.getScaleY(),
offsetX: this.getOffsetX(),
offsetY: this.getOffsetY(),
skewX: this.getSkewX(),
skewY: this.getSkewY()
};
this.attrs.x = 0;
this.attrs.y = 0;
this.attrs.rotation = 0;
this.attrs.scaleX = 1;
this.attrs.scaleY = 1;
this.attrs.offsetX = 0;
this.attrs.offsetY = 0;
this.attrs.skewX = 0;
this.attrs.skewY = 0;
this._clearCache(TRANSFORM);
this._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM);
// return original transform
return trans;
},
/**
* move node by an amount relative to its current position
* @method
* @memberof Kinetic.Node.prototype
* @param {Object} change
* @param {Number} change.x
* @param {Number} change.y
* @returns {Kinetic.Node}
* @example
* // move node in x direction by 1px and y direction by 2px<br>
* node.move({<br>
* x: 1,<br>
* y: 2)<br>
* });
*/
move: function(change) {
var changeX = change.x,
changeY = change.y,
x = this.getX(),
y = this.getY();
if(changeX !== undefined) {
x += changeX;
}
if(changeY !== undefined) {
y += changeY;
}
this.setPosition({x:x, y:y});
return this;
},
_eachAncestorReverse: function(func, top) {
var family = [],
parent = this.getParent(),
len, n;
// if top node is defined, and this node is top node,
// there's no need to build a family tree. just execute
// func with this because it will be the only node
if (top && top._id === this._id) {
func(this);
return true;
}
family.unshift(this);
while(parent && (!top || parent._id !== top._id)) {
family.unshift(parent);
parent = parent.parent;
}
len = family.length;
for(n = 0; n < len; n++) {
func(family[n]);
}
},
/**
* rotate node by an amount in degrees relative to its current rotation
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} theta
* @returns {Kinetic.Node}
*/
rotate: function(theta) {
this.setRotation(this.getRotation() + theta);
return this;
},
/**
* move node to the top of its siblings
* @method
* @memberof Kinetic.Node.prototype
* @returns {Boolean}
*/
moveToTop: function() {
if (!this.parent) {
Kinetic.Util.warn('Node has no parent. moveToTop function is ignored.');
return;
}
var index = this.index;
this.parent.children.splice(index, 1);
this.parent.children.push(this);
this.parent._setChildrenIndices();
return true;
},
/**
* move node up
* @method
* @memberof Kinetic.Node.prototype
* @returns {Boolean}
*/
moveUp: function() {
if (!this.parent) {
Kinetic.Util.warn('Node has no parent. moveUp function is ignored.');
return;
}
var index = this.index,
len = this.parent.getChildren().length;
if(index < len - 1) {
this.parent.children.splice(index, 1);
this.parent.children.splice(index + 1, 0, this);
this.parent._setChildrenIndices();
return true;
}
return false;
},
/**
* move node down
* @method
* @memberof Kinetic.Node.prototype
* @returns {Boolean}
*/
moveDown: function() {
if (!this.parent) {
Kinetic.Util.warn('Node has no parent. moveDown function is ignored.');
return;
}
var index = this.index;
if(index > 0) {
this.parent.children.splice(index, 1);
this.parent.children.splice(index - 1, 0, this);
this.parent._setChildrenIndices();
return true;
}
return false;
},
/**
* move node to the bottom of its siblings
* @method
* @memberof Kinetic.Node.prototype
* @returns {Boolean}
*/
moveToBottom: function() {
if (!this.parent) {
Kinetic.Util.warn('Node has no parent. moveToBottom function is ignored.');
return;
}
var index = this.index;
if(index > 0) {
this.parent.children.splice(index, 1);
this.parent.children.unshift(this);
this.parent._setChildrenIndices();
return true;
}
return false;
},
/**
* set zIndex relative to siblings
* @method
* @memberof Kinetic.Node.prototype
* @param {Integer} zIndex
* @returns {Kinetic.Node}
*/
setZIndex: function(zIndex) {
if (!this.parent) {
Kinetic.Util.warn('Node has no parent. zIndex parameter is ignored.');
return;
}
var index = this.index;
this.parent.children.splice(index, 1);
this.parent.children.splice(zIndex, 0, this);
this.parent._setChildrenIndices();
return this;
},
/**
* get absolute opacity
* @method
* @memberof Kinetic.Node.prototype
* @returns {Number}
*/
getAbsoluteOpacity: function() {
return this._getCache(ABSOLUTE_OPACITY, this._getAbsoluteOpacity);
},
_getAbsoluteOpacity: function() {
var absOpacity = this.getOpacity();
if(this.getParent()) {
absOpacity *= this.getParent().getAbsoluteOpacity();
}
return absOpacity;
},
/**
* move node to another container
* @method
* @memberof Kinetic.Node.prototype
* @param {Container} newContainer
* @returns {Kinetic.Node}
* @example
* // move node from current layer into layer2<br>
* node.moveTo(layer2);
*/
moveTo: function(newContainer) {
Kinetic.Node.prototype.remove.call(this);
newContainer.add(this);
return this;
},
/**
* convert Node into an object for serialization. Returns an object.
* @method
* @memberof Kinetic.Node.prototype
* @returns {Object}
*/
toObject: function() {
var type = Kinetic.Util,
obj = {},
attrs = this.getAttrs(),
key, val, getter, defaultValue;
obj.attrs = {};
// serialize only attributes that are not function, image, DOM, or objects with methods
for(key in attrs) {
val = attrs[key];
if (!type._isFunction(val) && !type._isElement(val) && !(type._isObject(val) && type._hasMethods(val))) {
getter = this[key];
// remove attr value so that we can extract the default value from the getter
delete attrs[key];
defaultValue = getter ? getter.call(this) : null;
// restore attr value
attrs[key] = val;
if (defaultValue !== val) {
obj.attrs[key] = val;
}
}
}
obj.className = this.getClassName();
return obj;
},
/**
* convert Node into a JSON string. Returns a JSON string.
* @method
* @memberof Kinetic.Node.prototype
* @returns {String}}
*/
toJSON: function() {
return JSON.stringify(this.toObject());
},
/**
* get parent container
* @method
* @memberof Kinetic.Node.prototype
* @returns {Kinetic.Node}
*/
getParent: function() {
return this.parent;
},
/**
* get layer ancestor
* @method
* @memberof Kinetic.Node.prototype
* @returns {Kinetic.Layer}
*/
getLayer: function() {
var parent = this.getParent();
return parent ? parent.getLayer() : null;
},
/**
* get stage ancestor
* @method
* @memberof Kinetic.Node.prototype
* @returns {Kinetic.Stage}
*/
getStage: function() {
return this._getCache(STAGE, this._getStage);
},
_getStage: function() {
var parent = this.getParent();
if(parent) {
return parent.getStage();
}
else {
return undefined;
}
},
/**
* fire event
* @method
* @memberof Kinetic.Node.prototype
* @param {String} eventType event type. can be a regular event, like click, mouseover, or mouseout, or it can be a custom event, like myCustomEvent
* @param {EventObject} [evt] event object
* @param {Boolean} [bubble] setting the value to false, or leaving it undefined, will result in the event
* not bubbling. Setting the value to true will result in the event bubbling.
* @returns {Kinetic.Node}
* @example
* // manually fire click event<br>
* node.fire('click');<br><br>
*
* // fire custom event<br>
* node.fire('foo');<br><br>
*
* // fire custom event with custom event object<br>
* node.fire('foo', {<br>
* bar: 10<br>
* });<br><br>
*
* // fire click event that bubbles<br>
* node.fire('click', null, true);
*/
fire: function(eventType, evt, bubble) {
// bubble
if (bubble) {
this._fireAndBubble(eventType, evt || {});
}
// no bubble
else {
this._fire(eventType, evt || {});
}
return this;
},
/**
* get absolute transform of the node which takes into
* account its ancestor transforms
* @method
* @memberof Kinetic.Node.prototype
* @returns {Kinetic.Transform}
*/
getAbsoluteTransform: function(top) {
// if using an argument, we can't cache the result.
if (top) {
return this._getAbsoluteTransform(top);
}
// if no argument, we can cache the result
else {
return this._getCache(ABSOLUTE_TRANSFORM, this._getAbsoluteTransform);
}
},
_getAbsoluteTransform: function(top) {
var at = new Kinetic.Transform(),
transformsEnabled, trans;
// start with stage and traverse downwards to self
this._eachAncestorReverse(function(node) {
transformsEnabled = node.transformsEnabled();
trans = node.getTransform();
if (transformsEnabled === 'all') {
at.multiply(trans);
}
else if (transformsEnabled === 'position') {
at.translate(node.x(), node.y());
}
}, top);
return at;
},
/**
* get transform of the node
* @method
* @memberof Kinetic.Node.prototype
* @returns {Kinetic.Transform}
*/
getTransform: function() {
return this._getCache(TRANSFORM, this._getTransform);
},
_getTransform: function() {
var m = new Kinetic.Transform(),
x = this.getX(),
y = this.getY(),
rotation = Kinetic.getAngle(this.getRotation()),
scaleX = this.getScaleX(),
scaleY = this.getScaleY(),
skewX = this.getSkewX(),
skewY = this.getSkewY(),
offsetX = this.getOffsetX(),
offsetY = this.getOffsetY();
if(x !== 0 || y !== 0) {
m.translate(x, y);
}
if(rotation !== 0) {
m.rotate(rotation);
}
if(skewX !== 0 || skewY !== 0) {
m.skew(skewX, skewY);
}
if(scaleX !== 1 || scaleY !== 1) {
m.scale(scaleX, scaleY);
}
if(offsetX !== 0 || offsetY !== 0) {
m.translate(-1 * offsetX, -1 * offsetY);
}
return m;
},
/**
* clone node. Returns a new Node instance with identical attributes. You can also override
* the node properties with an object literal, enabling you to use an existing node as a template
* for another node
* @method
* @memberof Kinetic.Node.prototype
* @param {Object} attrs override attrs
* @returns {Kinetic.Node}
* @example
* // simple clone<br>
* var clone = node.clone();<br><br>
*
* // clone a node and override the x position<br>
* var clone = rect.clone({<br>
* x: 5<br>
* });
*/
clone: function(obj) {
// instantiate new node
var className = this.getClassName(),
attrs = Kinetic.Util.cloneObject(this.attrs),
key, allListeners, len, n, listener;
// filter black attrs
for (var i in CLONE_BLACK_LIST) {
var blockAttr = CLONE_BLACK_LIST[i];
delete attrs[blockAttr];
}
// apply attr overrides
for (key in obj) {
attrs[key] = obj[key];
}
var node = new Kinetic[className](attrs);
// copy over listeners
for(key in this.eventListeners) {
allListeners = this.eventListeners[key];
len = allListeners.length;
for(n = 0; n < len; n++) {
listener = allListeners[n];
/*
* don't include kinetic namespaced listeners because
* these are generated by the constructors
*/
if(listener.name.indexOf(KINETIC) < 0) {
// if listeners array doesn't exist, then create it
if(!node.eventListeners[key]) {
node.eventListeners[key] = [];
}
node.eventListeners[key].push(listener);
}
}
}
return node;
},
/**
* Creates a composite data URL. If MIME type is not
* specified, then "image/png" will result. For "image/jpeg", specify a quality
* level as quality (range 0.0 - 1.0)
* @method
* @memberof Kinetic.Node.prototype
* @param {Object} config
* @param {String} [config.mimeType] can be "image/png" or "image/jpeg".
* "image/png" is the default
* @param {Number} [config.x] x position of canvas section
* @param {Number} [config.y] y position of canvas section
* @param {Number} [config.width] width of canvas section
* @param {Number} [config.height] height of canvas section
* @param {Number} [config.quality] jpeg quality. If using an "image/jpeg" mimeType,
* you can specify the quality from 0 to 1, where 0 is very poor quality and 1
* is very high quality
* @returns {String}
*/
toDataURL: function(config) {
config = config || {};
var mimeType = config.mimeType || null,
quality = config.quality || null,
stage = this.getStage(),
x = config.x || 0,
y = config.y || 0,
canvas = new Kinetic.SceneCanvas({
width: config.width || this.getWidth() || (stage ? stage.getWidth() : 0),
height: config.height || this.getHeight() || (stage ? stage.getHeight() : 0),
pixelRatio: 1
}),
context = canvas.getContext();
context.save();
if(x || y) {
context.translate(-1 * x, -1 * y);
}
this.drawScene(canvas);
context.restore();
return canvas.toDataURL(mimeType, quality);
},
/**
* converts node into an image. Since the toImage
* method is asynchronous, a callback is required. toImage is most commonly used
* to cache complex drawings as an image so that they don't have to constantly be redrawn
* @method
* @memberof Kinetic.Node.prototype
* @param {Object} config
* @param {Function} config.callback function executed when the composite has completed
* @param {String} [config.mimeType] can be "image/png" or "image/jpeg".
* "image/png" is the default
* @param {Number} [config.x] x position of canvas section
* @param {Number} [config.y] y position of canvas section
* @param {Number} [config.width] width of canvas section
* @param {Number} [config.height] height of canvas section
* @param {Number} [config.quality] jpeg quality. If using an "image/jpeg" mimeType,
* you can specify the quality from 0 to 1, where 0 is very poor quality and 1
* is very high quality
* @example
* var image = node.toImage({<br>
* callback: function(img) {<br>
* // do stuff with img<br>
* }<br>
* });
*/
toImage: function(config) {
Kinetic.Util._getImage(this.toDataURL(config), function(img) {
config.callback(img);
});
},
setSize: function(size) {
this.setWidth(size.width);
this.setHeight(size.height);
return this;
},
getSize: function() {
return {
width: this.getWidth(),
height: this.getHeight()
};
},
/**
* get width
* @method
* @memberof Kinetic.Node.prototype
* @returns {Integer}
*/
getWidth: function() {
return this.attrs.width || 0;
},
/**
* get height
* @method
* @memberof Kinetic.Node.prototype
* @returns {Integer}
*/
getHeight: function() {
return this.attrs.height || 0;
},
/**
* get class name, which may return Stage, Layer, Group, or shape class names like Rect, Circle, Text, etc.
* @method
* @memberof Kinetic.Node.prototype
* @returns {String}
*/
getClassName: function() {
return this.className || this.nodeType;
},
/**
* get the node type, which may return Stage, Layer, Group, or Node
* @method
* @memberof Kinetic.Node.prototype
* @returns {String}
*/
getType: function() {
return this.nodeType;
},
getDragDistance: function() {
// compare with undefined because we need to track 0 value
if (this.attrs.dragDistance !== undefined) {
return this.attrs.dragDistance;
} else if (this.parent) {
return this.parent.getDragDistance();
} else {
return Kinetic.dragDistance;
}
},
_get: function(selector) {
return this.nodeType === selector ? [this] : [];
},
_off: function(type, name) {
var evtListeners = this.eventListeners[type],
i, evtName;
for(i = 0; i < evtListeners.length; i++) {
evtName = evtListeners[i].name;
// the following two conditions must be true in order to remove a handler:
// 1) the current event name cannot be kinetic unless the event name is kinetic
// this enables developers to force remove a kinetic specific listener for whatever reason
// 2) an event name is not specified, or if one is specified, it matches the current event name
if((evtName !== 'kinetic' || name === 'kinetic') && (!name || evtName === name)) {
evtListeners.splice(i, 1);
if(evtListeners.length === 0) {
delete this.eventListeners[type];
break;
}
i--;
}
}
},
_fireChangeEvent: function(attr, oldVal, newVal) {
this._fire(attr + CHANGE, {
oldVal: oldVal,
newVal: newVal
});
},
/**
* set id
* @method
* @memberof Kinetic.Node.prototype
* @param {String} id
* @returns {Kinetic.Node}
*/
setId: function(id) {
var oldId = this.getId();
Kinetic._removeId(oldId);
Kinetic._addId(this, id);
this._setAttr(ID, id);
return this;
},
setName: function(name) {
var oldName = this.getName();
Kinetic._removeName(oldName, this._id);
Kinetic._addName(this, name);
this._setAttr(NAME, name);
return this;
},
/**
* set attr
* @method
* @memberof Kinetic.Node.prototype
* @param {String} attr
* @param {*} val
* @returns {Kinetic.Node}
* @example
* node.setAttr('x', 5);
*/
setAttr: function() {
var args = Array.prototype.slice.call(arguments),
attr = args[0],
val = args[1],
method = SET + Kinetic.Util._capitalize(attr),
func = this[method];
if(Kinetic.Util._isFunction(func)) {
func.call(this, val);
}
// otherwise set directly
else {
this._setAttr(attr, val);
}
return this;
},
_setAttr: function(key, val) {
var oldVal;
if(val !== undefined) {
oldVal = this.attrs[key];
this.attrs[key] = val;
this._fireChangeEvent(key, oldVal, val);
}
},
_setComponentAttr: function(key, component, val) {
var oldVal;
if(val !== undefined) {
oldVal = this.attrs[key];
if (!oldVal) {
// set value to default value using getAttr
this.attrs[key] = this.getAttr(key);
}
this.attrs[key][component] = val;
this._fireChangeEvent(key, oldVal, val);
}
},
_fireAndBubble: function(eventType, evt, compareShape) {
var okayToRun = true;
if(evt && this.nodeType === SHAPE) {
evt.target = this;
}
if(eventType === MOUSEENTER && compareShape && this._id === compareShape._id) {
okayToRun = false;
}
else if(eventType === MOUSELEAVE && compareShape && this._id === compareShape._id) {
okayToRun = false;
}
if(okayToRun) {
this._fire(eventType, evt);
// simulate event bubbling
if(evt && !evt.cancelBubble && this.parent) {
if(compareShape && compareShape.parent) {
this._fireAndBubble.call(this.parent, eventType, evt, compareShape.parent);
}
else {
this._fireAndBubble.call(this.parent, eventType, evt);
}
}
}
},
_fire: function(eventType, evt) {
var events = this.eventListeners[eventType],
i;
evt.type = eventType;
if (events) {
for(i = 0; i < events.length; i++) {
events[i].handler.call(this, evt);
}
}
},
/**
* draw both scene and hit graphs. If the node being drawn is the stage, all of the layers will be cleared and redrawn
* @method
* @memberof Kinetic.Node.prototype
* @returns {Kinetic.Node}
*/
draw: function() {
this.drawScene();
this.drawHit();
return this;
}
});
/**
* create node with JSON string. De-serializtion does not generate custom
* shape drawing functions, images, or event handlers (this would make the
* serialized object huge). If your app uses custom shapes, images, and
* event handlers (it probably does), then you need to select the appropriate
* shapes after loading the stage and set these properties via on(), setDrawFunc(),
* and setImage() methods
* @method
* @memberof Kinetic.Node
* @param {String} JSON string
* @param {DomElement} [container] optional container dom element used only if you're
* creating a stage node
*/
Kinetic.Node.create = function(json, container) {
return this._createNode(JSON.parse(json), container);
};
Kinetic.Node._createNode = function(obj, container) {
var className = Kinetic.Node.prototype.getClassName.call(obj),
children = obj.children,
no, len, n;
// if container was passed in, add it to attrs
if(container) {
obj.attrs.container = container;
}
no = new Kinetic[className](obj.attrs);
if(children) {
len = children.length;
for(n = 0; n < len; n++) {
no.add(this._createNode(children[n]));
}
}
return no;
};
// =========================== add getters setters ===========================
Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Node, 'position');
/**
* get/set node position relative to parent
* @name position
* @method
* @memberof Kinetic.Node.prototype
* @param {Object} pos
* @param {Number} pos.x
* @param {Nubmer} pos.y
* @returns {Object}
* @example
* // get position<br>
* var position = node.position();<br><br>
*
* // set position<br>
* node.position({<br>
* x: 5<br>
* y: 10<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'x', 0);
/**
* get/set x position
* @name x
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} x
* @returns {Object}
* @example
* // get x<br>
* var x = node.x();<br><br>
*
* // set x<br>
* node.x(5);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'y', 0);
/**
* get/set y position
* @name y
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} y
* @returns {Integer}
* @example
* // get y<br>
* var y = node.y();<br><br>
*
* // set y<br>
* node.y(5);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'opacity', 1);
/**
* get/set opacity. Opacity values range from 0 to 1.
* A node with an opacity of 0 is fully transparent, and a node
* with an opacity of 1 is fully opaque
* @name opacity
* @method
* @memberof Kinetic.Node.prototype
* @param {Object} opacity
* @returns {Number}
* @example
* // get opacity<br>
* var opacity = node.opacity();<br><br>
*
* // set opacity<br>
* node.opacity(0.5);
*/
Kinetic.Factory.addGetter(Kinetic.Node, 'name');
Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Node, 'name');
/**
* get/set name
* @name name
* @method
* @memberof Kinetic.Node.prototype
* @param {String} name
* @returns {String}
* @example
* // get name<br>
* var name = node.name();<br><br>
*
* // set name<br>
* node.name('foo');
*/
Kinetic.Factory.addGetter(Kinetic.Node, 'id');
Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Node, 'id');
/**
* get/set id
* @name id
* @method
* @memberof Kinetic.Node.prototype
* @param {String} id
* @returns {String}
* @example
* // get id<br>
* var name = node.id();<br><br>
*
* // set id<br>
* node.id('foo');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'rotation', 0);
/**
* get/set rotation in degrees
* @name rotation
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} rotation
* @returns {Number}
* @example
* // get rotation in degrees<br>
* var rotation = node.rotation();<br><br>
*
* // set rotation in degrees<br>
* node.rotation(45);
*/
Kinetic.Factory.addComponentsGetterSetter(Kinetic.Node, 'scale', ['x', 'y']);
/**
* get/set scale
* @name scale
* @param {Object} scale
* @param {Number} scale.x
* @param {Number} scale.y
* @method
* @memberof Kinetic.Node.prototype
* @returns {Object}
* @example
* // get scale<br>
* var scale = node.scale();<br><br>
*
* // set scale <br>
* shape.scale({<br>
* x: 2<br>
* y: 3<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'scaleX', 1);
/**
* get/set scale x
* @name scaleX
* @param {Number} x
* @method
* @memberof Kinetic.Node.prototype
* @returns {Number}
* @example
* // get scale x<br>
* var scaleX = node.scaleX();<br><br>
*
* // set scale x<br>
* node.scaleX(2);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'scaleY', 1);
/**
* get/set scale y
* @name scaleY
* @param {Number} y
* @method
* @memberof Kinetic.Node.prototype
* @returns {Number}
* @example
* // get scale y<br>
* var scaleY = node.scaleY();<br><br>
*
* // set scale y<br>
* node.scaleY(2);
*/
Kinetic.Factory.addComponentsGetterSetter(Kinetic.Node, 'skew', ['x', 'y']);
/**
* get/set skew
* @name skew
* @param {Object} skew
* @param {Number} skew.x
* @param {Number} skew.y
* @method
* @memberof Kinetic.Node.prototype
* @returns {Object}
* @example
* // get skew<br>
* var skew = node.skew();<br><br>
*
* // set skew <br>
* node.skew({<br>
* x: 20<br>
* y: 10
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'skewX', 0);
/**
* get/set skew x
* @name skewX
* @param {Number} x
* @method
* @memberof Kinetic.Node.prototype
* @returns {Number}
* @example
* // get skew x<br>
* var skewX = node.skewX();<br><br>
*
* // set skew x<br>
* node.skewX(3);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'skewY', 0);
/**
* get/set skew y
* @name skewY
* @param {Number} y
* @method
* @memberof Kinetic.Node.prototype
* @returns {Number}
* @example
* // get skew y<br>
* var skewY = node.skewY();<br><br>
*
* // set skew y<br>
* node.skewY(3);
*/
Kinetic.Factory.addComponentsGetterSetter(Kinetic.Node, 'offset', ['x', 'y']);
/**
* get/set offset. Offsets the default position and rotation point
* @method
* @memberof Kinetic.Node.prototype
* @param {Object} offset
* @param {Number} offset.x
* @param {Number} offset.y
* @returns {Object}
* @example
* // get offset<br>
* var offset = node.offset();<br><br>
*
* // set offset<br>
* node.offset({<br>
* x: 20<br>
* y: 10<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'offsetX', 0);
/**
* get/set offset x
* @name offsetX
* @memberof Kinetic.Node.prototype
* @param {Number} x
* @returns {Number}
* @example
* // get offset x<br>
* var offsetX = node.offsetX();<br><br>
*
* // set offset x<br>
* node.offsetX(3);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'offsetY', 0);
/**
* get/set drag distance
* @name dragDistance
* @memberof Kinetic.Node.prototype
* @param {Number} distance
* @returns {Number}
* @example
* // get drag distance<br>
* var dragDistance = node.dragDistance();<br><br>
*
* // set distance<br>
* // node starts dragging only if pointer moved more then 3 pixels<br>
* node.dragDistance(3);<br>
* // or set globally<br>
* Kinetic.dragDistance = 3;
*/
Kinetic.Factory.addSetter(Kinetic.Node, 'dragDistance');
Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Node, 'dragDistance');
/**
* get/set offset y
* @name offsetY
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} y
* @returns {Number}
* @example
* // get offset y<br>
* var offsetY = node.offsetY();<br><br>
*
* // set offset y<br>
* node.offsetY(3);
*/
Kinetic.Factory.addSetter(Kinetic.Node, 'width', 0);
Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Node, 'width');
/**
* get/set width
* @name width
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} width
* @returns {Number}
* @example
* // get width<br>
* var width = node.width();<br><br>
*
* // set width<br>
* node.width(100);
*/
Kinetic.Factory.addSetter(Kinetic.Node, 'height', 0);
Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Node, 'height');
/**
* get/set height
* @name height
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} height
* @returns {Number}
* @example
* // get height<br>
* var height = node.height();<br><br>
*
* // set height<br>
* node.height(100);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'listening', 'inherit');
/**
* get/set listenig attr. If you need to determine if a node is listening or not
* by taking into account its parents, use the isListening() method
* @name listening
* @method
* @memberof Kinetic.Node.prototype
* @param {Boolean|String} listening Can be "inherit", true, or false. The default is "inherit".
* @returns {Boolean|String}
* @example
* // get listening attr<br>
* var listening = node.listening();<br><br>
*
* // stop listening for events<br>
* node.listening(false);<br><br>
*
* // listen for events<br>
* node.listening(true);<br><br>
*
* // listen to events according to the parent<br>
* node.listening('inherit');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'filters', undefined, function(val) {this._filterUpToDate = false;return val;});
/**
* get/set filters. Filters are applied to cached canvases
* @name filters
* @method
* @memberof Kinetic.Node.prototype
* @param {Array} filters array of filters
* @returns {Array}
* @example
* // get filters<br>
* var filters = node.filters();<br><br>
*
* // set a single filter<br>
* node.cache();<br>
* node.filters([Kinetic.Filters.Blur]);<br><br>
*
* // set multiple filters<br>
* node.cache();<br>
* node.filters([<br>
* Kinetic.Filters.Blur,<br>
* Kinetic.Filters.Sepia,<br>
* Kinetic.Filters.Invert<br>
* ]);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'visible', 'inherit');
/**
* get/set visible attr. Can be "inherit", true, or false. The default is "inherit".
* If you need to determine if a node is visible or not
* by taking into account its parents, use the isVisible() method
* @name visible
* @method
* @memberof Kinetic.Node.prototype
* @param {Boolean|String} visible
* @returns {Boolean|String}
* @example
* // get visible attr<br>
* var visible = node.visible();<br><br>
*
* // make invisible<br>
* node.visible(false);<br><br>
*
* // make visible<br>
* node.visible(true);<br><br>
*
* // make visible according to the parent<br>
* node.visible('inherit');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'transformsEnabled', 'all');
/**
* get/set transforms that are enabled. Can be "all", "none", or "position". The default
* is "all"
* @name transformsEnabled
* @method
* @memberof Kinetic.Node.prototype
* @param {String} enabled
* @returns {String}
* @example
* // enable position transform only to improve draw performance<br>
* node.transformsEnabled('position');<br><br>
*
* // enable all transforms<br>
* node.transformsEnabled('all');
*/
/**
* get/set node size
* @name size
* @method
* @memberof Kinetic.Node.prototype
* @param {Object} size
* @param {Number} size.width
* @param {Number} size.height
* @returns {Object}
* @example
* // get node size<br>
* var size = node.size();<br>
* var x = size.x;<br>
* var y = size.y;<br><br>
*
* // set size<br>
* node.size({<br>
* width: 100,<br>
* height: 200<br>
* });
*/
Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Node, 'size');
Kinetic.Factory.backCompat(Kinetic.Node, {
rotateDeg: 'rotate',
setRotationDeg: 'setRotation',
getRotationDeg: 'getRotation'
});
Kinetic.Collection.mapMethods(Kinetic.Node);
})();
;(function() {
/**
* Grayscale Filter
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
*/
Kinetic.Filters.Grayscale = function(imageData) {
var data = imageData.data,
len = data.length,
i, brightness;
for(i = 0; i < len; i += 4) {
brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];
// red
data[i] = brightness;
// green
data[i + 1] = brightness;
// blue
data[i + 2] = brightness;
}
};
})();
;(function() {
/**
* Brighten Filter.
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
*/
Kinetic.Filters.Brighten = function(imageData) {
var brightness = this.brightness() * 255,
data = imageData.data,
len = data.length,
i;
for(i = 0; i < len; i += 4) {
// red
data[i] += brightness;
// green
data[i + 1] += brightness;
// blue
data[i + 2] += brightness;
}
};
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'brightness', 0, null, Kinetic.Factory.afterSetFilter);
/**
* get/set filter brightness. The brightness is a number between -1 and 1. Positive values
* brighten the pixels and negative values darken them.
* @name brightness
* @method
* @memberof Kinetic.Image.prototype
* @param {Number} brightness value between -1 and 1
* @returns {Number}
*/
})();
;(function() {
/**
* Invert Filter
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
*/
Kinetic.Filters.Invert = function(imageData) {
var data = imageData.data,
len = data.length,
i;
for(i = 0; i < len; i += 4) {
// red
data[i] = 255 - data[i];
// green
data[i + 1] = 255 - data[i + 1];
// blue
data[i + 2] = 255 - data[i + 2];
}
};
})();;/*
the Gauss filter
master repo: https://github.com/pavelpower/kineticjsGaussFilter/
*/
(function() {
/*
StackBlur - a fast almost Gaussian Blur For Canvas
Version: 0.5
Author: Mario Klingemann
Contact: mario@quasimondo.com
Website: http://www.quasimondo.com/StackBlurForCanvas
Twitter: @quasimondo
In case you find this class useful - especially in commercial projects -
I am not totally unhappy for a small donation to my PayPal account
mario@quasimondo.de
Or support me on flattr:
https://flattr.com/thing/72791/StackBlur-a-fast-almost-Gaussian-Blur-Effect-for-CanvasJavascript
Copyright (c) 2010 Mario Klingemann
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.
*/
function BlurStack() {
this.r = 0;
this.g = 0;
this.b = 0;
this.a = 0;
this.next = null;
}
var mul_table = [
512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512,
454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512,
482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456,
437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,
497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,
320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,
446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,
329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,
505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,
399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,
324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,
268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,
451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,
385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,
332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,
289,287,285,282,280,278,275,273,271,269,267,265,263,261,259
];
var shg_table = [
9, 11, 12, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 17,
17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19,
19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20,
20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21,
21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23,
23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24
];
function filterGaussBlurRGBA( imageData, radius) {
var pixels = imageData.data,
width = imageData.width,
height = imageData.height;
var x, y, i, p, yp, yi, yw, r_sum, g_sum, b_sum, a_sum,
r_out_sum, g_out_sum, b_out_sum, a_out_sum,
r_in_sum, g_in_sum, b_in_sum, a_in_sum,
pr, pg, pb, pa, rbs;
var div = radius + radius + 1,
widthMinus1 = width - 1,
heightMinus1 = height - 1,
radiusPlus1 = radius + 1,
sumFactor = radiusPlus1 * ( radiusPlus1 + 1 ) / 2,
stackStart = new BlurStack(),
stackEnd = null,
stack = stackStart,
stackIn = null,
stackOut = null,
mul_sum = mul_table[radius],
shg_sum = shg_table[radius];
for ( i = 1; i < div; i++ ) {
stack = stack.next = new BlurStack();
if ( i == radiusPlus1 ){
stackEnd = stack;
}
}
stack.next = stackStart;
yw = yi = 0;
for ( y = 0; y < height; y++ )
{
r_in_sum = g_in_sum = b_in_sum = a_in_sum = r_sum = g_sum = b_sum = a_sum = 0;
r_out_sum = radiusPlus1 * ( pr = pixels[yi] );
g_out_sum = radiusPlus1 * ( pg = pixels[yi+1] );
b_out_sum = radiusPlus1 * ( pb = pixels[yi+2] );
a_out_sum = radiusPlus1 * ( pa = pixels[yi+3] );
r_sum += sumFactor * pr;
g_sum += sumFactor * pg;
b_sum += sumFactor * pb;
a_sum += sumFactor * pa;
stack = stackStart;
for( i = 0; i < radiusPlus1; i++ )
{
stack.r = pr;
stack.g = pg;
stack.b = pb;
stack.a = pa;
stack = stack.next;
}
for( i = 1; i < radiusPlus1; i++ )
{
p = yi + (( widthMinus1 < i ? widthMinus1 : i ) << 2 );
r_sum += ( stack.r = ( pr = pixels[p])) * ( rbs = radiusPlus1 - i );
g_sum += ( stack.g = ( pg = pixels[p+1])) * rbs;
b_sum += ( stack.b = ( pb = pixels[p+2])) * rbs;
a_sum += ( stack.a = ( pa = pixels[p+3])) * rbs;
r_in_sum += pr;
g_in_sum += pg;
b_in_sum += pb;
a_in_sum += pa;
stack = stack.next;
}
stackIn = stackStart;
stackOut = stackEnd;
for ( x = 0; x < width; x++ )
{
pixels[yi+3] = pa = (a_sum * mul_sum) >> shg_sum;
if ( pa !== 0 )
{
pa = 255 / pa;
pixels[yi] = ((r_sum * mul_sum) >> shg_sum) * pa;
pixels[yi+1] = ((g_sum * mul_sum) >> shg_sum) * pa;
pixels[yi+2] = ((b_sum * mul_sum) >> shg_sum) * pa;
} else {
pixels[yi] = pixels[yi+1] = pixels[yi+2] = 0;
}
r_sum -= r_out_sum;
g_sum -= g_out_sum;
b_sum -= b_out_sum;
a_sum -= a_out_sum;
r_out_sum -= stackIn.r;
g_out_sum -= stackIn.g;
b_out_sum -= stackIn.b;
a_out_sum -= stackIn.a;
p = ( yw + ( ( p = x + radius + 1 ) < widthMinus1 ? p : widthMinus1 ) ) << 2;
r_in_sum += ( stackIn.r = pixels[p]);
g_in_sum += ( stackIn.g = pixels[p+1]);
b_in_sum += ( stackIn.b = pixels[p+2]);
a_in_sum += ( stackIn.a = pixels[p+3]);
r_sum += r_in_sum;
g_sum += g_in_sum;
b_sum += b_in_sum;
a_sum += a_in_sum;
stackIn = stackIn.next;
r_out_sum += ( pr = stackOut.r );
g_out_sum += ( pg = stackOut.g );
b_out_sum += ( pb = stackOut.b );
a_out_sum += ( pa = stackOut.a );
r_in_sum -= pr;
g_in_sum -= pg;
b_in_sum -= pb;
a_in_sum -= pa;
stackOut = stackOut.next;
yi += 4;
}
yw += width;
}
for ( x = 0; x < width; x++ )
{
g_in_sum = b_in_sum = a_in_sum = r_in_sum = g_sum = b_sum = a_sum = r_sum = 0;
yi = x << 2;
r_out_sum = radiusPlus1 * ( pr = pixels[yi]);
g_out_sum = radiusPlus1 * ( pg = pixels[yi+1]);
b_out_sum = radiusPlus1 * ( pb = pixels[yi+2]);
a_out_sum = radiusPlus1 * ( pa = pixels[yi+3]);
r_sum += sumFactor * pr;
g_sum += sumFactor * pg;
b_sum += sumFactor * pb;
a_sum += sumFactor * pa;
stack = stackStart;
for( i = 0; i < radiusPlus1; i++ )
{
stack.r = pr;
stack.g = pg;
stack.b = pb;
stack.a = pa;
stack = stack.next;
}
yp = width;
for( i = 1; i <= radius; i++ )
{
yi = ( yp + x ) << 2;
r_sum += ( stack.r = ( pr = pixels[yi])) * ( rbs = radiusPlus1 - i );
g_sum += ( stack.g = ( pg = pixels[yi+1])) * rbs;
b_sum += ( stack.b = ( pb = pixels[yi+2])) * rbs;
a_sum += ( stack.a = ( pa = pixels[yi+3])) * rbs;
r_in_sum += pr;
g_in_sum += pg;
b_in_sum += pb;
a_in_sum += pa;
stack = stack.next;
if( i < heightMinus1 )
{
yp += width;
}
}
yi = x;
stackIn = stackStart;
stackOut = stackEnd;
for ( y = 0; y < height; y++ )
{
p = yi << 2;
pixels[p+3] = pa = (a_sum * mul_sum) >> shg_sum;
if ( pa > 0 )
{
pa = 255 / pa;
pixels[p] = ((r_sum * mul_sum) >> shg_sum ) * pa;
pixels[p+1] = ((g_sum * mul_sum) >> shg_sum ) * pa;
pixels[p+2] = ((b_sum * mul_sum) >> shg_sum ) * pa;
} else {
pixels[p] = pixels[p+1] = pixels[p+2] = 0;
}
r_sum -= r_out_sum;
g_sum -= g_out_sum;
b_sum -= b_out_sum;
a_sum -= a_out_sum;
r_out_sum -= stackIn.r;
g_out_sum -= stackIn.g;
b_out_sum -= stackIn.b;
a_out_sum -= stackIn.a;
p = ( x + (( ( p = y + radiusPlus1) < heightMinus1 ? p : heightMinus1 ) * width )) << 2;
r_sum += ( r_in_sum += ( stackIn.r = pixels[p]));
g_sum += ( g_in_sum += ( stackIn.g = pixels[p+1]));
b_sum += ( b_in_sum += ( stackIn.b = pixels[p+2]));
a_sum += ( a_in_sum += ( stackIn.a = pixels[p+3]));
stackIn = stackIn.next;
r_out_sum += ( pr = stackOut.r );
g_out_sum += ( pg = stackOut.g );
b_out_sum += ( pb = stackOut.b );
a_out_sum += ( pa = stackOut.a );
r_in_sum -= pr;
g_in_sum -= pg;
b_in_sum -= pb;
a_in_sum -= pa;
stackOut = stackOut.next;
yi += width;
}
}
}
/**
* Blur Filter
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
*/
Kinetic.Filters.Blur = function(imageData) {
var radius = Math.round(this.blurRadius());
if (radius > 0) {
filterGaussBlurRGBA(imageData, radius);
}
};
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'blurRadius', 0, null, Kinetic.Factory.afterSetFilter);
/**
* get/set blur radius
* @name blurRadius
* @method
* @memberof Kinetic.Node.prototype
* @param {Integer} radius
* @returns {Integer}
*/
})();;(function() {
function pixelAt(idata, x, y) {
var idx = (y * idata.width + x) * 4;
var d = [];
d.push(idata.data[idx++], idata.data[idx++], idata.data[idx++], idata.data[idx++]);
return d;
}
function rgbDistance(p1, p2) {
return Math.sqrt(Math.pow(p1[0] - p2[0], 2) + Math.pow(p1[1] - p2[1], 2) + Math.pow(p1[2] - p2[2], 2));
}
function rgbMean(pTab) {
var m = [0, 0, 0];
for (var i = 0; i < pTab.length; i++) {
m[0] += pTab[i][0];
m[1] += pTab[i][1];
m[2] += pTab[i][2];
}
m[0] /= pTab.length;
m[1] /= pTab.length;
m[2] /= pTab.length;
return m;
}
function backgroundMask(idata, threshold) {
var rgbv_no = pixelAt(idata, 0, 0);
var rgbv_ne = pixelAt(idata, idata.width - 1, 0);
var rgbv_so = pixelAt(idata, 0, idata.height - 1);
var rgbv_se = pixelAt(idata, idata.width - 1, idata.height - 1);
var thres = threshold || 10;
if (rgbDistance(rgbv_no, rgbv_ne) < thres && rgbDistance(rgbv_ne, rgbv_se) < thres && rgbDistance(rgbv_se, rgbv_so) < thres && rgbDistance(rgbv_so, rgbv_no) < thres) {
// Mean color
var mean = rgbMean([rgbv_ne, rgbv_no, rgbv_se, rgbv_so]);
// Mask based on color distance
var mask = [];
for (var i = 0; i < idata.width * idata.height; i++) {
var d = rgbDistance(mean, [idata.data[i * 4], idata.data[i * 4 + 1], idata.data[i * 4 + 2]]);
mask[i] = (d < thres) ? 0 : 255;
}
return mask;
}
}
function applyMask(idata, mask) {
for (var i = 0; i < idata.width * idata.height; i++) {
idata.data[4 * i + 3] = mask[i];
}
}
function erodeMask(mask, sw, sh) {
var weights = [1, 1, 1, 1, 0, 1, 1, 1, 1];
var side = Math.round(Math.sqrt(weights.length));
var halfSide = Math.floor(side / 2);
var maskResult = [];
for (var y = 0; y < sh; y++) {
for (var x = 0; x < sw; x++) {
var so = y * sw + x;
var a = 0;
for (var cy = 0; cy < side; cy++) {
for (var cx = 0; cx < side; cx++) {
var scy = y + cy - halfSide;
var scx = x + cx - halfSide;
if (scy >= 0 && scy < sh && scx >= 0 && scx < sw) {
var srcOff = scy * sw + scx;
var wt = weights[cy * side + cx];
a += mask[srcOff] * wt;
}
}
}
maskResult[so] = (a === 255 * 8) ? 255 : 0;
}
}
return maskResult;
}
function dilateMask(mask, sw, sh) {
var weights = [1, 1, 1, 1, 1, 1, 1, 1, 1];
var side = Math.round(Math.sqrt(weights.length));
var halfSide = Math.floor(side / 2);
var maskResult = [];
for (var y = 0; y < sh; y++) {
for (var x = 0; x < sw; x++) {
var so = y * sw + x;
var a = 0;
for (var cy = 0; cy < side; cy++) {
for (var cx = 0; cx < side; cx++) {
var scy = y + cy - halfSide;
var scx = x + cx - halfSide;
if (scy >= 0 && scy < sh && scx >= 0 && scx < sw) {
var srcOff = scy * sw + scx;
var wt = weights[cy * side + cx];
a += mask[srcOff] * wt;
}
}
}
maskResult[so] = (a >= 255 * 4) ? 255 : 0;
}
}
return maskResult;
}
function smoothEdgeMask(mask, sw, sh) {
var weights = [1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9];
var side = Math.round(Math.sqrt(weights.length));
var halfSide = Math.floor(side / 2);
var maskResult = [];
for (var y = 0; y < sh; y++) {
for (var x = 0; x < sw; x++) {
var so = y * sw + x;
var a = 0;
for (var cy = 0; cy < side; cy++) {
for (var cx = 0; cx < side; cx++) {
var scy = y + cy - halfSide;
var scx = x + cx - halfSide;
if (scy >= 0 && scy < sh && scx >= 0 && scx < sw) {
var srcOff = scy * sw + scx;
var wt = weights[cy * side + cx];
a += mask[srcOff] * wt;
}
}
}
maskResult[so] = a;
}
}
return maskResult;
}
/**
* Mask Filter
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
*/
Kinetic.Filters.Mask = function(imageData) {
// Detect pixels close to the background color
var threshold = this.threshold(),
mask = backgroundMask(imageData, threshold);
if (mask) {
// Erode
mask = erodeMask(mask, imageData.width, imageData.height);
// Dilate
mask = dilateMask(mask, imageData.width, imageData.height);
// Gradient
mask = smoothEdgeMask(mask, imageData.width, imageData.height);
// Apply mask
applyMask(imageData, mask);
// todo : Update hit region function according to mask
}
return imageData;
};
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'threshold', 0, null, Kinetic.Factory.afterSetFilter);
})();
;(function () {
/**
* RGB Filter
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
* @author ippo615
*/
Kinetic.Filters.RGB = function (imageData) {
var data = imageData.data,
nPixels = data.length,
red = this.red(),
green = this.green(),
blue = this.blue(),
i, brightness;
for (i = 0; i < nPixels; i += 4) {
brightness = (0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2])/255;
data[i ] = brightness*red; // r
data[i + 1] = brightness*green; // g
data[i + 2] = brightness*blue; // b
data[i + 3] = data[i + 3]; // alpha
}
};
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'red', 0, function(val) {
this._filterUpToDate = false;
if (val > 255) {
return 255;
}
else if (val < 0) {
return 0;
}
else {
return Math.round(val);
}
});
/**
* get/set filter red value
* @name red
* @method
* @memberof Kinetic.Node.prototype
* @param {Integer} red value between 0 and 255
* @returns {Integer}
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'green', 0, function(val) {
this._filterUpToDate = false;
if (val > 255) {
return 255;
}
else if (val < 0) {
return 0;
}
else {
return Math.round(val);
}
});
/**
* get/set filter green value
* @name green
* @method
* @memberof Kinetic.Node.prototype
* @param {Integer} green value between 0 and 255
* @returns {Integer}
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'blue', 0, Kinetic.Validators.RGBComponent, Kinetic.Factory.afterSetFilter);
/**
* get/set filter blue value
* @name blue
* @method
* @memberof Kinetic.Node.prototype
* @param {Integer} blue value between 0 and 255
* @returns {Integer}
*/
})();
;(function () {
/**
* HSV Filter. Adjusts the hue, saturation and value
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
* @author ippo615
*/
Kinetic.Filters.HSV = function (imageData) {
var data = imageData.data,
nPixels = data.length,
v = Math.pow(2,this.value()),
s = Math.pow(2,this.saturation()),
h = Math.abs((this.hue()) + 360) % 360,
i;
// Basis for the technique used:
// http://beesbuzz.biz/code/hsv_color_transforms.php
// V is the value multiplier (1 for none, 2 for double, 0.5 for half)
// S is the saturation multiplier (1 for none, 2 for double, 0.5 for half)
// H is the hue shift in degrees (0 to 360)
// vsu = V*S*cos(H*PI/180);
// vsw = V*S*sin(H*PI/180);
//[ .299V+.701vsu+.168vsw .587V-.587vsu+.330vsw .114V-.114vsu-.497vsw ] [R]
//[ .299V-.299vsu-.328vsw .587V+.413vsu+.035vsw .114V-.114vsu+.292vsw ]*[G]
//[ .299V-.300vsu+1.25vsw .587V-.588vsu-1.05vsw .114V+.886vsu-.203vsw ] [B]
// Precompute the values in the matrix:
var vsu = v*s*Math.cos(h*Math.PI/180),
vsw = v*s*Math.sin(h*Math.PI/180);
// (result spot)(source spot)
var rr = 0.299*v+0.701*vsu+0.167*vsw,
rg = 0.587*v-0.587*vsu+0.330*vsw,
rb = 0.114*v-0.114*vsu-0.497*vsw;
var gr = 0.299*v-0.299*vsu-0.328*vsw,
gg = 0.587*v+0.413*vsu+0.035*vsw,
gb = 0.114*v-0.114*vsu+0.293*vsw;
var br = 0.299*v-0.300*vsu+1.250*vsw,
bg = 0.587*v-0.586*vsu-1.050*vsw,
bb = 0.114*v+0.886*vsu-0.200*vsw;
var r,g,b,a;
for (i = 0; i < nPixels; i += 4) {
r = data[i+0];
g = data[i+1];
b = data[i+2];
a = data[i+3];
data[i+0] = rr*r + rg*g + rb*b;
data[i+1] = gr*r + gg*g + gb*b;
data[i+2] = br*r + bg*g + bb*b;
data[i+3] = a; // alpha
}
};
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'hue', 0, null, Kinetic.Factory.afterSetFilter);
/**
* get/set hsv hue in degrees
* @name hue
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} hue value between 0 and 359
* @returns {Number}
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'saturation', 0, null, Kinetic.Factory.afterSetFilter);
/**
* get/set hsv saturation
* @name saturation
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} saturation 0 is no change, -1.0 halves the saturation, 1.0 doubles, etc..
* @returns {Number}
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'value', 0, null, Kinetic.Factory.afterSetFilter);
/**
* get/set hsv value
* @name value
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} value 0 is no change, -1.0 halves the value, 1.0 doubles, etc..
* @returns {Number}
*/
})();
;(function () {
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'hue', 0, null, Kinetic.Factory.afterSetFilter);
/**
* get/set hsv hue in degrees
* @name hue
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} hue value between 0 and 359
* @returns {Number}
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'saturation', 0, null, Kinetic.Factory.afterSetFilter);
/**
* get/set hsv saturation
* @name saturation
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} saturation 0 is no change, -1.0 halves the saturation, 1.0 doubles, etc..
* @returns {Number}
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'luminance', 0, null, Kinetic.Factory.afterSetFilter);
/**
* get/set hsl luminance
* @name value
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} value 0 is no change, -1.0 halves the value, 1.0 doubles, etc..
* @returns {Number}
*/
/**
* HSL Filter. Adjusts the hue, saturation and luminance (or lightness)
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
* @author ippo615
*/
Kinetic.Filters.HSL = function (imageData) {
var data = imageData.data,
nPixels = data.length,
v = 1,
s = Math.pow(2,this.saturation()),
h = Math.abs((this.hue()) + 360) % 360,
l = this.luminance()*127,
i;
// Basis for the technique used:
// http://beesbuzz.biz/code/hsv_color_transforms.php
// V is the value multiplier (1 for none, 2 for double, 0.5 for half)
// S is the saturation multiplier (1 for none, 2 for double, 0.5 for half)
// H is the hue shift in degrees (0 to 360)
// vsu = V*S*cos(H*PI/180);
// vsw = V*S*sin(H*PI/180);
//[ .299V+.701vsu+.168vsw .587V-.587vsu+.330vsw .114V-.114vsu-.497vsw ] [R]
//[ .299V-.299vsu-.328vsw .587V+.413vsu+.035vsw .114V-.114vsu+.292vsw ]*[G]
//[ .299V-.300vsu+1.25vsw .587V-.588vsu-1.05vsw .114V+.886vsu-.203vsw ] [B]
// Precompute the values in the matrix:
var vsu = v*s*Math.cos(h*Math.PI/180),
vsw = v*s*Math.sin(h*Math.PI/180);
// (result spot)(source spot)
var rr = 0.299*v+0.701*vsu+0.167*vsw,
rg = 0.587*v-0.587*vsu+0.330*vsw,
rb = 0.114*v-0.114*vsu-0.497*vsw;
var gr = 0.299*v-0.299*vsu-0.328*vsw,
gg = 0.587*v+0.413*vsu+0.035*vsw,
gb = 0.114*v-0.114*vsu+0.293*vsw;
var br = 0.299*v-0.300*vsu+1.250*vsw,
bg = 0.587*v-0.586*vsu-1.050*vsw,
bb = 0.114*v+0.886*vsu-0.200*vsw;
var r,g,b,a;
for (i = 0; i < nPixels; i += 4) {
r = data[i+0];
g = data[i+1];
b = data[i+2];
a = data[i+3];
data[i+0] = rr*r + rg*g + rb*b + l;
data[i+1] = gr*r + gg*g + gb*b + l;
data[i+2] = br*r + bg*g + bb*b + l;
data[i+3] = a; // alpha
}
};
})();
;(function () {
/**
* Emboss Filter
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
* Pixastic Lib - Emboss filter - v0.1.0
* Copyright (c) 2008 Jacob Seidelin, jseidelin@nihilogic.dk, http://blog.nihilogic.dk/
* License: [http://www.pixastic.com/lib/license.txt]
*/
Kinetic.Filters.Emboss = function (imageData) {
// pixastic strength is between 0 and 10. I want it between 0 and 1
// pixastic greyLevel is between 0 and 255. I want it between 0 and 1. Also,
// a max value of greyLevel yields a white emboss, and the min value yields a black
// emboss. Therefore, I changed greyLevel to whiteLevel
var strength = this.embossStrength() * 10,
greyLevel = this.embossWhiteLevel() * 255,
direction = this.embossDirection(),
blend = this.embossBlend(),
dirY = 0,
dirX = 0,
data = imageData.data,
w = imageData.width,
h = imageData.height,
w4 = w*4,
y = h;
switch (direction) {
case 'top-left':
dirY = -1;
dirX = -1;
break;
case 'top':
dirY = -1;
dirX = 0;
break;
case 'top-right':
dirY = -1;
dirX = 1;
break;
case 'right':
dirY = 0;
dirX = 1;
break;
case 'bottom-right':
dirY = 1;
dirX = 1;
break;
case 'bottom':
dirY = 1;
dirX = 0;
break;
case 'bottom-left':
dirY = 1;
dirX = -1;
break;
case 'left':
dirY = 0;
dirX = -1;
break;
}
do {
var offsetY = (y-1)*w4;
var otherY = dirY;
if (y + otherY < 1){
otherY = 0;
}
if (y + otherY > h) {
otherY = 0;
}
var offsetYOther = (y-1+otherY)*w*4;
var x = w;
do {
var offset = offsetY + (x-1)*4;
var otherX = dirX;
if (x + otherX < 1){
otherX = 0;
}
if (x + otherX > w) {
otherX = 0;
}
var offsetOther = offsetYOther + (x-1+otherX)*4;
var dR = data[offset] - data[offsetOther];
var dG = data[offset+1] - data[offsetOther+1];
var dB = data[offset+2] - data[offsetOther+2];
var dif = dR;
var absDif = dif > 0 ? dif : -dif;
var absG = dG > 0 ? dG : -dG;
var absB = dB > 0 ? dB : -dB;
if (absG > absDif) {
dif = dG;
}
if (absB > absDif) {
dif = dB;
}
dif *= strength;
if (blend) {
var r = data[offset] + dif;
var g = data[offset+1] + dif;
var b = data[offset+2] + dif;
data[offset] = (r > 255) ? 255 : (r < 0 ? 0 : r);
data[offset+1] = (g > 255) ? 255 : (g < 0 ? 0 : g);
data[offset+2] = (b > 255) ? 255 : (b < 0 ? 0 : b);
} else {
var grey = greyLevel - dif;
if (grey < 0) {
grey = 0;
} else if (grey > 255) {
grey = 255;
}
data[offset] = data[offset+1] = data[offset+2] = grey;
}
} while (--x);
} while (--y);
};
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'embossStrength', 0.5, null, Kinetic.Factory.afterSetFilter);
/**
* get/set emboss strength
* @name embossStrength
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} level between 0 and 1. Default is 0.5
* @returns {Number}
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'embossWhiteLevel', 0.5, null, Kinetic.Factory.afterSetFilter);
/**
* get/set emboss white level
* @name embossWhiteLevel
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} embossWhiteLevel between 0 and 1. Default is 0.5
* @returns {Number}
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'embossDirection', 'top-left', null, Kinetic.Factory.afterSetFilter);
/**
* get/set emboss direction
* @name embossDirection
* @method
* @memberof Kinetic.Node.prototype
* @param {String} embossDirection can be top-left, top, top-right, right, bottom-right, bottom, bottom-left or left
* The default is top-left
* @returns {String}
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'embossBlend', false, null, Kinetic.Factory.afterSetFilter);
/**
* get/set emboss blend
* @name embossBlend
* @method
* @memberof Kinetic.Node.prototype
* @param {Boolean} embossBlend
* @returns {Boolean}
*/
})();
;(function () {
function remap(fromValue, fromMin, fromMax, toMin, toMax) {
// Compute the range of the data
var fromRange = fromMax - fromMin,
toRange = toMax - toMin,
toValue;
// If either range is 0, then the value can only be mapped to 1 value
if (fromRange === 0) {
return toMin + toRange / 2;
}
if (toRange === 0) {
return toMin;
}
// (1) untranslate, (2) unscale, (3) rescale, (4) retranslate
toValue = (fromValue - fromMin) / fromRange;
toValue = (toRange * toValue) + toMin;
return toValue;
}
/**
* Enhance Filter. Adjusts the colors so that they span the widest
* possible range (ie 0-255). Performs w*h pixel reads and w*h pixel
* writes.
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
* @author ippo615
*/
Kinetic.Filters.Enhance = function (imageData) {
var data = imageData.data,
nSubPixels = data.length,
rMin = data[0], rMax = rMin, r,
gMin = data[1], gMax = gMin, g,
bMin = data[2], bMax = bMin, b,
aMin = data[3], aMax = aMin,
i;
// If we are not enhancing anything - don't do any computation
var enhanceAmount = this.enhance();
if( enhanceAmount === 0 ){ return; }
// 1st Pass - find the min and max for each channel:
for (i = 0; i < nSubPixels; i += 4) {
r = data[i + 0];
if (r < rMin) { rMin = r; }
else if (r > rMax) { rMax = r; }
g = data[i + 1];
if (g < gMin) { gMin = g; } else
if (g > gMax) { gMax = g; }
b = data[i + 2];
if (b < bMin) { bMin = b; } else
if (b > bMax) { bMax = b; }
//a = data[i + 3];
//if (a < aMin) { aMin = a; } else
//if (a > aMax) { aMax = a; }
}
// If there is only 1 level - don't remap
if( rMax === rMin ){ rMax = 255; rMin = 0; }
if( gMax === gMin ){ gMax = 255; gMin = 0; }
if( bMax === bMin ){ bMax = 255; bMin = 0; }
if( aMax === aMin ){ aMax = 255; aMin = 0; }
var rMid, rGoalMax,rGoalMin,
gMid, gGoalMax,gGoalMin,
bMid, bGoalMax,aGoalMin,
aMid, aGoalMax,bGoalMin;
// If the enhancement is positive - stretch the histogram
if ( enhanceAmount > 0 ){
rGoalMax = rMax + enhanceAmount*(255-rMax);
rGoalMin = rMin - enhanceAmount*(rMin-0);
gGoalMax = gMax + enhanceAmount*(255-gMax);
gGoalMin = gMin - enhanceAmount*(gMin-0);
bGoalMax = bMax + enhanceAmount*(255-bMax);
bGoalMin = bMin - enhanceAmount*(bMin-0);
aGoalMax = aMax + enhanceAmount*(255-aMax);
aGoalMin = aMin - enhanceAmount*(aMin-0);
// If the enhancement is negative - compress the histogram
} else {
rMid = (rMax + rMin)*0.5;
rGoalMax = rMax + enhanceAmount*(rMax-rMid);
rGoalMin = rMin + enhanceAmount*(rMin-rMid);
gMid = (gMax + gMin)*0.5;
gGoalMax = gMax + enhanceAmount*(gMax-gMid);
gGoalMin = gMin + enhanceAmount*(gMin-gMid);
bMid = (bMax + bMin)*0.5;
bGoalMax = bMax + enhanceAmount*(bMax-bMid);
bGoalMin = bMin + enhanceAmount*(bMin-bMid);
aMid = (aMax + aMin)*0.5;
aGoalMax = aMax + enhanceAmount*(aMax-aMid);
aGoalMin = aMin + enhanceAmount*(aMin-aMid);
}
// Pass 2 - remap everything, except the alpha
for (i = 0; i < nSubPixels; i += 4) {
data[i + 0] = remap(data[i + 0], rMin, rMax, rGoalMin, rGoalMax);
data[i + 1] = remap(data[i + 1], gMin, gMax, gGoalMin, gGoalMax);
data[i + 2] = remap(data[i + 2], bMin, bMax, bGoalMin, bGoalMax);
//data[i + 3] = remap(data[i + 3], aMin, aMax, aGoalMin, aGoalMax);
}
};
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'enhance', 0, null, Kinetic.Factory.afterSetFilter);
/**
* get/set enhance
* @name enhance
* @method
* @memberof Kinetic.Node.prototype
* @param {Float} amount
* @returns {Float}
*/
})();
;(function () {
/**
* Posterize Filter. Adjusts the channels so that there are no more
* than n different values for that channel. This is also applied
* to the alpha channel.
* @function
* @author ippo615
* @memberof Kinetic.Filters
* @param {Object} imageData
*/
Kinetic.Filters.Posterize = function (imageData) {
// level must be between 1 and 255
var levels = Math.round(this.levels() * 254) + 1,
data = imageData.data,
len = data.length,
scale = (255 / levels),
i;
for (i = 0; i < len; i += 1) {
data[i] = Math.floor(data[i] / scale) * scale;
}
};
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'levels', 0.5, null, Kinetic.Factory.afterSetFilter);
/**
* get/set levels. Must be a number between 0 and 1
* @name levels
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} level between 0 and 1
* @returns {Number}
*/
})();;(function () {
/**
* Noise Filter. Randomly adds or substracts to the color channels
* @function
* @memberof Kinetic.Filters
* @param {Object} imagedata
* @author ippo615
*/
Kinetic.Filters.Noise = function (imageData) {
var amount = this.noise() * 255,
data = imageData.data,
nPixels = data.length,
half = amount / 2,
i;
for (i = 0; i < nPixels; i += 4) {
data[i + 0] += half - 2 * half * Math.random();
data[i + 1] += half - 2 * half * Math.random();
data[i + 2] += half - 2 * half * Math.random();
}
};
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'noise', 0.2, null, Kinetic.Factory.afterSetFilter);
/**
* get/set noise amount. Must be a value between 0 and 1
* @name noise
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} noise
* @returns {Number}
*/
})();
;(function () {
/**
* Pixelate Filter. Averages groups of pixels and redraws
* them as larger pixels
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
* @author ippo615
*/
Kinetic.Filters.Pixelate = function (imageData) {
var pixelSize = Math.ceil(this.pixelSize()),
width = imageData.width,
height = imageData.height,
x, y, i,
//pixelsPerBin = pixelSize * pixelSize,
red, green, blue, alpha,
nBinsX = Math.ceil(width / pixelSize),
nBinsY = Math.ceil(height / pixelSize),
xBinStart, xBinEnd, yBinStart, yBinEnd,
xBin, yBin, pixelsInBin;
imageData = imageData.data;
for (xBin = 0; xBin < nBinsX; xBin += 1) {
for (yBin = 0; yBin < nBinsY; yBin += 1) {
// Initialize the color accumlators to 0
red = 0;
green = 0;
blue = 0;
alpha = 0;
// Determine which pixels are included in this bin
xBinStart = xBin * pixelSize;
xBinEnd = xBinStart + pixelSize;
yBinStart = yBin * pixelSize;
yBinEnd = yBinStart + pixelSize;
// Add all of the pixels to this bin!
pixelsInBin = 0;
for (x = xBinStart; x < xBinEnd; x += 1) {
if( x >= width ){ continue; }
for (y = yBinStart; y < yBinEnd; y += 1) {
if( y >= height ){ continue; }
i = (width * y + x) * 4;
red += imageData[i + 0];
green += imageData[i + 1];
blue += imageData[i + 2];
alpha += imageData[i + 3];
pixelsInBin += 1;
}
}
// Make sure the channels are between 0-255
red = red / pixelsInBin;
green = green / pixelsInBin;
blue = blue / pixelsInBin;
// Draw this bin
for (x = xBinStart; x < xBinEnd; x += 1) {
if( x >= width ){ continue; }
for (y = yBinStart; y < yBinEnd; y += 1) {
if( y >= height ){ continue; }
i = (width * y + x) * 4;
imageData[i + 0] = red;
imageData[i + 1] = green;
imageData[i + 2] = blue;
imageData[i + 3] = alpha;
}
}
}
}
};
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'pixelSize', 8, null, Kinetic.Factory.afterSetFilter);
/**
* get/set pixel size
* @name pixelSize
* @method
* @memberof Kinetic.Node.prototype
* @param {Integer} pixelSize
* @returns {Integer}
*/
})();;(function () {
/**
* Threshold Filter. Pushes any value above the mid point to
* the max and any value below the mid point to the min.
* This affects the alpha channel.
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
* @author ippo615
*/
Kinetic.Filters.Threshold = function (imageData) {
var level = this.threshold() * 255,
data = imageData.data,
len = data.length,
i;
for (i = 0; i < len; i += 1) {
data[i] = data[i] < level ? 0 : 255;
}
};
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'threshold', 0.5, null, Kinetic.Factory.afterSetFilter);
/**
* get/set threshold. Must be a value between 0 and 1
* @name threshold
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} threshold
* @returns {Number}
*/
})();;(function() {
/**
* Sepia Filter
* Based on: Pixastic Lib - Sepia filter - v0.1.0
* Copyright (c) 2008 Jacob Seidelin, jseidelin@nihilogic.dk, http://blog.nihilogic.dk/
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
* @author Jacob Seidelin <jseidelin@nihilogic.dk>
* @license MPL v1.1 [http://www.pixastic.com/lib/license.txt]
*/
Kinetic.Filters.Sepia = function (imageData) {
var data = imageData.data,
w = imageData.width,
y = imageData.height,
w4 = w*4,
offsetY, x, offset, or, og, ob, r, g, b;
do {
offsetY = (y-1)*w4;
x = w;
do {
offset = offsetY + (x-1)*4;
or = data[offset];
og = data[offset+1];
ob = data[offset+2];
r = or * 0.393 + og * 0.769 + ob * 0.189;
g = or * 0.349 + og * 0.686 + ob * 0.168;
b = or * 0.272 + og * 0.534 + ob * 0.131;
data[offset] = r > 255 ? 255 : r;
data[offset+1] = g > 255 ? 255 : g;
data[offset+2] = b > 255 ? 255 : b;
data[offset+3] = data[offset+3];
} while (--x);
} while (--y);
};
})();
;(function () {
/**
* Solarize Filter
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
* Pixastic Lib - Solarize filter - v0.1.0
* Copyright (c) 2008 Jacob Seidelin, jseidelin@nihilogic.dk, http://blog.nihilogic.dk/
* License: [http://www.pixastic.com/lib/license.txt]
*/
Kinetic.Filters.Solarize = function (imageData) {
var data = imageData.data,
w = imageData.width,
h = imageData.height,
w4 = w*4,
y = h;
do {
var offsetY = (y-1)*w4;
var x = w;
do {
var offset = offsetY + (x-1)*4;
var r = data[offset];
var g = data[offset+1];
var b = data[offset+2];
if (r > 127) {
r = 255 - r;
}
if (g > 127) {
g = 255 - g;
}
if (b > 127) {
b = 255 - b;
}
data[offset] = r;
data[offset+1] = g;
data[offset+2] = b;
} while (--x);
} while (--y);
};
})();
;/*jshint newcap:false */
(function () {
/*
* ToPolar Filter. Converts image data to polar coordinates. Performs
* w*h*4 pixel reads and w*h pixel writes. The r axis is placed along
* what would be the y axis and the theta axis along the x axis.
* @function
* @author ippo615
* @memberof Kinetic.Filters
* @param {ImageData} src, the source image data (what will be transformed)
* @param {ImageData} dst, the destination image data (where it will be saved)
* @param {Object} opt
* @param {Number} [opt.polarCenterX] horizontal location for the center of the circle,
* default is in the middle
* @param {Number} [opt.polarCenterY] vertical location for the center of the circle,
* default is in the middle
*/
var ToPolar = function(src,dst,opt){
var srcPixels = src.data,
dstPixels = dst.data,
xSize = src.width,
ySize = src.height,
xMid = opt.polarCenterX || xSize/2,
yMid = opt.polarCenterY || ySize/2,
i, x, y, r=0,g=0,b=0,a=0;
// Find the largest radius
var rad, rMax = Math.sqrt( xMid*xMid + yMid*yMid );
x = xSize - xMid;
y = ySize - yMid;
rad = Math.sqrt( x*x + y*y );
rMax = (rad > rMax)?rad:rMax;
// We'll be uisng y as the radius, and x as the angle (theta=t)
var rSize = ySize,
tSize = xSize,
radius, theta;
// We want to cover all angles (0-360) and we need to convert to
// radians (*PI/180)
var conversion = 360/tSize*Math.PI/180, sin, cos;
// var x1, x2, x1i, x2i, y1, y2, y1i, y2i, scale;
for( theta=0; theta<tSize; theta+=1 ){
sin = Math.sin(theta*conversion);
cos = Math.cos(theta*conversion);
for( radius=0; radius<rSize; radius+=1 ){
x = Math.floor(xMid+rMax*radius/rSize*cos);
y = Math.floor(yMid+rMax*radius/rSize*sin);
i = (y*xSize + x)*4;
r = srcPixels[i+0];
g = srcPixels[i+1];
b = srcPixels[i+2];
a = srcPixels[i+3];
// Store it
//i = (theta * xSize + radius) * 4;
i = (theta + radius*xSize) * 4;
dstPixels[i+0] = r;
dstPixels[i+1] = g;
dstPixels[i+2] = b;
dstPixels[i+3] = a;
}
}
};
/*
* FromPolar Filter. Converts image data from polar coordinates back to rectangular.
* Performs w*h*4 pixel reads and w*h pixel writes.
* @function
* @author ippo615
* @memberof Kinetic.Filters
* @param {ImageData} src, the source image data (what will be transformed)
* @param {ImageData} dst, the destination image data (where it will be saved)
* @param {Object} opt
* @param {Number} [opt.polarCenterX] horizontal location for the center of the circle,
* default is in the middle
* @param {Number} [opt.polarCenterY] vertical location for the center of the circle,
* default is in the middle
* @param {Number} [opt.polarRotation] amount to rotate the image counterclockwis,
* 0 is no rotation, 360 degrees is a full rotation
*/
var FromPolar = function(src,dst,opt){
var srcPixels = src.data,
dstPixels = dst.data,
xSize = src.width,
ySize = src.height,
xMid = opt.polarCenterX || xSize/2,
yMid = opt.polarCenterY || ySize/2,
i, x, y, dx, dy, r=0,g=0,b=0,a=0;
// Find the largest radius
var rad, rMax = Math.sqrt( xMid*xMid + yMid*yMid );
x = xSize - xMid;
y = ySize - yMid;
rad = Math.sqrt( x*x + y*y );
rMax = (rad > rMax)?rad:rMax;
// We'll be uisng x as the radius, and y as the angle (theta=t)
var rSize = ySize,
tSize = xSize,
radius, theta,
phaseShift = opt.polarRotation || 0;
// We need to convert to degrees and we need to make sure
// it's between (0-360)
// var conversion = tSize/360*180/Math.PI;
//var conversion = tSize/360*180/Math.PI;
var x1, y1;
for( x=0; x<xSize; x+=1 ){
for( y=0; y<ySize; y+=1 ){
dx = x - xMid;
dy = y - yMid;
radius = Math.sqrt(dx*dx + dy*dy)*rSize/rMax;
theta = (Math.atan2(dy,dx)*180/Math.PI + 360 + phaseShift)%360;
theta = theta*tSize/360;
x1 = Math.floor(theta);
y1 = Math.floor(radius);
i = (y1*xSize + x1)*4;
r = srcPixels[i+0];
g = srcPixels[i+1];
b = srcPixels[i+2];
a = srcPixels[i+3];
// Store it
i = (y*xSize + x)*4;
dstPixels[i+0] = r;
dstPixels[i+1] = g;
dstPixels[i+2] = b;
dstPixels[i+3] = a;
}
}
};
//Kinetic.Filters.ToPolar = Kinetic.Util._FilterWrapDoubleBuffer(ToPolar);
//Kinetic.Filters.FromPolar = Kinetic.Util._FilterWrapDoubleBuffer(FromPolar);
// create a temporary canvas for working - shared between multiple calls
var tempCanvas = Kinetic.Util.createCanvasElement();
/*
* Kaleidoscope Filter.
* @function
* @author ippo615
* @memberof Kinetic.Filters
*/
Kinetic.Filters.Kaleidoscope = function(imageData){
var xSize = imageData.width,
ySize = imageData.height;
var x,y,xoff,i, r,g,b,a, srcPos, dstPos;
var power = Math.round( this.kaleidoscopePower() );
var angle = Math.round( this.kaleidoscopeAngle() );
var offset = Math.floor(xSize*(angle%360)/360);
if( power < 1 ){return;}
// Work with our shared buffer canvas
tempCanvas.width = xSize;
tempCanvas.height = ySize;
var scratchData = tempCanvas.getContext('2d').getImageData(0,0,xSize,ySize);
// Convert thhe original to polar coordinates
ToPolar( imageData, scratchData, {
polarCenterX:xSize/2,
polarCenterY:ySize/2
});
// Determine how big each section will be, if it's too small
// make it bigger
var minSectionSize = xSize / Math.pow(2,power);
while( minSectionSize <= 8){
minSectionSize = minSectionSize*2;
power -= 1;
}
minSectionSize = Math.ceil(minSectionSize);
var sectionSize = minSectionSize;
// Copy the offset region to 0
// Depending on the size of filter and location of the offset we may need
// to copy the section backwards to prevent it from rewriting itself
var xStart = 0,
xEnd = sectionSize,
xDelta = 1;
if( offset+minSectionSize > xSize ){
xStart = sectionSize;
xEnd = 0;
xDelta = -1;
}
for( y=0; y<ySize; y+=1 ){
for( x=xStart; x !== xEnd; x+=xDelta ){
xoff = Math.round(x+offset)%xSize;
srcPos = (xSize*y+xoff)*4;
r = scratchData.data[srcPos+0];
g = scratchData.data[srcPos+1];
b = scratchData.data[srcPos+2];
a = scratchData.data[srcPos+3];
dstPos = (xSize*y+x)*4;
scratchData.data[dstPos+0] = r;
scratchData.data[dstPos+1] = g;
scratchData.data[dstPos+2] = b;
scratchData.data[dstPos+3] = a;
}
}
// Perform the actual effect
for( y=0; y<ySize; y+=1 ){
sectionSize = Math.floor( minSectionSize );
for( i=0; i<power; i+=1 ){
for( x=0; x<sectionSize+1; x+=1 ){
srcPos = (xSize*y+x)*4;
r = scratchData.data[srcPos+0];
g = scratchData.data[srcPos+1];
b = scratchData.data[srcPos+2];
a = scratchData.data[srcPos+3];
dstPos = (xSize*y+sectionSize*2-x-1)*4;
scratchData.data[dstPos+0] = r;
scratchData.data[dstPos+1] = g;
scratchData.data[dstPos+2] = b;
scratchData.data[dstPos+3] = a;
}
sectionSize *= 2;
}
}
// Convert back from polar coordinates
FromPolar(scratchData,imageData,{polarRotation:0});
};
/**
* get/set kaleidoscope power
* @name kaleidoscopePower
* @method
* @memberof Kinetic.Node.prototype
* @param {Integer} power of kaleidoscope
* @returns {Integer}
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'kaleidoscopePower', 2, null, Kinetic.Factory.afterSetFilter);
/**
* get/set kaleidoscope angle
* @name kaleidoscopeAngle
* @method
* @memberof Kinetic.Node.prototype
* @param {Integer} degrees
* @returns {Integer}
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'kaleidoscopeAngle', 0, null, Kinetic.Factory.afterSetFilter);
})();
;(function() {
var BATCH_DRAW_STOP_TIME_DIFF = 500;
var now =(function() {
if (Kinetic.root.performance && Kinetic.root.performance.now) {
return function() {
return Kinetic.root.performance.now();
};
}
else {
return function() {
return new Date().getTime();
};
}
})();
var RAF = (function() {
return Kinetic.root.requestAnimationFrame
|| Kinetic.root.webkitRequestAnimationFrame
|| Kinetic.root.mozRequestAnimationFrame
|| Kinetic.root.oRequestAnimationFrame
|| Kinetic.root.msRequestAnimationFrame
|| FRAF;
})();
function FRAF(callback) {
Kinetic.root.setTimeout(callback, 1000 / 60);
}
function requestAnimFrame() {
return RAF.apply(Kinetic.root, arguments);
}
/**
* Animation constructor. A stage is used to contain multiple layers and handle
* @constructor
* @memberof Kinetic
* @param {Function} func function executed on each animation frame. The function is passed a frame object, which contains
* timeDiff, lastTime, time, and frameRate properties. The timeDiff property is the number of milliseconds that have passed
* since the last animation frame. The lastTime property is time in milliseconds that elapsed from the moment the animation started
* to the last animation frame. The time property is the time in milliseconds that ellapsed from the moment the animation started
* to the current animation frame. The frameRate property is the current frame rate in frames / second
* @param {Kinetic.Layer|Array} [layers] layer(s) to be redrawn on each animation frame. Can be a layer, an array of layers, or null.
* Not specifying a node will result in no redraw.
* @example
* // move a node to the right at 50 pixels / second<br>
* var velocity = 50;<br><br>
*
* var anim = new Kinetic.Animation(function(frame) {<br>
* var dist = velocity * (frame.timeDiff / 1000);<br>
* node.move(dist, 0);<br>
* }, layer);<br><br>
*
* anim.start();
*/
Kinetic.Animation = function(func, layers) {
var Anim = Kinetic.Animation;
this.func = func;
this.setLayers(layers);
this.id = Anim.animIdCounter++;
this.frame = {
time: 0,
timeDiff: 0,
lastTime: now()
};
};
/*
* Animation methods
*/
Kinetic.Animation.prototype = {
/**
* set layers to be redrawn on each animation frame
* @method
* @memberof Kinetic.Animation.prototype
* @param {Kinetic.Layer|Array} [layers] layer(s) to be redrawn. Can be a layer, an array of layers, or null. Not specifying a node will result in no redraw.
*/
setLayers: function(layers) {
var lays = [];
// if passing in no layers
if (!layers) {
lays = [];
}
// if passing in an array of Layers
// NOTE: layers could be an array or Kinetic.Collection. for simplicity, I'm just inspecting
// the length property to check for both cases
else if (layers.length > 0) {
lays = layers;
}
// if passing in a Layer
else {
lays = [layers];
}
this.layers = lays;
},
/**
* get layers
* @method
* @memberof Kinetic.Animation.prototype
*/
getLayers: function() {
return this.layers;
},
/**
* add layer. Returns true if the layer was added, and false if it was not
* @method
* @memberof Kinetic.Animation.prototype
* @param {Kinetic.Layer} layer
*/
addLayer: function(layer) {
var layers = this.layers,
len, n;
if (layers) {
len = layers.length;
// don't add the layer if it already exists
for (n = 0; n < len; n++) {
if (layers[n]._id === layer._id) {
return false;
}
}
}
else {
this.layers = [];
}
this.layers.push(layer);
return true;
},
/**
* determine if animation is running or not. returns true or false
* @method
* @memberof Kinetic.Animation.prototype
*/
isRunning: function() {
var a = Kinetic.Animation,
animations = a.animations,
len = animations.length,
n;
for(n = 0; n < len; n++) {
if(animations[n].id === this.id) {
return true;
}
}
return false;
},
/**
* start animation
* @method
* @memberof Kinetic.Animation.prototype
*/
start: function() {
var Anim = Kinetic.Animation;
this.stop();
this.frame.timeDiff = 0;
this.frame.lastTime = now();
Anim._addAnimation(this);
},
/**
* stop animation
* @method
* @memberof Kinetic.Animation.prototype
*/
stop: function() {
Kinetic.Animation._removeAnimation(this);
},
_updateFrameObject: function(time) {
this.frame.timeDiff = time - this.frame.lastTime;
this.frame.lastTime = time;
this.frame.time += this.frame.timeDiff;
this.frame.frameRate = 1000 / this.frame.timeDiff;
}
};
Kinetic.Animation.animations = [];
Kinetic.Animation.animIdCounter = 0;
Kinetic.Animation.animRunning = false;
Kinetic.Animation._addAnimation = function(anim) {
this.animations.push(anim);
this._handleAnimation();
};
Kinetic.Animation._removeAnimation = function(anim) {
var id = anim.id,
animations = this.animations,
len = animations.length,
n;
for(n = 0; n < len; n++) {
if(animations[n].id === id) {
this.animations.splice(n, 1);
break;
}
}
};
Kinetic.Animation._runFrames = function() {
var layerHash = {},
animations = this.animations,
anim, layers, func, n, i, layersLen, layer, key;
/*
* loop through all animations and execute animation
* function. if the animation object has specified node,
* we can add the node to the nodes hash to eliminate
* drawing the same node multiple times. The node property
* can be the stage itself or a layer
*/
/*
* WARNING: don't cache animations.length because it could change while
* the for loop is running, causing a JS error
*/
for(n = 0; n < animations.length; n++) {
anim = animations[n];
layers = anim.layers;
func = anim.func;
anim._updateFrameObject(now());
layersLen = layers.length;
for (i=0; i<layersLen; i++) {
layer = layers[i];
if(layer._id !== undefined) {
layerHash[layer._id] = layer;
}
}
// if animation object has a function, execute it
if(func) {
func.call(anim, anim.frame);
}
}
for(key in layerHash) {
layerHash[key].draw();
}
};
Kinetic.Animation._animationLoop = function() {
var Anim = Kinetic.Animation;
if(Anim.animations.length) {
requestAnimFrame(Anim._animationLoop);
Anim._runFrames();
}
else {
Anim.animRunning = false;
}
};
Kinetic.Animation._handleAnimation = function() {
var that = this;
if(!this.animRunning) {
this.animRunning = true;
that._animationLoop();
}
};
var moveTo = Kinetic.Node.prototype.moveTo;
Kinetic.Node.prototype.moveTo = function(container) {
moveTo.call(this, container);
};
/**
* batch draw
* @method
* @memberof Kinetic.Layer.prototype
*/
Kinetic.Layer.prototype.batchDraw = function() {
var that = this,
Anim = Kinetic.Animation;
if (!this.batchAnim) {
this.batchAnim = new Anim(function() {
if (that.lastBatchDrawTime && now() - that.lastBatchDrawTime > BATCH_DRAW_STOP_TIME_DIFF) {
that.batchAnim.stop();
}
}, this);
}
this.lastBatchDrawTime = now();
if (!this.batchAnim.isRunning()) {
this.draw();
this.batchAnim.start();
}
};
/**
* batch draw
* @method
* @memberof Kinetic.Stage.prototype
*/
Kinetic.Stage.prototype.batchDraw = function() {
this.getChildren().each(function(layer) {
layer.batchDraw();
});
};
})((1,eval)('this'));;(function() {
var blacklist = {
node: 1,
duration: 1,
easing: 1,
onFinish: 1,
yoyo: 1
},
PAUSED = 1,
PLAYING = 2,
REVERSING = 3,
idCounter = 0;
/**
* Tween constructor. Tweens enable you to animate a node between the current state and a new state.
* You can play, pause, reverse, seek, reset, and finish tweens. By default, tweens are animated using
* a linear easing. For more tweening options, check out {@link Kinetic.Easings}
* @constructor
* @memberof Kinetic
* @example
* // instantiate new tween which fully rotates a node in 1 second
* var tween = new Kinetic.Tween({<br>
* node: node,<br>
* rotationDeg: 360,<br>
* duration: 1,<br>
* easing: Kinetic.Easings.EaseInOut<br>
* });<br><br>
*
* // play tween<br>
* tween.play();<br><br>
*
* // pause tween<br>
* tween.pause();
*/
Kinetic.Tween = function(config) {
var that = this,
node = config.node,
nodeId = node._id,
duration = config.duration || 1,
easing = config.easing || Kinetic.Easings.Linear,
yoyo = !!config.yoyo,
key;
this.node = node;
this._id = idCounter++;
this.anim = new Kinetic.Animation(function() {
that.tween.onEnterFrame();
}, node.getLayer());
this.tween = new Tween(key, function(i) {
that._tweenFunc(i);
}, easing, 0, 1, duration * 1000, yoyo);
this._addListeners();
// init attrs map
if (!Kinetic.Tween.attrs[nodeId]) {
Kinetic.Tween.attrs[nodeId] = {};
}
if (!Kinetic.Tween.attrs[nodeId][this._id]) {
Kinetic.Tween.attrs[nodeId][this._id] = {};
}
// init tweens map
if (!Kinetic.Tween.tweens[nodeId]) {
Kinetic.Tween.tweens[nodeId] = {};
}
for (key in config) {
if (blacklist[key] === undefined) {
this._addAttr(key, config[key]);
}
}
this.reset();
// callbacks
this.onFinish = config.onFinish;
this.onReset = config.onReset;
};
// start/diff object = attrs.nodeId.tweenId.attr
Kinetic.Tween.attrs = {};
// tweenId = tweens.nodeId.attr
Kinetic.Tween.tweens = {};
Kinetic.Tween.prototype = {
_addAttr: function(key, end) {
var node = this.node,
nodeId = node._id,
start, diff, tweenId, n, len;
// remove conflict from tween map if it exists
tweenId = Kinetic.Tween.tweens[nodeId][key];
if (tweenId) {
delete Kinetic.Tween.attrs[nodeId][tweenId][key];
}
// add to tween map
start = node.getAttr(key);
if (Kinetic.Util._isArray(end)) {
diff = [];
len = end.length;
for (n=0; n<len; n++) {
diff.push(end[n] - start[n]);
}
}
else {
diff = end - start;
}
Kinetic.Tween.attrs[nodeId][this._id][key] = {
start: start,
diff: diff
};
Kinetic.Tween.tweens[nodeId][key] = this._id;
},
_tweenFunc: function(i) {
var node = this.node,
attrs = Kinetic.Tween.attrs[node._id][this._id],
key, attr, start, diff, newVal, n, len;
for (key in attrs) {
attr = attrs[key];
start = attr.start;
diff = attr.diff;
if (Kinetic.Util._isArray(start)) {
newVal = [];
len = start.length;
for (n=0; n<len; n++) {
newVal.push(start[n] + (diff[n] * i));
}
}
else {
newVal = start + (diff * i);
}
node.setAttr(key, newVal);
}
},
_addListeners: function() {
var that = this;
// start listeners
this.tween.onPlay = function() {
that.anim.start();
};
this.tween.onReverse = function() {
that.anim.start();
};
// stop listeners
this.tween.onPause = function() {
that.anim.stop();
};
this.tween.onFinish = function() {
if (that.onFinish) {
that.onFinish();
}
};
this.tween.onReset = function() {
if (that.onReset) {
that.onReset();
}
};
},
/**
* play
* @method
* @memberof Kinetic.Tween.prototype
* @returns {Tween}
*/
play: function() {
this.tween.play();
return this;
},
/**
* reverse
* @method
* @memberof Kinetic.Tween.prototype
* @returns {Tween}
*/
reverse: function() {
this.tween.reverse();
return this;
},
/**
* reset
* @method
* @memberof Kinetic.Tween.prototype
* @returns {Tween}
*/
reset: function() {
var node = this.node;
this.tween.reset();
return this;
},
/**
* seek
* @method
* @memberof Kinetic.Tween.prototype
* @param {Integer} t time in seconds between 0 and the duration
* @returns {Tween}
*/
seek: function(t) {
var node = this.node;
this.tween.seek(t * 1000);
return this;
},
/**
* pause
* @method
* @memberof Kinetic.Tween.prototype
* @returns {Tween}
*/
pause: function() {
this.tween.pause();
return this;
},
/**
* finish
* @method
* @memberof Kinetic.Tween.prototype
* @returns {Tween}
*/
finish: function() {
var node = this.node;
this.tween.finish();
return this;
},
/**
* destroy
* @method
* @memberof Kinetic.Tween.prototype
*/
destroy: function() {
var nodeId = this.node._id,
thisId = this._id,
attrs = Kinetic.Tween.tweens[nodeId],
key;
this.pause();
for (key in attrs) {
delete Kinetic.Tween.tweens[nodeId][key];
}
delete Kinetic.Tween.attrs[nodeId][thisId];
}
};
var Tween = function(prop, propFunc, func, begin, finish, duration, yoyo) {
this.prop = prop;
this.propFunc = propFunc;
this.begin = begin;
this._pos = begin;
this.duration = duration;
this._change = 0;
this.prevPos = 0;
this.yoyo = yoyo;
this._time = 0;
this._position = 0;
this._startTime = 0;
this._finish = 0;
this.func = func;
this._change = finish - this.begin;
this.pause();
};
/*
* Tween methods
*/
Tween.prototype = {
fire: function(str) {
var handler = this[str];
if (handler) {
handler();
}
},
setTime: function(t) {
if(t > this.duration) {
if(this.yoyo) {
this._time = this.duration;
this.reverse();
}
else {
this.finish();
}
}
else if(t < 0) {
if(this.yoyo) {
this._time = 0;
this.play();
}
else {
this.reset();
}
}
else {
this._time = t;
this.update();
}
},
getTime: function() {
return this._time;
},
setPosition: function(p) {
this.prevPos = this._pos;
this.propFunc(p);
this._pos = p;
},
getPosition: function(t) {
if(t === undefined) {
t = this._time;
}
return this.func(t, this.begin, this._change, this.duration);
},
play: function() {
this.state = PLAYING;
this._startTime = this.getTimer() - this._time;
this.onEnterFrame();
this.fire('onPlay');
},
reverse: function() {
this.state = REVERSING;
this._time = this.duration - this._time;
this._startTime = this.getTimer() - this._time;
this.onEnterFrame();
this.fire('onReverse');
},
seek: function(t) {
this.pause();
this._time = t;
this.update();
this.fire('onSeek');
},
reset: function() {
this.pause();
this._time = 0;
this.update();
this.fire('onReset');
},
finish: function() {
this.pause();
this._time = this.duration;
this.update();
this.fire('onFinish');
},
update: function() {
this.setPosition(this.getPosition(this._time));
},
onEnterFrame: function() {
var t = this.getTimer() - this._startTime;
if(this.state === PLAYING) {
this.setTime(t);
}
else if (this.state === REVERSING) {
this.setTime(this.duration - t);
}
},
pause: function() {
this.state = PAUSED;
this.fire('onPause');
},
getTimer: function() {
return new Date().getTime();
}
};
/*
* These eases were ported from an Adobe Flash tweening library to JavaScript
* by Xaric
*/
/**
* @namespace Easings
* @memberof Kinetic
*/
Kinetic.Easings = {
/**
* back ease in
* @function
* @memberof Kinetic.Easings
*/
'BackEaseIn': function(t, b, c, d) {
var s = 1.70158;
return c * (t /= d) * t * ((s + 1) * t - s) + b;
},
/**
* back ease out
* @function
* @memberof Kinetic.Easings
*/
'BackEaseOut': function(t, b, c, d) {
var s = 1.70158;
return c * (( t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
},
/**
* back ease in out
* @function
* @memberof Kinetic.Easings
*/
'BackEaseInOut': function(t, b, c, d) {
var s = 1.70158;
if((t /= d / 2) < 1) {
return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
}
return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
},
/**
* elastic ease in
* @function
* @memberof Kinetic.Easings
*/
'ElasticEaseIn': function(t, b, c, d, a, p) {
// added s = 0
var s = 0;
if(t === 0) {
return b;
}
if((t /= d) == 1) {
return b + c;
}
if(!p) {
p = d * 0.3;
}
if(!a || a < Math.abs(c)) {
a = c;
s = p / 4;
}
else {
s = p / (2 * Math.PI) * Math.asin(c / a);
}
return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
},
/**
* elastic ease out
* @function
* @memberof Kinetic.Easings
*/
'ElasticEaseOut': function(t, b, c, d, a, p) {
// added s = 0
var s = 0;
if(t === 0) {
return b;
}
if((t /= d) == 1) {
return b + c;
}
if(!p) {
p = d * 0.3;
}
if(!a || a < Math.abs(c)) {
a = c;
s = p / 4;
}
else {
s = p / (2 * Math.PI) * Math.asin(c / a);
}
return (a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b);
},
/**
* elastic ease in out
* @function
* @memberof Kinetic.Easings
*/
'ElasticEaseInOut': function(t, b, c, d, a, p) {
// added s = 0
var s = 0;
if(t === 0) {
return b;
}
if((t /= d / 2) == 2) {
return b + c;
}
if(!p) {
p = d * (0.3 * 1.5);
}
if(!a || a < Math.abs(c)) {
a = c;
s = p / 4;
}
else {
s = p / (2 * Math.PI) * Math.asin(c / a);
}
if(t < 1) {
return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
}
return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p) * 0.5 + c + b;
},
/**
* bounce ease out
* @function
* @memberof Kinetic.Easings
*/
'BounceEaseOut': function(t, b, c, d) {
if((t /= d) < (1 / 2.75)) {
return c * (7.5625 * t * t) + b;
}
else if(t < (2 / 2.75)) {
return c * (7.5625 * (t -= (1.5 / 2.75)) * t + 0.75) + b;
}
else if(t < (2.5 / 2.75)) {
return c * (7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375) + b;
}
else {
return c * (7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375) + b;
}
},
/**
* bounce ease in
* @function
* @memberof Kinetic.Easings
*/
'BounceEaseIn': function(t, b, c, d) {
return c - Kinetic.Easings.BounceEaseOut(d - t, 0, c, d) + b;
},
/**
* bounce ease in out
* @function
* @memberof Kinetic.Easings
*/
'BounceEaseInOut': function(t, b, c, d) {
if(t < d / 2) {
return Kinetic.Easings.BounceEaseIn(t * 2, 0, c, d) * 0.5 + b;
}
else {
return Kinetic.Easings.BounceEaseOut(t * 2 - d, 0, c, d) * 0.5 + c * 0.5 + b;
}
},
/**
* ease in
* @function
* @memberof Kinetic.Easings
*/
'EaseIn': function(t, b, c, d) {
return c * (t /= d) * t + b;
},
/**
* ease out
* @function
* @memberof Kinetic.Easings
*/
'EaseOut': function(t, b, c, d) {
return -c * (t /= d) * (t - 2) + b;
},
/**
* ease in out
* @function
* @memberof Kinetic.Easings
*/
'EaseInOut': function(t, b, c, d) {
if((t /= d / 2) < 1) {
return c / 2 * t * t + b;
}
return -c / 2 * ((--t) * (t - 2) - 1) + b;
},
/**
* strong ease in
* @function
* @memberof Kinetic.Easings
*/
'StrongEaseIn': function(t, b, c, d) {
return c * (t /= d) * t * t * t * t + b;
},
/**
* strong ease out
* @function
* @memberof Kinetic.Easings
*/
'StrongEaseOut': function(t, b, c, d) {
return c * (( t = t / d - 1) * t * t * t * t + 1) + b;
},
/**
* strong ease in out
* @function
* @memberof Kinetic.Easings
*/
'StrongEaseInOut': function(t, b, c, d) {
if((t /= d / 2) < 1) {
return c / 2 * t * t * t * t * t + b;
}
return c / 2 * ((t -= 2) * t * t * t * t + 2) + b;
},
/**
* linear
* @function
* @memberof Kinetic.Easings
*/
'Linear': function(t, b, c, d) {
return c * t / d + b;
}
};
})();
;(function() {
Kinetic.DD = {
// properties
anim: new Kinetic.Animation(),
isDragging: false,
offset: {
x: 0,
y: 0
},
node: null,
// methods
_drag: function(evt) {
var dd = Kinetic.DD,
node = dd.node;
if(node) {
if(!dd.isDragging) {
var pos = node.getStage().getPointerPosition();
var dragDistance = node.dragDistance();
var distance = Math.max(
Math.abs(pos.x - dd.startPointerPos.x),
Math.abs(pos.y - dd.startPointerPos.y)
);
if (distance < dragDistance) {
return;
}
}
node._setDragPosition(evt);
if(!dd.isDragging) {
dd.isDragging = true;
node.fire('dragstart', {
type : 'dragstart',
target : node,
evt : evt
}, true);
}
// execute ondragmove if defined
node.fire('dragmove', {
type : 'dragmove',
target : node,
evt : evt
}, true);
}
},
_endDragBefore: function(evt) {
var dd = Kinetic.DD,
node = dd.node,
nodeType, layer;
if(node) {
nodeType = node.nodeType;
layer = node.getLayer();
dd.anim.stop();
// only fire dragend event if the drag and drop
// operation actually started.
if(dd.isDragging) {
dd.isDragging = false;
Kinetic.listenClickTap = false;
if (evt) {
evt.dragEndNode = node;
}
}
delete dd.node;
(layer || node).draw();
}
},
_endDragAfter: function(evt) {
evt = evt || {};
var dragEndNode = evt.dragEndNode;
if (evt && dragEndNode) {
dragEndNode.fire('dragend', {
type : 'dragend',
target : dragEndNode,
evt : evt
}, true);
}
}
};
// Node extenders
/**
* initiate drag and drop
* @method
* @memberof Kinetic.Node.prototype
*/
Kinetic.Node.prototype.startDrag = function() {
var dd = Kinetic.DD,
stage = this.getStage(),
layer = this.getLayer(),
pos = stage.getPointerPosition(),
ap = this.getAbsolutePosition();
if(pos) {
if (dd.node) {
dd.node.stopDrag();
}
dd.node = this;
dd.startPointerPos = pos;
dd.offset.x = pos.x - ap.x;
dd.offset.y = pos.y - ap.y;
dd.anim.setLayers(layer || this.getLayers());
dd.anim.start();
this._setDragPosition();
}
};
Kinetic.Node.prototype._setDragPosition = function(evt) {
var dd = Kinetic.DD,
pos = this.getStage().getPointerPosition(),
dbf = this.getDragBoundFunc();
if (!pos) {
return;
}
var newNodePos = {
x: pos.x - dd.offset.x,
y: pos.y - dd.offset.y
};
if(dbf !== undefined) {
newNodePos = dbf.call(this, newNodePos, evt);
}
this.setAbsolutePosition(newNodePos);
};
/**
* stop drag and drop
* @method
* @memberof Kinetic.Node.prototype
*/
Kinetic.Node.prototype.stopDrag = function() {
var dd = Kinetic.DD,
evt = {};
dd._endDragBefore(evt);
dd._endDragAfter(evt);
};
Kinetic.Node.prototype.setDraggable = function(draggable) {
this._setAttr('draggable', draggable);
this._dragChange();
};
var origDestroy = Kinetic.Node.prototype.destroy;
Kinetic.Node.prototype.destroy = function() {
var dd = Kinetic.DD;
// stop DD
if(dd.node && dd.node._id === this._id) {
this.stopDrag();
}
origDestroy.call(this);
};
/**
* determine if node is currently in drag and drop mode
* @method
* @memberof Kinetic.Node.prototype
*/
Kinetic.Node.prototype.isDragging = function() {
var dd = Kinetic.DD;
return dd.node && dd.node._id === this._id && dd.isDragging;
};
Kinetic.Node.prototype._listenDrag = function() {
var that = this;
this._dragCleanup();
if (this.getClassName() === 'Stage') {
this.on('contentMousedown.kinetic contentTouchstart.kinetic', function(evt) {
if(!Kinetic.DD.node) {
that.startDrag(evt);
}
});
}
else {
this.on('mousedown.kinetic touchstart.kinetic', function(evt) {
if(!Kinetic.DD.node) {
that.startDrag(evt);
}
});
}
// listening is required for drag and drop
/*
this._listeningEnabled = true;
this._clearSelfAndAncestorCache('listeningEnabled');
*/
};
Kinetic.Node.prototype._dragChange = function() {
if(this.attrs.draggable) {
this._listenDrag();
}
else {
// remove event listeners
this._dragCleanup();
/*
* force drag and drop to end
* if this node is currently in
* drag and drop mode
*/
var stage = this.getStage();
var dd = Kinetic.DD;
if(stage && dd.node && dd.node._id === this._id) {
dd.node.stopDrag();
}
}
};
Kinetic.Node.prototype._dragCleanup = function() {
if (this.getClassName() === 'Stage') {
this.off('contentMousedown.kinetic');
this.off('contentTouchstart.kinetic');
} else {
this.off('mousedown.kinetic');
this.off('touchstart.kinetic');
}
};
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'dragBoundFunc');
/**
* get/set drag bound function. This is used to override the default
* drag and drop position
* @name dragBoundFunc
* @method
* @memberof Kinetic.Node.prototype
* @param {Function} dragBoundFunc
* @returns {Function}
* @example
* // get drag bound function<br>
* var dragBoundFunc = node.dragBoundFunc();<br><br>
*
* // create vertical drag and drop<br>
* node.dragBoundFunc(function(){<br>
* return {<br>
* x: this.getAbsolutePosition().x,<br>
* y: pos.y<br>
* };<br>
* });
*/
Kinetic.Factory.addGetter(Kinetic.Node, 'draggable', false);
Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Node, 'draggable');
/**
* get/set draggable flag
* @name draggable
* @method
* @memberof Kinetic.Node.prototype
* @param {Boolean} draggable
* @returns {Boolean}
* @example
* // get draggable flag<br>
* var draggable = node.draggable();<br><br>
*
* // enable drag and drop<br>
* node.draggable(true);<br><br>
*
* // disable drag and drop<br>
* node.draggable(false);
*/
var html = Kinetic.document.documentElement;
html.addEventListener('mouseup', Kinetic.DD._endDragBefore, true);
html.addEventListener('touchend', Kinetic.DD._endDragBefore, true);
html.addEventListener('mouseup', Kinetic.DD._endDragAfter, false);
html.addEventListener('touchend', Kinetic.DD._endDragAfter, false);
})();
;(function() {
Kinetic.Util.addMethods(Kinetic.Container, {
__init: function(config) {
this.children = new Kinetic.Collection();
Kinetic.Node.call(this, config);
},
/**
* returns a {@link Kinetic.Collection} of direct descendant nodes
* @method
* @memberof Kinetic.Container.prototype
* @param {Function} [filterFunc] filter function
* @returns {Kinetic.Collection}
* @example
* // get all children<br>
* var children = layer.getChildren();<br><br>
*
* // get only circles<br>
* var circles = layer.getChildren(function(node){<br>
* return node.getClassName() === 'Circle';<br>
* });
*/
getChildren: function(predicate) {
if (!predicate) {
return this.children;
} else {
var results = new Kinetic.Collection();
this.children.each(function(child){
if (predicate(child)) {
results.push(child);
}
});
return results;
}
},
/**
* determine if node has children
* @method
* @memberof Kinetic.Container.prototype
* @returns {Boolean}
*/
hasChildren: function() {
return this.getChildren().length > 0;
},
/**
* remove all children
* @method
* @memberof Kinetic.Container.prototype
*/
removeChildren: function() {
var children = Kinetic.Collection.toCollection(this.children);
var child;
for (var i = 0; i < children.length; i++) {
child = children[i];
// reset parent to prevent many _setChildrenIndices calls
delete child.parent;
child.index = 0;
if (child.hasChildren()) {
child.removeChildren();
}
child.remove();
}
children = null;
this.children = new Kinetic.Collection();
return this;
},
/**
* destroy all children
* @method
* @memberof Kinetic.Container.prototype
*/
destroyChildren: function() {
var children = Kinetic.Collection.toCollection(this.children);
var child;
for (var i = 0; i < children.length; i++) {
child = children[i];
// reset parent to prevent many _setChildrenIndices calls
delete child.parent;
child.index = 0;
child.destroy();
}
children = null;
this.children = new Kinetic.Collection();
return this;
},
/**
* Add node or nodes to container.
* @method
* @memberof Kinetic.Container.prototype
* @param {...Kinetic.Node} child
* @returns {Container}
* @example
* layer.add(shape1, shape2, shape3);
*/
add: function(child) {
if (arguments.length > 1) {
for (var i = 0; i < arguments.length; i++) {
this.add(arguments[i]);
}
return;
}
if (child.getParent()) {
child.moveTo(this);
return;
}
var children = this.children;
this._validateAdd(child);
child.index = children.length;
child.parent = this;
children.push(child);
this._fire('add', {
child: child
});
// chainable
return this;
},
destroy: function() {
// destroy children
if (this.hasChildren()) {
this.destroyChildren();
}
// then destroy self
Kinetic.Node.prototype.destroy.call(this);
},
/**
* return a {@link Kinetic.Collection} of nodes that match the selector. Use '#' for id selections
* and '.' for name selections. You can also select by type or class name. Pass multiple selectors
* separated by a space.
* @method
* @memberof Kinetic.Container.prototype
* @param {String} selector
* @returns {Collection}
* @example
* // select node with id foo<br>
* var node = stage.find('#foo');<br><br>
*
* // select nodes with name bar inside layer<br>
* var nodes = layer.find('.bar');<br><br>
*
* // select all groups inside layer<br>
* var nodes = layer.find('Group');<br><br>
*
* // select all rectangles inside layer<br>
* var nodes = layer.find('Rect');<br><br>
*
* // select node with an id of foo or a name of bar inside layer<br>
* var nodes = layer.find('#foo, .bar');
*/
find: function(selector) {
var retArr = [],
selectorArr = selector.replace(/ /g, '').split(','),
len = selectorArr.length,
n, i, sel, arr, node, children, clen;
for (n = 0; n < len; n++) {
sel = selectorArr[n];
// id selector
if(sel.charAt(0) === '#') {
node = this._getNodeById(sel.slice(1));
if(node) {
retArr.push(node);
}
}
// name selector
else if(sel.charAt(0) === '.') {
arr = this._getNodesByName(sel.slice(1));
retArr = retArr.concat(arr);
}
// unrecognized selector, pass to children
else {
children = this.getChildren();
clen = children.length;
for(i = 0; i < clen; i++) {
retArr = retArr.concat(children[i]._get(sel));
}
}
}
return Kinetic.Collection.toCollection(retArr);
},
_getNodeById: function(key) {
var node = Kinetic.ids[key];
if(node !== undefined && this.isAncestorOf(node)) {
return node;
}
return null;
},
_getNodesByName: function(key) {
var arr = Kinetic.names[key] || [];
return this._getDescendants(arr);
},
_get: function(selector) {
var retArr = Kinetic.Node.prototype._get.call(this, selector);
var children = this.getChildren();
var len = children.length;
for(var n = 0; n < len; n++) {
retArr = retArr.concat(children[n]._get(selector));
}
return retArr;
},
// extenders
toObject: function() {
var obj = Kinetic.Node.prototype.toObject.call(this);
obj.children = [];
var children = this.getChildren();
var len = children.length;
for(var n = 0; n < len; n++) {
var child = children[n];
obj.children.push(child.toObject());
}
return obj;
},
_getDescendants: function(arr) {
var retArr = [];
var len = arr.length;
for(var n = 0; n < len; n++) {
var node = arr[n];
if(this.isAncestorOf(node)) {
retArr.push(node);
}
}
return retArr;
},
/**
* determine if node is an ancestor
* of descendant
* @method
* @memberof Kinetic.Container.prototype
* @param {Kinetic.Node} node
*/
isAncestorOf: function(node) {
var parent = node.getParent();
while(parent) {
if(parent._id === this._id) {
return true;
}
parent = parent.getParent();
}
return false;
},
clone: function(obj) {
// call super method
var node = Kinetic.Node.prototype.clone.call(this, obj);
this.getChildren().each(function(no) {
node.add(no.clone());
});
return node;
},
/**
* get all shapes that intersect a point. Note: because this method must clear a temporary
* canvas and redraw every shape inside the container, it should only be used for special sitations
* because it performs very poorly. Please use the {@link Kinetic.Stage#getIntersection} method if at all possible
* because it performs much better
* @method
* @memberof Kinetic.Container.prototype
* @param {Object} pos
* @param {Number} pos.x
* @param {Number} pos.y
* @returns {Array} array of shapes
*/
getAllIntersections: function(pos) {
var arr = [];
this.find('Shape').each(function(shape) {
if(shape.isVisible() && shape.intersects(pos)) {
arr.push(shape);
}
});
return arr;
},
_setChildrenIndices: function() {
this.children.each(function(child, n) {
child.index = n;
});
},
drawScene: function(can, top) {
var layer = this.getLayer(),
canvas = can || (layer && layer.getCanvas()),
context = canvas && canvas.getContext(),
cachedCanvas = this._cache.canvas,
cachedSceneCanvas = cachedCanvas && cachedCanvas.scene;
if (this.isVisible()) {
if (cachedSceneCanvas) {
this._drawCachedSceneCanvas(context);
}
else {
this._drawChildren(canvas, 'drawScene', top);
}
}
return this;
},
drawHit: function(can, top) {
var layer = this.getLayer(),
canvas = can || (layer && layer.hitCanvas),
context = canvas && canvas.getContext(),
cachedCanvas = this._cache.canvas,
cachedHitCanvas = cachedCanvas && cachedCanvas.hit;
if (this.shouldDrawHit()) {
if (cachedHitCanvas) {
this._drawCachedHitCanvas(context);
}
else {
this._drawChildren(canvas, 'drawHit', top);
}
}
return this;
},
_drawChildren: function(canvas, drawMethod, top) {
var layer = this.getLayer(),
context = canvas && canvas.getContext(),
clipWidth = this.getClipWidth(),
clipHeight = this.getClipHeight(),
hasClip = clipWidth && clipHeight,
clipX, clipY;
if (hasClip && layer) {
clipX = this.getClipX();
clipY = this.getClipY();
context.save();
layer._applyTransform(this, context);
context.beginPath();
context.rect(clipX, clipY, clipWidth, clipHeight);
context.clip();
context.reset();
}
this.children.each(function(child) {
child[drawMethod](canvas, top);
});
if (hasClip) {
context.restore();
}
}
});
Kinetic.Util.extend(Kinetic.Container, Kinetic.Node);
// deprecated methods
Kinetic.Container.prototype.get = Kinetic.Container.prototype.find;
// add getters setters
Kinetic.Factory.addComponentsGetterSetter(Kinetic.Container, 'clip', ['x', 'y', 'width', 'height']);
/**
* get/set clip
* @method
* @name clip
* @memberof Kinetic.Container.prototype
* @param {Object} clip
* @param {Number} clip.x
* @param {Number} clip.y
* @param {Number} clip.width
* @param {Number} clip.height
* @returns {Object}
* @example
* // get clip<br>
* var clip = container.clip();<br><br>
*
* // set clip<br>
* container.setClip({<br>
* x: 20,<br>
* y: 20,<br>
* width: 20,<br>
* height: 20<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Container, 'clipX');
/**
* get/set clip x
* @name clipX
* @method
* @memberof Kinetic.Container.prototype
* @param {Number} x
* @returns {Number}
* @example
* // get clip x<br>
* var clipX = container.clipX();<br><br>
*
* // set clip x<br>
* container.clipX(10);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Container, 'clipY');
/**
* get/set clip y
* @name clipY
* @method
* @memberof Kinetic.Container.prototype
* @param {Number} y
* @returns {Number}
* @example
* // get clip y<br>
* var clipY = container.clipY();<br><br>
*
* // set clip y<br>
* container.clipY(10);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Container, 'clipWidth');
/**
* get/set clip width
* @name clipWidth
* @method
* @memberof Kinetic.Container.prototype
* @param {Number} width
* @returns {Number}
* @example
* // get clip width<br>
* var clipWidth = container.clipWidth();<br><br>
*
* // set clip width<br>
* container.clipWidth(100);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Container, 'clipHeight');
/**
* get/set clip height
* @name clipHeight
* @method
* @memberof Kinetic.Container.prototype
* @param {Number} height
* @returns {Number}
* @example
* // get clip height<br>
* var clipHeight = container.clipHeight();<br><br>
*
* // set clip height<br>
* container.clipHeight(100);
*/
Kinetic.Collection.mapMethods(Kinetic.Container);
})();
;(function() {
var HAS_SHADOW = 'hasShadow';
function _fillFunc(context) {
context.fill();
}
function _strokeFunc(context) {
context.stroke();
}
function _fillFuncHit(context) {
context.fill();
}
function _strokeFuncHit(context) {
context.stroke();
}
function _clearHasShadowCache() {
this._clearCache(HAS_SHADOW);
}
Kinetic.Util.addMethods(Kinetic.Shape, {
__init: function(config) {
this.nodeType = 'Shape';
this._fillFunc = _fillFunc;
this._strokeFunc = _strokeFunc;
this._fillFuncHit = _fillFuncHit;
this._strokeFuncHit = _strokeFuncHit;
// set colorKey
var shapes = Kinetic.shapes;
var key;
while(true) {
key = Kinetic.Util.getRandomColor();
if(key && !( key in shapes)) {
break;
}
}
this.colorKey = key;
shapes[key] = this;
// call super constructor
Kinetic.Node.call(this, config);
this.on('shadowColorChange.kinetic shadowBlurChange.kinetic shadowOffsetChange.kinetic shadowOpacityChange.kinetic shadowEnabledChange.kinetic', _clearHasShadowCache);
},
hasChildren: function() {
return false;
},
getChildren: function() {
return [];
},
/**
* get canvas context tied to the layer
* @method
* @memberof Kinetic.Shape.prototype
* @returns {Kinetic.Context}
*/
getContext: function() {
return this.getLayer().getContext();
},
/**
* get canvas renderer tied to the layer. Note that this returns a canvas renderer, not a canvas element
* @method
* @memberof Kinetic.Shape.prototype
* @returns {Kinetic.Canvas}
*/
getCanvas: function() {
return this.getLayer().getCanvas();
},
/**
* returns whether or not a shadow will be rendered
* @method
* @memberof Kinetic.Shape.prototype
* @returns {Boolean}
*/
hasShadow: function() {
return this._getCache(HAS_SHADOW, this._hasShadow);
},
_hasShadow: function() {
return this.getShadowEnabled() && (this.getShadowOpacity() !== 0 && !!(this.getShadowColor() || this.getShadowBlur() || this.getShadowOffsetX() || this.getShadowOffsetY()));
},
/**
* returns whether or not the shape will be filled
* @method
* @memberof Kinetic.Shape.prototype
* @returns {Boolean}
*/
hasFill: function() {
return !!(this.getFill() || this.getFillPatternImage() || this.getFillLinearGradientColorStops() || this.getFillRadialGradientColorStops());
},
/**
* returns whether or not the shape will be stroked
* @method
* @memberof Kinetic.Shape.prototype
* @returns {Boolean}
*/
hasStroke: function() {
return !!(this.stroke() || this.strokeRed() || this.strokeGreen() || this.strokeBlue());
},
_get: function(selector) {
return this.className === selector || this.nodeType === selector ? [this] : [];
},
/**
* determines if point is in the shape, regardless if other shapes are on top of it. Note: because
* this method clears a temporary canvas and then redraws the shape, it performs very poorly if executed many times
* consecutively. Please use the {@link Kinetic.Stage#getIntersection} method if at all possible
* because it performs much better
* @method
* @memberof Kinetic.Shape.prototype
* @param {Object} point
* @param {Number} point.x
* @param {Number} point.y
* @returns {Boolean}
*/
intersects: function(pos) {
var stage = this.getStage(),
bufferHitCanvas = stage.bufferHitCanvas,
p;
bufferHitCanvas.getContext().clear();
this.drawScene(bufferHitCanvas);
p = bufferHitCanvas.context.getImageData(Math.round(pos.x), Math.round(pos.y), 1, 1).data;
return p[3] > 0;
},
// extends Node.prototype.destroy
destroy: function() {
Kinetic.Node.prototype.destroy.call(this);
delete Kinetic.shapes[this.colorKey];
},
_useBufferCanvas: function() {
return (this.hasShadow() || this.getAbsoluteOpacity() !== 1) && this.hasFill() && this.hasStroke() && this.getStage();
},
drawScene: function(can, top) {
var layer = this.getLayer(),
canvas = can || layer.getCanvas(),
context = canvas.getContext(),
cachedCanvas = this._cache.canvas,
drawFunc = this.sceneFunc(),
hasShadow = this.hasShadow(),
stage, bufferCanvas, bufferContext;
if(this.isVisible()) {
if (cachedCanvas) {
this._drawCachedSceneCanvas(context);
}
else if (drawFunc) {
context.save();
// if buffer canvas is needed
if (this._useBufferCanvas()) {
stage = this.getStage();
bufferCanvas = stage.bufferCanvas;
bufferContext = bufferCanvas.getContext();
bufferContext.clear();
bufferContext.save();
bufferContext._applyLineJoin(this);
layer._applyTransform(this, bufferContext, top);
drawFunc.call(this, bufferContext);
bufferContext.restore();
if (hasShadow) {
context.save();
context._applyShadow(this);
context.drawImage(bufferCanvas._canvas, 0, 0);
context.restore();
}
context._applyOpacity(this);
context.drawImage(bufferCanvas._canvas, 0, 0);
}
// if buffer canvas is not needed
else {
context._applyLineJoin(this);
layer._applyTransform(this, context, top);
if (hasShadow) {
context.save();
context._applyShadow(this);
drawFunc.call(this, context);
context.restore();
}
context._applyOpacity(this);
drawFunc.call(this, context);
}
context.restore();
}
}
return this;
},
drawHit: function(can, top) {
var layer = this.getLayer(),
canvas = can || layer.hitCanvas,
context = canvas.getContext(),
drawFunc = this.hitFunc() || this.sceneFunc(),
cachedCanvas = this._cache.canvas,
cachedHitCanvas = cachedCanvas && cachedCanvas.hit;
if(this.shouldDrawHit()) {
if (cachedHitCanvas) {
this._drawCachedHitCanvas(context);
}
else if (drawFunc) {
context.save();
context._applyLineJoin(this);
layer._applyTransform(this, context, top);
drawFunc.call(this, context);
context.restore();
}
}
return this;
},
/**
* draw hit graph using the cached scene canvas
* @method
* @memberof Kinetic.Shape.prototype
* @param {Integer} alphaThreshold alpha channel threshold that determines whether or not
* a pixel should be drawn onto the hit graph. Must be a value between 0 and 255.
* The default is 0
* @returns {Kinetic.Shape}
* @example
* shape.cache();
* shape.drawHitFromCache();
*/
drawHitFromCache: function(alphaThreshold) {
var threshold = alphaThreshold || 0,
cachedCanvas = this._cache.canvas,
sceneCanvas = this._getCachedSceneCanvas(),
sceneContext = sceneCanvas.getContext(),
hitCanvas = cachedCanvas.hit,
hitContext = hitCanvas.getContext(),
width = sceneCanvas.getWidth(),
height = sceneCanvas.getHeight(),
sceneImageData, sceneData, hitImageData, hitData, len, rgbColorKey, i, alpha;
hitContext.clear();
try {
sceneImageData = sceneContext.getImageData(0, 0, width, height);
sceneData = sceneImageData.data;
hitImageData = hitContext.getImageData(0, 0, width, height);
hitData = hitImageData.data;
len = sceneData.length;
rgbColorKey = Kinetic.Util._hexToRgb(this.colorKey);
// replace non transparent pixels with color key
for(i = 0; i < len; i += 4) {
alpha = sceneData[i + 3];
if (alpha > threshold) {
hitData[i] = rgbColorKey.r;
hitData[i + 1] = rgbColorKey.g;
hitData[i + 2] = rgbColorKey.b;
hitData[i + 3] = 255;
}
}
hitContext.putImageData(hitImageData, 0, 0);
}
catch(e) {
Kinetic.Util.warn('Unable to draw hit graph from cached scene canvas. ' + e.message);
}
return this;
},
});
Kinetic.Util.extend(Kinetic.Shape, Kinetic.Node);
// add getters and setters
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'stroke');
/**
* get/set stroke color
* @name stroke
* @method
* @memberof Kinetic.Shape.prototype
* @param {String} color
* @returns {String}
* @example
* // get stroke color<br>
* var stroke = shape.stroke();<br><br>
*
* // set stroke color with color string<br>
* shape.stroke('green');<br><br>
*
* // set stroke color with hex<br>
* shape.stroke('#00ff00');<br><br>
*
* // set stroke color with rgb<br>
* shape.stroke('rgb(0,255,0)');<br><br>
*
* // set stroke color with rgba and make it 50% opaque<br>
* shape.stroke('rgba(0,255,0,0.5');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'strokeRed', 0, Kinetic.Validators.RGBComponent);
/**
* get/set stroke red component
* @name strokeRed
* @method
* @memberof Kinetic.Shape.prototype
* @param {Integer} red
* @returns {Integer}
* @example
* // get stroke red component<br>
* var strokeRed = shape.strokeRed();<br><br>
*
* // set stroke red component<br>
* shape.strokeRed(0);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'strokeGreen', 0, Kinetic.Validators.RGBComponent);
/**
* get/set stroke green component
* @name strokeGreen
* @method
* @memberof Kinetic.Shape.prototype
* @param {Integer} green
* @returns {Integer}
* @example
* // get stroke green component<br>
* var strokeGreen = shape.strokeGreen();<br><br>
*
* // set stroke green component<br>
* shape.strokeGreen(255);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'strokeBlue', 0, Kinetic.Validators.RGBComponent);
/**
* get/set stroke blue component
* @name strokeBlue
* @method
* @memberof Kinetic.Shape.prototype
* @param {Integer} blue
* @returns {Integer}
* @example
* // get stroke blue component<br>
* var strokeBlue = shape.strokeBlue();<br><br>
*
* // set stroke blue component<br>
* shape.strokeBlue(0);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'strokeAlpha', 1, Kinetic.Validators.alphaComponent);
/**
* get/set stroke alpha component. Alpha is a real number between 0 and 1. The default
* is 1.
* @name strokeAlpha
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} alpha
* @returns {Number}
* @example
* // get stroke alpha component<br>
* var strokeAlpha = shape.strokeAlpha();<br><br>
*
* // set stroke alpha component<br>
* shape.strokeAlpha(0.5);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'strokeWidth', 2);
/**
* get/set stroke width
* @name strokeWidth
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} strokeWidth
* @returns {Number}
* @example
* // get stroke width<br>
* var strokeWidth = shape.strokeWidth();<br><br>
*
* // set stroke width<br>
* shape.strokeWidth();
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'lineJoin');
/**
* get/set line join. Can be miter, round, or bevel. The
* default is miter
* @name lineJoin
* @method
* @memberof Kinetic.Shape.prototype
* @param {String} lineJoin
* @returns {String}
* @example
* // get line join<br>
* var lineJoin = shape.lineJoin();<br><br>
*
* // set line join<br>
* shape.lineJoin('round');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'lineCap');
/**
* get/set line cap. Can be butt, round, or square
* @name lineCap
* @method
* @memberof Kinetic.Shape.prototype
* @param {String} lineCap
* @returns {String}
* @example
* // get line cap<br>
* var lineCap = shape.lineCap();<br><br>
*
* // set line cap<br>
* shape.lineCap('round');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'sceneFunc');
/**
* get/set scene draw function
* @name sceneFunc
* @method
* @memberof Kinetic.Shape.prototype
* @param {Function} drawFunc drawing function
* @returns {Function}
* @example
* // get scene draw function<br>
* var sceneFunc = shape.sceneFunc();<br><br>
*
* // set scene draw function<br>
* shape.sceneFunc(function(context) {<br>
* context.beginPath();<br>
* context.rect(0, 0, this.width(), this.height());<br>
* context.closePath();<br>
* context.fillStrokeShape(this);<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'hitFunc');
/**
* get/set hit draw function
* @name hitFunc
* @method
* @memberof Kinetic.Shape.prototype
* @param {Function} drawFunc drawing function
* @returns {Function}
* @example
* // get hit draw function<br>
* var hitFunc = shape.hitFunc();<br><br>
*
* // set hit draw function<br>
* shape.hitFunc(function(context) {<br>
* context.beginPath();<br>
* context.rect(0, 0, this.width(), this.height());<br>
* context.closePath();<br>
* context.fillStrokeShape(this);<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'dash');
/**
* get/set dash array for stroke.
* @name dash
* @method
* @memberof Kinetic.Shape.prototype
* @param {Array} dash
* @returns {Array}
* @example
* // apply dashed stroke that is 10px long and 5 pixels apart<br>
* line.dash([10, 5]);<br><br>
*
* // apply dashed stroke that is made up of alternating dashed<br>
* // lines that are 10px long and 20px apart, and dots that have<br>
* // a radius of 5px and are 20px apart<br>
* line.dash([10, 20, 0.001, 20]);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowColor');
/**
* get/set shadow color
* @name shadowColor
* @method
* @memberof Kinetic.Shape.prototype
* @param {String} color
* @returns {String}
* @example
* // get shadow color<br>
* var shadow = shape.shadowColor();<br><br>
*
* // set shadow color with color string<br>
* shape.shadowColor('green');<br><br>
*
* // set shadow color with hex<br>
* shape.shadowColor('#00ff00');<br><br>
*
* // set shadow color with rgb<br>
* shape.shadowColor('rgb(0,255,0)');<br><br>
*
* // set shadow color with rgba and make it 50% opaque<br>
* shape.shadowColor('rgba(0,255,0,0.5');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowRed', 0, Kinetic.Validators.RGBComponent);
/**
* get/set shadow red component
* @name shadowRed
* @method
* @memberof Kinetic.Shape.prototype
* @param {Integer} red
* @returns {Integer}
* @example
* // get shadow red component<br>
* var shadowRed = shape.shadowRed();<br><br>
*
* // set shadow red component<br>
* shape.shadowRed(0);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowGreen', 0, Kinetic.Validators.RGBComponent);
/**
* get/set shadow green component
* @name shadowGreen
* @method
* @memberof Kinetic.Shape.prototype
* @param {Integer} green
* @returns {Integer}
* @example
* // get shadow green component<br>
* var shadowGreen = shape.shadowGreen();<br><br>
*
* // set shadow green component<br>
* shape.shadowGreen(255);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowBlue', 0, Kinetic.Validators.RGBComponent);
/**
* get/set shadow blue component
* @name shadowBlue
* @method
* @memberof Kinetic.Shape.prototype
* @param {Integer} blue
* @returns {Integer}
* @example
* // get shadow blue component<br>
* var shadowBlue = shape.shadowBlue();<br><br>
*
* // set shadow blue component<br>
* shape.shadowBlue(0);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowAlpha', 1, Kinetic.Validators.alphaComponent);
/**
* get/set shadow alpha component. Alpha is a real number between 0 and 1. The default
* is 1.
* @name shadowAlpha
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} alpha
* @returns {Number}
* @example
* // get shadow alpha component<br>
* var shadowAlpha = shape.shadowAlpha();<br><br>
*
* // set shadow alpha component<br>
* shape.shadowAlpha(0.5);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowBlur');
/**
* get/set shadow blur
* @name shadowBlur
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} blur
* @returns {Number}
* @example
* // get shadow blur<br>
* var shadowBlur = shape.shadowBlur();<br><br>
*
* // set shadow blur<br>
* shape.shadowBlur(10);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowOpacity');
/**
* get/set shadow opacity. must be a value between 0 and 1
* @name shadowOpacity
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} opacity
* @returns {Number}
* @example
* // get shadow opacity<br>
* var shadowOpacity = shape.shadowOpacity();<br><br>
*
* // set shadow opacity<br>
* shape.shadowOpacity(0.5);
*/
Kinetic.Factory.addComponentsGetterSetter(Kinetic.Shape, 'shadowOffset', ['x', 'y']);
/**
* get/set shadow offset
* @name shadowOffset
* @method
* @memberof Kinetic.Shape.prototype
* @param {Object} offset
* @param {Number} offset.x
* @param {Number} offset.y
* @returns {Object}
* @example
* // get shadow offset<br>
* var shadowOffset = shape.shadowOffset();<br><br>
*
* // set shadow offset<br>
* shape.shadowOffset({<br>
* x: 20<br>
* y: 10<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowOffsetX', 0);
/**
* get/set shadow offset x
* @name shadowOffsetX
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} x
* @returns {Number}
* @example
* // get shadow offset x<br>
* var shadowOffsetX = shape.shadowOffsetX();<br><br>
*
* // set shadow offset x<br>
* shape.shadowOffsetX(5);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowOffsetY', 0);
/**
* get/set shadow offset y
* @name shadowOffsetY
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} y
* @returns {Number}
* @example
* // get shadow offset y<br>
* var shadowOffsetY = shape.shadowOffsetY();<br><br>
*
* // set shadow offset y<br>
* shape.shadowOffsetY(5);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPatternImage');
/**
* get/set fill pattern image
* @name fillPatternImage
* @method
* @memberof Kinetic.Shape.prototype
* @param {Image} image object
* @returns {Image}
* @example
* // get fill pattern image<br>
* var fillPatternImage = shape.fillPatternImage();<br><br>
*
* // set fill pattern image<br>
* var imageObj = new Image();<br>
* imageObj.onload = function() {<br>
* shape.fillPatternImage(imageObj);<br>
* };<br>
* imageObj.src = 'path/to/image/jpg';
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fill');
/**
* get/set fill color
* @name fill
* @method
* @memberof Kinetic.Shape.prototype
* @param {String} color
* @returns {String}
* @example
* // get fill color<br>
* var fill = shape.fill();<br><br>
*
* // set fill color with color string<br>
* shape.fill('green');<br><br>
*
* // set fill color with hex<br>
* shape.fill('#00ff00');<br><br>
*
* // set fill color with rgb<br>
* shape.fill('rgb(0,255,0)');<br><br>
*
* // set fill color with rgba and make it 50% opaque<br>
* shape.fill('rgba(0,255,0,0.5');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillRed', 0, Kinetic.Validators.RGBComponent);
/**
* get/set fill red component
* @name fillRed
* @method
* @memberof Kinetic.Shape.prototype
* @param {Integer} red
* @returns {Integer}
* @example
* // get fill red component<br>
* var fillRed = shape.fillRed();<br><br>
*
* // set fill red component<br>
* shape.fillRed(0);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillGreen', 0, Kinetic.Validators.RGBComponent);
/**
* get/set fill green component
* @name fillGreen
* @method
* @memberof Kinetic.Shape.prototype
* @param {Integer} green
* @returns {Integer}
* @example
* // get fill green component<br>
* var fillGreen = shape.fillGreen();<br><br>
*
* // set fill green component<br>
* shape.fillGreen(255);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillBlue', 0, Kinetic.Validators.RGBComponent);
/**
* get/set fill blue component
* @name fillBlue
* @method
* @memberof Kinetic.Shape.prototype
* @param {Integer} blue
* @returns {Integer}
* @example
* // get fill blue component<br>
* var fillBlue = shape.fillBlue();<br><br>
*
* // set fill blue component<br>
* shape.fillBlue(0);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillAlpha', 1, Kinetic.Validators.alphaComponent);
/**
* get/set fill alpha component. Alpha is a real number between 0 and 1. The default
* is 1.
* @name fillAlpha
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} alpha
* @returns {Number}
* @example
* // get fill alpha component<br>
* var fillAlpha = shape.fillAlpha();<br><br>
*
* // set fill alpha component<br>
* shape.fillAlpha(0.5);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPatternX', 0);
/**
* get/set fill pattern x
* @name fillPatternX
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} x
* @returns {Number}
* @example
* // get fill pattern x<br>
* var fillPatternX = shape.fillPatternX();<br><br>
*
* // set fill pattern x<br>
* shape.fillPatternX(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPatternY', 0);
/**
* get/set fill pattern y
* @name fillPatternY
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} y
* @returns {Number}
* @example
* // get fill pattern y<br>
* var fillPatternY = shape.fillPatternY();<br><br>
*
* // set fill pattern y<br>
* shape.fillPatternY(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillLinearGradientColorStops');
/**
* get/set fill linear gradient color stops
* @name fillLinearGradientColorStops
* @method
* @memberof Kinetic.Shape.prototype
* @param {Array} colorStops
* @returns {Array} colorStops
* @example
* // get fill linear gradient color stops<br>
* var colorStops = shape.fillLinearGradientColorStops();<br><br>
*
* // create a linear gradient that starts with red, changes to blue <br>
* // halfway through, and then changes to green<br>
* shape.fillLinearGradientColorStops(0, 'red', 0.5, 'blue', 1, 'green');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillRadialGradientStartRadius', 0);
/**
* get/set fill radial gradient start radius
* @name fillRadialGradientStartRadius
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} radius
* @returns {Number}
* @example
* // get radial gradient start radius<br>
* var startRadius = shape.fillRadialGradientStartRadius();<br><br>
*
* // set radial gradient start radius<br>
* shape.fillRadialGradientStartRadius(0);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillRadialGradientEndRadius', 0);
/**
* get/set fill radial gradient end radius
* @name fillRadialGradientEndRadius
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} radius
* @returns {Number}
* @example
* // get radial gradient end radius<br>
* var endRadius = shape.fillRadialGradientEndRadius();<br><br>
*
* // set radial gradient end radius<br>
* shape.fillRadialGradientEndRadius(100);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillRadialGradientColorStops');
/**
* get/set fill radial gradient color stops
* @name fillRadialGradientColorStops
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} colorStops
* @returns {Array}
* @example
* // get fill radial gradient color stops<br>
* var colorStops = shape.fillRadialGradientColorStops();<br><br>
*
* // create a radial gradient that starts with red, changes to blue <br>
* // halfway through, and then changes to green<br>
* shape.fillRadialGradientColorStops(0, 'red', 0.5, 'blue', 1, 'green');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPatternRepeat', 'repeat');
/**
* get/set fill pattern repeat. Can be 'repeat', 'repeat-x', 'repeat-y', or 'no-repeat'. The default is 'repeat'
* @name fillPatternRepeat
* @method
* @memberof Kinetic.Shape.prototype
* @param {String} repeat
* @returns {String}
* @example
* // get fill pattern repeat<br>
* var repeat = shape.fillPatternRepeat();<br><br>
*
* // repeat pattern in x direction only<br>
* shape.fillPatternRepeat('repeat-x');<br><br>
*
* // do not repeat the pattern<br>
* shape.fillPatternRepeat('no repeat');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillEnabled', true);
/**
* get/set fill enabled flag
* @name fillEnabled
* @method
* @memberof Kinetic.Shape.prototype
* @param {Boolean} enabled
* @returns {Boolean}
* @example
* // get fill enabled flag<br>
* var fillEnabled = shape.fillEnabled();<br><br>
*
* // disable fill<br>
* shape.fillEnabled(false);<br><br>
*
* // enable fill<br>
* shape.fillEnabled(true);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'strokeEnabled', true);
/**
* get/set stroke enabled flag
* @name strokeEnabled
* @method
* @memberof Kinetic.Shape.prototype
* @param {Boolean} enabled
* @returns {Boolean}
* @example
* // get stroke enabled flag<br>
* var strokeEnabled = shape.strokeEnabled();<br><br>
*
* // disable stroke<br>
* shape.strokeEnabled(false);<br><br>
*
* // enable stroke<br>
* shape.strokeEnabled(true);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowEnabled', true);
/**
* get/set shadow enabled flag
* @name shadowEnabled
* @method
* @memberof Kinetic.Shape.prototype
* @param {Boolean} enabled
* @returns {Boolean}
* @example
* // get shadow enabled flag<br>
* var shadowEnabled = shape.shadowEnabled();<br><br>
*
* // disable shadow<br>
* shape.shadowEnabled(false);<br><br>
*
* // enable shadow<br>
* shape.shadowEnabled(true);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'dashEnabled', true);
/**
* get/set dash enabled flag
* @name dashEnabled
* @method
* @memberof Kinetic.Shape.prototype
* @param {Boolean} enabled
* @returns {Boolean}
* @example
* // get dash enabled flag<br>
* var dashEnabled = shape.dashEnabled();<br><br>
*
* // disable dash<br>
* shape.dashEnabled(false);<br><br>
*
* // enable dash<br>
* shape.dashEnabled(true);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'strokeScaleEnabled', true);
/**
* get/set strokeScale enabled flag
* @name strokeScaleEnabled
* @method
* @memberof Kinetic.Shape.prototype
* @param {Boolean} enabled
* @returns {Boolean}
* @example
* // get stroke scale enabled flag<br>
* var strokeScaleEnabled = shape.strokeScaleEnabled();<br><br>
*
* // disable stroke scale<br>
* shape.strokeScaleEnabled(false);<br><br>
*
* // enable stroke scale<br>
* shape.strokeScaleEnabled(true);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPriority', 'color');
/**
* get/set fill priority. can be color, pattern, linear-gradient, or radial-gradient. The default is color.
* This is handy if you want to toggle between different fill types.
* @name fillPriority
* @method
* @memberof Kinetic.Shape.prototype
* @param {String} priority
* @returns {String}
* @example
* // get fill priority<br>
* var fillPriority = shape.fillPriority();<br><br>
*
* // set fill priority<br>
* shape.fillPriority('linear-gradient');
*/
Kinetic.Factory.addComponentsGetterSetter(Kinetic.Shape, 'fillPatternOffset', ['x', 'y']);
/**
* get/set fill pattern offset
* @name fillPatternOffset
* @method
* @memberof Kinetic.Shape.prototype
* @param {Object} offset
* @param {Number} offset.x
* @param {Number} offset.y
* @returns {Object}
* @example
* // get fill pattern offset<br>
* var patternOffset = shape.fillPatternOffset();<br><br>
*
* // set fill pattern offset<br>
* shape.fillPatternOffset({<br>
* x: 20<br>
* y: 10<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPatternOffsetX', 0);
/**
* get/set fill pattern offset x
* @name fillPatternOffsetX
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} x
* @returns {Number}
* @example
* // get fill pattern offset x<br>
* var patternOffsetX = shape.fillPatternOffsetX();<br><br>
*
* // set fill pattern offset x<br>
* shape.fillPatternOffsetX(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPatternOffsetY', 0);
/**
* get/set fill pattern offset y
* @name fillPatternOffsetY
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} y
* @returns {Number}
* @example
* // get fill pattern offset y<br>
* var patternOffsetY = shape.fillPatternOffsetY();<br><br>
*
* // set fill pattern offset y<br>
* shape.fillPatternOffsetY(10);
*/
Kinetic.Factory.addComponentsGetterSetter(Kinetic.Shape, 'fillPatternScale', ['x', 'y']);
/**
* get/set fill pattern scale
* @name fillPatternScale
* @method
* @memberof Kinetic.Shape.prototype
* @param {Object} scale
* @param {Number} scale.x
* @param {Number} scale.y
* @returns {Object}
* @example
* // get fill pattern scale<br>
* var patternScale = shape.fillPatternScale();<br><br>
*
* // set fill pattern scale<br>
* shape.fillPatternScale({<br>
* x: 2<br>
* y: 2<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPatternScaleX', 1);
/**
* get/set fill pattern scale x
* @name fillPatternScaleX
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} x
* @returns {Number}
* @example
* // get fill pattern scale x<br>
* var patternScaleX = shape.fillPatternScaleX();<br><br>
*
* // set fill pattern scale x<br>
* shape.fillPatternScaleX(2);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPatternScaleY', 1);
/**
* get/set fill pattern scale y
* @name fillPatternScaleY
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} y
* @returns {Number}
* @example
* // get fill pattern scale y<br>
* var patternScaleY = shape.fillPatternScaleY();<br><br>
*
* // set fill pattern scale y<br>
* shape.fillPatternScaleY(2);
*/
Kinetic.Factory.addComponentsGetterSetter(Kinetic.Shape, 'fillLinearGradientStartPoint', ['x', 'y']);
/**
* get/set fill linear gradient start point
* @name fillLinearGradientStartPoint
* @method
* @memberof Kinetic.Shape.prototype
* @param {Object} startPoint
* @param {Number} startPoint.x
* @param {Number} startPoint.y
* @returns {Object}
* @example
* // get fill linear gradient start point<br>
* var startPoint = shape.fillLinearGradientStartPoint();<br><br>
*
* // set fill linear gradient start point<br>
* shape.fillLinearGradientStartPoint({<br>
* x: 20<br>
* y: 10<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillLinearGradientStartPointX', 0);
/**
* get/set fill linear gradient start point x
* @name fillLinearGradientStartPointX
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} x
* @returns {Number}
* @example
* // get fill linear gradient start point x<br>
* var startPointX = shape.fillLinearGradientStartPointX();<br><br>
*
* // set fill linear gradient start point x<br>
* shape.fillLinearGradientStartPointX(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillLinearGradientStartPointY', 0);
/**
* get/set fill linear gradient start point y
* @name fillLinearGradientStartPointY
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} y
* @returns {Number}
* @example
* // get fill linear gradient start point y<br>
* var startPointY = shape.fillLinearGradientStartPointY();<br><br>
*
* // set fill linear gradient start point y<br>
* shape.fillLinearGradientStartPointY(20);
*/
Kinetic.Factory.addComponentsGetterSetter(Kinetic.Shape, 'fillLinearGradientEndPoint', ['x', 'y']);
/**
* get/set fill linear gradient end point
* @name fillLinearGradientEndPoint
* @method
* @memberof Kinetic.Shape.prototype
* @param {Object} endPoint
* @param {Number} endPoint.x
* @param {Number} endPoint.y
* @returns {Object}
* @example
* // get fill linear gradient end point<br>
* var endPoint = shape.fillLinearGradientEndPoint();<br><br>
*
* // set fill linear gradient end point<br>
* shape.fillLinearGradientEndPoint({<br>
* x: 20<br>
* y: 10<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillLinearGradientEndPointX', 0);
/**
* get/set fill linear gradient end point x
* @name fillLinearGradientEndPointX
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} x
* @returns {Number}
* @example
* // get fill linear gradient end point x<br>
* var endPointX = shape.fillLinearGradientEndPointX();<br><br>
*
* // set fill linear gradient end point x<br>
* shape.fillLinearGradientEndPointX(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillLinearGradientEndPointY', 0);
/**
* get/set fill linear gradient end point y
* @name fillLinearGradientEndPointY
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} y
* @returns {Number}
* @example
* // get fill linear gradient end point y<br>
* var endPointY = shape.fillLinearGradientEndPointY();<br><br>
*
* // set fill linear gradient end point y<br>
* shape.fillLinearGradientEndPointY(20);
*/
Kinetic.Factory.addComponentsGetterSetter(Kinetic.Shape, 'fillRadialGradientStartPoint', ['x', 'y']);
/**
* get/set fill radial gradient start point
* @name fillRadialGradientStartPoint
* @method
* @memberof Kinetic.Shape.prototype
* @param {Object} startPoint
* @param {Number} startPoint.x
* @param {Number} startPoint.y
* @returns {Object}
* @example
* // get fill radial gradient start point<br>
* var startPoint = shape.fillRadialGradientStartPoint();<br><br>
*
* // set fill radial gradient start point<br>
* shape.fillRadialGradientStartPoint({<br>
* x: 20<br>
* y: 10<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillRadialGradientStartPointX', 0);
/**
* get/set fill radial gradient start point x
* @name fillRadialGradientStartPointX
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} x
* @returns {Number}
* @example
* // get fill radial gradient start point x<br>
* var startPointX = shape.fillRadialGradientStartPointX();<br><br>
*
* // set fill radial gradient start point x<br>
* shape.fillRadialGradientStartPointX(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillRadialGradientStartPointY', 0);
/**
* get/set fill radial gradient start point y
* @name fillRadialGradientStartPointY
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} y
* @returns {Number}
* @example
* // get fill radial gradient start point y<br>
* var startPointY = shape.fillRadialGradientStartPointY();<br><br>
*
* // set fill radial gradient start point y<br>
* shape.fillRadialGradientStartPointY(20);
*/
Kinetic.Factory.addComponentsGetterSetter(Kinetic.Shape, 'fillRadialGradientEndPoint', ['x', 'y']);
/**
* get/set fill radial gradient end point
* @name fillRadialGradientEndPoint
* @method
* @memberof Kinetic.Shape.prototype
* @param {Object} endPoint
* @param {Number} endPoint.x
* @param {Number} endPoint.y
* @returns {Object}
* @example
* // get fill radial gradient end point<br>
* var endPoint = shape.fillRadialGradientEndPoint();<br><br>
*
* // set fill radial gradient end point<br>
* shape.fillRadialGradientEndPoint({<br>
* x: 20<br>
* y: 10<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillRadialGradientEndPointX', 0);
/**
* get/set fill radial gradient end point x
* @name fillRadialGradientEndPointX
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} x
* @returns {Number}
* @example
* // get fill radial gradient end point x<br>
* var endPointX = shape.fillRadialGradientEndPointX();<br><br>
*
* // set fill radial gradient end point x<br>
* shape.fillRadialGradientEndPointX(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillRadialGradientEndPointY', 0);
/**
* get/set fill radial gradient end point y
* @name fillRadialGradientEndPointY
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} y
* @returns {Number}
* @example
* // get fill radial gradient end point y<br>
* var endPointY = shape.fillRadialGradientEndPointY();<br><br>
*
* // set fill radial gradient end point y<br>
* shape.fillRadialGradientEndPointY(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPatternRotation', 0);
/**
* get/set fill pattern rotation in degrees
* @name fillPatternRotation
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} rotation
* @returns {Kinetic.Shape}
* @example
* // get fill pattern rotation<br>
* var patternRotation = shape.fillPatternRotation();<br><br>
*
* // set fill pattern rotation<br>
* shape.fillPatternRotation(20);
*/
Kinetic.Factory.backCompat(Kinetic.Shape, {
dashArray: 'dash',
getDashArray: 'getDash',
setDashArray: 'getDash',
drawFunc: 'sceneFunc',
getDrawFunc: 'getSceneFunc',
setDrawFunc: 'setSceneFunc',
drawHitFunc: 'hitFunc',
getDrawHitFunc: 'getHitFunc',
setDrawHitFunc: 'setHitFunc'
});
Kinetic.Collection.mapMethods(Kinetic.Shape);
})();
;/*jshint unused:false */
(function() {
// CONSTANTS
var STAGE = 'Stage',
STRING = 'string',
PX = 'px',
MOUSEOUT = 'mouseout',
MOUSELEAVE = 'mouseleave',
MOUSEOVER = 'mouseover',
MOUSEENTER = 'mouseenter',
MOUSEMOVE = 'mousemove',
MOUSEDOWN = 'mousedown',
MOUSEUP = 'mouseup',
CLICK = 'click',
DBL_CLICK = 'dblclick',
TOUCHSTART = 'touchstart',
TOUCHEND = 'touchend',
TAP = 'tap',
DBL_TAP = 'dbltap',
TOUCHMOVE = 'touchmove',
CONTENT_MOUSEOUT = 'contentMouseout',
CONTENT_MOUSELEAVE = 'contentMouseleave',
CONTENT_MOUSEOVER = 'contentMouseover',
CONTENT_MOUSEENTER = 'contentMouseenter',
CONTENT_MOUSEMOVE = 'contentMousemove',
CONTENT_MOUSEDOWN = 'contentMousedown',
CONTENT_MOUSEUP = 'contentMouseup',
CONTENT_CLICK = 'contentClick',
CONTENT_DBL_CLICK = 'contentDblclick',
CONTENT_TOUCHSTART = 'contentTouchstart',
CONTENT_TOUCHEND = 'contentTouchend',
CONTENT_TAP = 'contentTap',
CONTENT_DBL_TAP = 'contentDbltap',
CONTENT_TOUCHMOVE = 'contentTouchmove',
DIV = 'div',
RELATIVE = 'relative',
INLINE_BLOCK = 'inline-block',
KINETICJS_CONTENT = 'kineticjs-content',
SPACE = ' ',
UNDERSCORE = '_',
CONTAINER = 'container',
EMPTY_STRING = '',
EVENTS = [MOUSEDOWN, MOUSEMOVE, MOUSEUP, MOUSEOUT, TOUCHSTART, TOUCHMOVE, TOUCHEND, MOUSEOVER],
// cached variables
eventsLength = EVENTS.length;
function addEvent(ctx, eventName) {
ctx.content.addEventListener(eventName, function(evt) {
ctx[UNDERSCORE + eventName](evt);
}, false);
}
Kinetic.Util.addMethods(Kinetic.Stage, {
___init: function(config) {
this.nodeType = STAGE;
// call super constructor
Kinetic.Container.call(this, config);
this._id = Kinetic.idCounter++;
this._buildDOM();
this._bindContentEvents();
this._enableNestedTransforms = false;
Kinetic.stages.push(this);
},
_validateAdd: function(child) {
if (child.getType() !== 'Layer') {
Kinetic.Util.error('You may only add layers to the stage.');
}
},
/**
* set container dom element which contains the stage wrapper div element
* @method
* @memberof Kinetic.Stage.prototype
* @param {DomElement} container can pass in a dom element or id string
*/
setContainer: function(container) {
if( typeof container === STRING) {
var id = container;
container = Kinetic.document.getElementById(container);
if (!container) {
throw 'Can not find container in document with id ' + id;
}
}
this._setAttr(CONTAINER, container);
return this;
},
shouldDrawHit: function() {
return true;
},
draw: function() {
Kinetic.Node.prototype.draw.call(this);
return this;
},
/**
* draw layer scene graphs
* @name draw
* @method
* @memberof Kinetic.Stage.prototype
*/
/**
* draw layer hit graphs
* @name drawHit
* @method
* @memberof Kinetic.Stage.prototype
*/
/**
* set height
* @method
* @memberof Kinetic.Stage.prototype
* @param {Number} height
*/
setHeight: function(height) {
Kinetic.Node.prototype.setHeight.call(this, height);
this._resizeDOM();
return this;
},
/**
* set width
* @method
* @memberof Kinetic.Stage.prototype
* @param {Number} width
*/
setWidth: function(width) {
Kinetic.Node.prototype.setWidth.call(this, width);
this._resizeDOM();
return this;
},
/**
* clear all layers
* @method
* @memberof Kinetic.Stage.prototype
*/
clear: function() {
var layers = this.children,
len = layers.length,
n;
for(n = 0; n < len; n++) {
layers[n].clear();
}
return this;
},
clone: function(obj) {
if (!obj) {
obj = {};
}
obj.container = Kinetic.document.createElement(DIV);
return Kinetic.Container.prototype.clone.call(this, obj);
},
/**
* destroy stage
* @method
* @memberof Kinetic.Stage.prototype
*/
destroy: function() {
var content = this.content;
Kinetic.Container.prototype.destroy.call(this);
if(content && Kinetic.Util._isInDocument(content)) {
this.getContainer().removeChild(content);
}
var index = Kinetic.stages.indexOf(this);
if (index > -1) {
Kinetic.stages.splice(index, 1);
}
},
/**
* get pointer position which can be a touch position or mouse position
* @method
* @memberof Kinetic.Stage.prototype
* @returns {Object}
*/
getPointerPosition: function() {
return this.pointerPos;
},
getStage: function() {
return this;
},
/**
* get stage content div element which has the
* the class name "kineticjs-content"
* @method
* @memberof Kinetic.Stage.prototype
*/
getContent: function() {
return this.content;
},
/**
* Creates a composite data URL and requires a callback because the composite is generated asynchronously.
* @method
* @memberof Kinetic.Stage.prototype
* @param {Object} config
* @param {Function} config.callback function executed when the composite has completed
* @param {String} [config.mimeType] can be "image/png" or "image/jpeg".
* "image/png" is the default
* @param {Number} [config.x] x position of canvas section
* @param {Number} [config.y] y position of canvas section
* @param {Number} [config.width] width of canvas section
* @param {Number} [config.height] height of canvas section
* @param {Number} [config.quality] jpeg quality. If using an "image/jpeg" mimeType,
* you can specify the quality from 0 to 1, where 0 is very poor quality and 1
* is very high quality
*/
toDataURL: function(config) {
config = config || {};
var mimeType = config.mimeType || null,
quality = config.quality || null,
x = config.x || 0,
y = config.y || 0,
canvas = new Kinetic.SceneCanvas({
width: config.width || this.getWidth(),
height: config.height || this.getHeight(),
pixelRatio: 1
}),
_context = canvas.getContext()._context,
layers = this.children;
if(x || y) {
_context.translate(-1 * x, -1 * y);
}
function drawLayer(n) {
var layer = layers[n],
layerUrl = layer.toDataURL(),
imageObj = new Kinetic.window.Image();
imageObj.onload = function() {
_context.drawImage(imageObj, 0, 0);
if(n < layers.length - 1) {
drawLayer(n + 1);
}
else {
config.callback(canvas.toDataURL(mimeType, quality));
}
};
imageObj.src = layerUrl;
}
drawLayer(0);
},
/**
* converts stage into an image.
* @method
* @memberof Kinetic.Stage.prototype
* @param {Object} config
* @param {Function} config.callback function executed when the composite has completed
* @param {String} [config.mimeType] can be "image/png" or "image/jpeg".
* "image/png" is the default
* @param {Number} [config.x] x position of canvas section
* @param {Number} [config.y] y position of canvas section
* @param {Number} [config.width] width of canvas section
* @param {Number} [config.height] height of canvas section
* @param {Number} [config.quality] jpeg quality. If using an "image/jpeg" mimeType,
* you can specify the quality from 0 to 1, where 0 is very poor quality and 1
* is very high quality
*/
toImage: function(config) {
var cb = config.callback;
config.callback = function(dataUrl) {
Kinetic.Util._getImage(dataUrl, function(img) {
cb(img);
});
};
this.toDataURL(config);
},
/**
* get visible intersection shape. This is the preferred
* method for determining if a point intersects a shape or not
* @method
* @memberof Kinetic.Stage.prototype
* @param {Object} pos
* @param {Number} pos.x
* @param {Number} pos.y
* @returns {Kinetic.Shape}
*/
getIntersection: function(pos) {
var layers = this.getChildren(),
len = layers.length,
end = len - 1,
n, shape;
for(n = end; n >= 0; n--) {
shape = layers[n].getIntersection(pos);
if (shape) {
return shape;
}
}
return null;
},
_resizeDOM: function() {
if(this.content) {
var width = this.getWidth(),
height = this.getHeight(),
layers = this.getChildren(),
len = layers.length,
n, layer;
// set content dimensions
this.content.style.width = width + PX;
this.content.style.height = height + PX;
this.bufferCanvas.setSize(width, height);
this.bufferHitCanvas.setSize(width, height);
// set layer dimensions
for(n = 0; n < len; n++) {
layer = layers[n];
layer.getCanvas().setSize(width, height);
layer.hitCanvas.setSize(width, height);
layer.draw();
}
}
},
/**
* add layer or layers to stage
* @method
* @memberof Kinetic.Stage.prototype
* @param {...Kinetic.Layer} layer
* @example
* stage.add(layer1, layer2, layer3);
*/
add: function(layer) {
if (arguments.length > 1) {
for (var i = 0; i < arguments.length; i++) {
this.add(arguments[i]);
}
return;
}
Kinetic.Container.prototype.add.call(this, layer);
layer._setCanvasSize(this.width(), this.height());
// draw layer and append canvas to container
layer.draw();
this.content.appendChild(layer.canvas._canvas);
// chainable
return this;
},
getParent: function() {
return null;
},
getLayer: function() {
return null;
},
/**
* returns a {@link Kinetic.Collection} of layers
* @method
* @memberof Kinetic.Stage.prototype
*/
getLayers: function() {
return this.getChildren();
},
_bindContentEvents: function() {
for (var n = 0; n < eventsLength; n++) {
addEvent(this, EVENTS[n]);
}
},
_mouseover: function(evt) {
if (!Kinetic.UA.mobile) {
this._setPointerPosition(evt);
this._fire(CONTENT_MOUSEOVER, {evt: evt});
}
},
_mouseout: function(evt) {
if (!Kinetic.UA.mobile) {
this._setPointerPosition(evt);
var targetShape = this.targetShape;
if(targetShape && !Kinetic.isDragging()) {
targetShape._fireAndBubble(MOUSEOUT, {evt: evt});
targetShape._fireAndBubble(MOUSELEAVE, {evt: evt});
this.targetShape = null;
}
this.pointerPos = undefined;
this._fire(CONTENT_MOUSEOUT, {evt: evt});
}
},
_mousemove: function(evt) {
if (!Kinetic.UA.mobile) {
this._setPointerPosition(evt);
var dd = Kinetic.DD,
shape = this.getIntersection(this.getPointerPosition());
if(shape && shape.isListening()) {
if(!Kinetic.isDragging() && (!this.targetShape || this.targetShape._id !== shape._id)) {
if(this.targetShape) {
this.targetShape._fireAndBubble(MOUSEOUT, {evt: evt}, shape);
this.targetShape._fireAndBubble(MOUSELEAVE, {evt: evt}, shape);
}
shape._fireAndBubble(MOUSEOVER, {evt: evt}, this.targetShape);
shape._fireAndBubble(MOUSEENTER, {evt: evt}, this.targetShape);
this.targetShape = shape;
}
else {
shape._fireAndBubble(MOUSEMOVE, {evt: evt});
}
}
/*
* if no shape was detected, clear target shape and try
* to run mouseout from previous target shape
*/
else {
if(this.targetShape && !Kinetic.isDragging()) {
this.targetShape._fireAndBubble(MOUSEOUT, {evt: evt});
this.targetShape._fireAndBubble(MOUSELEAVE, {evt: evt});
this.targetShape = null;
}
}
// content event
this._fire(CONTENT_MOUSEMOVE, {evt: evt});
if(dd) {
dd._drag(evt);
}
}
// always call preventDefault for desktop events because some browsers
// try to drag and drop the canvas element
if (evt.preventDefault) {
evt.preventDefault();
}
},
_mousedown: function(evt) {
if (!Kinetic.UA.mobile) {
this._setPointerPosition(evt);
var shape = this.getIntersection(this.getPointerPosition());
Kinetic.listenClickTap = true;
if (shape && shape.isListening()) {
this.clickStartShape = shape;
shape._fireAndBubble(MOUSEDOWN, {evt: evt});
}
// content event
this._fire(CONTENT_MOUSEDOWN, {evt: evt});
}
// always call preventDefault for desktop events because some browsers
// try to drag and drop the canvas element
if (evt.preventDefault) {
evt.preventDefault();
}
},
_mouseup: function(evt) {
if (!Kinetic.UA.mobile) {
this._setPointerPosition(evt);
var that = this,
shape = this.getIntersection(this.getPointerPosition()),
clickStartShape = this.clickStartShape,
fireDblClick = false;
if(Kinetic.inDblClickWindow) {
fireDblClick = true;
Kinetic.inDblClickWindow = false;
}
else {
Kinetic.inDblClickWindow = true;
}
setTimeout(function() {
Kinetic.inDblClickWindow = false;
}, Kinetic.dblClickWindow);
if (shape && shape.isListening()) {
shape._fireAndBubble(MOUSEUP, {evt: evt});
// detect if click or double click occurred
if(Kinetic.listenClickTap && clickStartShape && clickStartShape._id === shape._id) {
shape._fireAndBubble(CLICK, {evt: evt});
if(fireDblClick) {
shape._fireAndBubble(DBL_CLICK, {evt: evt});
}
}
}
// content events
this._fire(CONTENT_MOUSEUP, {evt: evt});
if (Kinetic.listenClickTap) {
this._fire(CONTENT_CLICK, {evt: evt});
if(fireDblClick) {
this._fire(CONTENT_DBL_CLICK, {evt: evt});
}
}
Kinetic.listenClickTap = false;
}
// always call preventDefault for desktop events because some browsers
// try to drag and drop the canvas element
if (evt.preventDefault) {
evt.preventDefault();
}
},
_touchstart: function(evt) {
this._setPointerPosition(evt);
var shape = this.getIntersection(this.getPointerPosition());
Kinetic.listenClickTap = true;
if (shape && shape.isListening()) {
this.tapStartShape = shape;
shape._fireAndBubble(TOUCHSTART, {evt: evt});
// only call preventDefault if the shape is listening for events
if (shape.isListening() && evt.preventDefault) {
evt.preventDefault();
}
}
// content event
this._fire(CONTENT_TOUCHSTART, {evt: evt});
},
_touchend: function(evt) {
this._setPointerPosition(evt);
var shape = this.getIntersection(this.getPointerPosition()),
fireDblClick = false;
if(Kinetic.inDblClickWindow) {
fireDblClick = true;
Kinetic.inDblClickWindow = false;
}
else {
Kinetic.inDblClickWindow = true;
}
setTimeout(function() {
Kinetic.inDblClickWindow = false;
}, Kinetic.dblClickWindow);
if (shape && shape.isListening()) {
shape._fireAndBubble(TOUCHEND, {evt: evt});
// detect if tap or double tap occurred
if(Kinetic.listenClickTap && shape._id === this.tapStartShape._id) {
shape._fireAndBubble(TAP, {evt: evt});
if(fireDblClick) {
shape._fireAndBubble(DBL_TAP, {evt: evt});
}
}
// only call preventDefault if the shape is listening for events
if (shape.isListening() && evt.preventDefault) {
evt.preventDefault();
}
}
// content events
if (Kinetic.listenClickTap) {
this._fire(CONTENT_TOUCHEND, {evt: evt});
if(fireDblClick) {
this._fire(CONTENT_DBL_TAP, {evt: evt});
}
}
Kinetic.listenClickTap = false;
},
_touchmove: function(evt) {
this._setPointerPosition(evt);
var dd = Kinetic.DD,
shape = this.getIntersection(this.getPointerPosition());
if (shape && shape.isListening()) {
shape._fireAndBubble(TOUCHMOVE, {evt: evt});
// only call preventDefault if the shape is listening for events
if (shape.isListening() && evt.preventDefault) {
evt.preventDefault();
}
}
this._fire(CONTENT_TOUCHMOVE, {evt: evt});
// start drag and drop
if(dd) {
dd._drag(evt);
}
},
_setPointerPosition: function(evt) {
var contentPosition = this._getContentPosition(),
offsetX = evt.offsetX,
clientX = evt.clientX,
x = null,
y = null,
touch;
evt = evt ? evt : window.event;
// touch events
if(evt.touches !== undefined) {
// currently, only handle one finger
if (evt.touches.length > 0) {
touch = evt.touches[0];
// get the information for finger #1
x = touch.clientX - contentPosition.left;
y = touch.clientY - contentPosition.top;
}
}
// mouse events
else {
// if offsetX is defined, assume that offsetY is defined as well
if (offsetX !== undefined) {
x = offsetX;
y = evt.offsetY;
}
// we unforunately have to use UA detection here because accessing
// the layerX or layerY properties in newer veresions of Chrome
// throws a JS warning. layerX and layerY are required for FF
// when the container is transformed via CSS.
else if (Kinetic.UA.browser === 'mozilla') {
x = evt.layerX;
y = evt.layerY;
}
// if clientX is defined, assume that clientY is defined as well
else if (clientX !== undefined && contentPosition) {
x = clientX - contentPosition.left;
y = evt.clientY - contentPosition.top;
}
}
if (x !== null && y !== null) {
this.pointerPos = {
x: x,
y: y
};
}
},
_getContentPosition: function() {
var rect = this.content.getBoundingClientRect ? this.content.getBoundingClientRect() : { top: 0, left: 0 };
return {
top: rect.top,
left: rect.left
};
},
_buildDOM: function() {
var container = this.getContainer();
if (!container) {
if (Kinetic.Util.isBrowser()) {
throw 'Stage has not container. But container is required';
} else {
// automatically create element for jsdom in nodejs env
container = Kinetic.document.createElement(DIV);
}
}
// clear content inside container
container.innerHTML = EMPTY_STRING;
// content
this.content = Kinetic.document.createElement(DIV);
this.content.style.position = RELATIVE;
this.content.style.display = INLINE_BLOCK;
this.content.className = KINETICJS_CONTENT;
this.content.setAttribute('role', 'presentation');
container.appendChild(this.content);
// the buffer canvas pixel ratio must be 1 because it is used as an
// intermediate canvas before copying the result onto a scene canvas.
// not setting it to 1 will result in an over compensation
this.bufferCanvas = new Kinetic.SceneCanvas({
pixelRatio: 1
});
this.bufferHitCanvas = new Kinetic.HitCanvas();
this._resizeDOM();
},
_onContent: function(typesStr, handler) {
var types = typesStr.split(SPACE),
len = types.length,
n, baseEvent;
for(n = 0; n < len; n++) {
baseEvent = types[n];
this.content.addEventListener(baseEvent, handler, false);
}
},
// currently cache function is now working for stage, because stage has no its own canvas element
// TODO: may be it is better to cache all children layers?
cache: function() {
Kinetic.Util.warn('Cache function is not allowed for stage. You may use cache only for layers, groups and shapes.');
return;
},
clearCache : function() {
}
});
Kinetic.Util.extend(Kinetic.Stage, Kinetic.Container);
// add getters and setters
Kinetic.Factory.addGetter(Kinetic.Stage, 'container');
Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Stage, 'container');
/**
* get container DOM element
* @name container
* @method
* @memberof Kinetic.Stage.prototype
* @returns {DomElement} container
* @example
* // get container<br>
* var container = stage.container();<br><br>
*
* // set container<br>
* var container = document.createElement('div');<br>
* body.appendChild(container);<br>
* stage.container(container);
*/
})();
;(function() {
Kinetic.Util.addMethods(Kinetic.BaseLayer, {
___init: function(config) {
this.nodeType = 'Layer';
Kinetic.Container.call(this, config);
},
createPNGStream : function() {
return this.canvas._canvas.createPNGStream();
},
/**
* get layer canvas
* @method
* @memberof Kinetic.BaseLayer.prototype
*/
getCanvas: function() {
return this.canvas;
},
/**
* get layer hit canvas
* @method
* @memberof Kinetic.BaseLayer.prototype
*/
getHitCanvas: function() {
return this.hitCanvas;
},
/**
* get layer canvas context
* @method
* @memberof Kinetic.BaseLayer.prototype
*/
getContext: function() {
return this.getCanvas().getContext();
},
/**
* clear scene and hit canvas contexts tied to the layer
* @method
* @memberof Kinetic.BaseLayer.prototype
* @param {Object} [bounds]
* @param {Number} [bounds.x]
* @param {Number} [bounds.y]
* @param {Number} [bounds.width]
* @param {Number} [bounds.height]
* @example
* layer.clear();<br>
* layer.clear(0, 0, 100, 100);
*/
clear: function(bounds) {
this.getContext().clear(bounds);
this.getHitCanvas().getContext().clear(bounds);
return this;
},
// extend Node.prototype.setZIndex
setZIndex: function(index) {
Kinetic.Node.prototype.setZIndex.call(this, index);
var stage = this.getStage();
if(stage) {
stage.content.removeChild(this.getCanvas()._canvas);
if(index < stage.getChildren().length - 1) {
stage.content.insertBefore(this.getCanvas()._canvas, stage.getChildren()[index + 1].getCanvas()._canvas);
}
else {
stage.content.appendChild(this.getCanvas()._canvas);
}
}
return this;
},
// extend Node.prototype.moveToTop
moveToTop: function() {
Kinetic.Node.prototype.moveToTop.call(this);
var stage = this.getStage();
if(stage) {
stage.content.removeChild(this.getCanvas()._canvas);
stage.content.appendChild(this.getCanvas()._canvas);
}
},
// extend Node.prototype.moveUp
moveUp: function() {
if(Kinetic.Node.prototype.moveUp.call(this)) {
var stage = this.getStage();
if(stage) {
stage.content.removeChild(this.getCanvas()._canvas);
if(this.index < stage.getChildren().length - 1) {
stage.content.insertBefore(this.getCanvas()._canvas, stage.getChildren()[this.index + 1].getCanvas()._canvas);
}
else {
stage.content.appendChild(this.getCanvas()._canvas);
}
}
}
},
// extend Node.prototype.moveDown
moveDown: function() {
if(Kinetic.Node.prototype.moveDown.call(this)) {
var stage = this.getStage();
if(stage) {
var children = stage.getChildren();
stage.content.removeChild(this.getCanvas()._canvas);
stage.content.insertBefore(this.getCanvas()._canvas, children[this.index + 1].getCanvas()._canvas);
}
}
},
// extend Node.prototype.moveToBottom
moveToBottom: function() {
if(Kinetic.Node.prototype.moveToBottom.call(this)) {
var stage = this.getStage();
if(stage) {
var children = stage.getChildren();
stage.content.removeChild(this.getCanvas()._canvas);
stage.content.insertBefore(this.getCanvas()._canvas, children[1].getCanvas()._canvas);
}
}
},
getLayer: function() {
return this;
},
remove: function() {
var _canvas = this.getCanvas()._canvas;
Kinetic.Node.prototype.remove.call(this);
if(_canvas && _canvas.parentNode && Kinetic.Util._isInDocument(_canvas)) {
_canvas.parentNode.removeChild(_canvas);
}
return this;
},
getStage: function() {
return this.parent;
}
});
Kinetic.Util.extend(Kinetic.BaseLayer, Kinetic.Container);
// add getters and setters
Kinetic.Factory.addGetterSetter(Kinetic.BaseLayer, 'clearBeforeDraw', true);
/**
* get/set clearBeforeDraw flag which determines if the layer is cleared or not
* before drawing
* @name clearBeforeDraw
* @method
* @memberof Kinetic.BaseLayer.prototype
* @param {Boolean} clearBeforeDraw
* @returns {Boolean}
* @example
* // get clearBeforeDraw flag<br>
* var clearBeforeDraw = layer.clearBeforeDraw();<br><br>
*
* // disable clear before draw<br>
* layer.clearBeforeDraw(false);<br><br>
*
* // enable clear before draw<br>
* layer.clearBeforeDraw(true);
*/
Kinetic.Collection.mapMethods(Kinetic.BaseLayer);
})();
;(function() {
// constants
var HASH = '#',
BEFORE_DRAW ='beforeDraw',
DRAW = 'draw',
/*
* 2 - 3 - 4
* | |
* 1 - 0 5
* |
* 8 - 7 - 6
*/
INTERSECTION_OFFSETS = [
{x: 0, y: 0}, // 0
{x: -1, y: 0}, // 1
{x: -1, y: -1}, // 2
{x: 0, y: -1}, // 3
{x: 1, y: -1}, // 4
{x: 1, y: 0}, // 5
{x: 1, y: 1}, // 6
{x: 0, y: 1}, // 7
{x: -1, y: 1} // 8
],
INTERSECTION_OFFSETS_LEN = INTERSECTION_OFFSETS.length;
Kinetic.Util.addMethods(Kinetic.Layer, {
____init: function(config) {
this.nodeType = 'Layer';
this.canvas = new Kinetic.SceneCanvas();
this.hitCanvas = new Kinetic.HitCanvas();
// call super constructor
Kinetic.BaseLayer.call(this, config);
},
_setCanvasSize: function(width, height) {
this.canvas.setSize(width, height);
this.hitCanvas.setSize(width, height);
},
_validateAdd: function(child) {
var type = child.getType();
if (type !== 'Group' && type !== 'Shape') {
Kinetic.Util.error('You may only add groups and shapes to a layer.');
}
},
/**
* get visible intersection shape. This is the preferred
* method for determining if a point intersects a shape or not
* @method
* @memberof Kinetic.Layer.prototype
* @param {Object} pos
* @param {Number} pos.x
* @param {Number} pos.y
* @returns {Kinetic.Shape}
*/
getIntersection: function(pos) {
var obj, i, intersectionOffset, shape;
if(this.hitGraphEnabled() && this.isVisible()) {
for (i=0; i<INTERSECTION_OFFSETS_LEN; i++) {
intersectionOffset = INTERSECTION_OFFSETS[i];
obj = this._getIntersection({
x: pos.x + intersectionOffset.x,
y: pos.y + intersectionOffset.y
});
shape = obj.shape;
if (shape) {
return shape;
}
else if (!obj.antialiased) {
return null;
}
}
}
else {
return null;
}
},
_getIntersection: function(pos) {
var p = this.hitCanvas.context._context.getImageData(pos.x, pos.y, 1, 1).data,
p3 = p[3],
colorKey, shape;
// fully opaque pixel
if(p3 === 255) {
colorKey = Kinetic.Util._rgbToHex(p[0], p[1], p[2]);
shape = Kinetic.shapes[HASH + colorKey];
return {
shape: shape
};
}
// antialiased pixel
else if(p3 > 0) {
return {
antialiased: true
};
}
// empty pixel
else {
return {};
}
},
drawScene: function(can, top) {
var layer = this.getLayer(),
canvas = can || (layer && layer.getCanvas());
this._fire(BEFORE_DRAW, {
node: this
});
if(this.getClearBeforeDraw()) {
canvas.getContext().clear();
}
Kinetic.Container.prototype.drawScene.call(this, canvas, top);
this._fire(DRAW, {
node: this
});
return this;
},
// the apply transform method is handled by the Layer and FastLayer class
// because it is up to the layer to decide if an absolute or relative transform
// should be used
_applyTransform: function(shape, context, top) {
var m = shape.getAbsoluteTransform(top).getMatrix();
context.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
},
drawHit: function(can, top) {
var layer = this.getLayer(),
canvas = can || (layer && layer.hitCanvas);
if(layer && layer.getClearBeforeDraw()) {
layer.getHitCanvas().getContext().clear();
}
Kinetic.Container.prototype.drawHit.call(this, canvas, top);
return this;
},
/**
* clear scene and hit canvas contexts tied to the layer
* @method
* @memberof Kinetic.Layer.prototype
* @param {Object} [bounds]
* @param {Number} [bounds.x]
* @param {Number} [bounds.y]
* @param {Number} [bounds.width]
* @param {Number} [bounds.height]
* @example
* layer.clear();<br>
* layer.clear(0, 0, 100, 100);
*/
clear: function(bounds) {
this.getContext().clear(bounds);
this.getHitCanvas().getContext().clear(bounds);
return this;
},
// extend Node.prototype.setVisible
setVisible: function(visible) {
Kinetic.Node.prototype.setVisible.call(this, visible);
if(visible) {
this.getCanvas()._canvas.style.display = 'block';
this.hitCanvas._canvas.style.display = 'block';
}
else {
this.getCanvas()._canvas.style.display = 'none';
this.hitCanvas._canvas.style.display = 'none';
}
return this;
},
/**
* enable hit graph
* @name enableHitGraph
* @method
* @memberof Kinetic.Layer.prototype
* @returns {Node}
*/
enableHitGraph: function() {
this.setHitGraphEnabled(true);
return this;
},
/**
* disable hit graph
* @name enableHitGraph
* @method
* @memberof Kinetic.Layer.prototype
* @returns {Node}
*/
disableHitGraph: function() {
this.setHitGraphEnabled(false);
return this;
}
});
Kinetic.Util.extend(Kinetic.Layer, Kinetic.BaseLayer);
Kinetic.Factory.addGetterSetter(Kinetic.Layer, 'hitGraphEnabled', true);
/**
* get/set hitGraphEnabled flag. Disabling the hit graph will greatly increase
* draw performance because the hit graph will not be redrawn each time the layer is
* drawn. This, however, also disables mouse/touch event detection
* @name hitGraphEnabled
* @method
* @memberof Kinetic.Layer.prototype
* @param {Boolean} enabled
* @returns {Boolean}
* @example
* // get hitGraphEnabled flag<br>
* var hitGraphEnabled = layer.hitGraphEnabled();<br><br>
*
* // disable hit graph<br>
* layer.hitGraphEnabled(false);<br><br>
*
* // enable hit graph<br>
* layer.hitGraphEnabled(true);
*/
Kinetic.Collection.mapMethods(Kinetic.Layer);
})();
;(function() {
// constants
var HASH = '#',
BEFORE_DRAW ='beforeDraw',
DRAW = 'draw';
Kinetic.Util.addMethods(Kinetic.FastLayer, {
____init: function(config) {
this.nodeType = 'Layer';
this.canvas = new Kinetic.SceneCanvas();
// call super constructor
Kinetic.BaseLayer.call(this, config);
},
_validateAdd: function(child) {
var type = child.getType();
if (type !== 'Shape') {
Kinetic.Util.error('You may only add shapes to a fast layer.');
}
},
_setCanvasSize: function(width, height) {
this.canvas.setSize(width, height);
},
hitGraphEnabled: function() {
return false;
},
getIntersection: function() {
return null;
},
drawScene: function(can) {
var layer = this.getLayer(),
canvas = can || (layer && layer.getCanvas());
if(this.getClearBeforeDraw()) {
canvas.getContext().clear();
}
Kinetic.Container.prototype.drawScene.call(this, canvas);
return this;
},
// the apply transform method is handled by the Layer and FastLayer class
// because it is up to the layer to decide if an absolute or relative transform
// should be used
_applyTransform: function(shape, context, top) {
if (!top || top._id !== this._id) {
var m = shape.getTransform().getMatrix();
context.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
}
},
draw: function() {
this.drawScene();
return this;
},
/**
* clear scene and hit canvas contexts tied to the layer
* @method
* @memberof Kinetic.FastLayer.prototype
* @param {Object} [bounds]
* @param {Number} [bounds.x]
* @param {Number} [bounds.y]
* @param {Number} [bounds.width]
* @param {Number} [bounds.height]
* @example
* layer.clear();<br>
* layer.clear(0, 0, 100, 100);
*/
clear: function(bounds) {
this.getContext().clear(bounds);
return this;
},
// extend Node.prototype.setVisible
setVisible: function(visible) {
Kinetic.Node.prototype.setVisible.call(this, visible);
if(visible) {
this.getCanvas()._canvas.style.display = 'block';
}
else {
this.getCanvas()._canvas.style.display = 'none';
}
return this;
}
});
Kinetic.Util.extend(Kinetic.FastLayer, Kinetic.BaseLayer);
Kinetic.Collection.mapMethods(Kinetic.FastLayer);
})();
;(function() {
Kinetic.Util.addMethods(Kinetic.Group, {
___init: function(config) {
this.nodeType = 'Group';
// call super constructor
Kinetic.Container.call(this, config);
},
_validateAdd: function(child) {
var type = child.getType();
if (type !== 'Group' && type !== 'Shape') {
Kinetic.Util.error('You may only add groups and shapes to groups.');
}
}
});
Kinetic.Util.extend(Kinetic.Group, Kinetic.Container);
Kinetic.Collection.mapMethods(Kinetic.Group);
})();
;(function() {
/**
* Rect constructor
* @constructor
* @memberof Kinetic
* @augments Kinetic.Shape
* @param {Object} config
* @param {Number} [config.cornerRadius]
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var rect = new Kinetic.Rect({<br>
* width: 100,<br>
* height: 50,<br>
* fill: 'red',<br>
* stroke: 'black',<br>
* strokeWidth: 5<br>
* });
*/
Kinetic.Rect = function(config) {
this.___init(config);
};
Kinetic.Rect.prototype = {
___init: function(config) {
Kinetic.Shape.call(this, config);
this.className = 'Rect';
this.sceneFunc(this._sceneFunc);
},
_sceneFunc: function(context) {
var cornerRadius = this.getCornerRadius(),
width = this.getWidth(),
height = this.getHeight();
context.beginPath();
if(!cornerRadius) {
// simple rect - don't bother doing all that complicated maths stuff.
context.rect(0, 0, width, height);
}
else {
// arcTo would be nicer, but browser support is patchy (Opera)
context.moveTo(cornerRadius, 0);
context.lineTo(width - cornerRadius, 0);
context.arc(width - cornerRadius, cornerRadius, cornerRadius, Math.PI * 3 / 2, 0, false);
context.lineTo(width, height - cornerRadius);
context.arc(width - cornerRadius, height - cornerRadius, cornerRadius, 0, Math.PI / 2, false);
context.lineTo(cornerRadius, height);
context.arc(cornerRadius, height - cornerRadius, cornerRadius, Math.PI / 2, Math.PI, false);
context.lineTo(0, cornerRadius);
context.arc(cornerRadius, cornerRadius, cornerRadius, Math.PI, Math.PI * 3 / 2, false);
}
context.closePath();
context.fillStrokeShape(this);
}
};
Kinetic.Util.extend(Kinetic.Rect, Kinetic.Shape);
Kinetic.Factory.addGetterSetter(Kinetic.Rect, 'cornerRadius', 0);
/**
* get/set corner radius
* @name cornerRadius
* @method
* @memberof Kinetic.Rect.prototype
* @param {Number} cornerRadius
* @returns {Number}
* @example
* // get corner radius<br>
* var cornerRadius = rect.cornerRadius();<br><br>
*
* // set corner radius<br>
* rect.cornerRadius(10);
*/
Kinetic.Collection.mapMethods(Kinetic.Rect);
})();
;(function() {
// the 0.0001 offset fixes a bug in Chrome 27
var PIx2 = (Math.PI * 2) - 0.0001,
CIRCLE = 'Circle';
/**
* Circle constructor
* @constructor
* @memberof Kinetic
* @augments Kinetic.Shape
* @param {Object} config
* @param {Number} config.radius
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* // create circle
* var circle = new Kinetic.Circle({<br>
* radius: 40,<br>
* fill: 'red',<br>
* stroke: 'black'<br>
* strokeWidth: 5<br>
* });
*/
Kinetic.Circle = function(config) {
this.___init(config);
};
Kinetic.Circle.prototype = {
___init: function(config) {
// call super constructor
Kinetic.Shape.call(this, config);
this.className = CIRCLE;
this.sceneFunc(this._sceneFunc);
},
_sceneFunc: function(context) {
context.beginPath();
context.arc(0, 0, this.getRadius(), 0, PIx2, false);
context.closePath();
context.fillStrokeShape(this);
},
// implements Shape.prototype.getWidth()
getWidth: function() {
return this.getRadius() * 2;
},
// implements Shape.prototype.getHeight()
getHeight: function() {
return this.getRadius() * 2;
},
// implements Shape.prototype.setWidth()
setWidth: function(width) {
Kinetic.Node.prototype.setWidth.call(this, width);
this.setRadius(width / 2);
},
// implements Shape.prototype.setHeight()
setHeight: function(height) {
Kinetic.Node.prototype.setHeight.call(this, height);
this.setRadius(height / 2);
}
};
Kinetic.Util.extend(Kinetic.Circle, Kinetic.Shape);
// add getters setters
Kinetic.Factory.addGetterSetter(Kinetic.Circle, 'radius', 0);
/**
* get/set radius
* @name radius
* @method
* @memberof Kinetic.Circle.prototype
* @param {Number} radius
* @returns {Number}
* @example
* // get radius<br>
* var radius = circle.radius();<br><br>
*
* // set radius<br>
* circle.radius(10);<br>
*/
Kinetic.Collection.mapMethods(Kinetic.Circle);
})();
;(function() {
// the 0.0001 offset fixes a bug in Chrome 27
var PIx2 = (Math.PI * 2) - 0.0001,
ELLIPSE = 'Ellipse';
/**
* Ellipse constructor
* @constructor
* @augments Kinetic.Shape
* @param {Object} config
* @param {Object} config.radius defines x and y radius
* @@ShapeParams
* @@NodeParams
* @example
* var ellipse = new Kinetic.Ellipse({<br>
* radius : {<br>
* x : 50,<br>
* y : 50<br>
* },<br>
* fill: 'red'<br>
* });
*/
Kinetic.Ellipse = function(config) {
this.___init(config);
};
Kinetic.Ellipse.prototype = {
___init: function(config) {
// call super constructor
Kinetic.Shape.call(this, config);
this.className = ELLIPSE;
this.sceneFunc(this._sceneFunc);
},
_sceneFunc: function(context) {
var r = this.getRadius(),
rx = r.x,
ry = r.y;
context.beginPath();
context.save();
if(rx !== ry) {
context.scale(1, ry / rx);
}
context.arc(0, 0, rx, 0, PIx2, false);
context.restore();
context.closePath();
context.fillStrokeShape(this);
},
// implements Shape.prototype.getWidth()
getWidth: function() {
return this.getRadius().x * 2;
},
// implements Shape.prototype.getHeight()
getHeight: function() {
return this.getRadius().y * 2;
},
// implements Shape.prototype.setWidth()
setWidth: function(width) {
Kinetic.Node.prototype.setWidth.call(this, width);
this.setRadius({
x: width / 2
});
},
// implements Shape.prototype.setHeight()
setHeight: function(height) {
Kinetic.Node.prototype.setHeight.call(this, height);
this.setRadius({
y: height / 2
});
}
};
Kinetic.Util.extend(Kinetic.Ellipse, Kinetic.Shape);
// add getters setters
Kinetic.Factory.addComponentsGetterSetter(Kinetic.Ellipse, 'radius', ['x', 'y']);
/**
* get/set radius
* @name radius
* @method
* @memberof Kinetic.Ellipse.prototype
* @param {Object} radius
* @param {Number} radius.x
* @param {Number} radius.y
* @returns {Object}
* @example
* // get radius<br>
* var radius = ellipse.radius();<br><br>
*
* // set radius<br>
* ellipse.radius({<br>
* x: 200,<br>
* y: 100<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Ellipse, 'radiusX', 0);
/**
* get/set radius x
* @name radiusX
* @method
* @memberof Kinetic.Ellipse.prototype
* @param {Number} x
* @returns {Number}
* @example
* // get radius x<br>
* var radiusX = ellipse.radiusX();<br><br>
*
* // set radius x<br>
* ellipse.radiusX(200);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Ellipse, 'radiusY', 0);
/**
* get/set radius y
* @name radiusY
* @method
* @memberof Kinetic.Ellipse.prototype
* @param {Number} y
* @returns {Number}
* @example
* // get radius y<br>
* var radiusY = ellipse.radiusY();<br><br>
*
* // set radius y<br>
* ellipse.radiusY(200);
*/
Kinetic.Collection.mapMethods(Kinetic.Ellipse);
})();;(function() {
// the 0.0001 offset fixes a bug in Chrome 27
var PIx2 = (Math.PI * 2) - 0.0001;
/**
* Ring constructor
* @constructor
* @augments Kinetic.Shape
* @param {Object} config
* @param {Number} config.innerRadius
* @param {Number} config.outerRadius
* @param {Boolean} [config.clockwise]
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var ring = new Kinetic.Ring({<br>
* innerRadius: 40,<br>
* outerRadius: 80,<br>
* fill: 'red',<br>
* stroke: 'black',<br>
* strokeWidth: 5<br>
* });
*/
Kinetic.Ring = function(config) {
this.___init(config);
};
Kinetic.Ring.prototype = {
___init: function(config) {
// call super constructor
Kinetic.Shape.call(this, config);
this.className = 'Ring';
this.sceneFunc(this._sceneFunc);
},
_sceneFunc: function(context) {
context.beginPath();
context.arc(0, 0, this.getInnerRadius(), 0, PIx2, false);
context.moveTo(this.getOuterRadius(), 0);
context.arc(0, 0, this.getOuterRadius(), PIx2, 0, true);
context.closePath();
context.fillStrokeShape(this);
},
// implements Shape.prototype.getWidth()
getWidth: function() {
return this.getOuterRadius() * 2;
},
// implements Shape.prototype.getHeight()
getHeight: function() {
return this.getOuterRadius() * 2;
},
// implements Shape.prototype.setWidth()
setWidth: function(width) {
Kinetic.Node.prototype.setWidth.call(this, width);
this.setOuterRadius(width / 2);
},
// implements Shape.prototype.setHeight()
setHeight: function(height) {
Kinetic.Node.prototype.setHeight.call(this, height);
this.setOuterRadius(height / 2);
}
};
Kinetic.Util.extend(Kinetic.Ring, Kinetic.Shape);
// add getters setters
Kinetic.Factory.addGetterSetter(Kinetic.Ring, 'innerRadius', 0);
/**
* get/set innerRadius
* @name innerRadius
* @method
* @memberof Kinetic.Ring.prototype
* @param {Number} innerRadius
* @returns {Number}
* @example
* // get inner radius<br>
* var innerRadius = ring.innerRadius();<br><br>
*
* // set inner radius<br>
* ring.innerRadius(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Ring, 'outerRadius', 0);
/**
* get/set outerRadius
* @name outerRadius
* @method
* @memberof Kinetic.Ring.prototype
* @param {Number} outerRadius
* @returns {Number}
* @example
* // get outer radius<br>
* var outerRadius = ring.outerRadius();<br><br>
*
* // set outer radius<br>
* ring.outerRadius(20);
*/
Kinetic.Collection.mapMethods(Kinetic.Ring);
})();
;(function() {
/**
* Wedge constructor
* @constructor
* @augments Kinetic.Shape
* @param {Object} config
* @param {Number} config.angle in degrees
* @param {Number} config.radius
* @param {Boolean} [config.clockwise]
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* // draw a wedge that's pointing downwards<br>
* var wedge = new Kinetic.Wedge({<br>
* radius: 40,<br>
* fill: 'red',<br>
* stroke: 'black'<br>
* strokeWidth: 5,<br>
* angleDeg: 60,<br>
* rotationDeg: -120<br>
* });
*/
Kinetic.Wedge = function(config) {
this.___init(config);
};
Kinetic.Wedge.prototype = {
___init: function(config) {
// call super constructor
Kinetic.Shape.call(this, config);
this.className = 'Wedge';
this.sceneFunc(this._sceneFunc);
},
_sceneFunc: function(context) {
context.beginPath();
context.arc(0, 0, this.getRadius(), 0, Kinetic.getAngle(this.getAngle()), this.getClockwise());
context.lineTo(0, 0);
context.closePath();
context.fillStrokeShape(this);
}
};
Kinetic.Util.extend(Kinetic.Wedge, Kinetic.Shape);
// add getters setters
Kinetic.Factory.addGetterSetter(Kinetic.Wedge, 'radius', 0);
/**
* get/set radius
* @name radius
* @method
* @memberof Kinetic.Wedge.prototype
* @param {Number} radius
* @returns {Number}
* @example
* // get radius<br>
* var radius = wedge.radius();<br><br>
*
* // set radius<br>
* wedge.radius(10);<br>
*/
Kinetic.Factory.addGetterSetter(Kinetic.Wedge, 'angle', 0);
/**
* get/set angle in degrees
* @name angle
* @method
* @memberof Kinetic.Wedge.prototype
* @param {Number} angle
* @returns {Number}
* @example
* // get angle<br>
* var angle = wedge.angle();<br><br>
*
* // set angle<br>
* wedge.angle(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Wedge, 'clockwise', false);
/**
* get/set clockwise flag
* @name clockwise
* @method
* @memberof Kinetic.Wedge.prototype
* @param {Number} clockwise
* @returns {Number}
* @example
* // get clockwise flag<br>
* var clockwise = wedge.clockwise();<br><br>
*
* // draw wedge counter-clockwise<br>
* wedge.clockwise(false);<br><br>
*
* // draw wedge clockwise<br>
* wedge.clockwise(true);
*/
Kinetic.Factory.backCompat(Kinetic.Wedge, {
angleDeg: 'angle',
getAngleDeg: 'getAngle',
setAngleDeg: 'setAngle'
});
Kinetic.Collection.mapMethods(Kinetic.Wedge);
})();
;(function() {
var PI_OVER_180 = Math.PI / 180;
/**
* Arc constructor
* @constructor
* @augments Kinetic.Shape
* @param {Object} config
* @param {Number} config.angle in degrees
* @param {Number} config.innerRadius
* @param {Number} config.outerRadius
* @param {Boolean} [config.clockwise]
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* // draw a Arc that's pointing downwards<br>
* var arc = new Kinetic.Arc({<br>
* innerRadius: 40,<br>
* outerRadius: 80,<br>
* fill: 'red',<br>
* stroke: 'black'<br>
* strokeWidth: 5,<br>
* angle: 60,<br>
* rotationDeg: -120<br>
* });
*/
Kinetic.Arc = function(config) {
this.___init(config);
};
Kinetic.Arc.prototype = {
___init: function(config) {
// call super constructor
Kinetic.Shape.call(this, config);
this.className = 'Arc';
this.sceneFunc(this._sceneFunc);
},
_sceneFunc: function(context) {
var angle = Kinetic.getAngle(this.angle()),
clockwise = this.clockwise();
context.beginPath();
context.arc(0, 0, this.getOuterRadius(), 0, angle, clockwise);
context.arc(0, 0, this.getInnerRadius(), angle, 0, !clockwise);
context.closePath();
context.fillStrokeShape(this);
}
};
Kinetic.Util.extend(Kinetic.Arc, Kinetic.Shape);
// add getters setters
Kinetic.Factory.addGetterSetter(Kinetic.Arc, 'innerRadius', 0);
/**
* get/set innerRadius
* @name innerRadius
* @method
* @memberof Kinetic.Arc.prototype
* @param {Number} innerRadius
* @returns {Number}
* @example
* // get inner radius
* var innerRadius = arc.innerRadius();
*
* // set inner radius
* arc.innerRadius(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Arc, 'outerRadius', 0);
/**
* get/set outerRadius
* @name outerRadius
* @method
* @memberof Kinetic.Arc.prototype
* @param {Number} outerRadius
* @returns {Number}
* @example
* // get outer radius<br>
* var outerRadius = arc.outerRadius();<br><br>
*
* // set outer radius<br>
* arc.outerRadius(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Arc, 'angle', 0);
/**
* get/set angle in degrees
* @name angle
* @method
* @memberof Kinetic.Arc.prototype
* @param {Number} angle
* @returns {Number}
* @example
* // get angle<br>
* var angle = arc.angle();<br><br>
*
* // set angle<br>
* arc.angle(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Arc, 'clockwise', false);
/**
* get/set clockwise flag
* @name clockwise
* @method
* @memberof Kinetic.Arc.prototype
* @param {Boolean} clockwise
* @returns {Boolean}
* @example
* // get clockwise flag<br>
* var clockwise = arc.clockwise();<br><br>
*
* // draw arc counter-clockwise<br>
* arc.clockwise(false);<br><br>
*
* // draw arc clockwise<br>
* arc.clockwise(true);
*/
Kinetic.Collection.mapMethods(Kinetic.Arc);
})();
;(function() {
// CONSTANTS
var IMAGE = 'Image';
/**
* Image constructor
* @constructor
* @memberof Kinetic
* @augments Kinetic.Shape
* @param {Object} config
* @param {ImageObject} config.image
* @param {Object} [config.crop]
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var imageObj = new Image();<br>
* imageObj.onload = function() {<br>
* var image = new Kinetic.Image({<br>
* x: 200,<br>
* y: 50,<br>
* image: imageObj,<br>
* width: 100,<br>
* height: 100<br>
* });<br>
* };<br>
* imageObj.src = '/path/to/image.jpg'
*/
Kinetic.Image = function(config) {
this.___init(config);
};
Kinetic.Image.prototype = {
___init: function(config) {
// call super constructor
Kinetic.Shape.call(this, config);
this.className = IMAGE;
this.sceneFunc(this._sceneFunc);
this.hitFunc(this._hitFunc);
},
_useBufferCanvas: function() {
return (this.hasShadow() || this.getAbsoluteOpacity() !== 1) && this.hasStroke();
},
_sceneFunc: function(context) {
var width = this.getWidth(),
height = this.getHeight(),
image = this.getImage(),
crop, cropWidth, cropHeight, params;
if (image) {
crop = this.getCrop();
cropWidth = crop.width;
cropHeight = crop.height;
if (cropWidth && cropHeight) {
params = [image, crop.x, crop.y, cropWidth, cropHeight, 0, 0, width, height];
} else {
params = [image, 0, 0, width, height];
}
}
context.beginPath();
context.rect(0, 0, width, height);
context.closePath();
context.fillStrokeShape(this);
if (image) {
context.drawImage.apply(context, params);
}
},
_hitFunc: function(context) {
var width = this.getWidth(),
height = this.getHeight();
context.beginPath();
context.rect(0, 0, width, height);
context.closePath();
context.fillStrokeShape(this);
},
getWidth: function() {
var image = this.getImage();
return this.attrs.width || (image ? image.width : 0);
},
getHeight: function() {
var image = this.getImage();
return this.attrs.height || (image ? image.height : 0);
}
};
Kinetic.Util.extend(Kinetic.Image, Kinetic.Shape);
// add getters setters
Kinetic.Factory.addGetterSetter(Kinetic.Image, 'image');
/**
* set image
* @name setImage
* @method
* @memberof Kinetic.Image.prototype
* @param {ImageObject} image
*/
/**
* get image
* @name getImage
* @method
* @memberof Kinetic.Image.prototype
* @returns {ImageObject}
*/
Kinetic.Factory.addComponentsGetterSetter(Kinetic.Image, 'crop', ['x', 'y', 'width', 'height']);
/**
* get/set crop
* @method
* @name crop
* @memberof Kinetic.Image.prototype
* @param {Object} crop
* @param {Number} crop.x
* @param {Number} crop.y
* @param {Number} crop.width
* @param {Number} crop.height
* @returns {Object}
* @example
* // get crop<br>
* var crop = image.crop();<br><br>
*
* // set crop<br>
* image.crop({<br>
* x: 20,<br>
* y: 20,<br>
* width: 20,<br>
* height: 20<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Image, 'cropX', 0);
/**
* get/set crop x
* @method
* @name cropX
* @memberof Kinetic.Image.prototype
* @param {Number} x
* @returns {Number}
* @example
* // get crop x<br>
* var cropX = image.cropX();<br><br>
*
* // set crop x<br>
* image.cropX(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Image, 'cropY', 0);
/**
* get/set crop y
* @name cropY
* @method
* @memberof Kinetic.Image.prototype
* @param {Number} y
* @returns {Number}
* @example
* // get crop y<br>
* var cropY = image.cropY();<br><br>
*
* // set crop y<br>
* image.cropY(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Image, 'cropWidth', 0);
/**
* get/set crop width
* @name cropWidth
* @method
* @memberof Kinetic.Image.prototype
* @param {Number} width
* @returns {Number}
* @example
* // get crop width<br>
* var cropWidth = image.cropWidth();<br><br>
*
* // set crop width<br>
* image.cropWidth(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Image, 'cropHeight', 0);
/**
* get/set crop height
* @name cropHeight
* @method
* @memberof Kinetic.Image.prototype
* @param {Number} height
* @returns {Number}
* @example
* // get crop height<br>
* var cropHeight = image.cropHeight();<br><br>
*
* // set crop height<br>
* image.cropHeight(20);
*/
Kinetic.Collection.mapMethods(Kinetic.Image);
})();
;(function() {
// constants
var AUTO = 'auto',
//CANVAS = 'canvas',
CENTER = 'center',
CHANGE_KINETIC = 'Change.kinetic',
CONTEXT_2D = '2d',
DASH = '-',
EMPTY_STRING = '',
LEFT = 'left',
TEXT = 'text',
TEXT_UPPER = 'Text',
MIDDLE = 'middle',
NORMAL = 'normal',
PX_SPACE = 'px ',
SPACE = ' ',
RIGHT = 'right',
WORD = 'word',
CHAR = 'char',
NONE = 'none',
ATTR_CHANGE_LIST = ['fontFamily', 'fontSize', 'fontStyle', 'fontVariant', 'padding', 'align', 'lineHeight', 'text', 'width', 'height', 'wrap'],
// cached variables
attrChangeListLen = ATTR_CHANGE_LIST.length,
dummyContext = Kinetic.Util.createCanvasElement().getContext(CONTEXT_2D);
/**
* Text constructor
* @constructor
* @memberof Kinetic
* @augments Kinetic.Shape
* @param {Object} config
* @param {String} [config.fontFamily] default is Arial
* @param {Number} [config.fontSize] in pixels. Default is 12
* @param {String} [config.fontStyle] can be normal, bold, or italic. Default is normal
* @param {String} [config.fontVariant] can be normal or small-caps. Default is normal
* @param {String} config.text
* @param {String} [config.align] can be left, center, or right
* @param {Number} [config.padding]
* @param {Number} [config.width] default is auto
* @param {Number} [config.height] default is auto
* @param {Number} [config.lineHeight] default is 1
* @param {String} [config.wrap] can be word, char, or none. Default is word
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var text = new Kinetic.Text({<br>
* x: 10,<br>
* y: 15,<br>
* text: 'Simple Text',<br>
* fontSize: 30,<br>
* fontFamily: 'Calibri',<br>
* fill: 'green'<br>
* });
*/
Kinetic.Text = function(config) {
this.___init(config);
};
function _fillFunc(context) {
context.fillText(this.partialText, 0, 0);
}
function _strokeFunc(context) {
context.strokeText(this.partialText, 0, 0);
}
Kinetic.Text.prototype = {
___init: function(config) {
var that = this;
if (config.width === undefined) {
config.width = AUTO;
}
if (config.height === undefined) {
config.height = AUTO;
}
// call super constructor
Kinetic.Shape.call(this, config);
this._fillFunc = _fillFunc;
this._strokeFunc = _strokeFunc;
this.className = TEXT_UPPER;
// update text data for certain attr changes
for(var n = 0; n < attrChangeListLen; n++) {
this.on(ATTR_CHANGE_LIST[n] + CHANGE_KINETIC, that._setTextData);
}
this._setTextData();
this.sceneFunc(this._sceneFunc);
this.hitFunc(this._hitFunc);
},
_sceneFunc: function(context) {
var p = this.getPadding(),
textHeight = this.getTextHeight(),
lineHeightPx = this.getLineHeight() * textHeight,
textArr = this.textArr,
textArrLen = textArr.length,
totalWidth = this.getWidth(),
n;
context.setAttr('font', this._getContextFont());
context.setAttr('textBaseline', MIDDLE);
context.setAttr('textAlign', LEFT);
context.save();
context.translate(p, 0);
context.translate(0, p + textHeight / 2);
// draw text lines
for(n = 0; n < textArrLen; n++) {
var obj = textArr[n],
text = obj.text,
width = obj.width;
// horizontal alignment
context.save();
if(this.getAlign() === RIGHT) {
context.translate(totalWidth - width - p * 2, 0);
}
else if(this.getAlign() === CENTER) {
context.translate((totalWidth - width - p * 2) / 2, 0);
}
this.partialText = text;
context.fillStrokeShape(this);
context.restore();
context.translate(0, lineHeightPx);
}
context.restore();
},
_hitFunc: function(context) {
var width = this.getWidth(),
height = this.getHeight();
context.beginPath();
context.rect(0, 0, width, height);
context.closePath();
context.fillStrokeShape(this);
},
setText: function(text) {
var str = Kinetic.Util._isString(text) ? text : text.toString();
this._setAttr(TEXT, str);
return this;
},
/**
* get width of text area, which includes padding
* @method
* @memberof Kinetic.Text.prototype
* @returns {Number}
*/
getWidth: function() {
return this.attrs.width === AUTO ? this.getTextWidth() + this.getPadding() * 2 : this.attrs.width;
},
/**
* get the height of the text area, which takes into account multi-line text, line heights, and padding
* @method
* @memberof Kinetic.Text.prototype
* @returns {Number}
*/
getHeight: function() {
return this.attrs.height === AUTO ? (this.getTextHeight() * this.textArr.length * this.getLineHeight()) + this.getPadding() * 2 : this.attrs.height;
},
/**
* get text width
* @method
* @memberof Kinetic.Text.prototype
* @returns {Number}
*/
getTextWidth: function() {
return this.textWidth;
},
/**
* get text height
* @method
* @memberof Kinetic.Text.prototype
* @returns {Number}
*/
getTextHeight: function() {
return this.textHeight;
},
_getTextSize: function(text) {
var _context = dummyContext,
fontSize = this.getFontSize(),
metrics;
_context.save();
_context.font = this._getContextFont();
metrics = _context.measureText(text);
_context.restore();
return {
width: metrics.width,
height: parseInt(fontSize, 10)
};
},
_getContextFont: function() {
return this.getFontStyle() + SPACE + this.getFontVariant() + SPACE + this.getFontSize() + PX_SPACE + this.getFontFamily();
},
_addTextLine: function (line, width) {
return this.textArr.push({text: line, width: width});
},
_getTextWidth: function (text) {
return dummyContext.measureText(text).width;
},
_setTextData: function () {
var lines = this.getText().split('\n'),
fontSize = +this.getFontSize(),
textWidth = 0,
lineHeightPx = this.getLineHeight() * fontSize,
width = this.attrs.width,
height = this.attrs.height,
fixedWidth = width !== AUTO,
fixedHeight = height !== AUTO,
padding = this.getPadding(),
maxWidth = width - padding * 2,
maxHeightPx = height - padding * 2,
currentHeightPx = 0,
wrap = this.getWrap(),
shouldWrap = wrap !== NONE,
wrapAtWord = wrap !== CHAR && shouldWrap;
this.textArr = [];
dummyContext.save();
dummyContext.font = this._getContextFont();
for (var i = 0, max = lines.length; i < max; ++i) {
var line = lines[i],
lineWidth = this._getTextWidth(line);
if (fixedWidth && lineWidth > maxWidth) {
/*
* if width is fixed and line does not fit entirely
* break the line into multiple fitting lines
*/
while (line.length > 0) {
/*
* use binary search to find the longest substring that
* that would fit in the specified width
*/
var low = 0, high = line.length,
match = '', matchWidth = 0;
while (low < high) {
var mid = (low + high) >>> 1,
substr = line.slice(0, mid + 1),
substrWidth = this._getTextWidth(substr);
if (substrWidth <= maxWidth) {
low = mid + 1;
match = substr;
matchWidth = substrWidth;
} else {
high = mid;
}
}
/*
* 'low' is now the index of the substring end
* 'match' is the substring
* 'matchWidth' is the substring width in px
*/
if (match) {
// a fitting substring was found
if (wrapAtWord) {
// try to find a space or dash where wrapping could be done
var wrapIndex = Math.max(match.lastIndexOf(SPACE),
match.lastIndexOf(DASH)) + 1;
if (wrapIndex > 0) {
// re-cut the substring found at the space/dash position
low = wrapIndex;
match = match.slice(0, low);
matchWidth = this._getTextWidth(match);
}
}
this._addTextLine(match, matchWidth);
textWidth = Math.max(textWidth, matchWidth);
currentHeightPx += lineHeightPx;
if (!shouldWrap ||
(fixedHeight && currentHeightPx + lineHeightPx > maxHeightPx)) {
/*
* stop wrapping if wrapping is disabled or if adding
* one more line would overflow the fixed height
*/
break;
}
line = line.slice(low);
if (line.length > 0) {
// Check if the remaining text would fit on one line
lineWidth = this._getTextWidth(line);
if (lineWidth <= maxWidth) {
// if it does, add the line and break out of the loop
this._addTextLine(line, lineWidth);
currentHeightPx += lineHeightPx;
textWidth = Math.max(textWidth, lineWidth);
break;
}
}
} else {
// not even one character could fit in the element, abort
break;
}
}
} else {
// element width is automatically adjusted to max line width
this._addTextLine(line, lineWidth);
currentHeightPx += lineHeightPx;
textWidth = Math.max(textWidth, lineWidth);
}
// if element height is fixed, abort if adding one more line would overflow
if (fixedHeight && currentHeightPx + lineHeightPx > maxHeightPx) {
break;
}
}
dummyContext.restore();
this.textHeight = fontSize;
this.textWidth = textWidth;
}
};
Kinetic.Util.extend(Kinetic.Text, Kinetic.Shape);
// add getters setters
Kinetic.Factory.addGetterSetter(Kinetic.Text, 'fontFamily', 'Arial');
/**
* get/set font family
* @name fontFamily
* @method
* @memberof Kinetic.Text.prototype
* @param {String} fontFamily
* @returns {String}
* @example
* // get font family<br>
* var fontFamily = text.fontFamily();<br><br><br>
*
* // set font family<br>
* text.fontFamily('Arial');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Text, 'fontSize', 12);
/**
* get/set font size in pixels
* @name fontSize
* @method
* @memberof Kinetic.Text.prototype
* @param {Number} fontSize
* @returns {Number}
* @example
* // get font size<br>
* var fontSize = text.fontSize();<br><br>
*
* // set font size to 22px<br>
* text.fontSize(22);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Text, 'fontStyle', NORMAL);
/**
* set font style. Can be 'normal', 'italic', or 'bold'. 'normal' is the default.
* @name fontStyle
* @method
* @memberof Kinetic.Text.prototype
* @param {String} fontStyle
* @returns {String}
* @example
* // get font style<br>
* var fontStyle = text.fontStyle();<br><br>
*
* // set font style<br>
* text.fontStyle('bold');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Text, 'fontVariant', NORMAL);
/**
* set font variant. Can be 'normal' or 'small-caps'. 'normal' is the default.
* @name fontVariant
* @method
* @memberof Kinetic.Text.prototype
* @param {String} fontVariant
* @returns {String}
* @example
* // get font variant<br>
* var fontVariant = text.fontVariant();<br><br>
*
* // set font variant<br>
* text.fontVariant('small-caps');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Text, 'padding', 0);
/**
* set padding
* @name padding
* @method
* @memberof Kinetic.Text.prototype
* @param {Number} padding
* @returns {Number}
* @example
* // get padding<br>
* var padding = text.padding();<br><br>
*
* // set padding to 10 pixels<br>
* text.padding(10);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Text, 'align', LEFT);
/**
* get/set horizontal align of text. Can be 'left', 'center', or 'right'
* @name align
* @method
* @memberof Kinetic.Text.prototype
* @param {String} align
* @returns {String}
* @example
* // get text align<br>
* var align = text.align();<br><br>
*
* // center text<br>
* text.align('center');<br><br>
*
* // align text to right<br>
* text.align('right');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Text, 'lineHeight', 1);
/**
* get/set line height. The default is 1.
* @name lineHeight
* @method
* @memberof Kinetic.Text.prototype
* @param {Number} lineHeight
* @returns {Number}
* @example
* // get line height<br>
* var lineHeight = text.lineHeight();<br><br><br>
*
* // set the line height<br>
* text.lineHeight(2);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Text, 'wrap', WORD);
/**
* get/set wrap. Can be word, char, or none. Default is word.
* @name wrap
* @method
* @memberof Kinetic.Text.prototype
* @param {String} wrap
* @returns {String}
* @example
* // get wrap<br>
* var wrap = text.wrap();<br><br>
*
* // set wrap<br>
* text.wrap('word');
*/
Kinetic.Factory.addGetter(Kinetic.Text, 'text', EMPTY_STRING);
Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Text, 'text');
/**
* get/set text
* @name getText
* @method
* @memberof Kinetic.Text.prototype
* @param {String} text
* @returns {String}
* @example
* // get text<br>
* var text = text.text();<br><br>
*
* // set text<br>
* text.text('Hello world!');
*/
Kinetic.Collection.mapMethods(Kinetic.Text);
})();
;(function() {
/**
* Line constructor. Lines are defined by an array of points and
* a tension
* @constructor
* @memberof Kinetic
* @augments Kinetic.Shape
* @param {Object} config
* @param {Array} config.points
* @param {Number} [config.tension] Higher values will result in a more curvy line. A value of 0 will result in no interpolation.
* The default is 0
* @param {Boolean} [config.closed] defines whether or not the line shape is closed, creating a polygon or blob
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var line = new Kinetic.Line({<br>
* x: 100,<br>
* y: 50,<br>
* points: [73, 70, 340, 23, 450, 60, 500, 20],<br>
* stroke: 'red',<br>
* tension: 1<br>
* });
*/
Kinetic.Line = function(config) {
this.___init(config);
};
Kinetic.Line.prototype = {
___init: function(config) {
// call super constructor
Kinetic.Shape.call(this, config);
this.className = 'Line';
this.on('pointsChange.kinetic tensionChange.kinetic closedChange.kinetic', function() {
this._clearCache('tensionPoints');
});
this.sceneFunc(this._sceneFunc);
},
_sceneFunc: function(context) {
var points = this.getPoints(),
length = points.length,
tension = this.getTension(),
closed = this.getClosed(),
tp, len, n;
context.beginPath();
context.moveTo(points[0], points[1]);
// tension
if(tension !== 0 && length > 4) {
tp = this.getTensionPoints();
len = tp.length;
n = closed ? 0 : 4;
if (!closed) {
context.quadraticCurveTo(tp[0], tp[1], tp[2], tp[3]);
}
while(n < len - 2) {
context.bezierCurveTo(tp[n++], tp[n++], tp[n++], tp[n++], tp[n++], tp[n++]);
}
if (!closed) {
context.quadraticCurveTo(tp[len-2], tp[len-1], points[length-2], points[length-1]);
}
}
// no tension
else {
for(n = 2; n < length; n+=2) {
context.lineTo(points[n], points[n+1]);
}
}
// closed e.g. polygons and blobs
if (closed) {
context.closePath();
context.fillStrokeShape(this);
}
// open e.g. lines and splines
else {
context.strokeShape(this);
}
},
getTensionPoints: function() {
return this._getCache('tensionPoints', this._getTensionPoints);
},
_getTensionPoints: function() {
if (this.getClosed()) {
return this._getTensionPointsClosed();
}
else {
return Kinetic.Util._expandPoints(this.getPoints(), this.getTension());
}
},
_getTensionPointsClosed: function() {
var p = this.getPoints(),
len = p.length,
tension = this.getTension(),
util = Kinetic.Util,
firstControlPoints = util._getControlPoints(
p[len-2],
p[len-1],
p[0],
p[1],
p[2],
p[3],
tension
),
lastControlPoints = util._getControlPoints(
p[len-4],
p[len-3],
p[len-2],
p[len-1],
p[0],
p[1],
tension
),
middle = Kinetic.Util._expandPoints(p, tension),
tp = [
firstControlPoints[2],
firstControlPoints[3]
]
.concat(middle)
.concat([
lastControlPoints[0],
lastControlPoints[1],
p[len-2],
p[len-1],
lastControlPoints[2],
lastControlPoints[3],
firstControlPoints[0],
firstControlPoints[1],
p[0],
p[1]
]);
return tp;
}
};
Kinetic.Util.extend(Kinetic.Line, Kinetic.Shape);
// add getters setters
Kinetic.Factory.addGetterSetter(Kinetic.Line, 'closed', false);
/**
* get/set closed flag. The default is false
* @name closed
* @method
* @memberof Kinetic.Line.prototype
* @param {Boolean} closed
* @returns {Boolean}
* @example
* // get closed flag<br>
* var closed = line.closed();<br><br>
*
* // close the shape<br>
* line.closed(true);<br><br>
*
* // open the shape<br>
* line.closed(false);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Line, 'tension', 0);
/**
* get/set tension
* @name tension
* @method
* @memberof Kinetic.Line.prototype
* @param {Number} Higher values will result in a more curvy line. A value of 0 will result in no interpolation.
* The default is 0
* @returns {Number}
* @example
* // get tension<br>
* var tension = line.tension();<br><br>
*
* // set tension<br>
* line.tension(3);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Line, 'points');
/**
* get/set points array
* @name points
* @method
* @memberof Kinetic.Line.prototype
* @param {Array} points
* @returns {Array}
* @example
* // get points<br>
* var points = line.points();<br><br>
*
* // set points<br>
* line.points([10, 20, 30, 40, 50, 60]);<br><br>
*
* // push a new point<br>
* line.points(line.points().concat([70, 80]));
*/
Kinetic.Collection.mapMethods(Kinetic.Line);
})();;(function() {
/**
* Sprite constructor
* @constructor
* @memberof Kinetic
* @augments Kinetic.Shape
* @param {Object} config
* @param {String} config.animation animation key
* @param {Object} config.animations animation map
* @param {Integer} [config.frameIndex] animation frame index
* @param {Image} config.image image object
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var imageObj = new Image();<br>
* imageObj.onload = function() {<br>
* var sprite = new Kinetic.Sprite({<br>
* x: 200,<br>
* y: 100,<br>
* image: imageObj,<br>
* animation: 'standing',<br>
* animations: {<br>
* standing: [<br>
* // x, y, width, height (6 frames)<br>
* 0, 0, 49, 109,<br>
* 52, 0, 49, 109,<br>
* 105, 0, 49, 109,<br>
* 158, 0, 49, 109,<br>
* 210, 0, 49, 109,<br>
* 262, 0, 49, 109<br>
* ],<br>
* kicking: [<br>
* // x, y, width, height (6 frames)<br>
* 0, 109, 45, 98,<br>
* 45, 109, 45, 98,<br>
* 95, 109, 63, 98,<br>
* 156, 109, 70, 98,<br>
* 229, 109, 60, 98,<br>
* 287, 109, 41, 98<br>
* ]<br>
* },<br>
* frameRate: 7,<br>
* frameIndex: 0<br>
* });<br>
* };<br>
* imageObj.src = '/path/to/image.jpg'
*/
Kinetic.Sprite = function(config) {
this.___init(config);
};
Kinetic.Sprite.prototype = {
___init: function(config) {
// call super constructor
Kinetic.Shape.call(this, config);
this.className = 'Sprite';
this.anim = new Kinetic.Animation();
this.on('animationChange.kinetic', function() {
// reset index when animation changes
this.frameIndex(0);
});
// smooth change for frameRate
this.on('frameRateChange.kinetic', function() {
if (!this.anim.isRunning()) {
return;
}
clearInterval(this.interval);
this._setInterval();
});
this.sceneFunc(this._sceneFunc);
this.hitFunc(this._hitFunc);
},
_sceneFunc: function(context) {
var anim = this.getAnimation(),
index = this.frameIndex(),
ix4 = index * 4,
set = this.getAnimations()[anim],
x = set[ix4 + 0],
y = set[ix4 + 1],
width = set[ix4 + 2],
height = set[ix4 + 3],
image = this.getImage();
if(image) {
context.drawImage(image, x, y, width, height, 0, 0, width, height);
}
},
_hitFunc: function(context) {
var anim = this.getAnimation(),
index = this.frameIndex(),
ix4 = index * 4,
set = this.getAnimations()[anim],
width = set[ix4 + 2],
height = set[ix4 + 3];
context.beginPath();
context.rect(0, 0, width, height);
context.closePath();
context.fillShape(this);
},
_useBufferCanvas: function() {
return (this.hasShadow() || this.getAbsoluteOpacity() !== 1) && this.hasStroke();
},
_setInterval: function() {
var that = this;
this.interval = setInterval(function() {
that._updateIndex();
}, 1000 / this.getFrameRate());
},
/**
* start sprite animation
* @method
* @memberof Kinetic.Sprite.prototype
*/
start: function() {
var layer = this.getLayer();
/*
* animation object has no executable function because
* the updates are done with a fixed FPS with the setInterval
* below. The anim object only needs the layer reference for
* redraw
*/
this.anim.setLayers(layer);
this._setInterval();
this.anim.start();
},
/**
* stop sprite animation
* @method
* @memberof Kinetic.Sprite.prototype
*/
stop: function() {
this.anim.stop();
clearInterval(this.interval);
},
/**
* determine if animation of sprite is running or not. returns true or false
* @method
* @memberof Kinetic.Animation.prototype
* @returns {Boolean}
*/
isRunning: function() {
return this.anim.isRunning();
},
_updateIndex: function() {
var index = this.frameIndex(),
animation = this.getAnimation(),
animations = this.getAnimations(),
anim = animations[animation],
len = anim.length / 4;
if(index < len - 1) {
this.frameIndex(index + 1);
}
else {
this.frameIndex(0);
}
}
};
Kinetic.Util.extend(Kinetic.Sprite, Kinetic.Shape);
// add getters setters
Kinetic.Factory.addGetterSetter(Kinetic.Sprite, 'animation');
/**
* get/set animation key
* @name animation
* @method
* @memberof Kinetic.Sprite.prototype
* @param {String} anim animation key
* @returns {String}
* @example
* // get animation key<br>
* var animation = sprite.animation();<br><br>
*
* // set animation key<br>
* sprite.animation('kicking');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Sprite, 'animations');
/**
* get/set animations map
* @name animations
* @method
* @memberof Kinetic.Sprite.prototype
* @param {Object} animations
* @returns {Object}
* @example
* // get animations map<br>
* var animations = sprite.animations();<br><br>
*
* // set animations map<br>
* sprite.animations({<br>
* standing: [<br>
* // x, y, width, height (6 frames)<br>
* 0, 0, 49, 109,<br>
* 52, 0, 49, 109,<br>
* 105, 0, 49, 109,<br>
* 158, 0, 49, 109,<br>
* 210, 0, 49, 109,<br>
* 262, 0, 49, 109<br>
* ],<br>
* kicking: [<br>
* // x, y, width, height (6 frames)<br>
* 0, 109, 45, 98,<br>
* 45, 109, 45, 98,<br>
* 95, 109, 63, 98,<br>
* 156, 109, 70, 98,<br>
* 229, 109, 60, 98,<br>
* 287, 109, 41, 98<br>
* ]<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Sprite, 'image');
/**
* get/set image
* @name image
* @method
* @memberof Kinetic.Sprite.prototype
* @param {Image} image
* @returns {Image}
* @example
* // get image
* var image = sprite.image();<br><br>
*
* // set image<br>
* sprite.image(imageObj);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Sprite, 'frameIndex', 0);
/**
* set/set animation frame index
* @name frameIndex
* @method
* @memberof Kinetic.Sprite.prototype
* @param {Integer} frameIndex
* @returns {Integer}
* @example
* // get animation frame index<br>
* var frameIndex = sprite.frameIndex();<br><br>
*
* // set animation frame index<br>
* sprite.frameIndex(3);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Sprite, 'frameRate', 17);
/**
* get/set frame rate in frames per second. Increase this number to make the sprite
* animation run faster, and decrease the number to make the sprite animation run slower
* The default is 17 frames per second
* @name frameRate
* @method
* @memberof Kinetic.Sprite.prototype
* @param {Integer} frameRate
* @returns {Integer}
* @example
* // get frame rate<br>
* var frameRate = sprite.frameRate();<br><br>
*
* // set frame rate to 2 frames per second<br>
* sprite.frameRate(2);
*/
Kinetic.Factory.backCompat(Kinetic.Sprite, {
index: 'frameIndex',
getIndex: 'getFrameIndex',
setIndex: 'setFrameIndex'
});
Kinetic.Collection.mapMethods(Kinetic.Sprite);
})();
;(function () {
/**
* Path constructor.
* @author Jason Follas
* @constructor
* @memberof Kinetic
* @augments Kinetic.Shape
* @param {Object} config
* @param {String} config.data SVG data string
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var path = new Kinetic.Path({<br>
* x: 240,<br>
* y: 40,<br>
* data: 'M12.582,9.551C3.251,16.237,0.921,29.021,7.08,38.564l-2.36,1.689l4.893,2.262l4.893,2.262l-0.568-5.36l-0.567-5.359l-2.365,1.694c-4.657-7.375-2.83-17.185,4.352-22.33c7.451-5.338,17.817-3.625,23.156,3.824c5.337,7.449,3.625,17.813-3.821,23.152l2.857,3.988c9.617-6.893,11.827-20.277,4.935-29.896C35.591,4.87,22.204,2.658,12.582,9.551z',<br>
* fill: 'green',<br>
* scale: 2<br>
* });
*/
Kinetic.Path = function (config) {
this.___init(config);
};
Kinetic.Path.prototype = {
___init: function (config) {
this.dataArray = [];
var that = this;
// call super constructor
Kinetic.Shape.call(this, config);
this.className = 'Path';
this.dataArray = Kinetic.Path.parsePathData(this.getData());
this.on('dataChange.kinetic', function () {
that.dataArray = Kinetic.Path.parsePathData(this.getData());
});
this.sceneFunc(this._sceneFunc);
},
_sceneFunc: function(context) {
var ca = this.dataArray,
closedPath = false;
// context position
context.beginPath();
for (var n = 0; n < ca.length; n++) {
var c = ca[n].command;
var p = ca[n].points;
switch (c) {
case 'L':
context.lineTo(p[0], p[1]);
break;
case 'M':
context.moveTo(p[0], p[1]);
break;
case 'C':
context.bezierCurveTo(p[0], p[1], p[2], p[3], p[4], p[5]);
break;
case 'Q':
context.quadraticCurveTo(p[0], p[1], p[2], p[3]);
break;
case 'A':
var cx = p[0], cy = p[1], rx = p[2], ry = p[3], theta = p[4], dTheta = p[5], psi = p[6], fs = p[7];
var r = (rx > ry) ? rx : ry;
var scaleX = (rx > ry) ? 1 : rx / ry;
var scaleY = (rx > ry) ? ry / rx : 1;
context.translate(cx, cy);
context.rotate(psi);
context.scale(scaleX, scaleY);
context.arc(0, 0, r, theta, theta + dTheta, 1 - fs);
context.scale(1 / scaleX, 1 / scaleY);
context.rotate(-psi);
context.translate(-cx, -cy);
break;
case 'z':
context.closePath();
closedPath = true;
break;
}
}
if (closedPath) {
context.fillStrokeShape(this);
}
else {
context.strokeShape(this);
}
}
};
Kinetic.Util.extend(Kinetic.Path, Kinetic.Shape);
Kinetic.Path.getLineLength = function(x1, y1, x2, y2) {
return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
};
Kinetic.Path.getPointOnLine = function(dist, P1x, P1y, P2x, P2y, fromX, fromY) {
if(fromX === undefined) {
fromX = P1x;
}
if(fromY === undefined) {
fromY = P1y;
}
var m = (P2y - P1y) / ((P2x - P1x) + 0.00000001);
var run = Math.sqrt(dist * dist / (1 + m * m));
if(P2x < P1x) {
run *= -1;
}
var rise = m * run;
var pt;
if (P2x === P1x) { // vertical line
pt = {
x: fromX,
y: fromY + rise
};
} else if((fromY - P1y) / ((fromX - P1x) + 0.00000001) === m) {
pt = {
x: fromX + run,
y: fromY + rise
};
}
else {
var ix, iy;
var len = this.getLineLength(P1x, P1y, P2x, P2y);
if(len < 0.00000001) {
return undefined;
}
var u = (((fromX - P1x) * (P2x - P1x)) + ((fromY - P1y) * (P2y - P1y)));
u = u / (len * len);
ix = P1x + u * (P2x - P1x);
iy = P1y + u * (P2y - P1y);
var pRise = this.getLineLength(fromX, fromY, ix, iy);
var pRun = Math.sqrt(dist * dist - pRise * pRise);
run = Math.sqrt(pRun * pRun / (1 + m * m));
if(P2x < P1x) {
run *= -1;
}
rise = m * run;
pt = {
x: ix + run,
y: iy + rise
};
}
return pt;
};
Kinetic.Path.getPointOnCubicBezier = function(pct, P1x, P1y, P2x, P2y, P3x, P3y, P4x, P4y) {
function CB1(t) {
return t * t * t;
}
function CB2(t) {
return 3 * t * t * (1 - t);
}
function CB3(t) {
return 3 * t * (1 - t) * (1 - t);
}
function CB4(t) {
return (1 - t) * (1 - t) * (1 - t);
}
var x = P4x * CB1(pct) + P3x * CB2(pct) + P2x * CB3(pct) + P1x * CB4(pct);
var y = P4y * CB1(pct) + P3y * CB2(pct) + P2y * CB3(pct) + P1y * CB4(pct);
return {
x: x,
y: y
};
};
Kinetic.Path.getPointOnQuadraticBezier = function(pct, P1x, P1y, P2x, P2y, P3x, P3y) {
function QB1(t) {
return t * t;
}
function QB2(t) {
return 2 * t * (1 - t);
}
function QB3(t) {
return (1 - t) * (1 - t);
}
var x = P3x * QB1(pct) + P2x * QB2(pct) + P1x * QB3(pct);
var y = P3y * QB1(pct) + P2y * QB2(pct) + P1y * QB3(pct);
return {
x: x,
y: y
};
};
Kinetic.Path.getPointOnEllipticalArc = function(cx, cy, rx, ry, theta, psi) {
var cosPsi = Math.cos(psi), sinPsi = Math.sin(psi);
var pt = {
x: rx * Math.cos(theta),
y: ry * Math.sin(theta)
};
return {
x: cx + (pt.x * cosPsi - pt.y * sinPsi),
y: cy + (pt.x * sinPsi + pt.y * cosPsi)
};
};
/*
* get parsed data array from the data
* string. V, v, H, h, and l data are converted to
* L data for the purpose of high performance Path
* rendering
*/
Kinetic.Path.parsePathData = function(data) {
// Path Data Segment must begin with a moveTo
//m (x y)+ Relative moveTo (subsequent points are treated as lineTo)
//M (x y)+ Absolute moveTo (subsequent points are treated as lineTo)
//l (x y)+ Relative lineTo
//L (x y)+ Absolute LineTo
//h (x)+ Relative horizontal lineTo
//H (x)+ Absolute horizontal lineTo
//v (y)+ Relative vertical lineTo
//V (y)+ Absolute vertical lineTo
//z (closepath)
//Z (closepath)
//c (x1 y1 x2 y2 x y)+ Relative Bezier curve
//C (x1 y1 x2 y2 x y)+ Absolute Bezier curve
//q (x1 y1 x y)+ Relative Quadratic Bezier
//Q (x1 y1 x y)+ Absolute Quadratic Bezier
//t (x y)+ Shorthand/Smooth Relative Quadratic Bezier
//T (x y)+ Shorthand/Smooth Absolute Quadratic Bezier
//s (x2 y2 x y)+ Shorthand/Smooth Relative Bezier curve
//S (x2 y2 x y)+ Shorthand/Smooth Absolute Bezier curve
//a (rx ry x-axis-rotation large-arc-flag sweep-flag x y)+ Relative Elliptical Arc
//A (rx ry x-axis-rotation large-arc-flag sweep-flag x y)+ Absolute Elliptical Arc
// return early if data is not defined
if(!data) {
return [];
}
// command string
var cs = data;
// command chars
var cc = ['m', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z', 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'];
// convert white spaces to commas
cs = cs.replace(new RegExp(' ', 'g'), ',');
// create pipes so that we can split the data
for(var n = 0; n < cc.length; n++) {
cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
}
// create array
var arr = cs.split('|');
var ca = [];
// init context point
var cpx = 0;
var cpy = 0;
for( n = 1; n < arr.length; n++) {
var str = arr[n];
var c = str.charAt(0);
str = str.slice(1);
// remove ,- for consistency
str = str.replace(new RegExp(',-', 'g'), '-');
// add commas so that it's easy to split
str = str.replace(new RegExp('-', 'g'), ',-');
str = str.replace(new RegExp('e,-', 'g'), 'e-');
var p = str.split(',');
if(p.length > 0 && p[0] === '') {
p.shift();
}
// convert strings to floats
for(var i = 0; i < p.length; i++) {
p[i] = parseFloat(p[i]);
}
while(p.length > 0) {
if(isNaN(p[0])) {// case for a trailing comma before next command
break;
}
var cmd = null;
var points = [];
var startX = cpx, startY = cpy;
// Move var from within the switch to up here (jshint)
var prevCmd, ctlPtx, ctlPty; // Ss, Tt
var rx, ry, psi, fa, fs, x1, y1; // Aa
// convert l, H, h, V, and v to L
switch (c) {
// Note: Keep the lineTo's above the moveTo's in this switch
case 'l':
cpx += p.shift();
cpy += p.shift();
cmd = 'L';
points.push(cpx, cpy);
break;
case 'L':
cpx = p.shift();
cpy = p.shift();
points.push(cpx, cpy);
break;
// Note: lineTo handlers need to be above this point
case 'm':
var dx = p.shift();
var dy = p.shift();
cpx += dx;
cpy += dy;
cmd = 'M';
// After closing the path move the current position
// to the the first point of the path (if any).
if(ca.length>2 && ca[ca.length-1].command==='z'){
for(var idx=ca.length-2;idx>=0;idx--){
if(ca[idx].command==='M'){
cpx=ca[idx].points[0]+dx;
cpy=ca[idx].points[1]+dy;
break;
}
}
}
points.push(cpx, cpy);
c = 'l';
// subsequent points are treated as relative lineTo
break;
case 'M':
cpx = p.shift();
cpy = p.shift();
cmd = 'M';
points.push(cpx, cpy);
c = 'L';
// subsequent points are treated as absolute lineTo
break;
case 'h':
cpx += p.shift();
cmd = 'L';
points.push(cpx, cpy);
break;
case 'H':
cpx = p.shift();
cmd = 'L';
points.push(cpx, cpy);
break;
case 'v':
cpy += p.shift();
cmd = 'L';
points.push(cpx, cpy);
break;
case 'V':
cpy = p.shift();
cmd = 'L';
points.push(cpx, cpy);
break;
case 'C':
points.push(p.shift(), p.shift(), p.shift(), p.shift());
cpx = p.shift();
cpy = p.shift();
points.push(cpx, cpy);
break;
case 'c':
points.push(cpx + p.shift(), cpy + p.shift(), cpx + p.shift(), cpy + p.shift());
cpx += p.shift();
cpy += p.shift();
cmd = 'C';
points.push(cpx, cpy);
break;
case 'S':
ctlPtx = cpx;
ctlPty = cpy;
prevCmd = ca[ca.length - 1];
if(prevCmd.command === 'C') {
ctlPtx = cpx + (cpx - prevCmd.points[2]);
ctlPty = cpy + (cpy - prevCmd.points[3]);
}
points.push(ctlPtx, ctlPty, p.shift(), p.shift());
cpx = p.shift();
cpy = p.shift();
cmd = 'C';
points.push(cpx, cpy);
break;
case 's':
ctlPtx = cpx;
ctlPty = cpy;
prevCmd = ca[ca.length - 1];
if(prevCmd.command === 'C') {
ctlPtx = cpx + (cpx - prevCmd.points[2]);
ctlPty = cpy + (cpy - prevCmd.points[3]);
}
points.push(ctlPtx, ctlPty, cpx + p.shift(), cpy + p.shift());
cpx += p.shift();
cpy += p.shift();
cmd = 'C';
points.push(cpx, cpy);
break;
case 'Q':
points.push(p.shift(), p.shift());
cpx = p.shift();
cpy = p.shift();
points.push(cpx, cpy);
break;
case 'q':
points.push(cpx + p.shift(), cpy + p.shift());
cpx += p.shift();
cpy += p.shift();
cmd = 'Q';
points.push(cpx, cpy);
break;
case 'T':
ctlPtx = cpx;
ctlPty = cpy;
prevCmd = ca[ca.length - 1];
if(prevCmd.command === 'Q') {
ctlPtx = cpx + (cpx - prevCmd.points[0]);
ctlPty = cpy + (cpy - prevCmd.points[1]);
}
cpx = p.shift();
cpy = p.shift();
cmd = 'Q';
points.push(ctlPtx, ctlPty, cpx, cpy);
break;
case 't':
ctlPtx = cpx;
ctlPty = cpy;
prevCmd = ca[ca.length - 1];
if(prevCmd.command === 'Q') {
ctlPtx = cpx + (cpx - prevCmd.points[0]);
ctlPty = cpy + (cpy - prevCmd.points[1]);
}
cpx += p.shift();
cpy += p.shift();
cmd = 'Q';
points.push(ctlPtx, ctlPty, cpx, cpy);
break;
case 'A':
rx = p.shift();
ry = p.shift();
psi = p.shift();
fa = p.shift();
fs = p.shift();
x1 = cpx;
y1 = cpy;
cpx = p.shift();
cpy = p.shift();
cmd = 'A';
points = this.convertEndpointToCenterParameterization(x1, y1, cpx, cpy, fa, fs, rx, ry, psi);
break;
case 'a':
rx = p.shift();
ry = p.shift();
psi = p.shift();
fa = p.shift();
fs = p.shift();
x1 = cpx;
y1 = cpy; cpx += p.shift();
cpy += p.shift();
cmd = 'A';
points = this.convertEndpointToCenterParameterization(x1, y1, cpx, cpy, fa, fs, rx, ry, psi);
break;
}
ca.push({
command: cmd || c,
points: points,
start: {
x: startX,
y: startY
},
pathLength: this.calcLength(startX, startY, cmd || c, points)
});
}
if(c === 'z' || c === 'Z') {
ca.push({
command: 'z',
points: [],
start: undefined,
pathLength: 0
});
}
}
return ca;
};
Kinetic.Path.calcLength = function(x, y, cmd, points) {
var len, p1, p2, t;
var path = Kinetic.Path;
switch (cmd) {
case 'L':
return path.getLineLength(x, y, points[0], points[1]);
case 'C':
// Approximates by breaking curve into 100 line segments
len = 0.0;
p1 = path.getPointOnCubicBezier(0, x, y, points[0], points[1], points[2], points[3], points[4], points[5]);
for( t = 0.01; t <= 1; t += 0.01) {
p2 = path.getPointOnCubicBezier(t, x, y, points[0], points[1], points[2], points[3], points[4], points[5]);
len += path.getLineLength(p1.x, p1.y, p2.x, p2.y);
p1 = p2;
}
return len;
case 'Q':
// Approximates by breaking curve into 100 line segments
len = 0.0;
p1 = path.getPointOnQuadraticBezier(0, x, y, points[0], points[1], points[2], points[3]);
for( t = 0.01; t <= 1; t += 0.01) {
p2 = path.getPointOnQuadraticBezier(t, x, y, points[0], points[1], points[2], points[3]);
len += path.getLineLength(p1.x, p1.y, p2.x, p2.y);
p1 = p2;
}
return len;
case 'A':
// Approximates by breaking curve into line segments
len = 0.0;
var start = points[4];
// 4 = theta
var dTheta = points[5];
// 5 = dTheta
var end = points[4] + dTheta;
var inc = Math.PI / 180.0;
// 1 degree resolution
if(Math.abs(start - end) < inc) {
inc = Math.abs(start - end);
}
// Note: for purpose of calculating arc length, not going to worry about rotating X-axis by angle psi
p1 = path.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], start, 0);
if(dTheta < 0) {// clockwise
for( t = start - inc; t > end; t -= inc) {
p2 = path.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], t, 0);
len += path.getLineLength(p1.x, p1.y, p2.x, p2.y);
p1 = p2;
}
}
else {// counter-clockwise
for( t = start + inc; t < end; t += inc) {
p2 = path.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], t, 0);
len += path.getLineLength(p1.x, p1.y, p2.x, p2.y);
p1 = p2;
}
}
p2 = path.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], end, 0);
len += path.getLineLength(p1.x, p1.y, p2.x, p2.y);
return len;
}
return 0;
};
Kinetic.Path.convertEndpointToCenterParameterization = function(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg) {
// Derived from: http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes
var psi = psiDeg * (Math.PI / 180.0);
var xp = Math.cos(psi) * (x1 - x2) / 2.0 + Math.sin(psi) * (y1 - y2) / 2.0;
var yp = -1 * Math.sin(psi) * (x1 - x2) / 2.0 + Math.cos(psi) * (y1 - y2) / 2.0;
var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
if(lambda > 1) {
rx *= Math.sqrt(lambda);
ry *= Math.sqrt(lambda);
}
var f = Math.sqrt((((rx * rx) * (ry * ry)) - ((rx * rx) * (yp * yp)) - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp) + (ry * ry) * (xp * xp)));
if(fa === fs) {
f *= -1;
}
if(isNaN(f)) {
f = 0;
}
var cxp = f * rx * yp / ry;
var cyp = f * -ry * xp / rx;
var cx = (x1 + x2) / 2.0 + Math.cos(psi) * cxp - Math.sin(psi) * cyp;
var cy = (y1 + y2) / 2.0 + Math.sin(psi) * cxp + Math.cos(psi) * cyp;
var vMag = function(v) {
return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
};
var vRatio = function(u, v) {
return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
};
var vAngle = function(u, v) {
return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(vRatio(u, v));
};
var theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]);
var u = [(xp - cxp) / rx, (yp - cyp) / ry];
var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry];
var dTheta = vAngle(u, v);
if(vRatio(u, v) <= -1) {
dTheta = Math.PI;
}
if(vRatio(u, v) >= 1) {
dTheta = 0;
}
if(fs === 0 && dTheta > 0) {
dTheta = dTheta - 2 * Math.PI;
}
if(fs === 1 && dTheta < 0) {
dTheta = dTheta + 2 * Math.PI;
}
return [cx, cy, rx, ry, theta, dTheta, psi, fs];
};
// add getters setters
Kinetic.Factory.addGetterSetter(Kinetic.Path, 'data');
/**
* set SVG path data string. This method
* also automatically parses the data string
* into a data array. Currently supported SVG data:
* M, m, L, l, H, h, V, v, Q, q, T, t, C, c, S, s, A, a, Z, z
* @name setData
* @method
* @memberof Kinetic.Path.prototype
* @param {String} SVG path command string
*/
/**
* get SVG path data string
* @name getData
* @method
* @memberof Kinetic.Path.prototype
*/
Kinetic.Collection.mapMethods(Kinetic.Path);
})();
;(function() {
var EMPTY_STRING = '',
//CALIBRI = 'Calibri',
NORMAL = 'normal';
/**
* Path constructor.
* @author Jason Follas
* @constructor
* @memberof Kinetic
* @augments Kinetic.Shape
* @param {Object} config
* @param {String} [config.fontFamily] default is Calibri
* @param {Number} [config.fontSize] default is 12
* @param {String} [config.fontStyle] can be normal, bold, or italic. Default is normal
* @param {String} [config.fontVariant] can be normal or small-caps. Default is normal
* @param {String} config.text
* @param {String} config.data SVG data string
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var textpath = new Kinetic.TextPath({<br>
* x: 100,<br>
* y: 50,<br>
* fill: '#333',<br>
* fontSize: '24',<br>
* fontFamily: 'Arial',<br>
* text: 'All the world\'s a stage, and all the men and women merely players.',<br>
* data: 'M10,10 C0,0 10,150 100,100 S300,150 400,50'<br>
* });
*/
Kinetic.TextPath = function(config) {
this.___init(config);
};
function _fillFunc(context) {
context.fillText(this.partialText, 0, 0);
}
function _strokeFunc(context) {
context.strokeText(this.partialText, 0, 0);
}
Kinetic.TextPath.prototype = {
___init: function(config) {
var that = this;
this.dummyCanvas = Kinetic.Util.createCanvasElement();
this.dataArray = [];
// call super constructor
Kinetic.Shape.call(this, config);
// overrides
// TODO: shouldn't this be on the prototype?
this._fillFunc = _fillFunc;
this._strokeFunc = _strokeFunc;
this._fillFuncHit = _fillFunc;
this._strokeFuncHit = _strokeFunc;
this.className = 'TextPath';
this.dataArray = Kinetic.Path.parsePathData(this.attrs.data);
this.on('dataChange.kinetic', function() {
that.dataArray = Kinetic.Path.parsePathData(this.attrs.data);
});
// update text data for certain attr changes
this.on('textChange.kinetic textStroke.kinetic textStrokeWidth.kinetic', that._setTextData);
that._setTextData();
this.sceneFunc(this._sceneFunc);
},
_sceneFunc: function(context) {
context.setAttr('font', this._getContextFont());
context.setAttr('textBaseline', 'middle');
context.setAttr('textAlign', 'left');
context.save();
var glyphInfo = this.glyphInfo;
for(var i = 0; i < glyphInfo.length; i++) {
context.save();
var p0 = glyphInfo[i].p0;
context.translate(p0.x, p0.y);
context.rotate(glyphInfo[i].rotation);
this.partialText = glyphInfo[i].text;
context.fillStrokeShape(this);
context.restore();
//// To assist with debugging visually, uncomment following
// context.beginPath();
// if (i % 2)
// context.strokeStyle = 'cyan';
// else
// context.strokeStyle = 'green';
// var p1 = glyphInfo[i].p1;
// context.moveTo(p0.x, p0.y);
// context.lineTo(p1.x, p1.y);
// context.stroke();
}
context.restore();
},
/**
* get text width in pixels
* @method
* @memberof Kinetic.TextPath.prototype
*/
getTextWidth: function() {
return this.textWidth;
},
/**
* get text height in pixels
* @method
* @memberof Kinetic.TextPath.prototype
*/
getTextHeight: function() {
return this.textHeight;
},
/**
* set text
* @method
* @memberof Kinetic.TextPath.prototype
* @param {String} text
*/
setText: function(text) {
Kinetic.Text.prototype.setText.call(this, text);
},
_getTextSize: function(text) {
var dummyCanvas = this.dummyCanvas;
var _context = dummyCanvas.getContext('2d');
_context.save();
_context.font = this._getContextFont();
var metrics = _context.measureText(text);
_context.restore();
return {
width: metrics.width,
height: parseInt(this.attrs.fontSize, 10)
};
},
_setTextData: function() {
var that = this;
var size = this._getTextSize(this.attrs.text);
this.textWidth = size.width;
this.textHeight = size.height;
this.glyphInfo = [];
var charArr = this.attrs.text.split('');
var p0, p1, pathCmd;
var pIndex = -1;
var currentT = 0;
var getNextPathSegment = function() {
currentT = 0;
var pathData = that.dataArray;
for(var i = pIndex + 1; i < pathData.length; i++) {
if(pathData[i].pathLength > 0) {
pIndex = i;
return pathData[i];
}
else if(pathData[i].command == 'M') {
p0 = {
x: pathData[i].points[0],
y: pathData[i].points[1]
};
}
}
return {};
};
var findSegmentToFitCharacter = function(c) {
var glyphWidth = that._getTextSize(c).width;
var currLen = 0;
var attempts = 0;
p1 = undefined;
while(Math.abs(glyphWidth - currLen) / glyphWidth > 0.01 && attempts < 25) {
attempts++;
var cumulativePathLength = currLen;
while(pathCmd === undefined) {
pathCmd = getNextPathSegment();
if(pathCmd && cumulativePathLength + pathCmd.pathLength < glyphWidth) {
cumulativePathLength += pathCmd.pathLength;
pathCmd = undefined;
}
}
if(pathCmd === {} || p0 === undefined) {
return undefined;
}
var needNewSegment = false;
switch (pathCmd.command) {
case 'L':
if(Kinetic.Path.getLineLength(p0.x, p0.y, pathCmd.points[0], pathCmd.points[1]) > glyphWidth) {
p1 = Kinetic.Path.getPointOnLine(glyphWidth, p0.x, p0.y, pathCmd.points[0], pathCmd.points[1], p0.x, p0.y);
}
else {
pathCmd = undefined;
}
break;
case 'A':
var start = pathCmd.points[4];
// 4 = theta
var dTheta = pathCmd.points[5];
// 5 = dTheta
var end = pathCmd.points[4] + dTheta;
if(currentT === 0){
currentT = start + 0.00000001;
}
// Just in case start is 0
else if(glyphWidth > currLen) {
currentT += (Math.PI / 180.0) * dTheta / Math.abs(dTheta);
}
else {
currentT -= Math.PI / 360.0 * dTheta / Math.abs(dTheta);
}
// Credit for bug fix: @therth https://github.com/ericdrowell/KineticJS/issues/249
// Old code failed to render text along arc of this path: "M 50 50 a 150 50 0 0 1 250 50 l 50 0"
if(dTheta < 0 && currentT < end || dTheta >= 0 && currentT > end) {
currentT = end;
needNewSegment = true;
}
p1 = Kinetic.Path.getPointOnEllipticalArc(pathCmd.points[0], pathCmd.points[1], pathCmd.points[2], pathCmd.points[3], currentT, pathCmd.points[6]);
break;
case 'C':
if(currentT === 0) {
if(glyphWidth > pathCmd.pathLength) {
currentT = 0.00000001;
}
else {
currentT = glyphWidth / pathCmd.pathLength;
}
}
else if(glyphWidth > currLen) {
currentT += (glyphWidth - currLen) / pathCmd.pathLength;
}
else {
currentT -= (currLen - glyphWidth) / pathCmd.pathLength;
}
if(currentT > 1.0) {
currentT = 1.0;
needNewSegment = true;
}
p1 = Kinetic.Path.getPointOnCubicBezier(currentT, pathCmd.start.x, pathCmd.start.y, pathCmd.points[0], pathCmd.points[1], pathCmd.points[2], pathCmd.points[3], pathCmd.points[4], pathCmd.points[5]);
break;
case 'Q':
if(currentT === 0) {
currentT = glyphWidth / pathCmd.pathLength;
}
else if(glyphWidth > currLen) {
currentT += (glyphWidth - currLen) / pathCmd.pathLength;
}
else {
currentT -= (currLen - glyphWidth) / pathCmd.pathLength;
}
if(currentT > 1.0) {
currentT = 1.0;
needNewSegment = true;
}
p1 = Kinetic.Path.getPointOnQuadraticBezier(currentT, pathCmd.start.x, pathCmd.start.y, pathCmd.points[0], pathCmd.points[1], pathCmd.points[2], pathCmd.points[3]);
break;
}
if(p1 !== undefined) {
currLen = Kinetic.Path.getLineLength(p0.x, p0.y, p1.x, p1.y);
}
if(needNewSegment) {
needNewSegment = false;
pathCmd = undefined;
}
}
};
for(var i = 0; i < charArr.length; i++) {
// Find p1 such that line segment between p0 and p1 is approx. width of glyph
findSegmentToFitCharacter(charArr[i]);
if(p0 === undefined || p1 === undefined) {
break;
}
var width = Kinetic.Path.getLineLength(p0.x, p0.y, p1.x, p1.y);
// Note: Since glyphs are rendered one at a time, any kerning pair data built into the font will not be used.
// Can foresee having a rough pair table built in that the developer can override as needed.
var kern = 0;
// placeholder for future implementation
var midpoint = Kinetic.Path.getPointOnLine(kern + width / 2.0, p0.x, p0.y, p1.x, p1.y);
var rotation = Math.atan2((p1.y - p0.y), (p1.x - p0.x));
this.glyphInfo.push({
transposeX: midpoint.x,
transposeY: midpoint.y,
text: charArr[i],
rotation: rotation,
p0: p0,
p1: p1
});
p0 = p1;
}
}
};
// map TextPath methods to Text
Kinetic.TextPath.prototype._getContextFont = Kinetic.Text.prototype._getContextFont;
Kinetic.Util.extend(Kinetic.TextPath, Kinetic.Shape);
// add setters and getters
Kinetic.Factory.addGetterSetter(Kinetic.TextPath, 'fontFamily', 'Arial');
/**
* set font family
* @name setFontFamily
* @method
* @memberof Kinetic.TextPath.prototype
* @param {String} fontFamily
*/
/**
* get font family
* @name getFontFamily
* @method
* @memberof Kinetic.TextPath.prototype
*/
Kinetic.Factory.addGetterSetter(Kinetic.TextPath, 'fontSize', 12);
/**
* set font size
* @name setFontSize
* @method
* @memberof Kinetic.TextPath.prototype
* @param {int} fontSize
*/
/**
* get font size
* @name getFontSize
* @method
* @memberof Kinetic.TextPath.prototype
*/
Kinetic.Factory.addGetterSetter(Kinetic.TextPath, 'fontStyle', NORMAL);
/**
* set font style. Can be 'normal', 'italic', or 'bold'. 'normal' is the default.
* @name setFontStyle
* @method
* @memberof Kinetic.TextPath.prototype
* @param {String} fontStyle
*/
/**
* get font style
* @name getFontStyle
* @method
* @memberof Kinetic.TextPath.prototype
*/
Kinetic.Factory.addGetterSetter(Kinetic.TextPath, 'fontVariant', NORMAL);
/**
* set font variant. Can be 'normal' or 'small-caps'. 'normal' is the default.
* @name setFontVariant
* @method
* @memberof Kinetic.TextPath.prototype
* @param {String} fontVariant
*/
/**
* @get font variant
* @name getFontVariant
* @method
* @memberof Kinetic.TextPath.prototype
*/
Kinetic.Factory.addGetter(Kinetic.TextPath, 'text', EMPTY_STRING);
/**
* get text
* @name getText
* @method
* @memberof Kinetic.TextPath.prototype
*/
Kinetic.Collection.mapMethods(Kinetic.TextPath);
})();
;(function() {
/**
* RegularPolygon constructor. Examples include triangles, squares, pentagons, hexagons, etc.
* @constructor
* @memberof Kinetic
* @augments Kinetic.Shape
* @param {Object} config
* @param {Number} config.sides
* @param {Number} config.radius
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var hexagon = new Kinetic.RegularPolygon({<br>
* x: 100,<br>
* y: 200,<br>
* sides: 6,<br>
* radius: 70,<br>
* fill: 'red',<br>
* stroke: 'black',<br>
* strokeWidth: 4<br>
* });
*/
Kinetic.RegularPolygon = function(config) {
this.___init(config);
};
Kinetic.RegularPolygon.prototype = {
___init: function(config) {
// call super constructor
Kinetic.Shape.call(this, config);
this.className = 'RegularPolygon';
this.sceneFunc(this._sceneFunc);
},
_sceneFunc: function(context) {
var sides = this.attrs.sides,
radius = this.attrs.radius,
n, x, y;
context.beginPath();
context.moveTo(0, 0 - radius);
for(n = 1; n < sides; n++) {
x = radius * Math.sin(n * 2 * Math.PI / sides);
y = -1 * radius * Math.cos(n * 2 * Math.PI / sides);
context.lineTo(x, y);
}
context.closePath();
context.fillStrokeShape(this);
}
};
Kinetic.Util.extend(Kinetic.RegularPolygon, Kinetic.Shape);
// add getters setters
Kinetic.Factory.addGetterSetter(Kinetic.RegularPolygon, 'radius', 0);
/**
* set radius
* @name setRadius
* @method
* @memberof Kinetic.RegularPolygon.prototype
* @param {Number} radius
*/
/**
* get radius
* @name getRadius
* @method
* @memberof Kinetic.RegularPolygon.prototype
*/
Kinetic.Factory.addGetterSetter(Kinetic.RegularPolygon, 'sides', 0);
/**
* set number of sides
* @name setSides
* @method
* @memberof Kinetic.RegularPolygon.prototype
* @param {int} sides
*/
/**
* get number of sides
* @name getSides
* @method
* @memberof Kinetic.RegularPolygon.prototype
*/
Kinetic.Collection.mapMethods(Kinetic.RegularPolygon);
})();
;(function() {
/**
* Star constructor
* @constructor
* @memberof Kinetic
* @augments Kinetic.Shape
* @param {Object} config
* @param {Integer} config.numPoints
* @param {Number} config.innerRadius
* @param {Number} config.outerRadius
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var star = new Kinetic.Star({<br>
* x: 100,<br>
* y: 200,<br>
* numPoints: 5,<br>
* innerRadius: 70,<br>
* outerRadius: 70,<br>
* fill: 'red',<br>
* stroke: 'black',<br>
* strokeWidth: 4<br>
* });
*/
Kinetic.Star = function(config) {
this.___init(config);
};
Kinetic.Star.prototype = {
___init: function(config) {
// call super constructor
Kinetic.Shape.call(this, config);
this.className = 'Star';
this.sceneFunc(this._sceneFunc);
},
_sceneFunc: function(context) {
var innerRadius = this.innerRadius(),
outerRadius = this.outerRadius(),
numPoints = this.numPoints();
context.beginPath();
context.moveTo(0, 0 - outerRadius);
for(var n = 1; n < numPoints * 2; n++) {
var radius = n % 2 === 0 ? outerRadius : innerRadius;
var x = radius * Math.sin(n * Math.PI / numPoints);
var y = -1 * radius * Math.cos(n * Math.PI / numPoints);
context.lineTo(x, y);
}
context.closePath();
context.fillStrokeShape(this);
}
};
Kinetic.Util.extend(Kinetic.Star, Kinetic.Shape);
// add getters setters
Kinetic.Factory.addGetterSetter(Kinetic.Star, 'numPoints', 5);
/**
* set number of points
* @name setNumPoints
* @method
* @memberof Kinetic.Star.prototype
* @param {Integer} points
*/
/**
* get number of points
* @name getNumPoints
* @method
* @memberof Kinetic.Star.prototype
*/
Kinetic.Factory.addGetterSetter(Kinetic.Star, 'innerRadius', 0);
/**
* set inner radius
* @name setInnerRadius
* @method
* @memberof Kinetic.Star.prototype
* @param {Number} radius
*/
/**
* get inner radius
* @name getInnerRadius
* @method
* @memberof Kinetic.Star.prototype
*/
Kinetic.Factory.addGetterSetter(Kinetic.Star, 'outerRadius', 0);
/**
* set outer radius
* @name setOuterRadius
* @method
* @memberof Kinetic.Star.prototype
* @param {Number} radius
*/
/**
* get outer radius
* @name getOuterRadius
* @method
* @memberof Kinetic.Star.prototype
*/
Kinetic.Collection.mapMethods(Kinetic.Star);
})();
;(function() {
// constants
var ATTR_CHANGE_LIST = ['fontFamily', 'fontSize', 'fontStyle', 'padding', 'lineHeight', 'text'],
CHANGE_KINETIC = 'Change.kinetic',
NONE = 'none',
UP = 'up',
RIGHT = 'right',
DOWN = 'down',
LEFT = 'left',
LABEL = 'Label',
// cached variables
attrChangeListLen = ATTR_CHANGE_LIST.length;
/**
* Label constructor. Labels are groups that contain a Text and Tag shape
* @constructor
* @memberof Kinetic
* @param {Object} config
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* // create label
* var label = new Kinetic.Label({<br>
* x: 100,<br>
* y: 100, <br>
* draggable: true<br>
* });<br><br>
*
* // add a tag to the label<br>
* label.add(new Kinetic.Tag({<br>
* fill: '#bbb',<br>
* stroke: '#333',<br>
* shadowColor: 'black',<br>
* shadowBlur: 10,<br>
* shadowOffset: [10, 10],<br>
* shadowOpacity: 0.2,<br>
* lineJoin: 'round',<br>
* pointerDirection: 'up',<br>
* pointerWidth: 20,<br>
* pointerHeight: 20,<br>
* cornerRadius: 5<br>
* }));<br><br>
*
* // add text to the label<br>
* label.add(new Kinetic.Text({<br>
* text: 'Hello World!',<br>
* fontSize: 50,<br>
* lineHeight: 1.2,<br>
* padding: 10,<br>
* fill: 'green'<br>
* }));
*/
Kinetic.Label = function(config) {
this.____init(config);
};
Kinetic.Label.prototype = {
____init: function(config) {
var that = this;
this.className = LABEL;
Kinetic.Group.call(this, config);
this.on('add.kinetic', function(evt) {
that._addListeners(evt.child);
that._sync();
});
},
/**
* get Text shape for the label. You need to access the Text shape in order to update
* the text properties
* @name getText
* @method
* @memberof Kinetic.Label.prototype
*/
getText: function() {
return this.find('Text')[0];
},
/**
* get Tag shape for the label. You need to access the Tag shape in order to update
* the pointer properties and the corner radius
* @name getTag
* @method
* @memberof Kinetic.Label.prototype
*/
getTag: function() {
return this.find('Tag')[0];
},
_addListeners: function(text) {
var that = this,
n;
var func = function(){
that._sync();
};
// update text data for certain attr changes
for(n = 0; n < attrChangeListLen; n++) {
text.on(ATTR_CHANGE_LIST[n] + CHANGE_KINETIC, func);
}
},
getWidth: function() {
return this.getText().getWidth();
},
getHeight: function() {
return this.getText().getHeight();
},
_sync: function() {
var text = this.getText(),
tag = this.getTag(),
width, height, pointerDirection, pointerWidth, x, y, pointerHeight;
if (text && tag) {
width = text.getWidth();
height = text.getHeight();
pointerDirection = tag.getPointerDirection();
pointerWidth = tag.getPointerWidth();
pointerHeight = tag.getPointerHeight();
x = 0;
y = 0;
switch(pointerDirection) {
case UP:
x = width / 2;
y = -1 * pointerHeight;
break;
case RIGHT:
x = width + pointerWidth;
y = height / 2;
break;
case DOWN:
x = width / 2;
y = height + pointerHeight;
break;
case LEFT:
x = -1 * pointerWidth;
y = height / 2;
break;
}
tag.setAttrs({
x: -1 * x,
y: -1 * y,
width: width,
height: height
});
text.setAttrs({
x: -1 * x,
y: -1 * y
});
}
}
};
Kinetic.Util.extend(Kinetic.Label, Kinetic.Group);
Kinetic.Collection.mapMethods(Kinetic.Label);
/**
* Tag constructor. A Tag can be configured
* to have a pointer element that points up, right, down, or left
* @constructor
* @memberof Kinetic
* @param {Object} config
* @param {String} [config.pointerDirection] can be up, right, down, left, or none; the default
* is none. When a pointer is present, the positioning of the label is relative to the tip of the pointer.
* @param {Number} [config.pointerWidth]
* @param {Number} [config.pointerHeight]
* @param {Number} [config.cornerRadius]
*/
Kinetic.Tag = function(config) {
this.___init(config);
};
Kinetic.Tag.prototype = {
___init: function(config) {
Kinetic.Shape.call(this, config);
this.className = 'Tag';
this.sceneFunc(this._sceneFunc);
},
_sceneFunc: function(context) {
var width = this.getWidth(),
height = this.getHeight(),
pointerDirection = this.getPointerDirection(),
pointerWidth = this.getPointerWidth(),
pointerHeight = this.getPointerHeight();
//cornerRadius = this.getCornerRadius();
context.beginPath();
context.moveTo(0,0);
if (pointerDirection === UP) {
context.lineTo((width - pointerWidth)/2, 0);
context.lineTo(width/2, -1 * pointerHeight);
context.lineTo((width + pointerWidth)/2, 0);
}
context.lineTo(width, 0);
if (pointerDirection === RIGHT) {
context.lineTo(width, (height - pointerHeight)/2);
context.lineTo(width + pointerWidth, height/2);
context.lineTo(width, (height + pointerHeight)/2);
}
context.lineTo(width, height);
if (pointerDirection === DOWN) {
context.lineTo((width + pointerWidth)/2, height);
context.lineTo(width/2, height + pointerHeight);
context.lineTo((width - pointerWidth)/2, height);
}
context.lineTo(0, height);
if (pointerDirection === LEFT) {
context.lineTo(0, (height + pointerHeight)/2);
context.lineTo(-1 * pointerWidth, height/2);
context.lineTo(0, (height - pointerHeight)/2);
}
context.closePath();
context.fillStrokeShape(this);
}
};
Kinetic.Util.extend(Kinetic.Tag, Kinetic.Shape);
Kinetic.Factory.addGetterSetter(Kinetic.Tag, 'pointerDirection', NONE);
/**
* set pointer Direction
* @name setPointerDirection
* @method
* @memberof Kinetic.Tag.prototype
* @param {String} pointerDirection can be up, right, down, left, or none. The
* default is none
*/
/**
* get pointer Direction
* @name getPointerDirection
* @method
* @memberof Kinetic.Tag.prototype
*/
Kinetic.Factory.addGetterSetter(Kinetic.Tag, 'pointerWidth', 0);
/**
* set pointer width
* @name setPointerWidth
* @method
* @memberof Kinetic.Tag.prototype
* @param {Number} pointerWidth
*/
/**
* get pointer width
* @name getPointerWidth
* @method
* @memberof Kinetic.Tag.prototype
*/
Kinetic.Factory.addGetterSetter(Kinetic.Tag, 'pointerHeight', 0);
/**
* set pointer height
* @name setPointerHeight
* @method
* @memberof Kinetic.Tag.prototype
* @param {Number} pointerHeight
*/
/**
* get pointer height
* @name getPointerHeight
* @method
* @memberof Kinetic.Tag.prototype
*/
Kinetic.Factory.addGetterSetter(Kinetic.Tag, 'cornerRadius', 0);
/**
* set corner radius
* @name setCornerRadius
* @method
* @memberof Kinetic.Tag.prototype
* @param {Number} corner radius
*/
/**
* get corner radius
* @name getCornerRadius
* @method
* @memberof Kinetic.Tag.prototype
*/
Kinetic.Collection.mapMethods(Kinetic.Tag);
})();
| xixizhang96/Example | 例子example/jQuery+html5圆形进度条倒计时动画特效/改动版/js/kinetic-v5.1.0.js | JavaScript | mit | 514,339 |
/*!
* inferno v0.7.3
* (c) 2016 Dominic Gannaway
* Released under the MPL-2.0 License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.Inferno = factory());
}(this, function () { 'use strict';
var babelHelpers = {};
babelHelpers.typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;
};
babelHelpers.classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
babelHelpers.createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
babelHelpers.extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
babelHelpers;
function isNullOrUndefined(obj) {
return obj === void 0 || obj === null;
}
function isAttrAnEvent(attr) {
return attr[0] === 'o' && attr[1] === 'n' && attr.length > 3;
}
function VNode(blueprint) {
this.bp = blueprint;
this.dom = null;
this.instance = null;
this.tag = null;
this.children = null;
this.style = null;
this.className = null;
this.attrs = null;
this.events = null;
this.hooks = null;
this.key = null;
this.clipData = null;
}
VNode.prototype = {
setAttrs: function setAttrs(attrs) {
this.attrs = attrs;
return this;
},
setTag: function setTag(tag) {
this.tag = tag;
return this;
},
setStyle: function setStyle(style) {
this.style = style;
return this;
},
setClassName: function setClassName(className) {
this.className = className;
return this;
},
setChildren: function setChildren(children) {
this.children = children;
return this;
},
setHooks: function setHooks(hooks) {
this.hooks = hooks;
return this;
},
setEvents: function setEvents(events) {
this.events = events;
return this;
},
setKey: function setKey(key) {
this.key = key;
return this;
}
};
function createVNode(bp) {
return new VNode(bp);
}
function createBlueprint(shape, childrenType) {
var tag = shape.tag || null;
var tagIsDynamic = tag && tag.arg !== void 0 ? true : false;
var children = !isNullOrUndefined(shape.children) ? shape.children : null;
var childrenIsDynamic = children && children.arg !== void 0 ? true : false;
var attrs = shape.attrs || null;
var attrsIsDynamic = attrs && attrs.arg !== void 0 ? true : false;
var hooks = shape.hooks || null;
var hooksIsDynamic = hooks && hooks.arg !== void 0 ? true : false;
var events = shape.events || null;
var eventsIsDynamic = events && events.arg !== void 0 ? true : false;
var key = shape.key !== void 0 ? shape.key : null;
var keyIsDynamic = !isNullOrUndefined(key) && !isNullOrUndefined(key.arg);
var style = shape.style || null;
var styleIsDynamic = style && style.arg !== void 0 ? true : false;
var className = shape.className !== void 0 ? shape.className : null;
var classNameIsDynamic = className && className.arg !== void 0 ? true : false;
var blueprint = {
lazy: shape.lazy || false,
dom: null,
pools: {
keyed: {},
nonKeyed: []
},
tag: !tagIsDynamic ? tag : null,
className: className !== '' && className ? className : null,
style: style !== '' && style ? style : null,
isComponent: tagIsDynamic,
hasAttrs: attrsIsDynamic || (attrs ? true : false),
hasHooks: hooksIsDynamic,
hasEvents: eventsIsDynamic,
hasStyle: styleIsDynamic || (style !== '' && style ? true : false),
hasClassName: classNameIsDynamic || (className !== '' && className ? true : false),
childrenType: childrenType === void 0 ? children ? 5 : 0 : childrenType,
attrKeys: null,
eventKeys: null,
isSVG: shape.isSVG || false
};
return function () {
var vNode = new VNode(blueprint);
if (tagIsDynamic === true) {
vNode.tag = arguments[tag.arg];
}
if (childrenIsDynamic === true) {
vNode.children = arguments[children.arg];
}
if (attrsIsDynamic === true) {
vNode.attrs = arguments[attrs.arg];
} else {
vNode.attrs = attrs;
}
if (hooksIsDynamic === true) {
vNode.hooks = arguments[hooks.arg];
}
if (eventsIsDynamic === true) {
vNode.events = arguments[events.arg];
}
if (keyIsDynamic === true) {
vNode.key = arguments[key.arg];
}
if (styleIsDynamic === true) {
vNode.style = arguments[style.arg];
} else {
vNode.style = blueprint.style;
}
if (classNameIsDynamic === true) {
vNode.className = arguments[className.arg];
} else {
vNode.className = blueprint.className;
}
return vNode;
};
}
// Runs only once in applications lifetime
var isBrowser = typeof window !== 'undefined' && window.document;
// Copy of the util from dom/util, otherwise it makes massive bundles
function documentCreateElement(tag, isSVG) {
var dom = void 0;
if (isSVG === true) {
dom = document.createElementNS('http://www.w3.org/2000/svg', tag);
} else {
dom = document.createElement(tag);
}
return dom;
}
function createUniversalElement(tag, attrs, isSVG) {
if (isBrowser) {
var dom = documentCreateElement(tag, isSVG);
if (attrs) {
createStaticAttributes(attrs, dom);
}
return dom;
}
return null;
}
function createStaticAttributes(attrs, dom) {
var attrKeys = Object.keys(attrs);
for (var i = 0; i < attrKeys.length; i++) {
var attr = attrKeys[i];
var value = attrs[attr];
if (attr === 'className') {
dom.className = value;
} else {
if (value === true) {
dom.setAttribute(attr, attr);
} else if (!isNullOrUndefined(value) && value !== false && !isAttrAnEvent(attr)) {
dom.setAttribute(attr, value);
}
}
}
}
var index = {
createBlueprint: createBlueprint,
createVNode: createVNode,
universal: {
createElement: createUniversalElement
}
};
return index;
})); | sashberd/cdnjs | ajax/libs/inferno/0.7.3/inferno.js | JavaScript | mit | 6,896 |
/**
* OpenLayers 3 Layer Switcher Control.
* See [the examples](./examples) for usage.
* @constructor
* @extends {ol.control.Control}
* @param {Object} opt_options Control options, extends olx.control.ControlOptions adding:
* **`tipLabel`** `String` - the button tooltip.
*/
ol.control.LayerSwitcher = function(opt_options) {
var options = opt_options || {};
var tipLabel = options.tipLabel ?
options.tipLabel : 'Legend';
this.mapListeners = [];
this.hiddenClassName = 'ol-unselectable ol-control layer-switcher';
this.shownClassName = this.hiddenClassName + ' shown';
var element = document.createElement('div');
element.className = this.hiddenClassName;
var button = document.createElement('button');
button.setAttribute('title', tipLabel);
element.appendChild(button);
this.panel = document.createElement('div');
this.panel.className = 'panel';
element.appendChild(this.panel);
var this_ = this;
element.onmouseover = function(e) {
this_.showPanel();
};
button.onclick = function(e) {
this_.showPanel();
};
element.onmouseout = function(e) {
e = e || window.event;
if (!element.contains(e.toElement)) {
this_.hidePanel();
}
};
ol.control.Control.call(this, {
element: element,
target: options.target
});
};
ol.inherits(ol.control.LayerSwitcher, ol.control.Control);
/**
* Show the layer panel.
*/
ol.control.LayerSwitcher.prototype.showPanel = function() {
if (this.element.className != this.shownClassName) {
this.element.className = this.shownClassName;
this.renderPanel();
}
};
/**
* Hide the layer panel.
*/
ol.control.LayerSwitcher.prototype.hidePanel = function() {
if (this.element.className != this.hiddenClassName) {
this.element.className = this.hiddenClassName;
}
};
/**
* Re-draw the layer panel to represent the current state of the layers.
*/
ol.control.LayerSwitcher.prototype.renderPanel = function() {
this.ensureTopVisibleBaseLayerShown_();
while(this.panel.firstChild) {
this.panel.removeChild(this.panel.firstChild);
}
var ul = document.createElement('ul');
this.panel.appendChild(ul);
this.renderLayers_(this.getMap(), ul);
};
/**
* Set the map instance the control is associated with.
* @param {ol.Map} map The map instance.
*/
ol.control.LayerSwitcher.prototype.setMap = function(map) {
// Clean up listeners associated with the previous map
for (var i = 0, key; i < this.mapListeners.length; i++) {
this.getMap().unByKey(this.mapListeners[i]);
}
this.mapListeners.length = 0;
// Wire up listeners etc. and store reference to new map
ol.control.Control.prototype.setMap.call(this, map);
if (map) {
var this_ = this;
this.mapListeners.push(map.on('pointerdown', function() {
this_.hidePanel();
}));
this.renderPanel();
}
};
/**
* Ensure only the top-most base layer is visible if more than one is visible.
* @private
*/
ol.control.LayerSwitcher.prototype.ensureTopVisibleBaseLayerShown_ = function() {
var lastVisibleBaseLyr;
ol.control.LayerSwitcher.forEachRecursive(this.getMap(), function(l, idx, a) {
if (l.get('type') === 'base' && l.getVisible()) {
lastVisibleBaseLyr = l;
}
});
if (lastVisibleBaseLyr) this.setVisible_(lastVisibleBaseLyr, true);
};
/**
* Toggle the visible state of a layer.
* Takes care of hiding other layers in the same exclusive group if the layer
* is toggle to visible.
* @private
* @param {ol.layer.Base} The layer whos visibility will be toggled.
*/
ol.control.LayerSwitcher.prototype.setVisible_ = function(lyr, visible) {
var map = this.getMap();
lyr.setVisible(visible);
if (visible && lyr.get('type') === 'base') {
// Hide all other base layers regardless of grouping
ol.control.LayerSwitcher.forEachRecursive(map, function(l, idx, a) {
if (l != lyr && l.get('type') === 'base') {
l.setVisible(false);
}
});
}
};
/**
* Render all layers that are children of a group.
* @private
* @param {ol.layer.Base} lyr Layer to be rendered (should have a title property).
* @param {Number} idx Position in parent group list.
*/
ol.control.LayerSwitcher.prototype.renderLayer_ = function(lyr, idx) {
var this_ = this;
var li = document.createElement('li');
var lyrTitle = lyr.get('title');
var lyrId = lyr.get('title').replace(' ', '-') + '_' + idx;
var label = document.createElement('label');
if (lyr.getLayers) {
li.className = 'group';
label.innerHTML = lyrTitle;
li.appendChild(label);
var ul = document.createElement('ul');
li.appendChild(ul);
this.renderLayers_(lyr, ul);
} else {
var input = document.createElement('input');
if (lyr.get('type') === 'base') {
input.type = 'radio';
input.name = 'base';
} else {
input.type = 'checkbox';
}
input.id = lyrId;
input.checked = lyr.get('visible');
input.onchange = function(e) {
this_.setVisible_(lyr, e.target.checked);
};
li.appendChild(input);
label.htmlFor = lyrId;
label.innerHTML = lyrTitle;
li.appendChild(label);
}
return li;
};
/**
* Render all layers that are children of a group.
* @private
* @param {ol.layer.Group} lyr Group layer whos children will be rendered.
* @param {Element} elm DOM element that children will be appended to.
*/
ol.control.LayerSwitcher.prototype.renderLayers_ = function(lyr, elm) {
var lyrs = lyr.getLayers().getArray().slice().reverse();
for (var i = 0, l; i < lyrs.length; i++) {
l = lyrs[i];
if (l.get('title')) {
elm.appendChild(this.renderLayer_(l, i));
}
}
};
/**
* **Static** Call the supplied function for each layer in the passed layer group
* recursing nested groups.
* @param {ol.layer.Group} lyr The layer group to start iterating from.
* @param {Function} fn Callback which will be called for each `ol.layer.Base`
* found under `lyr`. The signature for `fn` is the same as `ol.Collection#forEach`
*/
ol.control.LayerSwitcher.forEachRecursive = function(lyr, fn) {
lyr.getLayers().forEach(function(lyr, idx, a) {
fn(lyr, idx, a);
if (lyr.getLayers) {
ol.control.LayerSwitcher.forEachRecursive(lyr, fn);
}
});
};
| mwernimont/sparrow-ui | src/main/webapp/js/vendor/ol3-layerswitcher/1.0.2/ol3-layerswitcher.js | JavaScript | cc0-1.0 | 6,635 |
/*
* Copyright (C) 2010 ENAC
*
* This file is part of paparazzi.
*
* paparazzi is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* paparazzi is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with paparazzi; see the file COPYING. If not, write to
* the Free Software Foundation, 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
*/
/* driver for the ADC ads1114 (16 bits I2C 860SpS max) from Texas instruments
* Navarro & Gorraz & Hattenberger
*/
#ifndef ADS_1114_H
#define ADS_1114_H
#include "std.h"
#include "mcu_periph/i2c.h"
/* I2C slave address */
#ifndef ADS1114_1_I2C_ADDR
#define ADS1114_1_I2C_ADDR 0x90 // slave address byte (I2c address(7bits) + R/W @ 0)
#endif
#ifndef ADS1114_2_I2C_ADDR
#define ADS1114_2_I2C_ADDR 0x92 // slave address byte (I2c address(7bits) + R/W @ 0)
#endif
/* I2C conf register */
#define ADS1114_POINTER_CONV_REG 0x00 // access to the Conversion register (16bits)
#define ADS1114_POINTER_CONFIG_REG 0x01 // access to the Configuration register (16bits)
/* ADS1114_1 default conf */
#ifndef ADS1114_1_OS
#define ADS1114_1_OS 0x0 // Operational status
#endif
#ifndef ADS1114_1_MUX
#define ADS1114_1_MUX 0x0 // Input multiplexer
#endif
#ifndef ADS1114_1_PGA
#define ADS1114_1_PGA 0x3 // Programable gain amplifier (= 4 with a Full Scale of +/- 1.024V)
#endif
#ifndef ADS1114_1_MODE
#define ADS1114_1_MODE 0x0 // Continuous conversion mode
#endif
#ifndef ADS1114_1_DR
#define ADS1114_1_DR 0x4 // Data rate (128 SPS)
#endif
#ifndef ADS1114_1_COMP_MODE
#define ADS1114_1_COMP_MODE 0x0 // Comparator mode
#endif
#ifndef ADS1114_1_COMP_POL
#define ADS1114_1_COMP_POL 0x0 // Comparator polarity
#endif
#ifndef ADS1114_1_COMP_LAT
#define ADS1114_1_COMP_LAT 0x0 // Latching comparator
#endif
#ifndef ADS1114_1_COMP_QUE
#define ADS1114_1_COMP_QUE 0x3 // Comparator queue (disable)
#endif
#define ADS1114_1_CONFIG_MSB ((ADS1114_1_OS<<7)|(ADS1114_1_MUX<<4)|(ADS1114_1_PGA<<1)|(ADS1114_1_MODE))
#define ADS1114_1_CONFIG_LSB ((ADS1114_1_DR<<5)|(ADS1114_1_COMP_MODE<<4)|(ADS1114_1_COMP_POL<<3)|(ADS1114_1_COMP_LAT<<2)|(ADS1114_1_COMP_QUE))
/* ADS1114_1 default conf */
#ifndef ADS1114_2_OS
#define ADS1114_2_OS 0x0 // Operational status
#endif
#ifndef ADS1114_2_MUX
#define ADS1114_2_MUX 0x0 // Input multiplexer
#endif
#ifndef ADS1114_2_PGA
#define ADS1114_2_PGA 0x3 // Programable gain amplifier (= 4 with a Full Scale of +/- 1.024V)
#endif
#ifndef ADS1114_2_MODE
#define ADS1114_2_MODE 0x0 // Continuous conversion mode
#endif
#ifndef ADS1114_2_DR
#define ADS1114_2_DR 0x4 // Data rate (128 SPS)
#endif
#ifndef ADS1114_2_COMP_MODE
#define ADS1114_2_COMP_MODE 0x0 // Comparator mode
#endif
#ifndef ADS1114_2_COMP_POL
#define ADS1114_2_COMP_POL 0x0 // Comparator polarity
#endif
#ifndef ADS1114_2_COMP_LAT
#define ADS1114_2_COMP_LAT 0x0 // Latching comparator
#endif
#ifndef ADS1114_2_COMP_QUE
#define ADS1114_2_COMP_QUE 0x3 // Comparator queue (disable)
#endif
#define ADS1114_2_CONFIG_MSB ((ADS1114_2_OS<<7)|(ADS1114_2_MUX<<4)|(ADS1114_2_PGA<<1)|(ADS1114_2_MODE))
#define ADS1114_2_CONFIG_LSB ((ADS1114_2_DR<<5)|(ADS1114_2_COMP_MODE<<4)|(ADS1114_2_COMP_POL<<3)|(ADS1114_2_COMP_LAT<<2)|(ADS1114_2_COMP_QUE))
/* Default I2C device */
// FIXME all ads on the same device for now
#ifndef ADS1114_I2C_DEV
#define ADS1114_I2C_DEV i2c1
#endif
struct ads1114_periph {
struct i2c_transaction trans;
uint8_t i2c_addr;
bool_t config_done;
bool_t data_available;
};
#if USE_ADS1114_1
extern struct ads1114_periph ads1114_1;
#endif
#if USE_ADS1114_2
extern struct ads1114_periph ads1114_2;
#endif
extern void ads1114_init(void);
extern void ads1114_read(struct ads1114_periph *p);
// Generic Event Macro
#define _Ads1114Event(_p) {\
if (!_p.config_done) { \
if (_p.trans.status == I2CTransSuccess) { _p.config_done = TRUE; _p.trans.status = I2CTransDone; } \
if (_p.trans.status == I2CTransFailed) { _p.trans.status = I2CTransDone; } \
} else { \
if (_p.trans.status == I2CTransSuccess) { _p.data_available = TRUE; _p.trans.status = I2CTransDone; } \
if (_p.trans.status == I2CTransFailed) { _p.trans.status = I2CTransDone; } \
} \
}
#if USE_ADS1114_1
#define Ads1114_1Event() _Ads1114Event(ads1114_1)
#else
#define Ads1114_1Event() {}
#endif
#if USE_ADS1114_2
#define Ads1114_2Event() _Ads1114Event(ads1114_2)
#else
#define Ads1114_2Event() {}
#endif
// Final event macro
#define Ads1114Event() { \
Ads1114_1Event(); \
Ads1114_2Event(); \
}
// Get value macro
// @param ads1114 periph
#define Ads1114GetValue(_p) ((int16_t)(((int16_t)_p.trans.buf[0]<<8)|_p.trans.buf[1]))
#endif // ADS_1114_H
| monzie9000/rory | workspace/EclipsePapa/src/sw/airborne/peripherals/ads1114.h | C | gpl-2.0 | 5,076 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package datafield
* @subpackage number
* @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2015111600; // The current plugin version (Date: YYYYMMDDXX)
$plugin->requires = 2015111000; // Requires this Moodle version
$plugin->component = 'datafield_number'; // Full name of the plugin (used for diagnostics)
| ernestovi/ups | moodle/mod/data/field/number/version.php | PHP | gpl-3.0 | 1,176 |
/*
* 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.
*/
package com.facebook.presto.sql.tree;
import com.google.common.collect.ImmutableList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import static java.util.Objects.requireNonNull;
public class NotExpression
extends Expression
{
private final Expression value;
public NotExpression(Expression value)
{
this(Optional.empty(), value);
}
public NotExpression(NodeLocation location, Expression value)
{
this(Optional.of(location), value);
}
private NotExpression(Optional<NodeLocation> location, Expression value)
{
super(location);
requireNonNull(value, "value is null");
this.value = value;
}
public Expression getValue()
{
return value;
}
@Override
public <R, C> R accept(AstVisitor<R, C> visitor, C context)
{
return visitor.visitNotExpression(this, context);
}
@Override
public List<Node> getChildren()
{
return ImmutableList.of(value);
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
NotExpression that = (NotExpression) o;
return Objects.equals(value, that.value);
}
@Override
public int hashCode()
{
return value.hashCode();
}
}
| marsorp/blog | presto166/presto-parser/src/main/java/com/facebook/presto/sql/tree/NotExpression.java | Java | apache-2.0 | 1,998 |
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* 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.
*/
package com.intellij.codeInsight.daemon.impl.quickfix;
import com.intellij.codeInsight.ExpectedTypeInfo;
import com.intellij.codeInsight.ExpectedTypesProvider;
import com.intellij.codeInsight.intention.impl.TypeExpression;
import com.intellij.codeInsight.template.TemplateBuilder;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author ven
*/
public class GuessTypeParameters {
private final JVMElementFactory myFactory;
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.quickfix.GuessTypeParameters");
public GuessTypeParameters(JVMElementFactory factory) {
myFactory = factory;
}
private List<PsiType> matchingTypeParameters (PsiType[] paramVals, PsiTypeParameter[] params, ExpectedTypeInfo info) {
PsiType type = info.getType();
int kind = info.getKind();
List<PsiType> result = new ArrayList<PsiType>();
for (int i = 0; i < paramVals.length; i++) {
PsiType val = paramVals[i];
if (val != null) {
switch (kind) {
case ExpectedTypeInfo.TYPE_STRICTLY:
if (val.equals(type)) result.add(myFactory.createType(params[i]));
break;
case ExpectedTypeInfo.TYPE_OR_SUBTYPE:
if (type.isAssignableFrom(val)) result.add(myFactory.createType(params[i]));
break;
case ExpectedTypeInfo.TYPE_OR_SUPERTYPE:
if (val.isAssignableFrom(type)) result.add(myFactory.createType(params[i]));
break;
}
}
}
return result;
}
public void setupTypeElement (PsiTypeElement typeElement, ExpectedTypeInfo[] infos, PsiSubstitutor substitutor,
TemplateBuilder builder, @Nullable PsiElement context, PsiClass targetClass) {
LOG.assertTrue(typeElement.isValid());
ApplicationManager.getApplication().assertWriteAccessAllowed();
PsiManager manager = typeElement.getManager();
GlobalSearchScope scope = typeElement.getResolveScope();
Project project = manager.getProject();
if (infos.length == 1 && substitutor != null && substitutor != PsiSubstitutor.EMPTY) {
ExpectedTypeInfo info = infos[0];
Map<PsiTypeParameter, PsiType> map = substitutor.getSubstitutionMap();
PsiType[] vals = map.values().toArray(PsiType.createArray(map.size()));
PsiTypeParameter[] params = map.keySet().toArray(new PsiTypeParameter[map.size()]);
List<PsiType> types = matchingTypeParameters(vals, params, info);
if (!types.isEmpty()) {
ContainerUtil.addAll(types, ExpectedTypesProvider.processExpectedTypes(infos, new MyTypeVisitor(manager, scope), project));
builder.replaceElement(typeElement, new TypeExpression(project, types.toArray(PsiType.createArray(types.size()))));
return;
}
else {
PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
PsiType type = info.getType();
PsiType defaultType = info.getDefaultType();
try {
PsiTypeElement inplaceTypeElement = ((PsiVariable)factory.createVariableDeclarationStatement("foo", type, null).getDeclaredElements()[0]).getTypeElement();
PsiSubstitutor rawingSubstitutor = getRawingSubstitutor (context, targetClass);
int substitionResult = substituteToTypeParameters(typeElement, inplaceTypeElement, vals, params, builder, rawingSubstitutor, true);
if (substitionResult != SUBSTITUTED_NONE) {
if (substitionResult == SUBSTITUTED_IN_PARAMETERS) {
PsiJavaCodeReferenceElement refElement = typeElement.getInnermostComponentReferenceElement();
LOG.assertTrue(refElement != null && refElement.getReferenceNameElement() != null);
type = getComponentType(type);
LOG.assertTrue(type != null);
defaultType = getComponentType(defaultType);
LOG.assertTrue(defaultType != null);
ExpectedTypeInfo info1 = ExpectedTypesProvider.createInfo(((PsiClassType)defaultType).rawType(),
ExpectedTypeInfo.TYPE_STRICTLY,
((PsiClassType)defaultType).rawType(),
info.getTailType());
MyTypeVisitor visitor = new MyTypeVisitor(manager, scope);
builder.replaceElement(refElement.getReferenceNameElement(),
new TypeExpression(project, ExpectedTypesProvider.processExpectedTypes(new ExpectedTypeInfo[]{info1}, visitor, project)));
}
return;
}
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
}
PsiType[] types = infos.length == 0 ? new PsiType[] {typeElement.getType()} : ExpectedTypesProvider.processExpectedTypes(infos, new MyTypeVisitor(manager, scope), project);
builder.replaceElement(typeElement,
new TypeExpression(project, types));
}
private static PsiSubstitutor getRawingSubstitutor(PsiElement context, PsiClass targetClass) {
if (context == null || targetClass == null) return PsiSubstitutor.EMPTY;
PsiTypeParameterListOwner currContext = PsiTreeUtil.getParentOfType(context, PsiTypeParameterListOwner.class);
PsiManager manager = context.getManager();
PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
while (currContext != null && !manager.areElementsEquivalent(currContext, targetClass)) {
PsiTypeParameter[] typeParameters = currContext.getTypeParameters();
substitutor = JavaPsiFacade.getInstance(context.getProject()).getElementFactory().createRawSubstitutor(substitutor, typeParameters);
currContext = currContext.getContainingClass();
}
return substitutor;
}
@Nullable
private static PsiClassType getComponentType (PsiType type) {
type = type.getDeepComponentType();
if (type instanceof PsiClassType) return (PsiClassType)type;
return null;
}
private static final int SUBSTITUTED_NONE = 0;
private static final int SUBSTITUTED_IN_REF = 1;
private static final int SUBSTITUTED_IN_PARAMETERS = 2;
private int substituteToTypeParameters (PsiTypeElement typeElement,
PsiTypeElement inplaceTypeElement,
PsiType[] paramVals,
PsiTypeParameter[] params,
TemplateBuilder builder,
PsiSubstitutor rawingSubstitutor,
boolean toplevel) {
PsiType type = inplaceTypeElement.getType();
List<PsiType> types = new ArrayList<PsiType>();
for (int i = 0; i < paramVals.length; i++) {
PsiType val = paramVals[i];
if (val == null) return SUBSTITUTED_NONE;
if (type.equals(val)) {
types.add(myFactory.createType(params[i]));
}
}
if (!types.isEmpty()) {
Project project = typeElement.getProject();
PsiType substituted = rawingSubstitutor.substitute(type);
if (!CommonClassNames.JAVA_LANG_OBJECT.equals(substituted.getCanonicalText()) && (toplevel || substituted.equals(type))) {
types.add(substituted);
}
builder.replaceElement(typeElement, new TypeExpression(project, types.toArray(PsiType.createArray(types.size()))));
return toplevel ? SUBSTITUTED_IN_REF : SUBSTITUTED_IN_PARAMETERS;
}
boolean substituted = false;
PsiJavaCodeReferenceElement ref = typeElement.getInnermostComponentReferenceElement();
PsiJavaCodeReferenceElement inplaceRef = inplaceTypeElement.getInnermostComponentReferenceElement();
if (ref != null) {
LOG.assertTrue(inplaceRef != null);
PsiTypeElement[] innerTypeElements = ref.getParameterList().getTypeParameterElements();
PsiTypeElement[] inplaceInnerTypeElements = inplaceRef.getParameterList().getTypeParameterElements();
for (int i = 0; i < innerTypeElements.length; i++) {
substituted |= substituteToTypeParameters(innerTypeElements[i], inplaceInnerTypeElements[i], paramVals, params, builder,
rawingSubstitutor, false) != SUBSTITUTED_NONE;
}
}
return substituted ? SUBSTITUTED_IN_PARAMETERS : SUBSTITUTED_NONE;
}
public static class MyTypeVisitor extends PsiTypeVisitor<PsiType> {
private final GlobalSearchScope myResolveScope;
private final PsiManager myManager;
public MyTypeVisitor(PsiManager manager, GlobalSearchScope resolveScope) {
myManager = manager;
myResolveScope = resolveScope;
}
@Override
public PsiType visitType(PsiType type) {
if (type.equals(PsiType.NULL)) return PsiType.getJavaLangObject(myManager, myResolveScope);
return type;
}
@Override
public PsiType visitCapturedWildcardType(PsiCapturedWildcardType capturedWildcardType) {
return capturedWildcardType.getUpperBound().accept(this);
}
}
}
| kdwink/intellij-community | java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/GuessTypeParameters.java | Java | apache-2.0 | 10,162 |
<html>
<head>
<script>
if (window.testRunner) {
testRunner.dumpAsText();
}
</script>
<style>
@-webkit-keyframes anim {
42% {
-webkit-border-horizontal-spacing: 42rem;
}
}
body::first-letter {
-webkit-animation-name: anim;
}
</style>
</head>
<body>
This test passes if it does not crash.
</body>
</html>
| js0701/chromium-crosswalk | third_party/WebKit/LayoutTests/animations/pseudo-element-animation-with-rems.html | HTML | bsd-3-clause | 345 |
//===-- PPCPredicates.cpp - PPC Branch Predicate Information --------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the PowerPC branch predicates.
//
//===----------------------------------------------------------------------===//
#include "PPCPredicates.h"
#include "llvm/Support/ErrorHandling.h"
#include <cassert>
using namespace llvm;
PPC::Predicate PPC::InvertPredicate(PPC::Predicate Opcode) {
switch (Opcode) {
case PPC::PRED_EQ: return PPC::PRED_NE;
case PPC::PRED_NE: return PPC::PRED_EQ;
case PPC::PRED_LT: return PPC::PRED_GE;
case PPC::PRED_GE: return PPC::PRED_LT;
case PPC::PRED_GT: return PPC::PRED_LE;
case PPC::PRED_LE: return PPC::PRED_GT;
case PPC::PRED_NU: return PPC::PRED_UN;
case PPC::PRED_UN: return PPC::PRED_NU;
case PPC::PRED_EQ_MINUS: return PPC::PRED_NE_PLUS;
case PPC::PRED_NE_MINUS: return PPC::PRED_EQ_PLUS;
case PPC::PRED_LT_MINUS: return PPC::PRED_GE_PLUS;
case PPC::PRED_GE_MINUS: return PPC::PRED_LT_PLUS;
case PPC::PRED_GT_MINUS: return PPC::PRED_LE_PLUS;
case PPC::PRED_LE_MINUS: return PPC::PRED_GT_PLUS;
case PPC::PRED_NU_MINUS: return PPC::PRED_UN_PLUS;
case PPC::PRED_UN_MINUS: return PPC::PRED_NU_PLUS;
case PPC::PRED_EQ_PLUS: return PPC::PRED_NE_MINUS;
case PPC::PRED_NE_PLUS: return PPC::PRED_EQ_MINUS;
case PPC::PRED_LT_PLUS: return PPC::PRED_GE_MINUS;
case PPC::PRED_GE_PLUS: return PPC::PRED_LT_MINUS;
case PPC::PRED_GT_PLUS: return PPC::PRED_LE_MINUS;
case PPC::PRED_LE_PLUS: return PPC::PRED_GT_MINUS;
case PPC::PRED_NU_PLUS: return PPC::PRED_UN_MINUS;
case PPC::PRED_UN_PLUS: return PPC::PRED_NU_MINUS;
// Simple predicates for single condition-register bits.
case PPC::PRED_BIT_SET: return PPC::PRED_BIT_UNSET;
case PPC::PRED_BIT_UNSET: return PPC::PRED_BIT_SET;
}
llvm_unreachable("Unknown PPC branch opcode!");
}
PPC::Predicate PPC::getSwappedPredicate(PPC::Predicate Opcode) {
switch (Opcode) {
case PPC::PRED_EQ: return PPC::PRED_EQ;
case PPC::PRED_NE: return PPC::PRED_NE;
case PPC::PRED_LT: return PPC::PRED_GT;
case PPC::PRED_GE: return PPC::PRED_LE;
case PPC::PRED_GT: return PPC::PRED_LT;
case PPC::PRED_LE: return PPC::PRED_GE;
case PPC::PRED_NU: return PPC::PRED_NU;
case PPC::PRED_UN: return PPC::PRED_UN;
case PPC::PRED_EQ_MINUS: return PPC::PRED_EQ_MINUS;
case PPC::PRED_NE_MINUS: return PPC::PRED_NE_MINUS;
case PPC::PRED_LT_MINUS: return PPC::PRED_GT_MINUS;
case PPC::PRED_GE_MINUS: return PPC::PRED_LE_MINUS;
case PPC::PRED_GT_MINUS: return PPC::PRED_LT_MINUS;
case PPC::PRED_LE_MINUS: return PPC::PRED_GE_MINUS;
case PPC::PRED_NU_MINUS: return PPC::PRED_NU_MINUS;
case PPC::PRED_UN_MINUS: return PPC::PRED_UN_MINUS;
case PPC::PRED_EQ_PLUS: return PPC::PRED_EQ_PLUS;
case PPC::PRED_NE_PLUS: return PPC::PRED_NE_PLUS;
case PPC::PRED_LT_PLUS: return PPC::PRED_GT_PLUS;
case PPC::PRED_GE_PLUS: return PPC::PRED_LE_PLUS;
case PPC::PRED_GT_PLUS: return PPC::PRED_LT_PLUS;
case PPC::PRED_LE_PLUS: return PPC::PRED_GE_PLUS;
case PPC::PRED_NU_PLUS: return PPC::PRED_NU_PLUS;
case PPC::PRED_UN_PLUS: return PPC::PRED_UN_PLUS;
case PPC::PRED_BIT_SET:
case PPC::PRED_BIT_UNSET:
llvm_unreachable("Invalid use of bit predicate code");
}
llvm_unreachable("Unknown PPC branch opcode!");
}
| endlessm/chromium-browser | third_party/swiftshader/third_party/llvm-10.0/llvm/lib/Target/PowerPC/MCTargetDesc/PPCPredicates.cpp | C++ | bsd-3-clause | 3,553 |
/**
* @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
*/
import { __core_private__ as r } from '@angular/core';
export declare type RenderDebugInfo = typeof r._RenderDebugInfo;
export declare var RenderDebugInfo: typeof r.RenderDebugInfo;
export declare type DirectRenderer = typeof r._DirectRenderer;
export declare var ReflectionCapabilities: typeof r.ReflectionCapabilities;
export declare type DebugDomRootRenderer = typeof r._DebugDomRootRenderer;
export declare var DebugDomRootRenderer: typeof r.DebugDomRootRenderer;
export declare var reflector: typeof r.reflector;
export declare type NoOpAnimationPlayer = typeof r._NoOpAnimationPlayer;
export declare var NoOpAnimationPlayer: typeof r.NoOpAnimationPlayer;
export declare type AnimationPlayer = typeof r._AnimationPlayer;
export declare var AnimationPlayer: typeof r.AnimationPlayer;
export declare type AnimationSequencePlayer = typeof r._AnimationSequencePlayer;
export declare var AnimationSequencePlayer: typeof r.AnimationSequencePlayer;
export declare type AnimationGroupPlayer = typeof r._AnimationGroupPlayer;
export declare var AnimationGroupPlayer: typeof r.AnimationGroupPlayer;
export declare type AnimationKeyframe = typeof r._AnimationKeyframe;
export declare var AnimationKeyframe: typeof r.AnimationKeyframe;
export declare type AnimationStyles = typeof r._AnimationStyles;
export declare var AnimationStyles: typeof r.AnimationStyles;
export declare var prepareFinalAnimationStyles: typeof r.prepareFinalAnimationStyles;
export declare var balanceAnimationKeyframes: typeof r.balanceAnimationKeyframes;
export declare var clearStyles: typeof r.clearStyles;
export declare var collectAndResolveStyles: typeof r.collectAndResolveStyles;
| tspycher/python-raspberry-bugcontrol | static-web/node_modules/@angular/platform-browser/src/private_import_core.d.ts | TypeScript | mit | 1,859 |
(function () {
/*** Variables ***/
var win = window,
doc = document,
attrProto = {
setAttribute: Element.prototype.setAttribute,
removeAttribute: Element.prototype.removeAttribute
},
hasShadow = Element.prototype.createShadowRoot,
container = doc.createElement('div'),
noop = function(){},
trueop = function(){ return true; },
regexReplaceCommas = /,/g,
regexCamelToDash = /([a-z])([A-Z])/g,
regexPseudoParens = /\(|\)/g,
regexPseudoCapture = /:(\w+)\u276A(.+?(?=\u276B))|:(\w+)/g,
regexDigits = /(\d+)/g,
keypseudo = {
action: function (pseudo, event) {
return pseudo.value.match(regexDigits).indexOf(String(event.keyCode)) > -1 == (pseudo.name == 'keypass') || null;
}
},
/*
- The prefix object generated here is added to the xtag object as xtag.prefix later in the code
- Prefix provides a variety of prefix variations for the browser in which your code is running
- The 4 variations of prefix are as follows:
* prefix.dom: the correct prefix case and form when used on DOM elements/style properties
* prefix.lowercase: a lowercase version of the prefix for use in various user-code situations
* prefix.css: the lowercase, dashed version of the prefix
* prefix.js: addresses prefixed APIs present in global and non-Element contexts
*/
prefix = (function () {
var styles = win.getComputedStyle(doc.documentElement, ''),
pre = (Array.prototype.slice
.call(styles)
.join('')
.match(/-(moz|webkit|ms)-/) || (styles.OLink === '' && ['', 'o'])
)[1];
return {
dom: pre == 'ms' ? 'MS' : pre,
lowercase: pre,
css: '-' + pre + '-',
js: pre == 'ms' ? pre : pre[0].toUpperCase() + pre.substr(1)
};
})(),
matchSelector = Element.prototype.matches || Element.prototype.matchesSelector || Element.prototype[prefix.lowercase + 'MatchesSelector'];
/*** Functions ***/
// Utilities
/*
This is an enhanced typeof check for all types of objects. Where typeof would normaly return
'object' for many common DOM objects (like NodeLists and HTMLCollections).
- For example: typeOf(document.children) will correctly return 'htmlcollection'
*/
var typeCache = {},
typeString = typeCache.toString,
typeRegexp = /\s([a-zA-Z]+)/;
function typeOf(obj) {
var type = typeString.call(obj);
return typeCache[type] || (typeCache[type] = type.match(typeRegexp)[1].toLowerCase());
}
function clone(item, type){
var fn = clone[type || typeOf(item)];
return fn ? fn(item) : item;
}
clone.object = function(src){
var obj = {};
for (var key in src) obj[key] = clone(src[key]);
return obj;
};
clone.array = function(src){
var i = src.length, array = new Array(i);
while (i--) array[i] = clone(src[i]);
return array;
};
/*
The toArray() method allows for conversion of any object to a true array. For types that
cannot be converted to an array, the method returns a 1 item array containing the passed-in object.
*/
var unsliceable = { 'undefined': 1, 'null': 1, 'number': 1, 'boolean': 1, 'string': 1, 'function': 1 };
function toArray(obj){
return unsliceable[typeOf(obj)] ? [obj] : Array.prototype.slice.call(obj, 0);
}
// DOM
var str = '';
function query(element, selector){
return (selector || str).length ? toArray(element.querySelectorAll(selector)) : [];
}
// Pseudos
function parsePseudo(fn){fn();}
// Mixins
function mergeOne(source, key, current){
var type = typeOf(current);
if (type == 'object' && typeOf(source[key]) == 'object') xtag.merge(source[key], current);
else source[key] = clone(current, type);
return source;
}
function mergeMixin(tag, original, mixin, name) {
var key, keys = {};
for (var z in original) keys[z.split(':')[0]] = z;
for (z in mixin) {
key = keys[z.split(':')[0]];
if (typeof original[key] == 'function') {
if (!key.match(':mixins')) {
original[key + ':mixins'] = original[key];
delete original[key];
key = key + ':mixins';
}
original[key].__mixin__ = xtag.applyPseudos(z + (z.match(':mixins') ? '' : ':mixins'), mixin[z], tag.pseudos, original[key].__mixin__);
}
else {
original[z] = mixin[z];
delete original[key];
}
}
}
var uniqueMixinCount = 0;
function addMixin(tag, original, mixin){
for (var z in mixin){
original[z + ':__mixin__(' + (uniqueMixinCount++) + ')'] = xtag.applyPseudos(z, mixin[z], tag.pseudos);
}
}
function resolveMixins(mixins, output){
var index = mixins.length;
while (index--){
output.unshift(mixins[index]);
if (xtag.mixins[mixins[index]].mixins) resolveMixins(xtag.mixins[mixins[index]].mixins, output);
}
return output;
}
function applyMixins(tag) {
resolveMixins(tag.mixins, []).forEach(function(name){
var mixin = xtag.mixins[name];
for (var type in mixin) {
var item = mixin[type],
original = tag[type];
if (!original) tag[type] = item;
else {
switch (type){
case 'mixins': break;
case 'events': addMixin(tag, original, item); break;
case 'accessors':
case 'prototype':
for (var z in item) {
if (!original[z]) original[z] = item[z];
else mergeMixin(tag, original[z], item[z], name);
}
break;
default: mergeMixin(tag, original, item, name);
}
}
}
});
return tag;
}
// Events
function delegateAction(pseudo, event) {
var match,
target = event.target,
root = event.currentTarget;
while (!match && target && target != root) {
if (target.tagName && matchSelector.call(target, pseudo.value)) match = target;
target = target.parentNode;
}
if (!match && root.tagName && matchSelector.call(root, pseudo.value)) match = root;
return match ? pseudo.listener = pseudo.listener.bind(match) : null;
}
function touchFilter(event){
return event.button === 0;
}
function writeProperty(key, event, base, desc){
if (desc) event[key] = base[key];
else Object.defineProperty(event, key, {
writable: true,
enumerable: true,
value: base[key]
});
}
var skipProps = {};
for (var z in doc.createEvent('CustomEvent')) skipProps[z] = 1;
function inheritEvent(event, base){
var desc = Object.getOwnPropertyDescriptor(event, 'target');
for (var z in base) {
if (!skipProps[z]) writeProperty(z, event, base, desc);
}
event.baseEvent = base;
}
// Accessors
function modAttr(element, attr, name, value, method){
attrProto[method].call(element, name, attr && attr.boolean ? '' : value);
}
function syncAttr(element, attr, name, value, method){
if (attr && (attr.property || attr.selector)) {
var nodes = attr.property ? [element.xtag[attr.property]] : attr.selector ? xtag.query(element, attr.selector) : [],
index = nodes.length;
while (index--) nodes[index][method](name, value);
}
}
function attachProperties(tag, prop, z, accessor, attr, name){
var key = z.split(':'), type = key[0];
if (type == 'get') {
key[0] = prop;
tag.prototype[prop].get = xtag.applyPseudos(key.join(':'), accessor[z], tag.pseudos, accessor[z]);
}
else if (type == 'set') {
key[0] = prop;
var setter = tag.prototype[prop].set = xtag.applyPseudos(key.join(':'), attr ? function(value){
var old, method = 'setAttribute';
if (attr.boolean){
value = !!value;
old = this.hasAttribute(name);
if (!value) method = 'removeAttribute';
}
else {
value = attr.validate ? attr.validate.call(this, value) : value;
old = this.getAttribute(name);
}
modAttr(this, attr, name, value, method);
accessor[z].call(this, value, old);
syncAttr(this, attr, name, value, method);
} : accessor[z] ? function(value){
accessor[z].call(this, value);
} : null, tag.pseudos, accessor[z]);
if (attr) attr.setter = accessor[z];
}
else tag.prototype[prop][z] = accessor[z];
}
function parseAccessor(tag, prop){
tag.prototype[prop] = {};
var accessor = tag.accessors[prop],
attr = accessor.attribute,
name;
if (attr) {
name = attr.name = (attr ? (attr.name || prop.replace(regexCamelToDash, '$1-$2')) : prop).toLowerCase();
attr.key = prop;
tag.attributes[name] = attr;
}
for (var z in accessor) attachProperties(tag, prop, z, accessor, attr, name);
if (attr) {
if (!tag.prototype[prop].get) {
var method = (attr.boolean ? 'has' : 'get') + 'Attribute';
tag.prototype[prop].get = function(){
return this[method](name);
};
}
if (!tag.prototype[prop].set) tag.prototype[prop].set = function(value){
value = attr.boolean ? !!value : attr.validate ? attr.validate.call(this, value) : value;
var method = attr.boolean ? (value ? 'setAttribute' : 'removeAttribute') : 'setAttribute';
modAttr(this, attr, name, value, method);
syncAttr(this, attr, name, value, method);
};
}
}
var unwrapComment = /\/\*!?(?:\@preserve)?[ \t]*(?:\r\n|\n)([\s\S]*?)(?:\r\n|\n)\s*\*\//;
function parseMultiline(fn){
return typeof fn == 'function' ? unwrapComment.exec(fn.toString())[1] : fn;
}
/*** X-Tag Object Definition ***/
var xtag = {
tags: {},
defaultOptions: {
pseudos: [],
mixins: [],
events: {},
methods: {},
accessors: {},
lifecycle: {},
attributes: {},
'prototype': {
xtag: {
get: function(){
return this.__xtag__ ? this.__xtag__ : (this.__xtag__ = { data: {} });
}
}
}
},
register: function (name, options) {
var _name;
if (typeof name == 'string') _name = name.toLowerCase();
else throw 'First argument must be a Custom Element string name';
xtag.tags[_name] = options || {};
var basePrototype = options.prototype;
delete options.prototype;
var tag = xtag.tags[_name].compiled = applyMixins(xtag.merge({}, xtag.defaultOptions, options));
var proto = tag.prototype;
var lifecycle = tag.lifecycle;
for (var z in tag.events) tag.events[z] = xtag.parseEvent(z, tag.events[z]);
for (z in lifecycle) lifecycle[z.split(':')[0]] = xtag.applyPseudos(z, lifecycle[z], tag.pseudos, lifecycle[z]);
for (z in tag.methods) proto[z.split(':')[0]] = { value: xtag.applyPseudos(z, tag.methods[z], tag.pseudos, tag.methods[z]), enumerable: true };
for (z in tag.accessors) parseAccessor(tag, z);
if (tag.shadow) tag.shadow = tag.shadow.nodeName ? tag.shadow : xtag.createFragment(tag.shadow);
if (tag.content) tag.content = tag.content.nodeName ? tag.content.innerHTML : parseMultiline(tag.content);
var created = lifecycle.created;
var finalized = lifecycle.finalized;
proto.createdCallback = {
enumerable: true,
value: function(){
var element = this;
if (tag.shadow && hasShadow) this.createShadowRoot().appendChild(tag.shadow.cloneNode(true));
if (tag.content) this.appendChild(document.createElement('div')).outerHTML = tag.content;
var output = created ? created.apply(this, arguments) : null;
xtag.addEvents(this, tag.events);
for (var name in tag.attributes) {
var attr = tag.attributes[name],
hasAttr = this.hasAttribute(name),
hasDefault = attr.def !== undefined;
if (hasAttr || attr.boolean || hasDefault) {
this[attr.key] = attr.boolean ? hasAttr : !hasAttr && hasDefault ? attr.def : this.getAttribute(name);
}
}
tag.pseudos.forEach(function(obj){
obj.onAdd.call(element, obj);
});
this.xtagComponentReady = true;
if (finalized) finalized.apply(this, arguments);
return output;
}
};
var inserted = lifecycle.inserted;
var removed = lifecycle.removed;
if (inserted || removed) {
proto.attachedCallback = { value: function(){
if (removed) this.xtag.__parentNode__ = this.parentNode;
if (inserted) return inserted.apply(this, arguments);
}, enumerable: true };
}
if (removed) {
proto.detachedCallback = { value: function(){
var args = toArray(arguments);
args.unshift(this.xtag.__parentNode__);
var output = removed.apply(this, args);
delete this.xtag.__parentNode__;
return output;
}, enumerable: true };
}
if (lifecycle.attributeChanged) proto.attributeChangedCallback = { value: lifecycle.attributeChanged, enumerable: true };
proto.setAttribute = {
writable: true,
enumerable: true,
value: function (name, value){
var old;
var _name = name.toLowerCase();
var attr = tag.attributes[_name];
if (attr) {
old = this.getAttribute(_name);
value = attr.boolean ? '' : attr.validate ? attr.validate.call(this, value) : value;
}
modAttr(this, attr, _name, value, 'setAttribute');
if (attr) {
if (attr.setter) attr.setter.call(this, attr.boolean ? true : value, old);
syncAttr(this, attr, _name, value, 'setAttribute');
}
}
};
proto.removeAttribute = {
writable: true,
enumerable: true,
value: function (name){
var _name = name.toLowerCase();
var attr = tag.attributes[_name];
var old = this.hasAttribute(_name);
modAttr(this, attr, _name, '', 'removeAttribute');
if (attr) {
if (attr.setter) attr.setter.call(this, attr.boolean ? false : undefined, old);
syncAttr(this, attr, _name, '', 'removeAttribute');
}
}
};
var definition = {};
var instance = basePrototype instanceof win.HTMLElement;
var extended = tag['extends'] && (definition['extends'] = tag['extends']);
if (basePrototype) Object.getOwnPropertyNames(basePrototype).forEach(function(z){
var prop = proto[z];
var desc = instance ? Object.getOwnPropertyDescriptor(basePrototype, z) : basePrototype[z];
if (prop) {
for (var y in desc) {
if (typeof desc[y] == 'function' && prop[y]) prop[y] = xtag.wrap(desc[y], prop[y]);
else prop[y] = desc[y];
}
}
proto[z] = prop || desc;
});
definition['prototype'] = Object.create(
extended ? Object.create(doc.createElement(extended).constructor).prototype : win.HTMLElement.prototype,
proto
);
return doc.registerElement(_name, definition);
},
/* Exposed Variables */
mixins: {},
prefix: prefix,
captureEvents: { focus: 1, blur: 1, scroll: 1, DOMMouseScroll: 1 },
customEvents: {
animationstart: {
attach: [prefix.dom + 'AnimationStart']
},
animationend: {
attach: [prefix.dom + 'AnimationEnd']
},
transitionend: {
attach: [prefix.dom + 'TransitionEnd']
},
move: {
attach: ['pointermove']
},
enter: {
attach: ['pointerenter']
},
leave: {
attach: ['pointerleave']
},
scrollwheel: {
attach: ['DOMMouseScroll', 'mousewheel'],
condition: function(event){
event.delta = event.wheelDelta ? event.wheelDelta / 40 : Math.round(event.detail / 3.5 * -1);
return true;
}
},
tap: {
attach: ['pointerdown', 'pointerup'],
condition: function(event, custom){
if (event.type == 'pointerdown') {
custom.startX = event.clientX;
custom.startY = event.clientY;
}
else if (event.button === 0 &&
Math.abs(custom.startX - event.clientX) < 10 &&
Math.abs(custom.startY - event.clientY) < 10) return true;
}
},
tapstart: {
attach: ['pointerdown'],
condition: touchFilter
},
tapend: {
attach: ['pointerup'],
condition: touchFilter
},
tapmove: {
attach: ['pointerdown'],
condition: function(event, custom){
if (event.type == 'pointerdown') {
var listener = custom.listener.bind(this);
if (!custom.tapmoveListeners) custom.tapmoveListeners = xtag.addEvents(document, {
pointermove: listener,
pointerup: listener,
pointercancel: listener
});
}
else if (event.type == 'pointerup' || event.type == 'pointercancel') {
xtag.removeEvents(document, custom.tapmoveListeners);
custom.tapmoveListeners = null;
}
return true;
}
},
taphold: {
attach: ['pointerdown', 'pointerup'],
condition: function(event, custom){
if (event.type == 'pointerdown') {
(custom.pointers = custom.pointers || {})[event.pointerId] = setTimeout(
xtag.fireEvent.bind(null, this, 'taphold'),
custom.duration || 1000
);
}
else if (event.type == 'pointerup') {
if (custom.pointers) {
clearTimeout(custom.pointers[event.pointerId]);
delete custom.pointers[event.pointerId];
}
}
else return true;
}
}
},
pseudos: {
__mixin__: {},
mixins: {
onCompiled: function(fn, pseudo){
var mixin = pseudo.source && pseudo.source.__mixin__ || pseudo.source;
if (mixin) switch (pseudo.value) {
case null: case '': case 'before': return function(){
mixin.apply(this, arguments);
return fn.apply(this, arguments);
};
case 'after': return function(){
var returns = fn.apply(this, arguments);
mixin.apply(this, arguments);
return returns;
};
case 'none': return fn;
}
else return fn;
}
},
keypass: keypseudo,
keyfail: keypseudo,
delegate: {
action: delegateAction
},
preventable: {
action: function (pseudo, event) {
return !event.defaultPrevented;
}
},
duration: {
onAdd: function(pseudo){
pseudo.source.duration = Number(pseudo.value);
}
},
capture: {
onCompiled: function(fn, pseudo){
if (pseudo.source) pseudo.source.capture = true;
}
}
},
/* UTILITIES */
clone: clone,
typeOf: typeOf,
toArray: toArray,
wrap: function (original, fn) {
return function(){
var output = original.apply(this, arguments);
fn.apply(this, arguments);
return output;
};
},
/*
Recursively merges one object with another. The first argument is the destination object,
all other objects passed in as arguments are merged from right to left, conflicts are overwritten
*/
merge: function(source, k, v){
if (typeOf(k) == 'string') return mergeOne(source, k, v);
for (var i = 1, l = arguments.length; i < l; i++){
var object = arguments[i];
for (var key in object) mergeOne(source, key, object[key]);
}
return source;
},
/*
----- This should be simplified! -----
Generates a random ID string
*/
uid: function(){
return Math.random().toString(36).substr(2,10);
},
/* DOM */
query: query,
skipTransition: function(element, fn, bind){
var prop = prefix.js + 'TransitionProperty';
element.style[prop] = element.style.transitionProperty = 'none';
var callback = fn ? fn.call(bind || element) : null;
return xtag.skipFrame(function(){
element.style[prop] = element.style.transitionProperty = '';
if (callback) callback.call(bind || element);
});
},
requestFrame: (function(){
var raf = win.requestAnimationFrame ||
win[prefix.lowercase + 'RequestAnimationFrame'] ||
function(fn){ return win.setTimeout(fn, 20); };
return function(fn){ return raf(fn); };
})(),
cancelFrame: (function(){
var cancel = win.cancelAnimationFrame ||
win[prefix.lowercase + 'CancelAnimationFrame'] ||
win.clearTimeout;
return function(id){ return cancel(id); };
})(),
skipFrame: function(fn){
var id = xtag.requestFrame(function(){ id = xtag.requestFrame(fn); });
return id;
},
matchSelector: function (element, selector) {
return matchSelector.call(element, selector);
},
set: function (element, method, value) {
element[method] = value;
if (window.CustomElements) CustomElements.upgradeAll(element);
},
innerHTML: function(el, html){
xtag.set(el, 'innerHTML', html);
},
hasClass: function (element, klass) {
return element.className.split(' ').indexOf(klass.trim())>-1;
},
addClass: function (element, klass) {
var list = element.className.trim().split(' ');
klass.trim().split(' ').forEach(function (name) {
if (!~list.indexOf(name)) list.push(name);
});
element.className = list.join(' ').trim();
return element;
},
removeClass: function (element, klass) {
var classes = klass.trim().split(' ');
element.className = element.className.trim().split(' ').filter(function (name) {
return name && !~classes.indexOf(name);
}).join(' ');
return element;
},
toggleClass: function (element, klass) {
return xtag[xtag.hasClass(element, klass) ? 'removeClass' : 'addClass'].call(null, element, klass);
},
/*
Runs a query on only the children of an element
*/
queryChildren: function (element, selector) {
var id = element.id,
attr = '#' + (element.id = id || 'x_' + xtag.uid()) + ' > ',
parent = element.parentNode || !container.appendChild(element);
selector = attr + (selector + '').replace(regexReplaceCommas, ',' + attr);
var result = element.parentNode.querySelectorAll(selector);
if (!id) element.removeAttribute('id');
if (!parent) container.removeChild(element);
return toArray(result);
},
/*
Creates a document fragment with the content passed in - content can be
a string of HTML, an element, or an array/collection of elements
*/
createFragment: function(content) {
var template = document.createElement('template');
if (content) {
if (content.nodeName) toArray(arguments).forEach(function(e){
template.content.appendChild(e);
});
else template.innerHTML = parseMultiline(content);
}
return document.importNode(template.content, true);
},
/*
Removes an element from the DOM for more performant node manipulation. The element
is placed back into the DOM at the place it was taken from.
*/
manipulate: function(element, fn){
var next = element.nextSibling,
parent = element.parentNode,
returned = fn.call(element) || element;
if (next) parent.insertBefore(returned, next);
else parent.appendChild(returned);
},
/* PSEUDOS */
applyPseudos: function(key, fn, target, source) {
var listener = fn,
pseudos = {};
if (key.match(':')) {
var matches = [],
valueFlag = 0;
key.replace(regexPseudoParens, function(match){
if (match == '(') return ++valueFlag == 1 ? '\u276A' : '(';
return !--valueFlag ? '\u276B' : ')';
}).replace(regexPseudoCapture, function(z, name, value, solo){
matches.push([name || solo, value]);
});
var i = matches.length;
while (i--) parsePseudo(function(){
var name = matches[i][0],
value = matches[i][1];
if (!xtag.pseudos[name]) throw "pseudo not found: " + name + " " + value;
value = (value === '' || typeof value == 'undefined') ? null : value;
var pseudo = pseudos[i] = Object.create(xtag.pseudos[name]);
pseudo.key = key;
pseudo.name = name;
pseudo.value = value;
pseudo['arguments'] = (value || '').split(',');
pseudo.action = pseudo.action || trueop;
pseudo.source = source;
pseudo.onAdd = pseudo.onAdd || noop;
pseudo.onRemove = pseudo.onRemove || noop;
var original = pseudo.listener = listener;
listener = function(){
var output = pseudo.action.apply(this, [pseudo].concat(toArray(arguments)));
if (output === null || output === false) return output;
output = pseudo.listener.apply(this, arguments);
pseudo.listener = original;
return output;
};
if (!target) pseudo.onAdd.call(fn, pseudo);
else target.push(pseudo);
});
}
for (var z in pseudos) {
if (pseudos[z].onCompiled) listener = pseudos[z].onCompiled(listener, pseudos[z]) || listener;
}
return listener;
},
removePseudos: function(target, pseudos){
pseudos.forEach(function(obj){
obj.onRemove.call(target, obj);
});
},
/*** Events ***/
parseEvent: function(type, fn) {
var pseudos = type.split(':'),
key = pseudos.shift(),
custom = xtag.customEvents[key],
event = xtag.merge({
type: key,
stack: noop,
condition: trueop,
capture: xtag.captureEvents[key],
attach: [],
_attach: [],
pseudos: '',
_pseudos: [],
onAdd: noop,
onRemove: noop
}, custom || {});
event.attach = toArray(event.base || event.attach);
event.chain = key + (event.pseudos.length ? ':' + event.pseudos : '') + (pseudos.length ? ':' + pseudos.join(':') : '');
var stack = xtag.applyPseudos(event.chain, fn, event._pseudos, event);
event.stack = function(e){
e.currentTarget = e.currentTarget || this;
var detail = e.detail || {};
if (!detail.__stack__) return stack.apply(this, arguments);
else if (detail.__stack__ == stack) {
e.stopPropagation();
e.cancelBubble = true;
return stack.apply(this, arguments);
}
};
event.listener = function(e){
var args = toArray(arguments),
output = event.condition.apply(this, args.concat([event]));
if (!output) return output;
// The second condition in this IF is to address the following Blink regression: https://code.google.com/p/chromium/issues/detail?id=367537
// Remove this when affected browser builds with this regression fall below 5% marketshare
if (e.type != key && (e.baseEvent && e.type != e.baseEvent.type)) {
xtag.fireEvent(e.target, key, {
baseEvent: e,
detail: output !== true && (output.__stack__ = stack) ? output : { __stack__: stack }
});
}
else return event.stack.apply(this, args);
};
event.attach.forEach(function(name) {
event._attach.push(xtag.parseEvent(name, event.listener));
});
return event;
},
addEvent: function (element, type, fn, capture) {
var event = typeof fn == 'function' ? xtag.parseEvent(type, fn) : fn;
event._pseudos.forEach(function(obj){
obj.onAdd.call(element, obj);
});
event._attach.forEach(function(obj) {
xtag.addEvent(element, obj.type, obj);
});
event.onAdd.call(element, event, event.listener);
element.addEventListener(event.type, event.stack, capture || event.capture);
return event;
},
addEvents: function (element, obj) {
var events = {};
for (var z in obj) {
events[z] = xtag.addEvent(element, z, obj[z]);
}
return events;
},
removeEvent: function (element, type, event) {
event = event || type;
event.onRemove.call(element, event, event.listener);
xtag.removePseudos(element, event._pseudos);
event._attach.forEach(function(obj) {
xtag.removeEvent(element, obj);
});
element.removeEventListener(event.type, event.stack);
},
removeEvents: function(element, obj){
for (var z in obj) xtag.removeEvent(element, obj[z]);
},
fireEvent: function(element, type, options){
var event = doc.createEvent('CustomEvent');
options = options || {};
event.initCustomEvent(type,
options.bubbles !== false,
options.cancelable !== false,
options.detail
);
if (options.baseEvent) inheritEvent(event, options.baseEvent);
element.dispatchEvent(event);
}
};
if (typeof define === 'function' && define.amd) define(xtag);
else if (typeof module !== 'undefined' && module.exports) module.exports = xtag;
else win.xtag = xtag;
doc.addEventListener('WebComponentsReady', function(){
xtag.fireEvent(doc.body, 'DOMComponentsLoaded');
});
})();
| rlugojr/cdnjs | ajax/libs/x-tag/1.5.10/x-tag-no-polyfills.js | JavaScript | mit | 30,690 |
/*
* linux/kernel/irq/chip.c
*
* Copyright (C) 1992, 1998-2006 Linus Torvalds, Ingo Molnar
* Copyright (C) 2005-2006, Thomas Gleixner, Russell King
*
* This file contains the core interrupt handling code, for irq-chip
* based architectures.
*
* Detailed information is available in Documentation/DocBook/genericirq
*/
#include <linux/irq.h>
#include <linux/msi.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/kernel_stat.h>
#include "internals.h"
static void dynamic_irq_init_x(unsigned int irq, bool keep_chip_data)
{
struct irq_desc *desc;
unsigned long flags;
desc = irq_to_desc(irq);
if (!desc) {
WARN(1, KERN_ERR "Trying to initialize invalid IRQ%d\n", irq);
return;
}
/* Ensure we don't have left over values from a previous use of this irq */
raw_spin_lock_irqsave(&desc->lock, flags);
desc->status = IRQ_DISABLED;
desc->chip = &no_irq_chip;
desc->handle_irq = handle_bad_irq;
desc->depth = 1;
desc->msi_desc = NULL;
desc->handler_data = NULL;
if (!keep_chip_data)
desc->chip_data = NULL;
desc->action = NULL;
desc->irq_count = 0;
desc->irqs_unhandled = 0;
#ifdef CONFIG_SMP
cpumask_setall(desc->affinity);
#ifdef CONFIG_GENERIC_PENDING_IRQ
cpumask_clear(desc->pending_mask);
#endif
#endif
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
/**
* dynamic_irq_init - initialize a dynamically allocated irq
* @irq: irq number to initialize
*/
void dynamic_irq_init(unsigned int irq)
{
dynamic_irq_init_x(irq, false);
}
/**
* dynamic_irq_init_keep_chip_data - initialize a dynamically allocated irq
* @irq: irq number to initialize
*
* does not set irq_to_desc(irq)->chip_data to NULL
*/
void dynamic_irq_init_keep_chip_data(unsigned int irq)
{
dynamic_irq_init_x(irq, true);
}
static void dynamic_irq_cleanup_x(unsigned int irq, bool keep_chip_data)
{
struct irq_desc *desc = irq_to_desc(irq);
unsigned long flags;
if (!desc) {
WARN(1, KERN_ERR "Trying to cleanup invalid IRQ%d\n", irq);
return;
}
raw_spin_lock_irqsave(&desc->lock, flags);
if (desc->action) {
raw_spin_unlock_irqrestore(&desc->lock, flags);
WARN(1, KERN_ERR "Destroying IRQ%d without calling free_irq\n",
irq);
return;
}
desc->msi_desc = NULL;
desc->handler_data = NULL;
if (!keep_chip_data)
desc->chip_data = NULL;
desc->handle_irq = handle_bad_irq;
desc->chip = &no_irq_chip;
desc->name = NULL;
clear_kstat_irqs(desc);
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
/**
* dynamic_irq_cleanup - cleanup a dynamically allocated irq
* @irq: irq number to initialize
*/
void dynamic_irq_cleanup(unsigned int irq)
{
dynamic_irq_cleanup_x(irq, false);
}
/**
* dynamic_irq_cleanup_keep_chip_data - cleanup a dynamically allocated irq
* @irq: irq number to initialize
*
* does not set irq_to_desc(irq)->chip_data to NULL
*/
void dynamic_irq_cleanup_keep_chip_data(unsigned int irq)
{
dynamic_irq_cleanup_x(irq, true);
}
/**
* set_irq_chip - set the irq chip for an irq
* @irq: irq number
* @chip: pointer to irq chip description structure
*/
int set_irq_chip(unsigned int irq, struct irq_chip *chip)
{
struct irq_desc *desc = irq_to_desc(irq);
unsigned long flags;
if (!desc) {
WARN(1, KERN_ERR "Trying to install chip for IRQ%d\n", irq);
return -EINVAL;
}
if (!chip)
chip = &no_irq_chip;
raw_spin_lock_irqsave(&desc->lock, flags);
irq_chip_set_defaults(chip);
desc->chip = chip;
raw_spin_unlock_irqrestore(&desc->lock, flags);
return 0;
}
EXPORT_SYMBOL(set_irq_chip);
/**
* set_irq_type - set the irq trigger type for an irq
* @irq: irq number
* @type: IRQ_TYPE_{LEVEL,EDGE}_* value - see include/linux/irq.h
*/
int set_irq_type(unsigned int irq, unsigned int type)
{
struct irq_desc *desc = irq_to_desc(irq);
unsigned long flags;
int ret = -ENXIO;
if (!desc) {
printk(KERN_ERR "Trying to set irq type for IRQ%d\n", irq);
return -ENODEV;
}
type &= IRQ_TYPE_SENSE_MASK;
if (type == IRQ_TYPE_NONE)
return 0;
raw_spin_lock_irqsave(&desc->lock, flags);
ret = __irq_set_trigger(desc, irq, type);
raw_spin_unlock_irqrestore(&desc->lock, flags);
return ret;
}
EXPORT_SYMBOL(set_irq_type);
/**
* set_irq_data - set irq type data for an irq
* @irq: Interrupt number
* @data: Pointer to interrupt specific data
*
* Set the hardware irq controller data for an irq
*/
int set_irq_data(unsigned int irq, void *data)
{
struct irq_desc *desc = irq_to_desc(irq);
unsigned long flags;
if (!desc) {
printk(KERN_ERR
"Trying to install controller data for IRQ%d\n", irq);
return -EINVAL;
}
raw_spin_lock_irqsave(&desc->lock, flags);
desc->handler_data = data;
raw_spin_unlock_irqrestore(&desc->lock, flags);
return 0;
}
EXPORT_SYMBOL(set_irq_data);
/**
* set_irq_msi - set MSI descriptor data for an irq
* @irq: Interrupt number
* @entry: Pointer to MSI descriptor data
*
* Set the MSI descriptor entry for an irq
*/
int set_irq_msi(unsigned int irq, struct msi_desc *entry)
{
struct irq_desc *desc = irq_to_desc(irq);
unsigned long flags;
if (!desc) {
printk(KERN_ERR
"Trying to install msi data for IRQ%d\n", irq);
return -EINVAL;
}
raw_spin_lock_irqsave(&desc->lock, flags);
desc->msi_desc = entry;
if (entry)
entry->irq = irq;
raw_spin_unlock_irqrestore(&desc->lock, flags);
return 0;
}
/**
* set_irq_chip_data - set irq chip data for an irq
* @irq: Interrupt number
* @data: Pointer to chip specific data
*
* Set the hardware irq chip data for an irq
*/
int set_irq_chip_data(unsigned int irq, void *data)
{
struct irq_desc *desc = irq_to_desc(irq);
unsigned long flags;
if (!desc) {
printk(KERN_ERR
"Trying to install chip data for IRQ%d\n", irq);
return -EINVAL;
}
if (!desc->chip) {
printk(KERN_ERR "BUG: bad set_irq_chip_data(IRQ#%d)\n", irq);
return -EINVAL;
}
raw_spin_lock_irqsave(&desc->lock, flags);
desc->chip_data = data;
raw_spin_unlock_irqrestore(&desc->lock, flags);
return 0;
}
EXPORT_SYMBOL(set_irq_chip_data);
/**
* set_irq_nested_thread - Set/Reset the IRQ_NESTED_THREAD flag of an irq
*
* @irq: Interrupt number
* @nest: 0 to clear / 1 to set the IRQ_NESTED_THREAD flag
*
* The IRQ_NESTED_THREAD flag indicates that on
* request_threaded_irq() no separate interrupt thread should be
* created for the irq as the handler are called nested in the
* context of a demultiplexing interrupt handler thread.
*/
void set_irq_nested_thread(unsigned int irq, int nest)
{
struct irq_desc *desc = irq_to_desc(irq);
unsigned long flags;
if (!desc)
return;
raw_spin_lock_irqsave(&desc->lock, flags);
if (nest)
desc->status |= IRQ_NESTED_THREAD;
else
desc->status &= ~IRQ_NESTED_THREAD;
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
EXPORT_SYMBOL_GPL(set_irq_nested_thread);
/*
* default enable function
*/
static void default_enable(unsigned int irq)
{
struct irq_desc *desc = irq_to_desc(irq);
desc->chip->unmask(irq);
desc->status &= ~IRQ_MASKED;
}
/*
* default disable function
*/
static void default_disable(unsigned int irq)
{
}
/*
* default startup function
*/
static unsigned int default_startup(unsigned int irq)
{
struct irq_desc *desc = irq_to_desc(irq);
desc->chip->enable(irq);
return 0;
}
/*
* default shutdown function
*/
static void default_shutdown(unsigned int irq)
{
struct irq_desc *desc = irq_to_desc(irq);
desc->chip->mask(irq);
desc->status |= IRQ_MASKED;
}
/*
* Fixup enable/disable function pointers
*/
void irq_chip_set_defaults(struct irq_chip *chip)
{
if (!chip->enable)
chip->enable = default_enable;
if (!chip->disable)
chip->disable = default_disable;
if (!chip->startup)
chip->startup = default_startup;
/*
* We use chip->disable, when the user provided its own. When
* we have default_disable set for chip->disable, then we need
* to use default_shutdown, otherwise the irq line is not
* disabled on free_irq():
*/
if (!chip->shutdown)
chip->shutdown = chip->disable != default_disable ?
chip->disable : default_shutdown;
if (!chip->name)
chip->name = chip->typename;
if (!chip->end)
chip->end = dummy_irq_chip.end;
}
static inline void mask_ack_irq(struct irq_desc *desc, int irq)
{
if (desc->chip->mask_ack)
desc->chip->mask_ack(irq);
else {
desc->chip->mask(irq);
if (desc->chip->ack)
desc->chip->ack(irq);
}
desc->status |= IRQ_MASKED;
}
static inline void mask_irq(struct irq_desc *desc, int irq)
{
if (desc->chip->mask) {
desc->chip->mask(irq);
desc->status |= IRQ_MASKED;
}
}
static inline void unmask_irq(struct irq_desc *desc, int irq)
{
if (desc->chip->unmask) {
desc->chip->unmask(irq);
desc->status &= ~IRQ_MASKED;
}
}
/*
* handle_nested_irq - Handle a nested irq from a irq thread
* @irq: the interrupt number
*
* Handle interrupts which are nested into a threaded interrupt
* handler. The handler function is called inside the calling
* threads context.
*/
void handle_nested_irq(unsigned int irq)
{
struct irq_desc *desc = irq_to_desc(irq);
struct irqaction *action;
int mask_this_irq = 0;
irqreturn_t action_ret;
might_sleep();
raw_spin_lock_irq(&desc->lock);
kstat_incr_irqs_this_cpu(irq, desc);
action = desc->action;
if (unlikely(!action || (desc->status & IRQ_DISABLED))) {
mask_this_irq = 1;
if (!(desc->status & IRQ_LEVEL))
desc->status |= IRQ_PENDING;
goto out_unlock;
}
desc->status |= IRQ_INPROGRESS;
raw_spin_unlock_irq(&desc->lock);
action_ret = action->thread_fn(action->irq, action->dev_id);
if (!noirqdebug)
note_interrupt(irq, desc, action_ret);
raw_spin_lock_irq(&desc->lock);
desc->status &= ~IRQ_INPROGRESS;
out_unlock:
if (unlikely(mask_this_irq)) {
chip_bus_lock(irq, desc);
mask_irq(desc, irq);
chip_bus_sync_unlock(irq, desc);
}
raw_spin_unlock_irq(&desc->lock);
}
EXPORT_SYMBOL_GPL(handle_nested_irq);
/**
* handle_simple_irq - Simple and software-decoded IRQs.
* @irq: the interrupt number
* @desc: the interrupt description structure for this irq
*
* Simple interrupts are either sent from a demultiplexing interrupt
* handler or come from hardware, where no interrupt hardware control
* is necessary.
*
* Note: The caller is expected to handle the ack, clear, mask and
* unmask issues if necessary.
*/
void
handle_simple_irq(unsigned int irq, struct irq_desc *desc)
{
struct irqaction *action;
irqreturn_t action_ret;
raw_spin_lock(&desc->lock);
if (unlikely(desc->status & IRQ_INPROGRESS))
goto out_unlock;
desc->status &= ~(IRQ_REPLAY | IRQ_WAITING);
kstat_incr_irqs_this_cpu(irq, desc);
action = desc->action;
if (unlikely(!action || (desc->status & IRQ_DISABLED)))
goto out_unlock;
desc->status |= IRQ_INPROGRESS;
raw_spin_unlock(&desc->lock);
action_ret = handle_IRQ_event(irq, action);
if (!noirqdebug)
note_interrupt(irq, desc, action_ret);
raw_spin_lock(&desc->lock);
desc->status &= ~IRQ_INPROGRESS;
out_unlock:
raw_spin_unlock(&desc->lock);
}
/**
* handle_level_irq - Level type irq handler
* @irq: the interrupt number
* @desc: the interrupt description structure for this irq
*
* Level type interrupts are active as long as the hardware line has
* the active level. This may require to mask the interrupt and unmask
* it after the associated handler has acknowledged the device, so the
* interrupt line is back to inactive.
*/
void
handle_level_irq(unsigned int irq, struct irq_desc *desc)
{
struct irqaction *action;
irqreturn_t action_ret;
raw_spin_lock(&desc->lock);
mask_ack_irq(desc, irq);
if (unlikely(desc->status & IRQ_INPROGRESS))
goto out_unlock;
desc->status &= ~(IRQ_REPLAY | IRQ_WAITING);
kstat_incr_irqs_this_cpu(irq, desc);
/*
* If its disabled or no action available
* keep it masked and get out of here
*/
action = desc->action;
if (unlikely(!action || (desc->status & IRQ_DISABLED)))
goto out_unlock;
desc->status |= IRQ_INPROGRESS;
raw_spin_unlock(&desc->lock);
action_ret = handle_IRQ_event(irq, action);
if (!noirqdebug)
note_interrupt(irq, desc, action_ret);
raw_spin_lock(&desc->lock);
desc->status &= ~IRQ_INPROGRESS;
if (!(desc->status & (IRQ_DISABLED | IRQ_ONESHOT)))
unmask_irq(desc, irq);
out_unlock:
raw_spin_unlock(&desc->lock);
}
EXPORT_SYMBOL_GPL(handle_level_irq);
/**
* handle_fasteoi_irq - irq handler for transparent controllers
* @irq: the interrupt number
* @desc: the interrupt description structure for this irq
*
* Only a single callback will be issued to the chip: an ->eoi()
* call when the interrupt has been serviced. This enables support
* for modern forms of interrupt handlers, which handle the flow
* details in hardware, transparently.
*/
void
handle_fasteoi_irq(unsigned int irq, struct irq_desc *desc)
{
struct irqaction *action;
irqreturn_t action_ret;
raw_spin_lock(&desc->lock);
if (unlikely(desc->status & IRQ_INPROGRESS))
goto out;
desc->status &= ~(IRQ_REPLAY | IRQ_WAITING);
kstat_incr_irqs_this_cpu(irq, desc);
/*
* If its disabled or no action available
* then mask it and get out of here:
*/
action = desc->action;
if (unlikely(!action || (desc->status & IRQ_DISABLED))) {
desc->status |= IRQ_PENDING;
mask_irq(desc, irq);
goto out;
}
desc->status |= IRQ_INPROGRESS;
desc->status &= ~IRQ_PENDING;
raw_spin_unlock(&desc->lock);
action_ret = handle_IRQ_event(irq, action);
if (!noirqdebug)
note_interrupt(irq, desc, action_ret);
raw_spin_lock(&desc->lock);
desc->status &= ~IRQ_INPROGRESS;
out:
desc->chip->eoi(irq);
raw_spin_unlock(&desc->lock);
}
/**
* handle_edge_irq - edge type IRQ handler
* @irq: the interrupt number
* @desc: the interrupt description structure for this irq
*
* Interrupt occures on the falling and/or rising edge of a hardware
* signal. The occurence is latched into the irq controller hardware
* and must be acked in order to be reenabled. After the ack another
* interrupt can happen on the same source even before the first one
* is handled by the associated event handler. If this happens it
* might be necessary to disable (mask) the interrupt depending on the
* controller hardware. This requires to reenable the interrupt inside
* of the loop which handles the interrupts which have arrived while
* the handler was running. If all pending interrupts are handled, the
* loop is left.
*/
void
handle_edge_irq(unsigned int irq, struct irq_desc *desc)
{
raw_spin_lock(&desc->lock);
desc->status &= ~(IRQ_REPLAY | IRQ_WAITING);
/*
* If we're currently running this IRQ, or its disabled,
* we shouldn't process the IRQ. Mark it pending, handle
* the necessary masking and go out
*/
if (unlikely((desc->status & (IRQ_INPROGRESS | IRQ_DISABLED)) ||
!desc->action)) {
desc->status |= (IRQ_PENDING | IRQ_MASKED);
mask_ack_irq(desc, irq);
goto out_unlock;
}
kstat_incr_irqs_this_cpu(irq, desc);
/* Start handling the irq */
if (desc->chip->ack)
desc->chip->ack(irq);
/* Mark the IRQ currently in progress.*/
desc->status |= IRQ_INPROGRESS;
do {
struct irqaction *action = desc->action;
irqreturn_t action_ret;
if (unlikely(!action)) {
mask_irq(desc, irq);
goto out_unlock;
}
/*
* When another irq arrived while we were handling
* one, we could have masked the irq.
* Renable it, if it was not disabled in meantime.
*/
if (unlikely((desc->status &
(IRQ_PENDING | IRQ_MASKED | IRQ_DISABLED)) ==
(IRQ_PENDING | IRQ_MASKED))) {
unmask_irq(desc, irq);
}
desc->status &= ~IRQ_PENDING;
raw_spin_unlock(&desc->lock);
action_ret = handle_IRQ_event(irq, action);
if (!noirqdebug)
note_interrupt(irq, desc, action_ret);
raw_spin_lock(&desc->lock);
} while ((desc->status & (IRQ_PENDING | IRQ_DISABLED)) == IRQ_PENDING);
desc->status &= ~IRQ_INPROGRESS;
out_unlock:
raw_spin_unlock(&desc->lock);
}
/**
* handle_percpu_irq - Per CPU local irq handler
* @irq: the interrupt number
* @desc: the interrupt description structure for this irq
*
* Per CPU interrupts on SMP machines without locking requirements
*/
void
handle_percpu_irq(unsigned int irq, struct irq_desc *desc)
{
irqreturn_t action_ret;
kstat_incr_irqs_this_cpu(irq, desc);
if (desc->chip->ack)
desc->chip->ack(irq);
action_ret = handle_IRQ_event(irq, desc->action);
if (!noirqdebug)
note_interrupt(irq, desc, action_ret);
if (desc->chip->eoi)
desc->chip->eoi(irq);
}
void
__set_irq_handler(unsigned int irq, irq_flow_handler_t handle, int is_chained,
const char *name)
{
struct irq_desc *desc = irq_to_desc(irq);
unsigned long flags;
if (!desc) {
printk(KERN_ERR
"Trying to install type control for IRQ%d\n", irq);
return;
}
if (!handle)
handle = handle_bad_irq;
else if (desc->chip == &no_irq_chip) {
printk(KERN_WARNING "Trying to install %sinterrupt handler "
"for IRQ%d\n", is_chained ? "chained " : "", irq);
/*
* Some ARM implementations install a handler for really dumb
* interrupt hardware without setting an irq_chip. This worked
* with the ARM no_irq_chip but the check in setup_irq would
* prevent us to setup the interrupt at all. Switch it to
* dummy_irq_chip for easy transition.
*/
desc->chip = &dummy_irq_chip;
}
chip_bus_lock(irq, desc);
raw_spin_lock_irqsave(&desc->lock, flags);
/* Uninstall? */
if (handle == handle_bad_irq) {
if (desc->chip != &no_irq_chip)
mask_ack_irq(desc, irq);
desc->status |= IRQ_DISABLED;
desc->depth = 1;
}
desc->handle_irq = handle;
desc->name = name;
if (handle != handle_bad_irq && is_chained) {
desc->status &= ~IRQ_DISABLED;
desc->status |= IRQ_NOREQUEST | IRQ_NOPROBE;
desc->depth = 0;
desc->chip->startup(irq);
}
raw_spin_unlock_irqrestore(&desc->lock, flags);
chip_bus_sync_unlock(irq, desc);
}
EXPORT_SYMBOL_GPL(__set_irq_handler);
void
set_irq_chip_and_handler(unsigned int irq, struct irq_chip *chip,
irq_flow_handler_t handle)
{
set_irq_chip(irq, chip);
__set_irq_handler(irq, handle, 0, NULL);
}
void
set_irq_chip_and_handler_name(unsigned int irq, struct irq_chip *chip,
irq_flow_handler_t handle, const char *name)
{
set_irq_chip(irq, chip);
__set_irq_handler(irq, handle, 0, name);
}
void set_irq_noprobe(unsigned int irq)
{
struct irq_desc *desc = irq_to_desc(irq);
unsigned long flags;
if (!desc) {
printk(KERN_ERR "Trying to mark IRQ%d non-probeable\n", irq);
return;
}
raw_spin_lock_irqsave(&desc->lock, flags);
desc->status |= IRQ_NOPROBE;
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
void set_irq_probe(unsigned int irq)
{
struct irq_desc *desc = irq_to_desc(irq);
unsigned long flags;
if (!desc) {
printk(KERN_ERR "Trying to mark IRQ%d probeable\n", irq);
return;
}
raw_spin_lock_irqsave(&desc->lock, flags);
desc->status &= ~IRQ_NOPROBE;
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
| droidzone/Supernova-Kernel | kernel/kernel/irq/chip.c | C | gpl-2.0 | 18,719 |
/*
Copyright (c) 2007-2015 Contributors as noted in the AUTHORS file
This file is part of libzmq, the ZeroMQ core engine in C++.
libzmq is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
As a special exception, the Contributors give you permission to link
this library with independent modules to produce an executable,
regardless of the license terms of these independent modules, and to
copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the
terms and conditions of the license of that module. An independent
module is a module which is not derived from or based on this library.
If you modify this library, you must extend this exception to your
version of the library.
libzmq 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 program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "testutil.hpp"
const char *bind_address = 0;
const char *connect_address = 0;
void test_round_robin_out (void *ctx)
{
void *dealer = zmq_socket (ctx, ZMQ_DEALER);
assert (dealer);
int rc = zmq_bind (dealer, bind_address);
assert (rc == 0);
const size_t services = 5;
void *rep [services];
for (size_t peer = 0; peer < services; ++peer) {
rep [peer] = zmq_socket (ctx, ZMQ_REP);
assert (rep [peer]);
int timeout = 250;
rc = zmq_setsockopt (rep [peer], ZMQ_RCVTIMEO, &timeout, sizeof (int));
assert (rc == 0);
rc = zmq_connect (rep [peer], connect_address);
assert (rc == 0);
}
// Wait for connections.
rc = zmq_poll (0, 0, 100);
assert (rc == 0);
// Send all requests
for (size_t i = 0; i < services; ++i)
s_send_seq (dealer, 0, "ABC", SEQ_END);
// Expect every REP got one message
zmq_msg_t msg;
zmq_msg_init (&msg);
for (size_t peer = 0; peer < services; ++peer)
s_recv_seq (rep [peer], "ABC", SEQ_END);
rc = zmq_msg_close (&msg);
assert (rc == 0);
close_zero_linger (dealer);
for (size_t peer = 0; peer < services; ++peer)
close_zero_linger (rep [peer]);
// Wait for disconnects.
rc = zmq_poll (0, 0, 100);
assert (rc == 0);
}
void test_fair_queue_in (void *ctx)
{
void *receiver = zmq_socket (ctx, ZMQ_DEALER);
assert (receiver);
int timeout = 250;
int rc = zmq_setsockopt (receiver, ZMQ_RCVTIMEO, &timeout, sizeof (int));
assert (rc == 0);
rc = zmq_bind (receiver, bind_address);
assert (rc == 0);
const size_t services = 5;
void *senders [services];
for (size_t peer = 0; peer < services; ++peer) {
senders [peer] = zmq_socket (ctx, ZMQ_DEALER);
assert (senders [peer]);
rc = zmq_setsockopt (senders [peer], ZMQ_RCVTIMEO, &timeout, sizeof (int));
assert (rc == 0);
rc = zmq_connect (senders [peer], connect_address);
assert (rc == 0);
}
zmq_msg_t msg;
rc = zmq_msg_init (&msg);
assert (rc == 0);
s_send_seq (senders [0], "A", SEQ_END);
s_recv_seq (receiver, "A", SEQ_END);
s_send_seq (senders [0], "A", SEQ_END);
s_recv_seq (receiver, "A", SEQ_END);
// send our requests
for (size_t peer = 0; peer < services; ++peer)
s_send_seq (senders [peer], "B", SEQ_END);
// Wait for data.
rc = zmq_poll (0, 0, 50);
assert (rc == 0);
// handle the requests
for (size_t peer = 0; peer < services; ++peer)
s_recv_seq (receiver, "B", SEQ_END);
rc = zmq_msg_close (&msg);
assert (rc == 0);
close_zero_linger (receiver);
for (size_t peer = 0; peer < services; ++peer)
close_zero_linger (senders [peer]);
// Wait for disconnects.
rc = zmq_poll (0, 0, 100);
assert (rc == 0);
}
void test_destroy_queue_on_disconnect (void *ctx)
{
void *A = zmq_socket (ctx, ZMQ_DEALER);
assert (A);
int rc = zmq_bind (A, bind_address);
assert (rc == 0);
void *B = zmq_socket (ctx, ZMQ_DEALER);
assert (B);
rc = zmq_connect (B, connect_address);
assert (rc == 0);
// Send a message in both directions
s_send_seq (A, "ABC", SEQ_END);
s_send_seq (B, "DEF", SEQ_END);
rc = zmq_disconnect (B, connect_address);
assert (rc == 0);
// Disconnect may take time and need command processing.
zmq_pollitem_t poller [2] = { { A, 0, 0, 0 }, { B, 0, 0, 0 } };
rc = zmq_poll (poller, 2, 100);
assert (rc == 0);
rc = zmq_poll (poller, 2, 100);
assert (rc == 0);
// No messages should be available, sending should fail.
zmq_msg_t msg;
zmq_msg_init (&msg);
rc = zmq_send (A, 0, 0, ZMQ_DONTWAIT);
assert (rc == -1);
assert (errno == EAGAIN);
rc = zmq_msg_recv (&msg, A, ZMQ_DONTWAIT);
assert (rc == -1);
assert (errno == EAGAIN);
// After a reconnect of B, the messages should still be gone
rc = zmq_connect (B, connect_address);
assert (rc == 0);
rc = zmq_msg_recv (&msg, A, ZMQ_DONTWAIT);
assert (rc == -1);
assert (errno == EAGAIN);
rc = zmq_msg_recv (&msg, B, ZMQ_DONTWAIT);
assert (rc == -1);
assert (errno == EAGAIN);
rc = zmq_msg_close (&msg);
assert (rc == 0);
close_zero_linger (A);
close_zero_linger (B);
// Wait for disconnects.
rc = zmq_poll (0, 0, 100);
assert (rc == 0);
}
void test_block_on_send_no_peers (void *ctx)
{
void *sc = zmq_socket (ctx, ZMQ_DEALER);
assert (sc);
int timeout = 250;
int rc = zmq_setsockopt (sc, ZMQ_SNDTIMEO, &timeout, sizeof (timeout));
assert (rc == 0);
rc = zmq_send (sc, 0, 0, ZMQ_DONTWAIT);
assert (rc == -1);
assert (errno == EAGAIN);
rc = zmq_send (sc, 0, 0, 0);
assert (rc == -1);
assert (errno == EAGAIN);
rc = zmq_close (sc);
assert (rc == 0);
}
int main (void)
{
setup_test_environment();
void *ctx = zmq_ctx_new ();
assert (ctx);
const char *binds [] = { "inproc://a", "tcp://127.0.0.1:5555" };
const char *connects [] = { "inproc://a", "tcp://localhost:5555" };
for (int transports = 0; transports < 2; ++transports) {
bind_address = binds [transports];
connect_address = connects [transports];
// SHALL route outgoing messages to available peers using a round-robin
// strategy.
test_round_robin_out (ctx);
// SHALL receive incoming messages from its peers using a fair-queuing
// strategy.
test_fair_queue_in (ctx);
// SHALL block on sending, or return a suitable error, when it has no connected peers.
test_block_on_send_no_peers (ctx);
// SHALL create a double queue when a peer connects to it. If this peer
// disconnects, the DEALER socket SHALL destroy its double queue and SHALL
// discard any messages it contains.
// *** Test disabled until libzmq does this properly ***
// test_destroy_queue_on_disconnect (ctx);
}
int rc = zmq_ctx_term (ctx);
assert (rc == 0);
return 0 ;
}
| madpilot78/ntopng | third-party/zeromq-4.1.7/tests/test_spec_dealer.cpp | C++ | gpl-3.0 | 7,543 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview New tab page
* This is the main code for the new tab page used by touch-enabled Chrome
* browsers. For now this is still a prototype.
*/
// Use an anonymous function to enable strict mode just for this file (which
// will be concatenated with other files when embedded in Chrome
cr.define('ntp', function() {
'use strict';
/**
* NewTabView instance.
* @type {!Object|undefined}
*/
var newTabView;
/**
* The 'notification-container' element.
* @type {!Element|undefined}
*/
var notificationContainer;
/**
* If non-null, an info bubble for showing messages to the user. It points at
* the Most Visited label, and is used to draw more attention to the
* navigation dot UI.
* @type {!Element|undefined}
*/
var promoBubble;
/**
* If non-null, an bubble confirming that the user has signed into sync. It
* points at the login status at the top of the page.
* @type {!Element|undefined}
*/
var loginBubble;
/**
* true if |loginBubble| should be shown.
* @type {boolean}
*/
var shouldShowLoginBubble = false;
/**
* The 'other-sessions-menu-button' element.
* @type {!Element|undefined}
*/
var otherSessionsButton;
/**
* The time when all sections are ready.
* @type {number|undefined}
* @private
*/
var startTime;
/**
* The time in milliseconds for most transitions. This should match what's
* in new_tab.css. Unfortunately there's no better way to try to time
* something to occur until after a transition has completed.
* @type {number}
* @const
*/
var DEFAULT_TRANSITION_TIME = 500;
/**
* See description for these values in ntp_stats.h.
* @enum {number}
*/
var NtpFollowAction = {
CLICKED_TILE: 11,
CLICKED_OTHER_NTP_PANE: 12,
OTHER: 13
};
/**
* Creates a NewTabView object. NewTabView extends PageListView with
* new tab UI specific logics.
* @constructor
* @extends {PageListView}
*/
function NewTabView() {
var pageSwitcherStart = null;
var pageSwitcherEnd = null;
if (loadTimeData.getValue('showApps')) {
pageSwitcherStart = getRequiredElement('page-switcher-start');
pageSwitcherEnd = getRequiredElement('page-switcher-end');
}
this.initialize(getRequiredElement('page-list'),
getRequiredElement('dot-list'),
getRequiredElement('card-slider-frame'),
getRequiredElement('trash'),
pageSwitcherStart, pageSwitcherEnd);
}
NewTabView.prototype = {
__proto__: ntp.PageListView.prototype,
/** @override */
appendTilePage: function(page, title, titleIsEditable, opt_refNode) {
ntp.PageListView.prototype.appendTilePage.apply(this, arguments);
if (promoBubble)
window.setTimeout(promoBubble.reposition.bind(promoBubble), 0);
}
};
/**
* Invoked at startup once the DOM is available to initialize the app.
*/
function onLoad() {
sectionsToWaitFor = 0;
if (loadTimeData.getBoolean('showMostvisited'))
sectionsToWaitFor++;
if (loadTimeData.getBoolean('showApps')) {
sectionsToWaitFor++;
if (loadTimeData.getBoolean('showAppLauncherPromo')) {
$('app-launcher-promo-close-button').addEventListener('click',
function() { chrome.send('stopShowingAppLauncherPromo'); });
$('apps-promo-learn-more').addEventListener('click',
function() { chrome.send('onLearnMore'); });
}
}
if (loadTimeData.getBoolean('isDiscoveryInNTPEnabled'))
sectionsToWaitFor++;
measureNavDots();
// Load the current theme colors.
themeChanged();
newTabView = new NewTabView();
notificationContainer = getRequiredElement('notification-container');
notificationContainer.addEventListener(
'webkitTransitionEnd', onNotificationTransitionEnd);
if (loadTimeData.getBoolean('showRecentlyClosed')) {
cr.ui.decorate($('recently-closed-menu-button'), ntp.RecentMenuButton);
chrome.send('getRecentlyClosedTabs');
} else {
$('recently-closed-menu-button').hidden = true;
}
if (loadTimeData.getBoolean('showOtherSessionsMenu')) {
otherSessionsButton = getRequiredElement('other-sessions-menu-button');
cr.ui.decorate(otherSessionsButton, ntp.OtherSessionsMenuButton);
otherSessionsButton.initialize(loadTimeData.getBoolean('isUserSignedIn'));
} else {
getRequiredElement('other-sessions-menu-button').hidden = true;
}
if (loadTimeData.getBoolean('showMostvisited')) {
var mostVisited = new ntp.MostVisitedPage();
// Move the footer into the most visited page if we are in "bare minimum"
// mode.
if (document.body.classList.contains('bare-minimum'))
mostVisited.appendFooter(getRequiredElement('footer'));
newTabView.appendTilePage(mostVisited,
loadTimeData.getString('mostvisited'),
false);
chrome.send('getMostVisited');
}
if (loadTimeData.getBoolean('isDiscoveryInNTPEnabled')) {
var suggestionsScript = document.createElement('script');
suggestionsScript.src = 'suggestions_page.js';
suggestionsScript.onload = function() {
newTabView.appendTilePage(new ntp.SuggestionsPage(),
loadTimeData.getString('suggestions'),
false,
(newTabView.appsPages.length > 0) ?
newTabView.appsPages[0] : null);
chrome.send('getSuggestions');
cr.dispatchSimpleEvent(document, 'sectionready', true, true);
};
document.querySelector('head').appendChild(suggestionsScript);
}
if (!loadTimeData.getBoolean('showWebStoreIcon')) {
var webStoreIcon = $('chrome-web-store-link');
// Not all versions of the NTP have a footer, so this may not exist.
if (webStoreIcon)
webStoreIcon.hidden = true;
} else {
var webStoreLink = loadTimeData.getString('webStoreLink');
var url = appendParam(webStoreLink, 'utm_source', 'chrome-ntp-launcher');
$('chrome-web-store-link').href = url;
$('chrome-web-store-link').addEventListener('click',
onChromeWebStoreButtonClick);
}
// We need to wait for all the footer menu setup to be completed before
// we can compute its layout.
layoutFooter();
if (loadTimeData.getString('login_status_message')) {
loginBubble = new cr.ui.Bubble;
loginBubble.anchorNode = $('login-container');
loginBubble.arrowLocation = cr.ui.ArrowLocation.TOP_END;
loginBubble.bubbleAlignment =
cr.ui.BubbleAlignment.BUBBLE_EDGE_TO_ANCHOR_EDGE;
loginBubble.deactivateToDismissDelay = 2000;
loginBubble.closeButtonVisible = false;
$('login-status-advanced').onclick = function() {
chrome.send('showAdvancedLoginUI');
};
$('login-status-dismiss').onclick = loginBubble.hide.bind(loginBubble);
var bubbleContent = $('login-status-bubble-contents');
loginBubble.content = bubbleContent;
// The anchor node won't be updated until updateLogin is called so don't
// show the bubble yet.
shouldShowLoginBubble = true;
}
if (loadTimeData.valueExists('bubblePromoText')) {
promoBubble = new cr.ui.Bubble;
promoBubble.anchorNode = getRequiredElement('promo-bubble-anchor');
promoBubble.arrowLocation = cr.ui.ArrowLocation.BOTTOM_START;
promoBubble.bubbleAlignment = cr.ui.BubbleAlignment.ENTIRELY_VISIBLE;
promoBubble.deactivateToDismissDelay = 2000;
promoBubble.content = parseHtmlSubset(
loadTimeData.getString('bubblePromoText'), ['BR']);
var bubbleLink = promoBubble.querySelector('a');
if (bubbleLink) {
bubbleLink.addEventListener('click', function(e) {
chrome.send('bubblePromoLinkClicked');
});
}
promoBubble.handleCloseEvent = function() {
promoBubble.hide();
chrome.send('bubblePromoClosed');
};
promoBubble.show();
chrome.send('bubblePromoViewed');
}
var loginContainer = getRequiredElement('login-container');
loginContainer.addEventListener('click', showSyncLoginUI);
if (loadTimeData.getBoolean('shouldShowSyncLogin'))
chrome.send('initializeSyncLogin');
doWhenAllSectionsReady(function() {
// Tell the slider about the pages.
newTabView.updateSliderCards();
// Mark the current page.
newTabView.cardSlider.currentCardValue.navigationDot.classList.add(
'selected');
if (loadTimeData.valueExists('notificationPromoText')) {
var promoText = loadTimeData.getString('notificationPromoText');
var tags = ['IMG'];
var attrs = {
src: function(node, value) {
return node.tagName == 'IMG' &&
/^data\:image\/(?:png|gif|jpe?g)/.test(value);
},
};
var promo = parseHtmlSubset(promoText, tags, attrs);
var promoLink = promo.querySelector('a');
if (promoLink) {
promoLink.addEventListener('click', function(e) {
chrome.send('notificationPromoLinkClicked');
});
}
showNotification(promo, [], function() {
chrome.send('notificationPromoClosed');
}, 60000);
chrome.send('notificationPromoViewed');
}
cr.dispatchSimpleEvent(document, 'ntpLoaded', true, true);
document.documentElement.classList.remove('starting-up');
startTime = Date.now();
});
preventDefaultOnPoundLinkClicks(); // From webui/js/util.js.
cr.ui.FocusManager.disableMouseFocusOnButtons();
}
/**
* Launches the chrome web store app with the chrome-ntp-launcher
* source.
* @param {Event} e The click event.
*/
function onChromeWebStoreButtonClick(e) {
chrome.send('recordAppLaunchByURL',
[encodeURIComponent(this.href),
ntp.APP_LAUNCH.NTP_WEBSTORE_FOOTER]);
}
/*
* The number of sections to wait on.
* @type {number}
*/
var sectionsToWaitFor = -1;
/**
* Queued callbacks which lie in wait for all sections to be ready.
* @type {array}
*/
var readyCallbacks = [];
/**
* Fired as each section of pages becomes ready.
* @param {Event} e Each page's synthetic DOM event.
*/
document.addEventListener('sectionready', function(e) {
if (--sectionsToWaitFor <= 0) {
while (readyCallbacks.length) {
readyCallbacks.shift()();
}
}
});
/**
* This is used to simulate a fire-once event (i.e. $(document).ready() in
* jQuery or Y.on('domready') in YUI. If all sections are ready, the callback
* is fired right away. If all pages are not ready yet, the function is queued
* for later execution.
* @param {function} callback The work to be done when ready.
*/
function doWhenAllSectionsReady(callback) {
assert(typeof callback == 'function');
if (sectionsToWaitFor > 0)
readyCallbacks.push(callback);
else
window.setTimeout(callback, 0); // Do soon after, but asynchronously.
}
/**
* Measure the width of a nav dot with a given title.
* @param {string} id The loadTimeData ID of the desired title.
* @return {number} The width of the nav dot.
*/
function measureNavDot(id) {
var measuringDiv = $('fontMeasuringDiv');
measuringDiv.textContent = loadTimeData.getString(id);
// The 4 is for border and padding.
return Math.max(measuringDiv.clientWidth * 1.15 + 4, 80);
}
/**
* Fills in an invisible div with the longest dot title string so that
* its length may be measured and the nav dots sized accordingly.
*/
function measureNavDots() {
var pxWidth = measureNavDot('appDefaultPageName');
if (loadTimeData.getBoolean('showMostvisited'))
pxWidth = Math.max(measureNavDot('mostvisited'), pxWidth);
var styleElement = document.createElement('style');
styleElement.type = 'text/css';
// max-width is used because if we run out of space, the nav dots will be
// shrunk.
styleElement.textContent = '.dot { max-width: ' + pxWidth + 'px; }';
document.querySelector('head').appendChild(styleElement);
}
/**
* Layout the footer so that the nav dots stay centered.
*/
function layoutFooter() {
// We need the image to be loaded.
var logo = $('logo-img');
var logoImg = logo.querySelector('img');
if (!logoImg.complete) {
logoImg.onload = layoutFooter;
return;
}
var menu = $('footer-menu-container');
if (menu.clientWidth > logoImg.width)
logo.style.WebkitFlex = '0 1 ' + menu.clientWidth + 'px';
else
menu.style.WebkitFlex = '0 1 ' + logoImg.width + 'px';
}
function themeChanged(opt_hasAttribution) {
$('themecss').href = 'chrome://theme/css/new_tab_theme.css?' + Date.now();
if (typeof opt_hasAttribution != 'undefined') {
document.documentElement.setAttribute('hasattribution',
opt_hasAttribution);
}
updateAttribution();
}
function setBookmarkBarAttached(attached) {
document.documentElement.setAttribute('bookmarkbarattached', attached);
}
/**
* Attributes the attribution image at the bottom left.
*/
function updateAttribution() {
var attribution = $('attribution');
if (document.documentElement.getAttribute('hasattribution') == 'true') {
attribution.hidden = false;
} else {
attribution.hidden = true;
}
}
/**
* Timeout ID.
* @type {number}
*/
var notificationTimeout = 0;
/**
* Shows the notification bubble.
* @param {string|Node} message The notification message or node to use as
* message.
* @param {Array.<{text: string, action: function()}>} links An array of
* records describing the links in the notification. Each record should
* have a 'text' attribute (the display string) and an 'action' attribute
* (a function to run when the link is activated).
* @param {Function} opt_closeHandler The callback invoked if the user
* manually dismisses the notification.
*/
function showNotification(message, links, opt_closeHandler, opt_timeout) {
window.clearTimeout(notificationTimeout);
var span = document.querySelector('#notification > span');
if (typeof message == 'string') {
span.textContent = message;
} else {
span.textContent = ''; // Remove all children.
span.appendChild(message);
}
var linksBin = $('notificationLinks');
linksBin.textContent = '';
for (var i = 0; i < links.length; i++) {
var link = linksBin.ownerDocument.createElement('div');
link.textContent = links[i].text;
link.action = links[i].action;
link.onclick = function() {
this.action();
hideNotification();
};
link.setAttribute('role', 'button');
link.setAttribute('tabindex', 0);
link.className = 'link-button';
linksBin.appendChild(link);
}
function closeFunc(e) {
if (opt_closeHandler)
opt_closeHandler();
hideNotification();
}
document.querySelector('#notification button').onclick = closeFunc;
document.addEventListener('dragstart', closeFunc);
notificationContainer.hidden = false;
showNotificationOnCurrentPage();
newTabView.cardSlider.frame.addEventListener(
'cardSlider:card_change_ended', onCardChangeEnded);
var timeout = opt_timeout || 10000;
notificationTimeout = window.setTimeout(hideNotification, timeout);
}
/**
* Hide the notification bubble.
*/
function hideNotification() {
notificationContainer.classList.add('inactive');
newTabView.cardSlider.frame.removeEventListener(
'cardSlider:card_change_ended', onCardChangeEnded);
}
/**
* Happens when 1 or more consecutive card changes end.
* @param {Event} e The cardSlider:card_change_ended event.
*/
function onCardChangeEnded(e) {
// If we ended on the same page as we started, ignore.
if (newTabView.cardSlider.currentCardValue.notification)
return;
// Hide the notification the old page.
notificationContainer.classList.add('card-changed');
showNotificationOnCurrentPage();
}
/**
* Move and show the notification on the current page.
*/
function showNotificationOnCurrentPage() {
var page = newTabView.cardSlider.currentCardValue;
doWhenAllSectionsReady(function() {
if (page != newTabView.cardSlider.currentCardValue)
return;
// NOTE: This moves the notification to inside of the current page.
page.notification = notificationContainer;
// Reveal the notification and instruct it to hide itself if ignored.
notificationContainer.classList.remove('inactive');
// Gives the browser time to apply this rule before we remove it (causing
// a transition).
window.setTimeout(function() {
notificationContainer.classList.remove('card-changed');
}, 0);
});
}
/**
* When done fading out, set hidden to true so the notification can't be
* tabbed to or clicked.
* @param {Event} e The webkitTransitionEnd event.
*/
function onNotificationTransitionEnd(e) {
if (notificationContainer.classList.contains('inactive'))
notificationContainer.hidden = true;
}
function setRecentlyClosedTabs(dataItems) {
$('recently-closed-menu-button').dataItems = dataItems;
layoutFooter();
}
function setMostVisitedPages(data, hasBlacklistedUrls) {
newTabView.mostVisitedPage.data = data;
cr.dispatchSimpleEvent(document, 'sectionready', true, true);
}
function setSuggestionsPages(data, hasBlacklistedUrls) {
newTabView.suggestionsPage.data = data;
}
/**
* Set the dominant color for a node. This will be called in response to
* getFaviconDominantColor. The node represented by |id| better have a setter
* for stripeColor.
* @param {string} id The ID of a node.
* @param {string} color The color represented as a CSS string.
*/
function setFaviconDominantColor(id, color) {
var node = $(id);
if (node)
node.stripeColor = color;
}
/**
* Updates the text displayed in the login container. If there is no text then
* the login container is hidden.
* @param {string} loginHeader The first line of text.
* @param {string} loginSubHeader The second line of text.
* @param {string} iconURL The url for the login status icon. If this is null
then the login status icon is hidden.
* @param {boolean} isUserSignedIn Indicates if the user is signed in or not.
*/
function updateLogin(loginHeader, loginSubHeader, iconURL, isUserSignedIn) {
if (loginHeader || loginSubHeader) {
$('login-container').hidden = false;
$('login-status-header').innerHTML = loginHeader;
$('login-status-sub-header').innerHTML = loginSubHeader;
$('card-slider-frame').classList.add('showing-login-area');
if (iconURL) {
$('login-status-header-container').style.backgroundImage = url(iconURL);
$('login-status-header-container').classList.add('login-status-icon');
} else {
$('login-status-header-container').style.backgroundImage = 'none';
$('login-status-header-container').classList.remove(
'login-status-icon');
}
} else {
$('login-container').hidden = true;
$('card-slider-frame').classList.remove('showing-login-area');
}
if (shouldShowLoginBubble) {
window.setTimeout(loginBubble.show.bind(loginBubble), 0);
chrome.send('loginMessageSeen');
shouldShowLoginBubble = false;
} else if (loginBubble) {
loginBubble.reposition();
}
if (otherSessionsButton) {
otherSessionsButton.updateSignInState(isUserSignedIn);
layoutFooter();
}
}
/**
* Show the sync login UI.
* @param {Event} e The click event.
*/
function showSyncLoginUI(e) {
var rect = e.currentTarget.getBoundingClientRect();
chrome.send('showSyncLoginUI',
[rect.left, rect.top, rect.width, rect.height]);
}
/**
* Logs the time to click for the specified item.
* @param {string} item The item to log the time-to-click.
*/
function logTimeToClick(item) {
var timeToClick = Date.now() - startTime;
chrome.send('logTimeToClick',
['NewTabPage.TimeToClick' + item, timeToClick]);
}
/**
* Wrappers to forward the callback to corresponding PageListView member.
*/
function appAdded() {
return newTabView.appAdded.apply(newTabView, arguments);
}
function appMoved() {
return newTabView.appMoved.apply(newTabView, arguments);
}
function appRemoved() {
return newTabView.appRemoved.apply(newTabView, arguments);
}
function appsPrefChangeCallback() {
return newTabView.appsPrefChangedCallback.apply(newTabView, arguments);
}
function appLauncherPromoPrefChangeCallback() {
return newTabView.appLauncherPromoPrefChangeCallback.apply(newTabView,
arguments);
}
function appsReordered() {
return newTabView.appsReordered.apply(newTabView, arguments);
}
function enterRearrangeMode() {
return newTabView.enterRearrangeMode.apply(newTabView, arguments);
}
function setForeignSessions(sessionList, isTabSyncEnabled) {
if (otherSessionsButton) {
otherSessionsButton.setForeignSessions(sessionList, isTabSyncEnabled);
layoutFooter();
}
}
function getAppsCallback() {
return newTabView.getAppsCallback.apply(newTabView, arguments);
}
function getAppsPageIndex() {
return newTabView.getAppsPageIndex.apply(newTabView, arguments);
}
function getCardSlider() {
return newTabView.cardSlider;
}
function leaveRearrangeMode() {
return newTabView.leaveRearrangeMode.apply(newTabView, arguments);
}
function saveAppPageName() {
return newTabView.saveAppPageName.apply(newTabView, arguments);
}
function setAppToBeHighlighted(appId) {
newTabView.highlightAppId = appId;
}
// Return an object with all the exports
return {
appAdded: appAdded,
appMoved: appMoved,
appRemoved: appRemoved,
appsPrefChangeCallback: appsPrefChangeCallback,
appLauncherPromoPrefChangeCallback: appLauncherPromoPrefChangeCallback,
enterRearrangeMode: enterRearrangeMode,
getAppsCallback: getAppsCallback,
getAppsPageIndex: getAppsPageIndex,
getCardSlider: getCardSlider,
onLoad: onLoad,
leaveRearrangeMode: leaveRearrangeMode,
logTimeToClick: logTimeToClick,
NtpFollowAction: NtpFollowAction,
saveAppPageName: saveAppPageName,
setAppToBeHighlighted: setAppToBeHighlighted,
setBookmarkBarAttached: setBookmarkBarAttached,
setForeignSessions: setForeignSessions,
setMostVisitedPages: setMostVisitedPages,
setSuggestionsPages: setSuggestionsPages,
setRecentlyClosedTabs: setRecentlyClosedTabs,
setFaviconDominantColor: setFaviconDominantColor,
showNotification: showNotification,
themeChanged: themeChanged,
updateLogin: updateLogin
};
});
document.addEventListener('DOMContentLoaded', ntp.onLoad);
var toCssPx = cr.ui.toCssPx;
| s20121035/rk3288_android5.1_repo | external/chromium_org/chrome/browser/resources/ntp4/new_tab.js | JavaScript | gpl-3.0 | 23,568 |
/*-----------------------------------------------------------------------------+
Copyright (c) 2007-2012: Joachim Faulhaber
Copyright (c) 1999-2006: Cortex Software GmbH, Kantstrasse 57, Berlin
+------------------------------------------------------------------------------+
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENCE.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
+-----------------------------------------------------------------------------*/
#ifndef BOOST_ICL_INTERVAL_BASE_MAP_HPP_JOFA_990223
#define BOOST_ICL_INTERVAL_BASE_MAP_HPP_JOFA_990223
#include <limits>
#include <boost/type_traits/ice.hpp>
#include <boost/mpl/and.hpp>
#include <boost/mpl/or.hpp>
#include <boost/mpl/not.hpp>
#include <boost/icl/detail/notate.hpp>
#include <boost/icl/detail/design_config.hpp>
#include <boost/icl/detail/on_absorbtion.hpp>
#include <boost/icl/detail/interval_map_algo.hpp>
#include <boost/icl/associative_interval_container.hpp>
#include <boost/icl/type_traits/is_interval_splitter.hpp>
#include <boost/icl/map.hpp>
namespace boost{namespace icl
{
template<class DomainT, class CodomainT>
struct mapping_pair
{
DomainT key;
CodomainT data;
mapping_pair():key(), data(){}
mapping_pair(const DomainT& key_value, const CodomainT& data_value)
:key(key_value), data(data_value){}
mapping_pair(const std::pair<DomainT,CodomainT>& std_pair)
:key(std_pair.first), data(std_pair.second){}
};
/** \brief Implements a map as a map of intervals (base class) */
template
<
class SubType,
typename DomainT,
typename CodomainT,
class Traits = icl::partial_absorber,
ICL_COMPARE Compare = ICL_COMPARE_INSTANCE(ICL_COMPARE_DEFAULT, DomainT),
ICL_COMBINE Combine = ICL_COMBINE_INSTANCE(icl::inplace_plus, CodomainT),
ICL_SECTION Section = ICL_SECTION_INSTANCE(icl::inter_section, CodomainT),
ICL_INTERVAL(ICL_COMPARE) Interval = ICL_INTERVAL_INSTANCE(ICL_INTERVAL_DEFAULT, DomainT, Compare),
ICL_ALLOC Alloc = std::allocator
>
class interval_base_map
{
public:
//==========================================================================
//= Associated types
//==========================================================================
typedef interval_base_map<SubType,DomainT,CodomainT,
Traits,Compare,Combine,Section,Interval,Alloc>
type;
/// The designated \e derived or \e sub_type of this base class
typedef SubType sub_type;
/// Auxilliary type for overloadresolution
typedef type overloadable_type;
/// Traits of an itl map
typedef Traits traits;
//--------------------------------------------------------------------------
//- Associated types: Related types
//--------------------------------------------------------------------------
/// The atomized type representing the corresponding container of elements
typedef typename icl::map<DomainT,CodomainT,
Traits,Compare,Combine,Section,Alloc> atomized_type;
//--------------------------------------------------------------------------
//- Associated types: Data
//--------------------------------------------------------------------------
/// Domain type (type of the keys) of the map
typedef DomainT domain_type;
typedef typename boost::call_traits<DomainT>::param_type domain_param;
/// Domain type (type of the keys) of the map
typedef CodomainT codomain_type;
/// Auxiliary type to help the compiler resolve ambiguities when using std::make_pair
typedef mapping_pair<domain_type,codomain_type> domain_mapping_type;
/// Conceptual is a map a set of elements of type \c element_type
typedef domain_mapping_type element_type;
/// The interval type of the map
typedef ICL_INTERVAL_TYPE(Interval,DomainT,Compare) interval_type;
/// Auxiliary type for overload resolution
typedef std::pair<interval_type,CodomainT> interval_mapping_type;
/// Type of an interval containers segment, that is spanned by an interval
typedef std::pair<interval_type,CodomainT> segment_type;
//--------------------------------------------------------------------------
//- Associated types: Size
//--------------------------------------------------------------------------
/// The difference type of an interval which is sometimes different form the domain_type
typedef typename difference_type_of<domain_type>::type difference_type;
/// The size type of an interval which is mostly std::size_t
typedef typename size_type_of<domain_type>::type size_type;
//--------------------------------------------------------------------------
//- Associated types: Functors
//--------------------------------------------------------------------------
/// Comparison functor for domain values
typedef ICL_COMPARE_DOMAIN(Compare,DomainT) domain_compare;
typedef ICL_COMPARE_DOMAIN(Compare,segment_type) segment_compare;
/// Combine functor for codomain value aggregation
typedef ICL_COMBINE_CODOMAIN(Combine,CodomainT) codomain_combine;
/// Inverse Combine functor for codomain value aggregation
typedef typename inverse<codomain_combine>::type inverse_codomain_combine;
/// Intersection functor for codomain values
typedef typename mpl::if_
<has_set_semantics<codomain_type>
, ICL_SECTION_CODOMAIN(Section,CodomainT)
, codomain_combine
>::type codomain_intersect;
/// Inverse Combine functor for codomain value intersection
typedef typename inverse<codomain_intersect>::type inverse_codomain_intersect;
/// Comparison functor for intervals which are keys as well
typedef exclusive_less_than<interval_type> interval_compare;
/// Comparison functor for keys
typedef exclusive_less_than<interval_type> key_compare;
//--------------------------------------------------------------------------
//- Associated types: Implementation and stl related
//--------------------------------------------------------------------------
/// The allocator type of the set
typedef Alloc<std::pair<const interval_type, codomain_type> >
allocator_type;
/// Container type for the implementation
typedef ICL_IMPL_SPACE::map<interval_type,codomain_type,
key_compare,allocator_type> ImplMapT;
/// key type of the implementing container
typedef typename ImplMapT::key_type key_type;
/// value type of the implementing container
typedef typename ImplMapT::value_type value_type;
/// data type of the implementing container
typedef typename ImplMapT::value_type::second_type data_type;
/// pointer type
typedef typename ImplMapT::pointer pointer;
/// const pointer type
typedef typename ImplMapT::const_pointer const_pointer;
/// reference type
typedef typename ImplMapT::reference reference;
/// const reference type
typedef typename ImplMapT::const_reference const_reference;
/// iterator for iteration over intervals
typedef typename ImplMapT::iterator iterator;
/// const_iterator for iteration over intervals
typedef typename ImplMapT::const_iterator const_iterator;
/// iterator for reverse iteration over intervals
typedef typename ImplMapT::reverse_iterator reverse_iterator;
/// const_iterator for iteration over intervals
typedef typename ImplMapT::const_reverse_iterator const_reverse_iterator;
/// element iterator: Depreciated, see documentation.
typedef boost::icl::element_iterator<iterator> element_iterator;
/// const element iterator: Depreciated, see documentation.
typedef boost::icl::element_iterator<const_iterator> element_const_iterator;
/// element reverse iterator: Depreciated, see documentation.
typedef boost::icl::element_iterator<reverse_iterator> element_reverse_iterator;
/// element const reverse iterator: Depreciated, see documentation.
typedef boost::icl::element_iterator<const_reverse_iterator> element_const_reverse_iterator;
typedef typename on_absorbtion<type, codomain_combine,
Traits::absorbs_identities>::type on_codomain_absorbtion;
public:
BOOST_STATIC_CONSTANT(bool,
is_total_invertible = ( Traits::is_total
&& has_inverse<codomain_type>::value));
BOOST_STATIC_CONSTANT(int, fineness = 0);
public:
//==========================================================================
//= Construct, copy, destruct
//==========================================================================
/** Default constructor for the empty object */
interval_base_map()
{
BOOST_CONCEPT_ASSERT((DefaultConstructibleConcept<DomainT>));
BOOST_CONCEPT_ASSERT((LessThanComparableConcept<DomainT>));
BOOST_CONCEPT_ASSERT((DefaultConstructibleConcept<CodomainT>));
BOOST_CONCEPT_ASSERT((EqualComparableConcept<CodomainT>));
}
/** Copy constructor */
interval_base_map(const interval_base_map& src): _map(src._map)
{
BOOST_CONCEPT_ASSERT((DefaultConstructibleConcept<DomainT>));
BOOST_CONCEPT_ASSERT((LessThanComparableConcept<DomainT>));
BOOST_CONCEPT_ASSERT((DefaultConstructibleConcept<CodomainT>));
BOOST_CONCEPT_ASSERT((EqualComparableConcept<CodomainT>));
}
/** Copy assignment operator */
interval_base_map& operator = (const interval_base_map& src)
{
this->_map = src._map;
return *this;
}
# ifndef BOOST_NO_RVALUE_REFERENCES
//==========================================================================
//= Move semantics
//==========================================================================
/** Move constructor */
interval_base_map(interval_base_map&& src): _map(boost::move(src._map))
{
BOOST_CONCEPT_ASSERT((DefaultConstructibleConcept<DomainT>));
BOOST_CONCEPT_ASSERT((LessThanComparableConcept<DomainT>));
BOOST_CONCEPT_ASSERT((DefaultConstructibleConcept<CodomainT>));
BOOST_CONCEPT_ASSERT((EqualComparableConcept<CodomainT>));
}
/** Move assignment operator */
interval_base_map& operator = (interval_base_map&& src)
{
this->_map = boost::move(src._map);
return *this;
}
//==========================================================================
# endif // BOOST_NO_RVALUE_REFERENCES
/** swap the content of containers */
void swap(interval_base_map& object) { _map.swap(object._map); }
//==========================================================================
//= Containedness
//==========================================================================
/** clear the map */
void clear() { icl::clear(*that()); }
/** is the map empty? */
bool empty()const { return icl::is_empty(*that()); }
//==========================================================================
//= Size
//==========================================================================
/** An interval map's size is it's cardinality */
size_type size()const
{
return icl::cardinality(*that());
}
/** Size of the iteration over this container */
std::size_t iterative_size()const
{
return _map.size();
}
//==========================================================================
//= Selection
//==========================================================================
/** Find the interval value pair, that contains \c key */
const_iterator find(const domain_type& key_value)const
{
return icl::find(*this, key_value);
}
/** Find the first interval value pair, that collides with interval
\c key_interval */
const_iterator find(const interval_type& key_interval)const
{
return _map.find(key_interval);
}
/** Total select function. */
codomain_type operator()(const domain_type& key_value)const
{
const_iterator it_ = icl::find(*this, key_value);
return it_==end() ? identity_element<codomain_type>::value()
: (*it_).second;
}
//==========================================================================
//= Addition
//==========================================================================
/** Addition of a key value pair to the map */
SubType& add(const element_type& key_value_pair)
{
return icl::add(*that(), key_value_pair);
}
/** Addition of an interval value pair to the map. */
SubType& add(const segment_type& interval_value_pair)
{
this->template _add<codomain_combine>(interval_value_pair);
return *that();
}
/** Addition of an interval value pair \c interval_value_pair to the map.
Iterator \c prior_ is a hint to the position \c interval_value_pair can be
inserted after. */
iterator add(iterator prior_, const segment_type& interval_value_pair)
{
return this->template _add<codomain_combine>(prior_, interval_value_pair);
}
//==========================================================================
//= Subtraction
//==========================================================================
/** Subtraction of a key value pair from the map */
SubType& subtract(const element_type& key_value_pair)
{
return icl::subtract(*that(), key_value_pair);
}
/** Subtraction of an interval value pair from the map. */
SubType& subtract(const segment_type& interval_value_pair)
{
on_invertible<type, is_total_invertible>
::subtract(*that(), interval_value_pair);
return *that();
}
//==========================================================================
//= Insertion
//==========================================================================
/** Insertion of a \c key_value_pair into the map. */
SubType& insert(const element_type& key_value_pair)
{
return icl::insert(*that(), key_value_pair);
}
/** Insertion of an \c interval_value_pair into the map. */
SubType& insert(const segment_type& interval_value_pair)
{
_insert(interval_value_pair);
return *that();
}
/** Insertion of an \c interval_value_pair into the map. Iterator \c prior_.
serves as a hint to insert after the element \c prior point to. */
iterator insert(iterator prior, const segment_type& interval_value_pair)
{
return _insert(prior, interval_value_pair);
}
/** With <tt>key_value_pair = (k,v)</tt> set value \c v for key \c k */
SubType& set(const element_type& key_value_pair)
{
return icl::set_at(*that(), key_value_pair);
}
/** With <tt>interval_value_pair = (I,v)</tt> set value \c v
for all keys in interval \c I in the map. */
SubType& set(const segment_type& interval_value_pair)
{
return icl::set_at(*that(), interval_value_pair);
}
//==========================================================================
//= Erasure
//==========================================================================
/** Erase a \c key_value_pair from the map. */
SubType& erase(const element_type& key_value_pair)
{
icl::erase(*that(), key_value_pair);
return *that();
}
/** Erase an \c interval_value_pair from the map. */
SubType& erase(const segment_type& interval_value_pair);
/** Erase a key value pair for \c key. */
SubType& erase(const domain_type& key)
{
return icl::erase(*that(), key);
}
/** Erase all value pairs within the range of the
interval <tt>inter_val</tt> from the map. */
SubType& erase(const interval_type& inter_val);
/** Erase all value pairs within the range of the interval that iterator
\c position points to. */
void erase(iterator position){ this->_map.erase(position); }
/** Erase all value pairs for a range of iterators <tt>[first,past)</tt>. */
void erase(iterator first, iterator past){ this->_map.erase(first, past); }
//==========================================================================
//= Intersection
//==========================================================================
/** The intersection of \c interval_value_pair and \c *this map is added to \c section. */
void add_intersection(SubType& section, const segment_type& interval_value_pair)const
{
on_definedness<SubType, Traits::is_total>
::add_intersection(section, *that(), interval_value_pair);
}
//==========================================================================
//= Symmetric difference
//==========================================================================
/** If \c *this map contains \c key_value_pair it is erased, otherwise it is added. */
SubType& flip(const element_type& key_value_pair)
{
return icl::flip(*that(), key_value_pair);
}
/** If \c *this map contains \c interval_value_pair it is erased, otherwise it is added. */
SubType& flip(const segment_type& interval_value_pair)
{
on_total_absorbable<SubType, Traits::is_total, Traits::absorbs_identities>
::flip(*that(), interval_value_pair);
return *that();
}
//==========================================================================
//= Iterator related
//==========================================================================
iterator lower_bound(const key_type& interval)
{ return _map.lower_bound(interval); }
iterator upper_bound(const key_type& interval)
{ return _map.upper_bound(interval); }
const_iterator lower_bound(const key_type& interval)const
{ return _map.lower_bound(interval); }
const_iterator upper_bound(const key_type& interval)const
{ return _map.upper_bound(interval); }
std::pair<iterator,iterator> equal_range(const key_type& interval)
{
return std::pair<iterator,iterator>
(lower_bound(interval), upper_bound(interval));
}
std::pair<const_iterator,const_iterator>
equal_range(const key_type& interval)const
{
return std::pair<const_iterator,const_iterator>
(lower_bound(interval), upper_bound(interval));
}
iterator begin() { return _map.begin(); }
iterator end() { return _map.end(); }
const_iterator begin()const { return _map.begin(); }
const_iterator end()const { return _map.end(); }
reverse_iterator rbegin() { return _map.rbegin(); }
reverse_iterator rend() { return _map.rend(); }
const_reverse_iterator rbegin()const { return _map.rbegin(); }
const_reverse_iterator rend()const { return _map.rend(); }
private:
template<class Combiner>
iterator _add(const segment_type& interval_value_pair);
template<class Combiner>
iterator _add(iterator prior_, const segment_type& interval_value_pair);
template<class Combiner>
void _subtract(const segment_type& interval_value_pair);
iterator _insert(const segment_type& interval_value_pair);
iterator _insert(iterator prior_, const segment_type& interval_value_pair);
private:
template<class Combiner>
void add_segment(const interval_type& inter_val, const CodomainT& co_val, iterator& it_);
template<class Combiner>
void add_main(interval_type& inter_val, const CodomainT& co_val,
iterator& it_, const iterator& last_);
template<class Combiner>
void add_rear(const interval_type& inter_val, const CodomainT& co_val, iterator& it_);
void add_front(const interval_type& inter_val, iterator& first_);
private:
void subtract_front(const interval_type& inter_val, iterator& first_);
template<class Combiner>
void subtract_main(const CodomainT& co_val, iterator& it_, const iterator& last_);
template<class Combiner>
void subtract_rear(interval_type& inter_val, const CodomainT& co_val, iterator& it_);
private:
void insert_main(const interval_type&, const CodomainT&, iterator&, const iterator&);
void erase_rest ( interval_type&, const CodomainT&, iterator&, const iterator&);
template<class FragmentT>
void total_add_intersection(SubType& section, const FragmentT& fragment)const
{
section += *that();
section.add(fragment);
}
void partial_add_intersection(SubType& section, const segment_type& operand)const
{
interval_type inter_val = operand.first;
if(icl::is_empty(inter_val))
return;
std::pair<const_iterator, const_iterator> exterior = equal_range(inter_val);
if(exterior.first == exterior.second)
return;
for(const_iterator it_=exterior.first; it_ != exterior.second; it_++)
{
interval_type common_interval = (*it_).first & inter_val;
if(!icl::is_empty(common_interval))
{
section.template _add<codomain_combine> (value_type(common_interval, (*it_).second) );
section.template _add<codomain_intersect>(value_type(common_interval, operand.second));
}
}
}
void partial_add_intersection(SubType& section, const element_type& operand)const
{
partial_add_intersection(section, make_segment<type>(operand));
}
protected:
template <class Combiner>
iterator gap_insert(iterator prior_, const interval_type& inter_val,
const codomain_type& co_val )
{
// inter_val is not conained in this map. Insertion will be successful
BOOST_ASSERT(this->_map.find(inter_val) == this->_map.end());
BOOST_ASSERT((!on_absorbtion<type,Combiner,Traits::absorbs_identities>::is_absorbable(co_val)));
return this->_map.insert(prior_, value_type(inter_val, version<Combiner>()(co_val)));
}
template <class Combiner>
std::pair<iterator, bool>
add_at(const iterator& prior_, const interval_type& inter_val,
const codomain_type& co_val )
{
// Never try to insert an identity element into an identity element absorber here:
BOOST_ASSERT((!(on_absorbtion<type,Combiner,Traits::absorbs_identities>::is_absorbable(co_val))));
iterator inserted_
= this->_map.insert(prior_, value_type(inter_val, Combiner::identity_element()));
if((*inserted_).first == inter_val && (*inserted_).second == Combiner::identity_element())
{
Combiner()((*inserted_).second, co_val);
return std::pair<iterator,bool>(inserted_, true);
}
else
return std::pair<iterator,bool>(inserted_, false);
}
std::pair<iterator, bool>
insert_at(const iterator& prior_, const interval_type& inter_val,
const codomain_type& co_val )
{
iterator inserted_
= this->_map.insert(prior_, value_type(inter_val, co_val));
if(inserted_ == prior_)
return std::pair<iterator,bool>(inserted_, false);
else if((*inserted_).first == inter_val)
return std::pair<iterator,bool>(inserted_, true);
else
return std::pair<iterator,bool>(inserted_, false);
}
protected:
sub_type* that() { return static_cast<sub_type*>(this); }
const sub_type* that()const { return static_cast<const sub_type*>(this); }
protected:
ImplMapT _map;
private:
//--------------------------------------------------------------------------
template<class Type, bool is_total_invertible>
struct on_invertible;
template<class Type>
struct on_invertible<Type, true>
{
typedef typename Type::segment_type segment_type;
typedef typename Type::inverse_codomain_combine inverse_codomain_combine;
static void subtract(Type& object, const segment_type& operand)
{ object.template _add<inverse_codomain_combine>(operand); }
};
template<class Type>
struct on_invertible<Type, false>
{
typedef typename Type::segment_type segment_type;
typedef typename Type::inverse_codomain_combine inverse_codomain_combine;
static void subtract(Type& object, const segment_type& operand)
{ object.template _subtract<inverse_codomain_combine>(operand); }
};
friend struct on_invertible<type, true>;
friend struct on_invertible<type, false>;
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
template<class Type, bool is_total>
struct on_definedness;
template<class Type>
struct on_definedness<Type, true>
{
static void add_intersection(Type& section, const Type& object,
const segment_type& operand)
{ object.total_add_intersection(section, operand); }
};
template<class Type>
struct on_definedness<Type, false>
{
static void add_intersection(Type& section, const Type& object,
const segment_type& operand)
{ object.partial_add_intersection(section, operand); }
};
friend struct on_definedness<type, true>;
friend struct on_definedness<type, false>;
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
template<class Type, bool has_set_semantics>
struct on_codomain_model;
template<class Type>
struct on_codomain_model<Type, true>
{
typedef typename Type::interval_type interval_type;
typedef typename Type::codomain_type codomain_type;
typedef typename Type::segment_type segment_type;
typedef typename Type::codomain_combine codomain_combine;
typedef typename Type::inverse_codomain_intersect inverse_codomain_intersect;
static void add(Type& intersection, interval_type& common_interval,
const codomain_type& flip_value, const codomain_type& co_value)
{
codomain_type common_value = flip_value;
inverse_codomain_intersect()(common_value, co_value);
intersection.template
_add<codomain_combine>(segment_type(common_interval, common_value));
}
};
template<class Type>
struct on_codomain_model<Type, false>
{
typedef typename Type::interval_type interval_type;
typedef typename Type::codomain_type codomain_type;
typedef typename Type::segment_type segment_type;
typedef typename Type::codomain_combine codomain_combine;
static void add(Type& intersection, interval_type& common_interval,
const codomain_type&, const codomain_type&)
{
intersection.template
_add<codomain_combine>(segment_type(common_interval,
identity_element<codomain_type>::value()));
}
};
friend struct on_codomain_model<type, true>;
friend struct on_codomain_model<type, false>;
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
template<class Type, bool is_total, bool absorbs_identities>
struct on_total_absorbable;
template<class Type>
struct on_total_absorbable<Type, true, true>
{
static void flip(Type& object, const typename Type::segment_type&)
{ icl::clear(object); }
};
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable:4127) // conditional expression is constant
#endif
template<class Type>
struct on_total_absorbable<Type, true, false>
{
typedef typename Type::segment_type segment_type;
typedef typename Type::codomain_type codomain_type;
static void flip(Type& object, const segment_type& operand)
{
object += operand;
ICL_FORALL(typename Type, it_, object)
(*it_).second = identity_element<codomain_type>::value();
if(mpl::not_<is_interval_splitter<Type> >::value)
icl::join(object);
}
};
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif
template<class Type, bool absorbs_identities>
struct on_total_absorbable<Type, false, absorbs_identities>
{
typedef typename Type::segment_type segment_type;
typedef typename Type::codomain_type codomain_type;
typedef typename Type::interval_type interval_type;
typedef typename Type::value_type value_type;
typedef typename Type::const_iterator const_iterator;
typedef typename Type::set_type set_type;
typedef typename Type::inverse_codomain_intersect inverse_codomain_intersect;
static void flip(Type& object, const segment_type& interval_value_pair)
{
// That which is common shall be subtracted
// That which is not shall be added
// So interval_value_pair has to be 'complementary added' or flipped
interval_type span = interval_value_pair.first;
std::pair<const_iterator, const_iterator> exterior
= object.equal_range(span);
const_iterator first_ = exterior.first;
const_iterator end_ = exterior.second;
interval_type covered, left_over, common_interval;
const codomain_type& x_value = interval_value_pair.second;
const_iterator it_ = first_;
set_type eraser;
Type intersection;
while(it_ != end_ )
{
const codomain_type& co_value = (*it_).second;
covered = (*it_++).first;
//[a ... : span
// [b ... : covered
//[a b) : left_over
left_over = right_subtract(span, covered);
//That which is common ...
common_interval = span & covered;
if(!icl::is_empty(common_interval))
{
// ... shall be subtracted
icl::add(eraser, common_interval);
on_codomain_model<Type, has_set_semantics<codomain_type>::value>
::add(intersection, common_interval, x_value, co_value);
}
icl::add(object, value_type(left_over, x_value)); //That which is not shall be added
// Because this is a collision free addition I don't have to distinguish codomain_types.
//... d) : span
//... c) : covered
// [c d) : span'
span = left_subtract(span, covered);
}
//If span is not empty here, it is not in the set so it shall be added
icl::add(object, value_type(span, x_value));
//finally rewrite the common segments
icl::erase(object, eraser);
object += intersection;
}
};
//--------------------------------------------------------------------------
} ;
//==============================================================================
//= Addition detail
//==============================================================================
template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>
inline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>
::add_front(const interval_type& inter_val, iterator& first_)
{
// If the collision sequence has a left residual 'left_resid' it will
// be split, to provide a standardized start of algorithms:
// The addend interval 'inter_val' covers the beginning of the collision sequence.
// only for the first there can be a left_resid: a part of *first_ left of inter_val
interval_type left_resid = right_subtract((*first_).first, inter_val);
if(!icl::is_empty(left_resid))
{ // [------------ . . .
// [left_resid---first_ --- . . .
iterator prior_ = cyclic_prior(*this, first_);
const_cast<interval_type&>((*first_).first)
= left_subtract((*first_).first, left_resid);
//NOTE: Only splitting
this->_map.insert(prior_, segment_type(left_resid, (*first_).second));
}
//POST:
// [----- inter_val ---- . . .
// ...[-- first_ --...
}
template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>
template<class Combiner>
inline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>
::add_segment(const interval_type& inter_val, const CodomainT& co_val, iterator& it_)
{
interval_type lead_gap = right_subtract(inter_val, (*it_).first);
if(!icl::is_empty(lead_gap))
{
// [lead_gap--- . . .
// [-- it_ ...
iterator prior_ = prior(it_);
iterator inserted_ = this->template gap_insert<Combiner>(prior_, lead_gap, co_val);
that()->handle_inserted(prior_, inserted_);
}
// . . . --------- . . . addend interval
// [-- it_ --) has a common part with the first overval
Combiner()((*it_).second, co_val);
that()->template handle_left_combined<Combiner>(it_++);
}
template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>
template<class Combiner>
inline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>
::add_main(interval_type& inter_val, const CodomainT& co_val,
iterator& it_, const iterator& last_)
{
interval_type cur_interval;
while(it_!=last_)
{
cur_interval = (*it_).first ;
add_segment<Combiner>(inter_val, co_val, it_);
// shrink interval
inter_val = left_subtract(inter_val, cur_interval);
}
}
template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>
template<class Combiner>
inline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>
::add_rear(const interval_type& inter_val, const CodomainT& co_val, iterator& it_)
{
iterator prior_ = cyclic_prior(*that(), it_);
interval_type cur_itv = (*it_).first ;
interval_type lead_gap = right_subtract(inter_val, cur_itv);
if(!icl::is_empty(lead_gap))
{ // [lead_gap--- . . .
// [prior) [-- it_ ...
iterator inserted_ = this->template gap_insert<Combiner>(prior_, lead_gap, co_val);
that()->handle_inserted(prior_, inserted_);
}
interval_type end_gap = left_subtract(inter_val, cur_itv);
if(!icl::is_empty(end_gap))
{
// [----------------end_gap)
// . . . -- it_ --)
Combiner()((*it_).second, co_val);
that()->template gap_insert_at<Combiner>(it_, prior_, end_gap, co_val);
}
else
{
// only for the last there can be a right_resid: a part of *it_ right of x
interval_type right_resid = left_subtract(cur_itv, inter_val);
if(icl::is_empty(right_resid))
{
// [---------------)
// [-- it_ ---)
Combiner()((*it_).second, co_val);
that()->template handle_preceeded_combined<Combiner>(prior_, it_);
}
else
{
// [--------------)
// [-- it_ --right_resid)
const_cast<interval_type&>((*it_).first) = right_subtract((*it_).first, right_resid);
//NOTE: This is NOT an insertion that has to take care for correct application of
// the Combiner functor. It only reestablished that state after splitting the
// 'it_' interval value pair. Using _map_insert<Combiner> does not work here.
iterator insertion_ = this->_map.insert(it_, value_type(right_resid, (*it_).second));
that()->handle_reinserted(insertion_);
Combiner()((*it_).second, co_val);
that()->template handle_preceeded_combined<Combiner>(insertion_, it_);
}
}
}
//==============================================================================
//= Addition
//==============================================================================
template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>
template<class Combiner>
inline typename interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>::iterator
interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>
::_add(const segment_type& addend)
{
typedef typename on_absorbtion<type,Combiner,
absorbs_identities<type>::value>::type on_absorbtion_;
const interval_type& inter_val = addend.first;
if(icl::is_empty(inter_val))
return this->_map.end();
const codomain_type& co_val = addend.second;
if(on_absorbtion_::is_absorbable(co_val))
return this->_map.end();
std::pair<iterator,bool> insertion
= this->_map.insert(value_type(inter_val, version<Combiner>()(co_val)));
if(insertion.second)
return that()->handle_inserted(insertion.first);
else
{
// Detect the first and the end iterator of the collision sequence
iterator first_ = this->_map.lower_bound(inter_val),
last_ = insertion.first;
//assert(end_ == this->_map.upper_bound(inter_val));
iterator it_ = first_;
interval_type rest_interval = inter_val;
add_front (rest_interval, it_ );
add_main<Combiner>(rest_interval, co_val, it_, last_);
add_rear<Combiner>(rest_interval, co_val, it_ );
return it_;
}
}
template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>
template<class Combiner>
inline typename interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>::iterator
interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>
::_add(iterator prior_, const segment_type& addend)
{
typedef typename on_absorbtion<type,Combiner,
absorbs_identities<type>::value>::type on_absorbtion_;
const interval_type& inter_val = addend.first;
if(icl::is_empty(inter_val))
return prior_;
const codomain_type& co_val = addend.second;
if(on_absorbtion_::is_absorbable(co_val))
return prior_;
std::pair<iterator,bool> insertion
= add_at<Combiner>(prior_, inter_val, co_val);
if(insertion.second)
return that()->handle_inserted(insertion.first);
else
{
// Detect the first and the end iterator of the collision sequence
std::pair<iterator,iterator> overlap = equal_range(inter_val);
iterator it_ = overlap.first,
last_ = prior(overlap.second);
interval_type rest_interval = inter_val;
add_front (rest_interval, it_ );
add_main<Combiner>(rest_interval, co_val, it_, last_);
add_rear<Combiner>(rest_interval, co_val, it_ );
return it_;
}
}
//==============================================================================
//= Subtraction detail
//==============================================================================
template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>
inline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>
::subtract_front(const interval_type& inter_val, iterator& it_)
{
interval_type left_resid = right_subtract((*it_).first, inter_val);
if(!icl::is_empty(left_resid)) // [--- inter_val ---)
{ //[prior_) [left_resid)[--- it_ . . .
iterator prior_ = cyclic_prior(*this, it_);
const_cast<interval_type&>((*it_).first) = left_subtract((*it_).first, left_resid);
this->_map.insert(prior_, value_type(left_resid, (*it_).second));
// The segemnt *it_ is split at inter_val.first(), so as an invariant
// segment *it_ is always "under" inter_val and a left_resid is empty.
}
}
template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>
template<class Combiner>
inline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>
::subtract_main(const CodomainT& co_val, iterator& it_, const iterator& last_)
{
while(it_ != last_)
{
Combiner()((*it_).second, co_val);
that()->template handle_left_combined<Combiner>(it_++);
}
}
template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>
template<class Combiner>
inline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>
::subtract_rear(interval_type& inter_val, const CodomainT& co_val, iterator& it_)
{
interval_type right_resid = left_subtract((*it_).first, inter_val);
if(icl::is_empty(right_resid))
{
Combiner()((*it_).second, co_val);
that()->template handle_combined<Combiner>(it_);
}
else
{
const_cast<interval_type&>((*it_).first) = right_subtract((*it_).first, right_resid);
iterator next_ = this->_map.insert(it_, value_type(right_resid, (*it_).second));
Combiner()((*it_).second, co_val);
that()->template handle_succeeded_combined<Combiner>(it_, next_);
}
}
//==============================================================================
//= Subtraction
//==============================================================================
template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>
template<class Combiner>
inline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>
::_subtract(const segment_type& minuend)
{
interval_type inter_val = minuend.first;
if(icl::is_empty(inter_val))
return;
const codomain_type& co_val = minuend.second;
if(on_absorbtion<type,Combiner,Traits::absorbs_identities>::is_absorbable(co_val))
return;
std::pair<iterator, iterator> exterior = equal_range(inter_val);
if(exterior.first == exterior.second)
return;
iterator last_ = prior(exterior.second);
iterator it_ = exterior.first;
subtract_front (inter_val, it_ );
subtract_main <Combiner>( co_val, it_, last_);
subtract_rear <Combiner>(inter_val, co_val, it_ );
}
//==============================================================================
//= Insertion
//==============================================================================
template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>
inline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>
::insert_main(const interval_type& inter_val, const CodomainT& co_val,
iterator& it_, const iterator& last_)
{
iterator end_ = boost::next(last_);
iterator prior_ = it_, inserted_;
if(prior_ != this->_map.end())
--prior_;
interval_type rest_interval = inter_val, left_gap, cur_itv;
interval_type last_interval = last_ ->first;
while(it_ != end_ )
{
cur_itv = (*it_).first ;
left_gap = right_subtract(rest_interval, cur_itv);
if(!icl::is_empty(left_gap))
{
inserted_ = this->_map.insert(prior_, value_type(left_gap, co_val));
it_ = that()->handle_inserted(inserted_);
}
// shrink interval
rest_interval = left_subtract(rest_interval, cur_itv);
prior_ = it_;
++it_;
}
//insert_rear(rest_interval, co_val, last_):
interval_type end_gap = left_subtract(rest_interval, last_interval);
if(!icl::is_empty(end_gap))
{
inserted_ = this->_map.insert(prior_, value_type(end_gap, co_val));
it_ = that()->handle_inserted(inserted_);
}
else
it_ = prior_;
}
template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>
inline typename interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>::iterator
interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>
::_insert(const segment_type& addend)
{
interval_type inter_val = addend.first;
if(icl::is_empty(inter_val))
return this->_map.end();
const codomain_type& co_val = addend.second;
if(on_codomain_absorbtion::is_absorbable(co_val))
return this->_map.end();
std::pair<iterator,bool> insertion = this->_map.insert(addend);
if(insertion.second)
return that()->handle_inserted(insertion.first);
else
{
// Detect the first and the end iterator of the collision sequence
iterator first_ = this->_map.lower_bound(inter_val),
last_ = insertion.first;
//assert((++last_) == this->_map.upper_bound(inter_val));
iterator it_ = first_;
insert_main(inter_val, co_val, it_, last_);
return it_;
}
}
template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>
inline typename interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>::iterator
interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>
::_insert(iterator prior_, const segment_type& addend)
{
interval_type inter_val = addend.first;
if(icl::is_empty(inter_val))
return prior_;
const codomain_type& co_val = addend.second;
if(on_codomain_absorbtion::is_absorbable(co_val))
return prior_;
std::pair<iterator,bool> insertion = insert_at(prior_, inter_val, co_val);
if(insertion.second)
return that()->handle_inserted(insertion.first);
{
// Detect the first and the end iterator of the collision sequence
std::pair<iterator,iterator> overlap = equal_range(inter_val);
iterator it_ = overlap.first,
last_ = prior(overlap.second);
insert_main(inter_val, co_val, it_, last_);
return it_;
}
}
//==============================================================================
//= Erasure segment_type
//==============================================================================
template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>
inline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>
::erase_rest(interval_type& inter_val, const CodomainT& co_val,
iterator& it_, const iterator& last_)
{
// For all intervals within loop: (*it_).first are contained_in inter_val
while(it_ != last_)
if((*it_).second == co_val)
this->_map.erase(it_++);
else it_++;
//erase_rear:
if((*it_).second == co_val)
{
interval_type right_resid = left_subtract((*it_).first, inter_val);
if(icl::is_empty(right_resid))
this->_map.erase(it_);
else
const_cast<interval_type&>((*it_).first) = right_resid;
}
}
template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>
inline SubType& interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>
::erase(const segment_type& minuend)
{
interval_type inter_val = minuend.first;
if(icl::is_empty(inter_val))
return *that();
const codomain_type& co_val = minuend.second;
if(on_codomain_absorbtion::is_absorbable(co_val))
return *that();
std::pair<iterator,iterator> exterior = equal_range(inter_val);
if(exterior.first == exterior.second)
return *that();
iterator first_ = exterior.first, end_ = exterior.second,
last_ = cyclic_prior(*this, end_);
iterator second_= first_; ++second_;
if(first_ == last_)
{ // [----inter_val----)
// .....first_==last_.....
// only for the last there can be a right_resid: a part of *it_ right of minuend
interval_type right_resid = left_subtract((*first_).first, inter_val);
if((*first_).second == co_val)
{
interval_type left_resid = right_subtract((*first_).first, inter_val);
if(!icl::is_empty(left_resid)) // [----inter_val----)
{ // [left_resid)..first_==last_......
const_cast<interval_type&>((*first_).first) = left_resid;
if(!icl::is_empty(right_resid))
this->_map.insert(first_, value_type(right_resid, co_val));
}
else if(!icl::is_empty(right_resid))
const_cast<interval_type&>((*first_).first) = right_resid;
else
this->_map.erase(first_);
}
}
else
{
// first AND NOT last
if((*first_).second == co_val)
{
interval_type left_resid = right_subtract((*first_).first, inter_val);
if(icl::is_empty(left_resid))
this->_map.erase(first_);
else
const_cast<interval_type&>((*first_).first) = left_resid;
}
erase_rest(inter_val, co_val, second_, last_);
}
return *that();
}
//==============================================================================
//= Erasure key_type
//==============================================================================
template <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>
inline SubType& interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>
::erase(const interval_type& minuend)
{
if(icl::is_empty(minuend))
return *that();
std::pair<iterator, iterator> exterior = equal_range(minuend);
if(exterior.first == exterior.second)
return *that();
iterator first_ = exterior.first,
end_ = exterior.second,
last_ = prior(end_);
interval_type left_resid = right_subtract((*first_).first, minuend);
interval_type right_resid = left_subtract(last_ ->first, minuend);
if(first_ == last_ )
if(!icl::is_empty(left_resid))
{
const_cast<interval_type&>((*first_).first) = left_resid;
if(!icl::is_empty(right_resid))
this->_map.insert(first_, value_type(right_resid, (*first_).second));
}
else if(!icl::is_empty(right_resid))
const_cast<interval_type&>((*first_).first) = left_subtract((*first_).first, minuend);
else
this->_map.erase(first_);
else
{ // [-------- minuend ---------)
// [left_resid fst) . . . . [lst right_resid)
iterator second_= first_; ++second_;
iterator start_ = icl::is_empty(left_resid)? first_: second_;
iterator stop_ = icl::is_empty(right_resid)? end_ : last_ ;
this->_map.erase(start_, stop_); //erase [start_, stop_)
if(!icl::is_empty(left_resid))
const_cast<interval_type&>((*first_).first) = left_resid;
if(!icl::is_empty(right_resid))
const_cast<interval_type&>(last_ ->first) = right_resid;
}
return *that();
}
//-----------------------------------------------------------------------------
// type traits
//-----------------------------------------------------------------------------
template
<
class SubType,
class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc
>
struct is_map<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> >
{
typedef is_map<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> > type;
BOOST_STATIC_CONSTANT(bool, value = true);
};
template
<
class SubType,
class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc
>
struct has_inverse<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> >
{
typedef has_inverse<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> > type;
BOOST_STATIC_CONSTANT(bool, value = (has_inverse<CodomainT>::value));
};
template
<
class SubType,
class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc
>
struct is_interval_container<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> >
{
typedef is_interval_container<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> > type;
BOOST_STATIC_CONSTANT(bool, value = true);
};
template
<
class SubType,
class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc
>
struct absorbs_identities<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> >
{
typedef absorbs_identities<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> > type;
BOOST_STATIC_CONSTANT(bool, value = (Traits::absorbs_identities));
};
template
<
class SubType,
class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc
>
struct is_total<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> >
{
typedef is_total<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> > type;
BOOST_STATIC_CONSTANT(bool, value = (Traits::is_total));
};
}} // namespace icl boost
#endif
| Stevenwork/Innov_code | v0.9/innovApp/libboost_1_49_0/include/boost/icl/interval_base_map.hpp | C++ | lgpl-3.0 | 56,535 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
package org.apache.cassandra.repair.consistent;
import java.net.UnknownHostException;
import java.util.Set;
import java.util.UUID;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.junit.Ignore;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.locator.InetAddressAndPort;
import org.apache.cassandra.streaming.PreviewKind;
import org.apache.cassandra.service.ActiveRepairService;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.UUIDGen;
@Ignore
public abstract class AbstractConsistentSessionTest
{
protected static final InetAddressAndPort COORDINATOR;
protected static final InetAddressAndPort PARTICIPANT1;
protected static final InetAddressAndPort PARTICIPANT2;
protected static final InetAddressAndPort PARTICIPANT3;
static
{
try
{
COORDINATOR = InetAddressAndPort.getByName("10.0.0.1");
PARTICIPANT1 = InetAddressAndPort.getByName("10.0.0.1");
PARTICIPANT2 = InetAddressAndPort.getByName("10.0.0.2");
PARTICIPANT3 = InetAddressAndPort.getByName("10.0.0.3");
}
catch (UnknownHostException e)
{
throw new AssertionError(e);
}
DatabaseDescriptor.daemonInitialization();
}
protected static final Set<InetAddressAndPort> PARTICIPANTS = ImmutableSet.of(PARTICIPANT1, PARTICIPANT2, PARTICIPANT3);
protected static Token t(int v)
{
return DatabaseDescriptor.getPartitioner().getToken(ByteBufferUtil.bytes(v));
}
protected static final Range<Token> RANGE1 = new Range<>(t(1), t(2));
protected static final Range<Token> RANGE2 = new Range<>(t(2), t(3));
protected static final Range<Token> RANGE3 = new Range<>(t(4), t(5));
protected static UUID registerSession(ColumnFamilyStore cfs)
{
UUID sessionId = UUIDGen.getTimeUUID();
ActiveRepairService.instance.registerParentRepairSession(sessionId,
COORDINATOR,
Lists.newArrayList(cfs),
Sets.newHashSet(RANGE1, RANGE2, RANGE3),
true,
System.currentTimeMillis(),
true,
PreviewKind.NONE);
return sessionId;
}
}
| pauloricardomg/cassandra | test/unit/org/apache/cassandra/repair/consistent/AbstractConsistentSessionTest.java | Java | apache-2.0 | 3,628 |
/*
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.parse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* An operation that removes every instance of an element from an array field.
*/
/** package */ class ParseRemoveOperation implements ParseFieldOperation {
protected final HashSet<Object> objects = new HashSet<>();
public ParseRemoveOperation(Collection<?> coll) {
objects.addAll(coll);
}
@Override
public JSONObject encode(ParseEncoder objectEncoder) throws JSONException {
JSONObject output = new JSONObject();
output.put("__op", "Remove");
output.put("objects", objectEncoder.encode(new ArrayList<>(objects)));
return output;
}
@Override
public ParseFieldOperation mergeWithPrevious(ParseFieldOperation previous) {
if (previous == null) {
return this;
} else if (previous instanceof ParseDeleteOperation) {
return new ParseSetOperation(objects);
} else if (previous instanceof ParseSetOperation) {
Object value = ((ParseSetOperation) previous).getValue();
if (value instanceof JSONArray || value instanceof List) {
return new ParseSetOperation(this.apply(value, null));
} else {
throw new IllegalArgumentException("You can only add an item to a List or JSONArray.");
}
} else if (previous instanceof ParseRemoveOperation) {
HashSet<Object> result = new HashSet<>(((ParseRemoveOperation) previous).objects);
result.addAll(objects);
return new ParseRemoveOperation(result);
} else {
throw new IllegalArgumentException("Operation is invalid after previous operation.");
}
}
@Override
public Object apply(Object oldValue, String key) {
if (oldValue == null) {
return new ArrayList<>();
} else if (oldValue instanceof JSONArray) {
ArrayList<Object> old = ParseFieldOperations.jsonArrayAsArrayList((JSONArray) oldValue);
@SuppressWarnings("unchecked")
ArrayList<Object> newValue = (ArrayList<Object>) this.apply(old, key);
return new JSONArray(newValue);
} else if (oldValue instanceof List) {
ArrayList<Object> result = new ArrayList<>((List<?>) oldValue);
result.removeAll(objects);
// Remove the removed objects from "objects" -- the items remaining
// should be ones that weren't removed by object equality.
ArrayList<Object> objectsToBeRemoved = new ArrayList<>(objects);
objectsToBeRemoved.removeAll(result);
// Build up set of object IDs for any ParseObjects in the remaining objects-to-be-removed
HashSet<String> objectIds = new HashSet<>();
for (Object obj : objectsToBeRemoved) {
if (obj instanceof ParseObject) {
objectIds.add(((ParseObject) obj).getObjectId());
}
}
// And iterate over "result" to see if any other ParseObjects need to be removed
Iterator<Object> resultIterator = result.iterator();
while (resultIterator.hasNext()) {
Object obj = resultIterator.next();
if (obj instanceof ParseObject && objectIds.contains(((ParseObject) obj).getObjectId())) {
resultIterator.remove();
}
}
return result;
} else {
throw new IllegalArgumentException("Operation is invalid after previous operation.");
}
}
}
| MSchantz/Parse-SDK-Android | Parse/src/main/java/com/parse/ParseRemoveOperation.java | Java | bsd-3-clause | 3,725 |
<?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\Loader;
use Symfony\Component\Config\Resource\FileResource;
/**
* PhpFileLoader loads service definitions from a PHP file.
*
* The PHP file is required and the $container variable can be
* used within the file to change the container.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class PhpFileLoader extends FileLoader
{
/**
* Loads a PHP file.
*
* @param mixed $file The resource
* @param string $type The resource type
*/
public function load($file, $type = null)
{
// the container and loader variables are exposed to the included file below
$container = $this->container;
$loader = $this;
$path = $this->locator->locate($file);
$this->setCurrentDir(dirname($path));
$this->container->addResource(new FileResource($path));
include $path;
}
/**
* Returns true if this class supports the given resource.
*
* @param mixed $resource A resource
* @param string $type The resource type
*
* @return bool true if this class supports the given resource, false otherwise
*/
public function supports($resource, $type = null)
{
return is_string($resource) && 'php' === pathinfo($resource, PATHINFO_EXTENSION);
}
}
| ozshel/theseus | web_service/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Loader/PhpFileLoader.php | PHP | bsd-3-clause | 1,576 |
<!DOCTYPE html>
<html>
<!--
Copyright 2008 The Closure Library Authors. All Rights Reserved.
Use of this source code is governed by the Apache License, Version 2.0.
See the COPYING file for details.
-->
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="UTF-8" />
<title>goog.dom.NodeOffset Tests</title>
<script src="../base.js"></script>
<script>
goog.require('goog.dom.NodeOffsetTest');
</script>
</head>
<body>
<div id="test1">Text<br> and <b>more <i id="i">text.</i></b></div>
<div id="test2"></div>
<div id="empty"></div>
</body>
</html>
| LeoLombardi/tos-laimas-compass | tos-laimas-compass-win32-x64/resources/app/node_modules/closure-util/.deps/library/b06c979ecae7d78dd1ac4f7b09adec643baac308/closure/goog/dom/nodeoffset_test.html | HTML | mit | 574 |
/**
* version: 1.1.3
*/
angular.module('ngWig', ['ngwig-app-templates']);
angular.module('ngWig').directive('ngWig', function () {
return {
scope: {
content: '=ngWig'
},
restrict: 'A',
replace: true,
templateUrl: 'ng-wig/views/ng-wig.html',
link: function (scope, element, attrs) {
scope.originalHeight = element.outerHeight();
scope.editMode = false;
scope.autoexpand = !('autoexpand' in attrs) || attrs['autoexpand'] !== 'off';
scope.cssPath = scope.cssPath ? scope.cssPath : 'css/ng-wig.css';
scope.toggleEditMode = function() {
scope.editMode = !scope.editMode;
};
scope.execCommand = function (command, options) {
if(command ==='createlink'){
options = prompt('Please enter the URL', 'http://');
}
scope.$emit('execCommand', {command: command, options: options});
};
}
}
}
);
angular.module('ngWig').directive('ngWigEditable', function () {
function init(scope, $element, attrs, ctrl) {
var document = $element[0].ownerDocument;
$element.attr('contenteditable', true);
//model --> view
ctrl.$render = function () {
$element.html(ctrl.$viewValue || '');
};
//view --> model
function viewToModel() {
ctrl.$setViewValue($element.html());
}
$element.bind('blur keyup change paste', viewToModel);
scope.$on('execCommand', function (event, params) {
$element[0].focus();
var ieStyleTextSelection = document.selection,
command = params.command,
options = params.options;
if (ieStyleTextSelection) {
var textRange = ieStyleTextSelection.createRange();
}
document.execCommand(command, false, options);
if (ieStyleTextSelection) {
textRange.collapse(false);
textRange.select();
}
viewToModel();
});
}
return {
restrict: 'A',
require: 'ngModel',
replace: true,
link: init
}
}
);
/**
* No box-sizing, such a shame
*
* 1.Calculate outer height
* @param bool Include margin
* @returns Number Height in pixels
*
* 2. Set outer height
* @param Number Height in pixels
* @param bool Include margin
* @returns angular.element Collection
*/
if (typeof angular.element.prototype.outerHeight !== 'function') {
angular.element.prototype.outerHeight = function() {
function parsePixels(cssString) {
if (cssString.slice(-2) === 'px') {
return parseFloat(cssString.slice(0, -2));
}
return 0;
}
var includeMargin = false, height, $element = this.eq(0), element = $element[0];
if (arguments[0] === true || arguments[0] === false || arguments[0] === undefined) {
if (!$element.length) {
return 0;
}
includeMargin = arguments[0] && true || false;
if (element.outerHeight) {
height = element.outerHeight;
} else {
height = element.offsetHeight;
}
if (includeMargin) {
height += parsePixels($element.css('marginTop')) + parsePixels($element.css('marginBottom'));
}
return height;
} else {
if (!$element.length) {
return this;
}
height = parseFloat(arguments[0]);
includeMargin = arguments[1] && true || false;
if (includeMargin) {
height -= parsePixels($element.css('marginTop')) + parsePixels($element.css('marginBottom'));
}
height -= parsePixels($element.css('borderTopWidth')) + parsePixels($element.css('borderBottomWidth')) +
parsePixels($element.css('paddingTop')) + parsePixels($element.css('paddingBottom'));
$element.css('height', height + 'px');
return this;
}
};
}
angular.module('ngwig-app-templates', ['ng-wig/views/ng-wig.html']);
angular.module("ng-wig/views/ng-wig.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("ng-wig/views/ng-wig.html",
"<div class=\"ng-wig\">\n" +
" <ul class=\"nw-toolbar\">\n" +
" <li class=\"nw-toolbar__item\">\n" +
" <button type=\"button\" class=\"nw-button nw-button--header-one\" title=\"Header\" ng-click=\"execCommand('formatblock', '<h1>')\"></button>\n" +
" </li><!--\n" +
" --><li class=\"nw-toolbar__item\">\n" +
" <button type=\"button\" class=\"nw-button nw-button--paragraph\" title=\"Paragraph\" ng-click=\"execCommand('formatblock', '<p>')\"></button>\n" +
" </li><!--\n" +
" --><li class=\"nw-toolbar__item\">\n" +
" <button type=\"button\" class=\"nw-button nw-button--unordered-list\" title=\"Unordered List\" ng-click=\"execCommand('insertunorderedlist')\"></button>\n" +
" </li><!--\n" +
" --><li class=\"nw-toolbar__item\">\n" +
" <button type=\"button\" class=\"nw-button nw-button--ordered-list\" title=\"Ordered List\" ng-click=\"execCommand('insertorderedlist')\"></button>\n" +
" </li><!--\n" +
" --><li class=\"nw-toolbar__item\">\n" +
" <button type=\"button\" class=\"nw-button nw-button--bold\" title=\"Bold\" ng-click=\"execCommand('bold')\"></button>\n" +
" </li><!--\n" +
" --><li class=\"nw-toolbar__item\">\n" +
" <button type=\"button\" class=\"nw-button nw-button--italic\" title=\"Italic\" ng-click=\"execCommand('italic')\"></button>\n" +
" </li><!--\n" +
" --><li class=\"nw-toolbar__item\">\n" +
" <button type=\"button\" class=\"nw-button nw-button--link\" title=\"link\" ng-click=\"execCommand('createlink')\"></button>\n" +
" </li><!--\n" +
" --><li class=\"nw-toolbar__item\">\n" +
" <button type=\"button\" class=\"nw-button nw-button--source\" ng-class=\"{ 'nw-button--active': editMode }\" ng-click=\"toggleEditMode()\"></button>\n" +
" </li>\n" +
" </ul>\n" +
"\n" +
" <div class=\"nw-editor-container\">\n" +
" <div class=\"nw-editor\">\n" +
" <textarea class=\"nw-editor__src\" ng-show=\"editMode\" ng-model=\"content\"></textarea>\n" +
" <div ng-class=\"{'nw-invisible': editMode, 'nw-autoexpand': autoexpand}\" class=\"nw-editor__res\" ng-model=\"content\" ng-wig-editable></div>\n" +
" </div>\n" +
" </div>\n" +
"</div>\n" +
"");
}]);
| dhenson02/cdnjs | ajax/libs/ng-wig/1.1.3/ng-wig.js | JavaScript | mit | 6,452 |
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef _ARCH_POWERPC_LOCAL_H
#define _ARCH_POWERPC_LOCAL_H
#include <linux/percpu.h>
#include <linux/atomic.h>
typedef struct
{
atomic_long_t a;
} local_t;
#define LOCAL_INIT(i) { ATOMIC_LONG_INIT(i) }
#define local_read(l) atomic_long_read(&(l)->a)
#define local_set(l,i) atomic_long_set(&(l)->a, (i))
#define local_add(i,l) atomic_long_add((i),(&(l)->a))
#define local_sub(i,l) atomic_long_sub((i),(&(l)->a))
#define local_inc(l) atomic_long_inc(&(l)->a)
#define local_dec(l) atomic_long_dec(&(l)->a)
static __inline__ long local_add_return(long a, local_t *l)
{
long t;
__asm__ __volatile__(
"1:" PPC_LLARX(%0,0,%2,0) " # local_add_return\n\
add %0,%1,%0\n"
PPC405_ERR77(0,%2)
PPC_STLCX "%0,0,%2 \n\
bne- 1b"
: "=&r" (t)
: "r" (a), "r" (&(l->a.counter))
: "cc", "memory");
return t;
}
#define local_add_negative(a, l) (local_add_return((a), (l)) < 0)
static __inline__ long local_sub_return(long a, local_t *l)
{
long t;
__asm__ __volatile__(
"1:" PPC_LLARX(%0,0,%2,0) " # local_sub_return\n\
subf %0,%1,%0\n"
PPC405_ERR77(0,%2)
PPC_STLCX "%0,0,%2 \n\
bne- 1b"
: "=&r" (t)
: "r" (a), "r" (&(l->a.counter))
: "cc", "memory");
return t;
}
static __inline__ long local_inc_return(local_t *l)
{
long t;
__asm__ __volatile__(
"1:" PPC_LLARX(%0,0,%1,0) " # local_inc_return\n\
addic %0,%0,1\n"
PPC405_ERR77(0,%1)
PPC_STLCX "%0,0,%1 \n\
bne- 1b"
: "=&r" (t)
: "r" (&(l->a.counter))
: "cc", "xer", "memory");
return t;
}
/*
* local_inc_and_test - increment and test
* @l: pointer of type local_t
*
* Atomically increments @l by 1
* and returns true if the result is zero, or false for all
* other cases.
*/
#define local_inc_and_test(l) (local_inc_return(l) == 0)
static __inline__ long local_dec_return(local_t *l)
{
long t;
__asm__ __volatile__(
"1:" PPC_LLARX(%0,0,%1,0) " # local_dec_return\n\
addic %0,%0,-1\n"
PPC405_ERR77(0,%1)
PPC_STLCX "%0,0,%1\n\
bne- 1b"
: "=&r" (t)
: "r" (&(l->a.counter))
: "cc", "xer", "memory");
return t;
}
#define local_cmpxchg(l, o, n) \
(cmpxchg_local(&((l)->a.counter), (o), (n)))
#define local_xchg(l, n) (xchg_local(&((l)->a.counter), (n)))
/**
* local_add_unless - add unless the number is a given value
* @l: pointer of type local_t
* @a: the amount to add to v...
* @u: ...unless v is equal to u.
*
* Atomically adds @a to @l, so long as it was not @u.
* Returns non-zero if @l was not @u, and zero otherwise.
*/
static __inline__ int local_add_unless(local_t *l, long a, long u)
{
long t;
__asm__ __volatile__ (
"1:" PPC_LLARX(%0,0,%1,0) " # local_add_unless\n\
cmpw 0,%0,%3 \n\
beq- 2f \n\
add %0,%2,%0 \n"
PPC405_ERR77(0,%2)
PPC_STLCX "%0,0,%1 \n\
bne- 1b \n"
" subf %0,%2,%0 \n\
2:"
: "=&r" (t)
: "r" (&(l->a.counter)), "r" (a), "r" (u)
: "cc", "memory");
return t != u;
}
#define local_inc_not_zero(l) local_add_unless((l), 1, 0)
#define local_sub_and_test(a, l) (local_sub_return((a), (l)) == 0)
#define local_dec_and_test(l) (local_dec_return((l)) == 0)
/*
* Atomically test *l and decrement if it is greater than 0.
* The function returns the old value of *l minus 1.
*/
static __inline__ long local_dec_if_positive(local_t *l)
{
long t;
__asm__ __volatile__(
"1:" PPC_LLARX(%0,0,%1,0) " # local_dec_if_positive\n\
cmpwi %0,1\n\
addi %0,%0,-1\n\
blt- 2f\n"
PPC405_ERR77(0,%1)
PPC_STLCX "%0,0,%1\n\
bne- 1b"
"\n\
2:" : "=&b" (t)
: "r" (&(l->a.counter))
: "cc", "memory");
return t;
}
/* Use these for per-cpu local_t variables: on some archs they are
* much more efficient than these naive implementations. Note they take
* a variable, not an address.
*/
#define __local_inc(l) ((l)->a.counter++)
#define __local_dec(l) ((l)->a.counter++)
#define __local_add(i,l) ((l)->a.counter+=(i))
#define __local_sub(i,l) ((l)->a.counter-=(i))
#endif /* _ARCH_POWERPC_LOCAL_H */
| BPI-SINOVOIP/BPI-Mainline-kernel | linux-4.14/arch/powerpc/include/asm/local.h | C | gpl-2.0 | 3,886 |
/*
* (C) COPYRIGHT 2016 ARM Limited. All rights reserved.
* Author: Liviu Dudau <Liviu.Dudau@arm.com>
*
* This program is free software and is provided to you under the terms of the
* GNU General Public License version 2 as published by the Free Software
* Foundation, and any use by you of this program is subject to the terms
* of such GNU licence.
*
* ARM Mali DP500/DP550/DP650 driver (crtc operations)
*/
#include <drm/drmP.h>
#include <drm/drm_atomic.h>
#include <drm/drm_atomic_helper.h>
#include <drm/drm_crtc.h>
#include <drm/drm_crtc_helper.h>
#include <linux/clk.h>
#include <linux/pm_runtime.h>
#include <video/videomode.h>
#include "malidp_drv.h"
#include "malidp_hw.h"
static enum drm_mode_status malidp_crtc_mode_valid(struct drm_crtc *crtc,
const struct drm_display_mode *mode)
{
struct malidp_drm *malidp = crtc_to_malidp_device(crtc);
struct malidp_hw_device *hwdev = malidp->dev;
/*
* check that the hardware can drive the required clock rate,
* but skip the check if the clock is meant to be disabled (req_rate = 0)
*/
long rate, req_rate = mode->crtc_clock * 1000;
if (req_rate) {
rate = clk_round_rate(hwdev->pxlclk, req_rate);
if (rate != req_rate) {
DRM_DEBUG_DRIVER("pxlclk doesn't support %ld Hz\n",
req_rate);
return MODE_NOCLOCK;
}
}
return MODE_OK;
}
static void malidp_crtc_atomic_enable(struct drm_crtc *crtc,
struct drm_crtc_state *old_state)
{
struct malidp_drm *malidp = crtc_to_malidp_device(crtc);
struct malidp_hw_device *hwdev = malidp->dev;
struct videomode vm;
int err = pm_runtime_get_sync(crtc->dev->dev);
if (err < 0) {
DRM_DEBUG_DRIVER("Failed to enable runtime power management: %d\n", err);
return;
}
drm_display_mode_to_videomode(&crtc->state->adjusted_mode, &vm);
clk_prepare_enable(hwdev->pxlclk);
/* We rely on firmware to set mclk to a sensible level. */
clk_set_rate(hwdev->pxlclk, crtc->state->adjusted_mode.crtc_clock * 1000);
hwdev->modeset(hwdev, &vm);
hwdev->leave_config_mode(hwdev);
drm_crtc_vblank_on(crtc);
}
static void malidp_crtc_atomic_disable(struct drm_crtc *crtc,
struct drm_crtc_state *old_state)
{
struct malidp_drm *malidp = crtc_to_malidp_device(crtc);
struct malidp_hw_device *hwdev = malidp->dev;
int err;
drm_crtc_vblank_off(crtc);
hwdev->enter_config_mode(hwdev);
clk_disable_unprepare(hwdev->pxlclk);
err = pm_runtime_put(crtc->dev->dev);
if (err < 0) {
DRM_DEBUG_DRIVER("Failed to disable runtime power management: %d\n", err);
}
}
static const struct gamma_curve_segment {
u16 start;
u16 end;
} segments[MALIDP_COEFFTAB_NUM_COEFFS] = {
/* sector 0 */
{ 0, 0 }, { 1, 1 }, { 2, 2 }, { 3, 3 },
{ 4, 4 }, { 5, 5 }, { 6, 6 }, { 7, 7 },
{ 8, 8 }, { 9, 9 }, { 10, 10 }, { 11, 11 },
{ 12, 12 }, { 13, 13 }, { 14, 14 }, { 15, 15 },
/* sector 1 */
{ 16, 19 }, { 20, 23 }, { 24, 27 }, { 28, 31 },
/* sector 2 */
{ 32, 39 }, { 40, 47 }, { 48, 55 }, { 56, 63 },
/* sector 3 */
{ 64, 79 }, { 80, 95 }, { 96, 111 }, { 112, 127 },
/* sector 4 */
{ 128, 159 }, { 160, 191 }, { 192, 223 }, { 224, 255 },
/* sector 5 */
{ 256, 319 }, { 320, 383 }, { 384, 447 }, { 448, 511 },
/* sector 6 */
{ 512, 639 }, { 640, 767 }, { 768, 895 }, { 896, 1023 },
{ 1024, 1151 }, { 1152, 1279 }, { 1280, 1407 }, { 1408, 1535 },
{ 1536, 1663 }, { 1664, 1791 }, { 1792, 1919 }, { 1920, 2047 },
{ 2048, 2175 }, { 2176, 2303 }, { 2304, 2431 }, { 2432, 2559 },
{ 2560, 2687 }, { 2688, 2815 }, { 2816, 2943 }, { 2944, 3071 },
{ 3072, 3199 }, { 3200, 3327 }, { 3328, 3455 }, { 3456, 3583 },
{ 3584, 3711 }, { 3712, 3839 }, { 3840, 3967 }, { 3968, 4095 },
};
#define DE_COEFTAB_DATA(a, b) ((((a) & 0xfff) << 16) | (((b) & 0xfff)))
static void malidp_generate_gamma_table(struct drm_property_blob *lut_blob,
u32 coeffs[MALIDP_COEFFTAB_NUM_COEFFS])
{
struct drm_color_lut *lut = (struct drm_color_lut *)lut_blob->data;
int i;
for (i = 0; i < MALIDP_COEFFTAB_NUM_COEFFS; ++i) {
u32 a, b, delta_in, out_start, out_end;
delta_in = segments[i].end - segments[i].start;
/* DP has 12-bit internal precision for its LUTs. */
out_start = drm_color_lut_extract(lut[segments[i].start].green,
12);
out_end = drm_color_lut_extract(lut[segments[i].end].green, 12);
a = (delta_in == 0) ? 0 : ((out_end - out_start) * 256) / delta_in;
b = out_start;
coeffs[i] = DE_COEFTAB_DATA(a, b);
}
}
/*
* Check if there is a new gamma LUT and if it is of an acceptable size. Also,
* reject any LUTs that use distinct red, green, and blue curves.
*/
static int malidp_crtc_atomic_check_gamma(struct drm_crtc *crtc,
struct drm_crtc_state *state)
{
struct malidp_crtc_state *mc = to_malidp_crtc_state(state);
struct drm_color_lut *lut;
size_t lut_size;
int i;
if (!state->color_mgmt_changed || !state->gamma_lut)
return 0;
if (crtc->state->gamma_lut &&
(crtc->state->gamma_lut->base.id == state->gamma_lut->base.id))
return 0;
if (state->gamma_lut->length % sizeof(struct drm_color_lut))
return -EINVAL;
lut_size = state->gamma_lut->length / sizeof(struct drm_color_lut);
if (lut_size != MALIDP_GAMMA_LUT_SIZE)
return -EINVAL;
lut = (struct drm_color_lut *)state->gamma_lut->data;
for (i = 0; i < lut_size; ++i)
if (!((lut[i].red == lut[i].green) &&
(lut[i].red == lut[i].blue)))
return -EINVAL;
if (!state->mode_changed) {
int ret;
state->mode_changed = true;
/*
* Kerneldoc for drm_atomic_helper_check_modeset mandates that
* it be invoked when the driver sets ->mode_changed. Since
* changing the gamma LUT doesn't depend on any external
* resources, it is safe to call it only once.
*/
ret = drm_atomic_helper_check_modeset(crtc->dev, state->state);
if (ret)
return ret;
}
malidp_generate_gamma_table(state->gamma_lut, mc->gamma_coeffs);
return 0;
}
/*
* Check if there is a new CTM and if it contains valid input. Valid here means
* that the number is inside the representable range for a Q3.12 number,
* excluding truncating the fractional part of the input data.
*
* The COLORADJ registers can be changed atomically.
*/
static int malidp_crtc_atomic_check_ctm(struct drm_crtc *crtc,
struct drm_crtc_state *state)
{
struct malidp_crtc_state *mc = to_malidp_crtc_state(state);
struct drm_color_ctm *ctm;
int i;
if (!state->color_mgmt_changed)
return 0;
if (!state->ctm)
return 0;
if (crtc->state->ctm && (crtc->state->ctm->base.id ==
state->ctm->base.id))
return 0;
/*
* The size of the ctm is checked in
* drm_atomic_replace_property_blob_from_id.
*/
ctm = (struct drm_color_ctm *)state->ctm->data;
for (i = 0; i < ARRAY_SIZE(ctm->matrix); ++i) {
/* Convert from S31.32 to Q3.12. */
s64 val = ctm->matrix[i];
u32 mag = ((((u64)val) & ~BIT_ULL(63)) >> 20) &
GENMASK_ULL(14, 0);
/*
* Convert to 2s complement and check the destination's top bit
* for overflow. NB: Can't check before converting or it'd
* incorrectly reject the case:
* sign == 1
* mag == 0x2000
*/
if (val & BIT_ULL(63))
mag = ~mag + 1;
if (!!(val & BIT_ULL(63)) != !!(mag & BIT(14)))
return -EINVAL;
mc->coloradj_coeffs[i] = mag;
}
return 0;
}
static int malidp_crtc_atomic_check_scaling(struct drm_crtc *crtc,
struct drm_crtc_state *state)
{
struct malidp_drm *malidp = crtc_to_malidp_device(crtc);
struct malidp_hw_device *hwdev = malidp->dev;
struct malidp_crtc_state *cs = to_malidp_crtc_state(state);
struct malidp_se_config *s = &cs->scaler_config;
struct drm_plane *plane;
struct videomode vm;
const struct drm_plane_state *pstate;
u32 h_upscale_factor = 0; /* U16.16 */
u32 v_upscale_factor = 0; /* U16.16 */
u8 scaling = cs->scaled_planes_mask;
int ret;
if (!scaling) {
s->scale_enable = false;
goto mclk_calc;
}
/* The scaling engine can only handle one plane at a time. */
if (scaling & (scaling - 1))
return -EINVAL;
drm_atomic_crtc_state_for_each_plane_state(plane, pstate, state) {
struct malidp_plane *mp = to_malidp_plane(plane);
u32 phase;
if (!(mp->layer->id & scaling))
continue;
/*
* Convert crtc_[w|h] to U32.32, then divide by U16.16 src_[w|h]
* to get the U16.16 result.
*/
h_upscale_factor = div_u64((u64)pstate->crtc_w << 32,
pstate->src_w);
v_upscale_factor = div_u64((u64)pstate->crtc_h << 32,
pstate->src_h);
s->enhancer_enable = ((h_upscale_factor >> 16) >= 2 ||
(v_upscale_factor >> 16) >= 2);
s->input_w = pstate->src_w >> 16;
s->input_h = pstate->src_h >> 16;
s->output_w = pstate->crtc_w;
s->output_h = pstate->crtc_h;
#define SE_N_PHASE 4
#define SE_SHIFT_N_PHASE 12
/* Calculate initial_phase and delta_phase for horizontal. */
phase = s->input_w;
s->h_init_phase =
((phase << SE_N_PHASE) / s->output_w + 1) / 2;
phase = s->input_w;
phase <<= (SE_SHIFT_N_PHASE + SE_N_PHASE);
s->h_delta_phase = phase / s->output_w;
/* Same for vertical. */
phase = s->input_h;
s->v_init_phase =
((phase << SE_N_PHASE) / s->output_h + 1) / 2;
phase = s->input_h;
phase <<= (SE_SHIFT_N_PHASE + SE_N_PHASE);
s->v_delta_phase = phase / s->output_h;
#undef SE_N_PHASE
#undef SE_SHIFT_N_PHASE
s->plane_src_id = mp->layer->id;
}
s->scale_enable = true;
s->hcoeff = malidp_se_select_coeffs(h_upscale_factor);
s->vcoeff = malidp_se_select_coeffs(v_upscale_factor);
mclk_calc:
drm_display_mode_to_videomode(&state->adjusted_mode, &vm);
ret = hwdev->se_calc_mclk(hwdev, s, &vm);
if (ret < 0)
return -EINVAL;
return 0;
}
static int malidp_crtc_atomic_check(struct drm_crtc *crtc,
struct drm_crtc_state *state)
{
struct malidp_drm *malidp = crtc_to_malidp_device(crtc);
struct malidp_hw_device *hwdev = malidp->dev;
struct drm_plane *plane;
const struct drm_plane_state *pstate;
u32 rot_mem_free, rot_mem_usable;
int rotated_planes = 0;
int ret;
/*
* check if there is enough rotation memory available for planes
* that need 90° and 270° rotation. Each plane has set its required
* memory size in the ->plane_check() callback, here we only make
* sure that the sums are less that the total usable memory.
*
* The rotation memory allocation algorithm (for each plane):
* a. If no more rotated planes exist, all remaining rotate
* memory in the bank is available for use by the plane.
* b. If other rotated planes exist, and plane's layer ID is
* DE_VIDEO1, it can use all the memory from first bank if
* secondary rotation memory bank is available, otherwise it can
* use up to half the bank's memory.
* c. If other rotated planes exist, and plane's layer ID is not
* DE_VIDEO1, it can use half of the available memory
*
* Note: this algorithm assumes that the order in which the planes are
* checked always has DE_VIDEO1 plane first in the list if it is
* rotated. Because that is how we create the planes in the first
* place, under current DRM version things work, but if ever the order
* in which drm_atomic_crtc_state_for_each_plane() iterates over planes
* changes, we need to pre-sort the planes before validation.
*/
/* first count the number of rotated planes */
drm_atomic_crtc_state_for_each_plane_state(plane, pstate, state) {
if (pstate->rotation & MALIDP_ROTATED_MASK)
rotated_planes++;
}
rot_mem_free = hwdev->rotation_memory[0];
/*
* if we have more than 1 plane using rotation memory, use the second
* block of rotation memory as well
*/
if (rotated_planes > 1)
rot_mem_free += hwdev->rotation_memory[1];
/* now validate the rotation memory requirements */
drm_atomic_crtc_state_for_each_plane_state(plane, pstate, state) {
struct malidp_plane *mp = to_malidp_plane(plane);
struct malidp_plane_state *ms = to_malidp_plane_state(pstate);
if (pstate->rotation & MALIDP_ROTATED_MASK) {
/* process current plane */
rotated_planes--;
if (!rotated_planes) {
/* no more rotated planes, we can use what's left */
rot_mem_usable = rot_mem_free;
} else {
if ((mp->layer->id != DE_VIDEO1) ||
(hwdev->rotation_memory[1] == 0))
rot_mem_usable = rot_mem_free / 2;
else
rot_mem_usable = hwdev->rotation_memory[0];
}
rot_mem_free -= rot_mem_usable;
if (ms->rotmem_size > rot_mem_usable)
return -EINVAL;
}
}
ret = malidp_crtc_atomic_check_gamma(crtc, state);
ret = ret ? ret : malidp_crtc_atomic_check_ctm(crtc, state);
ret = ret ? ret : malidp_crtc_atomic_check_scaling(crtc, state);
return ret;
}
static const struct drm_crtc_helper_funcs malidp_crtc_helper_funcs = {
.mode_valid = malidp_crtc_mode_valid,
.atomic_check = malidp_crtc_atomic_check,
.atomic_enable = malidp_crtc_atomic_enable,
.atomic_disable = malidp_crtc_atomic_disable,
};
static struct drm_crtc_state *malidp_crtc_duplicate_state(struct drm_crtc *crtc)
{
struct malidp_crtc_state *state, *old_state;
if (WARN_ON(!crtc->state))
return NULL;
old_state = to_malidp_crtc_state(crtc->state);
state = kmalloc(sizeof(*state), GFP_KERNEL);
if (!state)
return NULL;
__drm_atomic_helper_crtc_duplicate_state(crtc, &state->base);
memcpy(state->gamma_coeffs, old_state->gamma_coeffs,
sizeof(state->gamma_coeffs));
memcpy(state->coloradj_coeffs, old_state->coloradj_coeffs,
sizeof(state->coloradj_coeffs));
memcpy(&state->scaler_config, &old_state->scaler_config,
sizeof(state->scaler_config));
state->scaled_planes_mask = 0;
return &state->base;
}
static void malidp_crtc_reset(struct drm_crtc *crtc)
{
struct malidp_crtc_state *state = NULL;
if (crtc->state) {
state = to_malidp_crtc_state(crtc->state);
__drm_atomic_helper_crtc_destroy_state(crtc->state);
}
kfree(state);
state = kzalloc(sizeof(*state), GFP_KERNEL);
if (state) {
crtc->state = &state->base;
crtc->state->crtc = crtc;
}
}
static void malidp_crtc_destroy_state(struct drm_crtc *crtc,
struct drm_crtc_state *state)
{
struct malidp_crtc_state *mali_state = NULL;
if (state) {
mali_state = to_malidp_crtc_state(state);
__drm_atomic_helper_crtc_destroy_state(state);
}
kfree(mali_state);
}
static int malidp_crtc_enable_vblank(struct drm_crtc *crtc)
{
struct malidp_drm *malidp = crtc_to_malidp_device(crtc);
struct malidp_hw_device *hwdev = malidp->dev;
malidp_hw_enable_irq(hwdev, MALIDP_DE_BLOCK,
hwdev->map.de_irq_map.vsync_irq);
return 0;
}
static void malidp_crtc_disable_vblank(struct drm_crtc *crtc)
{
struct malidp_drm *malidp = crtc_to_malidp_device(crtc);
struct malidp_hw_device *hwdev = malidp->dev;
malidp_hw_disable_irq(hwdev, MALIDP_DE_BLOCK,
hwdev->map.de_irq_map.vsync_irq);
}
static const struct drm_crtc_funcs malidp_crtc_funcs = {
.gamma_set = drm_atomic_helper_legacy_gamma_set,
.destroy = drm_crtc_cleanup,
.set_config = drm_atomic_helper_set_config,
.page_flip = drm_atomic_helper_page_flip,
.reset = malidp_crtc_reset,
.atomic_duplicate_state = malidp_crtc_duplicate_state,
.atomic_destroy_state = malidp_crtc_destroy_state,
.enable_vblank = malidp_crtc_enable_vblank,
.disable_vblank = malidp_crtc_disable_vblank,
};
int malidp_crtc_init(struct drm_device *drm)
{
struct malidp_drm *malidp = drm->dev_private;
struct drm_plane *primary = NULL, *plane;
int ret;
ret = malidp_de_planes_init(drm);
if (ret < 0) {
DRM_ERROR("Failed to initialise planes\n");
return ret;
}
drm_for_each_plane(plane, drm) {
if (plane->type == DRM_PLANE_TYPE_PRIMARY) {
primary = plane;
break;
}
}
if (!primary) {
DRM_ERROR("no primary plane found\n");
ret = -EINVAL;
goto crtc_cleanup_planes;
}
ret = drm_crtc_init_with_planes(drm, &malidp->crtc, primary, NULL,
&malidp_crtc_funcs, NULL);
if (ret)
goto crtc_cleanup_planes;
drm_crtc_helper_add(&malidp->crtc, &malidp_crtc_helper_funcs);
drm_mode_crtc_set_gamma_size(&malidp->crtc, MALIDP_GAMMA_LUT_SIZE);
/* No inverse-gamma: it is per-plane. */
drm_crtc_enable_color_mgmt(&malidp->crtc, 0, true, MALIDP_GAMMA_LUT_SIZE);
malidp_se_set_enh_coeffs(malidp->dev);
return 0;
crtc_cleanup_planes:
malidp_de_planes_destroy(drm);
return ret;
}
| BPI-SINOVOIP/BPI-Mainline-kernel | linux-4.14/drivers/gpu/drm/arm/malidp_crtc.c | C | gpl-2.0 | 16,219 |
// Copyright (C) 2003-2015 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, 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 General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#include <testsuite_performance.h>
template<typename Container, int Iter>
void
do_loop()
{
// avoid excessive swap file use!
static const unsigned max_size = 250000;
// make results less random while
static const unsigned iterations = 10;
// keeping the total time reasonable
static const unsigned step = 50000;
using namespace std;
typedef int test_type;
typedef Container container_type;
typedef vector<test_type> vector_type;
// Initialize sorted array.
vector_type v(max_size, 0);
for (unsigned int i = 0; i != max_size; ++i)
v[i] = i;
for (unsigned int count = step; count <= max_size; count += step)
{
for (unsigned i = 0; i != iterations; ++i)
{
container_type test_set;
typename container_type::iterator iter = test_set.end();
// Each insert in amortized constant time (Table 69)
for (unsigned j = 0; j != count; ++j)
iter = test_set.insert(iter, v[j]);
}
}
}
int
main()
{
#ifdef TEST_S1
#define thread_type false
#endif
#ifdef TEST_T1
#define thread_type true
#endif
typedef __gnu_test::sets<int, thread_type>::type container_types;
typedef test_sequence<thread_type> test_type;
test_type test("insert_from_sorted");
__gnu_cxx::typelist::apply(test, container_types());
return 0;
}
| zjh171/gcc | libstdc++-v3/testsuite/performance/23_containers/insert_from_sorted/set.cc | C++ | gpl-2.0 | 2,129 |
/* Kernel thread helper functions.
* Copyright (C) 2004 IBM Corporation, Rusty Russell.
*
* Creation is done via kthreadd, so that we get a clean environment
* even if we're invoked from userspace (think modprobe, hotplug cpu,
* etc.).
*/
#include <linux/sched.h>
#include <linux/kthread.h>
#include <linux/completion.h>
#include <linux/err.h>
#include <linux/cpuset.h>
#include <linux/unistd.h>
#include <linux/file.h>
#include <linux/export.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <linux/freezer.h>
#include <linux/ptrace.h>
#include <linux/uaccess.h>
#include <trace/events/sched.h>
static DEFINE_SPINLOCK(kthread_create_lock);
static LIST_HEAD(kthread_create_list);
struct task_struct *kthreadd_task;
struct kthread_create_info
{
/* Information passed to kthread() from kthreadd. */
int (*threadfn)(void *data);
void *data;
int node;
/* Result passed back to kthread_create() from kthreadd. */
struct task_struct *result;
struct completion *done;
struct list_head list;
};
struct kthread {
unsigned long flags;
unsigned int cpu;
void *data;
struct completion parked;
struct completion exited;
};
enum KTHREAD_BITS {
KTHREAD_IS_PER_CPU = 0,
KTHREAD_SHOULD_STOP,
KTHREAD_SHOULD_PARK,
KTHREAD_IS_PARKED,
};
#define __to_kthread(vfork) \
container_of(vfork, struct kthread, exited)
static inline struct kthread *to_kthread(struct task_struct *k)
{
return __to_kthread(k->vfork_done);
}
static struct kthread *to_live_kthread(struct task_struct *k)
{
struct completion *vfork = ACCESS_ONCE(k->vfork_done);
if (likely(vfork))
return __to_kthread(vfork);
return NULL;
}
/**
* kthread_should_stop - should this kthread return now?
*
* When someone calls kthread_stop() on your kthread, it will be woken
* and this will return true. You should then return, and your return
* value will be passed through to kthread_stop().
*/
bool kthread_should_stop(void)
{
return test_bit(KTHREAD_SHOULD_STOP, &to_kthread(current)->flags);
}
EXPORT_SYMBOL(kthread_should_stop);
/**
* kthread_should_park - should this kthread park now?
*
* When someone calls kthread_park() on your kthread, it will be woken
* and this will return true. You should then do the necessary
* cleanup and call kthread_parkme()
*
* Similar to kthread_should_stop(), but this keeps the thread alive
* and in a park position. kthread_unpark() "restarts" the thread and
* calls the thread function again.
*/
bool kthread_should_park(void)
{
return test_bit(KTHREAD_SHOULD_PARK, &to_kthread(current)->flags);
}
/**
* kthread_freezable_should_stop - should this freezable kthread return now?
* @was_frozen: optional out parameter, indicates whether %current was frozen
*
* kthread_should_stop() for freezable kthreads, which will enter
* refrigerator if necessary. This function is safe from kthread_stop() /
* freezer deadlock and freezable kthreads should use this function instead
* of calling try_to_freeze() directly.
*/
bool kthread_freezable_should_stop(bool *was_frozen)
{
bool frozen = false;
might_sleep();
if (unlikely(freezing(current)))
frozen = __refrigerator(true);
if (was_frozen)
*was_frozen = frozen;
return kthread_should_stop();
}
EXPORT_SYMBOL_GPL(kthread_freezable_should_stop);
/**
* kthread_data - return data value specified on kthread creation
* @task: kthread task in question
*
* Return the data value specified when kthread @task was created.
* The caller is responsible for ensuring the validity of @task when
* calling this function.
*/
void *kthread_data(struct task_struct *task)
{
return to_kthread(task)->data;
}
/**
* probe_kthread_data - speculative version of kthread_data()
* @task: possible kthread task in question
*
* @task could be a kthread task. Return the data value specified when it
* was created if accessible. If @task isn't a kthread task or its data is
* inaccessible for any reason, %NULL is returned. This function requires
* that @task itself is safe to dereference.
*/
void *probe_kthread_data(struct task_struct *task)
{
struct kthread *kthread = to_kthread(task);
void *data = NULL;
probe_kernel_read(&data, &kthread->data, sizeof(data));
return data;
}
static void __kthread_parkme(struct kthread *self)
{
__set_current_state(TASK_PARKED);
while (test_bit(KTHREAD_SHOULD_PARK, &self->flags)) {
if (!test_and_set_bit(KTHREAD_IS_PARKED, &self->flags))
complete(&self->parked);
schedule();
__set_current_state(TASK_PARKED);
}
clear_bit(KTHREAD_IS_PARKED, &self->flags);
__set_current_state(TASK_RUNNING);
}
void kthread_parkme(void)
{
__kthread_parkme(to_kthread(current));
}
static int kthread(void *_create)
{
/* Copy data: it's on kthread's stack */
struct kthread_create_info *create = _create;
int (*threadfn)(void *data) = create->threadfn;
void *data = create->data;
struct completion *done;
struct kthread self;
int ret;
self.flags = 0;
self.data = data;
init_completion(&self.exited);
init_completion(&self.parked);
current->vfork_done = &self.exited;
/* If user was SIGKILLed, I release the structure. */
done = xchg(&create->done, NULL);
if (!done) {
kfree(create);
do_exit(-EINTR);
}
/* OK, tell user we're spawned, wait for stop or wakeup */
__set_current_state(TASK_UNINTERRUPTIBLE);
create->result = current;
complete(done);
schedule();
ret = -EINTR;
if (!test_bit(KTHREAD_SHOULD_STOP, &self.flags)) {
__kthread_parkme(&self);
ret = threadfn(data);
}
/* we can't just return, we must preserve "self" on stack */
do_exit(ret);
}
/* called from do_fork() to get node information for about to be created task */
int tsk_fork_get_node(struct task_struct *tsk)
{
#ifdef CONFIG_NUMA
if (tsk == kthreadd_task)
return tsk->pref_node_fork;
#endif
return NUMA_NO_NODE;
}
static void create_kthread(struct kthread_create_info *create)
{
int pid;
#ifdef CONFIG_NUMA
current->pref_node_fork = create->node;
#endif
/* We want our own signal handler (we take no signals by default). */
pid = kernel_thread(kthread, create, CLONE_FS | CLONE_FILES | SIGCHLD);
if (pid < 0) {
/* If user was SIGKILLed, I release the structure. */
struct completion *done = xchg(&create->done, NULL);
if (!done) {
kfree(create);
return;
}
create->result = ERR_PTR(pid);
complete(done);
}
}
/**
* kthread_create_on_node - create a kthread.
* @threadfn: the function to run until signal_pending(current).
* @data: data ptr for @threadfn.
* @node: memory node number.
* @namefmt: printf-style name for the thread.
*
* Description: This helper function creates and names a kernel
* thread. The thread will be stopped: use wake_up_process() to start
* it. See also kthread_run().
*
* If thread is going to be bound on a particular cpu, give its node
* in @node, to get NUMA affinity for kthread stack, or else give -1.
* When woken, the thread will run @threadfn() with @data as its
* argument. @threadfn() can either call do_exit() directly if it is a
* standalone thread for which no one will call kthread_stop(), or
* return when 'kthread_should_stop()' is true (which means
* kthread_stop() has been called). The return value should be zero
* or a negative error number; it will be passed to kthread_stop().
*
* Returns a task_struct or ERR_PTR(-ENOMEM).
*/
struct task_struct *kthread_create_on_node(int (*threadfn)(void *data),
void *data, int node,
const char namefmt[],
...)
{
DECLARE_COMPLETION_ONSTACK(done);
struct task_struct *task;
struct kthread_create_info *create = kmalloc(sizeof(*create),
GFP_KERNEL);
if (!create)
return ERR_PTR(-ENOMEM);
create->threadfn = threadfn;
create->data = data;
create->node = node;
create->done = &done;
spin_lock(&kthread_create_lock);
list_add_tail(&create->list, &kthread_create_list);
spin_unlock(&kthread_create_lock);
wake_up_process(kthreadd_task);
/*
* Wait for completion in killable state, for I might be chosen by
* the OOM killer while kthreadd is trying to allocate memory for
* new kernel thread.
*/
if (unlikely(wait_for_completion_killable(&done))) {
/*
* If I was SIGKILLed before kthreadd (or new kernel thread)
* calls complete(), leave the cleanup of this structure to
* that thread.
*/
if (xchg(&create->done, NULL))
return ERR_PTR(-ENOMEM);
/*
* kthreadd (or new kernel thread) will call complete()
* shortly.
*/
wait_for_completion(&done);
}
task = create->result;
if (!IS_ERR(task)) {
static const struct sched_param param = { .sched_priority = 0 };
va_list args;
va_start(args, namefmt);
vsnprintf(task->comm, sizeof(task->comm), namefmt, args);
va_end(args);
/*
* root may have changed our (kthreadd's) priority or CPU mask.
* The kernel thread should not inherit these properties.
*/
sched_setscheduler_nocheck(task, SCHED_NORMAL, ¶m);
set_cpus_allowed_ptr(task, cpu_all_mask);
}
kfree(create);
return task;
}
EXPORT_SYMBOL(kthread_create_on_node);
static void __kthread_bind(struct task_struct *p, unsigned int cpu, long state)
{
/* Must have done schedule() in kthread() before we set_task_cpu */
if (!wait_task_inactive(p, state)) {
WARN_ON(1);
return;
}
/* It's safe because the task is inactive. */
do_set_cpus_allowed(p, cpumask_of(cpu));
p->flags |= PF_NO_SETAFFINITY;
}
/**
* kthread_bind - bind a just-created kthread to a cpu.
* @p: thread created by kthread_create().
* @cpu: cpu (might not be online, must be possible) for @k to run on.
*
* Description: This function is equivalent to set_cpus_allowed(),
* except that @cpu doesn't need to be online, and the thread must be
* stopped (i.e., just returned from kthread_create()).
*/
void kthread_bind(struct task_struct *p, unsigned int cpu)
{
__kthread_bind(p, cpu, TASK_UNINTERRUPTIBLE);
}
EXPORT_SYMBOL(kthread_bind);
/**
* kthread_create_on_cpu - Create a cpu bound kthread
* @threadfn: the function to run until signal_pending(current).
* @data: data ptr for @threadfn.
* @cpu: The cpu on which the thread should be bound,
* @namefmt: printf-style name for the thread. Format is restricted
* to "name.*%u". Code fills in cpu number.
*
* Description: This helper function creates and names a kernel thread
* The thread will be woken and put into park mode.
*/
struct task_struct *kthread_create_on_cpu(int (*threadfn)(void *data),
void *data, unsigned int cpu,
const char *namefmt)
{
struct task_struct *p;
p = kthread_create_on_node(threadfn, data, cpu_to_mem(cpu), namefmt,
cpu);
if (IS_ERR(p))
return p;
set_bit(KTHREAD_IS_PER_CPU, &to_kthread(p)->flags);
to_kthread(p)->cpu = cpu;
/* Park the thread to get it out of TASK_UNINTERRUPTIBLE state */
kthread_park(p);
return p;
}
static void __kthread_unpark(struct task_struct *k, struct kthread *kthread)
{
clear_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
/*
* We clear the IS_PARKED bit here as we don't wait
* until the task has left the park code. So if we'd
* park before that happens we'd see the IS_PARKED bit
* which might be about to be cleared.
*/
if (test_and_clear_bit(KTHREAD_IS_PARKED, &kthread->flags)) {
if (test_bit(KTHREAD_IS_PER_CPU, &kthread->flags))
__kthread_bind(k, kthread->cpu, TASK_PARKED);
wake_up_state(k, TASK_PARKED);
}
}
/**
* kthread_unpark - unpark a thread created by kthread_create().
* @k: thread created by kthread_create().
*
* Sets kthread_should_park() for @k to return false, wakes it, and
* waits for it to return. If the thread is marked percpu then its
* bound to the cpu again.
*/
void kthread_unpark(struct task_struct *k)
{
struct kthread *kthread = to_live_kthread(k);
if (kthread)
__kthread_unpark(k, kthread);
}
/**
* kthread_park - park a thread created by kthread_create().
* @k: thread created by kthread_create().
*
* Sets kthread_should_park() for @k to return true, wakes it, and
* waits for it to return. This can also be called after kthread_create()
* instead of calling wake_up_process(): the thread will park without
* calling threadfn().
*
* Returns 0 if the thread is parked, -ENOSYS if the thread exited.
* If called by the kthread itself just the park bit is set.
*/
int kthread_park(struct task_struct *k)
{
struct kthread *kthread = to_live_kthread(k);
int ret = -ENOSYS;
if (kthread) {
if (!test_bit(KTHREAD_IS_PARKED, &kthread->flags)) {
set_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
if (k != current) {
wake_up_process(k);
wait_for_completion(&kthread->parked);
}
}
ret = 0;
}
return ret;
}
/**
* kthread_stop - stop a thread created by kthread_create().
* @k: thread created by kthread_create().
*
* Sets kthread_should_stop() for @k to return true, wakes it, and
* waits for it to exit. This can also be called after kthread_create()
* instead of calling wake_up_process(): the thread will exit without
* calling threadfn().
*
* If threadfn() may call do_exit() itself, the caller must ensure
* task_struct can't go away.
*
* Returns the result of threadfn(), or %-EINTR if wake_up_process()
* was never called.
*/
int kthread_stop(struct task_struct *k)
{
struct kthread *kthread;
int ret;
trace_sched_kthread_stop(k);
get_task_struct(k);
kthread = to_live_kthread(k);
if (kthread) {
set_bit(KTHREAD_SHOULD_STOP, &kthread->flags);
__kthread_unpark(k, kthread);
wake_up_process(k);
wait_for_completion(&kthread->exited);
}
ret = k->exit_code;
put_task_struct(k);
trace_sched_kthread_stop_ret(ret);
return ret;
}
EXPORT_SYMBOL(kthread_stop);
int kthreadd(void *unused)
{
struct task_struct *tsk = current;
/* Setup a clean context for our children to inherit. */
set_task_comm(tsk, "kthreadd");
ignore_signals(tsk);
set_cpus_allowed_ptr(tsk, cpu_all_mask);
set_mems_allowed(node_states[N_MEMORY]);
current->flags |= PF_NOFREEZE;
for (;;) {
set_current_state(TASK_INTERRUPTIBLE);
if (list_empty(&kthread_create_list))
schedule();
__set_current_state(TASK_RUNNING);
spin_lock(&kthread_create_lock);
while (!list_empty(&kthread_create_list)) {
struct kthread_create_info *create;
create = list_entry(kthread_create_list.next,
struct kthread_create_info, list);
list_del_init(&create->list);
spin_unlock(&kthread_create_lock);
create_kthread(create);
spin_lock(&kthread_create_lock);
}
spin_unlock(&kthread_create_lock);
}
return 0;
}
void __init_kthread_worker(struct kthread_worker *worker,
const char *name,
struct lock_class_key *key)
{
spin_lock_init(&worker->lock);
lockdep_set_class_and_name(&worker->lock, key, name);
INIT_LIST_HEAD(&worker->work_list);
worker->task = NULL;
}
EXPORT_SYMBOL_GPL(__init_kthread_worker);
/**
* kthread_worker_fn - kthread function to process kthread_worker
* @worker_ptr: pointer to initialized kthread_worker
*
* This function can be used as @threadfn to kthread_create() or
* kthread_run() with @worker_ptr argument pointing to an initialized
* kthread_worker. The started kthread will process work_list until
* the it is stopped with kthread_stop(). A kthread can also call
* this function directly after extra initialization.
*
* Different kthreads can be used for the same kthread_worker as long
* as there's only one kthread attached to it at any given time. A
* kthread_worker without an attached kthread simply collects queued
* kthread_works.
*/
int kthread_worker_fn(void *worker_ptr)
{
struct kthread_worker *worker = worker_ptr;
struct kthread_work *work;
WARN_ON(worker->task);
worker->task = current;
repeat:
set_current_state(TASK_INTERRUPTIBLE); /* mb paired w/ kthread_stop */
if (kthread_should_stop()) {
__set_current_state(TASK_RUNNING);
spin_lock_irq(&worker->lock);
worker->task = NULL;
spin_unlock_irq(&worker->lock);
return 0;
}
work = NULL;
spin_lock_irq(&worker->lock);
if (!list_empty(&worker->work_list)) {
work = list_first_entry(&worker->work_list,
struct kthread_work, node);
list_del_init(&work->node);
}
worker->current_work = work;
spin_unlock_irq(&worker->lock);
if (work) {
__set_current_state(TASK_RUNNING);
work->func(work);
} else if (!freezing(current))
schedule();
try_to_freeze();
goto repeat;
}
EXPORT_SYMBOL_GPL(kthread_worker_fn);
/* insert @work before @pos in @worker */
static void insert_kthread_work(struct kthread_worker *worker,
struct kthread_work *work,
struct list_head *pos)
{
lockdep_assert_held(&worker->lock);
list_add_tail(&work->node, pos);
work->worker = worker;
if (likely(worker->task))
wake_up_process(worker->task);
}
/**
* queue_kthread_work - queue a kthread_work
* @worker: target kthread_worker
* @work: kthread_work to queue
*
* Queue @work to work processor @task for async execution. @task
* must have been created with kthread_worker_create(). Returns %true
* if @work was successfully queued, %false if it was already pending.
*/
bool queue_kthread_work(struct kthread_worker *worker,
struct kthread_work *work)
{
bool ret = false;
unsigned long flags;
spin_lock_irqsave(&worker->lock, flags);
if (list_empty(&work->node)) {
insert_kthread_work(worker, work, &worker->work_list);
ret = true;
}
spin_unlock_irqrestore(&worker->lock, flags);
return ret;
}
EXPORT_SYMBOL_GPL(queue_kthread_work);
struct kthread_flush_work {
struct kthread_work work;
struct completion done;
};
static void kthread_flush_work_fn(struct kthread_work *work)
{
struct kthread_flush_work *fwork =
container_of(work, struct kthread_flush_work, work);
complete(&fwork->done);
}
/**
* flush_kthread_work - flush a kthread_work
* @work: work to flush
*
* If @work is queued or executing, wait for it to finish execution.
*/
void flush_kthread_work(struct kthread_work *work)
{
struct kthread_flush_work fwork = {
KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
COMPLETION_INITIALIZER_ONSTACK(fwork.done),
};
struct kthread_worker *worker;
bool noop = false;
retry:
worker = work->worker;
if (!worker)
return;
spin_lock_irq(&worker->lock);
if (work->worker != worker) {
spin_unlock_irq(&worker->lock);
goto retry;
}
if (!list_empty(&work->node))
insert_kthread_work(worker, &fwork.work, work->node.next);
else if (worker->current_work == work)
insert_kthread_work(worker, &fwork.work, worker->work_list.next);
else
noop = true;
spin_unlock_irq(&worker->lock);
if (!noop)
wait_for_completion(&fwork.done);
}
EXPORT_SYMBOL_GPL(flush_kthread_work);
/**
* flush_kthread_worker - flush all current works on a kthread_worker
* @worker: worker to flush
*
* Wait until all currently executing or pending works on @worker are
* finished.
*/
void flush_kthread_worker(struct kthread_worker *worker)
{
struct kthread_flush_work fwork = {
KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
COMPLETION_INITIALIZER_ONSTACK(fwork.done),
};
queue_kthread_work(worker, &fwork.work);
wait_for_completion(&fwork.done);
}
EXPORT_SYMBOL_GPL(flush_kthread_worker);
| iwinoto/v4l-media_build-devel | media/kernel/kthread.c | C | gpl-2.0 | 18,999 |
// Copyright (C) 2001-2015 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, 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 General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#include "1.h"
#include <list>
int main()
{
cons01<std::list< A<B> > >();
return 0;
}
| crystax/android-toolchain-gcc-5 | libstdc++-v3/testsuite/23_containers/list/cons/1.cc | C++ | gpl-2.0 | 855 |
/***************************************************************************//**
* @file
* @brief Clock management unit (CMU) API
* @author Energy Micro AS
* @version 3.0.0
*******************************************************************************
* @section License
* <b>(C) Copyright 2012 Energy Micro AS, http://www.energymicro.com</b>
*******************************************************************************
*
* 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.
* 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.
*
* DISCLAIMER OF WARRANTY/LIMITATION OF REMEDIES: Energy Micro AS has no
* obligation to support this Software. Energy Micro AS is providing the
* Software "AS IS", with no express or implied warranties of any kind,
* including, but not limited to, any implied warranties of merchantability
* or fitness for any particular purpose or warranties against infringement
* of any proprietary rights of a third party.
*
* Energy Micro AS will not be liable for any consequential, incidental, or
* special damages, or any other relief, or for any claim by any third party,
* arising from your use of this Software.
*
******************************************************************************/
#ifndef __EM_CMU_H
#define __EM_CMU_H
#include <stdbool.h>
#include "em_part.h"
#include "em_bitband.h"
#ifdef __cplusplus
extern "C" {
#endif
/***************************************************************************//**
* @addtogroup EM_Library
* @{
******************************************************************************/
/***************************************************************************//**
* @addtogroup CMU
* @{
******************************************************************************/
/** @cond DO_NOT_INCLUDE_WITH_DOXYGEN */
/* Select register ids, for internal use */
#define CMU_NOSEL_REG 0
#define CMU_HFCLKSEL_REG 1
#define CMU_LFACLKSEL_REG 2
#define CMU_LFBCLKSEL_REG 3
#define CMU_DBGCLKSEL_REG 4
#if defined (_EFM32_GIANT_FAMILY)
#define CMU_USBCCLKSEL_REG 5
#endif
#define CMU_SEL_REG_POS 0
#define CMU_SEL_REG_MASK 0xf
/* Divisor register ids, for internal use */
#define CMU_NODIV_REG 0
#define CMU_HFPERCLKDIV_REG 1
#define CMU_HFCORECLKDIV_REG 2
#define CMU_LFAPRESC0_REG 3
#define CMU_LFBPRESC0_REG 4
#if defined (_EFM32_GIANT_FAMILY)
#define CMU_HFCLKDIV_REG 5
#endif
#define CMU_DIV_REG_POS 4
#define CMU_DIV_REG_MASK 0xf
/* Enable register ids, for internal use */
#define CMU_NO_EN_REG 0
#define CMU_HFPERCLKDIV_EN_REG 1
#define CMU_HFPERCLKEN0_EN_REG 2
#define CMU_HFCORECLKEN0_EN_REG 3
#define CMU_LFACLKEN0_EN_REG 4
#define CMU_LFBCLKEN0_EN_REG 5
#define CMU_PCNT_EN_REG 6
#define CMU_EN_REG_POS 8
#define CMU_EN_REG_MASK 0xf
/* Enable register bit position, for internal use */
#define CMU_EN_BIT_POS 12
#define CMU_EN_BIT_MASK 0x1f
/* Clock branch bitfield position, for internal use */
#define CMU_HF_CLK_BRANCH 0
#define CMU_HFPER_CLK_BRANCH 1
#define CMU_HFCORE_CLK_BRANCH 2
#define CMU_LFA_CLK_BRANCH 3
#define CMU_RTC_CLK_BRANCH 4
#define CMU_LETIMER_CLK_BRANCH 5
#define CMU_LCDPRE_CLK_BRANCH 6
#define CMU_LCD_CLK_BRANCH 7
#define CMU_LESENSE_CLK_BRANCH 8
#define CMU_LFB_CLK_BRANCH 9
#define CMU_LEUART0_CLK_BRANCH 10
#define CMU_LEUART1_CLK_BRANCH 11
#define CMU_DBG_CLK_BRANCH 12
#define CMU_AUX_CLK_BRANCH 13
#define CMU_USBC_CLK_BRANCH 14
#define CMU_CLK_BRANCH_POS 17
#define CMU_CLK_BRANCH_MASK 0x1f
/** @endcond */
/*******************************************************************************
******************************** ENUMS ************************************
******************************************************************************/
/** Clock divisors. These values are valid for prescalers. */
#define cmuClkDiv_1 1 /**< Divide clock by 1. */
#define cmuClkDiv_2 2 /**< Divide clock by 2. */
#define cmuClkDiv_4 4 /**< Divide clock by 4. */
#define cmuClkDiv_8 8 /**< Divide clock by 8. */
#define cmuClkDiv_16 16 /**< Divide clock by 16. */
#define cmuClkDiv_32 32 /**< Divide clock by 32. */
#define cmuClkDiv_64 64 /**< Divide clock by 64. */
#define cmuClkDiv_128 128 /**< Divide clock by 128. */
#define cmuClkDiv_256 256 /**< Divide clock by 256. */
#define cmuClkDiv_512 512 /**< Divide clock by 512. */
#define cmuClkDiv_1024 1024 /**< Divide clock by 1024. */
#define cmuClkDiv_2048 2048 /**< Divide clock by 2048. */
#define cmuClkDiv_4096 4096 /**< Divide clock by 4096. */
#define cmuClkDiv_8192 8192 /**< Divide clock by 8192. */
#define cmuClkDiv_16384 16384 /**< Divide clock by 16384. */
#define cmuClkDiv_32768 32768 /**< Divide clock by 32768. */
/** Clock divider configuration */
typedef uint32_t CMU_ClkDiv_TypeDef;
/** High frequency RC bands. */
typedef enum
{
/** 1MHz RC band. */
cmuHFRCOBand_1MHz = _CMU_HFRCOCTRL_BAND_1MHZ,
/** 7MHz RC band. */
cmuHFRCOBand_7MHz = _CMU_HFRCOCTRL_BAND_7MHZ,
/** 11MHz RC band. */
cmuHFRCOBand_11MHz = _CMU_HFRCOCTRL_BAND_11MHZ,
/** 14MHz RC band. */
cmuHFRCOBand_14MHz = _CMU_HFRCOCTRL_BAND_14MHZ,
/** 21MHz RC band. */
cmuHFRCOBand_21MHz = _CMU_HFRCOCTRL_BAND_21MHZ,
/** 28MHz RC band. */
cmuHFRCOBand_28MHz = _CMU_HFRCOCTRL_BAND_28MHZ
} CMU_HFRCOBand_TypeDef;
#if defined(_EFM32_TINY_FAMILY) || defined(_EFM32_GIANT_FAMILY)
/** AUX High frequency RC bands. */
typedef enum
{
/** 1MHz RC band. */
cmuAUXHFRCOBand_1MHz = _CMU_AUXHFRCOCTRL_BAND_1MHZ,
/** 7MHz RC band. */
cmuAUXHFRCOBand_7MHz = _CMU_AUXHFRCOCTRL_BAND_7MHZ,
/** 11MHz RC band. */
cmuAUXHFRCOBand_11MHz = _CMU_AUXHFRCOCTRL_BAND_11MHZ,
/** 14MHz RC band. */
cmuAUXHFRCOBand_14MHz = _CMU_AUXHFRCOCTRL_BAND_14MHZ,
/** 21MHz RC band. */
cmuAUXHFRCOBand_21MHz = _CMU_AUXHFRCOCTRL_BAND_21MHZ,
/** 28MHz RC band. */
cmuAUXHFRCOBand_28MHz = _CMU_AUXHFRCOCTRL_BAND_28MHZ
} CMU_AUXHFRCOBand_TypeDef;
#endif
/** Clock points in CMU. Please refer to CMU overview in reference manual. */
typedef enum
{
/*******************/
/* HF clock branch */
/*******************/
/** High frequency clock */
#if defined(_EFM32_GIANT_FAMILY)
cmuClock_HF = (CMU_HFCLKDIV_REG << CMU_DIV_REG_POS) |
(CMU_HFCLKSEL_REG << CMU_SEL_REG_POS) |
(CMU_NO_EN_REG << CMU_EN_REG_POS) |
(0 << CMU_EN_BIT_POS) |
(CMU_HF_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#else
cmuClock_HF = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_HFCLKSEL_REG << CMU_SEL_REG_POS) |
(CMU_NO_EN_REG << CMU_EN_REG_POS) |
(0 << CMU_EN_BIT_POS) |
(CMU_HF_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/** Debug clock */
cmuClock_DBG = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_DBGCLKSEL_REG << CMU_SEL_REG_POS) |
(CMU_NO_EN_REG << CMU_EN_REG_POS) |
(0 << CMU_EN_BIT_POS) |
(CMU_DBG_CLK_BRANCH << CMU_CLK_BRANCH_POS),
/** AUX clock */
cmuClock_AUX = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_NO_EN_REG << CMU_EN_REG_POS) |
(0 << CMU_EN_BIT_POS) |
(CMU_AUX_CLK_BRANCH << CMU_CLK_BRANCH_POS),
/**********************************/
/* HF peripheral clock sub-branch */
/**********************************/
/** High frequency peripheral clock */
cmuClock_HFPER = (CMU_HFPERCLKDIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_HFPERCLKDIV_EN_REG << CMU_EN_REG_POS) |
(_CMU_HFPERCLKDIV_HFPERCLKEN_SHIFT << CMU_EN_BIT_POS) |
(CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS),
/** Universal sync/async receiver/transmitter 0 clock. */
#if defined(_CMU_HFPERCLKEN0_USART0_MASK)
cmuClock_USART0 = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_HFPERCLKEN0_USART0_SHIFT << CMU_EN_BIT_POS) |
(CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/** Universal sync/async receiver/transmitter 1 clock. */
#if defined(_CMU_HFPERCLKEN0_USART1_MASK)
cmuClock_USART1 = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_HFPERCLKEN0_USART1_SHIFT << CMU_EN_BIT_POS) |
(CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/** Universal sync/async receiver/transmitter 2 clock. */
#if defined(_CMU_HFPERCLKEN0_USART2_MASK)
cmuClock_USART2 = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_HFPERCLKEN0_USART2_SHIFT << CMU_EN_BIT_POS) |
(CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/** Universal async receiver/transmitter 0 clock. */
#if defined(_CMU_HFPERCLKEN0_UART0_MASK)
cmuClock_UART0 = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_HFPERCLKEN0_UART0_SHIFT << CMU_EN_BIT_POS) |
(CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/** Universal async receiver/transmitter 1 clock. */
#if defined(_CMU_HFPERCLKEN0_UART1_MASK)
cmuClock_UART1 = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_HFPERCLKEN0_UART1_SHIFT << CMU_EN_BIT_POS) |
(CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/** Timer 0 clock. */
#if defined(_CMU_HFPERCLKEN0_TIMER0_MASK)
cmuClock_TIMER0 = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_HFPERCLKEN0_TIMER0_SHIFT << CMU_EN_BIT_POS) |
(CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/** Timer 1 clock. */
#if defined(_CMU_HFPERCLKEN0_TIMER1_MASK)
cmuClock_TIMER1 = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_HFPERCLKEN0_TIMER1_SHIFT << CMU_EN_BIT_POS) |
(CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/** Timer 2 clock. */
#if defined(_CMU_HFPERCLKEN0_TIMER2_MASK)
cmuClock_TIMER2 = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_HFPERCLKEN0_TIMER2_SHIFT << CMU_EN_BIT_POS) |
(CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/** Timer 3 clock. */
#if defined(_CMU_HFPERCLKEN0_TIMER3_MASK)
cmuClock_TIMER3 = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_HFPERCLKEN0_TIMER3_SHIFT << CMU_EN_BIT_POS) |
(CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/** Analog comparator 0 clock. */
#if defined(_CMU_HFPERCLKEN0_ACMP0_MASK)
cmuClock_ACMP0 = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_HFPERCLKEN0_ACMP0_SHIFT << CMU_EN_BIT_POS) |
(CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/** Analog comparator 1 clock. */
#if defined(_CMU_HFPERCLKEN0_ACMP1_MASK)
cmuClock_ACMP1 = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_HFPERCLKEN0_ACMP1_SHIFT << CMU_EN_BIT_POS) |
(CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/** Peripheral reflex system clock. */
#if defined(_CMU_HFPERCLKEN0_PRS_MASK)
cmuClock_PRS = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_HFPERCLKEN0_PRS_SHIFT << CMU_EN_BIT_POS) |
(CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/** Digital to analog converter 0 clock. */
#if defined(_CMU_HFPERCLKEN0_DAC0_MASK)
cmuClock_DAC0 = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_HFPERCLKEN0_DAC0_SHIFT << CMU_EN_BIT_POS) |
(CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/** General purpose input/output clock. */
#if defined(GPIO_PRESENT)
cmuClock_GPIO = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_HFPERCLKEN0_GPIO_SHIFT << CMU_EN_BIT_POS) |
(CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/** Voltage comparator clock. */
#if defined(VCMP_PRESENT)
cmuClock_VCMP = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_HFPERCLKEN0_VCMP_SHIFT << CMU_EN_BIT_POS) |
(CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/** Analog to digital converter 0 clock. */
#if defined(_CMU_HFPERCLKEN0_ADC0_MASK)
cmuClock_ADC0 = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_HFPERCLKEN0_ADC0_SHIFT << CMU_EN_BIT_POS) |
(CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/** I2C 0 clock. */
#if defined(_CMU_HFPERCLKEN0_I2C0_MASK)
cmuClock_I2C0 = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_HFPERCLKEN0_I2C0_SHIFT << CMU_EN_BIT_POS) |
(CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/** I2C 1 clock. */
#if defined(_CMU_HFPERCLKEN0_I2C1_MASK)
cmuClock_I2C1 = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_HFPERCLKEN0_I2C1_SHIFT << CMU_EN_BIT_POS) |
(CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/**********************/
/* HF core sub-branch */
/**********************/
/** Core clock */
cmuClock_CORE = (CMU_HFCORECLKDIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_NO_EN_REG << CMU_EN_REG_POS) |
(0 << CMU_EN_BIT_POS) |
(CMU_HFCORE_CLK_BRANCH << CMU_CLK_BRANCH_POS),
/** Advanced encryption standard accelerator clock. */
#if defined(AES_PRESENT)
cmuClock_AES = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_HFCORECLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_HFCORECLKEN0_AES_SHIFT << CMU_EN_BIT_POS) |
(CMU_HFCORE_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/** Direct memory access controller clock. */
#if defined(DMA_PRESENT)
cmuClock_DMA = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_HFCORECLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_HFCORECLKEN0_DMA_SHIFT << CMU_EN_BIT_POS) |
(CMU_HFCORE_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/** Low energy clocking module clock. */
cmuClock_CORELE = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_HFCORECLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_HFCORECLKEN0_LE_SHIFT << CMU_EN_BIT_POS) |
(CMU_HFCORE_CLK_BRANCH << CMU_CLK_BRANCH_POS),
/** External bus interface clock. */
#if defined(EBI_PRESENT)
cmuClock_EBI = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_HFCORECLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_HFCORECLKEN0_EBI_SHIFT << CMU_EN_BIT_POS) |
(CMU_HFCORE_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
#if defined(USB_PRESENT)
cmuClock_USBC = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_USBCCLKSEL_REG << CMU_SEL_REG_POS) |
(CMU_HFCORECLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_HFCORECLKEN0_USBC_SHIFT << CMU_EN_BIT_POS) |
(CMU_USBC_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
#if defined(USB_PRESENT)
cmuClock_USB = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_HFCORECLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_HFCORECLKEN0_USB_SHIFT << CMU_EN_BIT_POS) |
(CMU_HFCORE_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/***************/
/* LF A branch */
/***************/
/** Low frequency A clock */
cmuClock_LFA = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_LFACLKSEL_REG << CMU_SEL_REG_POS) |
(CMU_NO_EN_REG << CMU_EN_REG_POS) |
(0 << CMU_EN_BIT_POS) |
(CMU_LFA_CLK_BRANCH << CMU_CLK_BRANCH_POS),
/** Real time counter clock. */
#if defined(RTC_PRESENT)
cmuClock_RTC = (CMU_LFAPRESC0_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_LFACLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_LFACLKEN0_RTC_SHIFT << CMU_EN_BIT_POS) |
(CMU_RTC_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/** Low energy timer 0 clock. */
#if defined(_CMU_LFACLKEN0_LETIMER0_MASK)
cmuClock_LETIMER0 = (CMU_LFAPRESC0_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_LFACLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_LFACLKEN0_LETIMER0_SHIFT << CMU_EN_BIT_POS) |
(CMU_LETIMER_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/** Liquid crystal display, pre FDIV clock. */
#if defined(_CMU_LFACLKEN0_LCD_MASK)
cmuClock_LCDpre = (CMU_LFAPRESC0_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_NO_EN_REG << CMU_EN_REG_POS) |
(0 << CMU_EN_BIT_POS) |
(CMU_LCDPRE_CLK_BRANCH << CMU_CLK_BRANCH_POS),
/** Liquid crystal display clock. Please notice that FDIV prescaler
* must be set by special API. */
cmuClock_LCD = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_LFACLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_LFACLKEN0_LCD_SHIFT << CMU_EN_BIT_POS) |
(CMU_LCD_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/** Pulse counter 0 clock. */
#if defined(_CMU_PCNTCTRL_PCNT0CLKEN_MASK)
cmuClock_PCNT0 = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_PCNT_EN_REG << CMU_EN_REG_POS) |
(_CMU_PCNTCTRL_PCNT0CLKEN_SHIFT << CMU_EN_BIT_POS) |
(CMU_LFA_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/** Pulse counter 1 clock. */
#if defined(_CMU_PCNTCTRL_PCNT1CLKEN_MASK)
cmuClock_PCNT1 = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_PCNT_EN_REG << CMU_EN_REG_POS) |
(_CMU_PCNTCTRL_PCNT1CLKEN_SHIFT << CMU_EN_BIT_POS) |
(CMU_LFA_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/** Pulse counter 2 clock. */
#if defined(_CMU_PCNTCTRL_PCNT2CLKEN_MASK)
cmuClock_PCNT2 = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_PCNT_EN_REG << CMU_EN_REG_POS) |
(_CMU_PCNTCTRL_PCNT2CLKEN_SHIFT << CMU_EN_BIT_POS) |
(CMU_LFA_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/** LESENSE clock. */
#if defined(_CMU_LFACLKEN0_LESENSE_MASK)
cmuClock_LESENSE = (CMU_LFAPRESC0_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_LFACLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_LFACLKEN0_LESENSE_SHIFT << CMU_EN_BIT_POS) |
(CMU_LESENSE_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/***************/
/* LF B branch */
/***************/
/** Low frequency B clock */
cmuClock_LFB = (CMU_NODIV_REG << CMU_DIV_REG_POS) |
(CMU_LFBCLKSEL_REG << CMU_SEL_REG_POS) |
(CMU_NO_EN_REG << CMU_EN_REG_POS) |
(0 << CMU_EN_BIT_POS) |
(CMU_LFB_CLK_BRANCH << CMU_CLK_BRANCH_POS),
/** Low energy universal asynchronous receiver/transmitter 0 clock. */
#if defined(_CMU_LFBCLKEN0_LEUART0_MASK)
cmuClock_LEUART0 = (CMU_LFBPRESC0_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_LFBCLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_LFBCLKEN0_LEUART0_SHIFT << CMU_EN_BIT_POS) |
(CMU_LEUART0_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
/** Low energy universal asynchronous receiver/transmitter 1 clock. */
#if defined(_CMU_LFBCLKEN0_LEUART1_MASK)
cmuClock_LEUART1 = (CMU_LFBPRESC0_REG << CMU_DIV_REG_POS) |
(CMU_NOSEL_REG << CMU_SEL_REG_POS) |
(CMU_LFBCLKEN0_EN_REG << CMU_EN_REG_POS) |
(_CMU_LFBCLKEN0_LEUART1_SHIFT << CMU_EN_BIT_POS) |
(CMU_LEUART1_CLK_BRANCH << CMU_CLK_BRANCH_POS),
#endif
} CMU_Clock_TypeDef;
/** Oscillator types. */
typedef enum
{
cmuOsc_LFXO, /**< Low frequency crystal oscillator. */
cmuOsc_LFRCO, /**< Low frequency RC oscillator. */
cmuOsc_HFXO, /**< High frequency crystal oscillator. */
cmuOsc_HFRCO, /**< High frequency RC oscillator. */
cmuOsc_AUXHFRCO, /**< Auxiliary high frequency RC oscillator. */
#if defined(_EFM32_TINY_FAMILY) || defined(_EFM32_GIANT_FAMILY)
cmuOsc_ULFRCO /**< Ultra low frequency RC oscillator. */
#endif
} CMU_Osc_TypeDef;
/** Selectable clock sources. */
typedef enum
{
cmuSelect_Error, /**< Usage error. */
cmuSelect_Disabled, /**< Clock selector disabled. */
cmuSelect_LFXO, /**< Low frequency crystal oscillator. */
cmuSelect_LFRCO, /**< Low frequency RC oscillator. */
cmuSelect_HFXO, /**< High frequency crystal oscillator. */
cmuSelect_HFRCO, /**< High frequency RC oscillator. */
cmuSelect_CORELEDIV2, /**< Core low energy clock divided by 2. */
cmuSelect_AUXHFRCO, /**< Auxilliary clock source can be used for debug clock */
cmuSelect_HFCLK, /**< Divided HFCLK on Giant for debug clock, undivided on Tiny Gecko and for USBC (not used on Gecko) */
#if defined(_EFM32_TINY_FAMILY) || defined(_EFM32_GIANT_FAMILY)
cmuSelect_ULFRCO, /**< Ultra low frequency RC oscillator. */
#endif
} CMU_Select_TypeDef;
/*******************************************************************************
***************************** PROTOTYPES **********************************
******************************************************************************/
void CMU_ClockEnable(CMU_Clock_TypeDef clock, bool enable);
uint32_t CMU_ClockFreqGet(CMU_Clock_TypeDef clock);
CMU_ClkDiv_TypeDef CMU_ClockDivGet(CMU_Clock_TypeDef clock);
CMU_Select_TypeDef CMU_ClockSelectGet(CMU_Clock_TypeDef clock);
void CMU_ClockDivSet(CMU_Clock_TypeDef clock, CMU_ClkDiv_TypeDef div);
void CMU_ClockSelectSet(CMU_Clock_TypeDef clock, CMU_Select_TypeDef ref);
CMU_HFRCOBand_TypeDef CMU_HFRCOBandGet(void);
void CMU_HFRCOBandSet(CMU_HFRCOBand_TypeDef band);
#if defined(_EFM32_TINY_FAMILY) || defined(_EFM32_GIANT_FAMILY)
CMU_AUXHFRCOBand_TypeDef CMU_AUXHFRCOBandGet(void);
void CMU_AUXHFRCOBandSet(CMU_AUXHFRCOBand_TypeDef band);
#endif
void CMU_HFRCOStartupDelaySet(uint32_t delay);
uint32_t CMU_HFRCOStartupDelayGet(void);
void CMU_OscillatorEnable(CMU_Osc_TypeDef osc, bool enable, bool wait);
uint32_t CMU_OscillatorTuningGet(CMU_Osc_TypeDef osc);
void CMU_OscillatorTuningSet(CMU_Osc_TypeDef osc, uint32_t val);
bool CMU_PCNTClockExternalGet(unsigned int inst);
void CMU_PCNTClockExternalSet(unsigned int inst, bool external);
uint32_t CMU_LCDClkFDIVGet(void);
void CMU_LCDClkFDIVSet(uint32_t div);
void CMU_FreezeEnable(bool enable);
uint32_t CMU_Calibrate(uint32_t HFCycles, CMU_Osc_TypeDef reference);
void CMU_CalibrateConfig(uint32_t downCycles, CMU_Osc_TypeDef downSel,
CMU_Osc_TypeDef upSel);
/***************************************************************************//**
* @brief
* Clear one or more pending CMU interrupts.
*
* @param[in] flags
* CMU interrupt sources to clear.
******************************************************************************/
__STATIC_INLINE void CMU_IntClear(uint32_t flags)
{
CMU->IFC = flags;
}
/***************************************************************************//**
* @brief
* Disable one or more CMU interrupts.
*
* @param[in] flags
* CMU interrupt sources to disable.
******************************************************************************/
__STATIC_INLINE void CMU_IntDisable(uint32_t flags)
{
CMU->IEN &= ~flags;
}
/***************************************************************************//**
* @brief
* Enable one or more CMU interrupts.
*
* @note
* Depending on the use, a pending interrupt may already be set prior to
* enabling the interrupt. Consider using CMU_IntClear() prior to enabling
* if such a pending interrupt should be ignored.
*
* @param[in] flags
* CMU interrupt sources to enable.
******************************************************************************/
__STATIC_INLINE void CMU_IntEnable(uint32_t flags)
{
CMU->IEN |= flags;
}
/***************************************************************************//**
* @brief
* Get pending CMU interrupts.
*
* @return
* CMU interrupt sources pending.
******************************************************************************/
__STATIC_INLINE uint32_t CMU_IntGet(void)
{
return CMU->IF;
}
/***************************************************************************//**
* @brief
* Get enabled and pending CMU interrupt flags.
*
* @details
* Useful for handling more interrupt sources in the same interrupt handler.
*
* @note
* The event bits are not cleared by the use of this function.
*
* @return
* Pending and enabled CMU interrupt sources.
* The return value is the bitwise AND combination of
* - the OR combination of enabled interrupt sources in CMU_IEN_nnn
* register (CMU_IEN_nnn) and
* - the OR combination of valid interrupt flags of the CMU module
* (CMU_IF_nnn).
******************************************************************************/
__STATIC_INLINE uint32_t CMU_IntGetEnabled(void)
{
uint32_t tmp = 0U;
/* Store LESENSE->IEN in temporary variable in order to define explicit order
* of volatile accesses. */
tmp = CMU->IEN;
/* Bitwise AND of pending and enabled interrupts */
return CMU->IF & tmp;
}
/**************************************************************************//**
* @brief
* Set one or more pending CMU interrupts from SW.
*
* @param[in] flags
* CMU interrupt sources to set to pending.
*****************************************************************************/
__STATIC_INLINE void CMU_IntSet(uint32_t flags)
{
CMU->IFS = flags;
}
/***************************************************************************//**
* @brief
* Lock the CMU in order to protect some of its registers against unintended
* modification.
*
* @details
* Please refer to the reference manual for CMU registers that will be
* locked.
*
* @note
* If locking the CMU registers, they must be unlocked prior to using any
* CMU API functions modifying CMU registers protected by the lock.
******************************************************************************/
__STATIC_INLINE void CMU_Lock(void)
{
CMU->LOCK = CMU_LOCK_LOCKKEY_LOCK;
}
/***************************************************************************//**
* @brief
* Unlock the CMU so that writing to locked registers again is possible.
******************************************************************************/
__STATIC_INLINE void CMU_Unlock(void)
{
CMU->LOCK = CMU_LOCK_LOCKKEY_UNLOCK;
}
/***************************************************************************//**
* @brief
* Get calibration count register
* @note
* If continuous calibrartion mode is active, calibration busy will allmost
* always be on, and we just need to read the value, where the normal case
* would be that this function call has been triggered by the CALRDY
* interrupt flag.
* @return
* Calibration count, the number of UPSEL clocks (see CMU_CalibrateConfig)
* in the period of DOWNSEL oscillator clock cycles configured by a previous
* write operation to CMU->CALCNT
******************************************************************************/
__STATIC_INLINE uint32_t CMU_CalibrateCountGet(void)
{
/* Wait until calibration completes, UNLESS continuous calibration mode is */
/* active */
#if defined (_EFM32_TINY_FAMILY) || defined(_EFM32_GIANT_FAMILY)
if (!(CMU->CALCTRL & CMU_CALCTRL_CONT))
{
while (CMU->STATUS & CMU_STATUS_CALBSY)
;
}
#else
while (CMU->STATUS & CMU_STATUS_CALBSY)
;
#endif
return CMU->CALCNT;
}
/***************************************************************************//**
* @brief
* Starts calibration
* @note
* This call is usually invoked after CMU_CalibrateConfig() and possibly
* CMU_CalibrateCont()
******************************************************************************/
__STATIC_INLINE void CMU_CalibrateStart(void)
{
CMU->CMD = CMU_CMD_CALSTART;
}
#if defined (_EFM32_TINY_FAMILY) || defined(_EFM32_GIANT_FAMILY)
/***************************************************************************//**
* @brief
* Stop the calibration counters
******************************************************************************/
__STATIC_INLINE void CMU_CalibrateStop(void)
{
CMU->CMD = CMU_CMD_CALSTOP;
}
/***************************************************************************//**
* @brief
* Configures continuous calibration mode
* @param[in] enable
* If true, enables continuous calibration, if false disables continuous
* calibrartion
******************************************************************************/
__STATIC_INLINE void CMU_CalibrateCont(bool enable)
{
BITBAND_Peripheral(&(CMU->CALCTRL), _CMU_CALCTRL_CONT_SHIFT, enable);
}
#endif
/** @} (end addtogroup CMU) */
/** @} (end addtogroup EM_Library) */
#ifdef __cplusplus
}
#endif
#endif /* __EM_CMU_H */
| poranmeloge/test-github | stm32_rtt_wifi/bsp/efm32/Libraries/emlib/inc/em_cmu.h | C | gpl-2.0 | 32,251 |
/* Implementation of the MAXLOC intrinsic
Copyright (C) 2002-2015 Free Software Foundation, Inc.
Contributed by Paul Brook <paul@nowt.org>
This file is part of the GNU Fortran 95 runtime library (libgfortran).
Libgfortran is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
Libgfortran is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Under Section 7 of GPL version 3, you are granted additional
permissions described in the GCC Runtime Library Exception, version
3.1, as published by the Free Software Foundation.
You should have received a copy of the GNU General Public License and
a copy of the GCC Runtime Library Exception along with this program;
see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
<http://www.gnu.org/licenses/>. */
#include "libgfortran.h"
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#if defined (HAVE_GFC_REAL_10) && defined (HAVE_GFC_INTEGER_16)
extern void maxloc0_16_r10 (gfc_array_i16 * const restrict retarray,
gfc_array_r10 * const restrict array);
export_proto(maxloc0_16_r10);
void
maxloc0_16_r10 (gfc_array_i16 * const restrict retarray,
gfc_array_r10 * const restrict array)
{
index_type count[GFC_MAX_DIMENSIONS];
index_type extent[GFC_MAX_DIMENSIONS];
index_type sstride[GFC_MAX_DIMENSIONS];
index_type dstride;
const GFC_REAL_10 *base;
GFC_INTEGER_16 * restrict dest;
index_type rank;
index_type n;
rank = GFC_DESCRIPTOR_RANK (array);
if (rank <= 0)
runtime_error ("Rank of array needs to be > 0");
if (retarray->base_addr == NULL)
{
GFC_DIMENSION_SET(retarray->dim[0], 0, rank-1, 1);
retarray->dtype = (retarray->dtype & ~GFC_DTYPE_RANK_MASK) | 1;
retarray->offset = 0;
retarray->base_addr = xmallocarray (rank, sizeof (GFC_INTEGER_16));
}
else
{
if (unlikely (compile_options.bounds_check))
bounds_iforeach_return ((array_t *) retarray, (array_t *) array,
"MAXLOC");
}
dstride = GFC_DESCRIPTOR_STRIDE(retarray,0);
dest = retarray->base_addr;
for (n = 0; n < rank; n++)
{
sstride[n] = GFC_DESCRIPTOR_STRIDE(array,n);
extent[n] = GFC_DESCRIPTOR_EXTENT(array,n);
count[n] = 0;
if (extent[n] <= 0)
{
/* Set the return value. */
for (n = 0; n < rank; n++)
dest[n * dstride] = 0;
return;
}
}
base = array->base_addr;
/* Initialize the return value. */
for (n = 0; n < rank; n++)
dest[n * dstride] = 1;
{
GFC_REAL_10 maxval;
#if defined(GFC_REAL_10_QUIET_NAN)
int fast = 0;
#endif
#if defined(GFC_REAL_10_INFINITY)
maxval = -GFC_REAL_10_INFINITY;
#else
maxval = -GFC_REAL_10_HUGE;
#endif
while (base)
{
do
{
/* Implementation start. */
#if defined(GFC_REAL_10_QUIET_NAN)
}
while (0);
if (unlikely (!fast))
{
do
{
if (*base >= maxval)
{
fast = 1;
maxval = *base;
for (n = 0; n < rank; n++)
dest[n * dstride] = count[n] + 1;
break;
}
base += sstride[0];
}
while (++count[0] != extent[0]);
if (likely (fast))
continue;
}
else do
{
#endif
if (*base > maxval)
{
maxval = *base;
for (n = 0; n < rank; n++)
dest[n * dstride] = count[n] + 1;
}
/* Implementation end. */
/* Advance to the next element. */
base += sstride[0];
}
while (++count[0] != extent[0]);
n = 0;
do
{
/* When we get to the end of a dimension, reset it and increment
the next dimension. */
count[n] = 0;
/* We could precalculate these products, but this is a less
frequently used path so probably not worth it. */
base -= sstride[n] * extent[n];
n++;
if (n == rank)
{
/* Break out of the loop. */
base = NULL;
break;
}
else
{
count[n]++;
base += sstride[n];
}
}
while (count[n] == extent[n]);
}
}
}
extern void mmaxloc0_16_r10 (gfc_array_i16 * const restrict,
gfc_array_r10 * const restrict, gfc_array_l1 * const restrict);
export_proto(mmaxloc0_16_r10);
void
mmaxloc0_16_r10 (gfc_array_i16 * const restrict retarray,
gfc_array_r10 * const restrict array,
gfc_array_l1 * const restrict mask)
{
index_type count[GFC_MAX_DIMENSIONS];
index_type extent[GFC_MAX_DIMENSIONS];
index_type sstride[GFC_MAX_DIMENSIONS];
index_type mstride[GFC_MAX_DIMENSIONS];
index_type dstride;
GFC_INTEGER_16 *dest;
const GFC_REAL_10 *base;
GFC_LOGICAL_1 *mbase;
int rank;
index_type n;
int mask_kind;
rank = GFC_DESCRIPTOR_RANK (array);
if (rank <= 0)
runtime_error ("Rank of array needs to be > 0");
if (retarray->base_addr == NULL)
{
GFC_DIMENSION_SET(retarray->dim[0], 0, rank - 1, 1);
retarray->dtype = (retarray->dtype & ~GFC_DTYPE_RANK_MASK) | 1;
retarray->offset = 0;
retarray->base_addr = xmallocarray (rank, sizeof (GFC_INTEGER_16));
}
else
{
if (unlikely (compile_options.bounds_check))
{
bounds_iforeach_return ((array_t *) retarray, (array_t *) array,
"MAXLOC");
bounds_equal_extents ((array_t *) mask, (array_t *) array,
"MASK argument", "MAXLOC");
}
}
mask_kind = GFC_DESCRIPTOR_SIZE (mask);
mbase = mask->base_addr;
if (mask_kind == 1 || mask_kind == 2 || mask_kind == 4 || mask_kind == 8
#ifdef HAVE_GFC_LOGICAL_16
|| mask_kind == 16
#endif
)
mbase = GFOR_POINTER_TO_L1 (mbase, mask_kind);
else
runtime_error ("Funny sized logical array");
dstride = GFC_DESCRIPTOR_STRIDE(retarray,0);
dest = retarray->base_addr;
for (n = 0; n < rank; n++)
{
sstride[n] = GFC_DESCRIPTOR_STRIDE(array,n);
mstride[n] = GFC_DESCRIPTOR_STRIDE_BYTES(mask,n);
extent[n] = GFC_DESCRIPTOR_EXTENT(array,n);
count[n] = 0;
if (extent[n] <= 0)
{
/* Set the return value. */
for (n = 0; n < rank; n++)
dest[n * dstride] = 0;
return;
}
}
base = array->base_addr;
/* Initialize the return value. */
for (n = 0; n < rank; n++)
dest[n * dstride] = 0;
{
GFC_REAL_10 maxval;
int fast = 0;
#if defined(GFC_REAL_10_INFINITY)
maxval = -GFC_REAL_10_INFINITY;
#else
maxval = -GFC_REAL_10_HUGE;
#endif
while (base)
{
do
{
/* Implementation start. */
}
while (0);
if (unlikely (!fast))
{
do
{
if (*mbase)
{
#if defined(GFC_REAL_10_QUIET_NAN)
if (unlikely (dest[0] == 0))
for (n = 0; n < rank; n++)
dest[n * dstride] = count[n] + 1;
if (*base >= maxval)
#endif
{
fast = 1;
maxval = *base;
for (n = 0; n < rank; n++)
dest[n * dstride] = count[n] + 1;
break;
}
}
base += sstride[0];
mbase += mstride[0];
}
while (++count[0] != extent[0]);
if (likely (fast))
continue;
}
else do
{
if (*mbase && *base > maxval)
{
maxval = *base;
for (n = 0; n < rank; n++)
dest[n * dstride] = count[n] + 1;
}
/* Implementation end. */
/* Advance to the next element. */
base += sstride[0];
mbase += mstride[0];
}
while (++count[0] != extent[0]);
n = 0;
do
{
/* When we get to the end of a dimension, reset it and increment
the next dimension. */
count[n] = 0;
/* We could precalculate these products, but this is a less
frequently used path so probably not worth it. */
base -= sstride[n] * extent[n];
mbase -= mstride[n] * extent[n];
n++;
if (n == rank)
{
/* Break out of the loop. */
base = NULL;
break;
}
else
{
count[n]++;
base += sstride[n];
mbase += mstride[n];
}
}
while (count[n] == extent[n]);
}
}
}
extern void smaxloc0_16_r10 (gfc_array_i16 * const restrict,
gfc_array_r10 * const restrict, GFC_LOGICAL_4 *);
export_proto(smaxloc0_16_r10);
void
smaxloc0_16_r10 (gfc_array_i16 * const restrict retarray,
gfc_array_r10 * const restrict array,
GFC_LOGICAL_4 * mask)
{
index_type rank;
index_type dstride;
index_type n;
GFC_INTEGER_16 *dest;
if (*mask)
{
maxloc0_16_r10 (retarray, array);
return;
}
rank = GFC_DESCRIPTOR_RANK (array);
if (rank <= 0)
runtime_error ("Rank of array needs to be > 0");
if (retarray->base_addr == NULL)
{
GFC_DIMENSION_SET(retarray->dim[0], 0, rank-1, 1);
retarray->dtype = (retarray->dtype & ~GFC_DTYPE_RANK_MASK) | 1;
retarray->offset = 0;
retarray->base_addr = xmallocarray (rank, sizeof (GFC_INTEGER_16));
}
else if (unlikely (compile_options.bounds_check))
{
bounds_iforeach_return ((array_t *) retarray, (array_t *) array,
"MAXLOC");
}
dstride = GFC_DESCRIPTOR_STRIDE(retarray,0);
dest = retarray->base_addr;
for (n = 0; n<rank; n++)
dest[n * dstride] = 0 ;
}
#endif
| evaautomation/gcc-linaro | libgfortran/generated/maxloc0_16_r10.c | C | gpl-2.0 | 9,168 |
/*
* Copyright 2015 Advanced Micro Devices, Inc.
*
* 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 COPYRIGHT HOLDER(S) OR AUTHOR(S) 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 <linux/types.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/gfp.h>
#include "smumgr.h"
#include "tonga_smumgr.h"
#include "pp_debug.h"
#include "smu_ucode_xfer_vi.h"
#include "tonga_ppsmc.h"
#include "smu/smu_7_1_2_d.h"
#include "smu/smu_7_1_2_sh_mask.h"
#include "cgs_common.h"
#define TONGA_SMC_SIZE 0x20000
#define BUFFER_SIZE 80000
#define MAX_STRING_SIZE 15
#define BUFFER_SIZETWO 131072 /*128 *1024*/
/**
* Set the address for reading/writing the SMC SRAM space.
* @param smumgr the address of the powerplay hardware manager.
* @param smcAddress the address in the SMC RAM to access.
*/
static int tonga_set_smc_sram_address(struct pp_smumgr *smumgr,
uint32_t smcAddress, uint32_t limit)
{
if (smumgr == NULL || smumgr->device == NULL)
return -EINVAL;
PP_ASSERT_WITH_CODE((0 == (3 & smcAddress)),
"SMC address must be 4 byte aligned.",
return -1;);
PP_ASSERT_WITH_CODE((limit > (smcAddress + 3)),
"SMC address is beyond the SMC RAM area.",
return -1;);
cgs_write_register(smumgr->device, mmSMC_IND_INDEX_0, smcAddress);
SMUM_WRITE_FIELD(smumgr->device, SMC_IND_ACCESS_CNTL, AUTO_INCREMENT_IND_11, 0);
return 0;
}
/**
* Copy bytes from an array into the SMC RAM space.
*
* @param smumgr the address of the powerplay SMU manager.
* @param smcStartAddress the start address in the SMC RAM to copy bytes to.
* @param src the byte array to copy the bytes from.
* @param byteCount the number of bytes to copy.
*/
int tonga_copy_bytes_to_smc(struct pp_smumgr *smumgr,
uint32_t smcStartAddress, const uint8_t *src,
uint32_t byteCount, uint32_t limit)
{
uint32_t addr;
uint32_t data, orig_data;
int result = 0;
uint32_t extra_shift;
if (smumgr == NULL || smumgr->device == NULL)
return -EINVAL;
PP_ASSERT_WITH_CODE((0 == (3 & smcStartAddress)),
"SMC address must be 4 byte aligned.",
return 0;);
PP_ASSERT_WITH_CODE((limit > (smcStartAddress + byteCount)),
"SMC address is beyond the SMC RAM area.",
return 0;);
addr = smcStartAddress;
while (byteCount >= 4) {
/*
* Bytes are written into the
* SMC address space with the MSB first
*/
data = (src[0] << 24) + (src[1] << 16) + (src[2] << 8) + src[3];
result = tonga_set_smc_sram_address(smumgr, addr, limit);
if (result)
goto out;
cgs_write_register(smumgr->device, mmSMC_IND_DATA_0, data);
src += 4;
byteCount -= 4;
addr += 4;
}
if (0 != byteCount) {
/* Now write odd bytes left, do a read modify write cycle */
data = 0;
result = tonga_set_smc_sram_address(smumgr, addr, limit);
if (result)
goto out;
orig_data = cgs_read_register(smumgr->device,
mmSMC_IND_DATA_0);
extra_shift = 8 * (4 - byteCount);
while (byteCount > 0) {
data = (data << 8) + *src++;
byteCount--;
}
data <<= extra_shift;
data |= (orig_data & ~((~0UL) << extra_shift));
result = tonga_set_smc_sram_address(smumgr, addr, limit);
if (result)
goto out;
cgs_write_register(smumgr->device, mmSMC_IND_DATA_0, data);
}
out:
return result;
}
int tonga_program_jump_on_start(struct pp_smumgr *smumgr)
{
static const unsigned char pData[] = { 0xE0, 0x00, 0x80, 0x40 };
tonga_copy_bytes_to_smc(smumgr, 0x0, pData, 4, sizeof(pData)+1);
return 0;
}
/**
* Return if the SMC is currently running.
*
* @param smumgr the address of the powerplay hardware manager.
*/
static int tonga_is_smc_ram_running(struct pp_smumgr *smumgr)
{
return ((0 == SMUM_READ_VFPF_INDIRECT_FIELD(smumgr->device, CGS_IND_REG__SMC,
SMC_SYSCON_CLOCK_CNTL_0, ck_disable))
&& (0x20100 <= cgs_read_ind_register(smumgr->device,
CGS_IND_REG__SMC, ixSMC_PC_C)));
}
static int tonga_send_msg_to_smc_offset(struct pp_smumgr *smumgr)
{
if (smumgr == NULL || smumgr->device == NULL)
return -EINVAL;
SMUM_WAIT_FIELD_UNEQUAL(smumgr, SMC_RESP_0, SMC_RESP, 0);
cgs_write_register(smumgr->device, mmSMC_MSG_ARG_0, 0x20000);
cgs_write_register(smumgr->device, mmSMC_MESSAGE_0, PPSMC_MSG_Test);
SMUM_WAIT_FIELD_UNEQUAL(smumgr, SMC_RESP_0, SMC_RESP, 0);
return 0;
}
/**
* Send a message to the SMC, and wait for its response.
*
* @param smumgr the address of the powerplay hardware manager.
* @param msg the message to send.
* @return The response that came from the SMC.
*/
static int tonga_send_msg_to_smc(struct pp_smumgr *smumgr, uint16_t msg)
{
if (smumgr == NULL || smumgr->device == NULL)
return -EINVAL;
if (!tonga_is_smc_ram_running(smumgr))
return -1;
SMUM_WAIT_FIELD_UNEQUAL(smumgr, SMC_RESP_0, SMC_RESP, 0);
PP_ASSERT_WITH_CODE(
1 == SMUM_READ_FIELD(smumgr->device, SMC_RESP_0, SMC_RESP),
"Failed to send Previous Message.",
);
cgs_write_register(smumgr->device, mmSMC_MESSAGE_0, msg);
SMUM_WAIT_FIELD_UNEQUAL(smumgr, SMC_RESP_0, SMC_RESP, 0);
PP_ASSERT_WITH_CODE(
1 == SMUM_READ_FIELD(smumgr->device, SMC_RESP_0, SMC_RESP),
"Failed to send Message.",
);
return 0;
}
/*
* Send a message to the SMC, and do not wait for its response.
*
* @param smumgr the address of the powerplay hardware manager.
* @param msg the message to send.
* @return The response that came from the SMC.
*/
static int tonga_send_msg_to_smc_without_waiting
(struct pp_smumgr *smumgr, uint16_t msg)
{
if (smumgr == NULL || smumgr->device == NULL)
return -EINVAL;
SMUM_WAIT_FIELD_UNEQUAL(smumgr, SMC_RESP_0, SMC_RESP, 0);
PP_ASSERT_WITH_CODE(
1 == SMUM_READ_FIELD(smumgr->device, SMC_RESP_0, SMC_RESP),
"Failed to send Previous Message.",
);
cgs_write_register(smumgr->device, mmSMC_MESSAGE_0, msg);
return 0;
}
/*
* Send a message to the SMC with parameter
*
* @param smumgr: the address of the powerplay hardware manager.
* @param msg: the message to send.
* @param parameter: the parameter to send
* @return The response that came from the SMC.
*/
static int tonga_send_msg_to_smc_with_parameter(struct pp_smumgr *smumgr,
uint16_t msg, uint32_t parameter)
{
if (smumgr == NULL || smumgr->device == NULL)
return -EINVAL;
if (!tonga_is_smc_ram_running(smumgr))
return PPSMC_Result_Failed;
SMUM_WAIT_FIELD_UNEQUAL(smumgr, SMC_RESP_0, SMC_RESP, 0);
cgs_write_register(smumgr->device, mmSMC_MSG_ARG_0, parameter);
return tonga_send_msg_to_smc(smumgr, msg);
}
/*
* Send a message to the SMC with parameter, do not wait for response
*
* @param smumgr: the address of the powerplay hardware manager.
* @param msg: the message to send.
* @param parameter: the parameter to send
* @return The response that came from the SMC.
*/
static int tonga_send_msg_to_smc_with_parameter_without_waiting(
struct pp_smumgr *smumgr,
uint16_t msg, uint32_t parameter)
{
if (smumgr == NULL || smumgr->device == NULL)
return -EINVAL;
SMUM_WAIT_FIELD_UNEQUAL(smumgr, SMC_RESP_0, SMC_RESP, 0);
cgs_write_register(smumgr->device, mmSMC_MSG_ARG_0, parameter);
return tonga_send_msg_to_smc_without_waiting(smumgr, msg);
}
/*
* Read a 32bit value from the SMC SRAM space.
* ALL PARAMETERS ARE IN HOST BYTE ORDER.
* @param smumgr the address of the powerplay hardware manager.
* @param smcAddress the address in the SMC RAM to access.
* @param value and output parameter for the data read from the SMC SRAM.
*/
int tonga_read_smc_sram_dword(struct pp_smumgr *smumgr,
uint32_t smcAddress, uint32_t *value,
uint32_t limit)
{
int result;
result = tonga_set_smc_sram_address(smumgr, smcAddress, limit);
if (0 != result)
return result;
*value = cgs_read_register(smumgr->device, mmSMC_IND_DATA_0);
return 0;
}
/*
* Write a 32bit value to the SMC SRAM space.
* ALL PARAMETERS ARE IN HOST BYTE ORDER.
* @param smumgr the address of the powerplay hardware manager.
* @param smcAddress the address in the SMC RAM to access.
* @param value to write to the SMC SRAM.
*/
int tonga_write_smc_sram_dword(struct pp_smumgr *smumgr,
uint32_t smcAddress, uint32_t value,
uint32_t limit)
{
int result;
result = tonga_set_smc_sram_address(smumgr, smcAddress, limit);
if (0 != result)
return result;
cgs_write_register(smumgr->device, mmSMC_IND_DATA_0, value);
return 0;
}
static int tonga_smu_fini(struct pp_smumgr *smumgr)
{
struct tonga_smumgr *priv = (struct tonga_smumgr *)(smumgr->backend);
smu_free_memory(smumgr->device, (void *)priv->smu_buffer.handle);
smu_free_memory(smumgr->device, (void *)priv->header_buffer.handle);
if (smumgr->backend != NULL) {
kfree(smumgr->backend);
smumgr->backend = NULL;
}
cgs_rel_firmware(smumgr->device, CGS_UCODE_ID_SMU);
return 0;
}
static enum cgs_ucode_id tonga_convert_fw_type_to_cgs(uint32_t fw_type)
{
enum cgs_ucode_id result = CGS_UCODE_ID_MAXIMUM;
switch (fw_type) {
case UCODE_ID_SMU:
result = CGS_UCODE_ID_SMU;
break;
case UCODE_ID_SDMA0:
result = CGS_UCODE_ID_SDMA0;
break;
case UCODE_ID_SDMA1:
result = CGS_UCODE_ID_SDMA1;
break;
case UCODE_ID_CP_CE:
result = CGS_UCODE_ID_CP_CE;
break;
case UCODE_ID_CP_PFP:
result = CGS_UCODE_ID_CP_PFP;
break;
case UCODE_ID_CP_ME:
result = CGS_UCODE_ID_CP_ME;
break;
case UCODE_ID_CP_MEC:
result = CGS_UCODE_ID_CP_MEC;
break;
case UCODE_ID_CP_MEC_JT1:
result = CGS_UCODE_ID_CP_MEC_JT1;
break;
case UCODE_ID_CP_MEC_JT2:
result = CGS_UCODE_ID_CP_MEC_JT2;
break;
case UCODE_ID_RLC_G:
result = CGS_UCODE_ID_RLC_G;
break;
default:
break;
}
return result;
}
/**
* Convert the PPIRI firmware type to SMU type mask.
* For MEC, we need to check all MEC related type
*/
static uint16_t tonga_get_mask_for_firmware_type(uint16_t firmwareType)
{
uint16_t result = 0;
switch (firmwareType) {
case UCODE_ID_SDMA0:
result = UCODE_ID_SDMA0_MASK;
break;
case UCODE_ID_SDMA1:
result = UCODE_ID_SDMA1_MASK;
break;
case UCODE_ID_CP_CE:
result = UCODE_ID_CP_CE_MASK;
break;
case UCODE_ID_CP_PFP:
result = UCODE_ID_CP_PFP_MASK;
break;
case UCODE_ID_CP_ME:
result = UCODE_ID_CP_ME_MASK;
break;
case UCODE_ID_CP_MEC:
case UCODE_ID_CP_MEC_JT1:
case UCODE_ID_CP_MEC_JT2:
result = UCODE_ID_CP_MEC_MASK;
break;
case UCODE_ID_RLC_G:
result = UCODE_ID_RLC_G_MASK;
break;
default:
break;
}
return result;
}
/**
* Check if the FW has been loaded,
* SMU will not return if loading has not finished.
*/
static int tonga_check_fw_load_finish(struct pp_smumgr *smumgr, uint32_t fwType)
{
uint16_t fwMask = tonga_get_mask_for_firmware_type(fwType);
if (0 != SMUM_WAIT_VFPF_INDIRECT_REGISTER(smumgr, SMC_IND,
SOFT_REGISTERS_TABLE_28, fwMask, fwMask)) {
printk(KERN_ERR "[ powerplay ] check firmware loading failed\n");
return -EINVAL;
}
return 0;
}
/* Populate one firmware image to the data structure */
static int tonga_populate_single_firmware_entry(struct pp_smumgr *smumgr,
uint16_t firmware_type,
struct SMU_Entry *pentry)
{
int result;
struct cgs_firmware_info info = {0};
result = cgs_get_firmware_info(
smumgr->device,
tonga_convert_fw_type_to_cgs(firmware_type),
&info);
if (result == 0) {
pentry->version = 0;
pentry->id = (uint16_t)firmware_type;
pentry->image_addr_high = smu_upper_32_bits(info.mc_addr);
pentry->image_addr_low = smu_lower_32_bits(info.mc_addr);
pentry->meta_data_addr_high = 0;
pentry->meta_data_addr_low = 0;
pentry->data_size_byte = info.image_size;
pentry->num_register_entries = 0;
if (firmware_type == UCODE_ID_RLC_G)
pentry->flags = 1;
else
pentry->flags = 0;
} else {
return result;
}
return result;
}
static int tonga_request_smu_reload_fw(struct pp_smumgr *smumgr)
{
struct tonga_smumgr *tonga_smu =
(struct tonga_smumgr *)(smumgr->backend);
uint16_t fw_to_load;
struct SMU_DRAMData_TOC *toc;
/**
* First time this gets called during SmuMgr init,
* we haven't processed SMU header file yet,
* so Soft Register Start offset is unknown.
* However, for this case, UcodeLoadStatus is already 0,
* so we can skip this if the Soft Registers Start offset is 0.
*/
cgs_write_ind_register(smumgr->device,
CGS_IND_REG__SMC, ixSOFT_REGISTERS_TABLE_28, 0);
tonga_send_msg_to_smc_with_parameter(smumgr,
PPSMC_MSG_SMU_DRAM_ADDR_HI,
tonga_smu->smu_buffer.mc_addr_high);
tonga_send_msg_to_smc_with_parameter(smumgr,
PPSMC_MSG_SMU_DRAM_ADDR_LO,
tonga_smu->smu_buffer.mc_addr_low);
toc = (struct SMU_DRAMData_TOC *)tonga_smu->pHeader;
toc->num_entries = 0;
toc->structure_version = 1;
PP_ASSERT_WITH_CODE(
0 == tonga_populate_single_firmware_entry(smumgr,
UCODE_ID_RLC_G,
&toc->entry[toc->num_entries++]),
"Failed to Get Firmware Entry.\n",
return -1);
PP_ASSERT_WITH_CODE(
0 == tonga_populate_single_firmware_entry(smumgr,
UCODE_ID_CP_CE,
&toc->entry[toc->num_entries++]),
"Failed to Get Firmware Entry.\n",
return -1);
PP_ASSERT_WITH_CODE(
0 == tonga_populate_single_firmware_entry
(smumgr, UCODE_ID_CP_PFP, &toc->entry[toc->num_entries++]),
"Failed to Get Firmware Entry.\n", return -1);
PP_ASSERT_WITH_CODE(
0 == tonga_populate_single_firmware_entry
(smumgr, UCODE_ID_CP_ME, &toc->entry[toc->num_entries++]),
"Failed to Get Firmware Entry.\n", return -1);
PP_ASSERT_WITH_CODE(
0 == tonga_populate_single_firmware_entry
(smumgr, UCODE_ID_CP_MEC, &toc->entry[toc->num_entries++]),
"Failed to Get Firmware Entry.\n", return -1);
PP_ASSERT_WITH_CODE(
0 == tonga_populate_single_firmware_entry
(smumgr, UCODE_ID_CP_MEC_JT1, &toc->entry[toc->num_entries++]),
"Failed to Get Firmware Entry.\n", return -1);
PP_ASSERT_WITH_CODE(
0 == tonga_populate_single_firmware_entry
(smumgr, UCODE_ID_CP_MEC_JT2, &toc->entry[toc->num_entries++]),
"Failed to Get Firmware Entry.\n", return -1);
PP_ASSERT_WITH_CODE(
0 == tonga_populate_single_firmware_entry
(smumgr, UCODE_ID_SDMA0, &toc->entry[toc->num_entries++]),
"Failed to Get Firmware Entry.\n", return -1);
PP_ASSERT_WITH_CODE(
0 == tonga_populate_single_firmware_entry
(smumgr, UCODE_ID_SDMA1, &toc->entry[toc->num_entries++]),
"Failed to Get Firmware Entry.\n", return -1);
tonga_send_msg_to_smc_with_parameter(smumgr,
PPSMC_MSG_DRV_DRAM_ADDR_HI,
tonga_smu->header_buffer.mc_addr_high);
tonga_send_msg_to_smc_with_parameter(smumgr,
PPSMC_MSG_DRV_DRAM_ADDR_LO,
tonga_smu->header_buffer.mc_addr_low);
fw_to_load = UCODE_ID_RLC_G_MASK
+ UCODE_ID_SDMA0_MASK
+ UCODE_ID_SDMA1_MASK
+ UCODE_ID_CP_CE_MASK
+ UCODE_ID_CP_ME_MASK
+ UCODE_ID_CP_PFP_MASK
+ UCODE_ID_CP_MEC_MASK;
PP_ASSERT_WITH_CODE(
0 == tonga_send_msg_to_smc_with_parameter_without_waiting(
smumgr, PPSMC_MSG_LoadUcodes, fw_to_load),
"Fail to Request SMU Load uCode", return 0);
return 0;
}
static int tonga_request_smu_load_specific_fw(struct pp_smumgr *smumgr,
uint32_t firmwareType)
{
return 0;
}
/**
* Upload the SMC firmware to the SMC microcontroller.
*
* @param smumgr the address of the powerplay hardware manager.
* @param pFirmware the data structure containing the various sections of the firmware.
*/
static int tonga_smu_upload_firmware_image(struct pp_smumgr *smumgr)
{
const uint8_t *src;
uint32_t byte_count;
uint32_t *data;
struct cgs_firmware_info info = {0};
if (smumgr == NULL || smumgr->device == NULL)
return -EINVAL;
cgs_get_firmware_info(smumgr->device,
tonga_convert_fw_type_to_cgs(UCODE_ID_SMU), &info);
if (info.image_size & 3) {
printk(KERN_ERR "[ powerplay ] SMC ucode is not 4 bytes aligned\n");
return -EINVAL;
}
if (info.image_size > TONGA_SMC_SIZE) {
printk(KERN_ERR "[ powerplay ] SMC address is beyond the SMC RAM area\n");
return -EINVAL;
}
cgs_write_register(smumgr->device, mmSMC_IND_INDEX_0, 0x20000);
SMUM_WRITE_FIELD(smumgr->device, SMC_IND_ACCESS_CNTL, AUTO_INCREMENT_IND_0, 1);
byte_count = info.image_size;
src = (const uint8_t *)info.kptr;
data = (uint32_t *)src;
for (; byte_count >= 4; data++, byte_count -= 4)
cgs_write_register(smumgr->device, mmSMC_IND_DATA_0, data[0]);
SMUM_WRITE_FIELD(smumgr->device, SMC_IND_ACCESS_CNTL, AUTO_INCREMENT_IND_0, 0);
return 0;
}
static int tonga_start_in_protection_mode(struct pp_smumgr *smumgr)
{
int result;
/* Assert reset */
SMUM_WRITE_VFPF_INDIRECT_FIELD(smumgr->device, CGS_IND_REG__SMC,
SMC_SYSCON_RESET_CNTL, rst_reg, 1);
result = tonga_smu_upload_firmware_image(smumgr);
if (result)
return result;
/* Clear status */
cgs_write_ind_register(smumgr->device, CGS_IND_REG__SMC,
ixSMU_STATUS, 0);
/* Enable clock */
SMUM_WRITE_VFPF_INDIRECT_FIELD(smumgr->device, CGS_IND_REG__SMC,
SMC_SYSCON_CLOCK_CNTL_0, ck_disable, 0);
/* De-assert reset */
SMUM_WRITE_VFPF_INDIRECT_FIELD(smumgr->device, CGS_IND_REG__SMC,
SMC_SYSCON_RESET_CNTL, rst_reg, 0);
/* Set SMU Auto Start */
SMUM_WRITE_VFPF_INDIRECT_FIELD(smumgr->device, CGS_IND_REG__SMC,
SMU_INPUT_DATA, AUTO_START, 1);
/* Clear firmware interrupt enable flag */
cgs_write_ind_register(smumgr->device, CGS_IND_REG__SMC,
ixFIRMWARE_FLAGS, 0);
SMUM_WAIT_VFPF_INDIRECT_FIELD(smumgr, SMC_IND,
RCU_UC_EVENTS, INTERRUPTS_ENABLED, 1);
/**
* Call Test SMU message with 0x20000 offset to trigger SMU start
*/
tonga_send_msg_to_smc_offset(smumgr);
/* Wait for done bit to be set */
SMUM_WAIT_VFPF_INDIRECT_FIELD_UNEQUAL(smumgr, SMC_IND,
SMU_STATUS, SMU_DONE, 0);
/* Check pass/failed indicator */
if (1 != SMUM_READ_VFPF_INDIRECT_FIELD(smumgr->device,
CGS_IND_REG__SMC, SMU_STATUS, SMU_PASS)) {
printk(KERN_ERR "[ powerplay ] SMU Firmware start failed\n");
return -EINVAL;
}
/* Wait for firmware to initialize */
SMUM_WAIT_VFPF_INDIRECT_FIELD(smumgr, SMC_IND,
FIRMWARE_FLAGS, INTERRUPTS_ENABLED, 1);
return 0;
}
static int tonga_start_in_non_protection_mode(struct pp_smumgr *smumgr)
{
int result = 0;
/* wait for smc boot up */
SMUM_WAIT_VFPF_INDIRECT_FIELD_UNEQUAL(smumgr, SMC_IND,
RCU_UC_EVENTS, boot_seq_done, 0);
/*Clear firmware interrupt enable flag*/
cgs_write_ind_register(smumgr->device, CGS_IND_REG__SMC,
ixFIRMWARE_FLAGS, 0);
SMUM_WRITE_VFPF_INDIRECT_FIELD(smumgr->device, CGS_IND_REG__SMC,
SMC_SYSCON_RESET_CNTL, rst_reg, 1);
result = tonga_smu_upload_firmware_image(smumgr);
if (result != 0)
return result;
/* Set smc instruct start point at 0x0 */
tonga_program_jump_on_start(smumgr);
SMUM_WRITE_VFPF_INDIRECT_FIELD(smumgr->device, CGS_IND_REG__SMC,
SMC_SYSCON_CLOCK_CNTL_0, ck_disable, 0);
/*De-assert reset*/
SMUM_WRITE_VFPF_INDIRECT_FIELD(smumgr->device, CGS_IND_REG__SMC,
SMC_SYSCON_RESET_CNTL, rst_reg, 0);
/* Wait for firmware to initialize */
SMUM_WAIT_VFPF_INDIRECT_FIELD(smumgr, SMC_IND,
FIRMWARE_FLAGS, INTERRUPTS_ENABLED, 1);
return result;
}
static int tonga_start_smu(struct pp_smumgr *smumgr)
{
int result;
/* Only start SMC if SMC RAM is not running */
if (!tonga_is_smc_ram_running(smumgr)) {
/*Check if SMU is running in protected mode*/
if (0 == SMUM_READ_VFPF_INDIRECT_FIELD(smumgr->device, CGS_IND_REG__SMC,
SMU_FIRMWARE, SMU_MODE)) {
result = tonga_start_in_non_protection_mode(smumgr);
if (result)
return result;
} else {
result = tonga_start_in_protection_mode(smumgr);
if (result)
return result;
}
}
result = tonga_request_smu_reload_fw(smumgr);
return result;
}
/**
* Write a 32bit value to the SMC SRAM space.
* ALL PARAMETERS ARE IN HOST BYTE ORDER.
* @param smumgr the address of the powerplay hardware manager.
* @param smcAddress the address in the SMC RAM to access.
* @param value to write to the SMC SRAM.
*/
static int tonga_smu_init(struct pp_smumgr *smumgr)
{
struct tonga_smumgr *tonga_smu;
uint8_t *internal_buf;
uint64_t mc_addr = 0;
/* Allocate memory for backend private data */
tonga_smu = (struct tonga_smumgr *)(smumgr->backend);
tonga_smu->header_buffer.data_size =
((sizeof(struct SMU_DRAMData_TOC) / 4096) + 1) * 4096;
tonga_smu->smu_buffer.data_size = 200*4096;
smu_allocate_memory(smumgr->device,
tonga_smu->header_buffer.data_size,
CGS_GPU_MEM_TYPE__VISIBLE_CONTIG_FB,
PAGE_SIZE,
&mc_addr,
&tonga_smu->header_buffer.kaddr,
&tonga_smu->header_buffer.handle);
tonga_smu->pHeader = tonga_smu->header_buffer.kaddr;
tonga_smu->header_buffer.mc_addr_high = smu_upper_32_bits(mc_addr);
tonga_smu->header_buffer.mc_addr_low = smu_lower_32_bits(mc_addr);
PP_ASSERT_WITH_CODE((NULL != tonga_smu->pHeader),
"Out of memory.",
kfree(smumgr->backend);
cgs_free_gpu_mem(smumgr->device,
(cgs_handle_t)tonga_smu->header_buffer.handle);
return -1);
smu_allocate_memory(smumgr->device,
tonga_smu->smu_buffer.data_size,
CGS_GPU_MEM_TYPE__VISIBLE_CONTIG_FB,
PAGE_SIZE,
&mc_addr,
&tonga_smu->smu_buffer.kaddr,
&tonga_smu->smu_buffer.handle);
internal_buf = tonga_smu->smu_buffer.kaddr;
tonga_smu->smu_buffer.mc_addr_high = smu_upper_32_bits(mc_addr);
tonga_smu->smu_buffer.mc_addr_low = smu_lower_32_bits(mc_addr);
PP_ASSERT_WITH_CODE((NULL != internal_buf),
"Out of memory.",
kfree(smumgr->backend);
cgs_free_gpu_mem(smumgr->device,
(cgs_handle_t)tonga_smu->smu_buffer.handle);
return -1;);
return 0;
}
static const struct pp_smumgr_func tonga_smu_funcs = {
.smu_init = &tonga_smu_init,
.smu_fini = &tonga_smu_fini,
.start_smu = &tonga_start_smu,
.check_fw_load_finish = &tonga_check_fw_load_finish,
.request_smu_load_fw = &tonga_request_smu_reload_fw,
.request_smu_load_specific_fw = &tonga_request_smu_load_specific_fw,
.send_msg_to_smc = &tonga_send_msg_to_smc,
.send_msg_to_smc_with_parameter = &tonga_send_msg_to_smc_with_parameter,
.download_pptable_settings = NULL,
.upload_pptable_settings = NULL,
};
int tonga_smum_init(struct pp_smumgr *smumgr)
{
struct tonga_smumgr *tonga_smu = NULL;
tonga_smu = kzalloc(sizeof(struct tonga_smumgr), GFP_KERNEL);
if (tonga_smu == NULL)
return -ENOMEM;
smumgr->backend = tonga_smu;
smumgr->smumgr_funcs = &tonga_smu_funcs;
return 0;
}
| codebam/linux | drivers/gpu/drm/amd/powerplay/smumgr/tonga_smumgr.c | C | gpl-2.0 | 22,886 |
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2009 Free Software Foundation, Inc.
*
* GRUB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GRUB is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GRUB. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRUB_COMMAND_HEADER
#define GRUB_COMMAND_HEADER 1
#include <grub/symbol.h>
#include <grub/err.h>
#include <grub/list.h>
#include <grub/misc.h>
typedef enum grub_command_flags
{
/* This is an extended command. */
GRUB_COMMAND_FLAG_EXTCMD = 0x10,
/* This is an dynamic command. */
GRUB_COMMAND_FLAG_DYNCMD = 0x20,
/* This command accepts block arguments. */
GRUB_COMMAND_FLAG_BLOCKS = 0x40,
/* This command accepts unknown arguments as direct parameters. */
GRUB_COMMAND_ACCEPT_DASH = 0x80,
/* This command accepts only options preceding direct arguments. */
GRUB_COMMAND_OPTIONS_AT_START = 0x100,
/* Can be executed in an entries extractor. */
GRUB_COMMAND_FLAG_EXTRACTOR = 0x200
} grub_command_flags_t;
struct grub_command;
typedef grub_err_t (*grub_command_func_t) (struct grub_command *cmd,
int argc, char **argv);
#define GRUB_COMMAND_PRIO_MASK 0xff
#define GRUB_COMMAND_FLAG_ACTIVE 0x100
/* The command description. */
struct grub_command
{
/* The next element. */
struct grub_command *next;
struct grub_command **prev;
/* The name. */
const char *name;
/* The priority. */
int prio;
/* The callback function. */
grub_command_func_t func;
/* The flags. */
grub_command_flags_t flags;
/* The summary of the command usage. */
const char *summary;
/* The description of the command. */
const char *description;
/* Arbitrary data. */
void *data;
};
typedef struct grub_command *grub_command_t;
extern grub_command_t EXPORT_VAR(grub_command_list);
grub_command_t
EXPORT_FUNC(grub_register_command_prio) (const char *name,
grub_command_func_t func,
const char *summary,
const char *description,
int prio);
void EXPORT_FUNC(grub_unregister_command) (grub_command_t cmd);
static inline grub_command_t
grub_register_command (const char *name,
grub_command_func_t func,
const char *summary,
const char *description)
{
return grub_register_command_prio (name, func, summary, description, 0);
}
static inline grub_command_t
grub_register_command_p1 (const char *name,
grub_command_func_t func,
const char *summary,
const char *description)
{
return grub_register_command_prio (name, func, summary, description, 1);
}
static inline grub_command_t
grub_command_find (const char *name)
{
return grub_named_list_find (GRUB_AS_NAMED_LIST (grub_command_list), name);
}
static inline grub_err_t
grub_command_execute (const char *name, int argc, char **argv)
{
grub_command_t cmd;
cmd = grub_command_find (name);
return (cmd) ? cmd->func (cmd, argc, argv) : GRUB_ERR_FILE_NOT_FOUND;
}
#define FOR_COMMANDS(var) FOR_LIST_ELEMENTS((var), grub_command_list)
#define FOR_COMMANDS_SAFE(var, next) FOR_LIST_ELEMENTS_SAFE((var), (next), grub_command_list)
void grub_register_core_commands (void);
#endif /* ! GRUB_COMMAND_HEADER */
| mjg59/grub | include/grub/command.h | C | gpl-3.0 | 3,666 |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Validate DateBox - jQuery EasyUI Demo</title>
<link rel="stylesheet" type="text/css" href="../../themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="../../themes/icon.css">
<link rel="stylesheet" type="text/css" href="../demo.css">
<script type="text/javascript" src="../../jquery.min.js"></script>
<script type="text/javascript" src="../../jquery.easyui.min.js"></script>
</head>
<body>
<h2>Validate DateBox</h2>
<div class="demo-info">
<div class="demo-tip icon-tip"></div>
<div>When the selected date is greater than specified date. The field validator will raise an error.</div>
</div>
<div style="margin:10px 0;"></div>
<input class="easyui-datebox" required data-options="validType:'md[\'10/11/2012\']'"></input>
<script>
$.extend($.fn.validatebox.defaults.rules, {
md: {
validator: function(value, param){
var d1 = $.fn.datebox.defaults.parser(param[0]);
var d2 = $.fn.datebox.defaults.parser(value);
return d2<=d1;
},
message: 'The date must be less than or equals to {0}.'
}
})
</script>
</body>
</html> | jackche0214/wechatpaltform | weixinmenu/Content/easyui/jquery-easyui-1.3.5/demo/datebox/validate.html | HTML | unlicense | 1,148 |
#
# $Id: UTF7.pm,v 2.4 2006/06/03 20:28:48 dankogai Exp $
#
package Encode::Unicode::UTF7;
use strict;
use warnings;
no warnings 'redefine';
use base qw(Encode::Encoding);
__PACKAGE__->Define('UTF-7');
our $VERSION = do { my @r = ( q$Revision: 2.4 $ =~ /\d+/g ); sprintf "%d." . "%02d" x $#r, @r };
use MIME::Base64;
use Encode;
#
# Algorithms taken from Unicode::String by Gisle Aas
#
our $OPTIONAL_DIRECT_CHARS = 1;
my $specials = quotemeta "\'(),-./:?";
$OPTIONAL_DIRECT_CHARS
and $specials .= quotemeta "!\"#$%&*;<=>@[]^_`{|}";
# \s will not work because it matches U+3000 DEOGRAPHIC SPACE
# We use qr/[\n\r\t\ ] instead
my $re_asis = qr/(?:[\n\r\t\ A-Za-z0-9$specials])/;
my $re_encoded = qr/(?:[^\n\r\t\ A-Za-z0-9$specials])/;
my $e_utf16 = find_encoding("UTF-16BE");
sub needs_lines { 1 }
sub encode($$;$) {
my ( $obj, $str, $chk ) = @_;
my $len = length($str);
pos($str) = 0;
my $bytes = '';
while ( pos($str) < $len ) {
if ( $str =~ /\G($re_asis+)/ogc ) {
$bytes .= $1;
}
elsif ( $str =~ /\G($re_encoded+)/ogsc ) {
if ( $1 eq "+" ) {
$bytes .= "+-";
}
else {
my $s = $1;
my $base64 = encode_base64( $e_utf16->encode($s), '' );
$base64 =~ s/=+$//;
$bytes .= "+$base64-";
}
}
else {
die "This should not happen! (pos=" . pos($str) . ")";
}
}
$_[1] = '' if $chk;
return $bytes;
}
sub decode($$;$) {
my ( $obj, $bytes, $chk ) = @_;
my $len = length($bytes);
my $str = "";
no warnings 'uninitialized';
while ( pos($bytes) < $len ) {
if ( $bytes =~ /\G([^+]+)/ogc ) {
$str .= $1;
}
elsif ( $bytes =~ /\G\+-/ogc ) {
$str .= "+";
}
elsif ( $bytes =~ /\G\+([A-Za-z0-9+\/]+)-?/ogsc ) {
my $base64 = $1;
my $pad = length($base64) % 4;
$base64 .= "=" x ( 4 - $pad ) if $pad;
$str .= $e_utf16->decode( decode_base64($base64) );
}
elsif ( $bytes =~ /\G\+/ogc ) {
$^W and warn "Bad UTF7 data escape";
$str .= "+";
}
else {
die "This should not happen " . pos($bytes);
}
}
$_[1] = '' if $chk;
return $str;
}
1;
__END__
=head1 NAME
Encode::Unicode::UTF7 -- UTF-7 encoding
=head1 SYNOPSIS
use Encode qw/encode decode/;
$utf7 = encode("UTF-7", $utf8);
$utf8 = decode("UTF-7", $ucs2);
=head1 ABSTRACT
This module implements UTF-7 encoding documented in RFC 2152. UTF-7,
as its name suggests, is a 7-bit re-encoded version of UTF-16BE. It
is designed to be MTA-safe and expected to be a standard way to
exchange Unicoded mails via mails. But with the advent of UTF-8 and
8-bit compliant MTAs, UTF-7 is hardly ever used.
UTF-7 was not supported by Encode until version 1.95 because of that.
But Unicode::String, a module by Gisle Aas which adds Unicode supports
to non-utf8-savvy perl did support UTF-7, the UTF-7 support was added
so Encode can supersede Unicode::String 100%.
=head1 In Practice
When you want to encode Unicode for mails and web pages, however, do
not use UTF-7 unless you are sure your recipients and readers can
handle it. Very few MUAs and WWW Browsers support these days (only
Mozilla seems to support one). For general cases, use UTF-8 for
message body and MIME-Header for header instead.
=head1 SEE ALSO
L<Encode>, L<Encode::Unicode>, L<Unicode::String>
RFC 2781 L<http://www.ietf.org/rfc/rfc2152.txt>
=cut
| leighpauls/k2cro4 | third_party/cygwin/lib/perl5/5.10/i686-cygwin/Encode/Unicode/UTF7.pm | Perl | bsd-3-clause | 3,618 |
; lzo1y_s2.asm -- lzo1y_decompress_asm_safe
;
; This file is part of the LZO real-time data compression library.
;
; Copyright (C) 2008 Markus Franz Xaver Johannes Oberhumer
; Copyright (C) 2007 Markus Franz Xaver Johannes Oberhumer
; Copyright (C) 2006 Markus Franz Xaver Johannes Oberhumer
; Copyright (C) 2005 Markus Franz Xaver Johannes Oberhumer
; Copyright (C) 2004 Markus Franz Xaver Johannes Oberhumer
; Copyright (C) 2003 Markus Franz Xaver Johannes Oberhumer
; Copyright (C) 2002 Markus Franz Xaver Johannes Oberhumer
; Copyright (C) 2001 Markus Franz Xaver Johannes Oberhumer
; Copyright (C) 2000 Markus Franz Xaver Johannes Oberhumer
; Copyright (C) 1999 Markus Franz Xaver Johannes Oberhumer
; Copyright (C) 1998 Markus Franz Xaver Johannes Oberhumer
; Copyright (C) 1997 Markus Franz Xaver Johannes Oberhumer
; Copyright (C) 1996 Markus Franz Xaver Johannes Oberhumer
; All Rights Reserved.
;
; The LZO library is free software; you can redistribute it and/or
; modify it under the terms of the GNU General Public License as
; published by the Free Software Foundation; either version 2 of
; the License, or (at your option) any later version.
;
; The LZO 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 General Public License for more details.
;
; You should have received a copy of the GNU General Public License
; along with the LZO library; see the file COPYING.
; If not, write to the Free Software Foundation, Inc.,
; 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
;
; Markus F.X.J. Oberhumer
; <markus@oberhumer.com>
; http://www.oberhumer.com/opensource/lzo/
;
; /***** DO NOT EDIT - GENERATED AUTOMATICALLY *****/
include asminit.def
public _lzo1y_decompress_asm_safe
_lzo1y_decompress_asm_safe:
db 85,87,86,83,81,82,131,236,12,252,139,116,36,40,139,124
db 36,48,189,3,0,0,0,141,70,253,3,68,36,44,137,68
db 36,4,137,248,139,84,36,52,3,2,137,4,36,49,192,49
db 219,172,60,17,118,87,44,17,60,4,115,92,141,20,7,57
db 20,36,15,130,130,2,0,0,141,20,6,57,84,36,4,15
db 130,110,2,0,0,137,193,235,110,5,255,0,0,0,141,84
db 6,18,57,84,36,4,15,130,87,2,0,0,138,30,70,8
db 219,116,230,141,68,24,18,235,31,141,180,38,0,0,0,0
db 57,116,36,4,15,130,57,2,0,0,138,6,70,60,16,115
db 127,8,192,116,215,131,192,3,141,84,7,0,57,20,36,15
db 130,37,2,0,0,141,84,6,0,57,84,36,4,15,130,16
db 2,0,0,137,193,193,232,2,33,233,139,22,131,198,4,137
db 23,131,199,4,72,117,243,243,164,138,6,70,60,16,115,64
db 141,87,3,57,20,36,15,130,238,1,0,0,193,232,2,138
db 30,141,151,255,251,255,255,141,4,152,70,41,194,59,84,36
db 48,15,130,218,1,0,0,138,2,136,7,138,66,1,136,71
db 1,138,66,2,136,71,2,1,239,233,163,0,0,0,137,246
db 60,64,114,68,137,193,193,232,2,141,87,255,33,232,138,30
db 193,233,4,141,4,152,70,41,194,73,57,232,115,76,233,181
db 0,0,0,5,255,0,0,0,141,86,3,57,84,36,4,15
db 130,126,1,0,0,138,30,70,8,219,116,231,141,76,24,33
db 49,192,235,20,141,116,38,0,60,32,15,130,200,0,0,0
db 131,224,31,116,224,141,72,2,102,139,6,141,87,255,193,232
db 2,131,198,2,41,194,57,232,114,110,59,84,36,48,15,130
db 77,1,0,0,141,4,15,57,4,36,15,130,58,1,0,0
db 137,203,193,235,2,116,17,139,2,131,194,4,137,7,131,199
db 4,75,117,243,33,233,116,9,138,2,66,136,7,71,73,117
db 247,138,70,254,33,232,15,132,196,254,255,255,141,20,7,57
db 20,36,15,130,2,1,0,0,141,20,6,57,84,36,4,15
db 130,238,0,0,0,138,14,70,136,15,71,72,117,247,138,6
db 70,233,42,255,255,255,137,246,59,84,36,48,15,130,223,0
db 0,0,141,68,15,0,57,4,36,15,130,203,0,0,0,135
db 214,243,164,137,214,235,170,129,193,255,0,0,0,141,86,3
db 57,84,36,4,15,130,169,0,0,0,138,30,70,8,219,116
db 230,141,76,11,9,235,21,144,60,16,114,44,137,193,131,224
db 8,193,224,13,131,225,7,116,225,131,193,2,102,139,6,131
db 198,2,141,151,0,192,255,255,193,232,2,116,57,41,194,233
db 38,255,255,255,141,116,38,0,141,87,2,57,20,36,114,106
db 193,232,2,138,30,141,87,255,141,4,152,70,41,194,59,84
db 36,48,114,93,138,2,136,7,138,90,1,136,95,1,131,199
db 2,233,43,255,255,255,131,249,3,15,149,192,59,60,36,119
db 57,139,84,36,40,3,84,36,44,57,214,119,38,114,29,43
db 124,36,48,139,84,36,52,137,58,247,216,131,196,12,90,89
db 91,94,95,93,195,184,1,0,0,0,235,227,184,8,0,0
db 0,235,220,184,4,0,0,0,235,213,184,5,0,0,0,235
db 206,184,6,0,0,0,235,199,144,141,180,38,0,0,0,0
end
| JosefMeixner/opentoonz | thirdparty/lzo/2.03/asm/i386/src_masm/lzo1y_s2.asm | Assembly | bsd-3-clause | 4,388 |
// Type definitions for galleria.js v1.4.2
// Project: https://github.com/aino/galleria
// Definitions by: Robert Imig <https://github.com/rimig>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module GalleriaJS {
interface GalleriaOptions {
dataSource: GalleriaEntry[];
autoplay?: boolean;
lightbox?: boolean;
}
interface GalleriaEntry {
image?: string;
thumbnail?: string;
title?: string;
description?: string;
}
interface GalleriaFactory {
run(): GalleriaFactory;
run(selector: String): GalleriaFactory;
run(selector: String, options: GalleriaOptions): GalleriaFactory;
loadTheme(url : String): GalleriaFactory;
configure(options: GalleriaOptions): GalleriaFactory;
ready( method: () => any): void;
refreshImage(): GalleriaFactory;
resize(): GalleriaFactory;
load( data: GalleriaEntry[]): GalleriaFactory;
setOptions( options: GalleriaOptions): GalleriaFactory;
}
}
declare var Galleria: GalleriaJS.GalleriaFactory; | rodzewich/playground | types/jquery-galleria/jquery-galleria.d.ts | TypeScript | mit | 1,084 |
/**
* Arabic translation (Syrian Localization, it may differ if you aren't from Syria or any Country in Middle East)
* @author Tawfek Daghistani <tawfekov@gmail.com>
* @version 2011-07-09
*/
if (elFinder && elFinder.prototype && typeof(elFinder.prototype.i18) == 'object') {
elFinder.prototype.i18.ar = {
translator : 'Tawfek Daghistani <tawfekov@gmail.com>',
language : 'العربية',
direction : 'rtl',
messages : {
/********************************** errors **********************************/
'error' : 'خطأ',
'errUnknown' : 'خطأ غير معروف .',
'errUnknownCmd' : 'أمر غير معروف .',
'errJqui' : 'إعدادات jQuery UI غير كاملة الرجاء التأكد من وجود كل من selectable, draggable and droppable',
'errNode' : '. موجود DOM إلى عنصر elFinder تحتاج ',
'errURL' : 'إعدادات خاطئة , عليك وضع الرابط ضمن الإعدادات',
'errAccess' : 'وصول مرفوض .',
'errConnect' : 'غير قادر على الاتصال بالخادم الخلفي (backend)',
'errAbort' : 'تم فصل الإتصال',
'errTimeout' : 'مهلة الإتصال قد إنتهت .',
'errNotFound' : 'الخادم الخلفي غير موجود .',
'errResponse' : 'رد غير مقبول من الخادم الخلفي',
'errConf' : 'خطأ في الإعدادات الخاصة بالخادم الخلفي ',
'errJSON' : 'الميزة PHP JSON module غير موجودة ',
'errNoVolumes' : 'لا يمكن القراءة من أي من الوسائط الموجودة ',
'errCmdParams' : 'البيانات المرسلة للأمر غير مقبولة "$1".',
'errDataNotJSON' : 'المعلومات المرسلة ليست من نوع JSON ',
'errDataEmpty' : 'لا يوجد معلومات مرسلة',
'errCmdReq' : 'الخادم الخلفي يطلب وجود اسم الأمر ',
'errOpen' : 'غير قادر على فتح "$1".',
'errNotFolder' : 'العنصر المختار ليس مجلد',
'errNotFile' : 'العنصر المختار ليس ملف',
'errRead' : 'غير قادر على القراءة "$1".',
'errWrite' : 'غير قادر على الكتابة "$1".',
'errPerm' : 'وصول مرفوض ',
'errLocked' : ' محمي و لا يمكن التعديل أو النقل أو إعادة التسمية"$1"',
'errExists' : ' موجود مسبقاً "$1"',
'errInvName' : 'الاسم مرفوض',
'errFolderNotFound' : 'المجلد غير موجود',
'errFileNotFound' : 'الملف غير موجود',
'errTrgFolderNotFound' : 'الملف الهدف "$1" غير موجود ',
'errPopup' : 'يمنعني المتصفح من إنشاء نافذة منبثقة , الرجاء تعديل الخيارات الخاصة من إعدادات المتصفح ',
'errMkdir' : ' غير قادر على إنشاء مجلد جديد "$1".',
'errMkfile' : ' غير قادر على إنشاء ملف جديد"$1".',
'errRename' : 'غير قادر على إعادة تسمية ال "$1".',
'errCopyFrom' : 'نسخ الملفات من الوسط المحدد "$1"غير مسموح.',
'errCopyTo' : 'نسخ الملفات إلى الوسط المحدد "$1" غير مسموح .',
'errUploadCommon' : 'خطأ أثناء عملية الرفع',
'errUpload' : 'غير قادر على رفع "$1".',
'errUploadNoFiles' : 'لم يتم رفع أي ملف ',
'errMaxSize' : 'حجم البيانات أكبر من الحجم المسموح به ',
'errFileMaxSize' : 'حجم الملف أكبر من الحجم المسموح به',
'errUploadMime' : 'نوع ملف غير مسموح ',
'errUploadTransfer' : '"$1" خطأ أثناء عملية النقل',
'errSave' : 'غير قادر على الحفظ في "$1".',
'errCopy' : 'غير قادر على النسخ إلى"$1".',
'errMove' : 'غير قادر على القص إلى "$1".',
'errCopyInItself' : 'غير قادر على نسخ الملف "$1" ضمن الملف نفسه.',
'errRm' : 'غير قادر على الحذف "$1".',
'errExtract' : 'غير قادر على استخراج الملفات من "$1".',
'errArchive' : 'غير قادر على إنشاء ملف مضغوط',
'errArcType' : 'نوع الملف المضغوط غير مدعومة',
'errNoArchive' : 'هذا الملف ليس ملف مضغوط أو ذو صسغة غير مدعومة ',
'errCmdNoSupport' : 'الخادم الخلفي لا يدعم هذا الأمر ',
'errReplByChild' : 'The folder “$1” can’t be replaced by an item it contains.',
'errArcSymlinks' : 'For security reason denied to unpack archives contains symlinks.',
'errArcMaxSize' : 'Archive files exceeds maximum allowed size.',
/******************************* commands names ********************************/
'cmdarchive' : 'أنشئ مجلد مضغوط',
'cmdback' : 'الخلف',
'cmdcopy' : 'نسخ',
'cmdcut' : 'قص',
'cmddownload' : 'تحميل',
'cmdduplicate' : 'تكرار',
'cmdedit' : 'تعديل الملف',
'cmdextract' : 'استخراج الملفات',
'cmdforward' : 'الأمام',
'cmdgetfile' : 'أختيار الملفات',
'cmdhelp' : 'عن هذا المشروع',
'cmdhome' : 'المجلد الرئيسي',
'cmdinfo' : 'معلومات ',
'cmdmkdir' : 'مجلد جديد',
'cmdmkfile' : 'ملف نصي جديد',
'cmdopen' : 'فتح',
'cmdpaste' : 'لصق',
'cmdquicklook' : 'معاينة',
'cmdreload' : 'إعادة تحميل',
'cmdrename' : 'إعادة تسمية',
'cmdrm' : 'حذف',
'cmdsearch' : 'بحث عن ملفات',
'cmdup' : 'تغيير المسار إلى مستوى أعلى',
'cmdupload' : 'رفع ملفات',
'cmdview' : 'عرض',
/*********************************** buttons ***********************************/
'btnClose' : 'إغلاق',
'btnSave' : 'حفظ',
'btnRm' : 'إزالة',
'btnCancel' : 'إلغاء',
'btnNo' : 'لا',
'btnYes' : 'نعم',
/******************************** notifications ********************************/
'ntfopen' : 'فتح مجلد',
'ntffile' : 'فتح ملف',
'ntfreload' : 'إعادة عرض محتويات المجلد ',
'ntfmkdir' : 'ينشئ المجلدات',
'ntfmkfile' : 'ينشئ الملفات',
'ntfrm' : 'حذف الملفات',
'ntfcopy' : 'نسخ الملفات',
'ntfmove' : 'نقل الملفات',
'ntfprepare' : 'تحضير لنسخ الملفات',
'ntfrename' : 'إعادة تسمية الملفات',
'ntfupload' : 'رفع الملفات',
'ntfdownload' : 'تحميل الملفات',
'ntfsave' : 'حفظ الملفات',
'ntfarchive' : 'ينشئ ملف مضغوط',
'ntfextract' : 'استخراج ملفات من الملف المضغوط ',
'ntfsearch' : 'يبحث عن ملفات',
'ntfsmth' : 'يحضر لشيء ما >_<',
/************************************ dates **********************************/
'dateUnknown' : 'غير معلوم',
'Today' : 'اليوم',
'Yesterday' : 'البارحة',
'Jan' : 'كانون الثاني',
'Feb' : 'شباط',
'Mar' : 'آذار',
'Apr' : 'نيسان',
'May' : 'أيار',
'Jun' : 'حزيران',
'Jul' : 'تموز',
'Aug' : 'آب',
'Sep' : 'أيلول',
'Oct' : 'تشرين الأول',
'Nov' : 'تشرين الثاني',
'Dec' : 'كانون الأول ',
/********************************** messages **********************************/
'confirmReq' : 'يرجى التأكيد',
'confirmRm' : 'هل انت متأكد من انك تريد الحذف<br/>لا يمكن التراجع عن هذه العملية ',
'confirmRepl' : 'استبدال الملف القديم بملف جديد ؟',
'apllyAll' : 'تطبيق على الكل',
'name' : 'الأسم',
'size' : 'الحجم',
'perms' : 'الصلاحيات',
'modify' : 'أخر تعديل',
'kind' : 'نوع الملف',
'read' : 'قراءة',
'write' : 'كتابة',
'noaccess' : 'وصول ممنوع',
'and' : 'و',
'unknown' : 'غير معروف',
'selectall' : 'تحديد كل الملفات',
'selectfiles' : 'تحديد ملفات',
'selectffile' : 'تحديد الملف الاول',
'selectlfile' : 'تحديد الملف الأخير',
'viewlist' : 'اعرض ك قائمة',
'viewicons' : 'اعرض ك ايقونات',
'places' : 'المواقع',
'calc' : 'حساب',
'path' : 'مسار',
'aliasfor' : 'Alias for',
'locked' : 'مقفول',
'dim' : 'الابعاد',
'files' : 'ملفات',
'folders' : 'مجلدات',
'items' : 'عناصر',
'yes' : 'نعم',
'no' : 'لا',
'link' : 'اربتاط',
'searcresult' : 'نتائج البحث',
'selected' : 'العناصر المحددة',
'about' : 'عن البرنامج',
'shortcuts' : 'الاختصارات',
'help' : 'مساعدة',
'webfm' : 'مدير ملفات الويب',
'ver' : 'رقم الإصدار',
'protocol' : 'اصدار البرتوكول',
'homepage' : 'الصفحة الرئيسية',
'docs' : 'التعليمات',
'github' : 'شاركنا بتطوير المشروع على Github',
'twitter' : 'تابعنا على تويتر',
'facebook' : 'انضم إلينا على الفيس بوك',
'team' : 'الفريق',
'chiefdev' : 'رئيس المبرمجين',
'developer' : 'مبرمح',
'contributor' : 'مبرمح',
'maintainer' : 'مشارك',
'translator' : 'مترجم',
'icons' : 'أيقونات',
'dontforget' : 'and don\'t forget to take your towel',
'shortcutsof' : 'الاختصارات غير مفعلة',
'dropFiles' : 'لصق الملفات هنا',
'or' : 'أو',
'selectForUpload' : 'اختر الملفات التي تريد رفعها',
'moveFiles' : 'قص الملفات',
'copyFiles' : 'نسخ الملفات',
'rmFromPlaces' : 'Remove from places',
'untitled folder' : 'untitled folder',
'untitled file.txt' : 'untitled file.txt',
/********************************** mimetypes **********************************/
'kindUnknown' : 'غير معروف',
'kindFolder' : 'مجلد',
'kindAlias' : 'اختصار',
'kindAliasBroken' : 'اختصار غير صالح',
// applications
'kindApp' : 'برنامج',
'kindPostscript' : 'Postscript ملف',
'kindMsOffice' : 'Microsoft Office ملف',
'kindMsWord' : 'Microsoft Word ملف',
'kindMsExcel' : 'Microsoft Excel ملف',
'kindMsPP' : 'Microsoft Powerpoint عرض تقديمي ',
'kindOO' : 'Open Office ملف',
'kindAppFlash' : 'تطبيق فلاش',
'kindPDF' : 'ملف (PDF)',
'kindTorrent' : 'Bittorrent ملف',
'kind7z' : '7z ملف',
'kindTAR' : 'TAR ملف',
'kindGZIP' : 'GZIP ملف',
'kindBZIP' : 'BZIP ملف',
'kindZIP' : 'ZIP ملف',
'kindRAR' : 'RAR ملف',
'kindJAR' : 'Java JAR ملف',
'kindTTF' : 'True Type خط ',
'kindOTF' : 'Open Type خط ',
'kindRPM' : 'RPM ملف تنصيب',
// texts
'kindText' : 'Text ملف',
'kindTextPlain' : 'مستند نصي',
'kindPHP' : 'PHP ملف نصي برمجي لـ',
'kindCSS' : 'Cascading style sheet',
'kindHTML' : 'HTML ملف',
'kindJS' : 'Javascript ملف نصي برمجي لـ',
'kindRTF' : 'Rich Text Format',
'kindC' : 'C ملف نصي برمجي لـ',
'kindCHeader' : 'C header ملف نصي برمجي لـ',
'kindCPP' : 'C++ ملف نصي برمجي لـ',
'kindCPPHeader' : 'C++ header ملف نصي برمجي لـ',
'kindShell' : 'Unix shell script',
'kindPython' : 'Python ملف نصي برمجي لـ',
'kindJava' : 'Java ملف نصي برمجي لـ',
'kindRuby' : 'Ruby ملف نصي برمجي لـ',
'kindPerl' : 'Perl script',
'kindSQL' : 'SQL ملف نصي برمجي لـ',
'kindXML' : 'XML ملف',
'kindAWK' : 'AWK ملف نصي برمجي لـ',
'kindCSV' : 'ملف CSV',
'kindDOCBOOK' : 'Docbook XML ملف',
// images
'kindصورة' : 'صورة',
'kindBMP' : 'BMP صورة',
'kindJPEG' : 'JPEG صورة',
'kindGIF' : 'GIF صورة',
'kindPNG' : 'PNG صورة',
'kindTIFF' : 'TIFF صورة',
'kindTGA' : 'TGA صورة',
'kindPSD' : 'Adobe Photoshop صورة',
'kindXBITMAP' : 'X bitmap صورة',
'kindPXM' : 'Pixelmator صورة',
// media
'kindAudio' : 'ملف صوتي',
'kindAudioMPEG' : 'MPEG ملف صوتي',
'kindAudioMPEG4' : 'MPEG-4 ملف صوتي',
'kindAudioMIDI' : 'MIDI ملف صوتي',
'kindAudioOGG' : 'Ogg Vorbis ملف صوتي',
'kindAudioWAV' : 'WAV ملف صوتي',
'AudioPlaylist' : 'MP3 قائمة تشغيل',
'kindVideo' : 'ملف فيديو',
'kindVideoDV' : 'DV ملف فيديو',
'kindVideoMPEG' : 'MPEG ملف فيديو',
'kindVideoMPEG4' : 'MPEG-4 ملف فيديو',
'kindVideoAVI' : 'AVI ملف فيديو',
'kindVideoMOV' : 'Quick Time ملف فيديو',
'kindVideoWM' : 'Windows Media ملف فيديو',
'kindVideoFlash' : 'Flash ملف فيديو',
'kindVideoMKV' : 'Matroska ملف فيديو',
'kindVideoOGG' : 'Ogg ملف فيديو'
}
}
}
| tokenly/tokenly-cms | www/themes/tokentalk/js/i18n/elfinder.ar.js | JavaScript | gpl-2.0 | 14,935 |
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Umbraco.Web.Models.ContentEditing
{
[DataContract(Name = "relation", Namespace = "")]
public class Relation
{
public Relation()
{
RelationType = new RelationType();
}
/// <summary>
/// Gets or sets the Parent Id of the Relation (Source)
/// </summary>
[DataMember(Name = "parentId")]
public int ParentId { get; set; }
/// <summary>
/// Gets or sets the Child Id of the Relation (Destination)
/// </summary>
[DataMember(Name = "childId")]
public int ChildId { get; set; }
/// <summary>
/// Gets or sets the <see cref="RelationType"/> for the Relation
/// </summary>
[DataMember(Name = "relationType", IsRequired = true)]
public RelationType RelationType { get; set; }
/// <summary>
/// Gets or sets a comment for the Relation
/// </summary>
[DataMember(Name = "comment")]
public string Comment { get; set; }
}
}
| Nicholas-Westby/Umbraco-CMS | src/Umbraco.Web/Models/ContentEditing/Relation.cs | C# | mit | 1,181 |
/* Definitions for option handling for OpenVMS.
Copyright (C) 2012-2015 Free Software Foundation, Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 3, or (at your
option) any later version.
GCC is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
#ifndef VMS_OPTS_H
#define VMS_OPTS_H
enum vms_pointer_size
{
VMS_POINTER_SIZE_NONE,
VMS_POINTER_SIZE_32,
VMS_POINTER_SIZE_64
};
#endif
| basicthinker/libptm | gcc/gcc/config/vms/vms-opts.h | C | gpl-3.0 | 921 |
/*
* multibytecodec.h: Common Multibyte Codec Implementation
*
* Written by Hye-Shik Chang <perky@FreeBSD.org>
*/
#ifndef _PYTHON_MULTIBYTECODEC_H_
#define _PYTHON_MULTIBYTECODEC_H_
#ifdef __cplusplus
extern "C" {
#endif
#ifdef uint16_t
typedef uint16_t ucs2_t, DBCHAR;
#else
typedef unsigned short ucs2_t, DBCHAR;
#endif
typedef union {
void *p;
int i;
unsigned char c[8];
ucs2_t u2[4];
Py_UCS4 u4[2];
} MultibyteCodec_State;
typedef int (*mbcodec_init)(const void *config);
typedef Py_ssize_t (*mbencode_func)(MultibyteCodec_State *state,
const void *config,
int kind, void *data,
Py_ssize_t *inpos, Py_ssize_t inlen,
unsigned char **outbuf, Py_ssize_t outleft,
int flags);
typedef int (*mbencodeinit_func)(MultibyteCodec_State *state,
const void *config);
typedef Py_ssize_t (*mbencodereset_func)(MultibyteCodec_State *state,
const void *config,
unsigned char **outbuf, Py_ssize_t outleft);
typedef Py_ssize_t (*mbdecode_func)(MultibyteCodec_State *state,
const void *config,
const unsigned char **inbuf, Py_ssize_t inleft,
_PyUnicodeWriter *writer);
typedef int (*mbdecodeinit_func)(MultibyteCodec_State *state,
const void *config);
typedef Py_ssize_t (*mbdecodereset_func)(MultibyteCodec_State *state,
const void *config);
typedef struct {
const char *encoding;
const void *config;
mbcodec_init codecinit;
mbencode_func encode;
mbencodeinit_func encinit;
mbencodereset_func encreset;
mbdecode_func decode;
mbdecodeinit_func decinit;
mbdecodereset_func decreset;
} MultibyteCodec;
typedef struct {
PyObject_HEAD
MultibyteCodec *codec;
} MultibyteCodecObject;
#define MultibyteCodec_Check(op) ((op)->ob_type == &MultibyteCodec_Type)
#define _MultibyteStatefulCodec_HEAD \
PyObject_HEAD \
MultibyteCodec *codec; \
MultibyteCodec_State state; \
PyObject *errors;
typedef struct {
_MultibyteStatefulCodec_HEAD
} MultibyteStatefulCodecContext;
#define MAXENCPENDING 2
#define _MultibyteStatefulEncoder_HEAD \
_MultibyteStatefulCodec_HEAD \
PyObject *pending;
typedef struct {
_MultibyteStatefulEncoder_HEAD
} MultibyteStatefulEncoderContext;
#define MAXDECPENDING 8
#define _MultibyteStatefulDecoder_HEAD \
_MultibyteStatefulCodec_HEAD \
unsigned char pending[MAXDECPENDING]; \
Py_ssize_t pendingsize;
typedef struct {
_MultibyteStatefulDecoder_HEAD
} MultibyteStatefulDecoderContext;
typedef struct {
_MultibyteStatefulEncoder_HEAD
} MultibyteIncrementalEncoderObject;
typedef struct {
_MultibyteStatefulDecoder_HEAD
} MultibyteIncrementalDecoderObject;
typedef struct {
_MultibyteStatefulDecoder_HEAD
PyObject *stream;
} MultibyteStreamReaderObject;
typedef struct {
_MultibyteStatefulEncoder_HEAD
PyObject *stream;
} MultibyteStreamWriterObject;
/* positive values for illegal sequences */
#define MBERR_TOOSMALL (-1) /* insufficient output buffer space */
#define MBERR_TOOFEW (-2) /* incomplete input buffer */
#define MBERR_INTERNAL (-3) /* internal runtime error */
#define MBERR_EXCEPTION (-4) /* an exception has been raised */
#define ERROR_STRICT (PyObject *)(1)
#define ERROR_IGNORE (PyObject *)(2)
#define ERROR_REPLACE (PyObject *)(3)
#define ERROR_ISCUSTOM(p) ((p) < ERROR_STRICT || ERROR_REPLACE < (p))
#define ERROR_DECREF(p) \
do { \
if (p != NULL && ERROR_ISCUSTOM(p)) \
Py_DECREF(p); \
} while (0);
#define MBENC_FLUSH 0x0001 /* encode all characters encodable */
#define MBENC_MAX MBENC_FLUSH
#define PyMultibyteCodec_CAPSULE_NAME "multibytecodec.__map_*"
#ifdef __cplusplus
}
#endif
#endif
| Kiddinglife/kidding-engine | python/Modules/cjkcodecs/multibytecodec.h | C | lgpl-3.0 | 4,288 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Upgrading from 1.7.2 to 2.0.0 : CodeIgniter User Guide</title>
<style type='text/css' media='all'>@import url('../userguide.css');</style>
<link rel='stylesheet' type='text/css' media='all' href='../userguide.css' />
<script type="text/javascript" src="../nav/nav.js"></script>
<script type="text/javascript" src="../nav/prototype.lite.js"></script>
<script type="text/javascript" src="../nav/moo.fx.js"></script>
<script type="text/javascript" src="../nav/user_guide_menu.js"></script>
<meta http-equiv='expires' content='-1' />
<meta http-equiv= 'pragma' content='no-cache' />
<meta name='robots' content='all' />
<meta name='author' content='ExpressionEngine Dev Team' />
<meta name='description' content='CodeIgniter User Guide' />
</head>
<body>
<!-- START NAVIGATION -->
<div id="nav"><div id="nav_inner"><script type="text/javascript">create_menu('../');</script></div></div>
<div id="nav2"><a name="top"></a><a href="javascript:void(0);" onclick="myHeight.toggle();"><img src="../images/nav_toggle_darker.jpg" width="154" height="43" border="0" title="Toggle Table of Contents" alt="Toggle Table of Contents" /></a></div>
<div id="masthead">
<table cellpadding="0" cellspacing="0" border="0" style="width:100%">
<tr>
<td><h1>CodeIgniter User Guide Version 2.2.1</h1></td>
<td id="breadcrumb_right"><a href="../toc.html">Table of Contents Page</a></td>
</tr>
</table>
</div>
<!-- END NAVIGATION -->
<!-- START BREADCRUMB -->
<table cellpadding="0" cellspacing="0" border="0" style="width:100%">
<tr>
<td id="breadcrumb">
<a href="http://codeigniter.com/">CodeIgniter Home</a> ›
<a href="../index.html">User Guide Home</a> ›
Upgrading from 1.7.2 to 2.0.0
</td>
<td id="searchbox"><form method="get" action="http://www.google.com/search"><input type="hidden" name="as_sitesearch" id="as_sitesearch" value="codeigniter.com/user_guide/" />Search User Guide <input type="text" class="input" style="width:200px;" name="q" id="q" size="31" maxlength="255" value="" /> <input type="submit" class="submit" name="sa" value="Go" /></form></td>
</tr>
</table>
<!-- END BREADCRUMB -->
<br clear="all" />
<!-- START CONTENT -->
<div id="content">
<h1>Upgrading from 1.7.2 to 2.0.0</h1>
<p>Before performing an update you should take your site offline by replacing the index.php file with a static one.</p>
<h2>Step 1: Update your CodeIgniter files</h2>
<p>Replace all files and directories in your "system" folder <strong>except</strong> your <kbd>application</kbd> folder.</p>
<p class="important"><strong>Note:</strong> If you have any custom developed files in these folders please make copies of them first.</p>
<h2>Step 2: Adjust get_dir_file_info() where necessary</h2>
<p>Version 2.0.0 brings a non-backwards compatible change to <kbd>get_dir_file_info()</kbd> in the <a href="../helpers/file_helper.html">File Helper</a>. Non-backwards compatible changes are extremely rare
in CodeIgniter, but this one we feel was warranted due to how easy it was to create serious server performance issues. If you <em>need</em>
recursiveness where you are using this helper function, change such instances, setting the second parameter, <kbd>$top_level_only</kbd> to FALSE:</p>
<code>get_dir_file_info('/path/to/directory', <kbd>FALSE</kbd>);</code>
</p>
<h2>Step 3: Convert your Plugins to Helpers</h2>
<p>2.0.0 gets rid of the "Plugin" system as their functionality was identical to Helpers, but non-extensible. You will need to rename your plugin files from <var>filename_pi.php</var> to <var>filename_helper.php</var>, move them to your <kbd>helpers</kbd> folder, and change all instances of:
<code>$this->load->plugin('foo');</code>
to
<code>$this->load->helper('foo');</code>
</p>
<h2>Step 4: Update stored encrypted data</h2>
<p class="important"><strong>Note:</strong> If your application does not use the Encryption library, does not store Encrypted data permanently, or is on an environment that does not support Mcrypt, you may skip this step.</p>
<p>The Encryption library has had a number of improvements, some for encryption strength and some for performance, that has an unavoidable consequence of
making it no longer possible to decode encrypted data produced by the original version of this library. To help with the transition, a new method has
been added, <kbd>encode_from_legacy()</kbd> that will decode the data with the original algorithm and return a re-encoded string using the improved methods.
This will enable you to easily replace stale encrypted data with fresh in your applications, either on the fly or en masse.</p>
<p>Please read <a href="../libraries/encryption.html#legacy">how to use this method</a> in the Encryption library documentation.</p>
<h2>Step 5: Remove loading calls for the compatibility helper.</h2>
<p>The compatibility helper has been removed from the CodeIgniter core. All methods in it should be natively available in supported PHP versions.</p>
<h2>Step 6: Update Class extension</h2>
<p>All core classes are now prefixed with <kbd>CI_</kbd>. Update Models and Controllers to extend CI_Model and CI_Controller, respectively.</p>
<h2>Step 7: Update Parent Constructor calls</h2>
<p>All native CodeIgniter classes now use the PHP 5 <kbd>__construct()</kbd> convention. Please update extended libraries to call <kbd>parent::__construct()</kbd>.</p>
<h2>Step 8: Update your user guide</h2>
<p>Please replace your local copy of the user guide with the new version, including the image files.</p>
</div>
<!-- END CONTENT -->
<div id="footer">
<p>
Previous Topic: <a href="index.html">Installation Instructions</a>
·
<a href="#top">Top of Page</a> ·
<a href="../index.html">User Guide Home</a> ·
Next Topic: <a href="troubleshooting.html">Troubleshooting</a>
</p>
<p><a href="http://codeigniter.com">CodeIgniter</a> · Copyright © 2006 - 2014 · <a href="http://ellislab.com/">EllisLab, Inc.</a> · Copyright © 2014 - 2015 · <a href="http://bcit.ca/">British Columbia Institute of Technology</a></p>
</div>
</body>
</html> | angieshates/LyonSoftProject | zResources/CodeIgniter/user_guide/installation/upgrade_200.html | HTML | apache-2.0 | 6,543 |
[![npm][npm]][npm-url]
[![node][node]][node-url]
[![deps][deps]][deps-url]
[![tests][tests]][tests-url]
[![coverage][cover]][cover-url]
[![chat][chat]][chat-url]
<div align="center">
<a href="https://github.com/webpack/webpack">
<img width="200" height="200"
src="https://cdn.rawgit.com/webpack/media/e7485eb2/logo/icon.svg">
</a>
<h1>Url Loader</h1>
</div>
<h2 align="center">Install</h2>
```bash
npm install --save-dev url-loader
```
<h2 align="center">Usage</h2>
[Documentation: Using loaders](http://webpack.github.io/docs/using-loaders.html)
The `url` loader works like the `file` loader, but can return a Data Url if the file is smaller than a byte limit.
The limit can be specified with a query parameter. (Defaults to no limit)
If the file is greater than the limit (in bytes) the [`file-loader`](https://github.com/webpack/file-loader) is used and all query parameters are passed to it.
``` javascript
require("url-loader?limit=10000!./file.png");
// => DataUrl if "file.png" is smaller than 10kb
require("url-loader?mimetype=image/png!./file.png");
// => Specify mimetype for the file (Otherwise it's inferred from extension.)
require("url-loader?prefix=img/!./file.png");
// => Parameters for the file-loader are valid too
// They are passed to the file-loader if used.
```
<h2 align="center">Contributing</h2>
Don't hesitate to create a pull request. Every contribution is appreciated. In development you can start the tests by calling `npm test`.
<h2 align="center">Maintainers</h2>
<table>
<tbody>
<tr>
<td align="center">
<img width="150" height="150"
src="https://avatars3.githubusercontent.com/u/166921?v=3&s=150">
</br>
<a href="https://github.com/bebraw">Juho Vepsäläinen</a>
</td>
<td align="center">
<img width="150" height="150"
src="https://avatars2.githubusercontent.com/u/8420490?v=3&s=150">
</br>
<a href="https://github.com/d3viant0ne">Joshua Wiens</a>
</td>
<td align="center">
<img width="150" height="150"
src="https://avatars3.githubusercontent.com/u/533616?v=3&s=150">
</br>
<a href="https://github.com/SpaceK33z">Kees Kluskens</a>
</td>
<td align="center">
<img width="150" height="150"
src="https://avatars3.githubusercontent.com/u/3408176?v=3&s=150">
</br>
<a href="https://github.com/TheLarkInn">Sean Larkin</a>
</td>
</tr>
<tbody>
</table>
[npm]: https://img.shields.io/npm/v/url-loader.svg
[npm-url]: https://npmjs.com/package/url-loader
[node]: https://img.shields.io/node/v/url-loader.svg
[node-url]: https://nodejs.org
[deps]: https://david-dm.org/webpack/url-loader.svg
[deps-url]: https://david-dm.org/webpack/url-loader
[tests]: http://img.shields.io/travis/webpack/url-loader.svg
[tests-url]: https://travis-ci.org/webpack/url-loader
[cover]: https://coveralls.io/repos/github/webpack/url-loader/badge.svg
[cover-url]: https://coveralls.io/github/webpack/url-loader
[chat]: https://badges.gitter.im/webpack/webpack.svg
[chat-url]: https://gitter.im/webpack/webpack
| puyanLiu/LPYFramework | 前端练习/autoFramework/webpack-demo3/node_modules/url-loader/README.md | Markdown | apache-2.0 | 3,239 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sync/internal_api/public/test/fake_sync_manager.h"
#include <cstddef>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/run_loop.h"
#include "base/sequenced_task_runner.h"
#include "base/single_thread_task_runner.h"
#include "base/thread_task_runner_handle.h"
#include "sync/internal_api/public/http_post_provider_factory.h"
#include "sync/internal_api/public/internal_components_factory.h"
#include "sync/internal_api/public/util/weak_handle.h"
#include "sync/syncable/directory.h"
#include "sync/test/fake_sync_encryption_handler.h"
class GURL;
namespace syncer {
FakeSyncManager::FakeSyncManager(ModelTypeSet initial_sync_ended_types,
ModelTypeSet progress_marker_types,
ModelTypeSet configure_fail_types) :
initial_sync_ended_types_(initial_sync_ended_types),
progress_marker_types_(progress_marker_types),
configure_fail_types_(configure_fail_types),
last_configure_reason_(CONFIGURE_REASON_UNKNOWN) {
fake_encryption_handler_.reset(new FakeSyncEncryptionHandler());
}
FakeSyncManager::~FakeSyncManager() {}
ModelTypeSet FakeSyncManager::GetAndResetCleanedTypes() {
ModelTypeSet cleaned_types = cleaned_types_;
cleaned_types_.Clear();
return cleaned_types;
}
ModelTypeSet FakeSyncManager::GetAndResetDownloadedTypes() {
ModelTypeSet downloaded_types = downloaded_types_;
downloaded_types_.Clear();
return downloaded_types;
}
ModelTypeSet FakeSyncManager::GetAndResetEnabledTypes() {
ModelTypeSet enabled_types = enabled_types_;
enabled_types_.Clear();
return enabled_types;
}
ConfigureReason FakeSyncManager::GetAndResetConfigureReason() {
ConfigureReason reason = last_configure_reason_;
last_configure_reason_ = CONFIGURE_REASON_UNKNOWN;
return reason;
}
void FakeSyncManager::WaitForSyncThread() {
// Post a task to |sync_task_runner_| and block until it runs.
base::RunLoop run_loop;
if (!sync_task_runner_->PostTaskAndReply(
FROM_HERE,
base::Bind(&base::DoNothing),
run_loop.QuitClosure())) {
NOTREACHED();
}
run_loop.Run();
}
void FakeSyncManager::Init(InitArgs* args) {
sync_task_runner_ = base::ThreadTaskRunnerHandle::Get();
PurgePartiallySyncedTypes();
test_user_share_.SetUp();
UserShare* share = test_user_share_.user_share();
for (ModelTypeSet::Iterator it = initial_sync_ended_types_.First();
it.Good(); it.Inc()) {
TestUserShare::CreateRoot(it.Get(), share);
}
FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
OnInitializationComplete(
WeakHandle<JsBackend>(),
WeakHandle<DataTypeDebugInfoListener>(),
true, initial_sync_ended_types_));
}
ModelTypeSet FakeSyncManager::InitialSyncEndedTypes() {
return initial_sync_ended_types_;
}
ModelTypeSet FakeSyncManager::GetTypesWithEmptyProgressMarkerToken(
ModelTypeSet types) {
ModelTypeSet empty_types = types;
empty_types.RemoveAll(progress_marker_types_);
return empty_types;
}
bool FakeSyncManager::PurgePartiallySyncedTypes() {
ModelTypeSet partial_types;
for (ModelTypeSet::Iterator i = progress_marker_types_.First();
i.Good(); i.Inc()) {
if (!initial_sync_ended_types_.Has(i.Get()))
partial_types.Put(i.Get());
}
progress_marker_types_.RemoveAll(partial_types);
cleaned_types_.PutAll(partial_types);
return true;
}
void FakeSyncManager::UpdateCredentials(const SyncCredentials& credentials) {
NOTIMPLEMENTED();
}
void FakeSyncManager::StartSyncingNormally(
const ModelSafeRoutingInfo& routing_info) {
// Do nothing.
}
void FakeSyncManager::ConfigureSyncer(
ConfigureReason reason,
ModelTypeSet to_download,
ModelTypeSet to_purge,
ModelTypeSet to_journal,
ModelTypeSet to_unapply,
const ModelSafeRoutingInfo& new_routing_info,
const base::Closure& ready_task,
const base::Closure& retry_task) {
last_configure_reason_ = reason;
enabled_types_ = GetRoutingInfoTypes(new_routing_info);
ModelTypeSet success_types = to_download;
success_types.RemoveAll(configure_fail_types_);
DVLOG(1) << "Faking configuration. Downloading: "
<< ModelTypeSetToString(success_types) << ". Cleaning: "
<< ModelTypeSetToString(to_purge);
// Update our fake directory by clearing and fake-downloading as necessary.
UserShare* share = GetUserShare();
share->directory->PurgeEntriesWithTypeIn(to_purge,
to_journal,
to_unapply);
for (ModelTypeSet::Iterator it = success_types.First(); it.Good(); it.Inc()) {
// We must be careful to not create the same root node twice.
if (!initial_sync_ended_types_.Has(it.Get())) {
TestUserShare::CreateRoot(it.Get(), share);
}
}
// Simulate cleaning up disabled types.
// TODO(sync): consider only cleaning those types that were recently disabled,
// if this isn't the first cleanup, which more accurately reflects the
// behavior of the real cleanup logic.
initial_sync_ended_types_.RemoveAll(to_purge);
progress_marker_types_.RemoveAll(to_purge);
cleaned_types_.PutAll(to_purge);
// Now simulate the actual configuration for those types that successfully
// download + apply.
progress_marker_types_.PutAll(success_types);
initial_sync_ended_types_.PutAll(success_types);
downloaded_types_.PutAll(success_types);
ready_task.Run();
}
void FakeSyncManager::AddObserver(Observer* observer) {
observers_.AddObserver(observer);
}
void FakeSyncManager::RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
SyncStatus FakeSyncManager::GetDetailedStatus() const {
NOTIMPLEMENTED();
return SyncStatus();
}
void FakeSyncManager::SaveChanges() {
// Do nothing.
}
void FakeSyncManager::ShutdownOnSyncThread(ShutdownReason reason) {
DCHECK(sync_task_runner_->RunsTasksOnCurrentThread());
test_user_share_.TearDown();
}
UserShare* FakeSyncManager::GetUserShare() {
return test_user_share_.user_share();
}
syncer::SyncContextProxy* FakeSyncManager::GetSyncContextProxy() {
return &null_sync_context_proxy_;
}
const std::string FakeSyncManager::cache_guid() {
return test_user_share_.user_share()->directory->cache_guid();
}
bool FakeSyncManager::ReceivedExperiment(Experiments* experiments) {
return false;
}
bool FakeSyncManager::HasUnsyncedItems() {
NOTIMPLEMENTED();
return false;
}
SyncEncryptionHandler* FakeSyncManager::GetEncryptionHandler() {
return fake_encryption_handler_.get();
}
ScopedVector<syncer::ProtocolEvent>
FakeSyncManager::GetBufferedProtocolEvents() {
return ScopedVector<syncer::ProtocolEvent>();
}
scoped_ptr<base::ListValue> FakeSyncManager::GetAllNodesForType(
syncer::ModelType type) {
return scoped_ptr<base::ListValue>(new base::ListValue());
}
void FakeSyncManager::RefreshTypes(ModelTypeSet types) {
last_refresh_request_types_ = types;
}
void FakeSyncManager::RegisterDirectoryTypeDebugInfoObserver(
syncer::TypeDebugInfoObserver* observer) {}
void FakeSyncManager::UnregisterDirectoryTypeDebugInfoObserver(
syncer::TypeDebugInfoObserver* observer) {}
bool FakeSyncManager::HasDirectoryTypeDebugInfoObserver(
syncer::TypeDebugInfoObserver* observer) {
return false;
}
void FakeSyncManager::RequestEmitDebugInfo() {}
void FakeSyncManager::OnIncomingInvalidation(
syncer::ModelType type,
scoped_ptr<InvalidationInterface> invalidation) {
// Do nothing.
}
ModelTypeSet FakeSyncManager::GetLastRefreshRequestTypes() {
return last_refresh_request_types_;
}
void FakeSyncManager::SetInvalidatorEnabled(bool invalidator_enabled) {
// Do nothing.
}
} // namespace syncer
| 7kbird/chrome | sync/internal_api/test/fake_sync_manager.cc | C++ | bsd-3-clause | 7,968 |
#!/bin/sh
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# This script generates a two roots - one legacy one signed with MD5, and
# another (newer) one signed with SHA1 - and has a leaf certificate signed
# by these without any distinguishers.
#
# The "cross-signed" comes from the fact that both the MD5 and SHA1 roots share
# the same Authority Key ID, Subject Key ID, Subject, and Subject Public Key
# Info. When the chain building algorithm is evaluating paths, if it prefers
# untrusted over trusted, then it will see the MD5 certificate as a self-signed
# cert that is "cross-signed" by the trusted SHA1 root.
#
# The SHA1 root should be (temporarily) trusted, and the resulting chain
# should be leaf -> SHA1root, not leaf -> MD5root, leaf -> SHA1root -> MD5root,
# or leaf -> MD5root -> SHA1root
try() {
echo "$@"
$@ || exit 1
}
try rm -rf out
try mkdir out
try echo 1 > out/2048-sha1-root-serial
try echo 2 > out/2048-md5-root-serial
touch out/2048-sha1-root-index.txt
touch out/2048-md5-root-index.txt
# Generate the key
try openssl genrsa -out out/2048-sha1-root.key 2048
# Generate the root certificate
CA_COMMON_NAME="Test Dup-Hash Root CA" \
try openssl req \
-new \
-key out/2048-sha1-root.key \
-out out/2048-sha1-root.req \
-config ca.cnf
CA_COMMON_NAME="Test Dup-Hash Root CA" \
try openssl x509 \
-req -days 3650 \
-sha1 \
-in out/2048-sha1-root.req \
-out out/2048-sha1-root.pem \
-text \
-signkey out/2048-sha1-root.key \
-extfile ca.cnf \
-extensions ca_cert
CA_COMMON_NAME="Test Dup-Hash Root CA" \
try openssl x509 \
-req -days 3650 \
-md5 \
-in out/2048-sha1-root.req \
-out out/2048-md5-root.pem \
-text \
-signkey out/2048-sha1-root.key \
-extfile ca.cnf \
-extensions ca_cert
# Generate the leaf certificate request
try openssl req \
-new \
-keyout out/ok_cert.key \
-out out/ok_cert.req \
-config ee.cnf
# Generate the leaf certificates
CA_COMMON_NAME="Test Dup-Hash Root CA" \
try openssl ca \
-batch \
-extensions user_cert \
-days 3650 \
-in out/ok_cert.req \
-out out/ok_cert.pem \
-config ca.cnf
try openssl x509 -text \
-in out/2048-md5-root.pem \
-out ../certificates/cross-signed-root-md5.pem
try openssl x509 -text \
-in out/2048-sha1-root.pem \
-out ../certificates/cross-signed-root-sha1.pem
try openssl x509 -text \
-in out/ok_cert.pem \
-out ../certificates/cross-signed-leaf.pem
| GeyerA/android_external_chromium_org | net/data/ssl/scripts/generate-cross-signed-certs.sh | Shell | bsd-3-clause | 2,586 |
/*
* arch/sh/kernel/cpu/sh4a/clock-sh7723.c
*
* SH7723 clock framework support
*
* Copyright (C) 2009 Magnus Damm
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/io.h>
#include <linux/clk.h>
#include <linux/clkdev.h>
#include <asm/clock.h>
#include <asm/hwblk.h>
#include <cpu/sh7723.h>
/* SH7723 registers */
#define FRQCR 0xa4150000
#define VCLKCR 0xa4150004
#define SCLKACR 0xa4150008
#define SCLKBCR 0xa415000c
#define IRDACLKCR 0xa4150018
#define PLLCR 0xa4150024
#define DLLFRQ 0xa4150050
/* Fixed 32 KHz root clock for RTC and Power Management purposes */
static struct clk r_clk = {
.rate = 32768,
};
/*
* Default rate for the root input clock, reset this with clk_set_rate()
* from the platform code.
*/
struct clk extal_clk = {
.rate = 33333333,
};
/* The dll multiplies the 32khz r_clk, may be used instead of extal */
static unsigned long dll_recalc(struct clk *clk)
{
unsigned long mult;
if (__raw_readl(PLLCR) & 0x1000)
mult = __raw_readl(DLLFRQ);
else
mult = 0;
return clk->parent->rate * mult;
}
static struct clk_ops dll_clk_ops = {
.recalc = dll_recalc,
};
static struct clk dll_clk = {
.ops = &dll_clk_ops,
.parent = &r_clk,
.flags = CLK_ENABLE_ON_INIT,
};
static unsigned long pll_recalc(struct clk *clk)
{
unsigned long mult = 1;
unsigned long div = 1;
if (__raw_readl(PLLCR) & 0x4000)
mult = (((__raw_readl(FRQCR) >> 24) & 0x1f) + 1);
else
div = 2;
return (clk->parent->rate * mult) / div;
}
static struct clk_ops pll_clk_ops = {
.recalc = pll_recalc,
};
static struct clk pll_clk = {
.ops = &pll_clk_ops,
.flags = CLK_ENABLE_ON_INIT,
};
struct clk *main_clks[] = {
&r_clk,
&extal_clk,
&dll_clk,
&pll_clk,
};
static int multipliers[] = { 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
static int divisors[] = { 1, 3, 2, 5, 3, 4, 5, 6, 8, 10, 12, 16, 20 };
static struct clk_div_mult_table div4_div_mult_table = {
.divisors = divisors,
.nr_divisors = ARRAY_SIZE(divisors),
.multipliers = multipliers,
.nr_multipliers = ARRAY_SIZE(multipliers),
};
static struct clk_div4_table div4_table = {
.div_mult_table = &div4_div_mult_table,
};
enum { DIV4_I, DIV4_U, DIV4_SH, DIV4_B, DIV4_B3, DIV4_P, DIV4_NR };
#define DIV4(_reg, _bit, _mask, _flags) \
SH_CLK_DIV4(&pll_clk, _reg, _bit, _mask, _flags)
struct clk div4_clks[DIV4_NR] = {
[DIV4_I] = DIV4(FRQCR, 20, 0x0dbf, CLK_ENABLE_ON_INIT),
[DIV4_U] = DIV4(FRQCR, 16, 0x0dbf, CLK_ENABLE_ON_INIT),
[DIV4_SH] = DIV4(FRQCR, 12, 0x0dbf, CLK_ENABLE_ON_INIT),
[DIV4_B] = DIV4(FRQCR, 8, 0x0dbf, CLK_ENABLE_ON_INIT),
[DIV4_B3] = DIV4(FRQCR, 4, 0x0db4, CLK_ENABLE_ON_INIT),
[DIV4_P] = DIV4(FRQCR, 0, 0x0dbf, 0),
};
enum { DIV4_IRDA, DIV4_ENABLE_NR };
struct clk div4_enable_clks[DIV4_ENABLE_NR] = {
[DIV4_IRDA] = DIV4(IRDACLKCR, 0, 0x0dbf, 0),
};
enum { DIV4_SIUA, DIV4_SIUB, DIV4_REPARENT_NR };
struct clk div4_reparent_clks[DIV4_REPARENT_NR] = {
[DIV4_SIUA] = DIV4(SCLKACR, 0, 0x0dbf, 0),
[DIV4_SIUB] = DIV4(SCLKBCR, 0, 0x0dbf, 0),
};
enum { DIV6_V, DIV6_NR };
struct clk div6_clks[DIV6_NR] = {
[DIV6_V] = SH_CLK_DIV6(&pll_clk, VCLKCR, 0),
};
static struct clk mstp_clks[] = {
/* See page 60 of Datasheet V1.0: Overview -> Block Diagram */
SH_HWBLK_CLK(HWBLK_TLB, &div4_clks[DIV4_I], CLK_ENABLE_ON_INIT),
SH_HWBLK_CLK(HWBLK_IC, &div4_clks[DIV4_I], CLK_ENABLE_ON_INIT),
SH_HWBLK_CLK(HWBLK_OC, &div4_clks[DIV4_I], CLK_ENABLE_ON_INIT),
SH_HWBLK_CLK(HWBLK_L2C, &div4_clks[DIV4_SH], CLK_ENABLE_ON_INIT),
SH_HWBLK_CLK(HWBLK_ILMEM, &div4_clks[DIV4_I], CLK_ENABLE_ON_INIT),
SH_HWBLK_CLK(HWBLK_FPU, &div4_clks[DIV4_I], CLK_ENABLE_ON_INIT),
SH_HWBLK_CLK(HWBLK_INTC, &div4_clks[DIV4_I], CLK_ENABLE_ON_INIT),
SH_HWBLK_CLK(HWBLK_DMAC0, &div4_clks[DIV4_B], 0),
SH_HWBLK_CLK(HWBLK_SHYWAY, &div4_clks[DIV4_SH], CLK_ENABLE_ON_INIT),
SH_HWBLK_CLK(HWBLK_HUDI, &div4_clks[DIV4_P], 0),
SH_HWBLK_CLK(HWBLK_UBC, &div4_clks[DIV4_I], 0),
SH_HWBLK_CLK(HWBLK_TMU0, &div4_clks[DIV4_P], 0),
SH_HWBLK_CLK(HWBLK_CMT, &r_clk, 0),
SH_HWBLK_CLK(HWBLK_RWDT, &r_clk, 0),
SH_HWBLK_CLK(HWBLK_DMAC1, &div4_clks[DIV4_B], 0),
SH_HWBLK_CLK(HWBLK_TMU1, &div4_clks[DIV4_P], 0),
SH_HWBLK_CLK(HWBLK_FLCTL, &div4_clks[DIV4_P], 0),
SH_HWBLK_CLK(HWBLK_SCIF0, &div4_clks[DIV4_P], 0),
SH_HWBLK_CLK(HWBLK_SCIF1, &div4_clks[DIV4_P], 0),
SH_HWBLK_CLK(HWBLK_SCIF2, &div4_clks[DIV4_P], 0),
SH_HWBLK_CLK(HWBLK_SCIF3, &div4_clks[DIV4_B], 0),
SH_HWBLK_CLK(HWBLK_SCIF4, &div4_clks[DIV4_B], 0),
SH_HWBLK_CLK(HWBLK_SCIF5, &div4_clks[DIV4_B], 0),
SH_HWBLK_CLK(HWBLK_MSIOF0, &div4_clks[DIV4_B], 0),
SH_HWBLK_CLK(HWBLK_MSIOF1, &div4_clks[DIV4_B], 0),
SH_HWBLK_CLK(HWBLK_MERAM, &div4_clks[DIV4_SH], 0),
SH_HWBLK_CLK(HWBLK_IIC, &div4_clks[DIV4_P], 0),
SH_HWBLK_CLK(HWBLK_RTC, &r_clk, 0),
SH_HWBLK_CLK(HWBLK_ATAPI, &div4_clks[DIV4_SH], 0),
SH_HWBLK_CLK(HWBLK_ADC, &div4_clks[DIV4_P], 0),
SH_HWBLK_CLK(HWBLK_TPU, &div4_clks[DIV4_B], 0),
SH_HWBLK_CLK(HWBLK_IRDA, &div4_clks[DIV4_P], 0),
SH_HWBLK_CLK(HWBLK_TSIF, &div4_clks[DIV4_B], 0),
SH_HWBLK_CLK(HWBLK_ICB, &div4_clks[DIV4_B], CLK_ENABLE_ON_INIT),
SH_HWBLK_CLK(HWBLK_SDHI0, &div4_clks[DIV4_B], 0),
SH_HWBLK_CLK(HWBLK_SDHI1, &div4_clks[DIV4_B], 0),
SH_HWBLK_CLK(HWBLK_KEYSC, &r_clk, 0),
SH_HWBLK_CLK(HWBLK_USB, &div4_clks[DIV4_B], 0),
SH_HWBLK_CLK(HWBLK_2DG, &div4_clks[DIV4_B], 0),
SH_HWBLK_CLK(HWBLK_SIU, &div4_clks[DIV4_B], 0),
SH_HWBLK_CLK(HWBLK_VEU2H1, &div4_clks[DIV4_B], 0),
SH_HWBLK_CLK(HWBLK_VOU, &div4_clks[DIV4_B], 0),
SH_HWBLK_CLK(HWBLK_BEU, &div4_clks[DIV4_B], 0),
SH_HWBLK_CLK(HWBLK_CEU, &div4_clks[DIV4_B], 0),
SH_HWBLK_CLK(HWBLK_VEU2H0, &div4_clks[DIV4_B], 0),
SH_HWBLK_CLK(HWBLK_VPU, &div4_clks[DIV4_B], 0),
SH_HWBLK_CLK(HWBLK_LCDC, &div4_clks[DIV4_B], 0),
};
static struct clk_lookup lookups[] = {
/* main clocks */
CLKDEV_CON_ID("rclk", &r_clk),
CLKDEV_CON_ID("extal", &extal_clk),
CLKDEV_CON_ID("dll_clk", &dll_clk),
CLKDEV_CON_ID("pll_clk", &pll_clk),
/* DIV4 clocks */
CLKDEV_CON_ID("cpu_clk", &div4_clks[DIV4_I]),
CLKDEV_CON_ID("umem_clk", &div4_clks[DIV4_U]),
CLKDEV_CON_ID("shyway_clk", &div4_clks[DIV4_SH]),
CLKDEV_CON_ID("bus_clk", &div4_clks[DIV4_B]),
CLKDEV_CON_ID("b3_clk", &div4_clks[DIV4_B3]),
CLKDEV_CON_ID("peripheral_clk", &div4_clks[DIV4_P]),
CLKDEV_CON_ID("irda_clk", &div4_enable_clks[DIV4_IRDA]),
CLKDEV_CON_ID("siua_clk", &div4_reparent_clks[DIV4_SIUA]),
CLKDEV_CON_ID("siub_clk", &div4_reparent_clks[DIV4_SIUB]),
/* DIV6 clocks */
CLKDEV_CON_ID("video_clk", &div6_clks[DIV6_V]),
/* MSTP clocks */
CLKDEV_CON_ID("tlb0", &mstp_clks[HWBLK_TLB]),
CLKDEV_CON_ID("ic0", &mstp_clks[HWBLK_IC]),
CLKDEV_CON_ID("oc0", &mstp_clks[HWBLK_OC]),
CLKDEV_CON_ID("l2c0", &mstp_clks[HWBLK_L2C]),
CLKDEV_CON_ID("ilmem0", &mstp_clks[HWBLK_ILMEM]),
CLKDEV_CON_ID("fpu0", &mstp_clks[HWBLK_FPU]),
CLKDEV_CON_ID("intc0", &mstp_clks[HWBLK_INTC]),
CLKDEV_CON_ID("dmac0", &mstp_clks[HWBLK_DMAC0]),
CLKDEV_CON_ID("sh0", &mstp_clks[HWBLK_SHYWAY]),
CLKDEV_CON_ID("hudi0", &mstp_clks[HWBLK_HUDI]),
CLKDEV_CON_ID("ubc0", &mstp_clks[HWBLK_UBC]),
{
/* TMU0 */
.dev_id = "sh_tmu.0",
.con_id = "tmu_fck",
.clk = &mstp_clks[HWBLK_TMU0],
}, {
/* TMU1 */
.dev_id = "sh_tmu.1",
.con_id = "tmu_fck",
.clk = &mstp_clks[HWBLK_TMU0],
}, {
/* TMU2 */
.dev_id = "sh_tmu.2",
.con_id = "tmu_fck",
.clk = &mstp_clks[HWBLK_TMU0],
},
CLKDEV_CON_ID("cmt_fck", &mstp_clks[HWBLK_CMT]),
CLKDEV_CON_ID("rwdt0", &mstp_clks[HWBLK_RWDT]),
CLKDEV_CON_ID("dmac1", &mstp_clks[HWBLK_DMAC1]),
{
/* TMU3 */
.dev_id = "sh_tmu.3",
.con_id = "tmu_fck",
.clk = &mstp_clks[HWBLK_TMU1],
}, {
/* TMU4 */
.dev_id = "sh_tmu.4",
.con_id = "tmu_fck",
.clk = &mstp_clks[HWBLK_TMU1],
}, {
/* TMU5 */
.dev_id = "sh_tmu.5",
.con_id = "tmu_fck",
.clk = &mstp_clks[HWBLK_TMU1],
},
CLKDEV_CON_ID("flctl0", &mstp_clks[HWBLK_FLCTL]),
{
/* SCIF0 */
.dev_id = "sh-sci.0",
.con_id = "sci_fck",
.clk = &mstp_clks[HWBLK_SCIF0],
}, {
/* SCIF1 */
.dev_id = "sh-sci.1",
.con_id = "sci_fck",
.clk = &mstp_clks[HWBLK_SCIF1],
}, {
/* SCIF2 */
.dev_id = "sh-sci.2",
.con_id = "sci_fck",
.clk = &mstp_clks[HWBLK_SCIF2],
}, {
/* SCIF3 */
.dev_id = "sh-sci.3",
.con_id = "sci_fck",
.clk = &mstp_clks[HWBLK_SCIF3],
}, {
/* SCIF4 */
.dev_id = "sh-sci.4",
.con_id = "sci_fck",
.clk = &mstp_clks[HWBLK_SCIF4],
}, {
/* SCIF5 */
.dev_id = "sh-sci.5",
.con_id = "sci_fck",
.clk = &mstp_clks[HWBLK_SCIF5],
},
CLKDEV_CON_ID("msiof0", &mstp_clks[HWBLK_MSIOF0]),
CLKDEV_CON_ID("msiof1", &mstp_clks[HWBLK_MSIOF1]),
CLKDEV_CON_ID("meram0", &mstp_clks[HWBLK_MERAM]),
CLKDEV_DEV_ID("i2c-sh_mobile.0", &mstp_clks[HWBLK_IIC]),
CLKDEV_CON_ID("rtc0", &mstp_clks[HWBLK_RTC]),
CLKDEV_CON_ID("atapi0", &mstp_clks[HWBLK_ATAPI]),
CLKDEV_CON_ID("adc0", &mstp_clks[HWBLK_ADC]),
CLKDEV_CON_ID("tpu0", &mstp_clks[HWBLK_TPU]),
CLKDEV_CON_ID("irda0", &mstp_clks[HWBLK_IRDA]),
CLKDEV_CON_ID("tsif0", &mstp_clks[HWBLK_TSIF]),
CLKDEV_CON_ID("icb0", &mstp_clks[HWBLK_ICB]),
CLKDEV_CON_ID("sdhi0", &mstp_clks[HWBLK_SDHI0]),
CLKDEV_CON_ID("sdhi1", &mstp_clks[HWBLK_SDHI1]),
CLKDEV_CON_ID("keysc0", &mstp_clks[HWBLK_KEYSC]),
CLKDEV_CON_ID("usb0", &mstp_clks[HWBLK_USB]),
CLKDEV_CON_ID("2dg0", &mstp_clks[HWBLK_2DG]),
CLKDEV_CON_ID("siu0", &mstp_clks[HWBLK_SIU]),
CLKDEV_CON_ID("veu1", &mstp_clks[HWBLK_VEU2H1]),
CLKDEV_CON_ID("vou0", &mstp_clks[HWBLK_VOU]),
CLKDEV_CON_ID("beu0", &mstp_clks[HWBLK_BEU]),
CLKDEV_CON_ID("ceu0", &mstp_clks[HWBLK_CEU]),
CLKDEV_CON_ID("veu0", &mstp_clks[HWBLK_VEU2H0]),
CLKDEV_CON_ID("vpu0", &mstp_clks[HWBLK_VPU]),
CLKDEV_CON_ID("lcdc0", &mstp_clks[HWBLK_LCDC]),
};
int __init arch_clk_init(void)
{
int k, ret = 0;
/* autodetect extal or dll configuration */
if (__raw_readl(PLLCR) & 0x1000)
pll_clk.parent = &dll_clk;
else
pll_clk.parent = &extal_clk;
for (k = 0; !ret && (k < ARRAY_SIZE(main_clks)); k++)
ret |= clk_register(main_clks[k]);
clkdev_add_table(lookups, ARRAY_SIZE(lookups));
if (!ret)
ret = sh_clk_div4_register(div4_clks, DIV4_NR, &div4_table);
if (!ret)
ret = sh_clk_div4_enable_register(div4_enable_clks,
DIV4_ENABLE_NR, &div4_table);
if (!ret)
ret = sh_clk_div4_reparent_register(div4_reparent_clks,
DIV4_REPARENT_NR, &div4_table);
if (!ret)
ret = sh_clk_div6_register(div6_clks, DIV6_NR);
if (!ret)
ret = sh_hwblk_clk_register(mstp_clks, HWBLK_NR);
return ret;
}
| WhiteBearSolutions/WBSAirback | packages/wbsairback-kernel-image/wbsairback-kernel-image-3.2.43/arch/sh/kernel/cpu/sh4a/clock-sh7723.c | C | apache-2.0 | 11,054 |
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v4.1.5
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var context_1 = require("./context/context");
var rowNode_1 = require("./entities/rowNode");
var renderedRow_1 = require("./rendering/renderedRow");
var utils_1 = require('./utils');
var SelectionRendererFactory = (function () {
function SelectionRendererFactory() {
}
SelectionRendererFactory.prototype.createSelectionCheckbox = function (rowNode, addRenderedRowEventListener) {
var eCheckbox = document.createElement('input');
eCheckbox.type = "checkbox";
eCheckbox.name = "name";
eCheckbox.className = 'ag-selection-checkbox';
utils_1.Utils.setCheckboxState(eCheckbox, rowNode.isSelected());
eCheckbox.addEventListener('click', function (event) { return event.stopPropagation(); });
eCheckbox.addEventListener('change', function () {
var newValue = eCheckbox.checked;
if (newValue) {
rowNode.setSelected(newValue);
}
else {
rowNode.setSelected(newValue);
}
});
var selectionChangedCallback = function () { return utils_1.Utils.setCheckboxState(eCheckbox, rowNode.isSelected()); };
rowNode.addEventListener(rowNode_1.RowNode.EVENT_ROW_SELECTED, selectionChangedCallback);
addRenderedRowEventListener(renderedRow_1.RenderedRow.EVENT_RENDERED_ROW_REMOVED, function () {
rowNode.removeEventListener(rowNode_1.RowNode.EVENT_ROW_SELECTED, selectionChangedCallback);
});
return eCheckbox;
};
SelectionRendererFactory = __decorate([
context_1.Bean('selectionRendererFactory'),
__metadata('design:paramtypes', [])
], SelectionRendererFactory);
return SelectionRendererFactory;
})();
exports.SelectionRendererFactory = SelectionRendererFactory;
| Eurofunk/ag-grid | dist/lib/selectionRendererFactory.js | JavaScript | mit | 2,720 |
/* Spellbook Class Extension */
if (!Array.prototype.remove) {
Array.prototype.remove = function (obj) {
var self = this;
if (typeof obj !== "object" && !obj instanceof Array) {
obj = [obj];
}
return self.filter(function(e){
if(obj.indexOf(e)<0) {
return e
}
});
};
}
if (!Array.prototype.clear) {
Array.prototype.clear = function() {
this.splice(0, this.length);
};
}
if (!Array.prototype.random) {
Array.prototype.random = function() {
self = this;
var index = Math.floor(Math.random() * (this.length));
return self[index];
};
}
if (!Array.prototype.shuffle) {
Array.prototype.shuffle = function() {
var input = this;
for (var i = input.length-1; i >=0; i--) {
var randomIndex = Math.floor(Math.random()*(i+1));
var itemAtIndex = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
return input;
}
}
if (!Array.prototype.first) {
Array.prototype.first = function() {
return this[0];
}
}
if (!Array.prototype.last) {
Array.prototype.last = function() {
return this[this.length - 1];
}
}
if (!Array.prototype.inArray) {
Array.prototype.inArray = function (value) {
return !!~this.indexOf(value);
};
}
if (!Array.prototype.contains) {
Array.prototype.contains = function (value) {
return !!~this.indexOf(value);
};
}
if (!Array.prototype.each) {
Array.prototype.each = function (interval, callback, response) {
var self = this;
var i = 0;
if (typeof interval !== "function" ) {
var inter = setInterval(function () {
callback(self[i], i);
i++;
if (i === self.length) {
clearInterval(inter);
if (typeof response === "function") response();
}
}, interval);
} else {
for (var i = 0; i < self.length; i++) {
interval(self[i], i);
if (typeof callback === "function") {
if (i === self.length - 1) callback();
}
}
}
}
}
if (!Array.prototype.eachEnd) {
Array.prototype.eachEnd = function (callback, response) {
var self = this;
var i = 0;
var done = function () {
if (i < self.length -1) {
i++;
callback(self[i], i, done);
} else {
if (typeof response === 'function') {
response();
}
}
}
callback(self[i], i, done);
}
}
if (!Object.prototype.extend) {
Object.prototype.extend = function(obj) {
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
this[i] = obj[i];
};
};
};
}
if (!Object.prototype.remove) {
Object.prototype.remove = function(keys) {
var self = this;
if (typeof obj === "object" && obj instanceof Array) {
arr.forEach(function(key){
delete(self[key]);
});
} else {
delete(self[keys]);
};
};
}
if (!Object.prototype.getKeys) {
Object.prototype.getKeys = function(keys) {
var self = this;
if (typeof obj === "object" && obj instanceof Array) {
var obj = {};
keys.forEach(function(key){
obj[key] = self[key];
});
} else {
obj[keys] = self[keys];
}
return obj;
};
}
if (!String.prototype.repeatify) {
String.prototype.repeatify = function(num) {
var strArray = [];
for (var i = 0; i < num; i++) {
strArray.push(this.normalize());
}
return strArray;
};
}
if (!Number.prototype.times) {
Number.prototype.times = function (callback) {
if (this % 1 === 0)
for (var i = 0; i < this; i++) {
callback()
}
};
}
if (!Number.prototype.isInteger) {
Number.prototype.isInteger = function () {
this.isInteger = function (num) {
return num % 1 === 0;
}
}
}
if (!Array.prototype.isArray) {
this.isArray = function () {
return typeof this === "object" && this instanceof Array;
};
}
if (!Function.prototype.isFunction) {
this.isFunction = function () {
return typeof this === 'function';
};
}
if (!Object.prototype.isObject) {
this.isObject = function () {
return typeof this === "object" && (isArray(this) === false );
};
}
if (!String.prototype.isString) {
this.isString = function () {
return typeof this === "string" || this instanceof String;
};
}
if (!Boolean.prototype.isBoolean) {
this.isBoolean = function () {
return typeof this === "boolean";
};
}
/* Spellbook Utils */
var Spellbook = function () {
this.test = function () {
return "Testing Spellbook";
};
this.range = function(a, b, step) {
var A= [];
if(typeof a == 'number'){
A[0]= a;
step = step || 1;
while(a+step<= b) {
A[A.length]= a+= step;
}
} else {
var s = 'abcdefghijklmnopqrstuvwxyz';
if(a=== a.toUpperCase()) {
b=b.toUpperCase();
s= s.toUpperCase();
}
s= s.substring(s.indexOf(a), s.indexOf(b)+ 1);
A= s.split('');
}
return A;
};
this.isFunction = function (fn) {
return typeof fn === 'function';
};
this.isArray = function (obj) {
return typeof obj === "object" && obj instanceof Array;
};
this.isObject = function (obj) {
return typeof obj === "object" && (isArray(obj) === false );
};
this.isNumber = function (obj) {
return typeof obj === "number" || obj instanceof Number;
};
this.isString = function (obj ) {
return typeof obj === "string" || obj instanceof String;
};
this.isBoolean = function (obj) {
return typeof obj === "boolean";
};
this.isInteger = function (obj) {
return obj % 1 === 0;
}
this.random = function (min, max) {
if (typeof min === "number" && typeof max === "number") {
return Math.floor(Math.random() * (max - min)) + min;
} else {
return 0;
}
};
this.clone = function (obj) {
if(obj === null || typeof(obj) !== 'object' || 'isActiveClone' in obj)
return obj;
var temp = obj.constructor();
for(var key in obj) {
if(Object.prototype.hasOwnProperty.call(obj, key)) {
obj['isActiveClone'] = null;
temp[key] = clone(obj[key]);
delete obj['isActiveClone'];
}
}
return temp;
};
this.assign = function (obj) {
return this.clone(obj);
};
this.remove = function (array, obj) {
if (typeof obj !== "object" && !obj instanceof Array) {
obj = [obj];
}
return array.filter(function(e){
if(obj.indexOf(e)<0) {
return e
}
});
};
this.clear = function (array) {
array.splice(0, array.length);
};
this.inArray = function (a, b) {
return !!~a.indexOf(b);
};
this.contains = function (a, b) {
return !!~a.indexOf(b);
};
this.times = function (number, callback) {
if (typeof number === 'number' && number > 0) {
if ( typeof callback === 'function') {
for (var i = 0; i < number; i++) {
callback();
}
}
}
};
this.each = function (array, interval, callback, response) {
var i = 0;
if (typeof interval !== "function" ) {
var inter = setInterval(function () {
callback(array[i], i);
i++;
if (i === array.length) {
clearInterval(inter);
if (typeof response === "function") response();
}
}, interval);
} else {
for (var i = 0; i < array.length; i++) {
interval(array[i], i);
if (typeof callback === "function") {
if (i === array.length - 1) callback();
}
}
}
}
this.eachEnd = function (array, callback, response) {
var i = 0;
var done = function () {
if (i < array.length -1) {
i++;
callback(array[i], i, done);
} else {
if (typeof response === 'function') {
response();
}
}
}
callback(array[i], i, done);
}
this.checkDate = function (value, userFormat) {
userFormat = userFormat || 'mm/dd/yyyy';
var delimiter = /[^mdy]/.exec(userFormat)[0];
var theFormat = userFormat.split(delimiter);
var theDate = value.split(delimiter);
function isDate(date, format) {
var m, d, y, i = 0, len = format.length, f;
for (i; i < len; i++) {
f = format[i];
if (/m/.test(f)) m = date[i];
if (/d/.test(f)) d = date[i];
if (/y/.test(f)) y = date[i];
}
return (
m > 0 && m < 13 &&
y && y.length === 4 &&
d > 0 &&
d <= (new Date(y, m, 0)).getDate()
);
};
return isDate(theDate, theFormat);
};
this.excerpt = function (str, nwords) {
var words = str.split(' ');
words.splice(nwords, words.length-1);
return words.join(' ');
}
};
if (typeof process === 'object') {
module.exports = new Spellbook;
} else {
Spellbook.prototype.get = function (url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', encodeURI(url));
xhr.onload = function() {
if (xhr.status === 200) {
callback(false, xhr.responseText);
} else {
callback("Request failed. Returned status of " + status);
}
};
xhr.send();
}
Spellbook.prototype.post = function (url, data, header, callback) {
function param(object) {
var encodedString = '';
for (var prop in object) {
if (object.hasOwnProperty(prop)) {
if (encodedString.length > 0) {
encodedString += '&';
}
encodedString += encodeURI(prop + '=' + object[prop]);
}
}
return encodedString;
}
if (typeof header === "function") {
callback = header;
header = "application/json";
var finaldata = JSON.stringify(data);
} else {
var finaldata = param(data);
}
xhr = new XMLHttpRequest();
xhr.open('POST', encodeURI(url));
xhr.setRequestHeader('Content-Type', header);
xhr.onload = function() {
if (xhr.status === 200 && xhr.responseText !== undefined) {
callback(null, xhr.responseText);
} else if (xhr.status !== 200) {
callback('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send(finaldata);
}
var sb = new Spellbook();
}
| viskin/cdnjs | ajax/libs/spellbook/0.0.28/spellbook.js | JavaScript | mit | 9,757 |
#include "ex14_49.h"
int main()
{
Date date(12, 4, 2015);
if (static_cast<bool>(date))
std::cout << date << std::endl;
}
| wy7980/Cpp-Primer | ch14/ex14_49_TEST.cpp | C++ | cc0-1.0 | 138 |
#
# Copyright (c) 2004, 2012, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
# @test
# @bug 4990825
# @run shell jstatLineCounts2.sh
# @summary Test that output of 'jstat -gcutil 0' has expected line counts
. ${TESTSRC-.}/../../jvmstat/testlibrary/utils.sh
setup
verify_os
JSTAT="${TESTJAVA}/bin/jstat"
${JSTAT} -J-XX:+UsePerfData -J-Duser.language=en -gcutil 0 2>&1 | awk -f ${TESTSRC}/lineCounts2.awk
| stain/jdk8u | test/sun/tools/jstat/jstatLineCounts2.sh | Shell | gpl-2.0 | 1,365 |
/*
*
* Copyright 2018 gRPC authors.
*
* 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.
*
*/
package grpc
// Version is the current grpc version.
const Version = "1.38.0"
| thaJeztah/cli | vendor/google.golang.org/grpc/version.go | GO | apache-2.0 | 683 |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*
*/
/* jslint sloppy:true */
/* global Windows:true, setImmediate */
var cordova = require('cordova'),
urlutil = require('cordova/urlutil');
var browserWrap,
popup,
navigationButtonsDiv,
navigationButtonsDivInner,
backButton,
forwardButton,
closeButton,
bodyOverflowStyle,
navigationEventsCallback;
// x-ms-webview is available starting from Windows 8.1 (platformId is 'windows')
// http://msdn.microsoft.com/en-us/library/windows/apps/dn301831.aspx
var isWebViewAvailable = cordova.platformId === 'windows';
function attachNavigationEvents(element, callback) {
if (isWebViewAvailable) {
element.addEventListener("MSWebViewNavigationStarting", function (e) {
callback({ type: "loadstart", url: e.uri}, {keepCallback: true} );
});
element.addEventListener("MSWebViewNavigationCompleted", function (e) {
if (e.isSuccess) {
callback({ type: "loadstop", url: e.uri }, { keepCallback: true });
} else {
callback({ type: "loaderror", url: e.uri, code: e.webErrorStatus, message: "Navigation failed with error code " + e.webErrorStatus}, { keepCallback: true });
}
});
element.addEventListener("MSWebViewUnviewableContentIdentified", function (e) {
// WebView found the content to be not HTML.
// http://msdn.microsoft.com/en-us/library/windows/apps/dn609716.aspx
callback({ type: "loaderror", url: e.uri, code: e.webErrorStatus, message: "Navigation failed with error code " + e.webErrorStatus}, { keepCallback: true });
});
element.addEventListener("MSWebViewContentLoading", function (e) {
if (navigationButtonsDiv && popup) {
if (popup.canGoBack) {
backButton.removeAttribute("disabled");
} else {
backButton.setAttribute("disabled", "true");
}
if (popup.canGoForward) {
forwardButton.removeAttribute("disabled");
} else {
forwardButton.setAttribute("disabled", "true");
}
}
});
} else {
var onError = function () {
callback({ type: "loaderror", url: this.contentWindow.location}, {keepCallback: true});
};
element.addEventListener("unload", function () {
callback({ type: "loadstart", url: this.contentWindow.location}, {keepCallback: true});
});
element.addEventListener("load", function () {
callback({ type: "loadstop", url: this.contentWindow.location}, {keepCallback: true});
});
element.addEventListener("error", onError);
element.addEventListener("abort", onError);
}
}
var IAB = {
close: function (win, lose) {
setImmediate(function () {
if (browserWrap) {
if (navigationEventsCallback) {
navigationEventsCallback({ type: "exit" });
}
browserWrap.parentNode.removeChild(browserWrap);
// Reset body overflow style to initial value
document.body.style.msOverflowStyle = bodyOverflowStyle;
browserWrap = null;
popup = null;
}
});
},
show: function (win, lose) {
setImmediate(function () {
if (browserWrap) {
browserWrap.style.display = "block";
}
});
},
open: function (win, lose, args) {
// make function async so that we can add navigation events handlers before view is loaded and navigation occured
setImmediate(function () {
var strUrl = args[0],
target = args[1],
features = args[2],
url;
navigationEventsCallback = win;
if (target === "_system") {
url = new Windows.Foundation.Uri(strUrl);
Windows.System.Launcher.launchUriAsync(url);
} else if (target === "_self" || !target) {
window.location = strUrl;
} else {
// "_blank" or anything else
if (!browserWrap) {
var browserWrapStyle = document.createElement('link');
browserWrapStyle.rel = "stylesheet";
browserWrapStyle.type = "text/css";
browserWrapStyle.href = urlutil.makeAbsolute("/www/css/inappbrowser.css");
document.head.appendChild(browserWrapStyle);
browserWrap = document.createElement("div");
browserWrap.className = "inAppBrowserWrap";
if (features.indexOf("fullscreen=yes") > -1) {
browserWrap.classList.add("inAppBrowserWrapFullscreen");
}
// Save body overflow style to be able to reset it back later
bodyOverflowStyle = document.body.style.msOverflowStyle;
browserWrap.onclick = function () {
setTimeout(function () {
IAB.close(navigationEventsCallback);
}, 0);
};
document.body.appendChild(browserWrap);
// Hide scrollbars for the whole body while inappbrowser's window is open
document.body.style.msOverflowStyle = "none";
}
if (features.indexOf("hidden=yes") !== -1) {
browserWrap.style.display = "none";
}
popup = document.createElement(isWebViewAvailable ? "x-ms-webview" : "iframe");
if (popup instanceof HTMLIFrameElement) {
// For iframe we need to override bacground color of parent element here
// otherwise pages without background color set will have transparent background
popup.style.backgroundColor = "white";
}
popup.style.borderWidth = "0px";
popup.style.width = "100%";
browserWrap.appendChild(popup);
if (features.indexOf("location=yes") !== -1 || features.indexOf("location") === -1) {
popup.style.height = "calc(100% - 70px)";
navigationButtonsDiv = document.createElement("div");
navigationButtonsDiv.className = "inappbrowser-app-bar";
navigationButtonsDiv.onclick = function (e) {
e.cancelBubble = true;
};
navigationButtonsDivInner = document.createElement("div");
navigationButtonsDivInner.className = "inappbrowser-app-bar-inner";
navigationButtonsDivInner.onclick = function (e) {
e.cancelBubble = true;
};
backButton = document.createElement("div");
backButton.innerText = "back";
backButton.className = "app-bar-action action-back";
backButton.addEventListener("click", function (e) {
if (popup.canGoBack)
popup.goBack();
});
forwardButton = document.createElement("div");
forwardButton.innerText = "forward";
forwardButton.className = "app-bar-action action-forward";
forwardButton.addEventListener("click", function (e) {
if (popup.canGoForward)
popup.goForward();
});
closeButton = document.createElement("div");
closeButton.innerText = "close";
closeButton.className = "app-bar-action action-close";
closeButton.addEventListener("click", function (e) {
setTimeout(function () {
IAB.close(navigationEventsCallback);
}, 0);
});
if (!isWebViewAvailable) {
// iframe navigation is not yet supported
backButton.setAttribute("disabled", "true");
forwardButton.setAttribute("disabled", "true");
}
navigationButtonsDivInner.appendChild(backButton);
navigationButtonsDivInner.appendChild(forwardButton);
navigationButtonsDivInner.appendChild(closeButton);
navigationButtonsDiv.appendChild(navigationButtonsDivInner);
browserWrap.appendChild(navigationButtonsDiv);
} else {
popup.style.height = "100%";
}
// start listening for navigation events
attachNavigationEvents(popup, navigationEventsCallback);
if (isWebViewAvailable) {
strUrl = strUrl.replace("ms-appx://", "ms-appx-web://");
}
popup.src = strUrl;
}
});
},
injectScriptCode: function (win, fail, args) {
setImmediate(function () {
var code = args[0],
hasCallback = args[1];
if (isWebViewAvailable && browserWrap && popup) {
var op = popup.invokeScriptAsync("eval", code);
op.oncomplete = function (e) {
if (hasCallback) {
// return null if event target is unavailable by some reason
var result = (e && e.target) ? [e.target.result] : [null];
win(result);
}
};
op.onerror = function () { };
op.start();
}
});
},
injectScriptFile: function (win, fail, args) {
setImmediate(function () {
var filePath = args[0],
hasCallback = args[1];
if (!!filePath) {
filePath = urlutil.makeAbsolute(filePath);
}
if (isWebViewAvailable && browserWrap && popup) {
var uri = new Windows.Foundation.Uri(filePath);
Windows.Storage.StorageFile.getFileFromApplicationUriAsync(uri).done(function (file) {
Windows.Storage.FileIO.readTextAsync(file).done(function (code) {
var op = popup.invokeScriptAsync("eval", code);
op.oncomplete = function(e) {
if (hasCallback) {
var result = [e.target.result];
win(result);
}
};
op.onerror = function () { };
op.start();
});
});
}
});
},
injectStyleCode: function (win, fail, args) {
setImmediate(function () {
var code = args[0],
hasCallback = args[1];
if (isWebViewAvailable && browserWrap && popup) {
injectCSS(popup, code, hasCallback && win);
}
});
},
injectStyleFile: function (win, fail, args) {
setImmediate(function () {
var filePath = args[0],
hasCallback = args[1];
filePath = filePath && urlutil.makeAbsolute(filePath);
if (isWebViewAvailable && browserWrap && popup) {
var uri = new Windows.Foundation.Uri(filePath);
Windows.Storage.StorageFile.getFileFromApplicationUriAsync(uri).then(function (file) {
return Windows.Storage.FileIO.readTextAsync(file);
}).done(function (code) {
injectCSS(popup, code, hasCallback && win);
}, function () {
// no-op, just catch an error
});
}
});
}
};
function injectCSS (webView, cssCode, callback) {
// This will automatically escape all thing that we need (quotes, slashes, etc.)
var escapedCode = JSON.stringify(cssCode);
var evalWrapper = "(function(d){var c=d.createElement('style');c.innerHTML=%s;d.head.appendChild(c);})(document)"
.replace('%s', escapedCode);
var op = webView.invokeScriptAsync("eval", evalWrapper);
op.oncomplete = function() {
if (callback) {
callback([]);
}
};
op.onerror = function () { };
op.start();
}
module.exports = IAB;
require("cordova/exec/proxy").add("InAppBrowser", module.exports);
| aroegies/trecrts-tools | trecrts-mobile-app/plugins/cordova-plugin-inappbrowser/src/windows/InAppBrowserProxy.js | JavaScript | apache-2.0 | 13,645 |
cask 'mplayer-osx-extended' do
version 'rev15'
sha256 '7979f2369730d389ceb4ec3082c65ffa3ec70f812f0699a2ef8acbae958a5c93'
# github.com is the official download host per the vendor homepage
url "https://github.com/sttz/MPlayer-OSX-Extended/releases/download/#{version}/MPlayer-OSX-Extended_#{version}.zip"
appcast 'https://github.com/sttz/MPlayer-OSX-Extended/releases.atom',
checkpoint: '97a7842a97b15d35ed296f0917e0c6ebdf9f5c54f978e15bf419134bac7bf232'
name 'MPlayer OSX Extended'
homepage 'http://www.mplayerosx.ch/'
license :gpl
app 'MPlayer OSX Extended.app'
zap delete: '~/.mplayer'
end
| elnappo/homebrew-cask | Casks/mplayer-osx-extended.rb | Ruby | bsd-2-clause | 624 |
/*
* Copyright (c) 2000-2006 LSI Logic Corporation.
*
*
* Name: mpi_ioc.h
* Title: MPI IOC, Port, Event, FW Download, and FW Upload messages
* Creation Date: August 11, 2000
*
* mpi_ioc.h Version: 01.05.12
*
* Version History
* ---------------
*
* Date Version Description
* -------- -------- ------------------------------------------------------
* 05-08-00 00.10.01 Original release for 0.10 spec dated 4/26/2000.
* 05-24-00 00.10.02 Added _MSG_IOC_INIT_REPLY structure.
* 06-06-00 01.00.01 Added CurReplyFrameSize field to _MSG_IOC_FACTS_REPLY.
* 06-12-00 01.00.02 Added _MSG_PORT_ENABLE_REPLY structure.
* Added _MSG_EVENT_ACK_REPLY structure.
* Added _MSG_FW_DOWNLOAD_REPLY structure.
* Added _MSG_TOOLBOX_REPLY structure.
* 06-30-00 01.00.03 Added MaxLanBuckets to _PORT_FACT_REPLY structure.
* 07-27-00 01.00.04 Added _EVENT_DATA structure definitions for _SCSI,
* _LINK_STATUS, _LOOP_STATE and _LOGOUT.
* 08-11-00 01.00.05 Switched positions of MsgLength and Function fields in
* _MSG_EVENT_ACK_REPLY structure to match specification.
* 11-02-00 01.01.01 Original release for post 1.0 work.
* Added a value for Manufacturer to WhoInit.
* 12-04-00 01.01.02 Modified IOCFacts reply, added FWUpload messages, and
* removed toolbox message.
* 01-09-01 01.01.03 Added event enabled and disabled defines.
* Added structures for FwHeader and DataHeader.
* Added ImageType to FwUpload reply.
* 02-20-01 01.01.04 Started using MPI_POINTER.
* 02-27-01 01.01.05 Added event for RAID status change and its event data.
* Added IocNumber field to MSG_IOC_FACTS_REPLY.
* 03-27-01 01.01.06 Added defines for ProductId field of MPI_FW_HEADER.
* Added structure offset comments.
* 04-09-01 01.01.07 Added structure EVENT_DATA_EVENT_CHANGE.
* 08-08-01 01.02.01 Original release for v1.2 work.
* New format for FWVersion and ProductId in
* MSG_IOC_FACTS_REPLY and MPI_FW_HEADER.
* 08-31-01 01.02.02 Addded event MPI_EVENT_SCSI_DEVICE_STATUS_CHANGE and
* related structure and defines.
* Added event MPI_EVENT_ON_BUS_TIMER_EXPIRED.
* Added MPI_IOCINIT_FLAGS_DISCARD_FW_IMAGE.
* Replaced a reserved field in MSG_IOC_FACTS_REPLY with
* IOCExceptions and changed DataImageSize to reserved.
* Added MPI_FW_DOWNLOAD_ITYPE_NVSTORE_DATA and
* MPI_FW_UPLOAD_ITYPE_NVDATA.
* 09-28-01 01.02.03 Modified Event Data for Integrated RAID.
* 11-01-01 01.02.04 Added defines for MPI_EXT_IMAGE_HEADER ImageType field.
* 03-14-02 01.02.05 Added HeaderVersion field to MSG_IOC_FACTS_REPLY.
* 05-31-02 01.02.06 Added define for
* MPI_IOCFACTS_EXCEPT_RAID_CONFIG_INVALID.
* Added AliasIndex to EVENT_DATA_LOGOUT structure.
* 04-01-03 01.02.07 Added defines for MPI_FW_HEADER_SIGNATURE_.
* 06-26-03 01.02.08 Added new values to the product family defines.
* 04-29-04 01.02.09 Added IOCCapabilities field to MSG_IOC_FACTS_REPLY and
* added related defines.
* 05-11-04 01.03.01 Original release for MPI v1.3.
* 08-19-04 01.05.01 Added four new fields to MSG_IOC_INIT.
* Added three new fields to MSG_IOC_FACTS_REPLY.
* Defined four new bits for the IOCCapabilities field of
* the IOCFacts reply.
* Added two new PortTypes for the PortFacts reply.
* Added six new events along with their EventData
* structures.
* Added a new MsgFlag to the FwDownload request to
* indicate last segment.
* Defined a new image type of boot loader.
* Added FW family codes for SAS product families.
* 10-05-04 01.05.02 Added ReplyFifoHostSignalingAddr field to
* MSG_IOC_FACTS_REPLY.
* 12-07-04 01.05.03 Added more defines for SAS Discovery Error event.
* 12-09-04 01.05.04 Added Unsupported device to SAS Device event.
* 01-15-05 01.05.05 Added event data for SAS SES Event.
* 02-09-05 01.05.06 Added MPI_FW_UPLOAD_ITYPE_FW_BACKUP define.
* 02-22-05 01.05.07 Added Host Page Buffer Persistent flag to IOC Facts
* Reply and IOC Init Request.
* 03-11-05 01.05.08 Added family code for 1068E family.
* Removed IOCFacts Reply EEDP Capability bit.
* 06-24-05 01.05.09 Added 5 new IOCFacts Reply IOCCapabilities bits.
* Added Max SATA Targets to SAS Discovery Error event.
* 08-30-05 01.05.10 Added 4 new events and their event data structures.
* Added new ReasonCode value for SAS Device Status Change
* event.
* Added new family code for FC949E.
* 03-27-06 01.05.11 Added MPI_IOCFACTS_CAPABILITY_TLR.
* Added additional Reason Codes and more event data fields
* to EVENT_DATA_SAS_DEVICE_STATUS_CHANGE.
* Added EVENT_DATA_SAS_BROADCAST_PRIMITIVE structure and
* new event.
* Added MPI_EVENT_SAS_SMP_ERROR and event data structure.
* Added MPI_EVENT_SAS_INIT_DEVICE_STATUS_CHANGE and event
* data structure.
* Added MPI_EVENT_SAS_INIT_TABLE_OVERFLOW and event
* data structure.
* Added MPI_EXT_IMAGE_TYPE_INITIALIZATION.
* 10-11-06 01.05.12 Added MPI_IOCFACTS_EXCEPT_METADATA_UNSUPPORTED.
* Added MaxInitiators field to PortFacts reply.
* Added SAS Device Status Change ReasonCode for
* asynchronous notificaiton.
* Added MPI_EVENT_SAS_EXPANDER_STATUS_CHANGE and event
* data structure.
* Added new ImageType values for FWDownload and FWUpload
* requests.
* --------------------------------------------------------------------------
*/
#ifndef MPI_IOC_H
#define MPI_IOC_H
/*****************************************************************************
*
* I O C M e s s a g e s
*
*****************************************************************************/
/****************************************************************************/
/* IOCInit message */
/****************************************************************************/
typedef struct _MSG_IOC_INIT
{
U8 WhoInit; /* 00h */
U8 Reserved; /* 01h */
U8 ChainOffset; /* 02h */
U8 Function; /* 03h */
U8 Flags; /* 04h */
U8 MaxDevices; /* 05h */
U8 MaxBuses; /* 06h */
U8 MsgFlags; /* 07h */
U32 MsgContext; /* 08h */
U16 ReplyFrameSize; /* 0Ch */
U8 Reserved1[2]; /* 0Eh */
U32 HostMfaHighAddr; /* 10h */
U32 SenseBufferHighAddr; /* 14h */
U32 ReplyFifoHostSignalingAddr; /* 18h */
SGE_SIMPLE_UNION HostPageBufferSGE; /* 1Ch */
U16 MsgVersion; /* 28h */
U16 HeaderVersion; /* 2Ah */
} MSG_IOC_INIT, MPI_POINTER PTR_MSG_IOC_INIT,
IOCInit_t, MPI_POINTER pIOCInit_t;
/* WhoInit values */
#define MPI_WHOINIT_NO_ONE (0x00)
#define MPI_WHOINIT_SYSTEM_BIOS (0x01)
#define MPI_WHOINIT_ROM_BIOS (0x02)
#define MPI_WHOINIT_PCI_PEER (0x03)
#define MPI_WHOINIT_HOST_DRIVER (0x04)
#define MPI_WHOINIT_MANUFACTURER (0x05)
/* Flags values */
#define MPI_IOCINIT_FLAGS_HOST_PAGE_BUFFER_PERSISTENT (0x04)
#define MPI_IOCINIT_FLAGS_REPLY_FIFO_HOST_SIGNAL (0x02)
#define MPI_IOCINIT_FLAGS_DISCARD_FW_IMAGE (0x01)
/* MsgVersion */
#define MPI_IOCINIT_MSGVERSION_MAJOR_MASK (0xFF00)
#define MPI_IOCINIT_MSGVERSION_MAJOR_SHIFT (8)
#define MPI_IOCINIT_MSGVERSION_MINOR_MASK (0x00FF)
#define MPI_IOCINIT_MSGVERSION_MINOR_SHIFT (0)
/* HeaderVersion */
#define MPI_IOCINIT_HEADERVERSION_UNIT_MASK (0xFF00)
#define MPI_IOCINIT_HEADERVERSION_UNIT_SHIFT (8)
#define MPI_IOCINIT_HEADERVERSION_DEV_MASK (0x00FF)
#define MPI_IOCINIT_HEADERVERSION_DEV_SHIFT (0)
typedef struct _MSG_IOC_INIT_REPLY
{
U8 WhoInit; /* 00h */
U8 Reserved; /* 01h */
U8 MsgLength; /* 02h */
U8 Function; /* 03h */
U8 Flags; /* 04h */
U8 MaxDevices; /* 05h */
U8 MaxBuses; /* 06h */
U8 MsgFlags; /* 07h */
U32 MsgContext; /* 08h */
U16 Reserved2; /* 0Ch */
U16 IOCStatus; /* 0Eh */
U32 IOCLogInfo; /* 10h */
} MSG_IOC_INIT_REPLY, MPI_POINTER PTR_MSG_IOC_INIT_REPLY,
IOCInitReply_t, MPI_POINTER pIOCInitReply_t;
/****************************************************************************/
/* IOC Facts message */
/****************************************************************************/
typedef struct _MSG_IOC_FACTS
{
U8 Reserved[2]; /* 00h */
U8 ChainOffset; /* 01h */
U8 Function; /* 02h */
U8 Reserved1[3]; /* 03h */
U8 MsgFlags; /* 04h */
U32 MsgContext; /* 08h */
} MSG_IOC_FACTS, MPI_POINTER PTR_IOC_FACTS,
IOCFacts_t, MPI_POINTER pIOCFacts_t;
typedef struct _MPI_FW_VERSION_STRUCT
{
U8 Dev; /* 00h */
U8 Unit; /* 01h */
U8 Minor; /* 02h */
U8 Major; /* 03h */
} MPI_FW_VERSION_STRUCT;
typedef union _MPI_FW_VERSION
{
MPI_FW_VERSION_STRUCT Struct;
U32 Word;
} MPI_FW_VERSION;
/* IOC Facts Reply */
typedef struct _MSG_IOC_FACTS_REPLY
{
U16 MsgVersion; /* 00h */
U8 MsgLength; /* 02h */
U8 Function; /* 03h */
U16 HeaderVersion; /* 04h */
U8 IOCNumber; /* 06h */
U8 MsgFlags; /* 07h */
U32 MsgContext; /* 08h */
U16 IOCExceptions; /* 0Ch */
U16 IOCStatus; /* 0Eh */
U32 IOCLogInfo; /* 10h */
U8 MaxChainDepth; /* 14h */
U8 WhoInit; /* 15h */
U8 BlockSize; /* 16h */
U8 Flags; /* 17h */
U16 ReplyQueueDepth; /* 18h */
U16 RequestFrameSize; /* 1Ah */
U16 Reserved_0101_FWVersion; /* 1Ch */ /* obsolete 16-bit FWVersion */
U16 ProductID; /* 1Eh */
U32 CurrentHostMfaHighAddr; /* 20h */
U16 GlobalCredits; /* 24h */
U8 NumberOfPorts; /* 26h */
U8 EventState; /* 27h */
U32 CurrentSenseBufferHighAddr; /* 28h */
U16 CurReplyFrameSize; /* 2Ch */
U8 MaxDevices; /* 2Eh */
U8 MaxBuses; /* 2Fh */
U32 FWImageSize; /* 30h */
U32 IOCCapabilities; /* 34h */
MPI_FW_VERSION FWVersion; /* 38h */
U16 HighPriorityQueueDepth; /* 3Ch */
U16 Reserved2; /* 3Eh */
SGE_SIMPLE_UNION HostPageBufferSGE; /* 40h */
U32 ReplyFifoHostSignalingAddr; /* 4Ch */
} MSG_IOC_FACTS_REPLY, MPI_POINTER PTR_MSG_IOC_FACTS_REPLY,
IOCFactsReply_t, MPI_POINTER pIOCFactsReply_t;
#define MPI_IOCFACTS_MSGVERSION_MAJOR_MASK (0xFF00)
#define MPI_IOCFACTS_MSGVERSION_MAJOR_SHIFT (8)
#define MPI_IOCFACTS_MSGVERSION_MINOR_MASK (0x00FF)
#define MPI_IOCFACTS_MSGVERSION_MINOR_SHIFT (0)
#define MPI_IOCFACTS_HDRVERSION_UNIT_MASK (0xFF00)
#define MPI_IOCFACTS_HDRVERSION_UNIT_SHIFT (8)
#define MPI_IOCFACTS_HDRVERSION_DEV_MASK (0x00FF)
#define MPI_IOCFACTS_HDRVERSION_DEV_SHIFT (0)
#define MPI_IOCFACTS_EXCEPT_CONFIG_CHECKSUM_FAIL (0x0001)
#define MPI_IOCFACTS_EXCEPT_RAID_CONFIG_INVALID (0x0002)
#define MPI_IOCFACTS_EXCEPT_FW_CHECKSUM_FAIL (0x0004)
#define MPI_IOCFACTS_EXCEPT_PERSISTENT_TABLE_FULL (0x0008)
#define MPI_IOCFACTS_EXCEPT_METADATA_UNSUPPORTED (0x0010)
#define MPI_IOCFACTS_FLAGS_FW_DOWNLOAD_BOOT (0x01)
#define MPI_IOCFACTS_FLAGS_REPLY_FIFO_HOST_SIGNAL (0x02)
#define MPI_IOCFACTS_FLAGS_HOST_PAGE_BUFFER_PERSISTENT (0x04)
#define MPI_IOCFACTS_EVENTSTATE_DISABLED (0x00)
#define MPI_IOCFACTS_EVENTSTATE_ENABLED (0x01)
#define MPI_IOCFACTS_CAPABILITY_HIGH_PRI_Q (0x00000001)
#define MPI_IOCFACTS_CAPABILITY_REPLY_HOST_SIGNAL (0x00000002)
#define MPI_IOCFACTS_CAPABILITY_QUEUE_FULL_HANDLING (0x00000004)
#define MPI_IOCFACTS_CAPABILITY_DIAG_TRACE_BUFFER (0x00000008)
#define MPI_IOCFACTS_CAPABILITY_SNAPSHOT_BUFFER (0x00000010)
#define MPI_IOCFACTS_CAPABILITY_EXTENDED_BUFFER (0x00000020)
#define MPI_IOCFACTS_CAPABILITY_EEDP (0x00000040)
#define MPI_IOCFACTS_CAPABILITY_BIDIRECTIONAL (0x00000080)
#define MPI_IOCFACTS_CAPABILITY_MULTICAST (0x00000100)
#define MPI_IOCFACTS_CAPABILITY_SCSIIO32 (0x00000200)
#define MPI_IOCFACTS_CAPABILITY_NO_SCSIIO16 (0x00000400)
#define MPI_IOCFACTS_CAPABILITY_TLR (0x00000800)
/*****************************************************************************
*
* P o r t M e s s a g e s
*
*****************************************************************************/
/****************************************************************************/
/* Port Facts message and Reply */
/****************************************************************************/
typedef struct _MSG_PORT_FACTS
{
U8 Reserved[2]; /* 00h */
U8 ChainOffset; /* 02h */
U8 Function; /* 03h */
U8 Reserved1[2]; /* 04h */
U8 PortNumber; /* 06h */
U8 MsgFlags; /* 07h */
U32 MsgContext; /* 08h */
} MSG_PORT_FACTS, MPI_POINTER PTR_MSG_PORT_FACTS,
PortFacts_t, MPI_POINTER pPortFacts_t;
typedef struct _MSG_PORT_FACTS_REPLY
{
U16 Reserved; /* 00h */
U8 MsgLength; /* 02h */
U8 Function; /* 03h */
U16 Reserved1; /* 04h */
U8 PortNumber; /* 06h */
U8 MsgFlags; /* 07h */
U32 MsgContext; /* 08h */
U16 Reserved2; /* 0Ch */
U16 IOCStatus; /* 0Eh */
U32 IOCLogInfo; /* 10h */
U8 Reserved3; /* 14h */
U8 PortType; /* 15h */
U16 MaxDevices; /* 16h */
U16 PortSCSIID; /* 18h */
U16 ProtocolFlags; /* 1Ah */
U16 MaxPostedCmdBuffers; /* 1Ch */
U16 MaxPersistentIDs; /* 1Eh */
U16 MaxLanBuckets; /* 20h */
U8 MaxInitiators; /* 22h */
U8 Reserved4; /* 23h */
U32 Reserved5; /* 24h */
} MSG_PORT_FACTS_REPLY, MPI_POINTER PTR_MSG_PORT_FACTS_REPLY,
PortFactsReply_t, MPI_POINTER pPortFactsReply_t;
/* PortTypes values */
#define MPI_PORTFACTS_PORTTYPE_INACTIVE (0x00)
#define MPI_PORTFACTS_PORTTYPE_SCSI (0x01)
#define MPI_PORTFACTS_PORTTYPE_FC (0x10)
#define MPI_PORTFACTS_PORTTYPE_ISCSI (0x20)
#define MPI_PORTFACTS_PORTTYPE_SAS (0x30)
/* ProtocolFlags values */
#define MPI_PORTFACTS_PROTOCOL_LOGBUSADDR (0x01)
#define MPI_PORTFACTS_PROTOCOL_LAN (0x02)
#define MPI_PORTFACTS_PROTOCOL_TARGET (0x04)
#define MPI_PORTFACTS_PROTOCOL_INITIATOR (0x08)
/****************************************************************************/
/* Port Enable Message */
/****************************************************************************/
typedef struct _MSG_PORT_ENABLE
{
U8 Reserved[2]; /* 00h */
U8 ChainOffset; /* 02h */
U8 Function; /* 03h */
U8 Reserved1[2]; /* 04h */
U8 PortNumber; /* 06h */
U8 MsgFlags; /* 07h */
U32 MsgContext; /* 08h */
} MSG_PORT_ENABLE, MPI_POINTER PTR_MSG_PORT_ENABLE,
PortEnable_t, MPI_POINTER pPortEnable_t;
typedef struct _MSG_PORT_ENABLE_REPLY
{
U8 Reserved[2]; /* 00h */
U8 MsgLength; /* 02h */
U8 Function; /* 03h */
U8 Reserved1[2]; /* 04h */
U8 PortNumber; /* 05h */
U8 MsgFlags; /* 07h */
U32 MsgContext; /* 08h */
U16 Reserved2; /* 0Ch */
U16 IOCStatus; /* 0Eh */
U32 IOCLogInfo; /* 10h */
} MSG_PORT_ENABLE_REPLY, MPI_POINTER PTR_MSG_PORT_ENABLE_REPLY,
PortEnableReply_t, MPI_POINTER pPortEnableReply_t;
/*****************************************************************************
*
* E v e n t M e s s a g e s
*
*****************************************************************************/
/****************************************************************************/
/* Event Notification messages */
/****************************************************************************/
typedef struct _MSG_EVENT_NOTIFY
{
U8 Switch; /* 00h */
U8 Reserved; /* 01h */
U8 ChainOffset; /* 02h */
U8 Function; /* 03h */
U8 Reserved1[3]; /* 04h */
U8 MsgFlags; /* 07h */
U32 MsgContext; /* 08h */
} MSG_EVENT_NOTIFY, MPI_POINTER PTR_MSG_EVENT_NOTIFY,
EventNotification_t, MPI_POINTER pEventNotification_t;
/* Event Notification Reply */
typedef struct _MSG_EVENT_NOTIFY_REPLY
{
U16 EventDataLength; /* 00h */
U8 MsgLength; /* 02h */
U8 Function; /* 03h */
U8 Reserved1[2]; /* 04h */
U8 AckRequired; /* 06h */
U8 MsgFlags; /* 07h */
U32 MsgContext; /* 08h */
U8 Reserved2[2]; /* 0Ch */
U16 IOCStatus; /* 0Eh */
U32 IOCLogInfo; /* 10h */
U32 Event; /* 14h */
U32 EventContext; /* 18h */
U32 Data[1]; /* 1Ch */
} MSG_EVENT_NOTIFY_REPLY, MPI_POINTER PTR_MSG_EVENT_NOTIFY_REPLY,
EventNotificationReply_t, MPI_POINTER pEventNotificationReply_t;
/* Event Acknowledge */
typedef struct _MSG_EVENT_ACK
{
U8 Reserved[2]; /* 00h */
U8 ChainOffset; /* 02h */
U8 Function; /* 03h */
U8 Reserved1[3]; /* 04h */
U8 MsgFlags; /* 07h */
U32 MsgContext; /* 08h */
U32 Event; /* 0Ch */
U32 EventContext; /* 10h */
} MSG_EVENT_ACK, MPI_POINTER PTR_MSG_EVENT_ACK,
EventAck_t, MPI_POINTER pEventAck_t;
typedef struct _MSG_EVENT_ACK_REPLY
{
U8 Reserved[2]; /* 00h */
U8 MsgLength; /* 02h */
U8 Function; /* 03h */
U8 Reserved1[3]; /* 04h */
U8 MsgFlags; /* 07h */
U32 MsgContext; /* 08h */
U16 Reserved2; /* 0Ch */
U16 IOCStatus; /* 0Eh */
U32 IOCLogInfo; /* 10h */
} MSG_EVENT_ACK_REPLY, MPI_POINTER PTR_MSG_EVENT_ACK_REPLY,
EventAckReply_t, MPI_POINTER pEventAckReply_t;
/* Switch */
#define MPI_EVENT_NOTIFICATION_SWITCH_OFF (0x00)
#define MPI_EVENT_NOTIFICATION_SWITCH_ON (0x01)
/* Event */
#define MPI_EVENT_NONE (0x00000000)
#define MPI_EVENT_LOG_DATA (0x00000001)
#define MPI_EVENT_STATE_CHANGE (0x00000002)
#define MPI_EVENT_UNIT_ATTENTION (0x00000003)
#define MPI_EVENT_IOC_BUS_RESET (0x00000004)
#define MPI_EVENT_EXT_BUS_RESET (0x00000005)
#define MPI_EVENT_RESCAN (0x00000006)
#define MPI_EVENT_LINK_STATUS_CHANGE (0x00000007)
#define MPI_EVENT_LOOP_STATE_CHANGE (0x00000008)
#define MPI_EVENT_LOGOUT (0x00000009)
#define MPI_EVENT_EVENT_CHANGE (0x0000000A)
#define MPI_EVENT_INTEGRATED_RAID (0x0000000B)
#define MPI_EVENT_SCSI_DEVICE_STATUS_CHANGE (0x0000000C)
#define MPI_EVENT_ON_BUS_TIMER_EXPIRED (0x0000000D)
#define MPI_EVENT_QUEUE_FULL (0x0000000E)
#define MPI_EVENT_SAS_DEVICE_STATUS_CHANGE (0x0000000F)
#define MPI_EVENT_SAS_SES (0x00000010)
#define MPI_EVENT_PERSISTENT_TABLE_FULL (0x00000011)
#define MPI_EVENT_SAS_PHY_LINK_STATUS (0x00000012)
#define MPI_EVENT_SAS_DISCOVERY_ERROR (0x00000013)
#define MPI_EVENT_IR_RESYNC_UPDATE (0x00000014)
#define MPI_EVENT_IR2 (0x00000015)
#define MPI_EVENT_SAS_DISCOVERY (0x00000016)
#define MPI_EVENT_SAS_BROADCAST_PRIMITIVE (0x00000017)
#define MPI_EVENT_SAS_INIT_DEVICE_STATUS_CHANGE (0x00000018)
#define MPI_EVENT_SAS_INIT_TABLE_OVERFLOW (0x00000019)
#define MPI_EVENT_SAS_SMP_ERROR (0x0000001A)
#define MPI_EVENT_SAS_EXPANDER_STATUS_CHANGE (0x0000001B)
#define MPI_EVENT_LOG_ENTRY_ADDED (0x00000021)
/* AckRequired field values */
#define MPI_EVENT_NOTIFICATION_ACK_NOT_REQUIRED (0x00)
#define MPI_EVENT_NOTIFICATION_ACK_REQUIRED (0x01)
/* EventChange Event data */
typedef struct _EVENT_DATA_EVENT_CHANGE
{
U8 EventState; /* 00h */
U8 Reserved; /* 01h */
U16 Reserved1; /* 02h */
} EVENT_DATA_EVENT_CHANGE, MPI_POINTER PTR_EVENT_DATA_EVENT_CHANGE,
EventDataEventChange_t, MPI_POINTER pEventDataEventChange_t;
/* LogEntryAdded Event data */
/* this structure matches MPI_LOG_0_ENTRY in mpi_cnfg.h */
#define MPI_EVENT_DATA_LOG_ENTRY_DATA_LENGTH (0x1C)
typedef struct _EVENT_DATA_LOG_ENTRY
{
U32 TimeStamp; /* 00h */
U32 Reserved1; /* 04h */
U16 LogSequence; /* 08h */
U16 LogEntryQualifier; /* 0Ah */
U8 LogData[MPI_EVENT_DATA_LOG_ENTRY_DATA_LENGTH]; /* 0Ch */
} EVENT_DATA_LOG_ENTRY, MPI_POINTER PTR_EVENT_DATA_LOG_ENTRY,
MpiEventDataLogEntry_t, MPI_POINTER pMpiEventDataLogEntry_t;
typedef struct _EVENT_DATA_LOG_ENTRY_ADDED
{
U16 LogSequence; /* 00h */
U16 Reserved1; /* 02h */
U32 Reserved2; /* 04h */
EVENT_DATA_LOG_ENTRY LogEntry; /* 08h */
} EVENT_DATA_LOG_ENTRY_ADDED, MPI_POINTER PTR_EVENT_DATA_LOG_ENTRY_ADDED,
MpiEventDataLogEntryAdded_t, MPI_POINTER pMpiEventDataLogEntryAdded_t;
/* SCSI Event data for Port, Bus and Device forms */
typedef struct _EVENT_DATA_SCSI
{
U8 TargetID; /* 00h */
U8 BusPort; /* 01h */
U16 Reserved; /* 02h */
} EVENT_DATA_SCSI, MPI_POINTER PTR_EVENT_DATA_SCSI,
EventDataScsi_t, MPI_POINTER pEventDataScsi_t;
/* SCSI Device Status Change Event data */
typedef struct _EVENT_DATA_SCSI_DEVICE_STATUS_CHANGE
{
U8 TargetID; /* 00h */
U8 Bus; /* 01h */
U8 ReasonCode; /* 02h */
U8 LUN; /* 03h */
U8 ASC; /* 04h */
U8 ASCQ; /* 05h */
U16 Reserved; /* 06h */
} EVENT_DATA_SCSI_DEVICE_STATUS_CHANGE,
MPI_POINTER PTR_EVENT_DATA_SCSI_DEVICE_STATUS_CHANGE,
MpiEventDataScsiDeviceStatusChange_t,
MPI_POINTER pMpiEventDataScsiDeviceStatusChange_t;
/* MPI SCSI Device Status Change Event data ReasonCode values */
#define MPI_EVENT_SCSI_DEV_STAT_RC_ADDED (0x03)
#define MPI_EVENT_SCSI_DEV_STAT_RC_NOT_RESPONDING (0x04)
#define MPI_EVENT_SCSI_DEV_STAT_RC_SMART_DATA (0x05)
/* SAS Device Status Change Event data */
typedef struct _EVENT_DATA_SAS_DEVICE_STATUS_CHANGE
{
U8 TargetID; /* 00h */
U8 Bus; /* 01h */
U8 ReasonCode; /* 02h */
U8 Reserved; /* 03h */
U8 ASC; /* 04h */
U8 ASCQ; /* 05h */
U16 DevHandle; /* 06h */
U32 DeviceInfo; /* 08h */
U16 ParentDevHandle; /* 0Ch */
U8 PhyNum; /* 0Eh */
U8 Reserved1; /* 0Fh */
U64 SASAddress; /* 10h */
U8 LUN[8]; /* 18h */
U16 TaskTag; /* 20h */
U16 Reserved2; /* 22h */
} EVENT_DATA_SAS_DEVICE_STATUS_CHANGE,
MPI_POINTER PTR_EVENT_DATA_SAS_DEVICE_STATUS_CHANGE,
MpiEventDataSasDeviceStatusChange_t,
MPI_POINTER pMpiEventDataSasDeviceStatusChange_t;
/* MPI SAS Device Status Change Event data ReasonCode values */
#define MPI_EVENT_SAS_DEV_STAT_RC_ADDED (0x03)
#define MPI_EVENT_SAS_DEV_STAT_RC_NOT_RESPONDING (0x04)
#define MPI_EVENT_SAS_DEV_STAT_RC_SMART_DATA (0x05)
#define MPI_EVENT_SAS_DEV_STAT_RC_NO_PERSIST_ADDED (0x06)
#define MPI_EVENT_SAS_DEV_STAT_RC_UNSUPPORTED (0x07)
#define MPI_EVENT_SAS_DEV_STAT_RC_INTERNAL_DEVICE_RESET (0x08)
#define MPI_EVENT_SAS_DEV_STAT_RC_TASK_ABORT_INTERNAL (0x09)
#define MPI_EVENT_SAS_DEV_STAT_RC_ABORT_TASK_SET_INTERNAL (0x0A)
#define MPI_EVENT_SAS_DEV_STAT_RC_CLEAR_TASK_SET_INTERNAL (0x0B)
#define MPI_EVENT_SAS_DEV_STAT_RC_QUERY_TASK_INTERNAL (0x0C)
#define MPI_EVENT_SAS_DEV_STAT_RC_ASYNC_NOTIFICATION (0x0D)
/* SCSI Event data for Queue Full event */
typedef struct _EVENT_DATA_QUEUE_FULL
{
U8 TargetID; /* 00h */
U8 Bus; /* 01h */
U16 CurrentDepth; /* 02h */
} EVENT_DATA_QUEUE_FULL, MPI_POINTER PTR_EVENT_DATA_QUEUE_FULL,
EventDataQueueFull_t, MPI_POINTER pEventDataQueueFull_t;
/* MPI Integrated RAID Event data */
typedef struct _EVENT_DATA_RAID
{
U8 VolumeID; /* 00h */
U8 VolumeBus; /* 01h */
U8 ReasonCode; /* 02h */
U8 PhysDiskNum; /* 03h */
U8 ASC; /* 04h */
U8 ASCQ; /* 05h */
U16 Reserved; /* 06h */
U32 SettingsStatus; /* 08h */
} EVENT_DATA_RAID, MPI_POINTER PTR_EVENT_DATA_RAID,
MpiEventDataRaid_t, MPI_POINTER pMpiEventDataRaid_t;
/* MPI Integrated RAID Event data ReasonCode values */
#define MPI_EVENT_RAID_RC_VOLUME_CREATED (0x00)
#define MPI_EVENT_RAID_RC_VOLUME_DELETED (0x01)
#define MPI_EVENT_RAID_RC_VOLUME_SETTINGS_CHANGED (0x02)
#define MPI_EVENT_RAID_RC_VOLUME_STATUS_CHANGED (0x03)
#define MPI_EVENT_RAID_RC_VOLUME_PHYSDISK_CHANGED (0x04)
#define MPI_EVENT_RAID_RC_PHYSDISK_CREATED (0x05)
#define MPI_EVENT_RAID_RC_PHYSDISK_DELETED (0x06)
#define MPI_EVENT_RAID_RC_PHYSDISK_SETTINGS_CHANGED (0x07)
#define MPI_EVENT_RAID_RC_PHYSDISK_STATUS_CHANGED (0x08)
#define MPI_EVENT_RAID_RC_DOMAIN_VAL_NEEDED (0x09)
#define MPI_EVENT_RAID_RC_SMART_DATA (0x0A)
#define MPI_EVENT_RAID_RC_REPLACE_ACTION_STARTED (0x0B)
/* MPI Integrated RAID Resync Update Event data */
typedef struct _MPI_EVENT_DATA_IR_RESYNC_UPDATE
{
U8 VolumeID; /* 00h */
U8 VolumeBus; /* 01h */
U8 ResyncComplete; /* 02h */
U8 Reserved1; /* 03h */
U32 Reserved2; /* 04h */
} MPI_EVENT_DATA_IR_RESYNC_UPDATE,
MPI_POINTER PTR_MPI_EVENT_DATA_IR_RESYNC_UPDATE,
MpiEventDataIrResyncUpdate_t, MPI_POINTER pMpiEventDataIrResyncUpdate_t;
/* MPI IR2 Event data */
/* MPI_LD_STATE or MPI_PD_STATE */
typedef struct _IR2_STATE_CHANGED
{
U16 PreviousState; /* 00h */
U16 NewState; /* 02h */
} IR2_STATE_CHANGED, MPI_POINTER PTR_IR2_STATE_CHANGED;
typedef struct _IR2_PD_INFO
{
U16 DeviceHandle; /* 00h */
U8 TruncEnclosureHandle; /* 02h */
U8 TruncatedSlot; /* 03h */
} IR2_PD_INFO, MPI_POINTER PTR_IR2_PD_INFO;
typedef union _MPI_IR2_RC_EVENT_DATA
{
IR2_STATE_CHANGED StateChanged;
U32 Lba;
IR2_PD_INFO PdInfo;
} MPI_IR2_RC_EVENT_DATA, MPI_POINTER PTR_MPI_IR2_RC_EVENT_DATA;
typedef struct _MPI_EVENT_DATA_IR2
{
U8 TargetID; /* 00h */
U8 Bus; /* 01h */
U8 ReasonCode; /* 02h */
U8 PhysDiskNum; /* 03h */
MPI_IR2_RC_EVENT_DATA IR2EventData; /* 04h */
} MPI_EVENT_DATA_IR2, MPI_POINTER PTR_MPI_EVENT_DATA_IR2,
MpiEventDataIR2_t, MPI_POINTER pMpiEventDataIR2_t;
/* MPI IR2 Event data ReasonCode values */
#define MPI_EVENT_IR2_RC_LD_STATE_CHANGED (0x01)
#define MPI_EVENT_IR2_RC_PD_STATE_CHANGED (0x02)
#define MPI_EVENT_IR2_RC_BAD_BLOCK_TABLE_FULL (0x03)
#define MPI_EVENT_IR2_RC_PD_INSERTED (0x04)
#define MPI_EVENT_IR2_RC_PD_REMOVED (0x05)
#define MPI_EVENT_IR2_RC_FOREIGN_CFG_DETECTED (0x06)
#define MPI_EVENT_IR2_RC_REBUILD_MEDIUM_ERROR (0x07)
/* defines for logical disk states */
#define MPI_LD_STATE_OPTIMAL (0x00)
#define MPI_LD_STATE_DEGRADED (0x01)
#define MPI_LD_STATE_FAILED (0x02)
#define MPI_LD_STATE_MISSING (0x03)
#define MPI_LD_STATE_OFFLINE (0x04)
/* defines for physical disk states */
#define MPI_PD_STATE_ONLINE (0x00)
#define MPI_PD_STATE_MISSING (0x01)
#define MPI_PD_STATE_NOT_COMPATIBLE (0x02)
#define MPI_PD_STATE_FAILED (0x03)
#define MPI_PD_STATE_INITIALIZING (0x04)
#define MPI_PD_STATE_OFFLINE_AT_HOST_REQUEST (0x05)
#define MPI_PD_STATE_FAILED_AT_HOST_REQUEST (0x06)
#define MPI_PD_STATE_OFFLINE_FOR_ANOTHER_REASON (0xFF)
/* MPI Link Status Change Event data */
typedef struct _EVENT_DATA_LINK_STATUS
{
U8 State; /* 00h */
U8 Reserved; /* 01h */
U16 Reserved1; /* 02h */
U8 Reserved2; /* 04h */
U8 Port; /* 05h */
U16 Reserved3; /* 06h */
} EVENT_DATA_LINK_STATUS, MPI_POINTER PTR_EVENT_DATA_LINK_STATUS,
EventDataLinkStatus_t, MPI_POINTER pEventDataLinkStatus_t;
#define MPI_EVENT_LINK_STATUS_FAILURE (0x00000000)
#define MPI_EVENT_LINK_STATUS_ACTIVE (0x00000001)
/* MPI Loop State Change Event data */
typedef struct _EVENT_DATA_LOOP_STATE
{
U8 Character4; /* 00h */
U8 Character3; /* 01h */
U8 Type; /* 02h */
U8 Reserved; /* 03h */
U8 Reserved1; /* 04h */
U8 Port; /* 05h */
U16 Reserved2; /* 06h */
} EVENT_DATA_LOOP_STATE, MPI_POINTER PTR_EVENT_DATA_LOOP_STATE,
EventDataLoopState_t, MPI_POINTER pEventDataLoopState_t;
#define MPI_EVENT_LOOP_STATE_CHANGE_LIP (0x0001)
#define MPI_EVENT_LOOP_STATE_CHANGE_LPE (0x0002)
#define MPI_EVENT_LOOP_STATE_CHANGE_LPB (0x0003)
/* MPI LOGOUT Event data */
typedef struct _EVENT_DATA_LOGOUT
{
U32 NPortID; /* 00h */
U8 AliasIndex; /* 04h */
U8 Port; /* 05h */
U16 Reserved1; /* 06h */
} EVENT_DATA_LOGOUT, MPI_POINTER PTR_EVENT_DATA_LOGOUT,
EventDataLogout_t, MPI_POINTER pEventDataLogout_t;
#define MPI_EVENT_LOGOUT_ALL_ALIASES (0xFF)
/* SAS SES Event data */
typedef struct _EVENT_DATA_SAS_SES
{
U8 PhyNum; /* 00h */
U8 Port; /* 01h */
U8 PortWidth; /* 02h */
U8 Reserved1; /* 04h */
} EVENT_DATA_SAS_SES, MPI_POINTER PTR_EVENT_DATA_SAS_SES,
MpiEventDataSasSes_t, MPI_POINTER pMpiEventDataSasSes_t;
/* SAS Broadcast Primitive Event data */
typedef struct _EVENT_DATA_SAS_BROADCAST_PRIMITIVE
{
U8 PhyNum; /* 00h */
U8 Port; /* 01h */
U8 PortWidth; /* 02h */
U8 Primitive; /* 04h */
} EVENT_DATA_SAS_BROADCAST_PRIMITIVE,
MPI_POINTER PTR_EVENT_DATA_SAS_BROADCAST_PRIMITIVE,
MpiEventDataSasBroadcastPrimitive_t,
MPI_POINTER pMpiEventDataSasBroadcastPrimitive_t;
#define MPI_EVENT_PRIMITIVE_CHANGE (0x01)
#define MPI_EVENT_PRIMITIVE_EXPANDER (0x03)
#define MPI_EVENT_PRIMITIVE_RESERVED2 (0x04)
#define MPI_EVENT_PRIMITIVE_RESERVED3 (0x05)
#define MPI_EVENT_PRIMITIVE_RESERVED4 (0x06)
#define MPI_EVENT_PRIMITIVE_CHANGE0_RESERVED (0x07)
#define MPI_EVENT_PRIMITIVE_CHANGE1_RESERVED (0x08)
/* SAS Phy Link Status Event data */
typedef struct _EVENT_DATA_SAS_PHY_LINK_STATUS
{
U8 PhyNum; /* 00h */
U8 LinkRates; /* 01h */
U16 DevHandle; /* 02h */
U64 SASAddress; /* 04h */
} EVENT_DATA_SAS_PHY_LINK_STATUS, MPI_POINTER PTR_EVENT_DATA_SAS_PHY_LINK_STATUS,
MpiEventDataSasPhyLinkStatus_t, MPI_POINTER pMpiEventDataSasPhyLinkStatus_t;
/* defines for the LinkRates field of the SAS PHY Link Status event */
#define MPI_EVENT_SAS_PLS_LR_CURRENT_MASK (0xF0)
#define MPI_EVENT_SAS_PLS_LR_CURRENT_SHIFT (4)
#define MPI_EVENT_SAS_PLS_LR_PREVIOUS_MASK (0x0F)
#define MPI_EVENT_SAS_PLS_LR_PREVIOUS_SHIFT (0)
#define MPI_EVENT_SAS_PLS_LR_RATE_UNKNOWN (0x00)
#define MPI_EVENT_SAS_PLS_LR_RATE_PHY_DISABLED (0x01)
#define MPI_EVENT_SAS_PLS_LR_RATE_FAILED_SPEED_NEGOTIATION (0x02)
#define MPI_EVENT_SAS_PLS_LR_RATE_SATA_OOB_COMPLETE (0x03)
#define MPI_EVENT_SAS_PLS_LR_RATE_1_5 (0x08)
#define MPI_EVENT_SAS_PLS_LR_RATE_3_0 (0x09)
/* SAS Discovery Event data */
typedef struct _EVENT_DATA_SAS_DISCOVERY
{
U32 DiscoveryStatus; /* 00h */
U32 Reserved1; /* 04h */
} EVENT_DATA_SAS_DISCOVERY, MPI_POINTER PTR_EVENT_DATA_SAS_DISCOVERY,
EventDataSasDiscovery_t, MPI_POINTER pEventDataSasDiscovery_t;
#define MPI_EVENT_SAS_DSCVRY_COMPLETE (0x00000000)
#define MPI_EVENT_SAS_DSCVRY_IN_PROGRESS (0x00000001)
#define MPI_EVENT_SAS_DSCVRY_PHY_BITS_MASK (0xFFFF0000)
#define MPI_EVENT_SAS_DSCVRY_PHY_BITS_SHIFT (16)
/* SAS Discovery Errror Event data */
typedef struct _EVENT_DATA_DISCOVERY_ERROR
{
U32 DiscoveryStatus; /* 00h */
U8 Port; /* 04h */
U8 Reserved1; /* 05h */
U16 Reserved2; /* 06h */
} EVENT_DATA_DISCOVERY_ERROR, MPI_POINTER PTR_EVENT_DATA_DISCOVERY_ERROR,
EventDataDiscoveryError_t, MPI_POINTER pEventDataDiscoveryError_t;
#define MPI_EVENT_DSCVRY_ERR_DS_LOOP_DETECTED (0x00000001)
#define MPI_EVENT_DSCVRY_ERR_DS_UNADDRESSABLE_DEVICE (0x00000002)
#define MPI_EVENT_DSCVRY_ERR_DS_MULTIPLE_PORTS (0x00000004)
#define MPI_EVENT_DSCVRY_ERR_DS_EXPANDER_ERR (0x00000008)
#define MPI_EVENT_DSCVRY_ERR_DS_SMP_TIMEOUT (0x00000010)
#define MPI_EVENT_DSCVRY_ERR_DS_OUT_ROUTE_ENTRIES (0x00000020)
#define MPI_EVENT_DSCVRY_ERR_DS_INDEX_NOT_EXIST (0x00000040)
#define MPI_EVENT_DSCVRY_ERR_DS_SMP_FUNCTION_FAILED (0x00000080)
#define MPI_EVENT_DSCVRY_ERR_DS_SMP_CRC_ERROR (0x00000100)
#define MPI_EVENT_DSCVRY_ERR_DS_MULTPL_SUBTRACTIVE (0x00000200)
#define MPI_EVENT_DSCVRY_ERR_DS_TABLE_TO_TABLE (0x00000400)
#define MPI_EVENT_DSCVRY_ERR_DS_MULTPL_PATHS (0x00000800)
#define MPI_EVENT_DSCVRY_ERR_DS_MAX_SATA_TARGETS (0x00001000)
/* SAS SMP Error Event data */
typedef struct _EVENT_DATA_SAS_SMP_ERROR
{
U8 Status; /* 00h */
U8 Port; /* 01h */
U8 SMPFunctionResult; /* 02h */
U8 Reserved1; /* 03h */
U64 SASAddress; /* 04h */
} EVENT_DATA_SAS_SMP_ERROR, MPI_POINTER PTR_EVENT_DATA_SAS_SMP_ERROR,
MpiEventDataSasSmpError_t, MPI_POINTER pMpiEventDataSasSmpError_t;
/* defines for the Status field of the SAS SMP Error event */
#define MPI_EVENT_SAS_SMP_FUNCTION_RESULT_VALID (0x00)
#define MPI_EVENT_SAS_SMP_CRC_ERROR (0x01)
#define MPI_EVENT_SAS_SMP_TIMEOUT (0x02)
#define MPI_EVENT_SAS_SMP_NO_DESTINATION (0x03)
#define MPI_EVENT_SAS_SMP_BAD_DESTINATION (0x04)
/* SAS Initiator Device Status Change Event data */
typedef struct _EVENT_DATA_SAS_INIT_DEV_STATUS_CHANGE
{
U8 ReasonCode; /* 00h */
U8 Port; /* 01h */
U16 DevHandle; /* 02h */
U64 SASAddress; /* 04h */
} EVENT_DATA_SAS_INIT_DEV_STATUS_CHANGE,
MPI_POINTER PTR_EVENT_DATA_SAS_INIT_DEV_STATUS_CHANGE,
MpiEventDataSasInitDevStatusChange_t,
MPI_POINTER pMpiEventDataSasInitDevStatusChange_t;
/* defines for the ReasonCode field of the SAS Initiator Device Status Change event */
#define MPI_EVENT_SAS_INIT_RC_ADDED (0x01)
/* SAS Initiator Device Table Overflow Event data */
typedef struct _EVENT_DATA_SAS_INIT_TABLE_OVERFLOW
{
U8 MaxInit; /* 00h */
U8 CurrentInit; /* 01h */
U16 Reserved1; /* 02h */
} EVENT_DATA_SAS_INIT_TABLE_OVERFLOW,
MPI_POINTER PTR_EVENT_DATA_SAS_INIT_TABLE_OVERFLOW,
MpiEventDataSasInitTableOverflow_t,
MPI_POINTER pMpiEventDataSasInitTableOverflow_t;
/* SAS Expander Status Change Event data */
typedef struct _EVENT_DATA_SAS_EXPANDER_STATUS_CHANGE
{
U8 ReasonCode; /* 00h */
U8 Reserved1; /* 01h */
U16 Reserved2; /* 02h */
U8 PhysicalPort; /* 04h */
U8 Reserved3; /* 05h */
U16 EnclosureHandle; /* 06h */
U64 SASAddress; /* 08h */
U32 DiscoveryStatus; /* 10h */
U16 DevHandle; /* 14h */
U16 ParentDevHandle; /* 16h */
U16 ExpanderChangeCount; /* 18h */
U16 ExpanderRouteIndexes; /* 1Ah */
U8 NumPhys; /* 1Ch */
U8 SASLevel; /* 1Dh */
U8 Flags; /* 1Eh */
U8 Reserved4; /* 1Fh */
} EVENT_DATA_SAS_EXPANDER_STATUS_CHANGE,
MPI_POINTER PTR_EVENT_DATA_SAS_EXPANDER_STATUS_CHANGE,
MpiEventDataSasExpanderStatusChange_t,
MPI_POINTER pMpiEventDataSasExpanderStatusChange_t;
/* values for ReasonCode field of SAS Expander Status Change Event data */
#define MPI_EVENT_SAS_EXP_RC_ADDED (0x00)
#define MPI_EVENT_SAS_EXP_RC_NOT_RESPONDING (0x01)
/* values for DiscoveryStatus field of SAS Expander Status Change Event data */
#define MPI_EVENT_SAS_EXP_DS_LOOP_DETECTED (0x00000001)
#define MPI_EVENT_SAS_EXP_DS_UNADDRESSABLE_DEVICE (0x00000002)
#define MPI_EVENT_SAS_EXP_DS_MULTIPLE_PORTS (0x00000004)
#define MPI_EVENT_SAS_EXP_DS_EXPANDER_ERR (0x00000008)
#define MPI_EVENT_SAS_EXP_DS_SMP_TIMEOUT (0x00000010)
#define MPI_EVENT_SAS_EXP_DS_OUT_ROUTE_ENTRIES (0x00000020)
#define MPI_EVENT_SAS_EXP_DS_INDEX_NOT_EXIST (0x00000040)
#define MPI_EVENT_SAS_EXP_DS_SMP_FUNCTION_FAILED (0x00000080)
#define MPI_EVENT_SAS_EXP_DS_SMP_CRC_ERROR (0x00000100)
#define MPI_EVENT_SAS_EXP_DS_SUBTRACTIVE_LINK (0x00000200)
#define MPI_EVENT_SAS_EXP_DS_TABLE_LINK (0x00000400)
#define MPI_EVENT_SAS_EXP_DS_UNSUPPORTED_DEVICE (0x00000800)
/* values for Flags field of SAS Expander Status Change Event data */
#define MPI_EVENT_SAS_EXP_FLAGS_ROUTE_TABLE_CONFIG (0x02)
#define MPI_EVENT_SAS_EXP_FLAGS_CONFIG_IN_PROGRESS (0x01)
/*****************************************************************************
*
* F i r m w a r e L o a d M e s s a g e s
*
*****************************************************************************/
/****************************************************************************/
/* Firmware Download message and associated structures */
/****************************************************************************/
typedef struct _MSG_FW_DOWNLOAD
{
U8 ImageType; /* 00h */
U8 Reserved; /* 01h */
U8 ChainOffset; /* 02h */
U8 Function; /* 03h */
U8 Reserved1[3]; /* 04h */
U8 MsgFlags; /* 07h */
U32 MsgContext; /* 08h */
SGE_MPI_UNION SGL; /* 0Ch */
} MSG_FW_DOWNLOAD, MPI_POINTER PTR_MSG_FW_DOWNLOAD,
FWDownload_t, MPI_POINTER pFWDownload_t;
#define MPI_FW_DOWNLOAD_MSGFLGS_LAST_SEGMENT (0x01)
#define MPI_FW_DOWNLOAD_ITYPE_RESERVED (0x00)
#define MPI_FW_DOWNLOAD_ITYPE_FW (0x01)
#define MPI_FW_DOWNLOAD_ITYPE_BIOS (0x02)
#define MPI_FW_DOWNLOAD_ITYPE_NVDATA (0x03)
#define MPI_FW_DOWNLOAD_ITYPE_BOOTLOADER (0x04)
#define MPI_FW_DOWNLOAD_ITYPE_MANUFACTURING (0x06)
#define MPI_FW_DOWNLOAD_ITYPE_CONFIG_1 (0x07)
#define MPI_FW_DOWNLOAD_ITYPE_CONFIG_2 (0x08)
#define MPI_FW_DOWNLOAD_ITYPE_MEGARAID (0x09)
typedef struct _FWDownloadTCSGE
{
U8 Reserved; /* 00h */
U8 ContextSize; /* 01h */
U8 DetailsLength; /* 02h */
U8 Flags; /* 03h */
U32 Reserved_0100_Checksum; /* 04h */ /* obsolete Checksum */
U32 ImageOffset; /* 08h */
U32 ImageSize; /* 0Ch */
} FW_DOWNLOAD_TCSGE, MPI_POINTER PTR_FW_DOWNLOAD_TCSGE,
FWDownloadTCSGE_t, MPI_POINTER pFWDownloadTCSGE_t;
/* Firmware Download reply */
typedef struct _MSG_FW_DOWNLOAD_REPLY
{
U8 ImageType; /* 00h */
U8 Reserved; /* 01h */
U8 MsgLength; /* 02h */
U8 Function; /* 03h */
U8 Reserved1[3]; /* 04h */
U8 MsgFlags; /* 07h */
U32 MsgContext; /* 08h */
U16 Reserved2; /* 0Ch */
U16 IOCStatus; /* 0Eh */
U32 IOCLogInfo; /* 10h */
} MSG_FW_DOWNLOAD_REPLY, MPI_POINTER PTR_MSG_FW_DOWNLOAD_REPLY,
FWDownloadReply_t, MPI_POINTER pFWDownloadReply_t;
/****************************************************************************/
/* Firmware Upload message and associated structures */
/****************************************************************************/
typedef struct _MSG_FW_UPLOAD
{
U8 ImageType; /* 00h */
U8 Reserved; /* 01h */
U8 ChainOffset; /* 02h */
U8 Function; /* 03h */
U8 Reserved1[3]; /* 04h */
U8 MsgFlags; /* 07h */
U32 MsgContext; /* 08h */
SGE_MPI_UNION SGL; /* 0Ch */
} MSG_FW_UPLOAD, MPI_POINTER PTR_MSG_FW_UPLOAD,
FWUpload_t, MPI_POINTER pFWUpload_t;
#define MPI_FW_UPLOAD_ITYPE_FW_IOC_MEM (0x00)
#define MPI_FW_UPLOAD_ITYPE_FW_FLASH (0x01)
#define MPI_FW_UPLOAD_ITYPE_BIOS_FLASH (0x02)
#define MPI_FW_UPLOAD_ITYPE_NVDATA (0x03)
#define MPI_FW_UPLOAD_ITYPE_BOOTLOADER (0x04)
#define MPI_FW_UPLOAD_ITYPE_FW_BACKUP (0x05)
#define MPI_FW_UPLOAD_ITYPE_MANUFACTURING (0x06)
#define MPI_FW_UPLOAD_ITYPE_CONFIG_1 (0x07)
#define MPI_FW_UPLOAD_ITYPE_CONFIG_2 (0x08)
#define MPI_FW_UPLOAD_ITYPE_MEGARAID (0x09)
#define MPI_FW_UPLOAD_ITYPE_COMPLETE (0x0A)
typedef struct _FWUploadTCSGE
{
U8 Reserved; /* 00h */
U8 ContextSize; /* 01h */
U8 DetailsLength; /* 02h */
U8 Flags; /* 03h */
U32 Reserved1; /* 04h */
U32 ImageOffset; /* 08h */
U32 ImageSize; /* 0Ch */
} FW_UPLOAD_TCSGE, MPI_POINTER PTR_FW_UPLOAD_TCSGE,
FWUploadTCSGE_t, MPI_POINTER pFWUploadTCSGE_t;
/* Firmware Upload reply */
typedef struct _MSG_FW_UPLOAD_REPLY
{
U8 ImageType; /* 00h */
U8 Reserved; /* 01h */
U8 MsgLength; /* 02h */
U8 Function; /* 03h */
U8 Reserved1[3]; /* 04h */
U8 MsgFlags; /* 07h */
U32 MsgContext; /* 08h */
U16 Reserved2; /* 0Ch */
U16 IOCStatus; /* 0Eh */
U32 IOCLogInfo; /* 10h */
U32 ActualImageSize; /* 14h */
} MSG_FW_UPLOAD_REPLY, MPI_POINTER PTR_MSG_FW_UPLOAD_REPLY,
FWUploadReply_t, MPI_POINTER pFWUploadReply_t;
typedef struct _MPI_FW_HEADER
{
U32 ArmBranchInstruction0; /* 00h */
U32 Signature0; /* 04h */
U32 Signature1; /* 08h */
U32 Signature2; /* 0Ch */
U32 ArmBranchInstruction1; /* 10h */
U32 ArmBranchInstruction2; /* 14h */
U32 Reserved; /* 18h */
U32 Checksum; /* 1Ch */
U16 VendorId; /* 20h */
U16 ProductId; /* 22h */
MPI_FW_VERSION FWVersion; /* 24h */
U32 SeqCodeVersion; /* 28h */
U32 ImageSize; /* 2Ch */
U32 NextImageHeaderOffset; /* 30h */
U32 LoadStartAddress; /* 34h */
U32 IopResetVectorValue; /* 38h */
U32 IopResetRegAddr; /* 3Ch */
U32 VersionNameWhat; /* 40h */
U8 VersionName[32]; /* 44h */
U32 VendorNameWhat; /* 64h */
U8 VendorName[32]; /* 68h */
} MPI_FW_HEADER, MPI_POINTER PTR_MPI_FW_HEADER,
MpiFwHeader_t, MPI_POINTER pMpiFwHeader_t;
#define MPI_FW_HEADER_WHAT_SIGNATURE (0x29232840)
/* defines for using the ProductId field */
#define MPI_FW_HEADER_PID_TYPE_MASK (0xF000)
#define MPI_FW_HEADER_PID_TYPE_SCSI (0x0000)
#define MPI_FW_HEADER_PID_TYPE_FC (0x1000)
#define MPI_FW_HEADER_PID_TYPE_SAS (0x2000)
#define MPI_FW_HEADER_SIGNATURE_0 (0x5AEAA55A)
#define MPI_FW_HEADER_SIGNATURE_1 (0xA55AEAA5)
#define MPI_FW_HEADER_SIGNATURE_2 (0x5AA55AEA)
#define MPI_FW_HEADER_PID_PROD_MASK (0x0F00)
#define MPI_FW_HEADER_PID_PROD_INITIATOR_SCSI (0x0100)
#define MPI_FW_HEADER_PID_PROD_TARGET_INITIATOR_SCSI (0x0200)
#define MPI_FW_HEADER_PID_PROD_TARGET_SCSI (0x0300)
#define MPI_FW_HEADER_PID_PROD_IM_SCSI (0x0400)
#define MPI_FW_HEADER_PID_PROD_IS_SCSI (0x0500)
#define MPI_FW_HEADER_PID_PROD_CTX_SCSI (0x0600)
#define MPI_FW_HEADER_PID_PROD_IR_SCSI (0x0700)
#define MPI_FW_HEADER_PID_FAMILY_MASK (0x00FF)
/* SCSI */
#define MPI_FW_HEADER_PID_FAMILY_1030A0_SCSI (0x0001)
#define MPI_FW_HEADER_PID_FAMILY_1030B0_SCSI (0x0002)
#define MPI_FW_HEADER_PID_FAMILY_1030B1_SCSI (0x0003)
#define MPI_FW_HEADER_PID_FAMILY_1030C0_SCSI (0x0004)
#define MPI_FW_HEADER_PID_FAMILY_1020A0_SCSI (0x0005)
#define MPI_FW_HEADER_PID_FAMILY_1020B0_SCSI (0x0006)
#define MPI_FW_HEADER_PID_FAMILY_1020B1_SCSI (0x0007)
#define MPI_FW_HEADER_PID_FAMILY_1020C0_SCSI (0x0008)
#define MPI_FW_HEADER_PID_FAMILY_1035A0_SCSI (0x0009)
#define MPI_FW_HEADER_PID_FAMILY_1035B0_SCSI (0x000A)
#define MPI_FW_HEADER_PID_FAMILY_1030TA0_SCSI (0x000B)
#define MPI_FW_HEADER_PID_FAMILY_1020TA0_SCSI (0x000C)
/* Fibre Channel */
#define MPI_FW_HEADER_PID_FAMILY_909_FC (0x0000)
#define MPI_FW_HEADER_PID_FAMILY_919_FC (0x0001) /* 919 and 929 */
#define MPI_FW_HEADER_PID_FAMILY_919X_FC (0x0002) /* 919X and 929X */
#define MPI_FW_HEADER_PID_FAMILY_919XL_FC (0x0003) /* 919XL and 929XL */
#define MPI_FW_HEADER_PID_FAMILY_939X_FC (0x0004) /* 939X and 949X */
#define MPI_FW_HEADER_PID_FAMILY_959_FC (0x0005)
#define MPI_FW_HEADER_PID_FAMILY_949E_FC (0x0006)
/* SAS */
#define MPI_FW_HEADER_PID_FAMILY_1064_SAS (0x0001)
#define MPI_FW_HEADER_PID_FAMILY_1068_SAS (0x0002)
#define MPI_FW_HEADER_PID_FAMILY_1078_SAS (0x0003)
#define MPI_FW_HEADER_PID_FAMILY_106xE_SAS (0x0004) /* 1068E, 1066E, and 1064E */
typedef struct _MPI_EXT_IMAGE_HEADER
{
U8 ImageType; /* 00h */
U8 Reserved; /* 01h */
U16 Reserved1; /* 02h */
U32 Checksum; /* 04h */
U32 ImageSize; /* 08h */
U32 NextImageHeaderOffset; /* 0Ch */
U32 LoadStartAddress; /* 10h */
U32 Reserved2; /* 14h */
} MPI_EXT_IMAGE_HEADER, MPI_POINTER PTR_MPI_EXT_IMAGE_HEADER,
MpiExtImageHeader_t, MPI_POINTER pMpiExtImageHeader_t;
/* defines for the ImageType field */
#define MPI_EXT_IMAGE_TYPE_UNSPECIFIED (0x00)
#define MPI_EXT_IMAGE_TYPE_FW (0x01)
#define MPI_EXT_IMAGE_TYPE_NVDATA (0x03)
#define MPI_EXT_IMAGE_TYPE_BOOTLOADER (0x04)
#define MPI_EXT_IMAGE_TYPE_INITIALIZATION (0x05)
#endif
| impedimentToProgress/UCI-BlueChip | snapgear_linux/linux-2.6.21.1/drivers/message/fusion/lsi/mpi_ioc.h | C | mit | 58,797 |
// BrowseDialog.h
#ifndef __BROWSE_DIALOG_H
#define __BROWSE_DIALOG_H
#include "../../../Common/MyString.h"
bool MyBrowseForFolder(HWND owner, LPCWSTR title, LPCWSTR path, UString &resultPath);
bool MyBrowseForFile(HWND owner, LPCWSTR title, LPCWSTR path, LPCWSTR filterDescription, LPCWSTR filter, UString &resultPath);
/* CorrectFsPath removes undesirable characters in names (dots and spaces at the end of file)
But it doesn't change "bad" name in any of the following cases:
- path is Super Path (with \\?\ prefix)
- path is relative and relBase is Super Path
- there is file or dir in filesystem with specified "bad" name */
bool CorrectFsPath(const UString &relBase, const UString &path, UString &result);
bool Dlg_CreateFolder(HWND wnd, UString &destName);
#endif
| ghosthawkone/project-kompress | lzma1600/CPP/7zip/UI/FileManager/BrowseDialog.h | C | mit | 796 |
/*
* irq_comm.c: Common API for in kernel interrupt controller
* Copyright (c) 2007, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307 USA.
* Authors:
* Yaozu (Eddie) Dong <Eddie.dong@intel.com>
*
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*/
#include <linux/kvm_host.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <trace/events/kvm.h>
#include <asm/msidef.h>
#ifdef CONFIG_IA64
#include <asm/iosapic.h>
#endif
#include "irq.h"
#include "ioapic.h"
static int kvm_set_pic_irq(struct kvm_kernel_irq_routing_entry *e,
struct kvm *kvm, int irq_source_id, int level,
bool line_status)
{
#ifdef CONFIG_X86
struct kvm_pic *pic = pic_irqchip(kvm);
return kvm_pic_set_irq(pic, e->irqchip.pin, irq_source_id, level);
#else
return -1;
#endif
}
static int kvm_set_ioapic_irq(struct kvm_kernel_irq_routing_entry *e,
struct kvm *kvm, int irq_source_id, int level,
bool line_status)
{
struct kvm_ioapic *ioapic = kvm->arch.vioapic;
return kvm_ioapic_set_irq(ioapic, e->irqchip.pin, irq_source_id, level,
line_status);
}
inline static bool kvm_is_dm_lowest_prio(struct kvm_lapic_irq *irq)
{
#ifdef CONFIG_IA64
return irq->delivery_mode ==
(IOSAPIC_LOWEST_PRIORITY << IOSAPIC_DELIVERY_SHIFT);
#else
return irq->delivery_mode == APIC_DM_LOWEST;
#endif
}
int kvm_irq_delivery_to_apic(struct kvm *kvm, struct kvm_lapic *src,
struct kvm_lapic_irq *irq, unsigned long *dest_map)
{
int i, r = -1;
struct kvm_vcpu *vcpu, *lowest = NULL;
if (irq->dest_mode == 0 && irq->dest_id == 0xff &&
kvm_is_dm_lowest_prio(irq)) {
printk(KERN_INFO "kvm: apic: phys broadcast and lowest prio\n");
irq->delivery_mode = APIC_DM_FIXED;
}
if (kvm_irq_delivery_to_apic_fast(kvm, src, irq, &r, dest_map))
return r;
kvm_for_each_vcpu(i, vcpu, kvm) {
if (!kvm_apic_present(vcpu))
continue;
if (!kvm_apic_match_dest(vcpu, src, irq->shorthand,
irq->dest_id, irq->dest_mode))
continue;
if (!kvm_is_dm_lowest_prio(irq)) {
if (r < 0)
r = 0;
r += kvm_apic_set_irq(vcpu, irq, dest_map);
} else if (kvm_lapic_enabled(vcpu)) {
if (!lowest)
lowest = vcpu;
else if (kvm_apic_compare_prio(vcpu, lowest) < 0)
lowest = vcpu;
}
}
if (lowest)
r = kvm_apic_set_irq(lowest, irq, dest_map);
return r;
}
static inline void kvm_set_msi_irq(struct kvm_kernel_irq_routing_entry *e,
struct kvm_lapic_irq *irq)
{
trace_kvm_msi_set_irq(e->msi.address_lo, e->msi.data);
irq->dest_id = (e->msi.address_lo &
MSI_ADDR_DEST_ID_MASK) >> MSI_ADDR_DEST_ID_SHIFT;
irq->vector = (e->msi.data &
MSI_DATA_VECTOR_MASK) >> MSI_DATA_VECTOR_SHIFT;
irq->dest_mode = (1 << MSI_ADDR_DEST_MODE_SHIFT) & e->msi.address_lo;
irq->trig_mode = (1 << MSI_DATA_TRIGGER_SHIFT) & e->msi.data;
irq->delivery_mode = e->msi.data & 0x700;
irq->level = 1;
irq->shorthand = 0;
/* TODO Deal with RH bit of MSI message address */
}
int kvm_set_msi(struct kvm_kernel_irq_routing_entry *e,
struct kvm *kvm, int irq_source_id, int level, bool line_status)
{
struct kvm_lapic_irq irq;
if (!level)
return -1;
kvm_set_msi_irq(e, &irq);
return kvm_irq_delivery_to_apic(kvm, NULL, &irq, NULL);
}
static int kvm_set_msi_inatomic(struct kvm_kernel_irq_routing_entry *e,
struct kvm *kvm)
{
struct kvm_lapic_irq irq;
int r;
kvm_set_msi_irq(e, &irq);
if (kvm_irq_delivery_to_apic_fast(kvm, NULL, &irq, &r, NULL))
return r;
else
return -EWOULDBLOCK;
}
/*
* Deliver an IRQ in an atomic context if we can, or return a failure,
* user can retry in a process context.
* Return value:
* -EWOULDBLOCK - Can't deliver in atomic context: retry in a process context.
* Other values - No need to retry.
*/
int kvm_set_irq_inatomic(struct kvm *kvm, int irq_source_id, u32 irq, int level)
{
struct kvm_kernel_irq_routing_entry *e;
int ret = -EINVAL;
struct kvm_irq_routing_table *irq_rt;
int idx;
trace_kvm_set_irq(irq, level, irq_source_id);
/*
* Injection into either PIC or IOAPIC might need to scan all CPUs,
* which would need to be retried from thread context; when same GSI
* is connected to both PIC and IOAPIC, we'd have to report a
* partial failure here.
* Since there's no easy way to do this, we only support injecting MSI
* which is limited to 1:1 GSI mapping.
*/
idx = srcu_read_lock(&kvm->irq_srcu);
irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
if (irq < irq_rt->nr_rt_entries)
hlist_for_each_entry(e, &irq_rt->map[irq], link) {
if (likely(e->type == KVM_IRQ_ROUTING_MSI))
ret = kvm_set_msi_inatomic(e, kvm);
else
ret = -EWOULDBLOCK;
break;
}
srcu_read_unlock(&kvm->irq_srcu, idx);
return ret;
}
int kvm_request_irq_source_id(struct kvm *kvm)
{
unsigned long *bitmap = &kvm->arch.irq_sources_bitmap;
int irq_source_id;
mutex_lock(&kvm->irq_lock);
irq_source_id = find_first_zero_bit(bitmap, BITS_PER_LONG);
if (irq_source_id >= BITS_PER_LONG) {
printk(KERN_WARNING "kvm: exhaust allocatable IRQ sources!\n");
irq_source_id = -EFAULT;
goto unlock;
}
ASSERT(irq_source_id != KVM_USERSPACE_IRQ_SOURCE_ID);
#ifdef CONFIG_X86
ASSERT(irq_source_id != KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID);
#endif
set_bit(irq_source_id, bitmap);
unlock:
mutex_unlock(&kvm->irq_lock);
return irq_source_id;
}
void kvm_free_irq_source_id(struct kvm *kvm, int irq_source_id)
{
ASSERT(irq_source_id != KVM_USERSPACE_IRQ_SOURCE_ID);
#ifdef CONFIG_X86
ASSERT(irq_source_id != KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID);
#endif
mutex_lock(&kvm->irq_lock);
if (irq_source_id < 0 ||
irq_source_id >= BITS_PER_LONG) {
printk(KERN_ERR "kvm: IRQ source ID out of range!\n");
goto unlock;
}
clear_bit(irq_source_id, &kvm->arch.irq_sources_bitmap);
if (!irqchip_in_kernel(kvm))
goto unlock;
kvm_ioapic_clear_all(kvm->arch.vioapic, irq_source_id);
#ifdef CONFIG_X86
kvm_pic_clear_all(pic_irqchip(kvm), irq_source_id);
#endif
unlock:
mutex_unlock(&kvm->irq_lock);
}
void kvm_register_irq_mask_notifier(struct kvm *kvm, int irq,
struct kvm_irq_mask_notifier *kimn)
{
mutex_lock(&kvm->irq_lock);
kimn->irq = irq;
hlist_add_head_rcu(&kimn->link, &kvm->mask_notifier_list);
mutex_unlock(&kvm->irq_lock);
}
void kvm_unregister_irq_mask_notifier(struct kvm *kvm, int irq,
struct kvm_irq_mask_notifier *kimn)
{
mutex_lock(&kvm->irq_lock);
hlist_del_rcu(&kimn->link);
mutex_unlock(&kvm->irq_lock);
synchronize_srcu(&kvm->irq_srcu);
}
void kvm_fire_mask_notifiers(struct kvm *kvm, unsigned irqchip, unsigned pin,
bool mask)
{
struct kvm_irq_mask_notifier *kimn;
int idx, gsi;
idx = srcu_read_lock(&kvm->irq_srcu);
gsi = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu)->chip[irqchip][pin];
if (gsi != -1)
hlist_for_each_entry_rcu(kimn, &kvm->mask_notifier_list, link)
if (kimn->irq == gsi)
kimn->func(kimn, mask);
srcu_read_unlock(&kvm->irq_srcu, idx);
}
int kvm_set_routing_entry(struct kvm_irq_routing_table *rt,
struct kvm_kernel_irq_routing_entry *e,
const struct kvm_irq_routing_entry *ue)
{
int r = -EINVAL;
int delta;
unsigned max_pin;
switch (ue->type) {
case KVM_IRQ_ROUTING_IRQCHIP:
delta = 0;
switch (ue->u.irqchip.irqchip) {
case KVM_IRQCHIP_PIC_MASTER:
e->set = kvm_set_pic_irq;
max_pin = PIC_NUM_PINS;
break;
case KVM_IRQCHIP_PIC_SLAVE:
e->set = kvm_set_pic_irq;
max_pin = PIC_NUM_PINS;
delta = 8;
break;
case KVM_IRQCHIP_IOAPIC:
max_pin = KVM_IOAPIC_NUM_PINS;
e->set = kvm_set_ioapic_irq;
break;
default:
goto out;
}
e->irqchip.irqchip = ue->u.irqchip.irqchip;
e->irqchip.pin = ue->u.irqchip.pin + delta;
if (e->irqchip.pin >= max_pin)
goto out;
rt->chip[ue->u.irqchip.irqchip][e->irqchip.pin] = ue->gsi;
break;
case KVM_IRQ_ROUTING_MSI:
e->set = kvm_set_msi;
e->msi.address_lo = ue->u.msi.address_lo;
e->msi.address_hi = ue->u.msi.address_hi;
e->msi.data = ue->u.msi.data;
break;
default:
goto out;
}
r = 0;
out:
return r;
}
#define IOAPIC_ROUTING_ENTRY(irq) \
{ .gsi = irq, .type = KVM_IRQ_ROUTING_IRQCHIP, \
.u.irqchip.irqchip = KVM_IRQCHIP_IOAPIC, .u.irqchip.pin = (irq) }
#define ROUTING_ENTRY1(irq) IOAPIC_ROUTING_ENTRY(irq)
#ifdef CONFIG_X86
# define PIC_ROUTING_ENTRY(irq) \
{ .gsi = irq, .type = KVM_IRQ_ROUTING_IRQCHIP, \
.u.irqchip.irqchip = SELECT_PIC(irq), .u.irqchip.pin = (irq) % 8 }
# define ROUTING_ENTRY2(irq) \
IOAPIC_ROUTING_ENTRY(irq), PIC_ROUTING_ENTRY(irq)
#else
# define ROUTING_ENTRY2(irq) \
IOAPIC_ROUTING_ENTRY(irq)
#endif
static const struct kvm_irq_routing_entry default_routing[] = {
ROUTING_ENTRY2(0), ROUTING_ENTRY2(1),
ROUTING_ENTRY2(2), ROUTING_ENTRY2(3),
ROUTING_ENTRY2(4), ROUTING_ENTRY2(5),
ROUTING_ENTRY2(6), ROUTING_ENTRY2(7),
ROUTING_ENTRY2(8), ROUTING_ENTRY2(9),
ROUTING_ENTRY2(10), ROUTING_ENTRY2(11),
ROUTING_ENTRY2(12), ROUTING_ENTRY2(13),
ROUTING_ENTRY2(14), ROUTING_ENTRY2(15),
ROUTING_ENTRY1(16), ROUTING_ENTRY1(17),
ROUTING_ENTRY1(18), ROUTING_ENTRY1(19),
ROUTING_ENTRY1(20), ROUTING_ENTRY1(21),
ROUTING_ENTRY1(22), ROUTING_ENTRY1(23),
#ifdef CONFIG_IA64
ROUTING_ENTRY1(24), ROUTING_ENTRY1(25),
ROUTING_ENTRY1(26), ROUTING_ENTRY1(27),
ROUTING_ENTRY1(28), ROUTING_ENTRY1(29),
ROUTING_ENTRY1(30), ROUTING_ENTRY1(31),
ROUTING_ENTRY1(32), ROUTING_ENTRY1(33),
ROUTING_ENTRY1(34), ROUTING_ENTRY1(35),
ROUTING_ENTRY1(36), ROUTING_ENTRY1(37),
ROUTING_ENTRY1(38), ROUTING_ENTRY1(39),
ROUTING_ENTRY1(40), ROUTING_ENTRY1(41),
ROUTING_ENTRY1(42), ROUTING_ENTRY1(43),
ROUTING_ENTRY1(44), ROUTING_ENTRY1(45),
ROUTING_ENTRY1(46), ROUTING_ENTRY1(47),
#endif
};
int kvm_setup_default_irq_routing(struct kvm *kvm)
{
return kvm_set_irq_routing(kvm, default_routing,
ARRAY_SIZE(default_routing), 0);
}
| shirishpargaonkar/cifsclient | virt/kvm/irq_comm.c | C | gpl-2.0 | 10,324 |
/**
File Name: expression-014.js
Corresponds To: ecma/Expressions/11.2.2-9-n.js
ECMA Section: 11.2.2. The new operator
Description:
Author: christine@netscape.com
Date: 12 november 1997
*/
var SECTION = "expression-014.js";
var VERSION = "ECMA_1";
var TITLE = "The new operator";
var BUGNUMBER= "327765";
startTest();
writeHeaderToLog( SECTION + " "+ TITLE);
var tc = 0;
var testcases = new Array();
var BOOLEAN = new Boolean();
var result = "Failed";
var exception = "No exception thrown";
var expect = "Passed";
try {
result = new BOOLEAN();
} catch ( e ) {
result = expect;
exception = e.toString();
}
testcases[tc++] = new TestCase(
SECTION,
"BOOLEAN = new Boolean(); result = new BOOLEAN()" +
" (threw " + exception +")",
expect,
result );
test();
| danialbehzadi/Nokia-RM-1013-2.0.0.11 | webkit/Source/JavaScriptCore/tests/mozilla/ecma_2/Exceptions/expression-014.js | JavaScript | gpl-3.0 | 966 |
/* linux/arch/arm/plat-samsung/include/plat/dma-s3c24xx.h
*
* Copyright (C) 2006 Simtec Electronics
* Ben Dooks <ben@simtec.co.uk>
*
* Samsung S3C24XX DMA support - per SoC functions
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <plat/dma-core.h>
extern struct bus_type dma_subsys;
extern struct s3c2410_dma_chan s3c2410_chans[S3C_DMA_CHANNELS];
#define DMA_CH_VALID (1<<31)
#define DMA_CH_NEVER (1<<30)
/* struct s3c24xx_dma_map
*
* this holds the mapping information for the channel selected
* to be connected to the specified device
*/
struct s3c24xx_dma_map {
const char *name;
unsigned long channels[S3C_DMA_CHANNELS];
};
struct s3c24xx_dma_selection {
struct s3c24xx_dma_map *map;
unsigned long map_size;
unsigned long dcon_mask;
void (*select)(struct s3c2410_dma_chan *chan,
struct s3c24xx_dma_map *map);
};
extern int s3c24xx_dma_init_map(struct s3c24xx_dma_selection *sel);
/* struct s3c24xx_dma_order_ch
*
* channel map for one of the `enum dma_ch` dma channels. the list
* entry contains a set of low-level channel numbers, orred with
* DMA_CH_VALID, which are checked in the order in the array.
*/
struct s3c24xx_dma_order_ch {
unsigned int list[S3C_DMA_CHANNELS]; /* list of channels */
unsigned int flags; /* flags */
};
/* struct s3c24xx_dma_order
*
* information provided by either the core or the board to give the
* dma system a hint on how to allocate channels
*/
struct s3c24xx_dma_order {
struct s3c24xx_dma_order_ch channels[DMACH_MAX];
};
extern int s3c24xx_dma_order_set(struct s3c24xx_dma_order *map);
/* DMA init code, called from the cpu support code */
extern int s3c2410_dma_init(void);
extern int s3c24xx_dma_init(unsigned int channels, unsigned int irq,
unsigned int stride);
| mericon/Xp_Kernel_LGH850 | virt/arch/arm/plat-samsung/include/plat/dma-s3c24xx.h | C | gpl-2.0 | 1,928 |
/****************************************************************************
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
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.
****************************************************************************/
#ifndef __cocos2d_libs__CCCustomEventListener__
#define __cocos2d_libs__CCCustomEventListener__
#include "base/CCEventListener.h"
/**
* @addtogroup base
* @{
*/
NS_CC_BEGIN
class EventCustom;
/** @class EventListenerCustom
* @brief Custom event listener.
* @code Usage:
* auto dispatcher = Director::getInstance()->getEventDispatcher();
* Adds a listener:
*
* auto callback = [](EventCustom* event){ do_some_thing(); };
* auto listener = EventListenerCustom::create(callback);
* dispatcher->addEventListenerWithSceneGraphPriority(listener, one_node);
*
* Dispatchs a custom event:
*
* EventCustom event("your_event_type");
* dispatcher->dispatchEvent(&event);
*
* Removes a listener
*
* dispatcher->removeEventListener(listener);
* \endcode
* @js cc._EventListenerCustom
*/
class CC_DLL EventListenerCustom : public EventListener
{
public:
/** Creates an event listener with type and callback.
* @param eventName The type of the event.
* @param callback The callback function when the specified event was emitted.
* @return An autoreleased EventListenerCustom object.
*/
static EventListenerCustom* create(const std::string& eventName, const std::function<void(EventCustom*)>& callback);
/// Overrides
virtual bool checkAvailable() override;
virtual EventListenerCustom* clone() override;
CC_CONSTRUCTOR_ACCESS:
/** Constructor */
EventListenerCustom();
/** Initializes event with type and callback function */
bool init(const ListenerID& listenerId, const std::function<void(EventCustom*)>& callback);
protected:
std::function<void(EventCustom*)> _onCustomEvent;
friend class LuaEventListenerCustom;
};
NS_CC_END
// end of base group
/// @}
#endif /* defined(__cocos2d_libs__CCCustomEventListener__) */
| dios-game/dios-cocos | src/oslibs/cocos/cocos-src/cocos/base/CCEventListenerCustom.h | C | mit | 3,164 |
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var AsyncAction_1 = require('./AsyncAction');
var AsyncScheduler_1 = require('./AsyncScheduler');
var VirtualTimeScheduler = (function (_super) {
__extends(VirtualTimeScheduler, _super);
function VirtualTimeScheduler(SchedulerAction, maxFrames) {
var _this = this;
if (SchedulerAction === void 0) { SchedulerAction = VirtualAction; }
if (maxFrames === void 0) { maxFrames = Number.POSITIVE_INFINITY; }
_super.call(this, SchedulerAction, function () { return _this.frame; });
this.maxFrames = maxFrames;
this.frame = 0;
this.index = -1;
}
/**
* Prompt the Scheduler to execute all of its queued actions, therefore
* clearing its queue.
* @return {void}
*/
VirtualTimeScheduler.prototype.flush = function () {
var _a = this, actions = _a.actions, maxFrames = _a.maxFrames;
var error, action;
while ((action = actions.shift()) && (this.frame = action.delay) <= maxFrames) {
if (error = action.execute(action.state, action.delay)) {
break;
}
}
if (error) {
while (action = actions.shift()) {
action.unsubscribe();
}
throw error;
}
};
VirtualTimeScheduler.frameTimeFactor = 10;
return VirtualTimeScheduler;
}(AsyncScheduler_1.AsyncScheduler));
exports.VirtualTimeScheduler = VirtualTimeScheduler;
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var VirtualAction = (function (_super) {
__extends(VirtualAction, _super);
function VirtualAction(scheduler, work, index) {
if (index === void 0) { index = scheduler.index += 1; }
_super.call(this, scheduler, work);
this.scheduler = scheduler;
this.work = work;
this.index = index;
this.index = scheduler.index = index;
}
VirtualAction.prototype.schedule = function (state, delay) {
if (delay === void 0) { delay = 0; }
if (!this.id) {
return _super.prototype.schedule.call(this, state, delay);
}
// If an action is rescheduled, we save allocations by mutating its state,
// pushing it to the end of the scheduler queue, and recycling the action.
// But since the VirtualTimeScheduler is used for testing, VirtualActions
// must be immutable so they can be inspected later.
var action = new VirtualAction(this.scheduler, this.work);
this.add(action);
return action.schedule(state, delay);
};
VirtualAction.prototype.requestAsyncId = function (scheduler, id, delay) {
if (delay === void 0) { delay = 0; }
this.delay = scheduler.frame + delay;
var actions = scheduler.actions;
actions.push(this);
actions.sort(VirtualAction.sortActions);
return true;
};
VirtualAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
if (delay === void 0) { delay = 0; }
return undefined;
};
VirtualAction.sortActions = function (a, b) {
if (a.delay === b.delay) {
if (a.index === b.index) {
return 0;
}
else if (a.index > b.index) {
return 1;
}
else {
return -1;
}
}
else if (a.delay > b.delay) {
return 1;
}
else {
return -1;
}
};
return VirtualAction;
}(AsyncAction_1.AsyncAction));
exports.VirtualAction = VirtualAction;
//# sourceMappingURL=VirtualTimeScheduler.js.map | diegojromerolopez/djanban | src/djanban/static/angularapps/taskboard/node_modules/rxjs/scheduler/VirtualTimeScheduler.js | JavaScript | mit | 3,914 |
#!/bin/sh
#
# Copyright (c) 2005 Amos Waterland
#
test_description='git branch assorted tests'
. ./test-lib.sh
test_expect_success 'prepare a trivial repository' '
echo Hello >A &&
git update-index --add A &&
git commit -m "Initial commit." &&
echo World >>A &&
git update-index --add A &&
git commit -m "Second commit." &&
HEAD=$(git rev-parse --verify HEAD)
'
test_expect_success 'git branch --help should not have created a bogus branch' '
test_might_fail git branch --man --help </dev/null >/dev/null 2>&1 &&
test_path_is_missing .git/refs/heads/--help
'
test_expect_success 'branch -h in broken repository' '
mkdir broken &&
(
cd broken &&
git init &&
>.git/refs/heads/master &&
test_expect_code 129 git branch -h >usage 2>&1
) &&
test_i18ngrep "[Uu]sage" broken/usage
'
test_expect_success 'git branch abc should create a branch' '
git branch abc && test_path_is_file .git/refs/heads/abc
'
test_expect_success 'git branch a/b/c should create a branch' '
git branch a/b/c && test_path_is_file .git/refs/heads/a/b/c
'
test_expect_success 'git branch HEAD should fail' '
test_must_fail git branch HEAD
'
cat >expect <<EOF
$_z40 $HEAD $GIT_COMMITTER_NAME <$GIT_COMMITTER_EMAIL> 1117150200 +0000 branch: Created from master
EOF
test_expect_success 'git branch -l d/e/f should create a branch and a log' '
GIT_COMMITTER_DATE="2005-05-26 23:30" \
git branch -l d/e/f &&
test_path_is_file .git/refs/heads/d/e/f &&
test_path_is_file .git/logs/refs/heads/d/e/f &&
test_cmp expect .git/logs/refs/heads/d/e/f
'
test_expect_success 'git branch -d d/e/f should delete a branch and a log' '
git branch -d d/e/f &&
test_path_is_missing .git/refs/heads/d/e/f &&
test_path_is_missing .git/logs/refs/heads/d/e/f
'
test_expect_success 'git branch j/k should work after branch j has been deleted' '
git branch j &&
git branch -d j &&
git branch j/k
'
test_expect_success 'git branch l should work after branch l/m has been deleted' '
git branch l/m &&
git branch -d l/m &&
git branch l
'
test_expect_success 'git branch -m dumps usage' '
test_expect_code 128 git branch -m 2>err &&
test_i18ngrep "branch name required" err
'
test_expect_success 'git branch -m m m/m should work' '
git branch -l m &&
git branch -m m m/m &&
test_path_is_file .git/logs/refs/heads/m/m
'
test_expect_success 'git branch -m n/n n should work' '
git branch -l n/n &&
git branch -m n/n n &&
test_path_is_file .git/logs/refs/heads/n
'
test_expect_success 'git branch -m o/o o should fail when o/p exists' '
git branch o/o &&
git branch o/p &&
test_must_fail git branch -m o/o o
'
test_expect_success 'git branch -m q r/q should fail when r exists' '
git branch q &&
git branch r &&
test_must_fail git branch -m q r/q
'
test_expect_success 'git branch -M foo bar should fail when bar is checked out' '
git branch bar &&
git checkout -b foo &&
test_must_fail git branch -M bar foo
'
test_expect_success 'git branch -M baz bam should succeed when baz is checked out' '
git checkout -b baz &&
git branch bam &&
git branch -M baz bam
'
test_expect_success 'git branch -M master should work when master is checked out' '
git checkout master &&
git branch -M master
'
test_expect_success 'git branch -M master master should work when master is checked out' '
git checkout master &&
git branch -M master master
'
test_expect_success 'git branch -M master2 master2 should work when master is checked out' '
git checkout master &&
git branch master2 &&
git branch -M master2 master2
'
test_expect_success 'git branch -v -d t should work' '
git branch t &&
test_path_is_file .git/refs/heads/t &&
git branch -v -d t &&
test_path_is_missing .git/refs/heads/t
'
test_expect_success 'git branch -v -m t s should work' '
git branch t &&
test_path_is_file .git/refs/heads/t &&
git branch -v -m t s &&
test_path_is_missing .git/refs/heads/t &&
test_path_is_file .git/refs/heads/s &&
git branch -d s
'
test_expect_success 'git branch -m -d t s should fail' '
git branch t &&
test_path_is_file .git/refs/heads/t &&
test_must_fail git branch -m -d t s &&
git branch -d t &&
test_path_is_missing .git/refs/heads/t
'
test_expect_success 'git branch --list -d t should fail' '
git branch t &&
test_path_is_file .git/refs/heads/t &&
test_must_fail git branch --list -d t &&
git branch -d t &&
test_path_is_missing .git/refs/heads/t
'
test_expect_success 'git branch --column' '
COLUMNS=81 git branch --column=column >actual &&
cat >expected <<\EOF &&
a/b/c bam foo l * master n o/p r
abc bar j/k m/m master2 o/o q
EOF
test_cmp expected actual
'
test_expect_success 'git branch --column with an extremely long branch name' '
long=this/is/a/part/of/long/branch/name &&
long=z$long/$long/$long/$long &&
test_when_finished "git branch -d $long" &&
git branch $long &&
COLUMNS=80 git branch --column=column >actual &&
cat >expected <<EOF &&
a/b/c
abc
bam
bar
foo
j/k
l
m/m
* master
master2
n
o/o
o/p
q
r
$long
EOF
test_cmp expected actual
'
test_expect_success 'git branch with column.*' '
git config column.ui column &&
git config column.branch "dense" &&
COLUMNS=80 git branch >actual &&
git config --unset column.branch &&
git config --unset column.ui &&
cat >expected <<\EOF &&
a/b/c bam foo l * master n o/p r
abc bar j/k m/m master2 o/o q
EOF
test_cmp expected actual
'
test_expect_success 'git branch --column -v should fail' '
test_must_fail git branch --column -v
'
test_expect_success 'git branch -v with column.ui ignored' '
git config column.ui column &&
COLUMNS=80 git branch -v | cut -c -10 | sed "s/ *$//" >actual &&
git config --unset column.ui &&
cat >expected <<\EOF &&
a/b/c
abc
bam
bar
foo
j/k
l
m/m
* master
master2
n
o/o
o/p
q
r
EOF
test_cmp expected actual
'
mv .git/config .git/config-saved
test_expect_success 'git branch -m q q2 without config should succeed' '
git branch -m q q2 &&
git branch -m q2 q
'
mv .git/config-saved .git/config
git config branch.s/s.dummy Hello
test_expect_success 'git branch -m s/s s should work when s/t is deleted' '
git branch -l s/s &&
test_path_is_file .git/logs/refs/heads/s/s &&
git branch -l s/t &&
test_path_is_file .git/logs/refs/heads/s/t &&
git branch -d s/t &&
git branch -m s/s s &&
test_path_is_file .git/logs/refs/heads/s
'
test_expect_success 'config information was renamed, too' '
test $(git config branch.s.dummy) = Hello &&
test_must_fail git config branch.s/s/dummy
'
test_expect_success 'deleting a symref' '
git branch target &&
git symbolic-ref refs/heads/symref refs/heads/target &&
echo "Deleted branch symref (was refs/heads/target)." >expect &&
git branch -d symref >actual &&
test_path_is_file .git/refs/heads/target &&
test_path_is_missing .git/refs/heads/symref &&
test_i18ncmp expect actual
'
test_expect_success 'deleting a dangling symref' '
git symbolic-ref refs/heads/dangling-symref nowhere &&
test_path_is_file .git/refs/heads/dangling-symref &&
echo "Deleted branch dangling-symref (was nowhere)." >expect &&
git branch -d dangling-symref >actual &&
test_path_is_missing .git/refs/heads/dangling-symref &&
test_i18ncmp expect actual
'
test_expect_success 'renaming a symref is not allowed' '
git symbolic-ref refs/heads/master2 refs/heads/master &&
test_must_fail git branch -m master2 master3 &&
git symbolic-ref refs/heads/master2 &&
test_path_is_file .git/refs/heads/master &&
test_path_is_missing .git/refs/heads/master3
'
test_expect_success SYMLINKS 'git branch -m u v should fail when the reflog for u is a symlink' '
git branch -l u &&
mv .git/logs/refs/heads/u real-u &&
ln -s real-u .git/logs/refs/heads/u &&
test_must_fail git branch -m u v
'
test_expect_success 'test tracking setup via --track' '
git config remote.local.url . &&
git config remote.local.fetch refs/heads/*:refs/remotes/local/* &&
(git show-ref -q refs/remotes/local/master || git fetch local) &&
git branch --track my1 local/master &&
test $(git config branch.my1.remote) = local &&
test $(git config branch.my1.merge) = refs/heads/master
'
test_expect_success 'test tracking setup (non-wildcard, matching)' '
git config remote.local.url . &&
git config remote.local.fetch refs/heads/master:refs/remotes/local/master &&
(git show-ref -q refs/remotes/local/master || git fetch local) &&
git branch --track my4 local/master &&
test $(git config branch.my4.remote) = local &&
test $(git config branch.my4.merge) = refs/heads/master
'
test_expect_success 'tracking setup fails on non-matching refspec' '
git config remote.local.url . &&
git config remote.local.fetch refs/heads/*:refs/remotes/local/* &&
(git show-ref -q refs/remotes/local/master || git fetch local) &&
git config remote.local.fetch refs/heads/s:refs/remotes/local/s &&
test_must_fail git branch --track my5 local/master &&
test_must_fail git config branch.my5.remote &&
test_must_fail git config branch.my5.merge
'
test_expect_success 'test tracking setup via config' '
git config branch.autosetupmerge true &&
git config remote.local.url . &&
git config remote.local.fetch refs/heads/*:refs/remotes/local/* &&
(git show-ref -q refs/remotes/local/master || git fetch local) &&
git branch my3 local/master &&
test $(git config branch.my3.remote) = local &&
test $(git config branch.my3.merge) = refs/heads/master
'
test_expect_success 'test overriding tracking setup via --no-track' '
git config branch.autosetupmerge true &&
git config remote.local.url . &&
git config remote.local.fetch refs/heads/*:refs/remotes/local/* &&
(git show-ref -q refs/remotes/local/master || git fetch local) &&
git branch --no-track my2 local/master &&
git config branch.autosetupmerge false &&
! test "$(git config branch.my2.remote)" = local &&
! test "$(git config branch.my2.merge)" = refs/heads/master
'
test_expect_success 'no tracking without .fetch entries' '
git config branch.autosetupmerge true &&
git branch my6 s &&
git config branch.autosetupmerge false &&
test -z "$(git config branch.my6.remote)" &&
test -z "$(git config branch.my6.merge)"
'
test_expect_success 'test tracking setup via --track but deeper' '
git config remote.local.url . &&
git config remote.local.fetch refs/heads/*:refs/remotes/local/* &&
(git show-ref -q refs/remotes/local/o/o || git fetch local) &&
git branch --track my7 local/o/o &&
test "$(git config branch.my7.remote)" = local &&
test "$(git config branch.my7.merge)" = refs/heads/o/o
'
test_expect_success 'test deleting branch deletes branch config' '
git branch -d my7 &&
test -z "$(git config branch.my7.remote)" &&
test -z "$(git config branch.my7.merge)"
'
test_expect_success 'test deleting branch without config' '
git branch my7 s &&
sha1=$(git rev-parse my7 | cut -c 1-7) &&
echo "Deleted branch my7 (was $sha1)." >expect &&
git branch -d my7 >actual 2>&1 &&
test_i18ncmp expect actual
'
test_expect_success 'test --track without .fetch entries' '
git branch --track my8 &&
test "$(git config branch.my8.remote)" &&
test "$(git config branch.my8.merge)"
'
test_expect_success 'branch from non-branch HEAD w/autosetupmerge=always' '
git config branch.autosetupmerge always &&
git branch my9 HEAD^ &&
git config branch.autosetupmerge false
'
test_expect_success 'branch from non-branch HEAD w/--track causes failure' '
test_must_fail git branch --track my10 HEAD^
'
test_expect_success 'branch from tag w/--track causes failure' '
git tag foobar &&
test_must_fail git branch --track my11 foobar
'
test_expect_success '--set-upstream-to fails on multiple branches' '
test_must_fail git branch --set-upstream-to master a b c
'
test_expect_success '--set-upstream-to fails on detached HEAD' '
git checkout HEAD^{} &&
test_must_fail git branch --set-upstream-to master &&
git checkout -
'
test_expect_success '--set-upstream-to fails on a missing dst branch' '
test_must_fail git branch --set-upstream-to master does-not-exist
'
test_expect_success '--set-upstream-to fails on a missing src branch' '
test_must_fail git branch --set-upstream-to does-not-exist master
'
test_expect_success '--set-upstream-to fails on a non-ref' '
test_must_fail git branch --set-upstream-to HEAD^{}
'
test_expect_success 'use --set-upstream-to modify HEAD' '
test_config branch.master.remote foo &&
test_config branch.master.merge foo &&
git branch my12 &&
git branch --set-upstream-to my12 &&
test "$(git config branch.master.remote)" = "." &&
test "$(git config branch.master.merge)" = "refs/heads/my12"
'
test_expect_success 'use --set-upstream-to modify a particular branch' '
git branch my13 &&
git branch --set-upstream-to master my13 &&
test "$(git config branch.my13.remote)" = "." &&
test "$(git config branch.my13.merge)" = "refs/heads/master"
'
test_expect_success '--unset-upstream should fail if given a non-existent branch' '
test_must_fail git branch --unset-upstream i-dont-exist
'
test_expect_success 'test --unset-upstream on HEAD' '
git branch my14 &&
test_config branch.master.remote foo &&
test_config branch.master.merge foo &&
git branch --set-upstream-to my14 &&
git branch --unset-upstream &&
test_must_fail git config branch.master.remote &&
test_must_fail git config branch.master.merge &&
# fail for a branch without upstream set
test_must_fail git branch --unset-upstream
'
test_expect_success '--unset-upstream should fail on multiple branches' '
test_must_fail git branch --unset-upstream a b c
'
test_expect_success '--unset-upstream should fail on detached HEAD' '
git checkout HEAD^{} &&
test_must_fail git branch --unset-upstream &&
git checkout -
'
test_expect_success 'test --unset-upstream on a particular branch' '
git branch my15 &&
git branch --set-upstream-to master my14 &&
git branch --unset-upstream my14 &&
test_must_fail git config branch.my14.remote &&
test_must_fail git config branch.my14.merge
'
test_expect_success '--set-upstream shows message when creating a new branch that exists as remote-tracking' '
git update-ref refs/remotes/origin/master HEAD &&
git branch --set-upstream origin/master 2>actual &&
test_when_finished git update-ref -d refs/remotes/origin/master &&
test_when_finished git branch -d origin/master &&
cat >expected <<EOF &&
The --set-upstream flag is deprecated and will be removed. Consider using --track or --set-upstream-to
If you wanted to make '"'master'"' track '"'origin/master'"', do this:
git branch -d origin/master
git branch --set-upstream-to origin/master
EOF
test_cmp expected actual
'
test_expect_success '--set-upstream with two args only shows the deprecation message' '
git branch --set-upstream master my13 2>actual &&
test_when_finished git branch --unset-upstream master &&
cat >expected <<EOF &&
The --set-upstream flag is deprecated and will be removed. Consider using --track or --set-upstream-to
EOF
test_cmp expected actual
'
test_expect_success '--set-upstream with one arg only shows the deprecation message if the branch existed' '
git branch --set-upstream my13 2>actual &&
test_when_finished git branch --unset-upstream my13 &&
cat >expected <<EOF &&
The --set-upstream flag is deprecated and will be removed. Consider using --track or --set-upstream-to
EOF
test_cmp expected actual
'
test_expect_success '--set-upstream-to notices an error to set branch as own upstream' '
git branch --set-upstream-to refs/heads/my13 my13 2>actual &&
cat >expected <<-\EOF &&
warning: Not setting branch my13 as its own upstream.
EOF
test_expect_code 1 git config branch.my13.remote &&
test_expect_code 1 git config branch.my13.merge &&
test_i18ncmp expected actual
'
# Keep this test last, as it changes the current branch
cat >expect <<EOF
$_z40 $HEAD $GIT_COMMITTER_NAME <$GIT_COMMITTER_EMAIL> 1117150200 +0000 branch: Created from master
EOF
test_expect_success 'git checkout -b g/h/i -l should create a branch and a log' '
GIT_COMMITTER_DATE="2005-05-26 23:30" \
git checkout -b g/h/i -l master &&
test_path_is_file .git/refs/heads/g/h/i &&
test_path_is_file .git/logs/refs/heads/g/h/i &&
test_cmp expect .git/logs/refs/heads/g/h/i
'
test_expect_success 'checkout -b makes reflog by default' '
git checkout master &&
git config --unset core.logAllRefUpdates &&
git checkout -b alpha &&
git rev-parse --verify alpha@{0}
'
test_expect_success 'checkout -b does not make reflog when core.logAllRefUpdates = false' '
git checkout master &&
git config core.logAllRefUpdates false &&
git checkout -b beta &&
test_must_fail git rev-parse --verify beta@{0}
'
test_expect_success 'checkout -b with -l makes reflog when core.logAllRefUpdates = false' '
git checkout master &&
git checkout -lb gamma &&
git config --unset core.logAllRefUpdates &&
git rev-parse --verify gamma@{0}
'
test_expect_success 'avoid ambiguous track' '
git config branch.autosetupmerge true &&
git config remote.ambi1.url lalala &&
git config remote.ambi1.fetch refs/heads/lalala:refs/heads/master &&
git config remote.ambi2.url lilili &&
git config remote.ambi2.fetch refs/heads/lilili:refs/heads/master &&
git branch all1 master &&
test -z "$(git config branch.all1.merge)"
'
test_expect_success 'autosetuprebase local on a tracked local branch' '
git config remote.local.url . &&
git config remote.local.fetch refs/heads/*:refs/remotes/local/* &&
git config branch.autosetuprebase local &&
(git show-ref -q refs/remotes/local/o || git fetch local) &&
git branch mybase &&
git branch --track myr1 mybase &&
test "$(git config branch.myr1.remote)" = . &&
test "$(git config branch.myr1.merge)" = refs/heads/mybase &&
test "$(git config branch.myr1.rebase)" = true
'
test_expect_success 'autosetuprebase always on a tracked local branch' '
git config remote.local.url . &&
git config remote.local.fetch refs/heads/*:refs/remotes/local/* &&
git config branch.autosetuprebase always &&
(git show-ref -q refs/remotes/local/o || git fetch local) &&
git branch mybase2 &&
git branch --track myr2 mybase &&
test "$(git config branch.myr2.remote)" = . &&
test "$(git config branch.myr2.merge)" = refs/heads/mybase &&
test "$(git config branch.myr2.rebase)" = true
'
test_expect_success 'autosetuprebase remote on a tracked local branch' '
git config remote.local.url . &&
git config remote.local.fetch refs/heads/*:refs/remotes/local/* &&
git config branch.autosetuprebase remote &&
(git show-ref -q refs/remotes/local/o || git fetch local) &&
git branch mybase3 &&
git branch --track myr3 mybase2 &&
test "$(git config branch.myr3.remote)" = . &&
test "$(git config branch.myr3.merge)" = refs/heads/mybase2 &&
! test "$(git config branch.myr3.rebase)" = true
'
test_expect_success 'autosetuprebase never on a tracked local branch' '
git config remote.local.url . &&
git config remote.local.fetch refs/heads/*:refs/remotes/local/* &&
git config branch.autosetuprebase never &&
(git show-ref -q refs/remotes/local/o || git fetch local) &&
git branch mybase4 &&
git branch --track myr4 mybase2 &&
test "$(git config branch.myr4.remote)" = . &&
test "$(git config branch.myr4.merge)" = refs/heads/mybase2 &&
! test "$(git config branch.myr4.rebase)" = true
'
test_expect_success 'autosetuprebase local on a tracked remote branch' '
git config remote.local.url . &&
git config remote.local.fetch refs/heads/*:refs/remotes/local/* &&
git config branch.autosetuprebase local &&
(git show-ref -q refs/remotes/local/master || git fetch local) &&
git branch --track myr5 local/master &&
test "$(git config branch.myr5.remote)" = local &&
test "$(git config branch.myr5.merge)" = refs/heads/master &&
! test "$(git config branch.myr5.rebase)" = true
'
test_expect_success 'autosetuprebase never on a tracked remote branch' '
git config remote.local.url . &&
git config remote.local.fetch refs/heads/*:refs/remotes/local/* &&
git config branch.autosetuprebase never &&
(git show-ref -q refs/remotes/local/master || git fetch local) &&
git branch --track myr6 local/master &&
test "$(git config branch.myr6.remote)" = local &&
test "$(git config branch.myr6.merge)" = refs/heads/master &&
! test "$(git config branch.myr6.rebase)" = true
'
test_expect_success 'autosetuprebase remote on a tracked remote branch' '
git config remote.local.url . &&
git config remote.local.fetch refs/heads/*:refs/remotes/local/* &&
git config branch.autosetuprebase remote &&
(git show-ref -q refs/remotes/local/master || git fetch local) &&
git branch --track myr7 local/master &&
test "$(git config branch.myr7.remote)" = local &&
test "$(git config branch.myr7.merge)" = refs/heads/master &&
test "$(git config branch.myr7.rebase)" = true
'
test_expect_success 'autosetuprebase always on a tracked remote branch' '
git config remote.local.url . &&
git config remote.local.fetch refs/heads/*:refs/remotes/local/* &&
git config branch.autosetuprebase remote &&
(git show-ref -q refs/remotes/local/master || git fetch local) &&
git branch --track myr8 local/master &&
test "$(git config branch.myr8.remote)" = local &&
test "$(git config branch.myr8.merge)" = refs/heads/master &&
test "$(git config branch.myr8.rebase)" = true
'
test_expect_success 'autosetuprebase unconfigured on a tracked remote branch' '
git config --unset branch.autosetuprebase &&
git config remote.local.url . &&
git config remote.local.fetch refs/heads/*:refs/remotes/local/* &&
(git show-ref -q refs/remotes/local/master || git fetch local) &&
git branch --track myr9 local/master &&
test "$(git config branch.myr9.remote)" = local &&
test "$(git config branch.myr9.merge)" = refs/heads/master &&
test "z$(git config branch.myr9.rebase)" = z
'
test_expect_success 'autosetuprebase unconfigured on a tracked local branch' '
git config remote.local.url . &&
git config remote.local.fetch refs/heads/*:refs/remotes/local/* &&
(git show-ref -q refs/remotes/local/o || git fetch local) &&
git branch mybase10 &&
git branch --track myr10 mybase2 &&
test "$(git config branch.myr10.remote)" = . &&
test "$(git config branch.myr10.merge)" = refs/heads/mybase2 &&
test "z$(git config branch.myr10.rebase)" = z
'
test_expect_success 'autosetuprebase unconfigured on untracked local branch' '
git config remote.local.url . &&
git config remote.local.fetch refs/heads/*:refs/remotes/local/* &&
(git show-ref -q refs/remotes/local/master || git fetch local) &&
git branch --no-track myr11 mybase2 &&
test "z$(git config branch.myr11.remote)" = z &&
test "z$(git config branch.myr11.merge)" = z &&
test "z$(git config branch.myr11.rebase)" = z
'
test_expect_success 'autosetuprebase unconfigured on untracked remote branch' '
git config remote.local.url . &&
git config remote.local.fetch refs/heads/*:refs/remotes/local/* &&
(git show-ref -q refs/remotes/local/master || git fetch local) &&
git branch --no-track myr12 local/master &&
test "z$(git config branch.myr12.remote)" = z &&
test "z$(git config branch.myr12.merge)" = z &&
test "z$(git config branch.myr12.rebase)" = z
'
test_expect_success 'autosetuprebase never on an untracked local branch' '
git config branch.autosetuprebase never &&
git config remote.local.url . &&
git config remote.local.fetch refs/heads/*:refs/remotes/local/* &&
(git show-ref -q refs/remotes/local/master || git fetch local) &&
git branch --no-track myr13 mybase2 &&
test "z$(git config branch.myr13.remote)" = z &&
test "z$(git config branch.myr13.merge)" = z &&
test "z$(git config branch.myr13.rebase)" = z
'
test_expect_success 'autosetuprebase local on an untracked local branch' '
git config branch.autosetuprebase local &&
git config remote.local.url . &&
git config remote.local.fetch refs/heads/*:refs/remotes/local/* &&
(git show-ref -q refs/remotes/local/master || git fetch local) &&
git branch --no-track myr14 mybase2 &&
test "z$(git config branch.myr14.remote)" = z &&
test "z$(git config branch.myr14.merge)" = z &&
test "z$(git config branch.myr14.rebase)" = z
'
test_expect_success 'autosetuprebase remote on an untracked local branch' '
git config branch.autosetuprebase remote &&
git config remote.local.url . &&
git config remote.local.fetch refs/heads/*:refs/remotes/local/* &&
(git show-ref -q refs/remotes/local/master || git fetch local) &&
git branch --no-track myr15 mybase2 &&
test "z$(git config branch.myr15.remote)" = z &&
test "z$(git config branch.myr15.merge)" = z &&
test "z$(git config branch.myr15.rebase)" = z
'
test_expect_success 'autosetuprebase always on an untracked local branch' '
git config branch.autosetuprebase always &&
git config remote.local.url . &&
git config remote.local.fetch refs/heads/*:refs/remotes/local/* &&
(git show-ref -q refs/remotes/local/master || git fetch local) &&
git branch --no-track myr16 mybase2 &&
test "z$(git config branch.myr16.remote)" = z &&
test "z$(git config branch.myr16.merge)" = z &&
test "z$(git config branch.myr16.rebase)" = z
'
test_expect_success 'autosetuprebase never on an untracked remote branch' '
git config branch.autosetuprebase never &&
git config remote.local.url . &&
git config remote.local.fetch refs/heads/*:refs/remotes/local/* &&
(git show-ref -q refs/remotes/local/master || git fetch local) &&
git branch --no-track myr17 local/master &&
test "z$(git config branch.myr17.remote)" = z &&
test "z$(git config branch.myr17.merge)" = z &&
test "z$(git config branch.myr17.rebase)" = z
'
test_expect_success 'autosetuprebase local on an untracked remote branch' '
git config branch.autosetuprebase local &&
git config remote.local.url . &&
git config remote.local.fetch refs/heads/*:refs/remotes/local/* &&
(git show-ref -q refs/remotes/local/master || git fetch local) &&
git branch --no-track myr18 local/master &&
test "z$(git config branch.myr18.remote)" = z &&
test "z$(git config branch.myr18.merge)" = z &&
test "z$(git config branch.myr18.rebase)" = z
'
test_expect_success 'autosetuprebase remote on an untracked remote branch' '
git config branch.autosetuprebase remote &&
git config remote.local.url . &&
git config remote.local.fetch refs/heads/*:refs/remotes/local/* &&
(git show-ref -q refs/remotes/local/master || git fetch local) &&
git branch --no-track myr19 local/master &&
test "z$(git config branch.myr19.remote)" = z &&
test "z$(git config branch.myr19.merge)" = z &&
test "z$(git config branch.myr19.rebase)" = z
'
test_expect_success 'autosetuprebase always on an untracked remote branch' '
git config branch.autosetuprebase always &&
git config remote.local.url . &&
git config remote.local.fetch refs/heads/*:refs/remotes/local/* &&
(git show-ref -q refs/remotes/local/master || git fetch local) &&
git branch --no-track myr20 local/master &&
test "z$(git config branch.myr20.remote)" = z &&
test "z$(git config branch.myr20.merge)" = z &&
test "z$(git config branch.myr20.rebase)" = z
'
test_expect_success 'autosetuprebase always on detached HEAD' '
git config branch.autosetupmerge always &&
test_when_finished git checkout master &&
git checkout HEAD^0 &&
git branch my11 &&
test -z "$(git config branch.my11.remote)" &&
test -z "$(git config branch.my11.merge)"
'
test_expect_success 'detect misconfigured autosetuprebase (bad value)' '
git config branch.autosetuprebase garbage &&
test_must_fail git branch
'
test_expect_success 'detect misconfigured autosetuprebase (no value)' '
git config --unset branch.autosetuprebase &&
echo "[branch] autosetuprebase" >>.git/config &&
test_must_fail git branch &&
git config --unset branch.autosetuprebase
'
test_expect_success 'attempt to delete a branch without base and unmerged to HEAD' '
git checkout my9 &&
git config --unset branch.my8.merge &&
test_must_fail git branch -d my8
'
test_expect_success 'attempt to delete a branch merged to its base' '
# we are on my9 which is the initial commit; traditionally
# we would not have allowed deleting my8 that is not merged
# to my9, but it is set to track master that already has my8
git config branch.my8.merge refs/heads/master &&
git branch -d my8
'
test_expect_success 'attempt to delete a branch merged to its base' '
git checkout master &&
echo Third >>A &&
git commit -m "Third commit" A &&
git branch -t my10 my9 &&
git branch -f my10 HEAD^ &&
# we are on master which is at the third commit, and my10
# is behind us, so traditionally we would have allowed deleting
# it; but my10 is set to track my9 that is further behind.
test_must_fail git branch -d my10
'
test_expect_success 'use set-upstream on the current branch' '
git checkout master &&
git --bare init myupstream.git &&
git push myupstream.git master:refs/heads/frotz &&
git remote add origin myupstream.git &&
git fetch &&
git branch --set-upstream master origin/frotz &&
test "z$(git config branch.master.remote)" = "zorigin" &&
test "z$(git config branch.master.merge)" = "zrefs/heads/frotz"
'
test_expect_success 'use --edit-description' '
write_script editor <<-\EOF &&
echo "New contents" >"$1"
EOF
EDITOR=./editor git branch --edit-description &&
write_script editor <<-\EOF &&
git stripspace -s <"$1" >"EDITOR_OUTPUT"
EOF
EDITOR=./editor git branch --edit-description &&
echo "New contents" >expect &&
test_cmp EDITOR_OUTPUT expect
'
test_expect_success 'detect typo in branch name when using --edit-description' '
write_script editor <<-\EOF &&
echo "New contents" >"$1"
EOF
test_must_fail env EDITOR=./editor git branch --edit-description no-such-branch
'
test_expect_success 'refuse --edit-description on unborn branch for now' '
write_script editor <<-\EOF &&
echo "New contents" >"$1"
EOF
git checkout --orphan unborn &&
test_must_fail env EDITOR=./editor git branch --edit-description
'
test_expect_success '--merged catches invalid object names' '
test_must_fail git branch --merged 0000000000000000000000000000000000000000
'
test_expect_success 'tracking with unexpected .fetch refspec' '
rm -rf a b c d &&
git init a &&
(
cd a &&
test_commit a
) &&
git init b &&
(
cd b &&
test_commit b
) &&
git init c &&
(
cd c &&
test_commit c &&
git remote add a ../a &&
git remote add b ../b &&
git fetch --all
) &&
git init d &&
(
cd d &&
git remote add c ../c &&
git config remote.c.fetch "+refs/remotes/*:refs/remotes/*" &&
git fetch c &&
git branch --track local/a/master remotes/a/master &&
test "$(git config branch.local/a/master.remote)" = "c" &&
test "$(git config branch.local/a/master.merge)" = "refs/remotes/a/master" &&
git rev-parse --verify a >expect &&
git rev-parse --verify local/a/master >actual &&
test_cmp expect actual
)
'
test_done
| overtherain/scriptfile | tool-kit/git-2.1.2/t/t3200-branch.sh | Shell | mit | 30,713 |
/*
* drivers/misc/tegra-baseband/bb-power.c
*
* Copyright (C) 2011 NVIDIA Corporation
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/interrupt.h>
#include <linux/workqueue.h>
#include <linux/delay.h>
#include <linux/fs.h>
#include <linux/usb.h>
#include <linux/uaccess.h>
#include <linux/platform_data/tegra_usb.h>
#include <mach/usb_phy.h>
#include <mach/tegra-bb-power.h>
#include "bb-power.h"
static struct tegra_bb_callback *callback;
static int attr_load_val;
static struct tegra_bb_power_mdata *mdata;
static bb_get_cblist get_cblist[] = {
NULL,
NULL,
NULL,
M7400_CB,
};
static int tegra_bb_power_gpio_init(struct tegra_bb_power_gdata *gdata)
{
int ret;
int irq;
unsigned gpio_id;
const char *gpio_label;
unsigned long gpio_flags;
struct tegra_bb_gpio_data *gpiolist;
struct tegra_bb_gpio_irqdata *gpioirq;
gpiolist = gdata->gpio;
for (; gpiolist->data.gpio != GPIO_INVALID; ++gpiolist) {
gpio_id = (gpiolist->data.gpio);
gpio_label = (gpiolist->data.label);
gpio_flags = (gpiolist->data.flags);
/* Request the gpio */
ret = gpio_request(gpio_id, gpio_label);
if (ret) {
pr_err("%s: Error: gpio_request for gpio %d failed.\n",
__func__, gpio_id);
return ret;
}
/* Set gpio direction, as requested */
if (gpio_flags == GPIOF_IN)
gpio_direction_input(gpio_id);
else
gpio_direction_output(gpio_id, (!gpio_flags ? 0 : 1));
/* Create a sysfs node, if requested */
if (gpiolist->doexport)
gpio_export(gpio_id, false);
}
gpioirq = gdata->gpioirq;
for (; gpioirq->id != GPIO_INVALID; ++gpioirq) {
/* Create interrupt handler, if requested */
if (gpioirq->handler != NULL) {
irq = gpio_to_irq(gpioirq->id);
ret = request_threaded_irq(irq, NULL, gpioirq->handler,
gpioirq->flags, gpioirq->name, gpioirq->cookie);
if (ret < 0) {
pr_err("%s: Error: threaded_irq req fail.\n"
, __func__);
return ret;
}
if (gpioirq->wake_capable) {
ret = enable_irq_wake(irq);
if (ret) {
pr_err("%s: Error: irqwake req fail.\n",
__func__);
return ret;
}
}
}
}
return 0;
}
static int tegra_bb_power_gpio_deinit(struct tegra_bb_power_gdata *gdata)
{
struct tegra_bb_gpio_data *gpiolist;
struct tegra_bb_gpio_irqdata *gpioirq;
gpiolist = gdata->gpio;
for (; gpiolist->data.gpio != GPIO_INVALID; ++gpiolist) {
/* Free the gpio */
gpio_free(gpiolist->data.gpio);
}
gpioirq = gdata->gpioirq;
for (; gpioirq->id != GPIO_INVALID; ++gpioirq) {
/* Free the irq */
free_irq(gpio_to_irq(gpioirq->id), gpioirq->cookie);
}
return 0;
}
static ssize_t tegra_bb_attr_write(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
int val;
if (sscanf(buf, "%d", &val) != 1)
return -EINVAL;
if (callback && callback->attrib) {
if (!callback->attrib(dev, val))
attr_load_val = val;
}
return count;
}
static ssize_t tegra_bb_attr_read(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%d", attr_load_val);
}
static DEVICE_ATTR(load, S_IRUSR | S_IWUSR | S_IRGRP,
tegra_bb_attr_read, tegra_bb_attr_write);
static void tegra_usbdevice_added(struct usb_device *udev)
{
const struct usb_device_descriptor *desc = &udev->descriptor;
if (desc->idVendor == mdata->vid &&
desc->idProduct == mdata->pid) {
pr_debug("%s: Device %s added.\n", udev->product, __func__);
if (mdata->wake_capable)
device_set_wakeup_enable(&udev->dev, true);
if (mdata->autosuspend_ready)
usb_enable_autosuspend(udev);
if (mdata->reg_cb)
mdata->reg_cb(udev);
}
}
static void tegra_usbdevice_removed(struct usb_device *udev)
{
const struct usb_device_descriptor *desc = &udev->descriptor;
if (desc->idVendor == mdata->vid &&
desc->idProduct == mdata->pid) {
pr_debug("%s: Device %s removed.\n", udev->product, __func__);
}
}
static int tegra_usb_notify(struct notifier_block *self, unsigned long action,
void *dev)
{
switch (action) {
case USB_DEVICE_ADD:
tegra_usbdevice_added((struct usb_device *)dev);
break;
case USB_DEVICE_REMOVE:
tegra_usbdevice_removed((struct usb_device *)dev);
break;
}
return NOTIFY_OK;
}
static struct notifier_block tegra_usb_nb = {
.notifier_call = tegra_usb_notify,
};
static int tegra_bb_power_probe(struct platform_device *device)
{
struct device *dev = &device->dev;
struct tegra_bb_pdata *pdata;
struct tegra_bb_power_data *data;
struct tegra_bb_power_gdata *gdata;
int err;
unsigned int bb_id;
pdata = (struct tegra_bb_pdata *) dev->platform_data;
if (!pdata) {
pr_err("%s - Error: platform data is empty.\n", __func__);
return -ENODEV;
}
/* Obtain BB specific callback list */
bb_id = pdata->bb_id;
if (get_cblist[bb_id] != NULL) {
callback = (struct tegra_bb_callback *) get_cblist[bb_id]();
if (callback && callback->init) {
data = (struct tegra_bb_power_data *)
callback->init((void *)pdata);
gdata = data->gpio_data;
if (!gdata) {
pr_err("%s - Error: Gpio data is empty.\n",
__func__);
return -ENODEV;
}
/* Initialize gpio as required */
tegra_bb_power_gpio_init(gdata);
mdata = data->modem_data;
if (mdata && mdata->vid && mdata->pid)
/* Register to notifications from usb core */
usb_register_notify(&tegra_usb_nb);
} else {
pr_err("%s - Error: init callback is empty.\n",
__func__);
return -ENODEV;
}
} else {
pr_err("%s - Error: callback data is empty.\n", __func__);
return -ENODEV;
}
/* Create the control sysfs node */
err = device_create_file(dev, &dev_attr_load);
if (err < 0) {
pr_err("%s - Error: device_create_file failed.\n", __func__);
return -ENODEV;
}
attr_load_val = 0;
return 0;
}
static int tegra_bb_power_remove(struct platform_device *device)
{
struct device *dev = &device->dev;
struct tegra_bb_power_data *data;
struct tegra_bb_power_gdata *gdata;
/* BB specific callback */
if (callback && callback->deinit) {
data = (struct tegra_bb_power_data *)
callback->deinit();
/* Deinitialize gpios */
gdata = data->gpio_data;
if (gdata)
tegra_bb_power_gpio_deinit(gdata);
else {
pr_err("%s - Error: Gpio data is empty.\n", __func__);
return -ENODEV;
}
mdata = data->modem_data;
if (mdata && mdata->vid && mdata->pid)
/* Register to notifications from usb core */
usb_unregister_notify(&tegra_usb_nb);
}
/* Remove the control sysfs node */
device_remove_file(dev, &dev_attr_load);
return 0;
}
#ifdef CONFIG_PM
static int tegra_bb_power_suspend(struct platform_device *device,
pm_message_t state)
{
/* BB specific callback */
if (callback && callback->power)
callback->power(PWRSTATE_L2L3);
return 0;
}
static int tegra_bb_power_resume(struct platform_device *device)
{
/* BB specific callback */
if (callback && callback->power)
callback->power(PWRSTATE_L3L0);
return 0;
}
#endif
static struct platform_driver tegra_bb_power_driver = {
.probe = tegra_bb_power_probe,
.remove = tegra_bb_power_remove,
#ifdef CONFIG_PM
.suspend = tegra_bb_power_suspend,
.resume = tegra_bb_power_resume,
#endif
.driver = {
.name = "tegra_baseband_power",
},
};
static int __init tegra_baseband_power_init(void)
{
pr_debug("%s\n", __func__);
return platform_driver_register(&tegra_bb_power_driver);
}
static void __exit tegra_baseband_power_exit(void)
{
pr_debug("%s\n", __func__);
platform_driver_unregister(&tegra_bb_power_driver);
}
module_init(tegra_baseband_power_init)
module_exit(tegra_baseband_power_exit)
MODULE_AUTHOR("NVIDIA Corporation");
MODULE_DESCRIPTION("Tegra modem power management driver");
MODULE_LICENSE("GPL");
| DmitryADP/diff_qc750 | kernel/drivers/misc/tegra-baseband/bb-power.c | C | gpl-2.0 | 8,209 |
/*
* SPDX-License-Identifier: MIT
*
* Copyright © 2016 Intel Corporation
*/
#include <linux/prime_numbers.h>
#include "gt/intel_engine_pm.h"
#include "gt/intel_gpu_commands.h"
#include "gt/intel_gt.h"
#include "gt/intel_gt_pm.h"
#include "gem/i915_gem_region.h"
#include "huge_gem_object.h"
#include "i915_selftest.h"
#include "selftests/i915_random.h"
#include "selftests/igt_flush_test.h"
#include "selftests/igt_mmap.h"
struct tile {
unsigned int width;
unsigned int height;
unsigned int stride;
unsigned int size;
unsigned int tiling;
unsigned int swizzle;
};
static u64 swizzle_bit(unsigned int bit, u64 offset)
{
return (offset & BIT_ULL(bit)) >> (bit - 6);
}
static u64 tiled_offset(const struct tile *tile, u64 v)
{
u64 x, y;
if (tile->tiling == I915_TILING_NONE)
return v;
y = div64_u64_rem(v, tile->stride, &x);
v = div64_u64_rem(y, tile->height, &y) * tile->stride * tile->height;
if (tile->tiling == I915_TILING_X) {
v += y * tile->width;
v += div64_u64_rem(x, tile->width, &x) << tile->size;
v += x;
} else if (tile->width == 128) {
const unsigned int ytile_span = 16;
const unsigned int ytile_height = 512;
v += y * ytile_span;
v += div64_u64_rem(x, ytile_span, &x) * ytile_height;
v += x;
} else {
const unsigned int ytile_span = 32;
const unsigned int ytile_height = 256;
v += y * ytile_span;
v += div64_u64_rem(x, ytile_span, &x) * ytile_height;
v += x;
}
switch (tile->swizzle) {
case I915_BIT_6_SWIZZLE_9:
v ^= swizzle_bit(9, v);
break;
case I915_BIT_6_SWIZZLE_9_10:
v ^= swizzle_bit(9, v) ^ swizzle_bit(10, v);
break;
case I915_BIT_6_SWIZZLE_9_11:
v ^= swizzle_bit(9, v) ^ swizzle_bit(11, v);
break;
case I915_BIT_6_SWIZZLE_9_10_11:
v ^= swizzle_bit(9, v) ^ swizzle_bit(10, v) ^ swizzle_bit(11, v);
break;
}
return v;
}
static int check_partial_mapping(struct drm_i915_gem_object *obj,
const struct tile *tile,
struct rnd_state *prng)
{
const unsigned long npages = obj->base.size / PAGE_SIZE;
struct i915_ggtt_view view;
struct i915_vma *vma;
unsigned long page;
u32 __iomem *io;
struct page *p;
unsigned int n;
u64 offset;
u32 *cpu;
int err;
err = i915_gem_object_set_tiling(obj, tile->tiling, tile->stride);
if (err) {
pr_err("Failed to set tiling mode=%u, stride=%u, err=%d\n",
tile->tiling, tile->stride, err);
return err;
}
GEM_BUG_ON(i915_gem_object_get_tiling(obj) != tile->tiling);
GEM_BUG_ON(i915_gem_object_get_stride(obj) != tile->stride);
i915_gem_object_lock(obj, NULL);
err = i915_gem_object_set_to_gtt_domain(obj, true);
i915_gem_object_unlock(obj);
if (err) {
pr_err("Failed to flush to GTT write domain; err=%d\n", err);
return err;
}
page = i915_prandom_u32_max_state(npages, prng);
view = compute_partial_view(obj, page, MIN_CHUNK_PAGES);
vma = i915_gem_object_ggtt_pin(obj, &view, 0, 0, PIN_MAPPABLE);
if (IS_ERR(vma)) {
pr_err("Failed to pin partial view: offset=%lu; err=%d\n",
page, (int)PTR_ERR(vma));
return PTR_ERR(vma);
}
n = page - view.partial.offset;
GEM_BUG_ON(n >= view.partial.size);
io = i915_vma_pin_iomap(vma);
i915_vma_unpin(vma);
if (IS_ERR(io)) {
pr_err("Failed to iomap partial view: offset=%lu; err=%d\n",
page, (int)PTR_ERR(io));
err = PTR_ERR(io);
goto out;
}
iowrite32(page, io + n * PAGE_SIZE / sizeof(*io));
i915_vma_unpin_iomap(vma);
offset = tiled_offset(tile, page << PAGE_SHIFT);
if (offset >= obj->base.size)
goto out;
intel_gt_flush_ggtt_writes(&to_i915(obj->base.dev)->gt);
p = i915_gem_object_get_page(obj, offset >> PAGE_SHIFT);
cpu = kmap(p) + offset_in_page(offset);
drm_clflush_virt_range(cpu, sizeof(*cpu));
if (*cpu != (u32)page) {
pr_err("Partial view for %lu [%u] (offset=%llu, size=%u [%llu, row size %u], fence=%d, tiling=%d, stride=%d) misalignment, expected write to page (%llu + %u [0x%llx]) of 0x%x, found 0x%x\n",
page, n,
view.partial.offset,
view.partial.size,
vma->size >> PAGE_SHIFT,
tile->tiling ? tile_row_pages(obj) : 0,
vma->fence ? vma->fence->id : -1, tile->tiling, tile->stride,
offset >> PAGE_SHIFT,
(unsigned int)offset_in_page(offset),
offset,
(u32)page, *cpu);
err = -EINVAL;
}
*cpu = 0;
drm_clflush_virt_range(cpu, sizeof(*cpu));
kunmap(p);
out:
__i915_vma_put(vma);
return err;
}
static int check_partial_mappings(struct drm_i915_gem_object *obj,
const struct tile *tile,
unsigned long end_time)
{
const unsigned int nreal = obj->scratch / PAGE_SIZE;
const unsigned long npages = obj->base.size / PAGE_SIZE;
struct i915_vma *vma;
unsigned long page;
int err;
err = i915_gem_object_set_tiling(obj, tile->tiling, tile->stride);
if (err) {
pr_err("Failed to set tiling mode=%u, stride=%u, err=%d\n",
tile->tiling, tile->stride, err);
return err;
}
GEM_BUG_ON(i915_gem_object_get_tiling(obj) != tile->tiling);
GEM_BUG_ON(i915_gem_object_get_stride(obj) != tile->stride);
i915_gem_object_lock(obj, NULL);
err = i915_gem_object_set_to_gtt_domain(obj, true);
i915_gem_object_unlock(obj);
if (err) {
pr_err("Failed to flush to GTT write domain; err=%d\n", err);
return err;
}
for_each_prime_number_from(page, 1, npages) {
struct i915_ggtt_view view =
compute_partial_view(obj, page, MIN_CHUNK_PAGES);
u32 __iomem *io;
struct page *p;
unsigned int n;
u64 offset;
u32 *cpu;
GEM_BUG_ON(view.partial.size > nreal);
cond_resched();
vma = i915_gem_object_ggtt_pin(obj, &view, 0, 0, PIN_MAPPABLE);
if (IS_ERR(vma)) {
pr_err("Failed to pin partial view: offset=%lu; err=%d\n",
page, (int)PTR_ERR(vma));
return PTR_ERR(vma);
}
n = page - view.partial.offset;
GEM_BUG_ON(n >= view.partial.size);
io = i915_vma_pin_iomap(vma);
i915_vma_unpin(vma);
if (IS_ERR(io)) {
pr_err("Failed to iomap partial view: offset=%lu; err=%d\n",
page, (int)PTR_ERR(io));
return PTR_ERR(io);
}
iowrite32(page, io + n * PAGE_SIZE / sizeof(*io));
i915_vma_unpin_iomap(vma);
offset = tiled_offset(tile, page << PAGE_SHIFT);
if (offset >= obj->base.size)
continue;
intel_gt_flush_ggtt_writes(&to_i915(obj->base.dev)->gt);
p = i915_gem_object_get_page(obj, offset >> PAGE_SHIFT);
cpu = kmap(p) + offset_in_page(offset);
drm_clflush_virt_range(cpu, sizeof(*cpu));
if (*cpu != (u32)page) {
pr_err("Partial view for %lu [%u] (offset=%llu, size=%u [%llu, row size %u], fence=%d, tiling=%d, stride=%d) misalignment, expected write to page (%llu + %u [0x%llx]) of 0x%x, found 0x%x\n",
page, n,
view.partial.offset,
view.partial.size,
vma->size >> PAGE_SHIFT,
tile->tiling ? tile_row_pages(obj) : 0,
vma->fence ? vma->fence->id : -1, tile->tiling, tile->stride,
offset >> PAGE_SHIFT,
(unsigned int)offset_in_page(offset),
offset,
(u32)page, *cpu);
err = -EINVAL;
}
*cpu = 0;
drm_clflush_virt_range(cpu, sizeof(*cpu));
kunmap(p);
if (err)
return err;
__i915_vma_put(vma);
if (igt_timeout(end_time,
"%s: timed out after tiling=%d stride=%d\n",
__func__, tile->tiling, tile->stride))
return -EINTR;
}
return 0;
}
static unsigned int
setup_tile_size(struct tile *tile, struct drm_i915_private *i915)
{
if (GRAPHICS_VER(i915) <= 2) {
tile->height = 16;
tile->width = 128;
tile->size = 11;
} else if (tile->tiling == I915_TILING_Y &&
HAS_128_BYTE_Y_TILING(i915)) {
tile->height = 32;
tile->width = 128;
tile->size = 12;
} else {
tile->height = 8;
tile->width = 512;
tile->size = 12;
}
if (GRAPHICS_VER(i915) < 4)
return 8192 / tile->width;
else if (GRAPHICS_VER(i915) < 7)
return 128 * I965_FENCE_MAX_PITCH_VAL / tile->width;
else
return 128 * GEN7_FENCE_MAX_PITCH_VAL / tile->width;
}
static int igt_partial_tiling(void *arg)
{
const unsigned int nreal = 1 << 12; /* largest tile row x2 */
struct drm_i915_private *i915 = arg;
struct drm_i915_gem_object *obj;
intel_wakeref_t wakeref;
int tiling;
int err;
if (!i915_ggtt_has_aperture(&i915->ggtt))
return 0;
/* We want to check the page mapping and fencing of a large object
* mmapped through the GTT. The object we create is larger than can
* possibly be mmaped as a whole, and so we must use partial GGTT vma.
* We then check that a write through each partial GGTT vma ends up
* in the right set of pages within the object, and with the expected
* tiling, which we verify by manual swizzling.
*/
obj = huge_gem_object(i915,
nreal << PAGE_SHIFT,
(1 + next_prime_number(i915->ggtt.vm.total >> PAGE_SHIFT)) << PAGE_SHIFT);
if (IS_ERR(obj))
return PTR_ERR(obj);
err = i915_gem_object_pin_pages_unlocked(obj);
if (err) {
pr_err("Failed to allocate %u pages (%lu total), err=%d\n",
nreal, obj->base.size / PAGE_SIZE, err);
goto out;
}
wakeref = intel_runtime_pm_get(&i915->runtime_pm);
if (1) {
IGT_TIMEOUT(end);
struct tile tile;
tile.height = 1;
tile.width = 1;
tile.size = 0;
tile.stride = 0;
tile.swizzle = I915_BIT_6_SWIZZLE_NONE;
tile.tiling = I915_TILING_NONE;
err = check_partial_mappings(obj, &tile, end);
if (err && err != -EINTR)
goto out_unlock;
}
for (tiling = I915_TILING_X; tiling <= I915_TILING_Y; tiling++) {
IGT_TIMEOUT(end);
unsigned int max_pitch;
unsigned int pitch;
struct tile tile;
if (i915->quirks & QUIRK_PIN_SWIZZLED_PAGES)
/*
* The swizzling pattern is actually unknown as it
* varies based on physical address of each page.
* See i915_gem_detect_bit_6_swizzle().
*/
break;
tile.tiling = tiling;
switch (tiling) {
case I915_TILING_X:
tile.swizzle = i915->ggtt.bit_6_swizzle_x;
break;
case I915_TILING_Y:
tile.swizzle = i915->ggtt.bit_6_swizzle_y;
break;
}
GEM_BUG_ON(tile.swizzle == I915_BIT_6_SWIZZLE_UNKNOWN);
if (tile.swizzle == I915_BIT_6_SWIZZLE_9_17 ||
tile.swizzle == I915_BIT_6_SWIZZLE_9_10_17)
continue;
max_pitch = setup_tile_size(&tile, i915);
for (pitch = max_pitch; pitch; pitch >>= 1) {
tile.stride = tile.width * pitch;
err = check_partial_mappings(obj, &tile, end);
if (err == -EINTR)
goto next_tiling;
if (err)
goto out_unlock;
if (pitch > 2 && GRAPHICS_VER(i915) >= 4) {
tile.stride = tile.width * (pitch - 1);
err = check_partial_mappings(obj, &tile, end);
if (err == -EINTR)
goto next_tiling;
if (err)
goto out_unlock;
}
if (pitch < max_pitch && GRAPHICS_VER(i915) >= 4) {
tile.stride = tile.width * (pitch + 1);
err = check_partial_mappings(obj, &tile, end);
if (err == -EINTR)
goto next_tiling;
if (err)
goto out_unlock;
}
}
if (GRAPHICS_VER(i915) >= 4) {
for_each_prime_number(pitch, max_pitch) {
tile.stride = tile.width * pitch;
err = check_partial_mappings(obj, &tile, end);
if (err == -EINTR)
goto next_tiling;
if (err)
goto out_unlock;
}
}
next_tiling: ;
}
out_unlock:
intel_runtime_pm_put(&i915->runtime_pm, wakeref);
i915_gem_object_unpin_pages(obj);
out:
i915_gem_object_put(obj);
return err;
}
static int igt_smoke_tiling(void *arg)
{
const unsigned int nreal = 1 << 12; /* largest tile row x2 */
struct drm_i915_private *i915 = arg;
struct drm_i915_gem_object *obj;
intel_wakeref_t wakeref;
I915_RND_STATE(prng);
unsigned long count;
IGT_TIMEOUT(end);
int err;
if (!i915_ggtt_has_aperture(&i915->ggtt))
return 0;
/*
* igt_partial_tiling() does an exhastive check of partial tiling
* chunking, but will undoubtably run out of time. Here, we do a
* randomised search and hope over many runs of 1s with different
* seeds we will do a thorough check.
*
* Remember to look at the st_seed if we see a flip-flop in BAT!
*/
if (i915->quirks & QUIRK_PIN_SWIZZLED_PAGES)
return 0;
obj = huge_gem_object(i915,
nreal << PAGE_SHIFT,
(1 + next_prime_number(i915->ggtt.vm.total >> PAGE_SHIFT)) << PAGE_SHIFT);
if (IS_ERR(obj))
return PTR_ERR(obj);
err = i915_gem_object_pin_pages_unlocked(obj);
if (err) {
pr_err("Failed to allocate %u pages (%lu total), err=%d\n",
nreal, obj->base.size / PAGE_SIZE, err);
goto out;
}
wakeref = intel_runtime_pm_get(&i915->runtime_pm);
count = 0;
do {
struct tile tile;
tile.tiling =
i915_prandom_u32_max_state(I915_TILING_Y + 1, &prng);
switch (tile.tiling) {
case I915_TILING_NONE:
tile.height = 1;
tile.width = 1;
tile.size = 0;
tile.stride = 0;
tile.swizzle = I915_BIT_6_SWIZZLE_NONE;
break;
case I915_TILING_X:
tile.swizzle = i915->ggtt.bit_6_swizzle_x;
break;
case I915_TILING_Y:
tile.swizzle = i915->ggtt.bit_6_swizzle_y;
break;
}
if (tile.swizzle == I915_BIT_6_SWIZZLE_9_17 ||
tile.swizzle == I915_BIT_6_SWIZZLE_9_10_17)
continue;
if (tile.tiling != I915_TILING_NONE) {
unsigned int max_pitch = setup_tile_size(&tile, i915);
tile.stride =
i915_prandom_u32_max_state(max_pitch, &prng);
tile.stride = (1 + tile.stride) * tile.width;
if (GRAPHICS_VER(i915) < 4)
tile.stride = rounddown_pow_of_two(tile.stride);
}
err = check_partial_mapping(obj, &tile, &prng);
if (err)
break;
count++;
} while (!__igt_timeout(end, NULL));
pr_info("%s: Completed %lu trials\n", __func__, count);
intel_runtime_pm_put(&i915->runtime_pm, wakeref);
i915_gem_object_unpin_pages(obj);
out:
i915_gem_object_put(obj);
return err;
}
static int make_obj_busy(struct drm_i915_gem_object *obj)
{
struct drm_i915_private *i915 = to_i915(obj->base.dev);
struct intel_engine_cs *engine;
for_each_uabi_engine(engine, i915) {
struct i915_request *rq;
struct i915_vma *vma;
struct i915_gem_ww_ctx ww;
int err;
vma = i915_vma_instance(obj, &engine->gt->ggtt->vm, NULL);
if (IS_ERR(vma))
return PTR_ERR(vma);
i915_gem_ww_ctx_init(&ww, false);
retry:
err = i915_gem_object_lock(obj, &ww);
if (!err)
err = i915_vma_pin_ww(vma, &ww, 0, 0, PIN_USER);
if (err)
goto err;
rq = intel_engine_create_kernel_request(engine);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
goto err_unpin;
}
err = i915_request_await_object(rq, vma->obj, true);
if (err == 0)
err = i915_vma_move_to_active(vma, rq,
EXEC_OBJECT_WRITE);
i915_request_add(rq);
err_unpin:
i915_vma_unpin(vma);
err:
if (err == -EDEADLK) {
err = i915_gem_ww_ctx_backoff(&ww);
if (!err)
goto retry;
}
i915_gem_ww_ctx_fini(&ww);
if (err)
return err;
}
i915_gem_object_put(obj); /* leave it only alive via its active ref */
return 0;
}
static enum i915_mmap_type default_mapping(struct drm_i915_private *i915)
{
if (HAS_LMEM(i915))
return I915_MMAP_TYPE_FIXED;
return I915_MMAP_TYPE_GTT;
}
static struct drm_i915_gem_object *
create_sys_or_internal(struct drm_i915_private *i915,
unsigned long size)
{
if (HAS_LMEM(i915)) {
struct intel_memory_region *sys_region =
i915->mm.regions[INTEL_REGION_SMEM];
return __i915_gem_object_create_user(i915, size, &sys_region, 1);
}
return i915_gem_object_create_internal(i915, size);
}
static bool assert_mmap_offset(struct drm_i915_private *i915,
unsigned long size,
int expected)
{
struct drm_i915_gem_object *obj;
u64 offset;
int ret;
obj = create_sys_or_internal(i915, size);
if (IS_ERR(obj))
return expected && expected == PTR_ERR(obj);
ret = __assign_mmap_offset(obj, default_mapping(i915), &offset, NULL);
i915_gem_object_put(obj);
return ret == expected;
}
static void disable_retire_worker(struct drm_i915_private *i915)
{
i915_gem_driver_unregister__shrinker(i915);
intel_gt_pm_get(&i915->gt);
cancel_delayed_work_sync(&i915->gt.requests.retire_work);
}
static void restore_retire_worker(struct drm_i915_private *i915)
{
igt_flush_test(i915);
intel_gt_pm_put(&i915->gt);
i915_gem_driver_register__shrinker(i915);
}
static void mmap_offset_lock(struct drm_i915_private *i915)
__acquires(&i915->drm.vma_offset_manager->vm_lock)
{
write_lock(&i915->drm.vma_offset_manager->vm_lock);
}
static void mmap_offset_unlock(struct drm_i915_private *i915)
__releases(&i915->drm.vma_offset_manager->vm_lock)
{
write_unlock(&i915->drm.vma_offset_manager->vm_lock);
}
static int igt_mmap_offset_exhaustion(void *arg)
{
struct drm_i915_private *i915 = arg;
struct drm_mm *mm = &i915->drm.vma_offset_manager->vm_addr_space_mm;
struct drm_i915_gem_object *obj;
struct drm_mm_node *hole, *next;
int loop, err = 0;
u64 offset;
int enospc = HAS_LMEM(i915) ? -ENXIO : -ENOSPC;
/* Disable background reaper */
disable_retire_worker(i915);
GEM_BUG_ON(!i915->gt.awake);
intel_gt_retire_requests(&i915->gt);
i915_gem_drain_freed_objects(i915);
/* Trim the device mmap space to only a page */
mmap_offset_lock(i915);
loop = 1; /* PAGE_SIZE units */
list_for_each_entry_safe(hole, next, &mm->hole_stack, hole_stack) {
struct drm_mm_node *resv;
resv = kzalloc(sizeof(*resv), GFP_NOWAIT);
if (!resv) {
err = -ENOMEM;
goto out_park;
}
resv->start = drm_mm_hole_node_start(hole) + loop;
resv->size = hole->hole_size - loop;
resv->color = -1ul;
loop = 0;
if (!resv->size) {
kfree(resv);
continue;
}
pr_debug("Reserving hole [%llx + %llx]\n",
resv->start, resv->size);
err = drm_mm_reserve_node(mm, resv);
if (err) {
pr_err("Failed to trim VMA manager, err=%d\n", err);
kfree(resv);
goto out_park;
}
}
GEM_BUG_ON(!list_is_singular(&mm->hole_stack));
mmap_offset_unlock(i915);
/* Just fits! */
if (!assert_mmap_offset(i915, PAGE_SIZE, 0)) {
pr_err("Unable to insert object into single page hole\n");
err = -EINVAL;
goto out;
}
/* Too large */
if (!assert_mmap_offset(i915, 2 * PAGE_SIZE, enospc)) {
pr_err("Unexpectedly succeeded in inserting too large object into single page hole\n");
err = -EINVAL;
goto out;
}
/* Fill the hole, further allocation attempts should then fail */
obj = create_sys_or_internal(i915, PAGE_SIZE);
if (IS_ERR(obj)) {
err = PTR_ERR(obj);
pr_err("Unable to create object for reclaimed hole\n");
goto out;
}
err = __assign_mmap_offset(obj, default_mapping(i915), &offset, NULL);
if (err) {
pr_err("Unable to insert object into reclaimed hole\n");
goto err_obj;
}
if (!assert_mmap_offset(i915, PAGE_SIZE, enospc)) {
pr_err("Unexpectedly succeeded in inserting object into no holes!\n");
err = -EINVAL;
goto err_obj;
}
i915_gem_object_put(obj);
/* Now fill with busy dead objects that we expect to reap */
for (loop = 0; loop < 3; loop++) {
if (intel_gt_is_wedged(&i915->gt))
break;
obj = i915_gem_object_create_internal(i915, PAGE_SIZE);
if (IS_ERR(obj)) {
err = PTR_ERR(obj);
goto out;
}
err = make_obj_busy(obj);
if (err) {
pr_err("[loop %d] Failed to busy the object\n", loop);
goto err_obj;
}
}
out:
mmap_offset_lock(i915);
out_park:
drm_mm_for_each_node_safe(hole, next, mm) {
if (hole->color != -1ul)
continue;
drm_mm_remove_node(hole);
kfree(hole);
}
mmap_offset_unlock(i915);
restore_retire_worker(i915);
return err;
err_obj:
i915_gem_object_put(obj);
goto out;
}
static int gtt_set(struct drm_i915_gem_object *obj)
{
struct i915_vma *vma;
void __iomem *map;
int err = 0;
vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0, PIN_MAPPABLE);
if (IS_ERR(vma))
return PTR_ERR(vma);
intel_gt_pm_get(vma->vm->gt);
map = i915_vma_pin_iomap(vma);
i915_vma_unpin(vma);
if (IS_ERR(map)) {
err = PTR_ERR(map);
goto out;
}
memset_io(map, POISON_INUSE, obj->base.size);
i915_vma_unpin_iomap(vma);
out:
intel_gt_pm_put(vma->vm->gt);
return err;
}
static int gtt_check(struct drm_i915_gem_object *obj)
{
struct i915_vma *vma;
void __iomem *map;
int err = 0;
vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0, PIN_MAPPABLE);
if (IS_ERR(vma))
return PTR_ERR(vma);
intel_gt_pm_get(vma->vm->gt);
map = i915_vma_pin_iomap(vma);
i915_vma_unpin(vma);
if (IS_ERR(map)) {
err = PTR_ERR(map);
goto out;
}
if (memchr_inv((void __force *)map, POISON_FREE, obj->base.size)) {
pr_err("%s: Write via mmap did not land in backing store (GTT)\n",
obj->mm.region->name);
err = -EINVAL;
}
i915_vma_unpin_iomap(vma);
out:
intel_gt_pm_put(vma->vm->gt);
return err;
}
static int wc_set(struct drm_i915_gem_object *obj)
{
void *vaddr;
vaddr = i915_gem_object_pin_map_unlocked(obj, I915_MAP_WC);
if (IS_ERR(vaddr))
return PTR_ERR(vaddr);
memset(vaddr, POISON_INUSE, obj->base.size);
i915_gem_object_flush_map(obj);
i915_gem_object_unpin_map(obj);
return 0;
}
static int wc_check(struct drm_i915_gem_object *obj)
{
void *vaddr;
int err = 0;
vaddr = i915_gem_object_pin_map_unlocked(obj, I915_MAP_WC);
if (IS_ERR(vaddr))
return PTR_ERR(vaddr);
if (memchr_inv(vaddr, POISON_FREE, obj->base.size)) {
pr_err("%s: Write via mmap did not land in backing store (WC)\n",
obj->mm.region->name);
err = -EINVAL;
}
i915_gem_object_unpin_map(obj);
return err;
}
static bool can_mmap(struct drm_i915_gem_object *obj, enum i915_mmap_type type)
{
bool no_map;
if (obj->ops->mmap_offset)
return type == I915_MMAP_TYPE_FIXED;
else if (type == I915_MMAP_TYPE_FIXED)
return false;
if (type == I915_MMAP_TYPE_GTT &&
!i915_ggtt_has_aperture(&to_i915(obj->base.dev)->ggtt))
return false;
i915_gem_object_lock(obj, NULL);
no_map = (type != I915_MMAP_TYPE_GTT &&
!i915_gem_object_has_struct_page(obj) &&
!i915_gem_object_has_iomem(obj));
i915_gem_object_unlock(obj);
return !no_map;
}
#define expand32(x) (((x) << 0) | ((x) << 8) | ((x) << 16) | ((x) << 24))
static int __igt_mmap(struct drm_i915_private *i915,
struct drm_i915_gem_object *obj,
enum i915_mmap_type type)
{
struct vm_area_struct *area;
unsigned long addr;
int err, i;
u64 offset;
if (!can_mmap(obj, type))
return 0;
err = wc_set(obj);
if (err == -ENXIO)
err = gtt_set(obj);
if (err)
return err;
err = __assign_mmap_offset(obj, type, &offset, NULL);
if (err)
return err;
addr = igt_mmap_offset(i915, offset, obj->base.size, PROT_WRITE, MAP_SHARED);
if (IS_ERR_VALUE(addr))
return addr;
pr_debug("igt_mmap(%s, %d) @ %lx\n", obj->mm.region->name, type, addr);
mmap_read_lock(current->mm);
area = vma_lookup(current->mm, addr);
mmap_read_unlock(current->mm);
if (!area) {
pr_err("%s: Did not create a vm_area_struct for the mmap\n",
obj->mm.region->name);
err = -EINVAL;
goto out_unmap;
}
for (i = 0; i < obj->base.size / sizeof(u32); i++) {
u32 __user *ux = u64_to_user_ptr((u64)(addr + i * sizeof(*ux)));
u32 x;
if (get_user(x, ux)) {
pr_err("%s: Unable to read from mmap, offset:%zd\n",
obj->mm.region->name, i * sizeof(x));
err = -EFAULT;
goto out_unmap;
}
if (x != expand32(POISON_INUSE)) {
pr_err("%s: Read incorrect value from mmap, offset:%zd, found:%x, expected:%x\n",
obj->mm.region->name,
i * sizeof(x), x, expand32(POISON_INUSE));
err = -EINVAL;
goto out_unmap;
}
x = expand32(POISON_FREE);
if (put_user(x, ux)) {
pr_err("%s: Unable to write to mmap, offset:%zd\n",
obj->mm.region->name, i * sizeof(x));
err = -EFAULT;
goto out_unmap;
}
}
if (type == I915_MMAP_TYPE_GTT)
intel_gt_flush_ggtt_writes(&i915->gt);
err = wc_check(obj);
if (err == -ENXIO)
err = gtt_check(obj);
out_unmap:
vm_munmap(addr, obj->base.size);
return err;
}
static int igt_mmap(void *arg)
{
struct drm_i915_private *i915 = arg;
struct intel_memory_region *mr;
enum intel_region_id id;
for_each_memory_region(mr, i915, id) {
unsigned long sizes[] = {
PAGE_SIZE,
mr->min_page_size,
SZ_4M,
};
int i;
for (i = 0; i < ARRAY_SIZE(sizes); i++) {
struct drm_i915_gem_object *obj;
int err;
obj = __i915_gem_object_create_user(i915, sizes[i], &mr, 1);
if (obj == ERR_PTR(-ENODEV))
continue;
if (IS_ERR(obj))
return PTR_ERR(obj);
err = __igt_mmap(i915, obj, I915_MMAP_TYPE_GTT);
if (err == 0)
err = __igt_mmap(i915, obj, I915_MMAP_TYPE_WC);
if (err == 0)
err = __igt_mmap(i915, obj, I915_MMAP_TYPE_FIXED);
i915_gem_object_put(obj);
if (err)
return err;
}
}
return 0;
}
static const char *repr_mmap_type(enum i915_mmap_type type)
{
switch (type) {
case I915_MMAP_TYPE_GTT: return "gtt";
case I915_MMAP_TYPE_WB: return "wb";
case I915_MMAP_TYPE_WC: return "wc";
case I915_MMAP_TYPE_UC: return "uc";
case I915_MMAP_TYPE_FIXED: return "fixed";
default: return "unknown";
}
}
static bool can_access(struct drm_i915_gem_object *obj)
{
bool access;
i915_gem_object_lock(obj, NULL);
access = i915_gem_object_has_struct_page(obj) ||
i915_gem_object_has_iomem(obj);
i915_gem_object_unlock(obj);
return access;
}
static int __igt_mmap_access(struct drm_i915_private *i915,
struct drm_i915_gem_object *obj,
enum i915_mmap_type type)
{
unsigned long __user *ptr;
unsigned long A, B;
unsigned long x, y;
unsigned long addr;
int err;
u64 offset;
memset(&A, 0xAA, sizeof(A));
memset(&B, 0xBB, sizeof(B));
if (!can_mmap(obj, type) || !can_access(obj))
return 0;
err = __assign_mmap_offset(obj, type, &offset, NULL);
if (err)
return err;
addr = igt_mmap_offset(i915, offset, obj->base.size, PROT_WRITE, MAP_SHARED);
if (IS_ERR_VALUE(addr))
return addr;
ptr = (unsigned long __user *)addr;
err = __put_user(A, ptr);
if (err) {
pr_err("%s(%s): failed to write into user mmap\n",
obj->mm.region->name, repr_mmap_type(type));
goto out_unmap;
}
intel_gt_flush_ggtt_writes(&i915->gt);
err = access_process_vm(current, addr, &x, sizeof(x), 0);
if (err != sizeof(x)) {
pr_err("%s(%s): access_process_vm() read failed\n",
obj->mm.region->name, repr_mmap_type(type));
goto out_unmap;
}
err = access_process_vm(current, addr, &B, sizeof(B), FOLL_WRITE);
if (err != sizeof(B)) {
pr_err("%s(%s): access_process_vm() write failed\n",
obj->mm.region->name, repr_mmap_type(type));
goto out_unmap;
}
intel_gt_flush_ggtt_writes(&i915->gt);
err = __get_user(y, ptr);
if (err) {
pr_err("%s(%s): failed to read from user mmap\n",
obj->mm.region->name, repr_mmap_type(type));
goto out_unmap;
}
if (x != A || y != B) {
pr_err("%s(%s): failed to read/write values, found (%lx, %lx)\n",
obj->mm.region->name, repr_mmap_type(type),
x, y);
err = -EINVAL;
goto out_unmap;
}
out_unmap:
vm_munmap(addr, obj->base.size);
return err;
}
static int igt_mmap_access(void *arg)
{
struct drm_i915_private *i915 = arg;
struct intel_memory_region *mr;
enum intel_region_id id;
for_each_memory_region(mr, i915, id) {
struct drm_i915_gem_object *obj;
int err;
obj = __i915_gem_object_create_user(i915, PAGE_SIZE, &mr, 1);
if (obj == ERR_PTR(-ENODEV))
continue;
if (IS_ERR(obj))
return PTR_ERR(obj);
err = __igt_mmap_access(i915, obj, I915_MMAP_TYPE_GTT);
if (err == 0)
err = __igt_mmap_access(i915, obj, I915_MMAP_TYPE_WB);
if (err == 0)
err = __igt_mmap_access(i915, obj, I915_MMAP_TYPE_WC);
if (err == 0)
err = __igt_mmap_access(i915, obj, I915_MMAP_TYPE_UC);
if (err == 0)
err = __igt_mmap_access(i915, obj, I915_MMAP_TYPE_FIXED);
i915_gem_object_put(obj);
if (err)
return err;
}
return 0;
}
static int __igt_mmap_gpu(struct drm_i915_private *i915,
struct drm_i915_gem_object *obj,
enum i915_mmap_type type)
{
struct intel_engine_cs *engine;
unsigned long addr;
u32 __user *ux;
u32 bbe;
int err;
u64 offset;
/*
* Verify that the mmap access into the backing store aligns with
* that of the GPU, i.e. that mmap is indeed writing into the same
* page as being read by the GPU.
*/
if (!can_mmap(obj, type))
return 0;
err = wc_set(obj);
if (err == -ENXIO)
err = gtt_set(obj);
if (err)
return err;
err = __assign_mmap_offset(obj, type, &offset, NULL);
if (err)
return err;
addr = igt_mmap_offset(i915, offset, obj->base.size, PROT_WRITE, MAP_SHARED);
if (IS_ERR_VALUE(addr))
return addr;
ux = u64_to_user_ptr((u64)addr);
bbe = MI_BATCH_BUFFER_END;
if (put_user(bbe, ux)) {
pr_err("%s: Unable to write to mmap\n", obj->mm.region->name);
err = -EFAULT;
goto out_unmap;
}
if (type == I915_MMAP_TYPE_GTT)
intel_gt_flush_ggtt_writes(&i915->gt);
for_each_uabi_engine(engine, i915) {
struct i915_request *rq;
struct i915_vma *vma;
struct i915_gem_ww_ctx ww;
vma = i915_vma_instance(obj, engine->kernel_context->vm, NULL);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto out_unmap;
}
i915_gem_ww_ctx_init(&ww, false);
retry:
err = i915_gem_object_lock(obj, &ww);
if (!err)
err = i915_vma_pin_ww(vma, &ww, 0, 0, PIN_USER);
if (err)
goto out_ww;
rq = i915_request_create(engine->kernel_context);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
goto out_unpin;
}
err = i915_request_await_object(rq, vma->obj, false);
if (err == 0)
err = i915_vma_move_to_active(vma, rq, 0);
err = engine->emit_bb_start(rq, vma->node.start, 0, 0);
i915_request_get(rq);
i915_request_add(rq);
if (i915_request_wait(rq, 0, HZ / 5) < 0) {
struct drm_printer p =
drm_info_printer(engine->i915->drm.dev);
pr_err("%s(%s, %s): Failed to execute batch\n",
__func__, engine->name, obj->mm.region->name);
intel_engine_dump(engine, &p,
"%s\n", engine->name);
intel_gt_set_wedged(engine->gt);
err = -EIO;
}
i915_request_put(rq);
out_unpin:
i915_vma_unpin(vma);
out_ww:
if (err == -EDEADLK) {
err = i915_gem_ww_ctx_backoff(&ww);
if (!err)
goto retry;
}
i915_gem_ww_ctx_fini(&ww);
if (err)
goto out_unmap;
}
out_unmap:
vm_munmap(addr, obj->base.size);
return err;
}
static int igt_mmap_gpu(void *arg)
{
struct drm_i915_private *i915 = arg;
struct intel_memory_region *mr;
enum intel_region_id id;
for_each_memory_region(mr, i915, id) {
struct drm_i915_gem_object *obj;
int err;
obj = __i915_gem_object_create_user(i915, PAGE_SIZE, &mr, 1);
if (obj == ERR_PTR(-ENODEV))
continue;
if (IS_ERR(obj))
return PTR_ERR(obj);
err = __igt_mmap_gpu(i915, obj, I915_MMAP_TYPE_GTT);
if (err == 0)
err = __igt_mmap_gpu(i915, obj, I915_MMAP_TYPE_WC);
if (err == 0)
err = __igt_mmap_gpu(i915, obj, I915_MMAP_TYPE_FIXED);
i915_gem_object_put(obj);
if (err)
return err;
}
return 0;
}
static int check_present_pte(pte_t *pte, unsigned long addr, void *data)
{
if (!pte_present(*pte) || pte_none(*pte)) {
pr_err("missing PTE:%lx\n",
(addr - (unsigned long)data) >> PAGE_SHIFT);
return -EINVAL;
}
return 0;
}
static int check_absent_pte(pte_t *pte, unsigned long addr, void *data)
{
if (pte_present(*pte) && !pte_none(*pte)) {
pr_err("present PTE:%lx; expected to be revoked\n",
(addr - (unsigned long)data) >> PAGE_SHIFT);
return -EINVAL;
}
return 0;
}
static int check_present(unsigned long addr, unsigned long len)
{
return apply_to_page_range(current->mm, addr, len,
check_present_pte, (void *)addr);
}
static int check_absent(unsigned long addr, unsigned long len)
{
return apply_to_page_range(current->mm, addr, len,
check_absent_pte, (void *)addr);
}
static int prefault_range(u64 start, u64 len)
{
const char __user *addr, *end;
char __maybe_unused c;
int err;
addr = u64_to_user_ptr(start);
end = addr + len;
for (; addr < end; addr += PAGE_SIZE) {
err = __get_user(c, addr);
if (err)
return err;
}
return __get_user(c, end - 1);
}
static int __igt_mmap_revoke(struct drm_i915_private *i915,
struct drm_i915_gem_object *obj,
enum i915_mmap_type type)
{
unsigned long addr;
int err;
u64 offset;
if (!can_mmap(obj, type))
return 0;
err = __assign_mmap_offset(obj, type, &offset, NULL);
if (err)
return err;
addr = igt_mmap_offset(i915, offset, obj->base.size, PROT_WRITE, MAP_SHARED);
if (IS_ERR_VALUE(addr))
return addr;
err = prefault_range(addr, obj->base.size);
if (err)
goto out_unmap;
err = check_present(addr, obj->base.size);
if (err) {
pr_err("%s: was not present\n", obj->mm.region->name);
goto out_unmap;
}
/*
* After unbinding the object from the GGTT, its address may be reused
* for other objects. Ergo we have to revoke the previous mmap PTE
* access as it no longer points to the same object.
*/
err = i915_gem_object_unbind(obj, I915_GEM_OBJECT_UNBIND_ACTIVE);
if (err) {
pr_err("Failed to unbind object!\n");
goto out_unmap;
}
if (type != I915_MMAP_TYPE_GTT) {
i915_gem_object_lock(obj, NULL);
__i915_gem_object_put_pages(obj);
i915_gem_object_unlock(obj);
if (i915_gem_object_has_pages(obj)) {
pr_err("Failed to put-pages object!\n");
err = -EINVAL;
goto out_unmap;
}
}
if (!obj->ops->mmap_ops) {
err = check_absent(addr, obj->base.size);
if (err) {
pr_err("%s: was not absent\n", obj->mm.region->name);
goto out_unmap;
}
} else {
/* ttm allows access to evicted regions by design */
err = check_present(addr, obj->base.size);
if (err) {
pr_err("%s: was not present\n", obj->mm.region->name);
goto out_unmap;
}
}
out_unmap:
vm_munmap(addr, obj->base.size);
return err;
}
static int igt_mmap_revoke(void *arg)
{
struct drm_i915_private *i915 = arg;
struct intel_memory_region *mr;
enum intel_region_id id;
for_each_memory_region(mr, i915, id) {
struct drm_i915_gem_object *obj;
int err;
obj = __i915_gem_object_create_user(i915, PAGE_SIZE, &mr, 1);
if (obj == ERR_PTR(-ENODEV))
continue;
if (IS_ERR(obj))
return PTR_ERR(obj);
err = __igt_mmap_revoke(i915, obj, I915_MMAP_TYPE_GTT);
if (err == 0)
err = __igt_mmap_revoke(i915, obj, I915_MMAP_TYPE_WC);
if (err == 0)
err = __igt_mmap_revoke(i915, obj, I915_MMAP_TYPE_FIXED);
i915_gem_object_put(obj);
if (err)
return err;
}
return 0;
}
int i915_gem_mman_live_selftests(struct drm_i915_private *i915)
{
static const struct i915_subtest tests[] = {
SUBTEST(igt_partial_tiling),
SUBTEST(igt_smoke_tiling),
SUBTEST(igt_mmap_offset_exhaustion),
SUBTEST(igt_mmap),
SUBTEST(igt_mmap_access),
SUBTEST(igt_mmap_revoke),
SUBTEST(igt_mmap_gpu),
};
return i915_subtests(tests, i915);
}
| rperier/linux | drivers/gpu/drm/i915/gem/selftests/i915_gem_mman.c | C | gpl-2.0 | 34,178 |
#
# Makefile for the Linux kernel device drivers.
#
# 15 Sep 2000, Christoph Hellwig <hch@infradead.org>
# Rewritten to use lists instead of if-statements.
#
obj-y += gpio/
obj-$(CONFIG_PCI) += pci/
obj-$(CONFIG_PARISC) += parisc/
obj-$(CONFIG_RAPIDIO) += rapidio/
obj-y += video/
obj-y += idle/
obj-$(CONFIG_ACPI) += acpi/
obj-$(CONFIG_SFI) += sfi/
# PnP must come after ACPI since it will eventually need to check if acpi
# was used and do nothing if so
obj-$(CONFIG_PNP) += pnp/
obj-$(CONFIG_ARM_AMBA) += amba/
obj-$(CONFIG_VIRTIO) += virtio/
obj-$(CONFIG_XEN) += xen/
# regulators early, since some subsystems rely on them to initialize
obj-$(CONFIG_REGULATOR) += regulator/
# char/ comes before serial/ etc so that the VT console is the boot-time
# default.
obj-y += char/
# gpu/ comes after char for AGP vs DRM startup
obj-y += gpu/
obj-$(CONFIG_CONNECTOR) += connector/
# i810fb and intelfb depend on char/agp/
obj-$(CONFIG_FB_I810) += video/i810/
obj-$(CONFIG_FB_INTEL) += video/intelfb/
obj-y += serial/
obj-$(CONFIG_PARPORT) += parport/
obj-y += base/ block/ misc/ mfd/
obj-$(CONFIG_NUBUS) += nubus/
obj-y += macintosh/
obj-$(CONFIG_IDE) += ide/
obj-$(CONFIG_SCSI) += scsi/
obj-$(CONFIG_ATA) += ata/
obj-$(CONFIG_MTD) += mtd/
obj-$(CONFIG_SPI) += spi/
obj-y += net/
obj-$(CONFIG_ATM) += atm/
obj-$(CONFIG_FUSION) += message/
obj-y += firewire/
obj-y += ieee1394/
obj-$(CONFIG_UIO) += uio/
obj-y += cdrom/
obj-y += auxdisplay/
obj-$(CONFIG_PCCARD) += pcmcia/
obj-$(CONFIG_DIO) += dio/
obj-$(CONFIG_SBUS) += sbus/
obj-$(CONFIG_ZORRO) += zorro/
obj-$(CONFIG_MAC) += macintosh/
obj-$(CONFIG_ATA_OVER_ETH) += block/aoe/
obj-$(CONFIG_PARIDE) += block/paride/
obj-$(CONFIG_TC) += tc/
obj-$(CONFIG_UWB) += uwb/
obj-$(CONFIG_USB_OTG_UTILS) += usb/otg/
obj-$(CONFIG_USB) += usb/
obj-$(CONFIG_USB_MUSB_HDRC) += usb/musb/
obj-$(CONFIG_PCI) += usb/
obj-$(CONFIG_USB_GADGET) += usb/gadget/
obj-$(CONFIG_SERIO) += input/serio/
obj-$(CONFIG_GAMEPORT) += input/gameport/
obj-$(CONFIG_INPUT) += input/
obj-$(CONFIG_I2O) += message/
obj-$(CONFIG_RTC_LIB) += rtc/
obj-y += i2c/ media/
obj-$(CONFIG_PPS) += pps/
obj-$(CONFIG_W1) += w1/
obj-$(CONFIG_POWER_SUPPLY) += power/
obj-$(CONFIG_HWMON) += hwmon/
obj-$(CONFIG_THERMAL) += thermal/
obj-$(CONFIG_WATCHDOG) += watchdog/
obj-$(CONFIG_PHONE) += telephony/
obj-$(CONFIG_MD) += md/
obj-$(CONFIG_BT) += bluetooth/
obj-$(CONFIG_ACCESSIBILITY) += accessibility/
obj-$(CONFIG_ISDN) += isdn/
obj-$(CONFIG_EDAC) += edac/
obj-$(CONFIG_MCA) += mca/
obj-$(CONFIG_EISA) += eisa/
obj-y += lguest/
obj-$(CONFIG_CPU_FREQ) += cpufreq/
obj-$(CONFIG_CPU_IDLE) += cpuidle/
obj-$(CONFIG_MMC) += mmc/
obj-$(CONFIG_MEMSTICK) += memstick/
obj-$(CONFIG_NEW_LEDS) += leds/
obj-$(CONFIG_INFINIBAND) += infiniband/
obj-$(CONFIG_SGI_SN) += sn/
obj-y += firmware/
obj-$(CONFIG_CRYPTO) += crypto/
obj-$(CONFIG_SUPERH) += sh/
obj-$(CONFIG_ARCH_SHMOBILE) += sh/
ifndef CONFIG_ARCH_USES_GETTIMEOFFSET
obj-y += clocksource/
endif
obj-$(CONFIG_DMA_ENGINE) += dma/
obj-$(CONFIG_DCA) += dca/
obj-$(CONFIG_HID) += hid/
obj-$(CONFIG_PPC_PS3) += ps3/
obj-$(CONFIG_OF) += of/
obj-$(CONFIG_SSB) += ssb/
obj-$(CONFIG_VHOST_NET) += vhost/
obj-$(CONFIG_VLYNQ) += vlynq/
obj-$(CONFIG_STAGING) += staging/
obj-y += platform/
obj-y += ieee802154/
| wkritzinger/asuswrt-merlin | release/src-rt-7.x.main/src/linux/linux-2.6.36/drivers/Makefile | Makefile | gpl-2.0 | 3,388 |
/* -*- c++ -*- */
/*
* Copyright 2004,2012 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
* GNU Radio is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* GNU Radio is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GNU Radio; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifndef INCLUDED_FILTER_HILBERT_FC_H
#define INCLUDED_FILTER_HILBERT_FC_H
#include <gnuradio/filter/api.h>
#include <gnuradio/filter/firdes.h>
#include <gnuradio/sync_block.h>
#include <gnuradio/types.h>
namespace gr {
namespace filter {
/*!
* \brief Hilbert transformer.
* \ingroup filter_blk
*
* \details
* real output is input appropriately delayed.
* imaginary output is hilbert filtered (90 degree phase shift)
* version of input.
*/
class FILTER_API hilbert_fc : virtual public sync_block
{
public:
// gr::filter::hilbert_fc::sptr
typedef boost::shared_ptr<hilbert_fc> sptr;
/*!
* Build a Hilbert transformer filter block.
*
* \param ntaps The number of taps for the filter.
* \param window Window type (see firdes::win_type) to use.
* \param beta Beta value for a Kaiser window.
*/
static sptr make(unsigned int ntaps,
firdes::win_type window=firdes::WIN_HAMMING,
double beta=6.76);
};
} /* namespace filter */
} /* namespace gr */
#endif /* INCLUDED_FILTER_HILBERT_FC_H */
| iohannez/gnuradio | gr-filter/include/gnuradio/filter/hilbert_fc.h | C | gpl-3.0 | 1,990 |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/menu_manager_factory.h"
#include "chrome/browser/extensions/menu_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/extension_system_provider.h"
#include "extensions/browser/extensions_browser_client.h"
namespace extensions {
// static
MenuManager* MenuManagerFactory::GetForBrowserContext(
content::BrowserContext* context) {
return static_cast<MenuManager*>(
GetInstance()->GetServiceForBrowserContext(context, true));
}
// static
MenuManagerFactory* MenuManagerFactory::GetInstance() {
return Singleton<MenuManagerFactory>::get();
}
// static
KeyedService* MenuManagerFactory::BuildServiceInstanceForTesting(
content::BrowserContext* context) {
return GetInstance()->BuildServiceInstanceFor(context);
}
MenuManagerFactory::MenuManagerFactory()
: BrowserContextKeyedServiceFactory(
"MenuManager",
BrowserContextDependencyManager::GetInstance()) {
DependsOn(ExtensionsBrowserClient::Get()->GetExtensionSystemFactory());
}
MenuManagerFactory::~MenuManagerFactory() {}
KeyedService* MenuManagerFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
Profile* profile = Profile::FromBrowserContext(context);
return new MenuManager(profile, ExtensionSystem::Get(profile)->state_store());
}
content::BrowserContext* MenuManagerFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return ExtensionsBrowserClient::Get()->GetOriginalContext(context);
}
bool MenuManagerFactory::ServiceIsCreatedWithBrowserContext() const {
return true;
}
bool MenuManagerFactory::ServiceIsNULLWhileTesting() const {
return true;
}
} // namespace extensions
| s20121035/rk3288_android5.1_repo | external/chromium_org/chrome/browser/extensions/menu_manager_factory.cc | C++ | gpl-3.0 | 2,014 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package org.apache.ignite.internal.processors.cache.binary;
import org.apache.ignite.cache.CacheAtomicityMode;
/**
* Cache EntryProcessor + Deployment for transactional cache.
*/
public class GridCacheBinaryTransactionalEntryProcessorDeploymentSelfTest extends
GridCacheBinaryAtomicEntryProcessorDeploymentSelfTest {
/** {@inheritDoc} */
@Override protected CacheAtomicityMode atomicityMode() {
return CacheAtomicityMode.TRANSACTIONAL;
}
}
| irudyak/ignite | modules/core/src/test/java/org/apache/ignite/internal/processors/cache/binary/GridCacheBinaryTransactionalEntryProcessorDeploymentSelfTest.java | Java | apache-2.0 | 1,284 |
// SPDX-License-Identifier: GPL-2.0
/*
* Copyright (c) 2009-2010 Intel Corporation
*
* Authors:
* Jesse Barnes <jbarnes@virtuousgeek.org>
*/
/*
* Some Intel Ibex Peak based platforms support so-called "intelligent
* power sharing", which allows the CPU and GPU to cooperate to maximize
* performance within a given TDP (thermal design point). This driver
* performs the coordination between the CPU and GPU, monitors thermal and
* power statistics in the platform, and initializes power monitoring
* hardware. It also provides a few tunables to control behavior. Its
* primary purpose is to safely allow CPU and GPU turbo modes to be enabled
* by tracking power and thermal budget; secondarily it can boost turbo
* performance by allocating more power or thermal budget to the CPU or GPU
* based on available headroom and activity.
*
* The basic algorithm is driven by a 5s moving average of temperature. If
* thermal headroom is available, the CPU and/or GPU power clamps may be
* adjusted upwards. If we hit the thermal ceiling or a thermal trigger,
* we scale back the clamp. Aside from trigger events (when we're critically
* close or over our TDP) we don't adjust the clamps more than once every
* five seconds.
*
* The thermal device (device 31, function 6) has a set of registers that
* are updated by the ME firmware. The ME should also take the clamp values
* written to those registers and write them to the CPU, but we currently
* bypass that functionality and write the CPU MSR directly.
*
* UNSUPPORTED:
* - dual MCP configs
*
* TODO:
* - handle CPU hotplug
* - provide turbo enable/disable api
*
* Related documents:
* - CDI 403777, 403778 - Auburndale EDS vol 1 & 2
* - CDI 401376 - Ibex Peak EDS
* - ref 26037, 26641 - IPS BIOS spec
* - ref 26489 - Nehalem BIOS writer's guide
* - ref 26921 - Ibex Peak BIOS Specification
*/
#include <linux/debugfs.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/kthread.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/sched.h>
#include <linux/sched/loadavg.h>
#include <linux/seq_file.h>
#include <linux/string.h>
#include <linux/tick.h>
#include <linux/timer.h>
#include <linux/dmi.h>
#include <drm/i915_drm.h>
#include <asm/msr.h>
#include <asm/processor.h>
#include "intel_ips.h"
#include <linux/io-64-nonatomic-lo-hi.h>
#define PCI_DEVICE_ID_INTEL_THERMAL_SENSOR 0x3b32
/*
* Package level MSRs for monitor/control
*/
#define PLATFORM_INFO 0xce
#define PLATFORM_TDP (1<<29)
#define PLATFORM_RATIO (1<<28)
#define IA32_MISC_ENABLE 0x1a0
#define IA32_MISC_TURBO_EN (1ULL<<38)
#define TURBO_POWER_CURRENT_LIMIT 0x1ac
#define TURBO_TDC_OVR_EN (1UL<<31)
#define TURBO_TDC_MASK (0x000000007fff0000UL)
#define TURBO_TDC_SHIFT (16)
#define TURBO_TDP_OVR_EN (1UL<<15)
#define TURBO_TDP_MASK (0x0000000000003fffUL)
/*
* Core/thread MSRs for monitoring
*/
#define IA32_PERF_CTL 0x199
#define IA32_PERF_TURBO_DIS (1ULL<<32)
/*
* Thermal PCI device regs
*/
#define THM_CFG_TBAR 0x10
#define THM_CFG_TBAR_HI 0x14
#define THM_TSIU 0x00
#define THM_TSE 0x01
#define TSE_EN 0xb8
#define THM_TSS 0x02
#define THM_TSTR 0x03
#define THM_TSTTP 0x04
#define THM_TSCO 0x08
#define THM_TSES 0x0c
#define THM_TSGPEN 0x0d
#define TSGPEN_HOT_LOHI (1<<1)
#define TSGPEN_CRIT_LOHI (1<<2)
#define THM_TSPC 0x0e
#define THM_PPEC 0x10
#define THM_CTA 0x12
#define THM_PTA 0x14
#define PTA_SLOPE_MASK (0xff00)
#define PTA_SLOPE_SHIFT 8
#define PTA_OFFSET_MASK (0x00ff)
#define THM_MGTA 0x16
#define MGTA_SLOPE_MASK (0xff00)
#define MGTA_SLOPE_SHIFT 8
#define MGTA_OFFSET_MASK (0x00ff)
#define THM_TRC 0x1a
#define TRC_CORE2_EN (1<<15)
#define TRC_THM_EN (1<<12)
#define TRC_C6_WAR (1<<8)
#define TRC_CORE1_EN (1<<7)
#define TRC_CORE_PWR (1<<6)
#define TRC_PCH_EN (1<<5)
#define TRC_MCH_EN (1<<4)
#define TRC_DIMM4 (1<<3)
#define TRC_DIMM3 (1<<2)
#define TRC_DIMM2 (1<<1)
#define TRC_DIMM1 (1<<0)
#define THM_TES 0x20
#define THM_TEN 0x21
#define TEN_UPDATE_EN 1
#define THM_PSC 0x24
#define PSC_NTG (1<<0) /* No GFX turbo support */
#define PSC_NTPC (1<<1) /* No CPU turbo support */
#define PSC_PP_DEF (0<<2) /* Perf policy up to driver */
#define PSP_PP_PC (1<<2) /* BIOS prefers CPU perf */
#define PSP_PP_BAL (2<<2) /* BIOS wants balanced perf */
#define PSP_PP_GFX (3<<2) /* BIOS prefers GFX perf */
#define PSP_PBRT (1<<4) /* BIOS run time support */
#define THM_CTV1 0x30
#define CTV_TEMP_ERROR (1<<15)
#define CTV_TEMP_MASK 0x3f
#define CTV_
#define THM_CTV2 0x32
#define THM_CEC 0x34 /* undocumented power accumulator in joules */
#define THM_AE 0x3f
#define THM_HTS 0x50 /* 32 bits */
#define HTS_PCPL_MASK (0x7fe00000)
#define HTS_PCPL_SHIFT 21
#define HTS_GPL_MASK (0x001ff000)
#define HTS_GPL_SHIFT 12
#define HTS_PP_MASK (0x00000c00)
#define HTS_PP_SHIFT 10
#define HTS_PP_DEF 0
#define HTS_PP_PROC 1
#define HTS_PP_BAL 2
#define HTS_PP_GFX 3
#define HTS_PCTD_DIS (1<<9)
#define HTS_GTD_DIS (1<<8)
#define HTS_PTL_MASK (0x000000fe)
#define HTS_PTL_SHIFT 1
#define HTS_NVV (1<<0)
#define THM_HTSHI 0x54 /* 16 bits */
#define HTS2_PPL_MASK (0x03ff)
#define HTS2_PRST_MASK (0x3c00)
#define HTS2_PRST_SHIFT 10
#define HTS2_PRST_UNLOADED 0
#define HTS2_PRST_RUNNING 1
#define HTS2_PRST_TDISOP 2 /* turbo disabled due to power */
#define HTS2_PRST_TDISHT 3 /* turbo disabled due to high temp */
#define HTS2_PRST_TDISUSR 4 /* user disabled turbo */
#define HTS2_PRST_TDISPLAT 5 /* platform disabled turbo */
#define HTS2_PRST_TDISPM 6 /* power management disabled turbo */
#define HTS2_PRST_TDISERR 7 /* some kind of error disabled turbo */
#define THM_PTL 0x56
#define THM_MGTV 0x58
#define TV_MASK 0x000000000000ff00
#define TV_SHIFT 8
#define THM_PTV 0x60
#define PTV_MASK 0x00ff
#define THM_MMGPC 0x64
#define THM_MPPC 0x66
#define THM_MPCPC 0x68
#define THM_TSPIEN 0x82
#define TSPIEN_AUX_LOHI (1<<0)
#define TSPIEN_HOT_LOHI (1<<1)
#define TSPIEN_CRIT_LOHI (1<<2)
#define TSPIEN_AUX2_LOHI (1<<3)
#define THM_TSLOCK 0x83
#define THM_ATR 0x84
#define THM_TOF 0x87
#define THM_STS 0x98
#define STS_PCPL_MASK (0x7fe00000)
#define STS_PCPL_SHIFT 21
#define STS_GPL_MASK (0x001ff000)
#define STS_GPL_SHIFT 12
#define STS_PP_MASK (0x00000c00)
#define STS_PP_SHIFT 10
#define STS_PP_DEF 0
#define STS_PP_PROC 1
#define STS_PP_BAL 2
#define STS_PP_GFX 3
#define STS_PCTD_DIS (1<<9)
#define STS_GTD_DIS (1<<8)
#define STS_PTL_MASK (0x000000fe)
#define STS_PTL_SHIFT 1
#define STS_NVV (1<<0)
#define THM_SEC 0x9c
#define SEC_ACK (1<<0)
#define THM_TC3 0xa4
#define THM_TC1 0xa8
#define STS_PPL_MASK (0x0003ff00)
#define STS_PPL_SHIFT 16
#define THM_TC2 0xac
#define THM_DTV 0xb0
#define THM_ITV 0xd8
#define ITV_ME_SEQNO_MASK 0x00ff0000 /* ME should update every ~200ms */
#define ITV_ME_SEQNO_SHIFT (16)
#define ITV_MCH_TEMP_MASK 0x0000ff00
#define ITV_MCH_TEMP_SHIFT (8)
#define ITV_PCH_TEMP_MASK 0x000000ff
#define thm_readb(off) readb(ips->regmap + (off))
#define thm_readw(off) readw(ips->regmap + (off))
#define thm_readl(off) readl(ips->regmap + (off))
#define thm_readq(off) readq(ips->regmap + (off))
#define thm_writeb(off, val) writeb((val), ips->regmap + (off))
#define thm_writew(off, val) writew((val), ips->regmap + (off))
#define thm_writel(off, val) writel((val), ips->regmap + (off))
static const int IPS_ADJUST_PERIOD = 5000; /* ms */
static bool late_i915_load = false;
/* For initial average collection */
static const int IPS_SAMPLE_PERIOD = 200; /* ms */
static const int IPS_SAMPLE_WINDOW = 5000; /* 5s moving window of samples */
#define IPS_SAMPLE_COUNT (IPS_SAMPLE_WINDOW / IPS_SAMPLE_PERIOD)
/* Per-SKU limits */
struct ips_mcp_limits {
int mcp_power_limit; /* mW units */
int core_power_limit;
int mch_power_limit;
int core_temp_limit; /* degrees C */
int mch_temp_limit;
};
/* Max temps are -10 degrees C to avoid PROCHOT# */
static struct ips_mcp_limits ips_sv_limits = {
.mcp_power_limit = 35000,
.core_power_limit = 29000,
.mch_power_limit = 20000,
.core_temp_limit = 95,
.mch_temp_limit = 90
};
static struct ips_mcp_limits ips_lv_limits = {
.mcp_power_limit = 25000,
.core_power_limit = 21000,
.mch_power_limit = 13000,
.core_temp_limit = 95,
.mch_temp_limit = 90
};
static struct ips_mcp_limits ips_ulv_limits = {
.mcp_power_limit = 18000,
.core_power_limit = 14000,
.mch_power_limit = 11000,
.core_temp_limit = 95,
.mch_temp_limit = 90
};
struct ips_driver {
struct device *dev;
void __iomem *regmap;
int irq;
struct task_struct *monitor;
struct task_struct *adjust;
struct dentry *debug_root;
struct timer_list timer;
/* Average CPU core temps (all averages in .01 degrees C for precision) */
u16 ctv1_avg_temp;
u16 ctv2_avg_temp;
/* GMCH average */
u16 mch_avg_temp;
/* Average for the CPU (both cores?) */
u16 mcp_avg_temp;
/* Average power consumption (in mW) */
u32 cpu_avg_power;
u32 mch_avg_power;
/* Offset values */
u16 cta_val;
u16 pta_val;
u16 mgta_val;
/* Maximums & prefs, protected by turbo status lock */
spinlock_t turbo_status_lock;
u16 mcp_temp_limit;
u16 mcp_power_limit;
u16 core_power_limit;
u16 mch_power_limit;
bool cpu_turbo_enabled;
bool __cpu_turbo_on;
bool gpu_turbo_enabled;
bool __gpu_turbo_on;
bool gpu_preferred;
bool poll_turbo_status;
bool second_cpu;
bool turbo_toggle_allowed;
struct ips_mcp_limits *limits;
/* Optional MCH interfaces for if i915 is in use */
unsigned long (*read_mch_val)(void);
bool (*gpu_raise)(void);
bool (*gpu_lower)(void);
bool (*gpu_busy)(void);
bool (*gpu_turbo_disable)(void);
/* For restoration at unload */
u64 orig_turbo_limit;
u64 orig_turbo_ratios;
};
static bool
ips_gpu_turbo_enabled(struct ips_driver *ips);
/**
* ips_cpu_busy - is CPU busy?
* @ips: IPS driver struct
*
* Check CPU for load to see whether we should increase its thermal budget.
*
* RETURNS:
* True if the CPU could use more power, false otherwise.
*/
static bool ips_cpu_busy(struct ips_driver *ips)
{
if ((avenrun[0] >> FSHIFT) > 1)
return true;
return false;
}
/**
* ips_cpu_raise - raise CPU power clamp
* @ips: IPS driver struct
*
* Raise the CPU power clamp by %IPS_CPU_STEP, in accordance with TDP for
* this platform.
*
* We do this by adjusting the TURBO_POWER_CURRENT_LIMIT MSR upwards (as
* long as we haven't hit the TDP limit for the SKU).
*/
static void ips_cpu_raise(struct ips_driver *ips)
{
u64 turbo_override;
u16 cur_tdp_limit, new_tdp_limit;
if (!ips->cpu_turbo_enabled)
return;
rdmsrl(TURBO_POWER_CURRENT_LIMIT, turbo_override);
cur_tdp_limit = turbo_override & TURBO_TDP_MASK;
new_tdp_limit = cur_tdp_limit + 8; /* 1W increase */
/* Clamp to SKU TDP limit */
if (((new_tdp_limit * 10) / 8) > ips->core_power_limit)
new_tdp_limit = cur_tdp_limit;
thm_writew(THM_MPCPC, (new_tdp_limit * 10) / 8);
turbo_override |= TURBO_TDC_OVR_EN | TURBO_TDP_OVR_EN;
wrmsrl(TURBO_POWER_CURRENT_LIMIT, turbo_override);
turbo_override &= ~TURBO_TDP_MASK;
turbo_override |= new_tdp_limit;
wrmsrl(TURBO_POWER_CURRENT_LIMIT, turbo_override);
}
/**
* ips_cpu_lower - lower CPU power clamp
* @ips: IPS driver struct
*
* Lower CPU power clamp b %IPS_CPU_STEP if possible.
*
* We do this by adjusting the TURBO_POWER_CURRENT_LIMIT MSR down, going
* as low as the platform limits will allow (though we could go lower there
* wouldn't be much point).
*/
static void ips_cpu_lower(struct ips_driver *ips)
{
u64 turbo_override;
u16 cur_limit, new_limit;
rdmsrl(TURBO_POWER_CURRENT_LIMIT, turbo_override);
cur_limit = turbo_override & TURBO_TDP_MASK;
new_limit = cur_limit - 8; /* 1W decrease */
/* Clamp to SKU TDP limit */
if (new_limit < (ips->orig_turbo_limit & TURBO_TDP_MASK))
new_limit = ips->orig_turbo_limit & TURBO_TDP_MASK;
thm_writew(THM_MPCPC, (new_limit * 10) / 8);
turbo_override |= TURBO_TDC_OVR_EN | TURBO_TDP_OVR_EN;
wrmsrl(TURBO_POWER_CURRENT_LIMIT, turbo_override);
turbo_override &= ~TURBO_TDP_MASK;
turbo_override |= new_limit;
wrmsrl(TURBO_POWER_CURRENT_LIMIT, turbo_override);
}
/**
* do_enable_cpu_turbo - internal turbo enable function
* @data: unused
*
* Internal function for actually updating MSRs. When we enable/disable
* turbo, we need to do it on each CPU; this function is the one called
* by on_each_cpu() when needed.
*/
static void do_enable_cpu_turbo(void *data)
{
u64 perf_ctl;
rdmsrl(IA32_PERF_CTL, perf_ctl);
if (perf_ctl & IA32_PERF_TURBO_DIS) {
perf_ctl &= ~IA32_PERF_TURBO_DIS;
wrmsrl(IA32_PERF_CTL, perf_ctl);
}
}
/**
* ips_enable_cpu_turbo - enable turbo mode on all CPUs
* @ips: IPS driver struct
*
* Enable turbo mode by clearing the disable bit in IA32_PERF_CTL on
* all logical threads.
*/
static void ips_enable_cpu_turbo(struct ips_driver *ips)
{
/* Already on, no need to mess with MSRs */
if (ips->__cpu_turbo_on)
return;
if (ips->turbo_toggle_allowed)
on_each_cpu(do_enable_cpu_turbo, ips, 1);
ips->__cpu_turbo_on = true;
}
/**
* do_disable_cpu_turbo - internal turbo disable function
* @data: unused
*
* Internal function for actually updating MSRs. When we enable/disable
* turbo, we need to do it on each CPU; this function is the one called
* by on_each_cpu() when needed.
*/
static void do_disable_cpu_turbo(void *data)
{
u64 perf_ctl;
rdmsrl(IA32_PERF_CTL, perf_ctl);
if (!(perf_ctl & IA32_PERF_TURBO_DIS)) {
perf_ctl |= IA32_PERF_TURBO_DIS;
wrmsrl(IA32_PERF_CTL, perf_ctl);
}
}
/**
* ips_disable_cpu_turbo - disable turbo mode on all CPUs
* @ips: IPS driver struct
*
* Disable turbo mode by setting the disable bit in IA32_PERF_CTL on
* all logical threads.
*/
static void ips_disable_cpu_turbo(struct ips_driver *ips)
{
/* Already off, leave it */
if (!ips->__cpu_turbo_on)
return;
if (ips->turbo_toggle_allowed)
on_each_cpu(do_disable_cpu_turbo, ips, 1);
ips->__cpu_turbo_on = false;
}
/**
* ips_gpu_busy - is GPU busy?
* @ips: IPS driver struct
*
* Check GPU for load to see whether we should increase its thermal budget.
* We need to call into the i915 driver in this case.
*
* RETURNS:
* True if the GPU could use more power, false otherwise.
*/
static bool ips_gpu_busy(struct ips_driver *ips)
{
if (!ips_gpu_turbo_enabled(ips))
return false;
return ips->gpu_busy();
}
/**
* ips_gpu_raise - raise GPU power clamp
* @ips: IPS driver struct
*
* Raise the GPU frequency/power if possible. We need to call into the
* i915 driver in this case.
*/
static void ips_gpu_raise(struct ips_driver *ips)
{
if (!ips_gpu_turbo_enabled(ips))
return;
if (!ips->gpu_raise())
ips->gpu_turbo_enabled = false;
return;
}
/**
* ips_gpu_lower - lower GPU power clamp
* @ips: IPS driver struct
*
* Lower GPU frequency/power if possible. Need to call i915.
*/
static void ips_gpu_lower(struct ips_driver *ips)
{
if (!ips_gpu_turbo_enabled(ips))
return;
if (!ips->gpu_lower())
ips->gpu_turbo_enabled = false;
return;
}
/**
* ips_enable_gpu_turbo - notify the gfx driver turbo is available
* @ips: IPS driver struct
*
* Call into the graphics driver indicating that it can safely use
* turbo mode.
*/
static void ips_enable_gpu_turbo(struct ips_driver *ips)
{
if (ips->__gpu_turbo_on)
return;
ips->__gpu_turbo_on = true;
}
/**
* ips_disable_gpu_turbo - notify the gfx driver to disable turbo mode
* @ips: IPS driver struct
*
* Request that the graphics driver disable turbo mode.
*/
static void ips_disable_gpu_turbo(struct ips_driver *ips)
{
/* Avoid calling i915 if turbo is already disabled */
if (!ips->__gpu_turbo_on)
return;
if (!ips->gpu_turbo_disable())
dev_err(ips->dev, "failed to disable graphics turbo\n");
else
ips->__gpu_turbo_on = false;
}
/**
* mcp_exceeded - check whether we're outside our thermal & power limits
* @ips: IPS driver struct
*
* Check whether the MCP is over its thermal or power budget.
*/
static bool mcp_exceeded(struct ips_driver *ips)
{
unsigned long flags;
bool ret = false;
u32 temp_limit;
u32 avg_power;
spin_lock_irqsave(&ips->turbo_status_lock, flags);
temp_limit = ips->mcp_temp_limit * 100;
if (ips->mcp_avg_temp > temp_limit)
ret = true;
avg_power = ips->cpu_avg_power + ips->mch_avg_power;
if (avg_power > ips->mcp_power_limit)
ret = true;
spin_unlock_irqrestore(&ips->turbo_status_lock, flags);
return ret;
}
/**
* cpu_exceeded - check whether a CPU core is outside its limits
* @ips: IPS driver struct
* @cpu: CPU number to check
*
* Check a given CPU's average temp or power is over its limit.
*/
static bool cpu_exceeded(struct ips_driver *ips, int cpu)
{
unsigned long flags;
int avg;
bool ret = false;
spin_lock_irqsave(&ips->turbo_status_lock, flags);
avg = cpu ? ips->ctv2_avg_temp : ips->ctv1_avg_temp;
if (avg > (ips->limits->core_temp_limit * 100))
ret = true;
if (ips->cpu_avg_power > ips->core_power_limit * 100)
ret = true;
spin_unlock_irqrestore(&ips->turbo_status_lock, flags);
if (ret)
dev_info(ips->dev, "CPU power or thermal limit exceeded\n");
return ret;
}
/**
* mch_exceeded - check whether the GPU is over budget
* @ips: IPS driver struct
*
* Check the MCH temp & power against their maximums.
*/
static bool mch_exceeded(struct ips_driver *ips)
{
unsigned long flags;
bool ret = false;
spin_lock_irqsave(&ips->turbo_status_lock, flags);
if (ips->mch_avg_temp > (ips->limits->mch_temp_limit * 100))
ret = true;
if (ips->mch_avg_power > ips->mch_power_limit)
ret = true;
spin_unlock_irqrestore(&ips->turbo_status_lock, flags);
return ret;
}
/**
* verify_limits - verify BIOS provided limits
* @ips: IPS structure
*
* BIOS can optionally provide non-default limits for power and temp. Check
* them here and use the defaults if the BIOS values are not provided or
* are otherwise unusable.
*/
static void verify_limits(struct ips_driver *ips)
{
if (ips->mcp_power_limit < ips->limits->mcp_power_limit ||
ips->mcp_power_limit > 35000)
ips->mcp_power_limit = ips->limits->mcp_power_limit;
if (ips->mcp_temp_limit < ips->limits->core_temp_limit ||
ips->mcp_temp_limit < ips->limits->mch_temp_limit ||
ips->mcp_temp_limit > 150)
ips->mcp_temp_limit = min(ips->limits->core_temp_limit,
ips->limits->mch_temp_limit);
}
/**
* update_turbo_limits - get various limits & settings from regs
* @ips: IPS driver struct
*
* Update the IPS power & temp limits, along with turbo enable flags,
* based on latest register contents.
*
* Used at init time and for runtime BIOS support, which requires polling
* the regs for updates (as a result of AC->DC transition for example).
*
* LOCKING:
* Caller must hold turbo_status_lock (outside of init)
*/
static void update_turbo_limits(struct ips_driver *ips)
{
u32 hts = thm_readl(THM_HTS);
ips->cpu_turbo_enabled = !(hts & HTS_PCTD_DIS);
/*
* Disable turbo for now, until we can figure out why the power figures
* are wrong
*/
ips->cpu_turbo_enabled = false;
if (ips->gpu_busy)
ips->gpu_turbo_enabled = !(hts & HTS_GTD_DIS);
ips->core_power_limit = thm_readw(THM_MPCPC);
ips->mch_power_limit = thm_readw(THM_MMGPC);
ips->mcp_temp_limit = thm_readw(THM_PTL);
ips->mcp_power_limit = thm_readw(THM_MPPC);
verify_limits(ips);
/* Ignore BIOS CPU vs GPU pref */
}
/**
* ips_adjust - adjust power clamp based on thermal state
* @data: ips driver structure
*
* Wake up every 5s or so and check whether we should adjust the power clamp.
* Check CPU and GPU load to determine which needs adjustment. There are
* several things to consider here:
* - do we need to adjust up or down?
* - is CPU busy?
* - is GPU busy?
* - is CPU in turbo?
* - is GPU in turbo?
* - is CPU or GPU preferred? (CPU is default)
*
* So, given the above, we do the following:
* - up (TDP available)
* - CPU not busy, GPU not busy - nothing
* - CPU busy, GPU not busy - adjust CPU up
* - CPU not busy, GPU busy - adjust GPU up
* - CPU busy, GPU busy - adjust preferred unit up, taking headroom from
* non-preferred unit if necessary
* - down (at TDP limit)
* - adjust both CPU and GPU down if possible
*
cpu+ gpu+ cpu+gpu- cpu-gpu+ cpu-gpu-
cpu < gpu < cpu+gpu+ cpu+ gpu+ nothing
cpu < gpu >= cpu+gpu-(mcp<) cpu+gpu-(mcp<) gpu- gpu-
cpu >= gpu < cpu-gpu+(mcp<) cpu- cpu-gpu+(mcp<) cpu-
cpu >= gpu >= cpu-gpu- cpu-gpu- cpu-gpu- cpu-gpu-
*
*/
static int ips_adjust(void *data)
{
struct ips_driver *ips = data;
unsigned long flags;
dev_dbg(ips->dev, "starting ips-adjust thread\n");
/*
* Adjust CPU and GPU clamps every 5s if needed. Doing it more
* often isn't recommended due to ME interaction.
*/
do {
bool cpu_busy = ips_cpu_busy(ips);
bool gpu_busy = ips_gpu_busy(ips);
spin_lock_irqsave(&ips->turbo_status_lock, flags);
if (ips->poll_turbo_status)
update_turbo_limits(ips);
spin_unlock_irqrestore(&ips->turbo_status_lock, flags);
/* Update turbo status if necessary */
if (ips->cpu_turbo_enabled)
ips_enable_cpu_turbo(ips);
else
ips_disable_cpu_turbo(ips);
if (ips->gpu_turbo_enabled)
ips_enable_gpu_turbo(ips);
else
ips_disable_gpu_turbo(ips);
/* We're outside our comfort zone, crank them down */
if (mcp_exceeded(ips)) {
ips_cpu_lower(ips);
ips_gpu_lower(ips);
goto sleep;
}
if (!cpu_exceeded(ips, 0) && cpu_busy)
ips_cpu_raise(ips);
else
ips_cpu_lower(ips);
if (!mch_exceeded(ips) && gpu_busy)
ips_gpu_raise(ips);
else
ips_gpu_lower(ips);
sleep:
schedule_timeout_interruptible(msecs_to_jiffies(IPS_ADJUST_PERIOD));
} while (!kthread_should_stop());
dev_dbg(ips->dev, "ips-adjust thread stopped\n");
return 0;
}
/*
* Helpers for reading out temp/power values and calculating their
* averages for the decision making and monitoring functions.
*/
static u16 calc_avg_temp(struct ips_driver *ips, u16 *array)
{
u64 total = 0;
int i;
u16 avg;
for (i = 0; i < IPS_SAMPLE_COUNT; i++)
total += (u64)(array[i] * 100);
do_div(total, IPS_SAMPLE_COUNT);
avg = (u16)total;
return avg;
}
static u16 read_mgtv(struct ips_driver *ips)
{
u16 ret;
u64 slope, offset;
u64 val;
val = thm_readq(THM_MGTV);
val = (val & TV_MASK) >> TV_SHIFT;
slope = offset = thm_readw(THM_MGTA);
slope = (slope & MGTA_SLOPE_MASK) >> MGTA_SLOPE_SHIFT;
offset = offset & MGTA_OFFSET_MASK;
ret = ((val * slope + 0x40) >> 7) + offset;
return 0; /* MCH temp reporting buggy */
}
static u16 read_ptv(struct ips_driver *ips)
{
u16 val;
val = thm_readw(THM_PTV) & PTV_MASK;
return val;
}
static u16 read_ctv(struct ips_driver *ips, int cpu)
{
int reg = cpu ? THM_CTV2 : THM_CTV1;
u16 val;
val = thm_readw(reg);
if (!(val & CTV_TEMP_ERROR))
val = (val) >> 6; /* discard fractional component */
else
val = 0;
return val;
}
static u32 get_cpu_power(struct ips_driver *ips, u32 *last, int period)
{
u32 val;
u32 ret;
/*
* CEC is in joules/65535. Take difference over time to
* get watts.
*/
val = thm_readl(THM_CEC);
/* period is in ms and we want mW */
ret = (((val - *last) * 1000) / period);
ret = (ret * 1000) / 65535;
*last = val;
return 0;
}
static const u16 temp_decay_factor = 2;
static u16 update_average_temp(u16 avg, u16 val)
{
u16 ret;
/* Multiply by 100 for extra precision */
ret = (val * 100 / temp_decay_factor) +
(((temp_decay_factor - 1) * avg) / temp_decay_factor);
return ret;
}
static const u16 power_decay_factor = 2;
static u16 update_average_power(u32 avg, u32 val)
{
u32 ret;
ret = (val / power_decay_factor) +
(((power_decay_factor - 1) * avg) / power_decay_factor);
return ret;
}
static u32 calc_avg_power(struct ips_driver *ips, u32 *array)
{
u64 total = 0;
u32 avg;
int i;
for (i = 0; i < IPS_SAMPLE_COUNT; i++)
total += array[i];
do_div(total, IPS_SAMPLE_COUNT);
avg = (u32)total;
return avg;
}
static void monitor_timeout(struct timer_list *t)
{
struct ips_driver *ips = from_timer(ips, t, timer);
wake_up_process(ips->monitor);
}
/**
* ips_monitor - temp/power monitoring thread
* @data: ips driver structure
*
* This is the main function for the IPS driver. It monitors power and
* tempurature in the MCP and adjusts CPU and GPU power clams accordingly.
*
* We keep a 5s moving average of power consumption and tempurature. Using
* that data, along with CPU vs GPU preference, we adjust the power clamps
* up or down.
*/
static int ips_monitor(void *data)
{
struct ips_driver *ips = data;
unsigned long seqno_timestamp, expire, last_msecs, last_sample_period;
int i;
u32 *cpu_samples, *mchp_samples, old_cpu_power;
u16 *mcp_samples, *ctv1_samples, *ctv2_samples, *mch_samples;
u8 cur_seqno, last_seqno;
mcp_samples = kcalloc(IPS_SAMPLE_COUNT, sizeof(u16), GFP_KERNEL);
ctv1_samples = kcalloc(IPS_SAMPLE_COUNT, sizeof(u16), GFP_KERNEL);
ctv2_samples = kcalloc(IPS_SAMPLE_COUNT, sizeof(u16), GFP_KERNEL);
mch_samples = kcalloc(IPS_SAMPLE_COUNT, sizeof(u16), GFP_KERNEL);
cpu_samples = kcalloc(IPS_SAMPLE_COUNT, sizeof(u32), GFP_KERNEL);
mchp_samples = kcalloc(IPS_SAMPLE_COUNT, sizeof(u32), GFP_KERNEL);
if (!mcp_samples || !ctv1_samples || !ctv2_samples || !mch_samples ||
!cpu_samples || !mchp_samples) {
dev_err(ips->dev,
"failed to allocate sample array, ips disabled\n");
kfree(mcp_samples);
kfree(ctv1_samples);
kfree(ctv2_samples);
kfree(mch_samples);
kfree(cpu_samples);
kfree(mchp_samples);
return -ENOMEM;
}
last_seqno = (thm_readl(THM_ITV) & ITV_ME_SEQNO_MASK) >>
ITV_ME_SEQNO_SHIFT;
seqno_timestamp = get_jiffies_64();
old_cpu_power = thm_readl(THM_CEC);
schedule_timeout_interruptible(msecs_to_jiffies(IPS_SAMPLE_PERIOD));
/* Collect an initial average */
for (i = 0; i < IPS_SAMPLE_COUNT; i++) {
u32 mchp, cpu_power;
u16 val;
mcp_samples[i] = read_ptv(ips);
val = read_ctv(ips, 0);
ctv1_samples[i] = val;
val = read_ctv(ips, 1);
ctv2_samples[i] = val;
val = read_mgtv(ips);
mch_samples[i] = val;
cpu_power = get_cpu_power(ips, &old_cpu_power,
IPS_SAMPLE_PERIOD);
cpu_samples[i] = cpu_power;
if (ips->read_mch_val) {
mchp = ips->read_mch_val();
mchp_samples[i] = mchp;
}
schedule_timeout_interruptible(msecs_to_jiffies(IPS_SAMPLE_PERIOD));
if (kthread_should_stop())
break;
}
ips->mcp_avg_temp = calc_avg_temp(ips, mcp_samples);
ips->ctv1_avg_temp = calc_avg_temp(ips, ctv1_samples);
ips->ctv2_avg_temp = calc_avg_temp(ips, ctv2_samples);
ips->mch_avg_temp = calc_avg_temp(ips, mch_samples);
ips->cpu_avg_power = calc_avg_power(ips, cpu_samples);
ips->mch_avg_power = calc_avg_power(ips, mchp_samples);
kfree(mcp_samples);
kfree(ctv1_samples);
kfree(ctv2_samples);
kfree(mch_samples);
kfree(cpu_samples);
kfree(mchp_samples);
/* Start the adjustment thread now that we have data */
wake_up_process(ips->adjust);
/*
* Ok, now we have an initial avg. From here on out, we track the
* running avg using a decaying average calculation. This allows
* us to reduce the sample frequency if the CPU and GPU are idle.
*/
old_cpu_power = thm_readl(THM_CEC);
schedule_timeout_interruptible(msecs_to_jiffies(IPS_SAMPLE_PERIOD));
last_sample_period = IPS_SAMPLE_PERIOD;
timer_setup(&ips->timer, monitor_timeout, TIMER_DEFERRABLE);
do {
u32 cpu_val, mch_val;
u16 val;
/* MCP itself */
val = read_ptv(ips);
ips->mcp_avg_temp = update_average_temp(ips->mcp_avg_temp, val);
/* Processor 0 */
val = read_ctv(ips, 0);
ips->ctv1_avg_temp =
update_average_temp(ips->ctv1_avg_temp, val);
/* Power */
cpu_val = get_cpu_power(ips, &old_cpu_power,
last_sample_period);
ips->cpu_avg_power =
update_average_power(ips->cpu_avg_power, cpu_val);
if (ips->second_cpu) {
/* Processor 1 */
val = read_ctv(ips, 1);
ips->ctv2_avg_temp =
update_average_temp(ips->ctv2_avg_temp, val);
}
/* MCH */
val = read_mgtv(ips);
ips->mch_avg_temp = update_average_temp(ips->mch_avg_temp, val);
/* Power */
if (ips->read_mch_val) {
mch_val = ips->read_mch_val();
ips->mch_avg_power =
update_average_power(ips->mch_avg_power,
mch_val);
}
/*
* Make sure ME is updating thermal regs.
* Note:
* If it's been more than a second since the last update,
* the ME is probably hung.
*/
cur_seqno = (thm_readl(THM_ITV) & ITV_ME_SEQNO_MASK) >>
ITV_ME_SEQNO_SHIFT;
if (cur_seqno == last_seqno &&
time_after(jiffies, seqno_timestamp + HZ)) {
dev_warn(ips->dev,
"ME failed to update for more than 1s, likely hung\n");
} else {
seqno_timestamp = get_jiffies_64();
last_seqno = cur_seqno;
}
last_msecs = jiffies_to_msecs(jiffies);
expire = jiffies + msecs_to_jiffies(IPS_SAMPLE_PERIOD);
__set_current_state(TASK_INTERRUPTIBLE);
mod_timer(&ips->timer, expire);
schedule();
/* Calculate actual sample period for power averaging */
last_sample_period = jiffies_to_msecs(jiffies) - last_msecs;
if (!last_sample_period)
last_sample_period = 1;
} while (!kthread_should_stop());
del_timer_sync(&ips->timer);
dev_dbg(ips->dev, "ips-monitor thread stopped\n");
return 0;
}
#if 0
#define THM_DUMPW(reg) \
{ \
u16 val = thm_readw(reg); \
dev_dbg(ips->dev, #reg ": 0x%04x\n", val); \
}
#define THM_DUMPL(reg) \
{ \
u32 val = thm_readl(reg); \
dev_dbg(ips->dev, #reg ": 0x%08x\n", val); \
}
#define THM_DUMPQ(reg) \
{ \
u64 val = thm_readq(reg); \
dev_dbg(ips->dev, #reg ": 0x%016x\n", val); \
}
static void dump_thermal_info(struct ips_driver *ips)
{
u16 ptl;
ptl = thm_readw(THM_PTL);
dev_dbg(ips->dev, "Processor temp limit: %d\n", ptl);
THM_DUMPW(THM_CTA);
THM_DUMPW(THM_TRC);
THM_DUMPW(THM_CTV1);
THM_DUMPL(THM_STS);
THM_DUMPW(THM_PTV);
THM_DUMPQ(THM_MGTV);
}
#endif
/**
* ips_irq_handler - handle temperature triggers and other IPS events
* @irq: irq number
* @arg: unused
*
* Handle temperature limit trigger events, generally by lowering the clamps.
* If we're at a critical limit, we clamp back to the lowest possible value
* to prevent emergency shutdown.
*/
static irqreturn_t ips_irq_handler(int irq, void *arg)
{
struct ips_driver *ips = arg;
u8 tses = thm_readb(THM_TSES);
u8 tes = thm_readb(THM_TES);
if (!tses && !tes)
return IRQ_NONE;
dev_info(ips->dev, "TSES: 0x%02x\n", tses);
dev_info(ips->dev, "TES: 0x%02x\n", tes);
/* STS update from EC? */
if (tes & 1) {
u32 sts, tc1;
sts = thm_readl(THM_STS);
tc1 = thm_readl(THM_TC1);
if (sts & STS_NVV) {
spin_lock(&ips->turbo_status_lock);
ips->core_power_limit = (sts & STS_PCPL_MASK) >>
STS_PCPL_SHIFT;
ips->mch_power_limit = (sts & STS_GPL_MASK) >>
STS_GPL_SHIFT;
/* ignore EC CPU vs GPU pref */
ips->cpu_turbo_enabled = !(sts & STS_PCTD_DIS);
/*
* Disable turbo for now, until we can figure
* out why the power figures are wrong
*/
ips->cpu_turbo_enabled = false;
if (ips->gpu_busy)
ips->gpu_turbo_enabled = !(sts & STS_GTD_DIS);
ips->mcp_temp_limit = (sts & STS_PTL_MASK) >>
STS_PTL_SHIFT;
ips->mcp_power_limit = (tc1 & STS_PPL_MASK) >>
STS_PPL_SHIFT;
verify_limits(ips);
spin_unlock(&ips->turbo_status_lock);
thm_writeb(THM_SEC, SEC_ACK);
}
thm_writeb(THM_TES, tes);
}
/* Thermal trip */
if (tses) {
dev_warn(ips->dev, "thermal trip occurred, tses: 0x%04x\n",
tses);
thm_writeb(THM_TSES, tses);
}
return IRQ_HANDLED;
}
#ifndef CONFIG_DEBUG_FS
static void ips_debugfs_init(struct ips_driver *ips) { return; }
static void ips_debugfs_cleanup(struct ips_driver *ips) { return; }
#else
/* Expose current state and limits in debugfs if possible */
static int cpu_temp_show(struct seq_file *m, void *data)
{
struct ips_driver *ips = m->private;
seq_printf(m, "%d.%02d\n", ips->ctv1_avg_temp / 100,
ips->ctv1_avg_temp % 100);
return 0;
}
DEFINE_SHOW_ATTRIBUTE(cpu_temp);
static int cpu_power_show(struct seq_file *m, void *data)
{
struct ips_driver *ips = m->private;
seq_printf(m, "%dmW\n", ips->cpu_avg_power);
return 0;
}
DEFINE_SHOW_ATTRIBUTE(cpu_power);
static int cpu_clamp_show(struct seq_file *m, void *data)
{
u64 turbo_override;
int tdp, tdc;
rdmsrl(TURBO_POWER_CURRENT_LIMIT, turbo_override);
tdp = (int)(turbo_override & TURBO_TDP_MASK);
tdc = (int)((turbo_override & TURBO_TDC_MASK) >> TURBO_TDC_SHIFT);
/* Convert to .1W/A units */
tdp = tdp * 10 / 8;
tdc = tdc * 10 / 8;
/* Watts Amperes */
seq_printf(m, "%d.%dW %d.%dA\n", tdp / 10, tdp % 10,
tdc / 10, tdc % 10);
return 0;
}
DEFINE_SHOW_ATTRIBUTE(cpu_clamp);
static int mch_temp_show(struct seq_file *m, void *data)
{
struct ips_driver *ips = m->private;
seq_printf(m, "%d.%02d\n", ips->mch_avg_temp / 100,
ips->mch_avg_temp % 100);
return 0;
}
DEFINE_SHOW_ATTRIBUTE(mch_temp);
static int mch_power_show(struct seq_file *m, void *data)
{
struct ips_driver *ips = m->private;
seq_printf(m, "%dmW\n", ips->mch_avg_power);
return 0;
}
DEFINE_SHOW_ATTRIBUTE(mch_power);
static void ips_debugfs_cleanup(struct ips_driver *ips)
{
debugfs_remove_recursive(ips->debug_root);
}
static void ips_debugfs_init(struct ips_driver *ips)
{
ips->debug_root = debugfs_create_dir("ips", NULL);
debugfs_create_file("cpu_temp", 0444, ips->debug_root, ips, &cpu_temp_fops);
debugfs_create_file("cpu_power", 0444, ips->debug_root, ips, &cpu_power_fops);
debugfs_create_file("cpu_clamp", 0444, ips->debug_root, ips, &cpu_clamp_fops);
debugfs_create_file("mch_temp", 0444, ips->debug_root, ips, &mch_temp_fops);
debugfs_create_file("mch_power", 0444, ips->debug_root, ips, &mch_power_fops);
}
#endif /* CONFIG_DEBUG_FS */
/**
* ips_detect_cpu - detect whether CPU supports IPS
*
* Walk our list and see if we're on a supported CPU. If we find one,
* return the limits for it.
*/
static struct ips_mcp_limits *ips_detect_cpu(struct ips_driver *ips)
{
u64 turbo_power, misc_en;
struct ips_mcp_limits *limits = NULL;
u16 tdp;
if (!(boot_cpu_data.x86 == 6 && boot_cpu_data.x86_model == 37)) {
dev_info(ips->dev, "Non-IPS CPU detected.\n");
return NULL;
}
rdmsrl(IA32_MISC_ENABLE, misc_en);
/*
* If the turbo enable bit isn't set, we shouldn't try to enable/disable
* turbo manually or we'll get an illegal MSR access, even though
* turbo will still be available.
*/
if (misc_en & IA32_MISC_TURBO_EN)
ips->turbo_toggle_allowed = true;
else
ips->turbo_toggle_allowed = false;
if (strstr(boot_cpu_data.x86_model_id, "CPU M"))
limits = &ips_sv_limits;
else if (strstr(boot_cpu_data.x86_model_id, "CPU L"))
limits = &ips_lv_limits;
else if (strstr(boot_cpu_data.x86_model_id, "CPU U"))
limits = &ips_ulv_limits;
else {
dev_info(ips->dev, "No CPUID match found.\n");
return NULL;
}
rdmsrl(TURBO_POWER_CURRENT_LIMIT, turbo_power);
tdp = turbo_power & TURBO_TDP_MASK;
/* Sanity check TDP against CPU */
if (limits->core_power_limit != (tdp / 8) * 1000) {
dev_info(ips->dev,
"CPU TDP doesn't match expected value (found %d, expected %d)\n",
tdp / 8, limits->core_power_limit / 1000);
limits->core_power_limit = (tdp / 8) * 1000;
}
return limits;
}
/**
* ips_get_i915_syms - try to get GPU control methods from i915 driver
* @ips: IPS driver
*
* The i915 driver exports several interfaces to allow the IPS driver to
* monitor and control graphics turbo mode. If we can find them, we can
* enable graphics turbo, otherwise we must disable it to avoid exceeding
* thermal and power limits in the MCP.
*/
static bool ips_get_i915_syms(struct ips_driver *ips)
{
ips->read_mch_val = symbol_get(i915_read_mch_val);
if (!ips->read_mch_val)
goto out_err;
ips->gpu_raise = symbol_get(i915_gpu_raise);
if (!ips->gpu_raise)
goto out_put_mch;
ips->gpu_lower = symbol_get(i915_gpu_lower);
if (!ips->gpu_lower)
goto out_put_raise;
ips->gpu_busy = symbol_get(i915_gpu_busy);
if (!ips->gpu_busy)
goto out_put_lower;
ips->gpu_turbo_disable = symbol_get(i915_gpu_turbo_disable);
if (!ips->gpu_turbo_disable)
goto out_put_busy;
return true;
out_put_busy:
symbol_put(i915_gpu_busy);
out_put_lower:
symbol_put(i915_gpu_lower);
out_put_raise:
symbol_put(i915_gpu_raise);
out_put_mch:
symbol_put(i915_read_mch_val);
out_err:
return false;
}
static bool
ips_gpu_turbo_enabled(struct ips_driver *ips)
{
if (!ips->gpu_busy && late_i915_load) {
if (ips_get_i915_syms(ips)) {
dev_info(ips->dev,
"i915 driver attached, reenabling gpu turbo\n");
ips->gpu_turbo_enabled = !(thm_readl(THM_HTS) & HTS_GTD_DIS);
}
}
return ips->gpu_turbo_enabled;
}
void
ips_link_to_i915_driver(void)
{
/* We can't cleanly get at the various ips_driver structs from
* this caller (the i915 driver), so just set a flag saying
* that it's time to try getting the symbols again.
*/
late_i915_load = true;
}
EXPORT_SYMBOL_GPL(ips_link_to_i915_driver);
static const struct pci_device_id ips_id_table[] = {
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_THERMAL_SENSOR), },
{ 0, }
};
MODULE_DEVICE_TABLE(pci, ips_id_table);
static int ips_blacklist_callback(const struct dmi_system_id *id)
{
pr_info("Blacklisted intel_ips for %s\n", id->ident);
return 1;
}
static const struct dmi_system_id ips_blacklist[] = {
{
.callback = ips_blacklist_callback,
.ident = "HP ProBook",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Hewlett-Packard"),
DMI_MATCH(DMI_PRODUCT_NAME, "HP ProBook"),
},
},
{ } /* terminating entry */
};
static int ips_probe(struct pci_dev *dev, const struct pci_device_id *id)
{
u64 platform_info;
struct ips_driver *ips;
u32 hts;
int ret = 0;
u16 htshi, trc, trc_required_mask;
u8 tse;
if (dmi_check_system(ips_blacklist))
return -ENODEV;
ips = devm_kzalloc(&dev->dev, sizeof(*ips), GFP_KERNEL);
if (!ips)
return -ENOMEM;
spin_lock_init(&ips->turbo_status_lock);
ips->dev = &dev->dev;
ips->limits = ips_detect_cpu(ips);
if (!ips->limits) {
dev_info(&dev->dev, "IPS not supported on this CPU\n");
return -ENXIO;
}
ret = pcim_enable_device(dev);
if (ret) {
dev_err(&dev->dev, "can't enable PCI device, aborting\n");
return ret;
}
ret = pcim_iomap_regions(dev, 1 << 0, pci_name(dev));
if (ret) {
dev_err(&dev->dev, "failed to map thermal regs, aborting\n");
return ret;
}
ips->regmap = pcim_iomap_table(dev)[0];
pci_set_drvdata(dev, ips);
tse = thm_readb(THM_TSE);
if (tse != TSE_EN) {
dev_err(&dev->dev, "thermal device not enabled (0x%02x), aborting\n", tse);
return -ENXIO;
}
trc = thm_readw(THM_TRC);
trc_required_mask = TRC_CORE1_EN | TRC_CORE_PWR | TRC_MCH_EN;
if ((trc & trc_required_mask) != trc_required_mask) {
dev_err(&dev->dev, "thermal reporting for required devices not enabled, aborting\n");
return -ENXIO;
}
if (trc & TRC_CORE2_EN)
ips->second_cpu = true;
update_turbo_limits(ips);
dev_dbg(&dev->dev, "max cpu power clamp: %dW\n",
ips->mcp_power_limit / 10);
dev_dbg(&dev->dev, "max core power clamp: %dW\n",
ips->core_power_limit / 10);
/* BIOS may update limits at runtime */
if (thm_readl(THM_PSC) & PSP_PBRT)
ips->poll_turbo_status = true;
if (!ips_get_i915_syms(ips)) {
dev_info(&dev->dev, "failed to get i915 symbols, graphics turbo disabled until i915 loads\n");
ips->gpu_turbo_enabled = false;
} else {
dev_dbg(&dev->dev, "graphics turbo enabled\n");
ips->gpu_turbo_enabled = true;
}
/*
* Check PLATFORM_INFO MSR to make sure this chip is
* turbo capable.
*/
rdmsrl(PLATFORM_INFO, platform_info);
if (!(platform_info & PLATFORM_TDP)) {
dev_err(&dev->dev, "platform indicates TDP override unavailable, aborting\n");
return -ENODEV;
}
/*
* IRQ handler for ME interaction
* Note: don't use MSI here as the PCH has bugs.
*/
ret = pci_alloc_irq_vectors(dev, 1, 1, PCI_IRQ_LEGACY);
if (ret < 0)
return ret;
ips->irq = pci_irq_vector(dev, 0);
ret = request_irq(ips->irq, ips_irq_handler, IRQF_SHARED, "ips", ips);
if (ret) {
dev_err(&dev->dev, "request irq failed, aborting\n");
return ret;
}
/* Enable aux, hot & critical interrupts */
thm_writeb(THM_TSPIEN, TSPIEN_AUX2_LOHI | TSPIEN_CRIT_LOHI |
TSPIEN_HOT_LOHI | TSPIEN_AUX_LOHI);
thm_writeb(THM_TEN, TEN_UPDATE_EN);
/* Collect adjustment values */
ips->cta_val = thm_readw(THM_CTA);
ips->pta_val = thm_readw(THM_PTA);
ips->mgta_val = thm_readw(THM_MGTA);
/* Save turbo limits & ratios */
rdmsrl(TURBO_POWER_CURRENT_LIMIT, ips->orig_turbo_limit);
ips_disable_cpu_turbo(ips);
ips->cpu_turbo_enabled = false;
/* Create thermal adjust thread */
ips->adjust = kthread_create(ips_adjust, ips, "ips-adjust");
if (IS_ERR(ips->adjust)) {
dev_err(&dev->dev,
"failed to create thermal adjust thread, aborting\n");
ret = -ENOMEM;
goto error_free_irq;
}
/*
* Set up the work queue and monitor thread. The monitor thread
* will wake up ips_adjust thread.
*/
ips->monitor = kthread_run(ips_monitor, ips, "ips-monitor");
if (IS_ERR(ips->monitor)) {
dev_err(&dev->dev,
"failed to create thermal monitor thread, aborting\n");
ret = -ENOMEM;
goto error_thread_cleanup;
}
hts = (ips->core_power_limit << HTS_PCPL_SHIFT) |
(ips->mcp_temp_limit << HTS_PTL_SHIFT) | HTS_NVV;
htshi = HTS2_PRST_RUNNING << HTS2_PRST_SHIFT;
thm_writew(THM_HTSHI, htshi);
thm_writel(THM_HTS, hts);
ips_debugfs_init(ips);
dev_info(&dev->dev, "IPS driver initialized, MCP temp limit %d\n",
ips->mcp_temp_limit);
return ret;
error_thread_cleanup:
kthread_stop(ips->adjust);
error_free_irq:
free_irq(ips->irq, ips);
pci_free_irq_vectors(dev);
return ret;
}
static void ips_remove(struct pci_dev *dev)
{
struct ips_driver *ips = pci_get_drvdata(dev);
u64 turbo_override;
ips_debugfs_cleanup(ips);
/* Release i915 driver */
if (ips->read_mch_val)
symbol_put(i915_read_mch_val);
if (ips->gpu_raise)
symbol_put(i915_gpu_raise);
if (ips->gpu_lower)
symbol_put(i915_gpu_lower);
if (ips->gpu_busy)
symbol_put(i915_gpu_busy);
if (ips->gpu_turbo_disable)
symbol_put(i915_gpu_turbo_disable);
rdmsrl(TURBO_POWER_CURRENT_LIMIT, turbo_override);
turbo_override &= ~(TURBO_TDC_OVR_EN | TURBO_TDP_OVR_EN);
wrmsrl(TURBO_POWER_CURRENT_LIMIT, turbo_override);
wrmsrl(TURBO_POWER_CURRENT_LIMIT, ips->orig_turbo_limit);
free_irq(ips->irq, ips);
pci_free_irq_vectors(dev);
if (ips->adjust)
kthread_stop(ips->adjust);
if (ips->monitor)
kthread_stop(ips->monitor);
dev_dbg(&dev->dev, "IPS driver removed\n");
}
static struct pci_driver ips_pci_driver = {
.name = "intel ips",
.id_table = ips_id_table,
.probe = ips_probe,
.remove = ips_remove,
};
module_pci_driver(ips_pci_driver);
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("Jesse Barnes <jbarnes@virtuousgeek.org>");
MODULE_DESCRIPTION("Intelligent Power Sharing Driver");
| CSE3320/kernel-code | linux-5.8/drivers/platform/x86/intel_ips.c | C | gpl-2.0 | 42,748 |
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import osv
from openerp import netsvc
from openerp.tools.translate import _
class procurement_order(osv.osv):
_inherit = 'procurement.order'
def check_buy(self, cr, uid, ids, context=None):
for procurement in self.browse(cr, uid, ids, context=context):
for line in procurement.product_id.flow_pull_ids:
if line.location_id==procurement.location_id:
return line.type_proc=='buy'
return super(procurement_order, self).check_buy(cr, uid, ids)
def check_produce(self, cr, uid, ids, context=None):
for procurement in self.browse(cr, uid, ids, context=context):
for line in procurement.product_id.flow_pull_ids:
if line.location_id==procurement.location_id:
return line.type_proc=='produce'
return super(procurement_order, self).check_produce(cr, uid, ids)
def check_move(self, cr, uid, ids, context=None):
for procurement in self.browse(cr, uid, ids, context=context):
for line in procurement.product_id.flow_pull_ids:
if line.location_id==procurement.location_id:
return (line.type_proc=='move') and (line.location_src_id)
return False
def action_move_create(self, cr, uid, ids, context=None):
proc_obj = self.pool.get('procurement.order')
move_obj = self.pool.get('stock.move')
picking_obj=self.pool.get('stock.picking')
wf_service = netsvc.LocalService("workflow")
for proc in proc_obj.browse(cr, uid, ids, context=context):
line = None
for line in proc.product_id.flow_pull_ids:
if line.location_id == proc.location_id:
break
assert line, 'Line cannot be False if we are on this state of the workflow'
origin = (proc.origin or proc.name or '').split(':')[0] +':'+line.name
picking_id = picking_obj.create(cr, uid, {
'origin': origin,
'company_id': line.company_id and line.company_id.id or False,
'type': line.picking_type,
'stock_journal_id': line.journal_id and line.journal_id.id or False,
'move_type': 'one',
'partner_id': line.partner_address_id.id,
'note': _('Picking for pulled procurement coming from original location %s, pull rule %s, via original Procurement %s (#%d)') % (proc.location_id.name, line.name, proc.name, proc.id),
'invoice_state': line.invoice_state,
})
move_id = move_obj.create(cr, uid, {
'name': line.name,
'picking_id': picking_id,
'company_id': line.company_id and line.company_id.id or False,
'product_id': proc.product_id.id,
'date': proc.date_planned,
'product_qty': proc.product_qty,
'product_uom': proc.product_uom.id,
'product_uos_qty': (proc.product_uos and proc.product_uos_qty)\
or proc.product_qty,
'product_uos': (proc.product_uos and proc.product_uos.id)\
or proc.product_uom.id,
'partner_id': line.partner_address_id.id,
'location_id': line.location_src_id.id,
'location_dest_id': line.location_id.id,
'move_dest_id': proc.move_id and proc.move_id.id or False, # to verif, about history ?
'tracking_id': False,
'cancel_cascade': line.cancel_cascade,
'state': 'confirmed',
'note': _('Move for pulled procurement coming from original location %s, pull rule %s, via original Procurement %s (#%d)') % (proc.location_id.name, line.name, proc.name, proc.id),
})
if proc.move_id and proc.move_id.state in ('confirmed'):
move_obj.write(cr,uid, [proc.move_id.id], {
'state':'waiting'
}, context=context)
proc_id = proc_obj.create(cr, uid, {
'name': line.name,
'origin': origin,
'note': _('Pulled procurement coming from original location %s, pull rule %s, via original Procurement %s (#%d)') % (proc.location_id.name, line.name, proc.name, proc.id),
'company_id': line.company_id and line.company_id.id or False,
'date_planned': proc.date_planned,
'product_id': proc.product_id.id,
'product_qty': proc.product_qty,
'product_uom': proc.product_uom.id,
'product_uos_qty': (proc.product_uos and proc.product_uos_qty)\
or proc.product_qty,
'product_uos': (proc.product_uos and proc.product_uos.id)\
or proc.product_uom.id,
'location_id': line.location_src_id.id,
'procure_method': line.procure_method,
'move_id': move_id,
})
wf_service = netsvc.LocalService("workflow")
wf_service.trg_validate(uid, 'stock.picking', picking_id, 'button_confirm', cr)
wf_service.trg_validate(uid, 'procurement.order', proc_id, 'button_confirm', cr)
if proc.move_id:
move_obj.write(cr, uid, [proc.move_id.id],
{'location_id':proc.location_id.id})
msg = _('Pulled from another location.')
self.write(cr, uid, [proc.id], {'state':'running', 'message': msg})
self.message_post(cr, uid, [proc.id], body=msg, context=context)
# trigger direct processing (the new procurement shares the same planned date as the original one, which is already being processed)
wf_service.trg_validate(uid, 'procurement.order', proc_id, 'button_check', cr)
return False
procurement_order()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| jeffery9/mixprint_addons | stock_location/procurement_pull.py | Python | agpl-3.0 | 6,951 |
<?php
require_once('../../_include.php');
$config = SimpleSAML_Configuration::getInstance();
$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
// Get the local session
$session = SimpleSAML_Session::getInstance();
SimpleSAML_Logger::info('SAML2.0 - SP.SingleLogoutService: Accessing SAML 2.0 SP endpoint SingleLogoutService');
if (!$config->getBoolean('enable.saml20-sp', TRUE))
throw new SimpleSAML_Error_Error('NOACCESS');
// Destroy local session if exists.
$session->doLogout('saml2');
$binding = SAML2_Binding::getCurrentBinding();
$message = $binding->receive();
$idpEntityId = $message->getIssuer();
if ($idpEntityId === NULL) {
/* Without an issuer we have no way to respond to the message. */
throw new SimpleSAML_Error_BadRequest('Received message on logout endpoint without issuer.');
}
$spEntityId = $metadata->getMetaDataCurrentEntityId('saml20-sp-hosted');
$idpMetadata = $metadata->getMetaDataConfig($idpEntityId, 'saml20-idp-remote');
$spMetadata = $metadata->getMetaDataConfig($spEntityId, 'saml20-sp-hosted');
sspmod_saml_Message::validateMessage($idpMetadata, $spMetadata, $message);
if ($message instanceof SAML2_LogoutRequest) {
try {
// Extract some parameters from the logout request
$requestid = $message->getId();
SimpleSAML_Logger::info('SAML2.0 - SP.SingleLogoutService: IdP (' . $idpEntityId .
') is sending logout request to me SP (' . $spEntityId . ') requestid '.$requestid);
SimpleSAML_Logger::stats('saml20-idp-SLO idpinit ' . $spEntityId . ' ' . $idpEntityId);
/* Create response. */
$lr = sspmod_saml_Message::buildLogoutResponse($spMetadata, $idpMetadata);
$lr->setRelayState($message->getRelayState());
$lr->setInResponseTo($message->getId());
SimpleSAML_Logger::info('SAML2.0 - SP.SingleLogoutService: SP me (' . $spEntityId . ') is sending logout response to IdP (' . $idpEntityId . ')');
/* Send response. */
$binding = new SAML2_HTTPRedirect();
$binding->send($lr);
} catch (Exception $exception) {
throw new SimpleSAML_Error_Error('LOGOUTREQUEST', $exception);
}
} elseif ($message instanceof SAML2_LogoutResponse) {
SimpleSAML_Logger::stats('saml20-sp-SLO spinit ' . $spEntityId . ' ' . $idpEntityId);
$id = $message->getRelayState();
if (empty($id)) {
/* For backwardscompatibility. */
$id = $message->getInResponseTo();
}
$returnTo = $session->getData('spLogoutReturnTo', $id);
if (empty($returnTo)) {
throw new SimpleSAML_Error_Error('LOGOUTINFOLOST');
}
SimpleSAML_Utilities::redirect($returnTo);
} else {
throw new SimpleSAML_Error_Error('SLOSERVICEPARAMS');
}
?> | Maqsood137/service.selfhealthnetwork.com | www/saml2/sp/SingleLogoutService.php | PHP | lgpl-2.1 | 2,618 |
<!DOCTYPE HTML>
<html>
<body>
This test passes if there are two green squares below:<br>
<svg width="300" height="300">
<svg id="svg" width="100" height="100">
<rect width="100%" height="100%" fill="green"/>
</svg>
<svg id="svg" x="100" y="100" width="100" height="100">
<rect width="100%" height="100%" fill="green"/>
</svg>
</svg>
</body>
</html>
| nwjs/chromium.src | third_party/blink/web_tests/svg/custom/use-dynamic-attribute-setting-expected.html | HTML | bsd-3-clause | 365 |
<html manifest="resources/abort-cache-onprogress.manifest">
<script>
if (window.testRunner) {
testRunner.dumpAsText()
testRunner.waitUntilDone();
}
function log(message) {
document.getElementById("result").innerHTML += message + "\n";
}
function onprogress(event) {
log("loading resource: " + event.loaded + " / " + event.total);
if (event.loaded == 3)
applicationCache.abort();
}
function onnoupdate() {
log("FAILURE");
log("noupdate");
if (window.testRunner)
testRunner.notifyDone();
}
function oncached() {
log("FAILURE");
log("CACHED");
if (window.testRunner)
testRunner.notifyDone();
}
function onupdateready() {
log("FAILURE");
log("UPDATEREADY");
if (window.testRunner)
testRunner.notifyDone();
}
function onerror() {
log("SUCCESS");
if (window.testRunner)
testRunner.notifyDone();
}
applicationCache.addEventListener('noupdate', onnoupdate, false);
applicationCache.addEventListener('cached', oncached, false);
applicationCache.addEventListener('error', onerror, false);
applicationCache.addEventListener('updateready', onupdateready, false);
applicationCache.addEventListener('progress', onprogress, false);
</script>
<div>This tests that download process was aborted after progress event.</div>
<div id="result"></div>
</html>
| js0701/chromium-crosswalk | third_party/WebKit/LayoutTests/http/tests/appcache/abort-cache-onprogress.html | HTML | bsd-3-clause | 1,351 |
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
ShimIE8 = _dereq_('../lib/Shim.IE8');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/Core":4,"../lib/Shim.IE8":27}],2:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
var BinaryTree = function (data, compareFunc, hashFunc) {
this.init.apply(this, arguments);
};
BinaryTree.prototype.init = function (data, index, compareFunc, hashFunc) {
this._store = [];
this._keys = [];
if (index !== undefined) { this.index(index); }
if (compareFunc !== undefined) { this.compareFunc(compareFunc); }
if (hashFunc !== undefined) { this.hashFunc(hashFunc); }
if (data !== undefined) { this.data(data); }
};
Shared.addModule('BinaryTree', BinaryTree);
Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting');
Shared.mixin(BinaryTree.prototype, 'Mixin.Common');
Shared.synthesize(BinaryTree.prototype, 'compareFunc');
Shared.synthesize(BinaryTree.prototype, 'hashFunc');
Shared.synthesize(BinaryTree.prototype, 'indexDir');
Shared.synthesize(BinaryTree.prototype, 'keys');
Shared.synthesize(BinaryTree.prototype, 'index', function (index) {
if (index !== undefined) {
// Convert the index object to an array of key val objects
this.keys(this.extractKeys(index));
}
return this.$super.call(this, index);
});
BinaryTree.prototype.extractKeys = function (obj) {
var i,
keys = [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
keys.push({
key: i,
val: obj[i]
});
}
}
return keys;
};
BinaryTree.prototype.data = function (val) {
if (val !== undefined) {
this._data = val;
if (this._hashFunc) { this._hash = this._hashFunc(val); }
return this;
}
return this._data;
};
/**
* Pushes an item to the binary tree node's store array.
* @param {*} val The item to add to the store.
* @returns {*}
*/
BinaryTree.prototype.push = function (val) {
if (val !== undefined) {
this._store.push(val);
return this;
}
return false;
};
/**
* Pulls an item from the binary tree node's store array.
* @param {*} val The item to remove from the store.
* @returns {*}
*/
BinaryTree.prototype.pull = function (val) {
if (val !== undefined) {
var index = this._store.indexOf(val);
if (index > -1) {
this._store.splice(index, 1);
return this;
}
}
return false;
};
/**
* Default compare method. Can be overridden.
* @param a
* @param b
* @returns {number}
* @private
*/
BinaryTree.prototype._compareFunc = function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (indexData.val === 1) {
result = this.sortAsc(a[indexData.key], b[indexData.key]);
} else if (indexData.val === -1) {
result = this.sortDesc(a[indexData.key], b[indexData.key]);
}
if (result !== 0) {
return result;
}
}
return result;
};
/**
* Default hash function. Can be overridden.
* @param obj
* @private
*/
BinaryTree.prototype._hashFunc = function (obj) {
/*var i,
indexData,
hash = '';
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (hash) { hash += '_'; }
hash += obj[indexData.key];
}
return hash;*/
return obj[this._keys[0].key];
};
BinaryTree.prototype.insert = function (data) {
var result,
inserted,
failed,
i;
if (data instanceof Array) {
// Insert array of data
inserted = [];
failed = [];
for (i = 0; i < data.length; i++) {
if (this.insert(data[i])) {
inserted.push(data[i]);
} else {
failed.push(data[i]);
}
}
return {
inserted: inserted,
failed: failed
};
}
if (!this._data) {
// Insert into this node (overwrite) as there is no data
this.data(data);
//this.push(data);
return true;
}
result = this._compareFunc(this._data, data);
if (result === 0) {
this.push(data);
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc);
}
return true;
}
if (result === -1) {
// Greater than this node
if (this._right) {
// Propagate down the right branch
this._right.insert(data);
} else {
// Assign to right branch
this._right = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc);
}
return true;
}
if (result === 1) {
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc);
}
return true;
}
return false;
};
BinaryTree.prototype.lookup = function (data, resultArr) {
var result = this._compareFunc(this._data, data);
resultArr = resultArr || [];
if (result === 0) {
if (this._left) { this._left.lookup(data, resultArr); }
resultArr.push(this._data);
if (this._right) { this._right.lookup(data, resultArr); }
}
if (result === -1) {
if (this._right) { this._right.lookup(data, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.lookup(data, resultArr); }
}
return resultArr;
};
BinaryTree.prototype.inOrder = function (type, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.inOrder(type, resultArr);
}
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
if (this._right) {
this._right.inOrder(type, resultArr);
}
return resultArr;
};
/*BinaryTree.prototype.find = function (type, search, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.find(type, search, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.find(type, search, resultArr);
}
return resultArr;
};*/
/**
*
* @param {String} type
* @param {String} key The data key / path to range search against.
* @param {Number} from Range search from this value (inclusive)
* @param {Number} to Range search to this value (inclusive)
* @param {Array=} resultArr Leave undefined when calling (internal use),
* passes the result array between recursive calls to be returned when
* the recursion chain completes.
* @param {Path=} pathResolver Leave undefined when calling (internal use),
* caches the path resolver instance for performance.
* @returns {Array} Array of matching document objects
*/
BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) {
resultArr = resultArr || [];
pathResolver = pathResolver || new Path(key);
if (this._left) {
this._left.findRange(type, key, from, to, resultArr, pathResolver);
}
// Check if this node's data is greater or less than the from value
var pathVal = pathResolver.value(this._data),
fromResult = this.sortAsc(pathVal, from),
toResult = this.sortAsc(pathVal, to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRange(type, key, from, to, resultArr, pathResolver);
}
return resultArr;
};
/*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.findRegExp(type, key, pattern, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRegExp(type, key, pattern, resultArr);
}
return resultArr;
};*/
BinaryTree.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path(),
indexKeyArr,
queryArr,
matchedKeys = [],
matchedKeyCount = 0,
i;
indexKeyArr = pathSolver.parseArr(this._index, {
verbose: true
});
queryArr = pathSolver.parseArr(query, {
ignore:/\$/,
verbose: true
});
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
Shared.finishModule('BinaryTree');
module.exports = BinaryTree;
},{"./Path":23,"./Shared":26}],3:[function(_dereq_,module,exports){
"use strict";
var Shared,
Db,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Crc,
Overload,
ReactorIO;
Shared = _dereq_('./Shared');
/**
* Creates a new collection. Collections store multiple documents and
* handle CRUD against those documents.
* @constructor
*/
var Collection = function (name) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name, options) {
this._primaryKey = '_id';
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._name = name;
this._data = [];
this._metrics = new Metrics();
this._options = options || {
changeTimestamp: false
};
// Create an object to store internal protected data
this._metaData = {};
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: [],
async: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100
};
this._deferTime = {
insert: 1,
update: 1,
remove: 1,
upsert: 1
};
this._deferredCalls = true;
// Set the subset to itself since it is the root collection
this.subsetOf(this);
};
Shared.addModule('Collection', Collection);
Shared.mixin(Collection.prototype, 'Mixin.Common');
Shared.mixin(Collection.prototype, 'Mixin.Events');
Shared.mixin(Collection.prototype, 'Mixin.ChainReactor');
Shared.mixin(Collection.prototype, 'Mixin.CRUD');
Shared.mixin(Collection.prototype, 'Mixin.Constants');
Shared.mixin(Collection.prototype, 'Mixin.Triggers');
Shared.mixin(Collection.prototype, 'Mixin.Sorting');
Shared.mixin(Collection.prototype, 'Mixin.Matching');
Shared.mixin(Collection.prototype, 'Mixin.Updating');
Shared.mixin(Collection.prototype, 'Mixin.Tags');
Metrics = _dereq_('./Metrics');
KeyValueStore = _dereq_('./KeyValueStore');
Path = _dereq_('./Path');
IndexHashMap = _dereq_('./IndexHashMap');
IndexBinaryTree = _dereq_('./IndexBinaryTree');
Crc = _dereq_('./Crc');
Db = Shared.modules.Db;
Overload = _dereq_('./Overload');
ReactorIO = _dereq_('./ReactorIO');
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Collection.prototype.crc = Crc;
/**
* Gets / sets the deferred calls flag. If set to true (default)
* then operations on large data sets can be broken up and done
* over multiple CPU cycles (creating an async state). For purely
* synchronous behaviour set this to false.
* @param {Boolean=} val The value to set.
* @returns {Boolean}
*/
Shared.synthesize(Collection.prototype, 'deferredCalls');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Gets / sets the metadata stored in the collection.
*/
Shared.synthesize(Collection.prototype, 'metaData');
/**
* Gets / sets boolean to determine if the collection should be
* capped or not.
*/
Shared.synthesize(Collection.prototype, 'capped');
/**
* Gets / sets capped collection size. This is the maximum number
* of records that the capped collection will store.
*/
Shared.synthesize(Collection.prototype, 'cappedSize');
Collection.prototype._asyncPending = function (key) {
this._deferQueue.async.push(key);
};
Collection.prototype._asyncComplete = function (key) {
// Remove async flag for this type
var index = this._deferQueue.async.indexOf(key);
while (index > -1) {
this._deferQueue.async.splice(index, 1);
index = this._deferQueue.async.indexOf(key);
}
if (this._deferQueue.async.length === 0) {
this.deferEmit('ready');
}
};
/**
* Get the data array that represents the collection's data.
* This data is returned by reference and should not be altered outside
* of the provided CRUD functionality of the collection as doing so
* may cause unstable index behaviour within the collection.
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function (callback) {
var key;
if (!this.isDropped()) {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
this.emit('drop', this);
delete this._db._collection[this._name];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._name;
delete this._data;
delete this._metrics;
delete this._listeners;
if (callback) { callback(false, true); }
return true;
}
} else {
if (callback) { callback(false, true); }
return true;
}
if (callback) { callback(false, true); }
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
var oldKey = this._primaryKey;
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
// Propagate change down the chain
this.chainSend('primaryKey', keyName, {oldData: oldKey});
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Handles any change to the collection.
* @private
*/
Collection.prototype._onChange = function () {
if (this._options.changeTimestamp) {
// Record the last change timestamp
this._metaData.lastChange = new Date();
}
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
// Apply the same debug settings
this.debug(db.debug());
}
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'mongoEmulation');
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set.
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param options Optional options object.
* @param callback Optional callback function.
*/
Collection.prototype.setData = function (data, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (data) {
var op = this._metrics.create('setData');
op.start();
options = this.options(options);
this.preSetData(data, options, callback);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
op.time('transformIn');
data = this.transformIn(data);
op.time('transformIn');
var oldData = [].concat(this._data);
this._dataReplace(data);
// Update the primary key index
op.time('Rebuild Primary Key Index');
this.rebuildPrimaryKeyIndex(options);
op.time('Rebuild Primary Key Index');
// Rebuild all other indexes
op.time('Rebuild All Other Indexes');
this._rebuildIndexes();
op.time('Rebuild All Other Indexes');
op.time('Resolve chains');
this.chainSend('setData', data, {oldData: oldData});
op.time('Resolve chains');
op.stop();
this._onChange();
this.emit('setData', this._data, oldData);
}
if (callback) { callback(false); }
return this;
};
/**
* Drops and rebuilds the primary key index for all documents in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a CRC string
jString = this.jStringify(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._onChange();
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} obj The document object to upsert or an array containing
* documents to upsert.
*
* If the document contains a primary key field (based on the collections's primary
* key) then the database will search for an existing document with a matching id.
* If a matching document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with new data. Any keys
* that do not currently exist on the document will be added to the document.
*
* If the document does not contain an id or the id passed does not match an existing
* document, an insert is performed instead. If no id is present a new primary key
* id is provided for the item.
*
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains either "insert" or
* "update" depending on the type of operation that was performed and "result"
* contains the return data from the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert,
returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (this._deferredCalls && obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
this._asyncPending('upsert');
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback(); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj);
break;
case 'update':
returnData.result = this.update(query, obj);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback(); }
}
return {};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
Collection.prototype.filter = function (query, func, options) {
return (this.find(query, options)).filter(func);
};
/**
* Executes a method against each document that matches query and then executes
* an update based on the return data of the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the update.
* @param {Object=} options Optional options object passed to the initial find call.
* @returns {Array}
*/
Collection.prototype.filterUpdate = function (query, func, options) {
var items = this.find(query, options),
results = [],
singleItem,
singleQuery,
singleUpdate,
pk = this.primaryKey(),
i;
for (i = 0; i < items.length; i++) {
singleItem = items[i];
singleUpdate = func(singleItem);
if (singleUpdate) {
singleQuery = {};
singleQuery[pk] = singleItem[pk];
results.push(this.update(singleQuery, singleUpdate));
}
}
return results;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// Decouple the update data
update = this.decouple(update);
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
this.convertToFdb(update);
}
// Handle transform
update = this.transformIn(update);
if (this.debug()) {
console.log(this.logIdentifier() + ' Updating some data');
}
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (referencedDoc) {
var oldDoc = self.decouple(referencedDoc),
newDoc,
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
newDoc = self.decouple(referencedDoc);
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, update, query, options, '');
}
// Inform indexes of the change
self._updateIndexes(oldDoc, referencedDoc);
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
op.time('Resolve chains');
this.chainSend('update', {
query: query,
update: update,
dataSet: updated
}, options);
op.time('Resolve chains');
this._onUpdate(updated);
this._onChange();
this.deferEmit('change', {type: 'update', data: updated});
}
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
/**
* Replaces an existing object with data from the new object without
* breaking data references.
* @param {Object} currentObj The object to alter.
* @param {Object} newObj The new object to overwrite the existing one with.
* @returns {*} Chain.
* @private
*/
Collection.prototype._replaceObj = function (currentObj, newObj) {
var i;
// Check if the new document has a different primary key value from the existing one
// Remove item from indexes
this._removeFromIndexes(currentObj);
// Remove existing keys from current object
for (i in currentObj) {
if (currentObj.hasOwnProperty(i)) {
delete currentObj[i];
}
}
// Add new keys to current object
for (i in newObj) {
if (newObj.hasOwnProperty(i)) {
currentObj[i] = newObj[i];
}
}
// Update the item in the primary index
if (!this._insertIntoIndexes(currentObj)) {
throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]);
}
// Update the object in the collection data
//this._data.splice(this._data.indexOf(currentObj), 1, newObj);
return this;
};
/**
* Helper method to update a document from it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to update to.
* @returns {Object} The document that was updated or undefined
* if no document was updated.
*/
Collection.prototype.updateById = function (id, update) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.update(searchObj, update)[0];
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
Collection.prototype.updateObject = function (doc, update, query, options, path, opType) {
// TODO: This method is long, try to break it into smaller pieces
update = this.decouple(update);
// Clear leading dots from path
path = path || '';
if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); }
//var oldDoc = this.decouple(doc),
var updated = false,
recurseUpdated = false,
operation,
tmpArray,
tmpIndex,
tmpCount,
tempIndex,
tempKey,
replaceObj,
pk,
pathInstance,
sourceIsArray,
updateIsArray,
i;
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$key':
case '$index':
case '$data':
case '$min':
case '$max':
// Ignore some operators
operation = true;
break;
case '$each':
operation = true;
// Loop over the array of updates and run each one
tmpCount = update.$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path);
if (recurseUpdated) {
updated = true;
}
}
updated = updated || recurseUpdated;
break;
case '$replace':
operation = true;
replaceObj = update.$replace;
pk = this.primaryKey();
// Loop the existing item properties and compare with
// the replacement (never remove primary key)
for (tempKey in doc) {
if (doc.hasOwnProperty(tempKey) && tempKey !== pk) {
if (replaceObj[tempKey] === undefined) {
// The new document doesn't have this field, remove it from the doc
this._updateUnset(doc, tempKey);
updated = true;
}
}
}
// Loop the new item props and update the doc
for (tempKey in replaceObj) {
if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) {
this._updateOverwrite(doc, tempKey, replaceObj[tempKey]);
updated = true;
}
}
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
var doUpdate = true;
// Check for a $min / $max operator
if (update[i] > 0) {
if (update.$max) {
// Check current value
if (doc[i] >= update.$max) {
// Don't update
doUpdate = false;
}
}
} else if (update[i] < 0) {
if (update.$min) {
// Check current value
if (doc[i] <= update.$min) {
// Don't update
doUpdate = false;
}
}
}
if (doUpdate) {
this._updateIncrement(doc, i, update[i]);
updated = true;
}
break;
case '$cast':
// Casts a property to the type specified if it is not already
// that type. If the cast is an array or an object and the property
// is not already that type a new array or object is created and
// set to the property, overwriting the previous value
switch (update[i]) {
case 'array':
if (!(doc[i] instanceof Array)) {
// Cast to an array
this._updateProperty(doc, i, update.$data || []);
updated = true;
}
break;
case 'object':
if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) {
// Cast to an object
this._updateProperty(doc, i, update.$data || {});
updated = true;
}
break;
case 'number':
if (typeof doc[i] !== 'number') {
// Cast to a number
this._updateProperty(doc, i, Number(doc[i]));
updated = true;
}
break;
case 'string':
if (typeof doc[i] !== 'string') {
// Cast to a string
this._updateProperty(doc, i, String(doc[i]));
updated = true;
}
break;
default:
throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]);
}
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')');
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')');
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (update[i].$key) {
hashMode = false;
pathSolver = new Path(update[i].$key);
objHash = pathSolver.value(update[i])[0];
// Remove the key from the object before we add it
delete update[i].$key;
} else if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = this.jStringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (this.jStringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')');
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!');
}
} else {
throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')');
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot move without a $index integer value!');
}
break;
}
}
} else {
throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')');
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$overwrite':
this._updateOverwrite(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$clear':
this._updateClear(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')');
}
break;
case '$toggle':
// Toggle the boolean property between true and false
this._updateProperty(doc, i, !doc[i]);
updated = true;
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Removes any documents from the collection that match the search query
* key/values.
* @param {Object} query The query object.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var self = this,
dataSet,
index,
arrIndex,
returnArr,
removeMethod,
triggerOperation,
doc,
newDoc;
if (typeof(options) === 'function') {
callback = options;
options = {};
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
if (callback) { callback(false, returnArr); }
return returnArr;
} else {
returnArr = [];
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
returnArr.push(dataItem);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
if (returnArr.length) {
//op.time('Resolve chains');
self.chainSend('remove', {
query: query,
dataSet: returnArr
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
this._onChange();
this.deferEmit('change', {type: 'remove', data: returnArr});
}
}
if (callback) { callback(false, returnArr); }
return returnArr;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Object} The document that was removed or undefined if
* nothing was removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj)[0];
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
* @param {Object=} resultObj A temp object to hold results in.
*/
Collection.prototype.processQueue = function (type, callback, resultObj) {
var self = this,
queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type],
dataArr,
result;
resultObj = resultObj || {
deferred: true
};
if (queue.length) {
// Process items up to the threshold
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
result = self[type](dataArr);
switch (type) {
case 'insert':
resultObj.inserted = resultObj.inserted || [];
resultObj.failed = resultObj.failed || [];
resultObj.inserted = resultObj.inserted.concat(result.inserted);
resultObj.failed = resultObj.failed.concat(result.failed);
break;
}
// Queue another process
setTimeout(function () {
self.processQueue.call(self, type, callback, resultObj);
}, deferTime);
} else {
if (callback) { callback(resultObj); }
this._asyncComplete(type);
}
// Check if all queues are complete
if (!this.isProcessingQueue()) {
this.deferEmit('queuesComplete');
}
};
/**
* Checks if any CRUD operations have been deferred and are still waiting to
* be processed.
* @returns {Boolean} True if there are still deferred CRUD operations to process
* or false if all queues are clear.
*/
Collection.prototype.isProcessingQueue = function () {
var i;
for (i in this._deferQueue) {
if (this._deferQueue.hasOwnProperty(i)) {
if (this._deferQueue[i].length) {
return true;
}
}
}
return false;
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype.insert = function (data, index, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var //self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
//deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
resultObj,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (this._deferredCalls && data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
this._asyncPending('insert');
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
resultObj = {
deferred: false,
inserted: inserted,
failed: failed
};
this._onInsert(inserted, failed);
if (callback) { callback(resultObj); }
this._onChange();
this.deferEmit('change', {type: 'insert', data: inserted});
return resultObj;
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var self = this,
indexViolation,
triggerOperation,
insertMethod,
newDoc,
capped = this.capped(),
cappedSize = this.cappedSize();
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
insertMethod = function (doc) {
// Add the item to the collection's indexes
self._insertIntoIndexes(doc);
// Check index overflow
if (index > self._data.length) {
index = self._data.length;
}
// Insert the document
self._dataInsertAtIndex(index, doc);
// Check capped collection status and remove first record
// if we are over the threshold
if (capped && self._data.length > cappedSize) {
// Remove the first item in the data array
self.removeById(self._data[0][self._primaryKey]);
}
//op.time('Resolve chains');
self.chainSend('insert', doc, {index: index});
//op.time('Resolve chains');
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return 'Trigger cancelled operation';
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
jString = this.jStringify(doc);
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc);
this._primaryCrc.uniqueSet(doc[this._primaryKey], jString);
this._crcLookup.uniqueSet(jString, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
jString = this.jStringify(doc);
// Remove from primary key index
this._primaryIndex.unSet(doc[this._primaryKey]);
this._primaryCrc.unSet(doc[this._primaryKey]);
this._crcLookup.unSet(jString);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Updates collection index data for the passed document.
* @param {Object} oldDoc The old document as it was before the update.
* @param {Object} newDoc The document as it now is after the update.
* @private
*/
Collection.prototype._updateIndexes = function (oldDoc, newDoc) {
this._removeFromIndexes(oldDoc);
this._insertIntoIndexes(newDoc);
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param {Object} query The query object to generate the subset with.
* @param {Object=} options An options object.
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Gets / sets the collection that this collection is a subset of.
* @param {Collection=} collection The collection to set as the parent of this subset.
* @returns {Collection}
*/
Shared.synthesize(Collection.prototype, 'subsetOf');
/**
* Checks if the collection is a subset of the passed collection.
* @param {Collection} collection The collection to test against.
* @returns {Boolean} True if the passed collection is the parent of
* the current collection.
*/
Collection.prototype.isSubsetOf = function (collection) {
return this._subsetOf === collection;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param search The string to search for. Case sensitive.
* @param options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = this.jStringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
* @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !!
* Optional callback. If specified the find process
* will not return a value and will assume that you wish to operate under an
* async mode. This will break up large find requests into smaller chunks and
* process them in a non-blocking fashion allowing large datasets to be queried
* without causing the browser UI to pause. Results from this type of operation
* will be passed back to the callback once completed.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options, callback) {
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (callback) {
// Check the size of the collection's data array
// Split operation into smaller tasks and callback when complete
callback('Callbacks for the find() operation are not yet implemented!', []);
return [];
}
return this._find.apply(this, arguments);
};
Collection.prototype._find = function (query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
options = this.options(options);
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
scanLength,
requiresTableScan = true,
resultArr,
joinCollectionIndex,
joinIndex,
joinCollection = {},
joinQuery,
joinPath,
joinCollectionName,
joinCollectionInstance,
joinMatch,
joinMatchIndex,
joinSearchQuery,
joinSearchOptions,
joinMulti,
joinRequire,
joinFindResults,
joinFindResult,
joinItem,
joinPrefix,
resultCollectionName,
resultIndex,
resultRemove = [],
index,
i, j, k, l,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
cursor = {},
pathSolver,
//renameFieldMethod,
//renameFieldPath,
matcher = function (doc) {
return self._match(doc, query, options, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(self.decouple(query), options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get an instance reference to the join collections
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinCollectionName = analysis.joinsOn[joinIndex];
joinPath = new Path(analysis.joinQueries[joinCollectionName]);
joinQuery = joinPath.value(query)[0];
joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery);
// Remove join clause from main query
delete query[analysis.joinQueries[joinCollectionName]];
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup || [];
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Don't require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
op.time('tableScan: ' + scanLength);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
if (options.$page !== undefined && options.$limit !== undefined) {
// Record paging data
cursor.page = options.$page;
cursor.pages = Math.ceil(resultArr.length / options.$limit);
cursor.records = resultArr.length;
// Check if we actually need to apply the paging logic
if (options.$page && options.$limit > 0) {
op.data('cursor', cursor);
// Skip to the page specified based on limit
resultArr.splice(0, options.$page * options.$limit);
}
}
if (options.$skip) {
cursor.skip = options.$skip;
// Skip past the number of records specified
resultArr.splice(0, options.$skip);
op.data('skip', options.$skip);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
cursor.limit = options.$limit;
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
// Set the key to store the join result in to the collection name by default
resultCollectionName = joinCollectionName;
// Get the join collection instance from the DB
if (joinCollection[joinCollectionName]) {
joinCollectionInstance = joinCollection[joinCollectionName];
} else {
joinCollectionInstance = this._db.collection(joinCollectionName);
}
// Get the match data for the join
joinMatch = options.$join[joinCollectionIndex][joinCollectionName];
// Loop our result data array
for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearchQuery = {};
joinMulti = false;
joinRequire = false;
joinPrefix = '';
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$where':
if (joinMatch[joinMatchIndex].query) {
// Commented old code here, new one does dynamic reverse lookups
//joinSearchQuery = joinMatch[joinMatchIndex].query;
joinSearchQuery = self._resolveDynamicQuery(joinMatch[joinMatchIndex].query, resultArr[resultIndex]);
}
if (joinMatch[joinMatchIndex].options) { joinSearchOptions = joinMatch[joinMatchIndex].options; }
break;
case '$as':
// Rename the collection when stored in the result document
resultCollectionName = joinMatch[joinMatchIndex];
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatch[joinMatchIndex];
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatch[joinMatchIndex];
break;
case '$prefix':
// Add a prefix to properties mixed in
joinPrefix = joinMatch[joinMatchIndex];
break;
default:
break;
}
} else {
// Get the data to match against and store in the search object
// Resolve complex referenced query
joinSearchQuery[joinMatchIndex] = self._resolveDynamicQuery(joinMatch[joinMatchIndex], resultArr[resultIndex]);
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinCollectionInstance.find(joinSearchQuery, joinSearchOptions);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
if (resultCollectionName === '$root') {
// The property name to store the join results in is $root
// which means we need to mixin the results but this only
// works if joinMulti is disabled
if (joinMulti !== false) {
// Throw an exception here as this join is not physically possible!
throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!');
}
// Mixin the result
joinFindResult = joinFindResults[0];
joinItem = resultArr[resultIndex];
for (l in joinFindResult) {
if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) {
// Properties are only mixed in if they do not already exist
// in the target item (are undefined). Using a prefix denoted via
// $prefix is a good way to prevent property name conflicts
joinItem[joinPrefix + l] = joinFindResult[l];
}
}
} else {
resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
}
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultArr[resultIndex]);
}
}
}
}
}
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
for (i = 0; i < resultRemove.length; i++) {
index = resultArr.indexOf(resultRemove[i]);
if (index > -1) {
resultArr.splice(index, 1);
}
}
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Check for an $as operator in the options object and if it exists
// iterate over the fields and generate a rename function that will
// operate over the entire returned data array and rename each object's
// fields to their new names
// TODO: Enable $as in collection find to allow renaming fields
/*if (options.$as) {
renameFieldPath = new Path();
renameFieldMethod = function (obj, oldFieldPath, newFieldName) {
renameFieldPath.path(oldFieldPath);
renameFieldPath.rename(newFieldName);
};
for (i in options.$as) {
if (options.$as.hasOwnProperty(i)) {
}
}
}*/
if (!options.$aggregate) {
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
}
// Process aggregation
if (options.$aggregate) {
op.data('flag.aggregate', true);
op.time('aggregate');
pathSolver = new Path(options.$aggregate);
resultArr = pathSolver.value(resultArr);
op.time('aggregate');
}
op.stop();
resultArr.__fdbOp = op;
resultArr.$cursor = cursor;
return resultArr;
};
Collection.prototype._resolveDynamicQuery = function (query, item) {
var self = this,
newQuery,
propType,
propVal,
pathResult,
i;
if (typeof query === 'string') {
// Check if the property name starts with a back-reference
if (query.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
pathResult = new Path(query.substr(3, query.length - 3)).value(item);
} else {
pathResult = new Path(query).value(item);
}
if (pathResult.length > 1) {
return {$in: pathResult};
} else {
return pathResult[0];
}
}
newQuery = {};
for (i in query) {
if (query.hasOwnProperty(i)) {
propType = typeof query[i];
propVal = query[i];
switch (propType) {
case 'string':
// Check if the property name starts with a back-reference
if (propVal.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
newQuery[i] = new Path(propVal.substr(3, propVal.length - 3)).value(item)[0];
} else {
newQuery[i] = propVal;
}
break;
case 'object':
newQuery[i] = self._resolveDynamicQuery(propVal, item);
break;
default:
newQuery[i] = propVal;
break;
}
}
}
return newQuery;
};
/**
* Returns one document that satisfies the specified query criteria. If multiple
* documents satisfy the query, this method returns the first document to match
* the query.
* @returns {*}
*/
Collection.prototype.findOne = function () {
return (this.find.apply(this, arguments))[0];
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @param {Object=} options An options object.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query, options) {
var item = this.find(query, {$decouple: false})[0],
sortedData;
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup from order of insert
return this._data.indexOf(item);
} else {
// Trying to locate index based on query with sort order
options.$decouple = false;
sortedData = this.find(query, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Returns the index of the document identified by the passed item's primary key.
* @param {*} itemLookup The document whose primary key should be used to lookup
* or the id to lookup.
* @param {Object=} options An options object.
* @returns {Number} The index the item with the matching primary key is occupying.
*/
Collection.prototype.indexOfDocById = function (itemLookup, options) {
var item,
sortedData;
if (typeof itemLookup !== 'object') {
item = this._primaryIndex.get(itemLookup);
} else {
item = this._primaryIndex.get(itemLookup[this._primaryKey]);
}
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup
return this._data.indexOf(item);
} else {
// Sorted lookup
options.$decouple = false;
sortedData = this.find({}, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Removes a document from the collection by it's index in the collection's
* data array.
* @param {Number} index The index of the document to remove.
* @returns {Object} The document that has been removed or false if none was
* removed.
*/
Collection.prototype.removeByIndex = function (index) {
var doc,
docId;
doc = this._data[index];
if (doc !== undefined) {
doc = this.decouple(doc);
docId = doc[this.primaryKey()];
return this.removeById(docId);
}
return false;
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformIn(data[i]);
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformOut(data[i]);
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = String(sortKey);
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};
/**
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
bucketData,
bucketOrder,
bucketKey,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
bucketData = this.bucket(keyObj.___fdbKey, arr);
bucketOrder = bucketData.order;
buckets = bucketData.buckets;
// Loop buckets and sort contents
for (i = 0; i < bucketOrder.length; i++) {
bucketKey = bucketOrder[i];
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey]));
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};
/**
* Sorts array by individual sort path.
* @param key
* @param arr
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var self = this,
sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortAsc(valA, valB);
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortDesc(valA, valB);
};
} else {
throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
Collection.prototype.bucket = function (key, arr) {
var i,
oldField,
field,
fieldArr = [],
buckets = {};
for (i = 0; i < arr.length; i++) {
field = String(arr[i][key]);
if (oldField !== field) {
fieldArr.push(field);
oldField = field;
}
buckets[field] = buckets[field] || [];
buckets[field].push(arr[i]);
}
return {
buckets: buckets,
order: fieldArr
};
};
/**
* Internal method that takes a search query and options and returns an object
* containing details about the query which can be used to optimise the search.
*
* @param query
* @param options
* @param op
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [this._name],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinCollectionIndex,
joinCollectionName,
joinCollections = [],
joinCollectionReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
queryKeyCount,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
pathSolver = new Path();
queryKeyCount = pathSolver.countKeys(query);
if (queryKeyCount) {
if (query[this._primaryKey] !== undefined) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
analysis.indexMatch.push({
lookup: this._primaryIndex.lookup(query, options),
keyData: {
matchedKeys: [this._primaryKey],
totalKeyCount: queryKeyCount,
score: 1
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
if (indexMatchData.score > 0) {
// This index can be used, store it
indexLookup = indexRef.lookup(query, options);
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.score === queryKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.score > b.keyData.score) {
// This index has a higher score than the other
return -1;
}
if (a.keyData.score < b.keyData.score) {
// This index has a lower score than the other
return 1;
}
// The indexes have the same score but can still be compared by the number of records
// they return from the query. The fewer records they return the better so order by
// record count
if (a.keyData.score === b.keyData.score) {
return a.lookup.length - b.lookup.length;
}
});
op.time('findOptimalIndex');
}
}
// Check for join data
if (options.$join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
// Loop the join collections and keep a reference to them
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
joinCollections.push(joinCollectionName);
// Check if the join uses an $as operator
if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) {
joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as);
} else {
joinCollectionReferences.push(joinCollectionName);
}
}
}
}
// Loop the join collection references and determine if the query references
// any of the collections that are used in the join. If there no queries against
// joined collections the find method can use a code path optimised for this.
// Queries against joined collections requires the joined collections to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinCollectionReferences.length; index++) {
// Check if the query references any collection data that the join will create
queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinCollections[index]] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinCollections;
analysis.queriesOn = analysis.queriesOn.concat(joinCollections);
}
return analysis;
};
/**
* Checks if the passed query references this collection.
* @param query
* @param collection
* @param path
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesCollection = function (query, collection, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === collection) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesCollection(query[i], collection, path);
}
}
}
}
return false;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docArr = this.find(match),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
subDocOptions = subDocOptions || {};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
if (subDocOptions.$split) {
resultObj.subDocs.push(subDocResults);
} else {
resultObj.subDocs = resultObj.subDocs.concat(subDocResults);
}
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.$stats) {
return resultObj;
} else {
return resultObj.subDocs;
}
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
return resultObj;
};
/**
* Finds the first sub-document from the collection's documents that matches
* the subDocQuery parameter.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {Object}
*/
Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this.findSub(match, path, subDocQuery, subDocOptions)[0];
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index,
time = {
start: new Date().getTime()
};
if (options) {
switch (options.type) {
case 'hashed':
index = new IndexHashMap(keys, options, this);
break;
case 'btree':
index = new IndexBinaryTree(keys, options, this);
break;
default:
// Default
index = new IndexHashMap(keys, options, this);
break;
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pm = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pm !== collection.primaryKey()) {
throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pm])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pm]) !== collection._primaryCrc.get(arrItem[pm])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pm])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = new Overload({
/**
* Adds a data source to collate data from and specifies the
* key name to collate data to.
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {String=} keyName Optional name of the key to collate data to.
* If none is provided the record CRUD is operated on the root collection
* data.
*/
'object, string': function (collection, keyName) {
var self = this;
self.collateAdd(collection, function (packet) {
var obj1,
obj2;
switch (packet.type) {
case 'insert':
if (keyName) {
obj1 = {
$push: {}
};
obj1.$push[keyName] = self.decouple(packet.data);
self.update({}, obj1);
} else {
self.insert(packet.data);
}
break;
case 'update':
if (keyName) {
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
} else {
self.update(packet.data.query, packet.data.update);
}
break;
case 'remove':
if (keyName) {
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
} else {
self.remove(packet.data);
}
break;
default:
}
});
},
/**
* Adds a data source to collate data from and specifies a process
* method that will handle the collation functionality (for custom
* collation).
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {Function} process The process method.
*/
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
Db.prototype.collection = new Overload({
/**
* Get a collection with no name (generates a random name). If the
* collection does not already exist then one is created for that
* name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'': function () {
return this.$main.call(this, {
name: this.objectId()
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {Object} data An options object or a collection instance.
* @returns {Collection}
*/
'object': function (data) {
// Handle being passed an instance
if (data instanceof Collection) {
if (data.state() !== 'droppped') {
return data;
} else {
return this.$main.call(this, {
name: data.name()
});
}
}
return this.$main.call(this, data);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'string': function (collectionName) {
return this.$main.call(this, {
name: collectionName
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @returns {Collection}
*/
'string, string': function (collectionName, primaryKey) {
return this.$main.call(this, {
name: collectionName,
primaryKey: primaryKey
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, object': function (collectionName, options) {
options.name = collectionName;
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, string, object': function (collectionName, primaryKey, options) {
options.name = collectionName;
options.primaryKey = primaryKey;
return this.$main.call(this, options);
},
/**
* The main handler method. This gets called by all the other variants and
* handles the actual logic of the overloaded method.
* @func collection
* @memberof Db
* @param {Object} options An options object.
* @returns {*}
*/
'$main': function (options) {
var self = this,
name = options.name;
if (name) {
if (this._collection[name]) {
return this._collection[name];
} else {
if (options && options.autoCreate === false) {
if (options && options.throwError !== false) {
throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!');
}
return undefined;
}
if (this.debug()) {
console.log(this.logIdentifier() + ' Creating collection ' + name);
}
}
this._collection[name] = this._collection[name] || new Collection(name, options).db(this);
this._collection[name].mongoEmulation(this.mongoEmulation());
if (options.primaryKey !== undefined) {
this._collection[name].primaryKey(options.primaryKey);
}
if (options.capped !== undefined) {
// Check we have a size
if (options.size !== undefined) {
this._collection[name].capped(options.capped);
this._collection[name].cappedSize(options.size);
} else {
throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!');
}
}
// Listen for events on this collection so we can fire global events
// on the database in response to it
self._collection[name].on('change', function () {
self.emit('change', self._collection[name], 'collection', name);
});
self.emit('create', self._collection[name], 'collection', name);
return this._collection[name];
} else {
if (!options || (options && options.throwError !== false)) {
throw(this.logIdentifier() + ' Cannot get collection with undefined name!');
}
}
}
});
/**
* Determine if a collection with the passed name already exists.
* @memberof Db
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Db.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @memberof Db
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each collection
* the database is currently managing.
*/
Db.prototype.collections = function (search) {
var arr = [],
collections = this._collection,
collection,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in collections) {
if (collections.hasOwnProperty(i)) {
collection = collections[i];
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
} else {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Crc":5,"./IndexBinaryTree":7,"./IndexHashMap":8,"./KeyValueStore":9,"./Metrics":10,"./Overload":22,"./Path":23,"./ReactorIO":24,"./Shared":26}],4:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Db,
Metrics,
Overload,
_instances = [];
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB instance. Core instances handle the lifecycle of
* multiple database instances.
* @constructor
*/
var Core = function (name) {
this.init.apply(this, arguments);
};
Core.prototype.init = function (name) {
this._db = {};
this._debug = {};
this._name = name || 'ForerunnerDB';
_instances.push(this);
};
/**
* Returns the number of instantiated ForerunnerDB objects.
* @returns {Number} The number of instantiated instances.
*/
Core.prototype.instantiatedCount = function () {
return _instances.length;
};
/**
* Get all instances as an array or a single ForerunnerDB instance
* by it's array index.
* @param {Number=} index Optional index of instance to get.
* @returns {Array|Object} Array of instances or a single instance.
*/
Core.prototype.instances = function (index) {
if (index !== undefined) {
return _instances[index];
}
return _instances;
};
/**
* Get all instances as an array of instance names or a single ForerunnerDB
* instance by it's name.
* @param {String=} name Optional name of instance to get.
* @returns {Array|Object} Array of instance names or a single instance.
*/
Core.prototype.namedInstances = function (name) {
var i,
instArr;
if (name !== undefined) {
for (i = 0; i < _instances.length; i++) {
if (_instances[i].name === name) {
return _instances[i];
}
}
return undefined;
}
instArr = [];
for (i = 0; i < _instances.length; i++) {
instArr.push(_instances[i].name);
}
return instArr;
};
Core.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if an array of named modules are loaded and if so
* calls the passed callback method.
* @func moduleLoaded
* @memberof Core
* @param {Array} moduleName The array of module names to check for.
* @param {Function} callback The callback method to call if modules are loaded.
*/
'array, function': function (moduleNameArr, callback) {
var moduleName,
i;
for (i = 0; i < moduleNameArr.length; i++) {
moduleName = moduleNameArr[i];
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
}
}
if (callback) { callback(); }
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Core.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded() method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Expose version() method to non-instantiated object ForerunnerDB
Core.version = Core.prototype.version;
// Expose instances() method to non-instantiated object ForerunnerDB
Core.instances = Core.prototype.instances;
// Expose instantiatedCount() method to non-instantiated object ForerunnerDB
Core.instantiatedCount = Core.prototype.instantiatedCount;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.Constants');
Db = _dereq_('./Db.js');
Metrics = _dereq_('./Metrics.js');
/**
* Gets / sets the name of the instance. This is primarily used for
* name-spacing persistent storage.
* @param {String=} val The name of the instance to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'mongoEmulation');
// Set a flag to determine environment
Core.prototype._isServer = false;
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Added to provide an error message for users who have not seen
* the new instantiation breaking change warning and try to get
* a collection directly from the core instance.
*/
Core.prototype.collection = function () {
throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44");
};
module.exports = Core;
},{"./Db.js":6,"./Metrics.js":10,"./Overload":22,"./Shared":26}],5:[function(_dereq_,module,exports){
"use strict";
/**
* @mixin
*/
var crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line
}
crcTable[n] = c;
}
return crcTable;
}());
module.exports = function(str) {
var crc = 0 ^ (-1), // jshint ignore:line
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line
}
return (crc ^ (-1)) >>> 0; // jshint ignore:line
};
},{}],6:[function(_dereq_,module,exports){
"use strict";
var Shared,
Core,
Collection,
Metrics,
Crc,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB database instance.
* @constructor
*/
var Db = function (name, core) {
this.init.apply(this, arguments);
};
Db.prototype.init = function (name, core) {
this.core(core);
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Shared.addModule('Db', Db);
Db.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Db.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Db.moduleLoaded = Db.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Db.version = Db.prototype.version;
// Provide public access to the Shared object
Db.shared = Shared;
Db.prototype.shared = Shared;
Shared.addModule('Db', Db);
Shared.mixin(Db.prototype, 'Mixin.Common');
Shared.mixin(Db.prototype, 'Mixin.ChainReactor');
Shared.mixin(Db.prototype, 'Mixin.Constants');
Shared.mixin(Db.prototype, 'Mixin.Tags');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Crc = _dereq_('./Crc.js');
Db.prototype._isServer = false;
/**
* Gets / sets the core object this database belongs to.
*/
Shared.synthesize(Db.prototype, 'core');
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'mongoEmulation');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Db.prototype.crc = Crc;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Db.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Db.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Db.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Db.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Db.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
Db.prototype.drop = new Overload({
/**
* Drops the database.
* @func drop
* @memberof Db
*/
'': function () {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop();
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional callback method.
* @func drop
* @memberof Db
* @param {Function} callback Optional callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional persistent storage drop. Persistent
* storage is dropped by default if no preference is provided.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
*/
'boolean': function (removePersist) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database and optionally controls dropping persistent storage
* and callback method.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
* @param {Function} callback Optional callback method.
*/
'boolean, function': function (removePersist, callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist, afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
}
});
/**
* Gets a database instance by name.
* @memberof Core
* @param {String=} name Optional name of the database. If none is provided
* a random name is assigned.
* @returns {Db}
*/
Core.prototype.db = function (name) {
// Handle being passed an instance
if (name instanceof Db) {
return name;
}
if (!name) {
name = this.objectId();
}
this._db[name] = this._db[name] || new Db(name, this);
this._db[name].mongoEmulation(this.mongoEmulation());
return this._db[name];
};
/**
* Returns an array of databases that ForerunnerDB currently has.
* @memberof Core
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each database
* that ForerunnerDB is currently managing and it's child entities.
*/
Core.prototype.databases = function (search) {
var arr = [],
tmpObj,
addDb,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._db) {
if (this._db.hasOwnProperty(i)) {
addDb = true;
if (search) {
if (!search.exec(i)) {
addDb = false;
}
}
if (addDb) {
tmpObj = {
name: i,
children: []
};
if (this.shared.moduleExists('Collection')) {
tmpObj.children.push({
module: 'collection',
moduleName: 'Collections',
count: this._db[i].collections().length
});
}
if (this.shared.moduleExists('CollectionGroup')) {
tmpObj.children.push({
module: 'collectionGroup',
moduleName: 'Collection Groups',
count: this._db[i].collectionGroups().length
});
}
if (this.shared.moduleExists('Document')) {
tmpObj.children.push({
module: 'document',
moduleName: 'Documents',
count: this._db[i].documents().length
});
}
if (this.shared.moduleExists('Grid')) {
tmpObj.children.push({
module: 'grid',
moduleName: 'Grids',
count: this._db[i].grids().length
});
}
if (this.shared.moduleExists('Overview')) {
tmpObj.children.push({
module: 'overview',
moduleName: 'Overviews',
count: this._db[i].overviews().length
});
}
if (this.shared.moduleExists('View')) {
tmpObj.children.push({
module: 'view',
moduleName: 'Views',
count: this._db[i].views().length
});
}
arr.push(tmpObj);
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Db');
module.exports = Db;
},{"./Collection.js":3,"./Crc.js":5,"./Metrics.js":10,"./Overload":22,"./Shared":26}],7:[function(_dereq_,module,exports){
"use strict";
/*
name
id
rebuild
state
match
lookup
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree'),
treeInstance = new BinaryTree(),
btree = function () {};
treeInstance.inOrder('hash');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new (btree.create(2, this.sortAsc))();
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree = new (btree.create(2, this.sortAsc))();
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
dataItemHash = this._itemKeyHash(dataItem, this._keys),
keyArr;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// We store multiple items that match a key inside an array
// that is then stored against that key in the tree...
// Check if item exists for this key already
keyArr = this._btree.get(dataItemHash);
// Check if the array exists
if (keyArr === undefined) {
// Generate an array for this key first
keyArr = [];
// Put the new array into the tree under the key
this._btree.put(dataItemHash, keyArr);
}
// Push the item into the array
keyArr.push(dataItem);
this._size++;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
dataItemHash = this._itemKeyHash(dataItem, this._keys),
keyArr,
itemIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Try and get the array for the item hash key
keyArr = this._btree.get(dataItemHash);
if (keyArr !== undefined) {
// The key array exits, remove the item from the key array
itemIndex = keyArr.indexOf(dataItem);
if (itemIndex > -1) {
// Check the length of the array
if (keyArr.length === 1) {
// This item is the last in the array, just kill the tree entry
this._btree.del(dataItemHash);
} else {
// Remove the item
keyArr.splice(itemIndex, 1);
}
this._size--;
}
}
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexBinaryTree.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./BinaryTree":2,"./Path":23,"./Shared":26}],8:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.update = function (dataItem, options) {
// TODO: Write updates to work
// 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this)
// 2: Remove the uniqueHash as it currently stands
// 3: Generate a new uniqueHash for dataItem
// 4: Insert the new uniqueHash
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":23,"./Shared":26}],9:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} obj A lookup query, can be a string key, an array of string keys,
* an object with further query clauses or a regular expression that should be
* run against all keys.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (obj) {
var pKeyVal = obj[this._primaryKey],
arrIndex,
arrCount,
lookupItem,
result;
if (pKeyVal instanceof Array) {
// An array of primary keys, find all matches
arrCount = pKeyVal.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this._data[pKeyVal[arrIndex]];
if (lookupItem) {
result.push(lookupItem);
}
}
return result;
} else if (pKeyVal instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.test(arrIndex)) {
result.push(this._data[arrIndex]);
}
}
}
return result;
} else if (typeof pKeyVal === 'object') {
// The primary key clause is an object, now we have to do some
// more extensive searching
if (pKeyVal.$ne) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (arrIndex !== pKeyVal.$ne) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$in && (pKeyVal.$in instanceof Array)) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.$in.indexOf(arrIndex) > -1) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$nin && (pKeyVal.$nin instanceof Array)) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.$nin.indexOf(arrIndex) === -1) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$or && (pKeyVal.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < pKeyVal.$or.length; arrIndex++) {
result = result.concat(this.lookup(pKeyVal.$or[arrIndex]));
}
return result;
}
} else {
// Key is a basic lookup from string
lookupItem = this._data[pKeyVal];
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
}
};
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":26}],10:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":21,"./Shared":26}],11:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],12:[function(_dereq_,module,exports){
"use strict";
/**
* The chain reactor mixin, provides methods to the target object that allow chain
* reaction events to propagate to the target and be handled, processed and passed
* on down the chain.
* @mixin
*/
var ChainReactor = {
/**
*
* @param obj
*/
chain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list');
}
}
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
unChain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list');
}
}
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
arrItem,
count = arr.length,
index;
for (index = 0; index < count; index++) {
arrItem = arr[index];
if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) {
if (this.debug && this.debug()) {
if (arrItem._reactorIn && arrItem._reactorOut) {
console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"');
} else {
console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"');
}
}
arrItem.chainReceive(this, type, data, options);
} else {
console.log('Reactor Data:', type, data, options);
console.log('Reactor Node:', arrItem);
throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!');
}
}
}
},
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
};
if (this.debug && this.debug()) {
console.log(this.logIdentifier() + 'Received data from parent reactor node');
}
// Fire our internal handler
if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],13:[function(_dereq_,module,exports){
"use strict";
var idCounter = 0,
Overload = _dereq_('./Overload'),
Serialiser = _dereq_('./Serialiser'),
Common,
serialiser = new Serialiser();
/**
* Provides commonly used methods to most classes in ForerunnerDB.
* @mixin
*/
Common = {
// Expose the serialiser object so it can be extended with new data handlers.
serialiser: serialiser,
/**
* Gets / sets data in the item store. The store can be used to set and
* retrieve data against a key. Useful for adding arbitrary key/value data
* to a collection / view etc and retrieving it later.
* @param {String|*} key The key under which to store the passed value or
* retrieve the existing stored value.
* @param {*=} val Optional value. If passed will overwrite the existing value
* stored against the specified key if one currently exists.
* @returns {*}
*/
store: function (key, val) {
if (key !== undefined) {
if (val !== undefined) {
// Store the data
this._store = this._store || {};
this._store[key] = val;
return this;
}
if (this._store) {
return this._store[key];
}
}
return undefined;
},
/**
* Removes a previously stored key/value pair from the item store, set previously
* by using the store() method.
* @param {String|*} key The key of the key/value pair to remove;
* @returns {Common} Returns this for chaining.
*/
unStore: function (key) {
if (key !== undefined) {
delete this._store[key];
}
return this;
},
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @param {Number=} copies Optional number of copies to produce. If specified, the return
* value will be an array of decoupled objects, each distinct from the other.
* @returns {*}
*/
decouple: function (data, copies) {
if (data !== undefined) {
if (!copies) {
return this.jParse(this.jStringify(data));
} else {
var i,
json = this.jStringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(this.jParse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Parses and returns data from stringified version.
* @param {String} data The stringified version of data to parse.
* @returns {Object} The parsed JSON object from the data.
*/
jParse: function (data) {
return serialiser.parse(data);
//return JSON.parse(data);
},
/**
* Converts a JSON object into a stringified version.
* @param {Object} data The data to stringify.
* @returns {String} The stringified data.
*/
jStringify: function (data) {
return serialiser.stringify(data);
//return JSON.stringify(data);
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
]),
/**
* Returns a string describing the class this instance is derived from.
* @returns {string}
*/
classIdentifier: function () {
return 'ForerunnerDB.' + this.className;
},
/**
* Returns a string describing the instance by it's class name and instance
* object name.
* @returns {String} The instance identifier.
*/
instanceIdentifier: function () {
return '[' + this.className + ']' + this.name();
},
/**
* Returns a string used to denote a console log against this instance,
* consisting of the class identifier and instance identifier.
* @returns {string} The log identifier.
*/
logIdentifier: function () {
return this.classIdentifier() + ': ' + this.instanceIdentifier();
},
/**
* Converts a query object with MongoDB dot notation syntax
* to Forerunner's object notation syntax.
* @param {Object} obj The object to convert.
*/
convertToFdb: function (obj) {
var varName,
splitArr,
objCopy,
i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
objCopy = obj;
if (i.indexOf('.') > -1) {
// Replace .$ with a placeholder before splitting by . char
i = i.replace('.$', '[|$|]');
splitArr = i.split('.');
while ((varName = splitArr.shift())) {
// Replace placeholder back to original .$
varName = varName.replace('[|$|]', '.$');
if (splitArr.length) {
objCopy[varName] = {};
} else {
objCopy[varName] = obj[i];
}
objCopy = objCopy[varName];
}
delete obj[i];
}
}
}
},
/**
* Checks if the state is dropped.
* @returns {boolean} True when dropped, false otherwise.
*/
isDropped: function () {
return this._state === 'dropped';
}
};
module.exports = Common;
},{"./Overload":22,"./Serialiser":25}],14:[function(_dereq_,module,exports){
"use strict";
/**
* Provides some database constants.
* @mixin
*/
var Constants = {
TYPE_INSERT: 0,
TYPE_UPDATE: 1,
TYPE_REMOVE: 2,
PHASE_BEFORE: 0,
PHASE_AFTER: 1
};
module.exports = Constants;
},{}],15:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides event emitter functionality including the methods: on, off, once, emit, deferEmit.
* @mixin
*/
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
once: new Overload({
'string, function': function (eventName, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, internalCallback);
},
'string, *, function': function (eventName, id, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, id, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, id, internalCallback);
}
}),
off: new Overload({
'string': function (event) {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
return this;
},
'string, function': function (event, listener) {
var arr,
index;
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (this._listeners && event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
},
'string, *': function (event, id) {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arrIndex,
arrCount,
tmpFunc,
arr,
listenerIdArr,
listenerIdCount,
listenerIdIndex;
// Handle global emit
if (this._listeners[event]['*']) {
arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Check we have a function to execute
tmpFunc = arr[arrIndex];
if (typeof tmpFunc === 'function') {
tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
listenerIdArr = this._listeners[event];
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex];
if (typeof tmpFunc === 'function') {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
}
return this;
},
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc. Only the data from the last
* de-bounced event will be emitted.
* @param {String} eventName The name of the event to emit.
* @param {*=} data Optional data to emit with the event.
*/
deferEmit: function (eventName, data) {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
this._deferTimeout = this._deferTimeout || {};
if (this._deferTimeout[eventName]) {
clearTimeout(this._deferTimeout[eventName]);
}
// Set a timeout
this._deferTimeout[eventName] = setTimeout(function () {
if (self.debug()) {
console.log(self.logIdentifier() + ' Emitting ' + args[0]);
}
self.emit.apply(self, args);
}, 1);
} else {
this.emit.apply(this, arguments);
}
return this;
}
};
module.exports = Events;
},{"./Overload":22}],16:[function(_dereq_,module,exports){
"use strict";
/**
* Provides object matching algorithm methods.
* @mixin
*/
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {Object} queryOptions The options the query was passed with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, queryOptions, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp = opToApply,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
options = options || {};
queryOptions = queryOptions || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
// Check if options currently holds a root source object
if (!options.$rootSource) {
// Root query not assigned, hold the root query
options.$rootSource = source;
}
// Assign current query data
options.$currentQuery = test;
options.$rootData = options.$rootData || {};
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number') {
// Number comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
// TODO: We can probably use a queryOptions.$locale as a second parameter here
// TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) {
if (!test.test(source)) {
matchedAll = false;
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Assign previous query data
options.$previousQuery = options.$parent;
// Assign parent query data
options.$parent = {
query: test[i],
key: i,
parent: options.$previousQuery
};
// Reset operation flag
operation = false;
// Grab first two chars of the key name to check for $
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], queryOptions, options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object} queryOptions The options the query was passed with.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, queryOptions, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$eq': // Equals
return source == test; // jshint ignore:line
case '$eeq': // Equals equals
return source === test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$nee': // Not equals equals
return source !== test;
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
throw(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key);
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
throw(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key);
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
case '$count':
var countKey,
countArr,
countVal;
// Iterate the count object's keys
for (countKey in test) {
if (test.hasOwnProperty(countKey)) {
// Check the property exists and is an array. If the property being counted is not
// an array (or doesn't exist) then use a value of zero in any further count logic
countArr = source[countKey];
if (typeof countArr === 'object' && countArr instanceof Array) {
countVal = countArr.length;
} else {
countVal = 0;
}
// Now recurse down the query chain further to satisfy the query for this key (countKey)
if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) {
return false;
}
}
}
// Allow the item in the results
return true;
case '$find':
case '$findOne':
case '$findSub':
var fromType = 'collection',
findQuery,
findOptions,
subQuery,
subOptions,
subPath,
result,
operation = {};
// Check we have a database object to work from
if (!this.db()) {
throw('Cannot operate a ' + key + ' sub-query on an anonymous collection (one with no db set)!');
}
// Check all parts of the $find operation exist
if (!test.$from) {
throw(key + ' missing $from property!');
}
if (test.$fromType) {
fromType = test.$fromType;
// Check the fromType exists as a method
if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') {
throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!');
}
}
// Perform the find operation
findQuery = test.$query || {};
findOptions = test.$options || {};
if (key === '$findSub') {
if (!test.$path) {
throw(key + ' missing $path property!');
}
subPath = test.$path;
subQuery = test.$subQuery || {};
subOptions = test.$subOptions || {};
result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions);
} else {
result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions);
}
operation[options.$parent.parent.key] = result;
return this._match(source, operation, queryOptions, 'and', options);
}
return -1;
}
};
module.exports = Matching;
},{}],17:[function(_dereq_,module,exports){
"use strict";
/**
* Provides sorting methods.
* @mixin
*/
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],18:[function(_dereq_,module,exports){
"use strict";
var Tags,
tagMap = {};
/**
* Provides class instance tagging and tag operation methods.
* @mixin
*/
Tags = {
/**
* Tags a class instance for later lookup.
* @param {String} name The tag to add.
* @returns {boolean}
*/
tagAdd: function (name) {
var i,
self = this,
mapArr = tagMap[name] = tagMap[name] || [];
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === self) {
return true;
}
}
mapArr.push(self);
// Hook the drop event for this so we can react
if (self.on) {
self.on('drop', function () {
// We've been dropped so remove ourselves from the tag map
self.tagRemove(name);
});
}
return true;
},
/**
* Removes a tag from a class instance.
* @param {String} name The tag to remove.
* @returns {boolean}
*/
tagRemove: function (name) {
var i,
mapArr = tagMap[name];
if (mapArr) {
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === this) {
mapArr.splice(i, 1);
return true;
}
}
}
return false;
},
/**
* Gets an array of all instances tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @returns {Array} The array of instances that have the passed tag.
*/
tagLookup: function (name) {
return tagMap[name] || [];
},
/**
* Drops all instances that are tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @param {Function} callback Callback once dropping has completed
* for all instances that match the passed tag name.
* @returns {boolean}
*/
tagDrop: function (name, callback) {
var arr = this.tagLookup(name),
dropCb,
dropCount,
i;
dropCb = function () {
dropCount--;
if (callback && dropCount === 0) {
callback(false);
}
};
if (arr.length) {
dropCount = arr.length;
// Loop the array and drop all items
for (i = arr.length - 1; i >= 0; i--) {
arr[i].drop(dropCb);
}
}
return true;
}
};
module.exports = Tags;
},{}],19:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides trigger functionality methods.
* @mixin
*/
var Triggers = {
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Number} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {Function} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (this.debug()) {
var typeName,
phaseName;
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
//console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Check the response for a non-expected result (anything other than
// undefined, true or false is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":22}],20:[function(_dereq_,module,exports){
"use strict";
/**
* Provides methods to handle object update operations.
* @mixin
*/
var Updating = {
/**
* Updates a property on an object.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
_updateProperty: function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"');
}
},
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
_updateIncrement: function (doc, prop, val) {
doc[prop] += val;
},
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
_updateSpliceMove: function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
},
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
_updateSplicePush: function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
},
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
_updatePush: function (arr, doc) {
arr.push(doc);
},
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
_updatePull: function (arr, index) {
arr.splice(index, 1);
},
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
_updateMultiply: function (doc, prop, val) {
doc[prop] *= val;
},
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
_updateRename: function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
},
/**
* Sets a property on a document to the passed value.
* @param {Object} doc The document to modify.
* @param {String} prop The property to set.
* @param {*} val The new property value.
* @private
*/
_updateOverwrite: function (doc, prop, val) {
doc[prop] = val;
},
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
_updateUnset: function (doc, prop) {
delete doc[prop];
},
/**
* Removes all properties from an object without destroying
* the object instance, thereby maintaining data-bound linking.
* @param {Object} doc The parent object to modify.
* @param {String} prop The name of the child object to clear.
* @private
*/
_updateClear: function (doc, prop) {
var obj = doc[prop],
i;
if (obj && typeof obj === 'object') {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
this._updateUnset(obj, i);
}
}
}
},
/**
* Pops an item or items from the array stack.
* @param {Object} doc The document to modify.
* @param {Number} val If set to a positive integer, will pop the number specified
* from the stack, if set to a negative integer will shift the number specified
* from the stack.
* @return {Boolean}
* @private
*/
_updatePop: function (doc, val) {
var updated = false,
i;
if (doc.length > 0) {
if (val > 0) {
for (i = 0; i < val; i++) {
doc.pop();
}
updated = true;
} else if (val < 0) {
for (i = 0; i > val; i--) {
doc.shift();
}
updated = true;
}
}
return updated;
}
};
module.exports = Updating;
},{}],21:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":23,"./Shared":26}],22:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {Object} def
* @returns {Function}
* @constructor
*/
var Overload = function (def) {
if (def) {
var self = this,
index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = this.generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
var arr = [],
lookup,
type,
name;
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return self.callExtend(this, '$main', def, def[index], arguments);
}
}
} else {
// Generate lookup key from arguments
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Handle been presented with a single undefined argument
if (arguments.length === 1 && type === 'undefined') {
break;
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return self.callExtend(this, '$main', def, def[lookup], arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments);
}
}
}
}
name = typeof this.name === 'function' ? this.name() : 'Unknown';
console.log('Overload: ', def);
throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature for the passed arguments: ' + this.jStringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
Overload.prototype.generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(this.generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
Overload.prototype.callExtend = function (context, prop, propContext, func, args) {
var tmp,
ret;
if (context && propContext[prop]) {
tmp = context[prop];
context[prop] = propContext[prop];
ret = func.apply(context, args);
context[prop] = tmp;
return ret;
} else {
return func.apply(context, args);
}
};
module.exports = Overload;
},{}],23:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.Common');
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* The options object accepts an "ignore" field with a regular expression
* as the value. If any key matches the expression it is not included in
* the results.
*
* The options object accepts a boolean "verbose" field. If set to true
* the results will include all paths leading up to endpoints as well as
* they endpoints themselves.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
if (options.verbose) {
paths.push(newPath);
}
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
Path.prototype.valueOne = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @param {Object=} options An optional options object.
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path, options) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr,
returnArr,
i, k;
if (obj !== undefined && typeof obj === 'object') {
if (!options || options && !options.skipArrCheck) {
// Check if we were passed an array of objects and if so,
// iterate over the array and return the value from each
// array item
if (obj instanceof Array) {
returnArr = [];
for (i = 0; i < obj.length; i++) {
returnArr.push(this.valueOne(obj[i], path));
}
return returnArr;
}
}
valuesArr = [];
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true}));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":26}],24:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Provides chain reactor node linking so that a chain reaction can propagate
* down a node tree. Effectively creates a chain link between the reactorIn and
* reactorOut objects where a chain reaction from the reactorIn is passed through
* the reactorProcess before being passed to the reactorOut object. Reactor
* packets are only passed through to the reactorOut if the reactor IO method
* chainSend is used.
* @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur inside this object will be passed through
* to the reactorOut object.
* @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur in the reactorIn object will be passed
* through to this object.
* @param {Function} reactorProcess The processing method to use when chain
* reactions occur.
* @constructor
*/
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain || !reactorOut.chainReceive) {
throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
/**
* Drop a reactor IO object, breaking the reactor link between the in and out
* reactor nodes.
* @returns {boolean}
*/
ReactorIO.prototype.drop = function () {
if (!this.isDropped()) {
this._state = 'dropped';
// Remove links
if (this._reactorIn) {
this._reactorIn.unChain(this);
}
if (this._reactorOut) {
this.unChain(this._reactorOut);
}
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
this.emit('drop', this);
delete this._listeners;
}
return true;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(ReactorIO.prototype, 'state');
Shared.mixin(ReactorIO.prototype, 'Mixin.Common');
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.mixin(ReactorIO.prototype, 'Mixin.Events');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":26}],25:[function(_dereq_,module,exports){
"use strict";
/**
* Provides functionality to encode and decode JavaScript objects to strings
* and back again. This differs from JSON.stringify and JSON.parse in that
* special objects such as dates can be encoded to strings and back again
* so that the reconstituted version of the string still contains a JavaScript
* date object.
* @constructor
*/
var Serialiser = function () {
this.init.apply(this, arguments);
};
Serialiser.prototype.init = function () {
this._encoder = [];
this._decoder = {};
// Register our handlers
this.registerEncoder('$date', function (data) {
if (data instanceof Date) {
return data.toISOString();
}
});
this.registerDecoder('$date', function (data) {
return new Date(data);
});
};
/**
* Register an encoder that can handle encoding for a particular
* object type.
* @param {String} handles The name of the handler e.g. $date.
* @param {Function} method The encoder method.
*/
Serialiser.prototype.registerEncoder = function (handles, method) {
this._encoder.push(function (data) {
var methodVal = method(data),
returnObj;
if (methodVal !== undefined) {
returnObj = {};
returnObj[handles] = methodVal;
}
return returnObj;
});
};
/**
* Register a decoder that can handle decoding for a particular
* object type.
* @param {String} handles The name of the handler e.g. $date. When an object
* has a field matching this handler name then this decode will be invoked
* to provide a decoded version of the data that was previously encoded by
* it's counterpart encoder method.
* @param {Function} method The decoder method.
*/
Serialiser.prototype.registerDecoder = function (handles, method) {
this._decoder[handles] = method;
};
/**
* Loops the encoders and asks each one if it wants to handle encoding for
* the passed data object. If no value is returned (undefined) then the data
* will be passed to the next encoder and so on. If a value is returned the
* loop will break and the encoded data will be used.
* @param {Object} data The data object to handle.
* @returns {*} The encoded data.
* @private
*/
Serialiser.prototype._encode = function (data) {
// Loop the encoders and if a return value is given by an encoder
// the loop will exit and return that value.
var count = this._encoder.length,
retVal;
while (count-- && !retVal) {
retVal = this._encoder[count](data);
}
return retVal;
};
/**
* Converts a previously encoded string back into an object.
* @param {String} data The string to convert to an object.
* @returns {Object} The reconstituted object.
*/
Serialiser.prototype.parse = function (data) {
return this._parse(JSON.parse(data));
};
/**
* Handles restoring an object with special data markers back into
* it's original format.
* @param {Object} data The object to recurse.
* @param {Object=} target The target object to restore data to.
* @returns {Object} The final restored object.
* @private
*/
Serialiser.prototype._parse = function (data, target) {
var i;
if (typeof data === 'object' && data !== null) {
if (data instanceof Array) {
target = target || [];
} else {
target = target || {};
}
// Iterate through the object's keys and handle
// special object types and restore them
for (i in data) {
if (data.hasOwnProperty(i)) {
if (i.substr(0, 1) === '$' && this._decoder[i]) {
// This is a special object type and a handler
// exists, restore it
return this._decoder[i](data[i]);
}
// Not a special object or no handler, recurse as normal
target[i] = this._parse(data[i], target[i]);
}
}
} else {
target = data;
}
// The data is a basic type
return target;
};
/**
* Converts an object to a encoded string representation.
* @param {Object} data The object to encode.
*/
Serialiser.prototype.stringify = function (data) {
return JSON.stringify(this._stringify(data));
};
/**
* Recurse down an object and encode special objects so they can be
* stringified and later restored.
* @param {Object} data The object to parse.
* @param {Object=} target The target object to store converted data to.
* @returns {Object} The converted object.
* @private
*/
Serialiser.prototype._stringify = function (data, target) {
var handledData,
i;
if (typeof data === 'object' && data !== null) {
// Handle special object types so they can be encoded with
// a special marker and later restored by a decoder counterpart
handledData = this._encode(data);
if (handledData) {
// An encoder handled this object type so return it now
return handledData;
}
if (data instanceof Array) {
target = target || [];
} else {
target = target || {};
}
// Iterate through the object's keys and serialise
for (i in data) {
if (data.hasOwnProperty(i)) {
target[i] = this._stringify(data[i], target[i]);
}
}
} else {
target = data;
}
// The data is a basic type
return target;
};
module.exports = Serialiser;
},{}],26:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* A shared object that can be used to store arbitrary data between class
* instances, and access helper methods.
* @mixin
*/
var Shared = {
version: '1.3.505',
modules: {},
plugins: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
// Store the module in the module registry
this.modules[name] = module;
// Tell the universe we are loading this module
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @memberof Shared
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
// Set the finished loading flag to true
this.modules[name]._fdbFinished = true;
// Assign the module name to itself so it knows what it
// is called
if (this.modules[name].prototype) {
this.modules[name].prototype.className = name;
} else {
this.modules[name].className = name;
}
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
if (callback) { callback(name, this.modules[name]); }
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @memberof Shared
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
/**
* Adds the properties and methods defined in the mixin to the passed object.
* @memberof Shared
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
mixin: new Overload({
'object, string': function (obj, mixinName) {
var mixinObj;
if (typeof mixinName === 'string') {
mixinObj = this.mixins[mixinName];
if (!mixinObj) {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
}
return this.$main.call(this, obj, mixinObj);
},
'object, *': function (obj, mixinObj) {
return this.$main.call(this, obj, mixinObj);
},
'$main': function (obj, mixinObj) {
if (mixinObj && typeof mixinObj === 'object') {
for (var i in mixinObj) {
if (mixinObj.hasOwnProperty(i)) {
obj[i] = mixinObj[i];
}
}
}
return obj;
}
}),
/**
* Generates a generic getter/setter method for the passed method name.
* @memberof Shared
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @memberof Shared
* @param arr
* @returns {Function}
* @constructor
*/
overload: Overload,
/**
* Define the mixins that other modules can use as required.
* @memberof Shared
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching'),
'Mixin.Updating': _dereq_('./Mixin.Updating'),
'Mixin.Tags': _dereq_('./Mixin.Tags')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":11,"./Mixin.ChainReactor":12,"./Mixin.Common":13,"./Mixin.Constants":14,"./Mixin.Events":15,"./Mixin.Matching":16,"./Mixin.Sorting":17,"./Mixin.Tags":18,"./Mixin.Triggers":19,"./Mixin.Updating":20,"./Overload":22}],27:[function(_dereq_,module,exports){
/* jshint strict:false */
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun/*, thisArg*/) {
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0; // jshint ignore:line
if (typeof fun !== 'function') {
throw new TypeError();
}
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
// NOTE: Technically this should Object.defineProperty at
// the next index, as push can be affected by
// properties on Object.prototype and Array.prototype.
// But that method's new, and collisions should be
// rare, so use the more-compatible alternative.
if (fun.call(thisArg, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}
if (typeof Object.create !== 'function') {
Object.create = (function() {
var Temp = function() {};
return function (prototype) {
if (arguments.length > 1) {
throw Error('Second argument not supported');
}
if (typeof prototype !== 'object') {
throw TypeError('Argument must be an object');
}
Temp.prototype = prototype;
var result = new Temp();
Temp.prototype = null;
return result;
};
})();
}
// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14e
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
// 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if (this === null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
// 2. Let lenValue be the result of calling the Get
// internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0; // jshint ignore:line
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
// 6. If n >= len, return -1.
if (n >= len) {
return -1;
}
// 7. If n >= 0, then Let k be n.
// 8. Else, n<0, Let k be len - abs(n).
// If k is less than 0, then let k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 9. Repeat, while k < len
while (k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
module.exports = {};
},{}]},{},[1]);
| AMoo-Miki/cdnjs | ajax/libs/forerunnerdb/1.3.505/fdb-core.js | JavaScript | mit | 240,356 |
<?php
/**
* Minileven functions and definitions
*
* Sets up the theme and provides some helper functions. Some helper functions
* are used in the theme as custom template tags. Others are attached to action and
* filter hooks in WordPress to change core functionality.
*
* The first function, minileven_setup(), sets up the theme by registering support
* for various features in WordPress, such as post thumbnails, navigation menus, and the like.
*
* @package Minileven
*/
/**
* Set the content width based on the theme's design and stylesheet.
*/
if ( ! isset( $content_width ) )
$content_width = 584;
/**
* Tell WordPress to run minileven_setup() when the 'after_setup_theme' hook is run.
*/
add_action( 'after_setup_theme', 'minileven_setup' );
if ( ! function_exists( 'minileven_setup' ) ):
/**
* Sets up theme defaults and registers support for various WordPress features.
*/
function minileven_setup() {
global $wp_version;
/**
* Custom template tags for this theme.
*/
require( get_template_directory() . '/inc/template-tags.php' );
/**
* Custom functions that act independently of the theme templates
*/
require( get_template_directory() . '/inc/tweaks.php' );
/**
* Implement the Custom Header functions
*/
require( get_template_directory() . '/inc/custom-header.php' );
/* Make Minileven available for translation.
* Translations can be added to the /languages/ directory.
* If you're building a theme based on Minileven, use a find and replace
* to change 'minileven' to the name of your theme in all the template files.
*/
/* Don't load a minileven textdomain, as it uses the Jetpack textdomain.
load_theme_textdomain( 'minileven', get_template_directory() . '/languages' );
*/
// Add default posts and comments RSS feed links to <head>.
add_theme_support( 'automatic-feed-links' );
// This theme uses wp_nav_menu() in one location.
register_nav_menu( 'primary', __( 'Primary Menu', 'jetpack' ) );
// Add support for a variety of post formats
add_theme_support( 'post-formats', array( 'gallery' ) );
// Add support for custom backgrounds
add_theme_support( 'custom-background' );
// Add support for post thumbnails
add_theme_support( 'post-thumbnails' );
}
endif; // minileven_setup
/**
* Enqueue scripts and styles
*/
function minileven_scripts() {
global $post;
wp_enqueue_style( 'style', get_stylesheet_uri() );
wp_enqueue_script( 'small-menu', get_template_directory_uri() . '/js/small-menu.js', array( 'jquery' ), '20120206', true );
if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
wp_enqueue_script( 'comment-reply' );
}
}
add_action( 'wp_enqueue_scripts', 'minileven_scripts' );
function minileven_fonts() {
/* translators: If there are characters in your language that are not supported
by Open Sans, translate this to 'off'. Do not translate into your own language. */
if ( 'off' !== _x( 'on', 'Open Sans font: on or off', 'jetpack' ) ) {
$opensans_subsets = 'latin,latin-ext';
/* translators: To add an additional Open Sans character subset specific to your language, translate
this to 'greek', 'cyrillic' or 'vietnamese'. Do not translate into your own language. */
$opensans_subset = _x( 'no-subset', 'Open Sans font: add new subset (greek, cyrillic, vietnamese)', 'jetpack' );
if ( 'cyrillic' == $opensans_subset )
$opensans_subsets .= ',cyrillic,cyrillic-ext';
elseif ( 'greek' == $opensans_subset )
$opensans_subsets .= ',greek,greek-ext';
elseif ( 'vietnamese' == $opensans_subset )
$opensans_subsets .= ',vietnamese';
$opensans_query_args = array(
'family' => 'Open+Sans:200,200italic,300,300italic,400,400italic,600,600italic,700,700italic',
'subset' => $opensans_subsets,
);
wp_register_style( 'minileven-open-sans', add_query_arg( $opensans_query_args, "//fonts.googleapis.com/css" ), array(), null );
}
}
add_action( 'init', 'minileven_fonts' );
/**
* Register our sidebars and widgetized areas.
* @since Minileven 1.0
*/
function minileven_widgets_init() {
register_sidebar( array(
'name' => __( 'Main Sidebar', 'jetpack' ),
'id' => 'sidebar-1',
'before_widget' => '<aside id="%1$s" class="widget %2$s">',
'after_widget' => "</aside>",
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3>',
) );
}
add_action( 'widgets_init', 'minileven_widgets_init' );
function minileven_posts_per_page() {
return 5;
}
add_filter('pre_option_posts_per_page', 'minileven_posts_per_page');
/**
* Determine the currently active theme.
*/
function minileven_actual_current_theme() {
$removed = remove_action( 'option_stylesheet', 'jetpack_mobile_stylesheet' );
$stylesheet = get_option( 'stylesheet' );
if ( $removed )
add_action( 'option_stylesheet', 'jetpack_mobile_stylesheet' );
return $stylesheet;
}
/* This function grabs the location of the custom menus from the current theme. If no menu is set in a location
* it will return a boolean "false". This function helps Minileven know which custom menu to display. */
function minileven_get_menu_location() {
$theme_slug = minileven_actual_current_theme();
$mods = get_option( "theme_mods_{$theme_slug}" );
if ( has_filter( 'jetpack_mobile_theme_menu' ) ) {
/**
* Filter the menu displayed in the Mobile Theme.
*
* @since 3.4.0
*
* @param int $menu_id ID of the menu to display.
*/
return array( 'primary' => apply_filters( 'jetpack_mobile_theme_menu', $menu_id ) );
}
if ( isset( $mods['nav_menu_locations'] ) && ! empty( $mods['nav_menu_locations'] ) )
return $mods['nav_menu_locations'];
return false;
}
/* This function grabs the custom background image from the user's current theme so that Minileven can display it. */
function minileven_get_background() {
$theme_slug = minileven_actual_current_theme();
$mods = get_option( "theme_mods_$theme_slug" );
if ( ! empty( $mods ) ) {
return array(
'color' => isset( $mods['background_color'] ) ? $mods['background_color'] : null,
'image' => isset( $mods['background_image'] ) ? $mods['background_image'] : null,
'repeat' => isset( $mods['background_repeat'] ) ? $mods['background_repeat'] : null,
'position' => isset( $mods['background_position_x'] ) ? $mods['background_position_x'] : null,
'attachment' => isset( $mods['attachment'] ) ? $mods['attachment'] : null,
);
}
return false;
}
/**
* If the user has set a static front page, show all posts on the front page, instead of a static page.
*/
if ( '1' == get_option( 'wp_mobile_static_front_page' ) )
add_filter( 'pre_option_page_on_front', '__return_zero' );
/**
* Retrieves the IDs for images in a gallery.
*
* @uses get_post_galleries() first, if available. Falls back to shortcode parsing,
* then as last option uses a get_posts() call.
*
* @return array List of image IDs from the post gallery.
*/
function minileven_get_gallery_images() {
$images = array();
if ( function_exists( 'get_post_galleries' ) ) {
$galleries = get_post_galleries( get_the_ID(), false );
if ( isset( $galleries[0]['ids'] ) )
$images = explode( ',', $galleries[0]['ids'] );
} else {
$pattern = get_shortcode_regex();
preg_match( "/$pattern/s", get_the_content(), $match );
$atts = shortcode_parse_atts( $match[3] );
if ( isset( $atts['ids'] ) )
$images = explode( ',', $atts['ids'] );
}
if ( ! $images ) {
$images = get_posts( array(
'fields' => 'ids',
'numberposts' => 999,
'order' => 'ASC',
'orderby' => 'menu_order',
'post_mime_type' => 'image',
'post_parent' => get_the_ID(),
'post_type' => 'attachment',
) );
}
return $images;
}
/**
* Allow plugins to filter where Featured Images are displayed.
* Default has Featured Images disabled on single view and pages.
*
* @uses is_search()
* @uses apply_filters()
* @return bool
*/
function minileven_show_featured_images() {
$enabled = ( is_home() || is_search() || is_archive() ) ? true : false;
/**
* Filter where featured images are displayed in the Mobile Theme.
*
* By setting $enabled to true or false using functions like is_home() or
* is_archive(), you can control where featured images are be displayed.
*
* @since 3.2.0
*
* @param bool $enabled True if featured images should be displayed, false if not.
*/
return (bool) apply_filters( 'minileven_show_featured_images', $enabled );
}
| riddya85/rentail_upwrk | wp-content/plugins/jetpack/modules/minileven/theme/pub/minileven/functions.php | PHP | gpl-2.0 | 8,400 |
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>
CIP JavaScript documentation for sequence "
pfcPoint3D"
</title>
<link href="cipdoc_default.css" type="text/css" rel="stylesheet">
<script language="JAVASCRIPT">
function findProperNode ()
{
top.frames [0].document.apiwizard.api (
2,
410
);
}
</script>
</head>
<body onLoad="findProperNode()" class="frame-entity">
<table cellspacing="0" width="100%" border="0" class="toolbar">
<tr>
<td class="toolbar-navigation"><a href="library.html">Library</a> | <a href="m-pfcBase.html">Module</a></td><td class="toolbar-lib-name">
</td>
</tr>
</table>
<hr>
<h2>Class pfcPoint3D</h2>
<hr>
<br>
<b>Description</b>
<br>
<br>A 3x1 array that stores a three-dimensional point.
<br>
<br>Array provides methods for accessing its elemnts by index(indices) and for modifying its elements. Array object "does not know" its dimentions.<br>
<br>
<hr>
<br>
<br>
<b>Array Dimensions:
[3]
</b>
<br>
<hr>
<br>
<b>Method Summary</b>
<br>
<br>
<table cellpadding="3" border="0" class="method-summary">
<tr>
<td></td>
</tr>
<tr>
<td class="return-type"><tt>number</tt></td><td class="func-signature"><tt><a class="method" href="#Item">Item</a>
(
integer Index
)
</tt></td>
</tr>
<tr>
<td></td><td colspan="2" class="entities-text">Accesses an item by its index in the sequence.</td>
</tr>
<tr>
<td class="return-type"><tt>void</tt></td><td class="func-signature"><tt><a class="method" href="#Set">Set</a>
(
integer Index
, number Item
)
</tt></td>
</tr>
<tr>
<td></td><td colspan="2" class="entities-text">Assigns an item to the designated index in the sequence.</td>
</tr>
<tr>
<td></td>
</tr>
</table>
<br>
<hr>
<br>
<b>Method Detail</b>
<br>
<hr>
<br>
<a name="Item">
<table cellpadding="5" cellspacing="0" border="0" class="method-def">
<tr>
<td class="return-type"><tt>number</tt></td><td class="func-name"><tt>Item</tt></td><td class="func-params"><tt>
(
integer Index
)
</tt></td>
</tr>
</table>
</a>
<br>Accesses an item by its index in the sequence.<br>
<br>
<hr>
<br>
<a name="Set">
<table cellpadding="5" cellspacing="0" border="0" class="method-def">
<tr>
<td class="return-type"><tt>void</tt></td><td class="func-name"><tt>Set</tt></td><td class="func-params"><tt>
(
integer Index
, number Item
)
</tt></td>
</tr>
</table>
</a>
<br>Assigns an item to the designated index in the sequence.</body>
</html>
| 2014c2g12/c2g12 | wsgi/wsgi/static/weblink/doc/api/t-pfcBase-Point3D.html | HTML | gpl-2.0 | 2,542 |
/* HP PA-RISC SOM object file format: definitions internal to BFD.
Copyright 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1998, 2000, 2001,
2002, 2003, 2004, 2005, 2007, 2008, 2012 Free Software Foundation, Inc.
Contributed by the Center for Software Science at the
University of Utah (pa-gdb-bugs@cs.utah.edu).
This file is part of BFD, the Binary File Descriptor library.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
02110-1301, USA. */
#ifndef _SOM_H
#define _SOM_H
#include "libhppa.h"
/* We want reloc.h to provide PA 2.0 defines. */
#define PA_2_0
#include "som/aout.h"
#include "som/lst.h"
#include "som/internal.h"
/* The SOM BFD backend doesn't currently use anything from these
two include files, but it's likely to need them in the future. */
#ifdef R_DLT_REL
#include <shl.h>
#include <dl.h>
#endif
#if defined (HOST_HPPABSD) || defined (HOST_HPPAOSF)
/* BSD uses a completely different scheme for object file identification.
so for now, define _PA_RISC_ID to accept any random value for a model
number. */
#undef _PA_RISC_ID
#define _PA_RISC_ID(__m_num) 1
#endif /* HOST_HPPABSD */
typedef struct som_symbol
{
asymbol symbol;
unsigned int som_type;
/* Structured like the ELF tc_data union. Allows more code sharing
in GAS this way. */
union
{
struct
{
unsigned int hppa_arg_reloc;
unsigned int hppa_priv_level;
} ap;
void * any;
}
tc_data;
/* Index of this symbol in the symbol table. Only used when
building relocation streams for incomplete objects. */
int index;
/* How many times this symbol is used in a relocation. By sorting
the symbols from most used to least used we can significantly
reduce the size of the relocation stream for incomplete objects. */
int reloc_count;
/* During object file writing, the offset of the name of this symbol
in the SOM string table. */
int stringtab_offset;
}
som_symbol_type;
/* A structure containing all the magic information stored in a BFD's
private data which needs to be copied during an objcopy/strip run. */
struct som_exec_data
{
/* Sort-of a magic number. BSD uses it to distinguish between
native executables and hpux executables. */
short system_id;
/* Magic exec flags. These control things like whether or not
null pointer dereferencing is allowed and the like. */
long exec_flags;
/* We must preserve the version identifier too. Some versions
of the HP linker do not grok NEW_VERSION_ID for reasons unknown. */
unsigned int version_id;
/* Add more stuff here as needed. Good examples of information
we might want to pass would be presumed_dp, entry_* and maybe
others from the file header. */
};
struct somdata
{
/* All the magic information about an executable which lives
in the private BFD structure and needs to be copied from
the input bfd to the output bfd during an objcopy/strip. */
struct som_exec_data *exec_data;
/* These three fields are only used when writing files and are
generated from scratch. They need not be copied for objcopy
or strip to work. */
struct som_header *file_hdr;
struct som_string_auxhdr *copyright_aux_hdr;
struct som_string_auxhdr *version_aux_hdr;
struct som_exec_auxhdr *exec_hdr;
struct som_compilation_unit *comp_unit;
/* Pointers to a saved copy of the symbol and string tables. These
need not be copied for objcopy or strip to work. */
som_symbol_type *symtab;
char *stringtab;
asymbol **sorted_syms;
/* We remember these offsets so that after check_file_format, we have
no dependencies on the particular format of the exec_hdr.
These offsets need not be copied for objcopy or strip to work. */
file_ptr sym_filepos;
file_ptr str_filepos;
file_ptr reloc_filepos;
unsigned stringtab_size;
void * line_info;
};
struct som_data_struct
{
struct somdata a;
};
/* Substructure of som_section_data_struct used to hold information
which can't be represented by the generic BFD section structure,
but which must be copied during objcopy or strip. */
struct som_copyable_section_data_struct
{
/* Various fields in space and subspace headers that we need
to pass around. */
unsigned int sort_key : 8;
unsigned int access_control_bits : 7;
unsigned int is_defined : 1;
unsigned int is_private : 1;
unsigned int quadrant : 2;
unsigned int is_comdat : 1;
unsigned int is_common : 1;
unsigned int dup_common : 1;
/* For subspaces, this points to the section which represents the
space in which the subspace is contained. For spaces it points
back to the section for this space. */
asection *container;
/* The user-specified space number. It is wrong to use this as
an index since duplicates and holes are allowed. */
int space_number;
/* Add more stuff here as needed. Good examples of information
we might want to pass would be initialization pointers,
and the many subspace flags we do not represent yet. */
};
/* Used to keep extra SOM specific information for a given section.
reloc_size holds the size of the relocation stream, note this
is very different from the number of relocations as SOM relocations
are variable length.
reloc_stream is the actual stream of relocation entries. */
struct som_section_data_struct
{
struct som_copyable_section_data_struct *copy_data;
unsigned int reloc_size;
unsigned char *reloc_stream;
struct som_space_dictionary_record *space_dict;
struct som_subspace_dictionary_record *subspace_dict;
};
#define somdata(bfd) ((bfd)->tdata.som_data->a)
#define obj_som_exec_data(bfd) (somdata (bfd).exec_data)
#define obj_som_file_hdr(bfd) (somdata (bfd).file_hdr)
#define obj_som_exec_hdr(bfd) (somdata (bfd).exec_hdr)
#define obj_som_copyright_hdr(bfd) (somdata (bfd).copyright_aux_hdr)
#define obj_som_version_hdr(bfd) (somdata (bfd).version_aux_hdr)
#define obj_som_compilation_unit(bfd) (somdata (bfd).comp_unit)
#define obj_som_symtab(bfd) (somdata (bfd).symtab)
#define obj_som_stringtab(bfd) (somdata (bfd).stringtab)
#define obj_som_sym_filepos(bfd) (somdata (bfd).sym_filepos)
#define obj_som_str_filepos(bfd) (somdata (bfd).str_filepos)
#define obj_som_stringtab_size(bfd) (somdata (bfd).stringtab_size)
#define obj_som_reloc_filepos(bfd) (somdata (bfd).reloc_filepos)
#define obj_som_sorted_syms(bfd) (somdata (bfd).sorted_syms)
#define som_section_data(sec) ((struct som_section_data_struct *) sec->used_by_bfd)
#define som_symbol_data(symbol) ((som_symbol_type *) symbol)
/* Defines groups of basic relocations. FIXME: These should
be the only basic relocations created by GAS. The rest
should be internal to the BFD backend.
The idea is both SOM and ELF define these basic relocation
types so they map into a SOM or ELF specific relocation as
appropriate. This allows GAS to share much more code
between the two object formats. */
#define R_HPPA_NONE R_NO_RELOCATION
#define R_HPPA R_CODE_ONE_SYMBOL
#define R_HPPA_PCREL_CALL R_PCREL_CALL
#define R_HPPA_ABS_CALL R_ABS_CALL
#define R_HPPA_GOTOFF R_DP_RELATIVE
#define R_HPPA_ENTRY R_ENTRY
#define R_HPPA_EXIT R_EXIT
#define R_HPPA_COMPLEX R_COMP1
#define R_HPPA_BEGIN_BRTAB R_BEGIN_BRTAB
#define R_HPPA_END_BRTAB R_END_BRTAB
#define R_HPPA_BEGIN_TRY R_BEGIN_TRY
#define R_HPPA_END_TRY R_END_TRY
/* Exported functions, mostly for use by GAS. */
bfd_boolean bfd_som_set_section_attributes (asection *, int, int, unsigned int, int);
bfd_boolean bfd_som_set_subsection_attributes (asection *, asection *, int, unsigned int, int, int, int, int);
void bfd_som_set_symbol_type (asymbol *, unsigned int);
bfd_boolean bfd_som_attach_aux_hdr (bfd *, int, char *);
int ** hppa_som_gen_reloc_type (bfd *, int, int, enum hppa_reloc_field_selector_type_alt, int, asymbol *);
bfd_boolean bfd_som_attach_compilation_unit (bfd *, const char *, const char *, const char *, const char *);
#endif /* _SOM_H */
| ixaxaar/sdcc | support/sdbinutils/bfd/som.h | C | gpl-2.0 | 8,726 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.